Files
mtusi2026lab2/bench/ab.py
T
ricoromaandClaude Opus 5.5 7b775a29a9 chore: carry over lab 1 solution into lab 2 skeleton
Copy the committed lab 1 sources as-is: src/, student-tests/, bench/,
Dockerfile, docker-compose.yml, pyproject.toml, uv.lock,
.python-version, config_example.toml, AGENTS.md, CLAUDE.md, .claude/,
openspec/, .graphifyignore and KNOWN_ISSUES.md. Lab 1 evidence stays
in the lab 1 repository.

Merge the new skeleton files with own sections: Makefile (lab 2
targets plus own run, docker, bench and common targets), .gitignore,
.dockerignore and .env.example. Rename the image to
mtusi-messenger:lab2 and point AGENTS.md at lab 2.

The application is still the in-memory lab 1 implementation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:11:46 +03:00

119 lines
4.6 KiB
Python

"""Два прогона подряд: «до» и «после» одного изменения, в одной сессии.
Запуск — `make bench_ab BEFORE=<метка> AFTER=<метка> REAPPLY=<commit>`.
В рабочем дереве должен лежать код «до», а изменение — быть
закоммиченным и откаченным отдельным commit; `REAPPLY` — commit отката.
Скрипт снимает стенд и разложение «до», коммитит их, возвращает
изменение (`git revert` commit отката) и снимает «после». Между
прогонами на хосте нет другой работы. Только stdlib. Методика — design
change `perf-bottleneck-fix`, решения 7 и 9.
"""
import argparse
import re
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def git(*args: str) -> subprocess.CompletedProcess[str]:
return subprocess.run(
["git", "-C", str(ROOT), *args],
capture_output=True,
text=True,
check=False,
)
def problems(args: argparse.Namespace) -> list[str]:
"""Что мешает начать; пустой список — можно запускать."""
found = []
for name in (args.before, args.after):
if not re.fullmatch(r"[A-Za-z0-9._-]+", name or ""):
found.append(f"bad label {name!r}: use [A-Za-z0-9._-]")
continue
for path in (
ROOT / "evidence" / "bench" / name,
ROOT / "evidence" / "profile" / f"{name}.txt",
):
if path.exists():
found.append(f"{path.relative_to(ROOT)} already exists")
if args.before == args.after:
found.append("BEFORE and AFTER must be different labels")
if git("status", "--porcelain").stdout.strip():
# иначе стенд запишет в паспорт dirty: true
found.append("working tree is not clean: commit or remove changes")
if git("cat-file", "-e", f"{args.reapply}^{{commit}}").returncode != 0:
found.append(f"commit {args.reapply!r} not found")
elif git("merge-base", "--is-ancestor", args.reapply, "HEAD").returncode:
found.append(f"commit {args.reapply} is not in the current branch")
return found
def steps(args: argparse.Namespace) -> list[list[str]]:
# стенд идёт раньше разложения: его dirty считается по всему дереву
return [
["make", "bench", f"BENCH_LABEL={args.before}"],
["make", "bench_inproc", f"BENCH_LABEL={args.before}"],
[
"git",
"add",
f"evidence/bench/{args.before}",
f"evidence/profile/{args.before}.txt",
],
["git", "commit", "-m", f"docs: add {args.before} bench evidence"],
["git", "revert", "--no-edit", args.reapply],
["make", "bench", f"BENCH_LABEL={args.after}"],
["make", "bench_inproc", f"BENCH_LABEL={args.after}"],
]
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--before", default="")
parser.add_argument("--after", default="")
parser.add_argument("--reapply", default="")
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args(argv)
if not (args.before and args.after and args.reapply):
print(
"usage: make bench_ab BEFORE=<label> AFTER=<label> "
"REAPPLY=<revert commit>",
flush=True,
)
return 2
found = problems(args)
if found:
print("bench_ab refused:\n " + "\n ".join(found), flush=True)
return 2
plan = steps(args)
if args.dry_run:
print("\n".join(" ".join(step) for step in plan), flush=True)
return 0
started = time.monotonic()
for number, step in enumerate(plan, 1):
print(f"\n=== [{number}/{len(plan)}] {' '.join(step)}", flush=True)
code = subprocess.run(step, cwd=ROOT, check=False).returncode
if code != 0:
print(
f"\nbench_ab stopped: step {number} exited with {code}; "
"later steps were not run",
flush=True,
)
return 1
minutes = (time.monotonic() - started) / 60
head = git("rev-parse", "--short", "HEAD").stdout.strip()
print(
f"\nbench_ab done in {minutes:.0f} min: labels {args.before} and "
f"{args.after}, HEAD {head}",
flush=True,
)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))