feat(e2e): S0.2 ours-arm run capture (STRA-251)

Add scripts/e2e/evidence/capture.py, which builds one S0.1 END_TO_END record for the
ours arm from the meta file, the replay output, the engine logs and the power series.
analyze_session.py is wrapped by subprocess (--csv), never imported or edited.
Add test_capture.py (19 CPU-only stdlib tests, fixtures built in temp dirs).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-28 20:40:25 +01:00
co-authored by Claude Sonnet 5.5
parent 75254fb593
commit f01011a3ba
2 changed files with 982 additions and 0 deletions
+578
View File
@@ -0,0 +1,578 @@
#!/usr/bin/env python3
"""Run capture, OURS arm (STRA-251, S0.2 of STRA-245): build ONE S0.1 END_TO_END record from a finished run. Offline tooling, stdlib only,
Python >= 3.9, Windows and Linux. It reads outputs; it never launches the engine, a GPU job or the replay driver, and it changes no
existing file. Records belong in the run root (server ~/work/leleka-e2e/runs/<series>/<pair>/<arm>/, laptop main checkout artifacts/runs),
never in Git.
CLI v1 (fixed by the leaf):
capture.py --arm ours --meta META.json --replay-output REPLAY.json --engine-log strata-next.log --inference-log inference.log
--power-series POWER.csv --out REC.json [--analyze-session PATH]
Exit codes
0 record written
2 the logs carry no `leleka-serve cpu: ` line (message: "missing leleka-serve cpu: lines"); check C0, nothing written
3 another input is missing, damaged or inconsistent (the message names it); includes an existing --out (never overwritten)
4 the ENFORCED GPU power limit is N/A, empty or not a positive number in a sample (fail closed)
5 scripts/e2e/analyze_session.py failed or its --csv columns drifted
64 usage error (not 2, so that 2 stays unambiguous); the vanilla arms are STRA-315 and are refused here
How the pieces are obtained
analyze_session.py is a flat script (argparse and the whole report at module level, no main guard), so it is NEVER imported: it is wrapped
by SUBPROCESS and its `--csv` output is parsed (STRA-251 round-5 re-cut). The two logs are staged under their fixed names
(strata-next.log, inference.log) in a private temporary directory, with CRLF folded to LF (raw bytes are never stored; comparisons are on
the normalised text), because the script reads a RUN directory.
--meta (written by the runner, STRA-257): arm, series_id, block, pair_id, position, predecessor, schedule_hash, h0_id, machine and
ours_build_id (an object commit / target_triple / cargo_features / profile_value_sha256 = the FROZEN build id, STRA-304/322). Optional:
owner_attestation {present, identifier, time_utc}, foreign_load {samples}, synthetic, long_session_argv, source_snapshot_sha256.
--replay-output: the run JSON of replay_session.py (STRA-308); status must be "ok".
Engine logs (inference.log first, then strata-next.log; CRLF tolerated, a trailing CR is stripped):
`leleka-serve cpu: ...` and `leleka-serve gpu: ...` lines are copied VERBATIM, with the prefix, into kernel_lines (cpu lines required).
`leleka-serve gpu N: <name>, cc ...` gives gpu_name, `leleka-serve cpu: logical ...: <brand>; ...` gives cpu_model,
`leleka-serve gpu: CUDA driver X.Y ...` gives cuda_version.
RUN-FACTS CONTRACT v1 (key=value tokens separated by blanks; the engine does not print these today, the runner or a later engine change
must write them; a missing line is exit 3, never a guess; repeated lines must agree):
leleka-serve build: commit=<hex> target=<triple> features=<a,b|empty> profile_sha256=<hex> the OBSERVED BUILD ID
leleka-serve model: digest=<text> mapping=<text>
leleka-serve config: context_tokens=<int> kv=<text> slots=<int> batch=<int> speculation=<text>
leleka-serve cache: state=<WARM-OS/EMPTY-ENGINE|COLD> metric=<text> value=<number> unit=<text> measured before the run
--power-series (laptop: the S3.8 watchdog samples.tsv; server: an nvidia-smi sampler; both accepted): `# key=value` header lines, then a
header row and rows, tab or comma separated. Columns (names are matched case-insensitively, units in [] ignored):
limit = limit_w | enforced.power.limit power = power_w | power.draw time = utc | timestamp | t_s ok = ok (optional; 0 = a gap)
Header lines needed: thresholds_source (BOOTSTRAP|S3.7) and thresholds_sha256; optional power_limit_source (default enforced.power.limit),
power_max_limit_w, driver_version, gpu_name. power_max_limit_w, driver_version and (if the log has no gpu line) gpu_name are otherwise read
from `nvidia-smi --query-gpu` on this machine (process PATH); unreadable = exit 3.
gap_count = rows with ok=0 plus consecutive usable samples more than GAP_S seconds apart.
Not derived here, on purpose: `countable` and `invalid_reasons` are written as the neutral placeholders false / [] (the schema requires the
keys); STRA-312 derives both. In particular a mismatch between ours_build_id_observed and ours_build_id_frozen is only stored.
`quality` is a NOT_CHECKED placeholder that scripts/e2e/evidence/quality_step.py replaces.
"""
import argparse
import csv
import datetime
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
DEFAULT_ANALYZE = os.path.normpath(os.path.join(HERE, "..", "analyze_session.py"))
DEFAULT_UPSTREAM_DOC = os.path.normpath(os.path.join(HERE, "..", "..", "..", "docs", "upstream.md"))
EXIT_OK, EXIT_NO_CPU, EXIT_INPUT, EXIT_POWER_NA, EXIT_ANALYZE, EXIT_USAGE = 0, 2, 3, 4, 5, 64
GAP_S = 10.0 # a sample gap above this is counted (scripts/laptop/monitor.sh uses 10 s)
SMI_TIMEOUT_S = 5
ANALYZE_TIMEOUT_S = 300
KERNEL_LINE = re.compile(r"^leleka-serve (cpu|gpu): ")
CSV_COLUMNS = ("idx", "prompt_tokens", "reused_tokens", "engine_prefill_tok_s", "vram_expert_share", "join_ok")
META_KEYS = ("arm", "series_id", "block", "pair_id", "position", "predecessor", "schedule_hash", "h0_id", "machine", "ours_build_id")
BUILD_KEYS = ("commit", "target_triple", "cargo_features", "profile_value_sha256")
NA_TOKENS = {"", "n/a", "[n/a]", "na", "nan", "[not supported]", "[unknown error]", "unknown", "none", "null"}
class Fail(Exception):
def __init__(self, code, message):
Exception.__init__(self, message)
self.code = code
self.message = message
def fail_input(message):
return Fail(EXIT_INPUT, message)
# ---- small readers -------------------------------------------------------------------------------------------------------------------------
def read_bytes(path, what):
try:
with open(path, "rb") as f:
return f.read()
except OSError as exc:
raise fail_input("%s: cannot read %s: %s" % (what, path, exc.strerror or exc))
def normalise(raw):
return raw.decode("utf-8", "replace").replace("\r\n", "\n").replace("\r", "\n")
def read_text_lines(path, what):
return normalise(read_bytes(path, what)).split("\n")
def read_json(path, what):
try:
return json.loads(read_bytes(path, what).decode("utf-8-sig"))
except ValueError as exc:
raise fail_input("%s: %s is not valid JSON: %s" % (what, path, exc))
def sha256_hex(data):
return hashlib.sha256(data).hexdigest()
def to_float(token):
"""A number, or None for an N/A-like token or anything unparsable (units like ' W' are stripped)."""
t = str(token).strip()
if t.lower() in NA_TOKENS:
return None
t = re.sub(r"\s*(w|mhz|mib|%)\s*$", "", t, flags=re.I)
try:
v = float(t)
except ValueError:
return None
return v if v == v and v not in (float("inf"), float("-inf")) else None
def number_out(v):
return int(v) if float(v).is_integer() and abs(v) < 1e15 else v
# ---- meta ------------------------------------------------------------------------------------------------------------------------------------
def load_meta(path, arm):
meta = read_json(path, "--meta")
if not isinstance(meta, dict):
raise fail_input("--meta: %s is not a JSON object" % path)
for key in META_KEYS:
if key not in meta:
raise fail_input("--meta: missing key %s" % key)
if meta["arm"] != arm:
raise fail_input("--meta: arm %r differs from --arm %s" % (meta["arm"], arm))
for key in ("series_id", "pair_id", "predecessor", "schedule_hash", "h0_id", "machine"):
if not isinstance(meta[key], str) or not meta[key]:
raise fail_input("--meta: %s must be a non-empty string" % key)
for key in ("block", "position"):
if isinstance(meta[key], bool) or not isinstance(meta[key], int):
raise fail_input("--meta: %s must be an integer" % key)
frozen = meta["ours_build_id"]
if not isinstance(frozen, dict) or any(k not in frozen for k in BUILD_KEYS):
raise fail_input("--meta: ours_build_id must be an object with %s" % ", ".join(BUILD_KEYS))
return meta
# ---- replay output -----------------------------------------------------------------------------------------------------------------------------
def load_replay(path, meta):
rep = read_json(path, "--replay-output")
if not isinstance(rep, dict) or rep.get("mode") != "replay":
raise fail_input("--replay-output: %s is not a replay_session.py run JSON" % path)
if rep.get("status") != "ok":
raise fail_input("--replay-output: run status is %r, not ok (%s)" % (rep.get("status"), rep.get("error") or rep.get("mismatches") or "no detail"))
if rep.get("h0_id") != meta["h0_id"]:
raise fail_input("--replay-output: h0_id %r differs from --meta h0_id %r" % (rep.get("h0_id"), meta["h0_id"]))
turns = rep.get("turns")
if not isinstance(turns, list) or not turns:
raise fail_input("--replay-output: no turns")
need = ("turn", "prompt_sha256", "reply_sha256", "prompt_tokens", "cached_tokens", "output_tokens", "ttft_s", "latency_s", "decode_time_s")
for k, t in enumerate(turns):
for key in need:
if t.get(key) is None:
raise fail_input("--replay-output: turn %d has no usable %s" % (k + 1, key))
if t["turn"] != k + 1:
raise fail_input("--replay-output: turns are not numbered 1..n in order (position %d holds turn %r)" % (k + 1, t["turn"]))
if not t["ttft_s"] > 0 or not t["latency_s"] > 0:
raise fail_input("--replay-output: turn %d has a non-positive ttft_s or latency_s" % (k + 1))
for key in ("wall", "wall_norm"):
if not isinstance(rep.get(key), (int, float)) or not rep[key] > 0:
raise fail_input("--replay-output: %s missing or not positive" % key)
return rep
# ---- analyze_session.py by subprocess --------------------------------------------------------------------------------------------------------
def run_analyze(analyze_path, strata_lines, inference_lines):
"""Stage the logs under the names the script reads, run it with --csv, return the CSV rows. The script is never imported."""
if not os.path.isfile(analyze_path):
raise Fail(EXIT_ANALYZE, "analyze_session.py not found at %s" % analyze_path)
with tempfile.TemporaryDirectory(prefix="leleka-capture-") as tmp:
run_dir = os.path.join(tmp, "run")
os.mkdir(run_dir)
for name, lines in (("strata-next.log", strata_lines), ("inference.log", inference_lines)):
with open(os.path.join(run_dir, name), "w", encoding="utf-8", newline="\n") as f:
f.write("\n".join(lines))
csv_path = os.path.join(tmp, "trace.csv")
env = dict(os.environ)
env["PYTHONDONTWRITEBYTECODE"] = "1"
try:
proc = subprocess.run([sys.executable, analyze_path, run_dir, "--csv", csv_path], cwd=tmp, env=env, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, timeout=ANALYZE_TIMEOUT_S)
except (OSError, subprocess.SubprocessError) as exc:
raise Fail(EXIT_ANALYZE, "analyze_session.py could not run: %s" % exc)
if proc.returncode != 0:
tail = proc.stderr.decode("utf-8", "replace").strip().splitlines()[-3:]
raise Fail(EXIT_ANALYZE, "analyze_session.py exited %d: %s" % (proc.returncode, " | ".join(tail)))
if not os.path.isfile(csv_path):
raise Fail(EXIT_ANALYZE, "analyze_session.py wrote no --csv file")
with open(csv_path, newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
rows = list(reader)
columns = reader.fieldnames or []
if not rows:
raise fail_input("engine logs: no `generation done:` lines for analyze_session.py (is --engine-log strata-next.log?)")
missing = [c for c in CSV_COLUMNS if c not in columns]
if missing:
raise Fail(EXIT_ANALYZE, "analyze_session.py --csv columns drifted, missing: %s" % ", ".join(missing))
return rows
# ---- engine logs ---------------------------------------------------------------------------------------------------------------------------------
def parse_kv(text):
out = {}
for token in text.split():
if "=" in token:
k, v = token.split("=", 1)
out[k] = v
return out
def one_fact(lines, kind, keys):
"""Every `leleka-serve <kind>: k=v ...` line; they must agree. Returns {key: value} or raises exit 3."""
found = []
prefix = "leleka-serve %s: " % kind
for l in lines:
if l.startswith(prefix):
kv = parse_kv(l[len(prefix):])
found.append({k: kv.get(k) for k in keys})
if not found:
raise fail_input("engine logs: no `%s` line (run-facts contract v1)" % prefix.strip())
for f in found[1:]:
if f != found[0]:
raise fail_input("engine logs: `%s` lines disagree: %s vs %s" % (prefix.strip(), found[0], f))
got = found[0]
absent = [k for k in keys if got[k] is None]
if absent:
raise fail_input("engine logs: `%s` line lacks %s" % (prefix.strip(), ", ".join(absent)))
return got
def to_int(value, what):
try:
return int(value)
except (TypeError, ValueError):
raise fail_input("engine logs: %s is not an integer: %r" % (what, value))
def parse_engine(lines):
kernel_lines = []
for l in lines:
if KERNEL_LINE.match(l) and l not in kernel_lines:
kernel_lines.append(l)
cpu_lines = [l for l in kernel_lines if l.startswith("leleka-serve cpu: ")]
if not cpu_lines:
raise Fail(EXIT_NO_CPU, "missing leleka-serve cpu: lines")
brands = []
for l in cpu_lines:
m = re.match(r"leleka-serve cpu: logical \S+ \(\d+\): (.*?); AVX2/FMA/F16C:", l)
if m and m.group(1) not in brands:
brands.append(m.group(1))
if not brands:
raise fail_input("engine logs: no `leleka-serve cpu: logical ...` line names the CPU model")
gpus = []
for l in lines:
m = re.match(r"leleka-serve gpu \d+: (.*?), cc \d", l)
if m and m.group(1) not in gpus:
gpus.append(m.group(1))
cuda = None
for l in kernel_lines:
m = re.match(r"leleka-serve gpu: CUDA driver (\d+\.\d+)", l)
if m:
cuda = m.group(1)
break
if cuda is None:
raise fail_input("engine logs: no `leleka-serve gpu: CUDA driver X.Y` line (cuda_version)")
build = one_fact(lines, "build", ("commit", "target", "features", "profile_sha256"))
model = one_fact(lines, "model", ("digest", "mapping"))
config = one_fact(lines, "config", ("context_tokens", "kv", "slots", "batch", "speculation"))
cache = one_fact(lines, "cache", ("state", "metric", "value", "unit"))
return {"kernel_lines": kernel_lines, "cpu_model": " + ".join(brands), "gpu_names": gpus, "cuda_version": cuda, "build": build, "model": model,
"config": config, "cache": cache}
# ---- power series -----------------------------------------------------------------------------------------------------------------------------------
def norm_column(name):
return re.sub(r"\s*\[.*?\]\s*", "", name).strip().lower()
def parse_time(token):
v = to_float(token)
if v is not None:
return v
t = str(token).strip()
if t.endswith("Z"):
t = t[:-1]
for fmt in ("%Y-%m-%dT%H:%M:%S.%f", "%Y-%m-%dT%H:%M:%S", "%Y/%m/%d %H:%M:%S.%f", "%Y/%m/%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S"):
try:
return (datetime.datetime.strptime(t, fmt) - datetime.datetime(1970, 1, 1)).total_seconds()
except ValueError:
continue
return None
def parse_power(raw):
header, table = {}, []
for line in normalise(raw).split("\n"):
if not line.strip():
continue
if line.startswith("#"):
m = re.match(r"#\s*([A-Za-z0-9_.]+)\s*=\s*(.*)$", line)
if m:
header[m.group(1)] = m.group(2).strip()
continue
table.append(line)
if len(table) < 2:
raise fail_input("--power-series: no header row and samples")
delim = "\t" if "\t" in table[0] else ","
cols = [norm_column(c) for c in table[0].split(delim)]
def col(*names):
for n in names:
if n in cols:
return cols.index(n)
return None
i_limit, i_power = col("limit_w", "enforced.power.limit"), col("power_w", "power.draw")
i_time, i_ok = col("utc", "timestamp", "t_s"), col("ok")
if i_limit is None or i_power is None or i_time is None:
raise fail_input("--power-series: needs limit (limit_w | enforced.power.limit), power (power_w | power.draw) and time (utc | timestamp | t_s) columns")
i_maxlim, i_driver, i_name = col("power_max_limit_w", "power.max_limit"), col("driver_version"), col("name")
rows, gaps_ok0, extras = [], 0, {}
for line in table[1:]:
f = line.split(delim)
if len(f) != len(cols):
raise fail_input("--power-series: a row has %d fields, the header has %d" % (len(f), len(cols)))
if i_ok is not None and f[i_ok].strip() == "0":
gaps_ok0 += 1
continue
t = parse_time(f[i_time])
if t is None:
raise fail_input("--power-series: unparsable time %r" % f[i_time])
rows.append({"t": t, "limit_raw": f[i_limit], "limit": to_float(f[i_limit]), "power": to_float(f[i_power])})
for key, idx in (("power_max_limit_w", i_maxlim), ("driver_version", i_driver), ("gpu_name", i_name)):
if idx is not None and f[idx].strip().lower() not in NA_TOKENS and key not in extras:
extras[key] = f[idx].strip()
if not rows:
raise fail_input("--power-series: no usable sample")
for r in rows:
if r["limit"] is None or not r["limit"] > 0:
raise Fail(EXIT_POWER_NA, "enforced power limit is N/A or not a positive number in a sample (%r): fail closed" % r["limit_raw"].strip())
powers = [r["power"] for r in rows if r["power"] is not None]
if not powers:
raise fail_input("--power-series: no sample carries a power draw")
gaps = gaps_ok0 + sum(1 for a, b in zip(rows, rows[1:]) if b["t"] - a["t"] > GAP_S)
limits = [r["limit"] for r in rows]
return {"header": header, "extras": extras, "min_w": min(powers), "max_w": max(powers), "mean_w": sum(powers) / len(powers), "gap_count": gaps,
"limit_start": limits[0], "limit_end": limits[-1], "limit_min": min(limits), "limit_max": max(limits)}
def smi_query(fields):
"""One `nvidia-smi --query-gpu` line from this machine, as a list of strings, or None."""
exe = shutil.which("nvidia-smi")
if not exe:
return None
try:
proc = subprocess.run([exe, "--query-gpu=" + ",".join(fields), "--format=csv,noheader,nounits"], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
timeout=SMI_TIMEOUT_S)
except (OSError, subprocess.SubprocessError):
return None
if proc.returncode != 0:
return None
first = proc.stdout.decode("utf-8", "replace").strip().splitlines()
if not first:
return None
parts = [p.strip() for p in first[0].split(",")]
return parts if len(parts) == len(fields) else None
def machine_fact(power, key, smi_field):
"""header line, then a sampler column, then the machine (nvidia-smi); None when unreadable."""
for source in (power["header"], power["extras"]):
v = source.get(key)
if v and v.lower() not in NA_TOKENS:
return v
got = smi_query([smi_field])
if got and got[0].lower() not in NA_TOKENS:
return got[0]
return None
# ---- software ------------------------------------------------------------------------------------------------------------------------------------
def upstream_commit(doc_path):
try:
with open(doc_path, encoding="utf-8") as f:
text = f.read()
except OSError as exc:
raise fail_input("docs/upstream.md not readable (%s): %s" % (doc_path, exc.strerror or exc))
m = re.search(r"\|\s*Upstream commit SHA\s*\|\s*`([0-9a-f]{40})`", text)
if not m:
raise fail_input("docs/upstream.md: no `Upstream commit SHA` row with a 40-hex commit")
return m.group(1)
# ---- assembly --------------------------------------------------------------------------------------------------------------------------------------
def build_id(commit, target, features, profile):
feats = [x for x in (features or "").split(",") if x and x != "-"]
return {"commit": commit, "target_triple": target, "cargo_features": feats, "profile_value_sha256": profile}
def assemble(args, meta, rep, eng, power, power_raw, rows, smi_facts):
turns_out = []
for k, (t, row) in enumerate(zip(rep["turns"], rows)):
engine_rate = to_float(row.get("engine_prefill_tok_s", "")) if row.get("join_ok") == "True" else None
if engine_rate is not None and engine_rate > 0:
prefill = engine_rate
else:
fresh = t["prompt_tokens"] - t["cached_tokens"]
prefill = fresh / t["ttft_s"] if fresh > 0 else None
if prefill is None or not prefill > 0:
raise fail_input("turn %d: no prefill rate (no engine PREFILL-PROFILE chunk and nothing uncached to divide by)" % (k + 1))
dec = t["output_tokens"] / t["decode_time_s"] if t["decode_time_s"] > 0 and t["output_tokens"] > 0 else None
turns_out.append({"turn": t["turn"], "prompt_tokens": t["prompt_tokens"], "cached_tokens": t["cached_tokens"], "output_tokens": t["output_tokens"],
"ttft_s": t["ttft_s"], "prefill_tok_s": prefill, "decode_tok_s": dec, "wall_s": t["latency_s"],
"prompt_sha256": t["prompt_sha256"], "reply_sha256": t["reply_sha256"]})
vram = [to_float(r.get("vram_expert_share", "")) for r in rows]
vram = [v for v in vram if v is not None]
cfg = eng["config"]
if to_int(cfg["context_tokens"], "config context_tokens") != rep.get("context_tokens"):
sys.stderr.write("capture: warning: engine config context_tokens %s differs from the replay context_tokens %s\n" % (cfg["context_tokens"], rep.get("context_tokens")))
gpu_name = " + ".join(eng["gpu_names"]) if eng["gpu_names"] else smi_facts.get("gpu_name")
argv = meta.get("long_session_argv") or ["replay_session.py", "replay", "--turns", str(len(rep["turns"])), "--target-tokens", str(rep.get("target_tokens")),
"--context", str(rep.get("context_tokens"))]
snapshot = meta.get("source_snapshot_sha256") or sha256_hex("\n".join(t["prompt_sha256"] for t in rep["turns"]).encode("ascii"))
cache = eng["cache"]
value = to_float(cache["value"])
if value is None:
raise fail_input("engine logs: cache value %r is not a number" % cache["value"])
build = eng["build"]
series_name = os.path.basename(args.power_series)
rec = {
"schema_version": "1",
"level": "END_TO_END",
}
if meta.get("synthetic") is True:
rec["synthetic"] = True
rec.update({
"arm_identity": {"arm": meta["arm"], "series_id": meta["series_id"], "schedule_sha256": meta["schedule_hash"], "block": meta["block"],
"position": meta["position"], "predecessor_arm": meta["predecessor"], "pair_id": meta["pair_id"], "h0_id": meta["h0_id"]},
"ours_build_id_observed": build_id(build["commit"], build["target"], build["features"], build["profile_sha256"]),
"ours_build_id_frozen": {k: meta["ours_build_id"][k] for k in BUILD_KEYS},
"countable": False,
"invalid_reasons": [],
"power_sample_summary": {"min_w": number_out(power["min_w"]), "max_w": number_out(power["max_w"]), "mean_w": number_out(power["mean_w"]),
"gap_count": power["gap_count"], "series_sha256": sha256_hex(power_raw),
"power_max_limit_w": number_out(smi_facts["power_max_limit_w"]),
"power_limit_changed": power["limit_start"] != power["limit_end"],
"power_limit_source": power["header"].get("power_limit_source", "enforced.power.limit")},
"thresholds_source": power["header"]["thresholds_source"],
"thresholds_sha256": power["header"]["thresholds_sha256"],
"workload": {"long_session_argv": argv, "source_snapshot_sha256": snapshot, "turn1_tokens": turns_out[0]["prompt_tokens"]},
"cache": {"state": cache["state"], "page_cache_residency_before": {"metric": cache["metric"], "value": number_out(value), "unit": cache["unit"]}},
"hardware": {"machine_role": meta["machine"], "cpu_model": eng["cpu_model"], "gpu_name": gpu_name, "os": smi_facts["os"],
"enforced_power_limit_w_start": number_out(power["limit_start"]), "enforced_power_limit_w_end": number_out(power["limit_end"]),
"power_sample_series_file": series_name,
"owner_attestation": meta.get("owner_attestation", {"present": False, "identifier": None, "time_utc": None}),
"foreign_load": meta.get("foreign_load", {"samples": []})},
"software": {"driver_version": smi_facts["driver_version"], "cuda_version": eng["cuda_version"], "leleka_commit": build["commit"],
"strata_upstream_commit": smi_facts["upstream_commit"]},
"model": {"digest": eng["model"]["digest"], "digest_mapping": eng["model"]["mapping"]},
"configuration": {"context_tokens": to_int(cfg["context_tokens"], "config context_tokens"), "kv": cfg["kv"], "slots": to_int(cfg["slots"], "config slots"),
"batch": to_int(cfg["batch"], "config batch"), "speculation": cfg["speculation"]},
"metrics": {"turns": turns_out, "wall_s": rep["wall"], "wall_norm_s": rep["wall_norm"], "draft_acceptance": None,
"expert_cache_hit": round(sum(vram) / len(vram), 4) if vram else None, "kv_streaming_hit": None},
"quality": {"verdict": "NOT_CHECKED", "tolerance": "none", "basis": "quality_step.py runs after capture and replaces this block", "baseline": "none",
"tool_call_integrity": "NOT_CHECKED"},
"kernel_lines": eng["kernel_lines"],
})
return rec
def run(args):
if args.arm != "ours":
raise Fail(EXIT_USAGE, "arm %s is captured by STRA-315, this script captures --arm ours only" % args.arm)
if os.path.exists(args.out):
raise fail_input("--out %s exists; a record is never overwritten" % args.out)
meta = load_meta(args.meta, args.arm)
rep = load_replay(args.replay_output, meta)
inference_lines = read_text_lines(args.inference_log, "--inference-log")
strata_lines = read_text_lines(args.engine_log, "--engine-log")
eng = parse_engine(inference_lines + strata_lines)
power_raw = read_bytes(args.power_series, "--power-series")
power = parse_power(power_raw)
for key in ("thresholds_source", "thresholds_sha256"):
if not power["header"].get(key):
raise fail_input("--power-series: header line `# %s=` missing" % key)
rows = run_analyze(args.analyze_session, strata_lines, inference_lines)
if len(rows) != len(rep["turns"]):
raise fail_input("engine log holds %d generations, the replay output %d turns" % (len(rows), len(rep["turns"])))
for k, (t, row) in enumerate(zip(rep["turns"], rows)):
try:
logged = int(row["prompt_tokens"])
except ValueError:
raise Fail(EXIT_ANALYZE, "analyze_session.py --csv: prompt_tokens of row %d is not an integer" % (k + 1))
if abs(logged - t["prompt_tokens"]) > 1:
raise fail_input("turn %d: engine log prompt_tokens %d differs from the replay output %d" % (k + 1, logged, t["prompt_tokens"]))
max_limit = machine_fact(power, "power_max_limit_w", "power.max_limit")
driver = machine_fact(power, "driver_version", "driver_version")
gpu_fallback = None
if not eng["gpu_names"]:
gpu_fallback = machine_fact(power, "gpu_name", "name")
if gpu_fallback is None:
raise fail_input("gpu_name: no `leleka-serve gpu N:` line, no sampler column and nvidia-smi unreadable")
smi = {"power_max_limit_w": to_float(max_limit) if max_limit else None, "driver_version": driver, "os": sys_os(),
"gpu_name": gpu_fallback, "upstream_commit": upstream_commit(args.upstream_doc)}
if smi["power_max_limit_w"] is None or not smi["power_max_limit_w"] > 0:
raise fail_input("power_max_limit_w: not in the power-series header or columns and nvidia-smi unreadable")
if not smi["driver_version"]:
raise fail_input("driver_version: not in the power-series header or columns and nvidia-smi unreadable")
rec = assemble(args, meta, rep, eng, power, power_raw, rows, smi)
if power["limit_min"] != power["limit_max"] and not rec["power_sample_summary"]["power_limit_changed"]:
sys.stderr.write("capture: warning: the enforced limit moved inside the run (%s..%s W) and returned to its start value\n" % (power["limit_min"], power["limit_max"]))
out_dir = os.path.dirname(os.path.abspath(args.out))
os.makedirs(out_dir, exist_ok=True)
tmp_path = args.out + ".tmp"
with open(tmp_path, "w", encoding="utf-8", newline="\n") as f:
json.dump(rec, f, indent=2)
f.write("\n")
os.replace(tmp_path, args.out)
return EXIT_OK
def sys_os():
import platform
return platform.platform()
class Parser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write("capture.py: usage error: %s\n" % message)
raise SystemExit(EXIT_USAGE)
def main(argv=None):
ap = Parser(description=__doc__.split("\n")[0], add_help=True)
ap.add_argument("--arm", required=True)
ap.add_argument("--meta", required=True)
ap.add_argument("--replay-output", required=True)
ap.add_argument("--engine-log", required=True, help="strata-next.log")
ap.add_argument("--inference-log", required=True, help="inference.log")
ap.add_argument("--power-series", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--analyze-session", default=DEFAULT_ANALYZE, help="path of analyze_session.py (default: the sibling in scripts/e2e)")
ap.add_argument("--upstream-doc", default=DEFAULT_UPSTREAM_DOC, help="docs/upstream.md (default: this checkout's)")
args = ap.parse_args(argv)
try:
return run(args)
except Fail as exc:
sys.stderr.write("capture: %s\n" % exc.message)
return exc.code
if __name__ == "__main__":
sys.exit(main())
+404
View File
@@ -0,0 +1,404 @@
#!/usr/bin/env python3
"""Tests of capture.py (STRA-251). CPU-only, stdlib only, Python >= 3.9, Windows and Linux:
python -m unittest discover -s scripts/e2e/evidence -p "test_capture.py" -v
Every fixture is built here in a temporary directory (nothing is committed, no weights, no captured requests, no credentials). capture.py runs as a
real subprocess; analyze_session.py runs through it for real (the wrap is part of what is tested)."""
import hashlib
import json
import os
import re
import stat
import subprocess
import sys
import tempfile
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
CAPTURE = os.path.join(HERE, "capture.py")
VALIDATE = os.path.join(HERE, "validate.py")
ANALYZE = os.path.normpath(os.path.join(HERE, "..", "analyze_session.py"))
COMMIT = "0123456789abcdef0123456789abcdef01234567"
OTHER_COMMIT = "fedcba9876543210fedcba9876543210fedcba98"
PROFILE = "f467e6a6af8f3bc29f37fe326d5dd922ebcf260e69561d160a1637fe8cd04dd0"
THRESH = "0bf18d635f3bbcd7a832ffb3470087a916f07374bc88b9064667f5b7de86c558"
PROMPTS = [43000, 86500, 130000, 172500, 215000]
CACHED = [0, 43700, 87200, 130700, 173200]
CPU_LINES = [
"leleka-serve cpu: logical 0-15 (16): Sample CPU 16-Core; AVX2/FMA/F16C: yes; AVX-512 F/BW/VL/DQ/VBMI/VNNI: all; kernel family on this core: AVX-512",
"leleka-serve cpu: process kernel family AVX-512 (IQ rows: 512-bit on, 256-bit on; IQ4_NL on)",
]
GPU_LINES = [
"leleka-serve gpu: CUDA driver 12.8, 1 device(s), sm_86 companions in this build: yes, chain kernels: default",
"leleka-serve gpu 0: Sample GPU 16GB, cc 8.6, 48 SMs, 16.0 GiB; kernels: sm_86 companion; MMQ launch: x",
]
FACT_LINES = [
"leleka-serve build: commit=%s target=x86_64-unknown-linux-gnu features=cuda,native-cpu-expert profile_sha256=%s" % (COMMIT, PROFILE),
"leleka-serve model: digest=sample-model-digest mapping=sample-digest-mapping-ref",
"leleka-serve config: context_tokens=262144 kv=sample-kv slots=1 batch=512 speculation=off",
"leleka-serve cache: state=WARM-OS/EMPTY-ENGINE metric=model_file_resident_fraction value=0.97 unit=fraction",
]
def read_raw(path):
with open(path, "rb") as f:
return f.read()
def sha(text):
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def power_text(limits=("130.0", "130.0"), header_extra=True, comma=False):
"""The watchdog samples.tsv shape (tab) or an nvidia-smi sampler shape (comma)."""
lines = ["# watchdog_sample_series v1", "# thresholds_source=BOOTSTRAP", "# thresholds_sha256=" + THRESH, "# power_limit_source=enforced.power.limit"]
if header_extra:
lines += ["# power_max_limit_w=150.0", "# driver_version=571.96"]
if comma:
lines = [l for l in lines if "watchdog" not in l]
lines.append("timestamp, power.draw [W], enforced.power.limit [W]")
for i in range(4):
lim = limits[0] if i < 2 else limits[1]
lines.append("2026/10/28 12:00:%02d.000, %s, %s" % (i, 118.0 + i, lim))
return "\n".join(lines) + "\n"
cols = ["phase", "t_s", "utc", "ok", "why", "pstate", "sm_mhz", "mem_mhz", "power_w", "throttle", "limit_w", "temp_c", "util", "vram_mib"]
lines.append("\t".join(cols))
for i in range(4):
lim = limits[0] if i < 2 else limits[1]
lines.append("\t".join(["run", str(i), str(1790000000 + i), "1", "", "P0", "1800", "7000", str(118.0 + i), "0x0", lim, "70", "99", "9000"]))
return "\n".join(lines) + "\n"
class Run:
"""A finished run in a temporary directory plus the means to call capture.py on it."""
def __init__(self, test, inference_extra=(), facts=True, cpu=True, nl="\n", power=None, replay_edit=None, meta_edit=None, engine_edit=None):
self.dir = tempfile.mkdtemp(prefix="cap-test-")
test.addCleanup(self._cleanup)
d = self.dir
self.meta = {"arm": "ours", "series_id": "series-test", "block": 1, "pair_id": "pair-test", "position": 2, "predecessor": "vanilla_default",
"schedule_hash": sha("schedule"), "h0_id": "h0-test", "machine": "unit-test-machine",
"ours_build_id": {"commit": COMMIT, "target_triple": "x86_64-unknown-linux-gnu", "cargo_features": ["cuda", "native-cpu-expert"],
"profile_value_sha256": PROFILE}, "synthetic": True}
if meta_edit:
meta_edit(self.meta)
turns, wall = [], 0.0
for k in range(5):
ttft, lat = 20.0 + 5 * k, 27.0 + 5 * k
wall += lat
turns.append({"turn": k + 1, "prompt_sha256": sha("prompt%d" % k), "reply_sha256": sha("reply%d" % k), "prompt_tokens": PROMPTS[k],
"cached_tokens": CACHED[k], "output_tokens": 700, "n_k": 700, "ttft_s": ttft, "latency_s": lat, "decode_time_s": lat - ttft,
"length_unmatched": False, "reply_matches_h0": True, "status": "completed"})
self.replay = {"mode": "replay", "h0_id": "h0-test", "context_tokens": 262144, "target_tokens": 245000, "status": "ok", "turns": turns,
"wall": wall, "wall_norm": wall, "ttft_sum": 125.0}
if replay_edit:
replay_edit(self.replay)
strata, inf = [], []
gpu_lines = list(GPU_LINES)
inf += (CPU_LINES if cpu else []) + gpu_lines + (FACT_LINES if facts else []) + list(inference_extra)
t = 1790000000000
for k in range(5):
p, c = PROMPTS[k], CACHED[k]
strata.append("generation start: t_unix_ms=%d prompt_tokens=%d max_new=700" % (t, p))
inf.append("prefill_phase start n=%d resume=%d" % (p, c))
inf.append("PREFILL-PROFILE first=%d tokens=%d total_ms=%.1f" % (c, p - c, (p - c) / 2.0))
inf.append("leleka-serve request outcome=completed produced=700 rounds=300 reused=%d" % c)
inf.append("expert tier: 12 layer groups, entries vram %d hit, pcie %d hit, cpu %d hit, 3 adaptations, %d swaps" % (80 * (k + 1), 15 * (k + 1), 5 * (k + 1), k))
t += 27000 + 5000 * k
strata.append("generation done: t_unix_ms=%d finish=Stop prompt_tokens=%d reused=%d generated=700 prompt_ms=%d decode_ms=7000 disconnected=false"
% (t, p, c, (20 + 5 * k) * 1000))
t += 1000
if engine_edit:
strata, inf = engine_edit(strata, inf)
self.paths = {}
for name, body in (("strata-next.log", "\n".join(strata) + "\n"), ("inference.log", "\n".join(inf) + "\n")):
self._write(name, body.replace("\n", nl))
self._write("meta.json", json.dumps(self.meta))
self._write("replay.json", json.dumps(self.replay))
self._write("power.csv", power if power is not None else power_text())
self.out = os.path.join(d, "out", "rec.json")
def _write(self, name, text):
path = os.path.join(self.dir, name)
with open(path, "w", encoding="utf-8", newline="") as f:
f.write(text)
self.paths[name] = path
def _cleanup(self):
import shutil
shutil.rmtree(self.dir, ignore_errors=True)
def argv(self, arm="ours", extra=()):
return [sys.executable, CAPTURE, "--arm", arm, "--meta", self.paths["meta.json"], "--replay-output", self.paths["replay.json"],
"--engine-log", self.paths["strata-next.log"], "--inference-log", self.paths["inference.log"], "--power-series", self.paths["power.csv"],
"--out", self.out] + list(extra)
def run(self, path_dir=None, extra=(), arm="ours", env_extra=None):
env = dict(os.environ)
empty = os.path.join(self.dir, "no-tools")
os.makedirs(empty, exist_ok=True)
env["PATH"] = path_dir or empty # no nvidia-smi on the PATH unless a test provides a shim
env["PYTHONDONTWRITEBYTECODE"] = "1"
env.update(env_extra or {})
return subprocess.run(self.argv(arm, extra), stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, universal_newlines=True)
def record(self):
with open(self.out, encoding="utf-8") as f:
return json.load(f)
def validate(path):
return subprocess.run([sys.executable, VALIDATE, path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
def make_smi_shim(test, driver="571.96", max_limit="150.00", name="Shim GPU"):
"""An nvidia-smi on a private PATH directory that answers the three --query-gpu fields capture.py asks for."""
d = tempfile.mkdtemp(prefix="cap-smi-")
import shutil
test.addCleanup(lambda: shutil.rmtree(d, ignore_errors=True))
py = os.path.join(d, "smi.py")
with open(py, "w") as f:
f.write("import sys\nq = sys.argv[1].split('=')[1]\n"
"print({'driver_version': %r, 'power.max_limit': %r, 'name': %r}.get(q, 'N/A'))\n" % (driver, max_limit, name))
if os.name == "nt":
with open(os.path.join(d, "nvidia-smi.cmd"), "w") as f:
f.write('@echo off\r\n"%s" "%s" %%*\r\n' % (sys.executable, py))
else:
exe = os.path.join(d, "nvidia-smi")
with open(exe, "w") as f:
f.write('#!/bin/sh\nexec "%s" "%s" "$@"\n' % (sys.executable, py))
os.chmod(exe, os.stat(exe).st_mode | stat.S_IXUSR)
return d
class TestCapture(unittest.TestCase):
def ok(self, r):
self.assertEqual(r.returncode, 0, "stdout=%r stderr=%r" % (r.stdout, r.stderr))
def test_ours_record_is_written_and_validates(self): # AC2
run = Run(self)
r = run.run()
self.ok(r)
v = validate(run.out)
self.assertEqual(v.returncode, 0, v.stdout + v.stderr)
self.assertTrue(v.stdout.startswith("OK ours"), v.stdout)
rec = run.record()
ai = rec["arm_identity"]
self.assertEqual((ai["arm"], ai["series_id"], ai["block"], ai["position"], ai["predecessor_arm"], ai["pair_id"], ai["h0_id"]),
("ours", "series-test", 1, 2, "vanilla_default", "pair-test", "h0-test"))
self.assertEqual(ai["schedule_sha256"], sha("schedule"))
self.assertEqual(rec["kernel_lines"], CPU_LINES + [GPU_LINES[0]]) # verbatim, with the prefix; the per-device `gpu 0:` line has another shape
self.assertEqual(rec["hardware"]["cpu_model"], "Sample CPU 16-Core")
self.assertEqual(rec["hardware"]["gpu_name"], "Sample GPU 16GB")
self.assertEqual(rec["hardware"]["machine_role"], "unit-test-machine")
self.assertEqual(rec["software"]["cuda_version"], "12.8")
self.assertEqual(rec["software"]["driver_version"], "571.96")
self.assertRegex(rec["software"]["strata_upstream_commit"], r"^[0-9a-f]{40}$")
self.assertEqual(rec["model"], {"digest": "sample-model-digest", "digest_mapping": "sample-digest-mapping-ref"})
self.assertEqual(rec["configuration"]["context_tokens"], 262144)
self.assertEqual(rec["cache"]["state"], "WARM-OS/EMPTY-ENGINE")
self.assertEqual(rec["cache"]["page_cache_residency_before"]["value"], 0.97)
self.assertEqual([t["prompt_sha256"] for t in rec["metrics"]["turns"]], [sha("prompt%d" % k) for k in range(5)])
self.assertEqual([t["reply_sha256"] for t in rec["metrics"]["turns"]], [sha("reply%d" % k) for k in range(5)])
self.assertEqual(rec["workload"]["turn1_tokens"], PROMPTS[0])
self.assertEqual(rec["thresholds_source"], "BOOTSTRAP")
self.assertEqual(rec["power_sample_summary"]["series_sha256"], hashlib.sha256(read_raw(run.paths["power.csv"])).hexdigest())
self.assertFalse(rec["power_sample_summary"]["power_limit_changed"])
self.assertEqual(rec["power_sample_summary"]["gap_count"], 0)
# the engine's own prefill rate (PREFILL-PROFILE through analyze_session.py --csv) is used: 2 ms per token -> 2000 tok/s for the first turn
self.assertAlmostEqual(rec["metrics"]["turns"][0]["prefill_tok_s"], 2000.0, places=0)
self.assertAlmostEqual(rec["metrics"]["turns"][0]["decode_tok_s"], 100.0, places=6) # 700 tokens / 7 s
self.assertEqual(rec["metrics"]["wall_s"], run.replay["wall"])
self.assertIsNotNone(rec["metrics"]["expert_cache_hit"])
def test_power_limit_change_is_recorded_not_hidden(self): # AC3
run = Run(self, power=power_text(limits=("130.0", "125.0")))
self.ok(run.run())
rec = run.record()
ps = rec["power_sample_summary"]
self.assertIs(ps["power_limit_changed"], True)
self.assertEqual((rec["hardware"]["enforced_power_limit_w_start"], rec["hardware"]["enforced_power_limit_w_end"]), (130, 125))
self.assertEqual(ps["series_sha256"], hashlib.sha256(read_raw(run.paths["power.csv"])).hexdigest())
v = validate(run.out)
self.assertEqual(v.returncode, 0, v.stdout)
def test_na_enforced_limit_exits_4(self): # AC3
for bad in ("N/A", "[N/A]", "", "NA", "0"):
with self.subTest(bad=bad):
run = Run(self, power=power_text(limits=("130.0", bad)))
r = run.run()
self.assertEqual(r.returncode, 4, r.stdout + r.stderr)
self.assertIn("fail closed", r.stderr)
self.assertFalse(os.path.exists(run.out))
run = Run(self, power=power_text(limits=("130.0", "N/A"), comma=True))
self.assertEqual(run.run().returncode, 4)
def test_missing_cpu_lines_exits_2(self): # AC4
run = Run(self, cpu=False)
r = run.run()
self.assertEqual(r.returncode, 2, r.stdout + r.stderr)
self.assertIn("missing leleka-serve cpu: lines", r.stderr)
self.assertFalse(os.path.exists(run.out))
# a bare `cpu:` line (the vanilla shape, no engine prefix) does not count either
run = Run(self, cpu=False, inference_extra=["cpu: logical 0-15 (16): Sample CPU; AVX2/FMA/F16C: yes"])
self.assertEqual(run.run().returncode, 2)
def test_build_id_mismatch(self): # AC5
def edit(meta):
meta["ours_build_id"] = dict(meta["ours_build_id"], commit=OTHER_COMMIT)
run = Run(self, meta_edit=edit)
r = run.run()
self.ok(r)
rec = run.record()
self.assertEqual(rec["ours_build_id_observed"]["commit"], COMMIT)
self.assertEqual(rec["ours_build_id_frozen"]["commit"], OTHER_COMMIT)
self.assertNotEqual(rec["ours_build_id_observed"], rec["ours_build_id_frozen"])
self.assertEqual(rec["ours_build_id_observed"]["cargo_features"], ["cuda", "native-cpu-expert"])
# capture.py derives neither: the placeholders are the neutral values the schema needs, with no reason added for the mismatch
self.assertIs(rec["countable"], False)
self.assertEqual(rec["invalid_reasons"], [])
self.assertEqual(validate(run.out).returncode, 0)
def test_crlf_logs_give_the_same_record(self):
lf, crlf = Run(self), Run(self, nl="\r\n")
self.ok(lf.run())
self.ok(crlf.run())
a, b = lf.record(), crlf.record()
self.assertEqual(a["kernel_lines"], b["kernel_lines"])
self.assertFalse(any("\r" in l for l in b["kernel_lines"]))
self.assertEqual(a["metrics"], b["metrics"])
self.assertEqual(a["ours_build_id_observed"], b["ours_build_id_observed"])
def test_secrets_in_the_logs_never_reach_the_record(self):
secret = "sk-test-0123456789SECRET"
run = Run(self, inference_extra=["E2E_API_KEY=" + secret, "leleka-serve cpu: logical 0 (1): Sample; note E2E_API_KEY is not printed"])
r = run.run(env_extra={"E2E_API_KEY": secret})
self.ok(r)
with open(run.out, encoding="utf-8") as f:
text = f.read()
self.assertNotIn(secret, text)
self.assertNotIn("E2E_API_KEY=", text)
def test_missing_run_facts_exit_3_and_name_the_line(self):
run = Run(self, facts=False)
r = run.run()
self.assertEqual(r.returncode, 3, r.stderr)
self.assertIn("leleka-serve build:", r.stderr)
self.assertFalse(os.path.exists(run.out))
def test_disagreeing_build_lines_exit_3(self):
other = FACT_LINES[0].replace(COMMIT, OTHER_COMMIT)
run = Run(self, inference_extra=[other])
r = run.run()
self.assertEqual(r.returncode, 3, r.stderr)
self.assertIn("disagree", r.stderr)
def test_analyze_session_is_wrapped_never_imported(self): # AC6 (grep part) and the column-drift guard
with open(CAPTURE, encoding="utf-8") as f:
text = f.read()
self.assertIsNone(re.search(r"import analyze_session|from analyze_session", text))
self.assertIsNone(re.search(r"importlib|__import__|runpy", text))
fake = tempfile.mkdtemp(prefix="cap-fake-")
self.addCleanup(lambda: __import__("shutil").rmtree(fake, ignore_errors=True))
script = os.path.join(fake, "analyze_session.py")
with open(script, "w") as f:
f.write("import sys\nopen(sys.argv[sys.argv.index('--csv') + 1], 'w').write('idx,prompt_tokens\\n0,43000\\n')\n")
run = Run(self)
r = run.run(extra=["--analyze-session", script])
self.assertEqual(r.returncode, 5, r.stderr)
self.assertIn("drifted", r.stderr)
self.assertIn("engine_prefill_tok_s", r.stderr)
with open(script, "w") as f:
f.write("import sys\nsys.exit(7)\n")
r = run.run(extra=["--analyze-session", script])
self.assertEqual(r.returncode, 5, r.stderr)
self.assertIn("exited 7", r.stderr)
def test_engine_log_that_disagrees_with_the_replay_output_exits_3(self):
def edit(replay):
replay["turns"][2]["prompt_tokens"] = 130500
run = Run(self, replay_edit=edit)
r = run.run()
self.assertEqual(r.returncode, 3, r.stderr)
self.assertIn("turn 3", r.stderr)
run = Run(self, engine_edit=lambda s, i: (s[:-2], i)) # one generation fewer in the engine log
r = run.run()
self.assertEqual(r.returncode, 3, r.stderr)
self.assertIn("4 generations", r.stderr)
def test_replay_that_is_not_ok_or_for_another_h0_exits_3(self):
run = Run(self, replay_edit=lambda rep: rep.update({"status": "failed", "error": "turn 4: HTTP 500"}))
r = run.run()
self.assertEqual(r.returncode, 3, r.stderr)
self.assertIn("not ok", r.stderr)
run = Run(self, replay_edit=lambda rep: rep.update({"h0_id": "another-h0"}))
r = run.run()
self.assertEqual(r.returncode, 3, r.stderr)
self.assertIn("h0_id", r.stderr)
def test_vanilla_arms_are_refused_here(self):
run = Run(self)
for arm in ("vanilla_default", "vanilla_noskip"):
r = run.run(arm=arm)
self.assertEqual(r.returncode, 64, r.stderr)
self.assertIn("STRA-315", r.stderr)
self.assertFalse(os.path.exists(run.out))
def test_usage_error_is_64_not_2(self):
r = subprocess.run([sys.executable, CAPTURE, "--arm", "ours"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
self.assertEqual(r.returncode, 64)
def test_an_existing_record_is_never_overwritten(self):
run = Run(self)
self.ok(run.run())
before = read_raw(run.out)
r = run.run()
self.assertEqual(r.returncode, 3, r.stderr)
self.assertEqual(read_raw(run.out), before)
def test_sampler_csv_and_machine_facts_from_nvidia_smi(self):
# server shape: comma separated nvidia-smi sampler, no driver / max-limit in it; they come from nvidia-smi on the PATH (shim)
run = Run(self, power=power_text(header_extra=False, comma=True))
shim = make_smi_shim(self, driver="570.123", max_limit="575.00")
r = run.run(path_dir=shim)
self.ok(r)
rec = run.record()
self.assertEqual(rec["software"]["driver_version"], "570.123")
self.assertEqual(rec["power_sample_summary"]["power_max_limit_w"], 575)
self.assertEqual(rec["power_sample_summary"]["gap_count"], 0)
self.assertEqual(rec["power_sample_summary"]["min_w"], 118)
self.assertEqual(validate(run.out).returncode, 0)
def test_unreadable_machine_facts_exit_3(self):
run = Run(self, power=power_text(header_extra=False)) # no header values and no nvidia-smi on the PATH
r = run.run()
self.assertEqual(r.returncode, 3, r.stderr)
self.assertIn("power_max_limit_w", r.stderr)
def test_power_gaps_are_counted(self):
text = power_text()
lines = text.split("\n")
# move the last two samples 60 s later: one gap; mark one more sample as failed (ok=0): a second gap
for i in (-3, -2):
f = lines[i].split("\t")
f[2] = str(int(f[2]) + 60)
lines[i] = "\t".join(f)
f = lines[-5].split("\t")
f[3] = "0"
lines[-5] = "\t".join(f)
run = Run(self, power="\n".join(lines))
self.ok(run.run())
self.assertEqual(run.record()["power_sample_summary"]["gap_count"], 2)
def test_missing_thresholds_header_exits_3(self):
text = "\n".join(l for l in power_text().split("\n") if not l.startswith("# thresholds_sha256"))
run = Run(self, power=text)
r = run.run()
self.assertEqual(r.returncode, 3, r.stderr)
self.assertIn("thresholds_sha256", r.stderr)
if __name__ == "__main__":
unittest.main()