Files
mtusi2026lab3/experiments/lab3-scale-v2/runner.py
T

214 lines
10 KiB
Python

"""Prepare once; the user starts the long preregistered experiment explicitly."""
import argparse
import copy
import fcntl
import json
import random
import re
import sys
import tarfile
import time
from datetime import datetime, timezone
from pathlib import Path
from design import CONFIGS, DESIGN, config, freeze_confirmation, next_rate
from runtime import HERE, ROOT, Runtime, check_ports, digest, environment, original, save, shell, sources
def validate_name(name):
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}-v2", name):
raise ValueError("Series name must contain letters/digits/_/- and end with -v2")
return name
def directory_for(name, smoke=False):
validate_name(name)
return ROOT / (".memory/lab3-scale-v2-smoke" if smoke else "evidence/grade5-v2") / name
def prepare(name, smoke=False):
directory = directory_for(name, smoke)
fingerprint = sources()
if directory.exists():
existing = json.loads((directory / "design.json").read_text())
if existing["sources"] != fingerprint:
raise RuntimeError("Prepared sources changed; choose a new series ending in -v2")
if digest(existing) != (directory / "design.sha256").read_text().strip():
raise RuntimeError("Prepared design checksum differs")
if json.loads((directory / "status.json").read_text())["status"] != "prepared":
raise RuntimeError("Series already started or preparation was incomplete; choose a new series")
print("Already prepared: " + str(directory), flush=True)
return directory
check_ports()
env = environment()
image = "highload-lab3-bench-v2:" + env["app_code_sha256"][:16]
print("Building one image for every v2 condition", flush=True)
shell(["docker", "build", "-t", image, "src"])
image_id = shell(["docker", "image", "inspect", "--format", "{{.Id}}", image])
design = {**copy.deepcopy(DESIGN), "series": name, "smoke_only": smoke,
"sources": fingerprint, "image": image, "image_id": image_id,
"frozen_utc": datetime.now(timezone.utc).isoformat()}
if smoke:
design.update(duration_s=5, warmup_s=2, cooldown_s=1, budget_seconds=300)
directory.mkdir(parents=True)
save(directory / "design.json", design)
(directory / "design.sha256").write_text(digest(design) + "\n")
save(directory / "environment-prepared.json", env)
with tarfile.open(directory / "source.tar.gz", "w:gz") as archive:
for relative in fingerprint:
archive.add(ROOT / relative, arcname=relative, recursive=False)
save(directory / "status.json", {"status": "preparing", "long_experiment_started": False,
"smoke_only": smoke})
# Credentials remain outside evidence and the source archive.
runtime = Runtime(name, image, env)
runtime.compose(["config", "--quiet"])
save(directory / "status.json", {"status": "prepared", "long_experiment_started": False,
"smoke_only": smoke})
print("PREPARED: " + str(directory), flush=True)
return directory
class StopExperiment(RuntimeError):
pass
class Experiment:
def __init__(self, directory):
self.directory = directory
self.design = json.loads((directory / "design.json").read_text())
if digest(self.design) != (directory / "design.sha256").read_text().strip():
raise RuntimeError("Frozen design checksum differs")
if self.design["sources"] != sources():
raise RuntimeError("Code/instrument changed after preparation; choose a new series")
current_image = shell(["docker", "image", "inspect", "--format", "{{.Id}}", self.design["image"]])
if current_image != self.design["image_id"]:
raise RuntimeError("Prepared Docker image changed")
self.protocol_sha = digest(self.design)
self.started = time.monotonic()
self.sequence = 0
self.runtime = Runtime(self.design["series"], self.design["image"], environment())
self.order = []
def run_point(self, point):
# Budget stops are explicit and keep every completed or partial run.
needed = self.design["warmup_s"] + self.design["duration_s"] + self.design["cooldown_s"] + 15
if time.monotonic() - self.started + needed > self.design["budget_seconds"]:
raise StopExperiment("budget_exhausted")
if self.design["sources"] != sources():
raise StopExperiment("sources_changed_during_experiment")
self.sequence += 1
name = f"{self.sequence:03d}-{point['variant']}-r{point['repeat']}-rate{point['rate']}"
if point.get("regime"):
name += "-" + point["regime"]
target = self.directory / point["phase"] / name
self.order.append({"sequence": self.sequence, "directory": str(target.relative_to(self.directory)), **point})
save(self.directory / "execution-order.json", self.order)
save(self.directory / "status.json", {"status": "running", "current": self.order[-1],
"elapsed_s": round(time.monotonic() - self.started, 1), "completed_runs": self.sequence - 1,
"smoke_only": self.design["smoke_only"]})
print(f"START {point['phase']} {name}", flush=True)
result = self.runtime.execute(point, target, self.protocol_sha, self.design, self.sequence)
if not result["valid"]:
cause = "generator_limited" if result["generator_limited"] else "instrument_or_runtime_invalid"
raise StopExperiment(cause)
if not result["correctness"]["passed"]:
raise StopExperiment("confirmed_data_not_preserved")
time.sleep(self.design["cooldown_s"])
return result
def execute(self):
old = json.loads((self.directory / "status.json").read_text())
if old["status"] != "prepared":
raise RuntimeError("Series has already started; raw data are retained. Prepare a new series.")
check_ports()
status, error, restored = "failed", None, False
try:
self.runtime.suspend_main()
save(self.directory / "environment-run.json", self.runtime.env_info)
if self.design["smoke_only"]:
for variant, settings in (("I0", config("A4", 16)), ("I1", config("A4", 1)), ("D1", config("A4", 16, 2))):
result = self.run_point({"phase": "smoke", "base": "A4", "rate": 20, "repeat": 1,
"variant": variant, "config": settings})
if not result["slo_pass"]:
raise StopExperiment("smoke_slo_not_met")
status = "smoke_complete"
else:
calibration = {name: [] for name in CONFIGS}
names = list(CONFIGS)
random.Random(self.design["calibration_seed"]).shuffle(names)
for name in names:
while True:
rate = next_rate(calibration[name], self.design["search"])
if rate is None:
break
result = self.run_point({"phase": "calibration", "base": name, "variant": name,
"rate": rate, "repeat": len(calibration[name]) + 1, "config": config(name)})
calibration[name].append({"rate": rate, "valid": result["valid"], "slo_pass": result["slo_pass"]})
save(self.directory / "calibration.json", calibration)
confirmation = freeze_confirmation(calibration)
confirmation["design_sha256"] = self.protocol_sha
save(self.directory / "confirmation.json", confirmation)
(self.directory / "confirmation.sha256").write_text(digest(confirmation) + "\n")
# This schedule is frozen before seeing any confirmation outcome.
for phase in ("scaling", "database", "gomax"):
for point in confirmation[phase]:
self.run_point(point)
status = "complete"
except StopExperiment as failure:
status, error = str(failure), str(failure)
except KeyboardInterrupt:
status, error = "interrupted", "KeyboardInterrupt"
except Exception as failure:
status, error = "failed", str(failure)
finally:
restored = self.runtime.restore()
save(self.directory / "restoration.json", json.loads((self.runtime.private / "restoration.json").read_text()))
save(self.directory / "status.json", {"status": status, "error": error, "restoration_ok": restored,
"elapsed_s": round(time.monotonic() - self.started, 1), "scheduled_or_started_runs": self.sequence,
"smoke_only": self.design["smoke_only"]})
print(f"FINISHED: {status}; original application restored={restored}", flush=True)
from results import analyze
analyze(self.directory)
return 0 if status in ("complete", "smoke_complete") and restored else 1
def main():
parser = argparse.ArgumentParser(__doc__)
parser.add_argument("action", choices=("prepare", "run", "smoke", "status", "analyze", "restore"))
parser.add_argument("--series", default="scale-check-v2")
args = parser.parse_args()
validate_name(args.series)
smoke = args.action == "smoke"
directory = directory_for(args.series, smoke)
if args.action == "status":
print((directory / "status.json").read_text())
return 0
if args.action == "analyze":
from results import analyze
analyze(directory)
return 0
lock_path = ROOT / ".memory/benchmark/experiment.lock"
lock_path.parent.mkdir(parents=True, exist_ok=True)
with lock_path.open("a") as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
parser.error("Another v1/v2 experiment is running")
if args.action == "prepare":
prepare(args.series)
return 0
if args.action == "restore":
design = json.loads((directory / "design.json").read_text())
return 0 if Runtime(args.series, design["image"], environment()).restore() else 1
if smoke:
prepare(args.series, smoke=True)
return Experiment(directory).execute()
if __name__ == "__main__":
try:
sys.exit(main())
except Exception as error:
print("ERROR: " + str(error), file=sys.stderr)
sys.exit(1)