Files
mtusi2026lab3/run-remaining.sh
T

261 lines
12 KiB
Bash
Executable File

#!/bin/sh
# bash ./run-remaining.sh # исходные серии и A/A, без изменения кода
# bash ./run-remaining.sh status # только состояние результатов
# bash ./run-remaining.sh after # ПОСЛЕ анализа и изменения overflow 5 -> 0
# Для фона: nohup bash ./run-remaining.sh > /tmp/lab3-remaining.log 2>&1 &
# Готовые метки не перезаписываются. Git-операций и изменения кода нет.
set -eu
cd "$(dirname "$0")"
exec python3 -u - "$@" <<'PY'
import argparse
import ast
import csv
import fcntl
import hashlib
import json
from pathlib import Path
import shutil
import subprocess
import tempfile
import time
ROOT = Path.cwd()
SCALING = ROOT / "evidence/scaling"
LABELS = ("scaling-a", "scaling-b", "scaling-db", "scaling-ab-before",
"scaling-ab-aa", "scaling-ab-after")
parser = argparse.ArgumentParser(description="Оставшиеся замеры ЛР3")
parser.add_argument("mode", nargs="?", default="baseline", choices=("baseline", "after", "status"))
args = parser.parse_args()
def say(message):
print(time.strftime("[%H:%M:%S] ") + message, flush=True)
def fail(message):
raise SystemExit("STOP: " + message)
def rows(path):
if not path.is_file():
return []
with path.open(newline="") as handle:
return list(csv.DictReader(handle))
def source_hash():
digest = hashlib.sha256()
for path in sorted([*(ROOT / "src").rglob("*.py"), *(ROOT / "migrations").rglob("*.py")]):
digest.update(path.relative_to(ROOT).as_posix().encode())
digest.update(b"\0")
digest.update(path.read_bytes())
digest.update(b"\0")
return digest.hexdigest()
def pool_defaults():
tree = ast.parse((ROOT / "src/config.py").read_text())
cls = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "Database")
return {node.target.id: ast.literal_eval(node.value) for node in cls.body
if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name)
and node.target.id in ("pool_size", "pool_overflow")}
def read_meta(label):
path = SCALING / label / "meta.json"
if not path.is_file():
fail(label + ": нет meta.json; неполную метку нужно разобрать отдельно")
return json.loads(path.read_text())
def validate(label, expected_sha=None, expected_series=None):
folder = SCALING / label
meta = read_meta(label)
if meta.get("aborted") or not meta.get("finished"):
fail(label + ": прогон не завершён. Сохраните метку и передайте журнал Codex")
if expected_sha and meta["code"]["src_sha256"] != expected_sha:
fail(label + ": хеш приложения отличается от ожидаемого")
if expected_series and meta.get("series") != expected_series:
fail(label + ": другая серия в паспорте")
warnings = meta.get("host_warnings", [])
# Явное указание пользователя 15.10: питание от батареи допустимо.
unexpected = [w for w in warnings if w != "host on battery power: CPU may be throttled"]
if unexpected:
fail(label + ": предупреждения о хосте: " + "; ".join(unexpected))
searches = rows(folder / "searches.csv")
plan = {int(item["cell"]) for item in meta["plan"]}
completed = [int(item["cell"]) for item in searches]
if set(completed) != plan or len(completed) != len(plan):
fail(label + ": не все ячейки завершены либо есть дубли; автоматического переснятия нет")
for item in searches:
if not item.get("r_star") or float(item["r_star"]) <= 0:
fail(label + ": не найден положительный R*")
if item.get("flags") or item.get("generator_bound", "").lower() == "true":
fail(label + ": требуется анализ: " + (item.get("flags") or "generator_bound"))
run_rows = rows(folder / "runs.csv")
keys = [(item["cell"], item["step"]) for item in run_rows]
if len(keys) != len(set(keys)) or {int(item["cell"]) for item in run_rows} != plan:
fail(label + ": неполные/повторяющиеся ступени; нужен разбор прерванного запуска")
for item in searches:
if sum(row["cell"] == item["cell"] for row in run_rows) != int(item["steps"]):
fail(label + ": число ступеней не совпадает с паспортом ячейки")
say(label + ": готово, ячеек " + str(len(searches)) +
", src=" + meta["code"]["src_sha256"][:16])
for warning in warnings:
say(" сохранённое предупреждение: " + warning)
return meta
if args.mode == "status":
for label in LABELS:
folder = SCALING / label
if not folder.exists():
print(label + ": ещё не запускалась")
continue
try:
meta = read_meta(label)
count = len(rows(folder / "searches.csv"))
state = "прерван" if meta.get("aborted") else ("завершён" if meta.get("finished") else "идёт / не завершён")
print(label + ": " + state + ", ячеек " + str(count) +
"/" + str(len(meta.get("plan", []))))
except (OSError, ValueError, SystemExit) as error:
print(label + ": " + str(error))
raise SystemExit(0)
for command in ("make", "docker", "uv"):
if not shutil.which(command):
fail("не найдена команда " + command)
# Не допускает двух экземпляров этой цепочки.
lock_id = hashlib.sha256(str(ROOT).encode()).hexdigest()[:16]
coordinator = (Path(tempfile.gettempdir()) /
("lab3-remaining-" + lock_id + ".lock")).open("a")
try:
fcntl.flock(coordinator, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
fail("другой экземпляр run-remaining.sh уже работает")
log_dir = Path(tempfile.mkdtemp(prefix="lab3-remaining-" + args.mode + "-"))
say("Журналы команд: " + str(log_dir))
def run(name, *command):
say("Команда: " + " ".join(command))
with (log_dir / (name + ".log")).open("w") as handle:
process = subprocess.Popen(command, cwd=ROOT, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True, bufsize=1)
try:
for line in process.stdout:
handle.write(line)
handle.flush()
print(line, end="", flush=True)
code = process.wait()
except KeyboardInterrupt:
process.send_signal(__import__("signal").SIGINT)
process.wait()
raise
if code:
fail(name + ": код " + str(code) + "; журнал " +
str(log_dir / (name + ".log")))
# Дождаться уже запущенной серии b, не останавливая и не дублируя её.
with (ROOT / "bench/.bench.lock").open("a") as handle:
last_note = 0
while True:
try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
fcntl.flock(handle, fcntl.LOCK_UN)
break
except BlockingIOError:
if time.monotonic() - last_note >= 30:
say("Ожидаю завершения уже запущенного bench-прогона...")
last_note = time.monotonic()
time.sleep(5)
subprocess.run(["docker", "version", "--format", "{{.Server.Version}}"], check=True)
running = subprocess.check_output(["docker", "ps", "--format", "{{.Names}}"], text=True).strip()
if running:
fail("есть работающие контейнеры: " + running.replace("\n", ", ") +
". Остановите свой стенд отдельно; чужие контейнеры скрипт не трогает")
code_paths = ["src", "migrations", "Dockerfile", "compose.yaml", ".dockerignore",
"requirements.txt", "uv.lock", "pyproject.toml", "bench"]
dirty = subprocess.check_output(["git", "status", "--porcelain", "--", *code_paths], text=True)
if dirty.strip():
fail("исходники изменены относительно коммита; сначала зафиксируйте согласованные изменения")
initial_sha = source_hash()
say("Код приложения: " + initial_sha)
def series(series_name, label):
if source_hash() != initial_sha:
fail("код изменился во время цепочки")
if (SCALING / label).exists():
say("Проверяю существующую метку " + label)
else:
run(label, "make", "bench-scaling", "SERIES=" + series_name, "SCALING_LABEL=" + label)
return validate(label, initial_sha, series_name)
def plots(name, labels):
if (ROOT / "evidence/plots" / name).exists():
say("Графики уже существуют: evidence/plots/" + name)
else:
run("plots-" + name, "make", "bench-plots",
"LABELS=" + " ".join(labels), "PLOTS=" + name)
def compare(before, after, aa=None):
path = ROOT / "evidence/compare" / (before + "__" + after + ".md")
if path.exists():
say("Сравнение уже существует: " + str(path.relative_to(ROOT)))
return
command = ["make", "bench-compare", "BEFORE=" + before, "AFTER=" + after]
if aa:
command.append("AA=" + aa)
run("compare-" + after, *command)
if args.mode == "baseline":
if pool_defaults() != {"pool_size": 10, "pool_overflow": 5}:
fail("baseline ожидает исходный пул 10 + 5; код не менялся автоматически")
for series_name in ("a", "b", "db"):
series(series_name, "scaling-" + series_name)
plots("scaling", ["scaling-a", "scaling-b", "scaling-db"])
db_rows = [item for item in rows(SCALING / "scaling-db/searches.csv")
if item["config"] == "4x1-pg0.5"]
churn_count = sum("churn" in item["signals_at_fail"].split(";") for item in db_rows)
if len(db_rows) != 3 or churn_count < 2:
say("Базовые серии готовы. Условие H4 не выполнено: churn в " +
str(churn_count) + "/3 повторов.")
say("Передайте результаты Codex: по RUNBOOK нужно выбрать другое улучшение до A/B.")
raise SystemExit(0)
before = series("ab", "scaling-ab-before")
aa = series("ab", "scaling-ab-aa")
if before["code"]["src_sha256"] != aa["code"]["src_sha256"]:
fail("before и A/A имеют разный код")
compare("scaling-ab-before", "scaling-ab-aa")
say("ГОТОВО: a, b, db, before и A/A. Пул остался исходным: 10 + 5.")
say("Сообщите Codex: «Прогоны baseline завершены, проанализируй evidence». Код пока не меняйте.")
else:
before = validate("scaling-ab-before", expected_series="ab")
validate("scaling-ab-aa", before["code"]["src_sha256"], "ab")
if initial_sha == before["code"]["src_sha256"]:
fail("код совпадает с before: сначала анализ и согласованное улучшение")
if pool_defaults() != {"pool_size": 10, "pool_overflow": 0}:
fail("режим after подготовлен для H4: ожидается пул 10 + 0")
if not (SCALING / "scaling-ab-after").exists():
for name, command in (
("check", ["make", "check"]),
("lint", ["make", "lint"]),
("requirements", ["make", "requirements-check"]),
("isolated", ["make", "test-isolated"]),
("failures", ["make", "failure-checks"]),
):
run(name, *command)
series("ab", "scaling-ab-after")
compare("scaling-ab-before", "scaling-ab-after", "scaling-ab-aa")
plots("scaling-ab", ["scaling-ab-before", "scaling-ab-aa", "scaling-ab-after"])
say("ГОТОВО: after и сравнение с A/A. Передайте результаты Codex для итогового отчёта.")
PY