Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 58.1 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 # less the workspace's own .braid file and its .git guard
780 files = count_files(ws) - sum(
781 os.path.lexists(os.path.join(ws, name)) for name in (".braid", ".git")
782 )
783 if files != info["files"]:
784 raise Failure(f"the workspace has {files} files, git's tree {info['files']}")
785 configure_git(tools, made["git-bare"])
786 kept = (repo, made["git-bare"])
787 remove(ws, made["git-full"])
788 else:
789 remove(repo, ws, made["git-bare"], made["git-full"])
790 # The first round's repositories serve the store and history scenarios.
791 if ctx._imported is None:
792 ctx._imported = kept
793 elif kept is not None:
794 remove(*kept)
795 name = f"{info['name']}, {info['commits']:,} commits"
796 return [
797 Row(
798 "import",
799 "history only",
800 f"Import {name}: `braid init` + `braid git import` vs "
801 "`git clone --no-local --bare`",
802 out["braid"],
803 out["git-bare"],
804 ),
805 Row(
806 "import",
807 "history and a working copy",
808 f"Import {name} and check it out: `braid init` + `braid git import` + "
809 "`braid workspace add` vs `git clone --no-local`",
810 out["braid-checkout"],
811 out["git-full"],
812 ),
813 ]
814
815
816# ---------------------------------------------------------------------------
817# 2. Status
818
819
820def check_status(tools, tree, modified):
821 """Both tools must see the same thing: a clean tree, or exactly the
822 modified files."""
823 braid = tools.braid_run(tree.ws, "status", "--json", capture=True).json()
824 git = tools.git_run(tree.git, "status", "--porcelain", capture=True).lines()
825 want = sorted(modified)
826 if sorted(braid["modified"]) != want or braid["added"] or braid["deleted"]:
827 raise Failure(f"braid status does not list exactly the {len(want)} modified files")
828 if sorted(line[3:] for line in git) != want or any(line[:2] != " M" for line in git):
829 raise Failure(f"git status does not list exactly the {len(want)} modified files")
830
831
832def scenario_status(ctx):
833 tools = ctx.tools
834 tree = ctx.tree()
835 count = tree.count
836 rounds = ctx.settings["status_rounds"]
837 warmup = ctx.settings["warmup"]
838 rows = []
839 # Modified files, spread over the tree.
840 many = ctx.settings["modified"]
841 changed = [tree_path((k * count // many + 7) % count) for k in range(many)]
842 originals = {}
843 for case in ("clean", "modified"):
844 if case == "modified":
845 for path in changed:
846 for full in tree.both(path):
847 originals[full] = full.read_bytes()
848 append(full, b"modified\n")
849 modified = changed if case == "modified" else []
850 check_status(tools, tree, modified)
851 label = "clean" if case == "clean" else f"{len(changed)} files modified"
852 for untracked_cache in (False, True):
853 tools.git_run(tree.git, "config", "core.untrackedCache", str(untracked_cache).lower())
854 setting = "untracked cache on" if untracked_cache else "no untracked cache"
855 ctx.log(f"status, {label}, git with {setting}")
856 runs = alternate(
857 rounds,
858 {
859 "braid": lambda _r: tools.braid_run(tree.ws, "status"),
860 "git": lambda _r: tools.git_run(tree.git, "status"),
861 },
862 warmup=warmup,
863 )
864 git_text = (
865 "`git status` with `core.untrackedCache=true`"
866 if untracked_cache
867 else "`git status` with no untracked cache"
868 )
869 rows.append(
870 Row(
871 "status",
872 f"{label}, git {setting}",
873 f"Status of {count:,} files, {label}: `braid status` vs {git_text} "
874 "and no fsmonitor",
875 runs["braid"],
876 runs["git"],
877 )
878 )
879 if case == "modified":
880 for full, data in originals.items():
881 full.write_bytes(data)
882 check_status(tools, tree, [])
883 tools.git_run(tree.git, "config", "core.untrackedCache", "false")
884 return rows
885
886
887# ---------------------------------------------------------------------------
888# 3. Commit
889
890
891def scenario_commit(ctx):
892 tools = ctx.tools
893 tree = ctx.tree()
894 count = tree.count
895 rounds = ctx.settings["commit_rounds"]
896 warmup = ctx.settings["warmup"]
897 check_status(tools, tree, [])
898 before = int(tools.git_run(tree.git, "rev-list", "--count", "main", capture=True).text())
899 ctx.log(f"commit one changed file of {count}, {rounds} rounds")
900 picked = {}
901
902 def pick(index):
903 if index not in picked:
904 path = tree_path((len(picked) * 7_919 + 4_242) % count)
905 picked[index] = path
906 for full in tree.both(path):
907 append(full, f"edit {index}\n".encode())
908 return picked[index]
909
910 def braid(index):
911 pick(index)
912 run = tools.braid_run(tree.ws, "commit", "-m", f"Edit {index}", "--json", capture=True)
913 if run.json()["changes"] != 1:
914 raise Failure("braid commit did not record exactly one path")
915 return run
916
917 def git(index):
918 path = pick(index)
919 return tools.git_run(tree.git, "add", path) + tools.git_run(
920 tree.git, "commit", "-q", "-m", f"Edit {index}"
921 )
922
923 runs = alternate(rounds, {"braid": braid, "git": git}, warmup=warmup)
924 after = int(tools.git_run(tree.git, "rev-list", "--count", "main", capture=True).text())
925 if after - before != rounds + warmup:
926 raise Failure(f"git made {after - before} commits, not {rounds + warmup}")
927 check_status(tools, tree, [])
928 return [
929 Row(
930 "commit",
931 f"one changed file of {count:,}",
932 f"Commit one changed file in a tree of {count:,} files: `braid commit` vs "
933 "`git add` + `git commit`",
934 runs["braid"],
935 runs["git"],
936 )
937 ]
938
939
940# ---------------------------------------------------------------------------
941# 4. Wide directory
942
943
944def wide_series(ctx, size, commits, warmup):
945 """Appends one new file to a directory of `size` files and commits it,
946 `commits` times, with git (add and commit), with a braid workspace
947 (commit), and without a working copy (change create --land). Returns
948 the timed Runs of each, in order."""
949 tools = ctx.tools
950 base = ctx.work / f"wide-{size}"
951 git_repo = base / "git"
952 ws_repo = base / "braid"
953 ws = base / "braid-ws"
954 change_repo = base / "braid-change"
955 scratch = base / "new-file"
956 ctx.log(f"wide directory of {size} files: {commits} commits each")
957 git_seed(tools, git_repo, wide_files(size))
958 braid_from_git(tools, ws_repo, git_repo, ws)
959 braid_from_git(tools, change_repo, git_repo)
960 # One new file per round, written when the round's first contestant
961 # starts: every contestant commits the same file in that round.
962 written = {}
963
964 def write(index):
965 if index not in written:
966 number = size + len(written)
967 path = wide_path(number)
968 data = wide_content(number)
969 (git_repo / path).write_bytes(data)
970 (ws / path).write_bytes(data)
971 scratch.write_bytes(data)
972 written[index] = path
973 return written[index]
974
975 def braid_commit(index):
976 write(index)
977 run = tools.braid_run(ws, "commit", "-m", f"Add file {index}", "--json", capture=True)
978 if run.json()["changes"] != 1:
979 raise Failure("braid commit did not record exactly one path")
980 return run
981
982 def braid_change(index):
983 path = write(index)
984 run = tools.braid_run(
985 change_repo,
986 "change",
987 "create",
988 "--base",
989 "main",
990 "--set",
991 f"{path}=@{scratch}",
992 "-m",
993 f"Add file {index}",
994 "--land",
995 "main",
996 capture=True,
997 )
998 if run.json()["land"]["outcome"] != "fast-forward":
999 raise Failure("braid change create --land did not fast-forward")
1000 return run
1001
1002 def git(index):
1003 path = write(index)
1004 return tools.git_run(git_repo, "add", path) + tools.git_run(
1005 git_repo, "commit", "-q", "-m", f"Add file {index}"
1006 )
1007
1008 contestants = {"braid-commit": braid_commit, "git": git, "braid-change": braid_change}
1009 runs = alternate(commits, contestants, warmup=warmup)
1010 total = commits + warmup
1011 made = int(tools.git_run(git_repo, "rev-list", "--count", "main", capture=True).text()) - 1
1012 landed = len(tools.braid_run(change_repo, "log", "main", "-n", ALL, capture=True).lines()) - 1
1013 unlanded = len(tools.braid_run(ws, "status", "--json", capture=True).json()["unlanded"])
1014 if (made, landed, unlanded) != (total, total, total):
1015 raise Failure(
1016 f"expected {total} commits each; git made {made}, change create landed "
1017 f"{landed}, the workspace has {unlanded}"
1018 )
1019 if not ctx.keep:
1020 remove(base)
1021 return runs
1022
1023
1024def median_of(runs):
1025 return statistics.median(run.wall for run in runs)
1026
1027
1028def trend(runs):
1029 """How much slower the last quarter of a series is than the first, from
1030 the medians of each: 0.1 means 10% slower."""
1031 quarter = max(1, len(runs) // 4)
1032 first = median_of(runs[:quarter])
1033 last = median_of(runs[-quarter:])
1034 return last / first - 1 if first else None
1035
1036
1037def exponent(sizes, costs):
1038 """The slope of log(cost) against log(size), by least squares: 0 when the
1039 cost does not grow with the directory, 1 when it grows in proportion."""
1040 xs = [math.log(size) for size in sizes]
1041 ys = [math.log(cost) for cost in costs]
1042 mean_x = sum(xs) / len(xs)
1043 mean_y = sum(ys) / len(ys)
1044 den = sum((x - mean_x) ** 2 for x in xs)
1045 return sum((x - mean_x) * (y - mean_y) for x, y in zip(xs, ys)) / den if den else None
1046
1047
1048def scenario_wide(ctx):
1049 settings = ctx.settings
1050 size = settings["wide_files"]
1051 commits = settings["wide_commits"]
1052 warmup = settings["warmup"]
1053 main = wide_series(ctx, size, commits, warmup)
1054 rows = [
1055 Row(
1056 "wide",
1057 f"new file in {size:,}: braid commit",
1058 f"One new file per commit in a directory of {size:,} files, {commits} times: "
1059 "`braid commit` vs `git add` + `git commit`",
1060 main["braid-commit"],
1061 main["git"],
1062 ),
1063 Row(
1064 "wide",
1065 f"new file in {size:,}: change create --land",
1066 f"The same, without a working copy: `braid change create --land` vs "
1067 "`git add` + `git commit`",
1068 main["braid-change"],
1069 main["git"],
1070 ),
1071 ]
1072
1073 # Does the cost of one commit grow with the directory? The same series,
1074 # shorter, on smaller directories, against the start of the main one.
1075 sweep_commits = settings["wide_sweep_commits"]
1076 sizes = list(settings["wide_sweep"]) + [size]
1077 medians = {name: [] for name in main}
1078 for sweep_size in settings["wide_sweep"]:
1079 series = wide_series(ctx, sweep_size, sweep_commits, warmup)
1080 for name in medians:
1081 medians[name].append(median_of(series[name]))
1082 for name in medians:
1083 medians[name].append(median_of(main[name][:sweep_commits]))
1084 growth = {name: medians[name][-1] / medians[name][0] for name in medians}
1085 slopes = {name: exponent(sizes, medians[name]) for name in medians}
1086 drift = {name: trend(main[name]) for name in main}
1087 ctx.extra["wide"] = {
1088 "sizes": sizes,
1089 "median_seconds_by_size": medians,
1090 "growth": growth,
1091 "exponent": slopes,
1092 "trend_over_main_series": drift,
1093 }
1094 labels = {"git": "git", "braid-commit": "braid commit", "braid-change": "change create"}
1095 note = ", ".join(f"{labels[name]} x{growth[name]:.2f}" for name in labels)
1096 rows.append(
1097 Row(
1098 "wide",
1099 f"growth from {sizes[0]:,} to {size:,} files",
1100 f"Cost of one commit in a directory of {size:,} files divided by its cost "
1101 f"in one of {sizes[0]:,}",
1102 kind="info",
1103 note=note,
1104 extra={"growth": growth, "exponent": slopes},
1105 )
1106 )
1107 note = ", ".join(f"{labels[name]} {drift[name]:+.0%}" for name in labels)
1108 rows.append(
1109 Row(
1110 "wide",
1111 f"drift over the {commits} commits",
1112 f"Last quarter of the {commits} commits against the first",
1113 kind="info",
1114 note=note,
1115 extra={"trend": drift},
1116 )
1117 )
1118 return rows
1119
1120
1121# ---------------------------------------------------------------------------
1122# 5. Agents
1123
1124
1125def run_agents(count, agent):
1126 """Runs `agent(i)` for i in 1..count on as many threads, released at
1127 once. Returns the wall time until the last one finished."""
1128 barrier = threading.Barrier(count + 1)
1129 errors = []
1130
1131 def body(index):
1132 try:
1133 barrier.wait(timeout=600)
1134 agent(index)
1135 except BaseException as err: # reported below, from the main thread
1136 errors.append(err)
1137
1138 threads = [threading.Thread(target=body, args=(i,)) for i in range(1, count + 1)]
1139 GATE.wait()
1140 for thread in threads:
1141 thread.start()
1142 barrier.wait(timeout=600)
1143 start = time.perf_counter()
1144 for thread in threads:
1145 thread.join()
1146 wall = time.perf_counter() - start
1147 if errors:
1148 raise errors[0]
1149 return wall
1150
1151
1152def braid_agents(ctx, base, count, commits):
1153 tools = ctx.tools
1154 seed = base / "seed"
1155 repo = base / "braid"
1156 git_seed(tools, seed, agents_files(count))
1157 braid_from_git(tools, repo, seed)
1158 for index in range(1, count + 1):
1159 tools.braid_run(repo, "workspace", "add", f"agent-{index:02d}", base / f"ws-{index:02d}")
1160 outcomes = {}
1161 lock = threading.Lock()
1162
1163 def agent(index):
1164 ws = base / f"ws-{index:02d}"
1165 env = dict(
1166 tools.env,
1167 BRAID_AGENT=f"agent-{index:02d}",
1168 BRAID_AUTHOR=f"Agent {index} <agent-{index:02d}@example.org>",
1169 )
1170 for change in range(commits):
1171 append(ws / agent_file(index), f"agent {index} change {change}\n".encode())
1172 tools.braid_run(ws, "commit", "-m", f"Agent {index}, change {change}", env=env)
1173 landed = tools.braid_run(ws, "land", "--json", env=env, capture=True)
1174 outcome = landed.json()["outcome"]
1175 with lock:
1176 outcomes[outcome] = outcomes.get(outcome, 0) + 1
1177
1178 wall = run_agents(count, agent)
1179 total = 1 + count * commits
1180 landed = len(tools.braid_run(repo, "log", "main", "-n", ALL, capture=True).lines())
1181 if landed != total:
1182 raise Failure(f"main has {landed} changesets after the agents, not {total}")
1183 check = base / "check"
1184 tools.braid_run(repo, "workspace", "add", "check", check)
1185 for index in range(1, count + 1):
1186 lines = (check / agent_file(index)).read_text().splitlines()
1187 if len(lines) != 1 + commits:
1188 raise Failure(f"agent {index}'s file has {len(lines)} lines on main")
1189 return Run(wall, None), outcomes
1190
1191
1192def git_agents(ctx, base, count, commits):
1193 tools = ctx.tools
1194 seed = base / "seed"
1195 hub = base / "hub.git"
1196 git_seed(tools, seed, agents_files(count))
1197 tools.git_run(base, "clone", "-q", "--bare", seed, hub)
1198 configure_git(tools, hub)
1199 for index in range(1, count + 1):
1200 clone = base / f"clone-{index:02d}"
1201 tools.git_run(base, "clone", "-q", hub, clone)
1202 configure_git(tools, clone)
1203 retries = []
1204 lock = threading.Lock()
1205
1206 def agent(index):
1207 clone = base / f"clone-{index:02d}"
1208 mine = 0
1209 for change in range(commits):
1210 append(clone / agent_file(index), f"agent {index} change {change}\n".encode())
1211 tools.git_run(clone, "commit", "-q", "-a", "-m", f"Agent {index}, change {change}")
1212 while tools.git_run(clone, "push", "-q", "origin", "main", check=False).code != 0:
1213 mine += 1
1214 if mine > 1_000 * commits:
1215 raise Failure(f"agent {index} could not push")
1216 tools.git_run(clone, "pull", "-q", "--rebase", "origin", "main")
1217 with lock:
1218 retries.append(mine)
1219
1220 wall = run_agents(count, agent)
1221 total = 1 + count * commits
1222 landed = int(tools.git_run(hub, "rev-list", "--count", "main", capture=True).text())
1223 if landed != total:
1224 raise Failure(f"the hub's main has {landed} commits after the agents, not {total}")
1225 for index in range(1, count + 1):
1226 text = tools.git_run(hub, "show", f"main:{agent_file(index)}", capture=True).text()
1227 if len(text.splitlines()) != 1 + commits:
1228 raise Failure(f"agent {index}'s file is wrong on the hub's main")
1229 return Run(wall, None), sum(retries)
1230
1231
1232def scenario_agents(ctx):
1233 settings = ctx.settings
1234 commits = settings["agent_commits"]
1235 rounds = settings["agent_rounds"]
1236 rows = []
1237 for count in settings["agents"]:
1238 walls = {"braid": [], "git": []}
1239 retries = []
1240 outcomes = {}
1241 for index in range(rounds):
1242 for who in round_order(["braid", "git"], index):
1243 ctx.log(f"{count} agents, round {index + 1}/{rounds}: {who}")
1244 base = ctx.work / f"agents-{count}-{index}-{who}"
1245 if who == "braid":
1246 run, landed = braid_agents(ctx, base, count, commits)
1247 for outcome, number in landed.items():
1248 outcomes[outcome] = outcomes.get(outcome, 0) + number
1249 else:
1250 run, retried = git_agents(ctx, base, count, commits)
1251 retries.append(retried)
1252 walls[who].append(run)
1253 if not ctx.keep:
1254 remove(base)
1255 pushes = count * commits
1256 per_push = statistics.median(retries) / pushes
1257 rebased = outcomes.get("rebased", 0) / max(1, sum(outcomes.values()))
1258 rows.append(
1259 Row(
1260 "agents",
1261 f"{count} agents x {commits} commits",
1262 f"{count} agents land {commits} commits each, at once: `braid commit` + "
1263 "`braid land` in a workspace each, vs `git commit` + `git push` from a "
1264 "clone each, with `git pull --rebase` and a new push when rejected",
1265 walls["braid"],
1266 walls["git"],
1267 note=f"git retried {per_push:.2f} times per push; "
1268 f"braid rebased {rebased:.0%} of its landings, retrying none",
1269 extra={
1270 "git_retries_per_round": retries,
1271 "git_retries_per_push": per_push,
1272 "braid_land_outcomes": outcomes,
1273 },
1274 )
1275 )
1276 return rows
1277
1278
1279# ---------------------------------------------------------------------------
1280# 6. Store size
1281
1282
1283def scenario_store(ctx):
1284 braid_repo, _ = ctx.imported()
1285 git_repo = ctx.gc_git()
1286 info = ctx.extra["source"]
1287 braid_blocks, braid_bytes = disk_usage(braid_repo / ".braid" / "store")
1288 git_blocks, git_bytes = disk_usage(git_repo)
1289 store = ctx.extra.setdefault("store", {})
1290 store.update(
1291 {
1292 "braid_store": [braid_blocks, braid_bytes],
1293 "git_after_gc_aggressive": [git_blocks, git_bytes],
1294 }
1295 )
1296 return [
1297 Row(
1298 "store",
1299 "after the import",
1300 f"Size of {info['name']}: `du` of `.braid/store` after `braid git import` vs "
1301 "the bare clone after `git gc --aggressive`",
1302 [braid_blocks],
1303 [git_blocks],
1304 kind="size",
1305 note=f"file sizes alone: {braid_bytes / git_bytes:.2f}",
1306 )
1307 ]
1308
1309
1310# ---------------------------------------------------------------------------
1311# 7. History
1312
1313
1314def unsupported(run):
1315 """Whether braid refused the command line itself: a subcommand or an
1316 argument it does not have yet."""
1317 err = run.err.decode("utf-8", "replace")
1318 return run.code == 2 and (
1319 "unrecognized subcommand" in err or "unexpected argument" in err
1320 )
1321
1322
1323def pick_paths(tools, git_repo):
1324 """The file of main that most first-parent commits changed, and one that
1325 only one of them touched, with how many changed each file."""
1326 present = set(
1327 tools.git_run(git_repo, "ls-tree", "-r", "--name-only", "main", capture=True).lines()
1328 )
1329 counts = {}
1330 names = tools.git_run(
1331 git_repo, "log", "--first-parent", "--format=", "--name-only", "main", capture=True
1332 ).lines()
1333 for name in names:
1334 if name in present:
1335 counts[name] = counts.get(name, 0) + 1
1336 hot = min(counts, key=lambda name: (-counts[name], name))
1337 cold = min(counts, key=lambda name: (counts[name], name))
1338 return hot, cold, counts
1339
1340
1341def with_json(args):
1342 """Braid arguments with --json, before any `--`."""
1343 if "--" in args:
1344 at = args.index("--")
1345 return [*args[:at], "--json", *args[at:]]
1346 return [*args, "--json"]
1347
1348
1349def scenario_history(ctx):
1350 tools = ctx.tools
1351 braid_repo, _ = ctx.imported()
1352 git_repo = ctx.gc_git()
1353 info = ctx.extra["source"]
1354 rounds = ctx.settings["history_rounds"]
1355 warmup = ctx.settings["warmup"]
1356 hot, cold, counts = pick_paths(tools, git_repo)
1357 ctx.extra["history"] = {"hot": [hot, counts[hot]], "cold": [cold, counts[cold]]}
1358 name = info["name"]
1359 # Braid follows first parents, so git does too: both list the same
1360 # changesets. The last item is what git lists, to check braid against.
1361 queries = [
1362 (
1363 "log -n 1000",
1364 f"Newest 1000 changesets of {name}: `braid log -n 1000` vs "
1365 "`git log --first-parent -n 1000 --format=%H`",
1366 ["log", "main", "-n", "1000"],
1367 ["log", "--first-parent", "-n", "1000", "--format=%H", "main"],
1368 ["log", "--first-parent", "-n", "1000", "--format=%H", "main"],
1369 ),
1370 (
1371 "log -- the most changed file",
1372 f"History of the file most changed in {name}: "
1373 "`braid log -- <path>` vs `git log --first-parent -- <path>`",
1374 ["log", "main", "-n", ALL, "--", hot],
1375 ["log", "--first-parent", "-n", ALL, "main", "--", hot],
1376 ["log", "--first-parent", "--format=%H", "main", "--", hot],
1377 ),
1378 (
1379 "log -- a file one commit touched",
1380 f"History of a file one commit touched in {name}: "
1381 "`braid log -- <path>` vs `git log --first-parent -- <path>`",
1382 ["log", "main", "-n", ALL, "--", cold],
1383 ["log", "--first-parent", "-n", ALL, "main", "--", cold],
1384 ["log", "--first-parent", "--format=%H", "main", "--", cold],
1385 ),
1386 (
1387 "blame the most changed file",
1388 f"Blame of the file most changed in {name}: `braid blame main <path>` vs "
1389 "`git blame --first-parent <path>`",
1390 ["blame", "main", hot],
1391 ["blame", "--first-parent", "main", "--", hot],
1392 None,
1393 ),
1394 ]
1395 rows = []
1396 for case, compared, braid_args, git_args, listing in queries:
1397 # A log query is checked through --json, one entry per changeset,
1398 # against git's list; blame only has to succeed, since its output
1399 # is braid's own.
1400 probe_args = with_json(braid_args) if listing else braid_args
1401 probe = tools.braid_run(braid_repo, *probe_args, check=False, capture=True)
1402 if unsupported(probe):
1403 reason = probe.err.decode("utf-8", "replace").strip().splitlines()[0]
1404 rows.append(Row("history", case, compared, skipped=f"not in braid yet ({reason})"))
1405 continue
1406 if probe.code != 0:
1407 raise Failure(f"braid {case}: {probe.err.decode('utf-8', 'replace')[-400:]}")
1408 if listing:
1409 expected = len(tools.git_run(git_repo, *listing, capture=True).lines())
1410 got = len(probe.json())
1411 if got != expected:
1412 raise Failure(f"braid {case}: {got} changesets, git lists {expected} commits")
1413 elif not probe.out.strip():
1414 raise Failure(f"braid {case} printed nothing")
1415 ctx.log(f"history: {case}")
1416 runs = alternate(
1417 rounds,
1418 {
1419 "braid": lambda _r, a=braid_args: tools.braid_run(braid_repo, *a),
1420 "git": lambda _r, a=git_args: tools.git_run(git_repo, *a),
1421 },
1422 warmup=warmup,
1423 )
1424 rows.append(Row("history", case, compared, runs["braid"], runs["git"]))
1425 return rows
1426
1427
1428RUNNERS = {
1429 "import": scenario_import,
1430 "status": scenario_status,
1431 "commit": scenario_commit,
1432 "wide": scenario_wide,
1433 "agents": scenario_agents,
1434 "store": scenario_store,
1435 "history": scenario_history,
1436}
1437
1438
1439# ---------------------------------------------------------------------------
1440# Main
1441
1442
1443def build_braid():
1444 """Builds braid in release mode and returns the binary's path."""
1445 print("building braid in release mode", file=sys.stderr, flush=True)
1446 subprocess.run(
1447 ["cargo", "build", "--release", "--locked", "-p", "elffuss-braid-cli"],
1448 cwd=ROOT,
1449 check=True,
1450 )
1451 meta = subprocess.run(
1452 ["cargo", "metadata", "--format-version", "1", "--no-deps"],
1453 cwd=ROOT,
1454 check=True,
1455 capture_output=True,
1456 )
1457 target = Path(json.loads(meta.stdout)["target_directory"])
1458 return target / "release" / ("braid.exe" if os.name == "nt" else "braid")
1459
1460
1461def describe_build(git):
1462 """Which braid was measured: the commit, and whether the tree differed."""
1463 def ask(*args):
1464 out = subprocess.run(
1465 [git, "-C", str(ROOT), *args],
1466 capture_output=True,
1467 text=True,
1468 env=clean_environment(),
1469 )
1470 return out.stdout.strip() if out.returncode == 0 else None
1471
1472 status = ask("status", "--porcelain", "--untracked-files=no")
1473 return {
1474 "commit": ask("rev-parse", "HEAD"),
1475 "modified": None if status is None else bool(status),
1476 }
1477
1478
1479def parse_args(argv):
1480 parser = argparse.ArgumentParser(
1481 description="Benchmarks braid against git on this machine and prints braid/git ratios.",
1482 )
1483 parser.add_argument("--quick", action="store_true", help="small inputs, for a smoke run")
1484 parser.add_argument(
1485 "--only",
1486 metavar="LIST",
1487 help="comma-separated scenarios to run (default: all): " + ", ".join(SCENARIOS),
1488 )
1489 parser.add_argument("--list", action="store_true", help="list the scenarios and exit")
1490 parser.add_argument("--rounds", type=int, metavar="N", help="rounds of every scenario")
1491 parser.add_argument(
1492 "--braid", type=Path, metavar="PATH", help="a braid binary to use instead of building one"
1493 )
1494 parser.add_argument(
1495 "--git", default="git", metavar="PATH", help="the git binary (default: git)"
1496 )
1497 parser.add_argument(
1498 "--source",
1499 metavar="URL_OR_PATH",
1500 help="the git repository to import, instead of the pinned one (or, with --quick, "
1501 "this repository's own history)",
1502 )
1503 parser.add_argument(
1504 "--source-ref", default="HEAD", metavar="REF", help="what to import from --source"
1505 )
1506 parser.add_argument(
1507 "--workdir",
1508 type=Path,
1509 metavar="DIR",
1510 help="where to make the inputs (default: a new temporary directory)",
1511 )
1512 parser.add_argument(
1513 "--keep", action="store_true", help="keep the inputs instead of removing them"
1514 )
1515 parser.add_argument(
1516 "--markdown", action="store_true", help="also print the table as Markdown, rounded"
1517 )
1518 parser.add_argument(
1519 "--max-load",
1520 type=float,
1521 metavar="N",
1522 help="before each timed round, wait until the load average of the last minute "
1523 "is below N (on a machine shared with other work)",
1524 )
1525 args = parser.parse_args(argv)
1526 if args.only:
1527 chosen = {name.strip() for name in args.only.split(",") if name.strip()}
1528 unknown = sorted(chosen - set(SCENARIOS))
1529 if unknown:
1530 parser.error(f"unknown scenarios: {', '.join(unknown)}")
1531 # Always in the same order, which is also the order inputs are
1532 # shared in.
1533 args.only = [name for name in SCENARIOS if name in chosen]
1534 else:
1535 args.only = list(SCENARIOS)
1536 return args
1537
1538
1539def main(argv=None):
1540 args = parse_args(argv)
1541 if args.list:
1542 for name, text in SCENARIOS.items():
1543 print(f"{name:<8} {text}")
1544 return 0
1545 mode = "quick" if args.quick else "full"
1546 settings = dict(QUICK if args.quick else FULL)
1547 if args.rounds:
1548 for key in settings:
1549 if key.endswith("_rounds"):
1550 settings[key] = args.rounds
1551 if args.source:
1552 source = {"url": args.source, "ref": args.source_ref, "commit": None, "name": "the source"}
1553 elif args.quick:
1554 source = {"url": str(ROOT), "ref": "HEAD", "commit": None, "name": "this repository"}
1555 else:
1556 source = dict(PINNED)
1557
1558 git = shutil.which(args.git)
1559 if git is None:
1560 print(f"bench: {args.git} not found", file=sys.stderr)
1561 return 1
1562 braid = args.braid.resolve() if args.braid else build_braid()
1563
1564 if args.workdir:
1565 args.workdir.mkdir(parents=True, exist_ok=True)
1566 work = Path(tempfile.mkdtemp(prefix="braid-bench-", dir=args.workdir))
1567 else:
1568 work = Path(tempfile.mkdtemp(prefix="braid-bench-"))
1569 work = work.resolve()
1570 free = shutil.disk_usage(work).free
1571 if free < NEEDED_SPACE[mode]:
1572 remove(work)
1573 print(
1574 f"bench: the work directory has {free >> 20} MiB free, and a {mode} run needs "
1575 f"{NEEDED_SPACE[mode] >> 20} MiB; pass --workdir elsewhere",
1576 file=sys.stderr,
1577 )
1578 return 1
1579
1580 GATE.limit = args.max_load
1581 tools = Tools(braid, git)
1582 ctx = Context(tools, settings, work, source, args.keep)
1583 started = datetime.datetime.now(datetime.timezone.utc)
1584 load_before = os.getloadavg() if hasattr(os, "getloadavg") else None
1585 rows = []
1586 errors = {}
1587 try:
1588 for position, name in enumerate(args.only):
1589 print(f"{name}: {SCENARIOS[name]}", file=sys.stderr, flush=True)
1590 try:
1591 rows.extend(RUNNERS[name](ctx))
1592 except Failure as err:
1593 print(f"bench: {name} failed: {err}", file=sys.stderr, flush=True)
1594 errors[name] = str(err)
1595 except Exception as err: # a bug here, or in braid's output
1596 traceback.print_exc()
1597 errors[name] = f"{type(err).__name__}: {err}"
1598 ctx.drop(set(args.only[position + 1 :]))
1599 finally:
1600 if not args.keep:
1601 remove(work)
1602 else:
1603 print(f"inputs kept in {work}", file=sys.stderr)
1604
1605 print_table(rows)
1606 if args.markdown:
1607 print_markdown(rows)
1608 for name, err in errors.items():
1609 print(f"FAILED {name}: {err}")
1610
1611 results = {
1612 "format": 1,
1613 "mode": mode,
1614 "started": started.isoformat(timespec="seconds"),
1615 "finished": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"),
1616 "scenarios": args.only,
1617 "settings": settings,
1618 "braid": describe_build(git),
1619 "git": subprocess.run(
1620 [git, "--version"], capture_output=True, text=True, env=tools.env
1621 ).stdout.strip(),
1622 "system": platform.system(),
1623 "cpus": os.cpu_count(),
1624 "load_before": load_before,
1625 "load_after": os.getloadavg() if hasattr(os, "getloadavg") else None,
1626 "max_load": GATE.limit,
1627 "seconds_waited_for_load": round(GATE.waited, 1),
1628 "rounds_run_above_max_load": GATE.gave_up,
1629 "rows": [row.to_json() for row in rows],
1630 "extra": ctx.extra,
1631 "errors": errors,
1632 }
1633 RESULTS.mkdir(parents=True, exist_ok=True)
1634 stamp = started.strftime("%Y%m%d-%H%M%S")
1635 path = RESULTS / f"{stamp}-{mode}.json"
1636 path.write_text(json.dumps(results, indent=2) + "\n")
1637 print(f"raw measurements: {path.relative_to(ROOT)}")
1638 return 1 if errors else 0
1639
1640
1641if __name__ == "__main__":
1642 sys.exit(main())