"""The in-game gate's parser: one run folder of scripts/game-gate.ps1 to its state and its summary.json. python -I tools/game_gate.py state # JSON on stdout: what the supervisor stops on python -I tools/game_gate.py summary # writes /summary.json; exit 0 PASS, 1 FAIL, 2 ERROR Standard library only. It reads run.json and events.jsonl (written by the gate script), launcher.txt (the play script's output: the precompile lines), leonida.log (the runtime's log) and data/*/crashes.log. The summary holds numbers, switch names and verdicts only: no path, no user or machine name, nothing the title printed. Schema and rules: docs/game_gate.md. """ import csv import datetime as dt import glob import json import os import re import statistics import sys SCHEMA = "leonida-gate-summary/1" # The runtime's first 3D frames draw hundreds of times a frame; its menus and loading screens a few dozen # (capture.rs uses the same threshold). Two frame lines in a row, so a single busy menu frame does not count. WORLD_DRAWS = 500 WORLD_LINES = 2 # Warm: this long in the world with no pipeline being made and no wait for one that ran out. (Draws dropped for # a pipeline the host never has go on all run long, so they do not count.) WARM_QUIET_S = 60.0 # The frames counted for fps start this long after the world is reached, and the end median covers this long. AFTER_WORLD_S = 60.0 END_WINDOW_S = 60.0 # A run that shows no new frame for longer than this, once in the world, is frozen, not slow. GAP_FAIL_S = 10.0 # The last frame line before the stop request is at most this old for the run to count as alive. ALIVE_S = 30.0 # The memory stop: the PC under its commit floor this long (5 s memory lines). COMMIT_LOW_S = 20.0 DEVICE_LOST = 0x887A0005 ANSI = re.compile(r"\x1b\[[0-9;]*m") LINE = re.compile(r"^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?)Z\s+([A-Z]+)\s+([\w:]+): (.*)$") FRAME = re.compile( r"([\d.]+) fps, ([\d.]+) ms/frame \(.*?\), ([\d.]+) draws/frame, dropped ([\d.]+) without a host pipeline " r"\((\d+) being made\)") SHADERS = re.compile(r"^(\d+) shaders in the cache, (?:(\d+) do not translate, )?(\d+) s$") KNOWN = re.compile(r"^(\d+) pipelines known, (\d+) made before \([^)]*\), (\d+) bad; (\d+) to make") MADE = re.compile(r"^(\d+) made in (\d+) s .*ms each: median ([\d.]+)") PANIC = re.compile(r"(?:^thread '[^']*'(?: \(\d+\))? panicked at|^Leonida: panic on thread)") FAULT = re.compile(r"^Leonida: unhandled exception (0x[0-9a-fA-F]+) at (\S+)(.*)$") ACCESS = re.compile(r"\((read|write|execute)\w* (0x[0-9a-fA-F]+)") # The memory line and the video memory line (diagnostics builds, every 5 s with the frame line). MEMORY = re.compile(r"^memory: (\d+) MB private \((\d+) MB of it in memory; the PC has (\d+) MB free and (\d+) MB " r"left to commit\)") VIDEO = re.compile(r"^video memory as the system counts it, [^:]*: the card's own: budget (\d+) MB, in use (\d+) MB, " r".*?; the PC's shared with the card: budget (\d+) MB, in use (\d+) MB") # The census line with them: objects let go that wait for their submissions, and those handed to the reaper thread # and not let go yet (the reaper's queue, the number a pile-up shows first). WAITS = re.compile(r"^memory, what waits to be let go: (\d+) objects let go that wait for the submissions that may use " r"them \(LEONIDA_BURY_LAG\), (\d+) retired objects, landed host lists and lists' fronts handed to the " r"thread that lets them go") SERIES = "memory.csv" SERIES_COLUMNS = ("t_s", "private_mb", "in_memory_mb", "pc_free_mb", "pc_commit_left_mb", "vram_budget_mb", "vram_in_use_mb", "shared_in_use_mb", "waiting_objects", "reaper_queue") # The runtime's own words this parser reads, and where they are written: tests/test_game_gate.py checks that # each is still there, so a reworded line fails the test, not the next gate. SOURCES = { "draws/frame, dropped": "d3d12/crates/leonida-gpu/src/host.rs", "without a host pipeline ({making} being made)": "d3d12/crates/leonida-gpu/src/host.rs", '"present"': "d3d12/crates/leonida-gpu/src/host.rs", "a pipeline not made within its wait": "d3d12/crates/leonida-gpu/src/pipeline/make.rs", ": suspending the title": "d3d12/crates/leonida-hle/src/modules/lifecycle.rs", "; ending the title": "d3d12/crates/leonida-hle/src/modules/lifecycle.rs", "title did not finish suspending in time": "d3d12/crates/leonida-hle/src/modules/lifecycle.rs", '"relaunched"': "d3d12/crates/leonida-hle/src/modules/lifecycle.rs", "host GPU failure: ": "d3d12/crates/leonida-gpu/src/host.rs", "host command list did not close": "d3d12/crates/leonida-gpu/src/host.rs", "Leonida: panic on thread": "d3d12/crates/leonida-loader/src/crash.rs", "Leonida: {what} {:#010x} at {}{detail}": "d3d12/crates/leonida-loader/src/crash.rs", "unhandled exception": "d3d12/crates/leonida-loader/src/crash.rs", "shaders in the cache, {} do not translate, {:.0} s": "d3d12/apps/leonida/src/translate.rs", "pipelines known, {} made before ({mark}), {} bad; {} to make": "d3d12/apps/leonida/src/warm.rs", "made in {:.0} s (": "d3d12/apps/leonida/src/warm.rs", "memory: {:.0} MB private ({:.0} MB of it in memory; the PC has {:.0} MB free and {:.0} MB": "d3d12/crates/leonida-gpu/src/copystat.rs", "left to commit); host copies": "d3d12/crates/leonida-gpu/src/copystat.rs", "video memory as the system counts it, {}: the card's own: budget {} MB, in use {} MB": "d3d12/crates/leonida-gpu/src/host.rs", "the PC's shared with the card: budget {} MB, in use {} MB": "d3d12/crates/leonida-gpu/src/host.rs", 'h.log_video_memory("with the memory line")': "d3d12/crates/leonida-gpu/src/copystat.rs", # One key over the whole part WAITS reads, the ", " between its two numbers too. "memory, what waits to be let go: {waiting} objects let go that wait for the submissions that may use them " "(LEONIDA_BURY_LAG), {handed} retired objects, landed host lists and lists' fronts handed to the thread that " "lets them go": "d3d12/crates/leonida-gpu/src/census.rs", "crate::census::log();": "d3d12/crates/leonida-gpu/src/copystat.rs", } def when(text): """Seconds since the epoch of an ISO 8601 UTC time ('...Z', any number of fraction digits).""" m = re.match(r"(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.(\d+))?", text) if not m: raise ValueError(f"not a time: {text!r}") y, mo, d, h, mi, s, frac = m.groups() base = dt.datetime(int(y), int(mo), int(d), int(h), int(mi), int(s), tzinfo=dt.timezone.utc).timestamp() return base + (float("0." + frac) if frac else 0.0) def read_lines(path): if not os.path.exists(path): return [] with open(path, encoding="utf-8", errors="replace") as f: return [ANSI.sub("", line.rstrip("\r\n")) for line in f] def percentile(values, p): """Nearest rank, as the runtime's frame-time statistics do.""" ordered = sorted(values) if not ordered: return None rank = max(1, -(-p * len(ordered) // 100)) return ordered[min(rank, len(ordered)) - 1] class Run: """Everything one run folder says, in seconds since the run started.""" def __init__(self, folder): self.folder = folder with open(os.path.join(folder, "run.json"), encoding="utf-8-sig") as f: self.meta = json.load(f) self.start = when(self.meta["started_utc"]) self.events = [] for line in read_lines(os.path.join(folder, "events.jsonl")): if line.strip(): e = json.loads(line) e["t_s"] = when(e["t"]) - self.start self.events.append(e) self.frames = [] # (t, fps, draws, dropped, making) self.presents = [] # t of each present (diagnostics builds, frame debug lines) self.missed = [] # t of each pipeline not made within its wait self.memory = [] # (t, private MB, in memory MB, PC free MB, PC left to commit MB) self.video = [] # (t, card budget MB, card in use MB, shared budget MB, shared in use MB) self.waits = [] # (t, objects waiting for their submissions, the reaper's queue) self.settings = None # from the runtime's settings line self.suspend = None self.ended_at = None self.relaunched = False self.crashes = [] # dicts: kind, at_s, ... self.last_at = None self.read_log(read_lines(os.path.join(folder, "leonida.log"))) for path in sorted(glob.glob(os.path.join(folder, "data", "*", "crashes.log"))): self.read_crashes(read_lines(path)) self.precompile = read_precompile(read_lines(os.path.join(folder, "launcher.txt"))) def read_log(self, lines): for line in lines: m = LINE.match(line) if not m: # Lines with no time (panics, the host GPU failure) belong to the last time seen. self.read_crash_line(line, self.last_at) continue t = when(m.group(1)) - self.start self.last_at = t target, text = m.group(3), m.group(4) if target == "leonida_gpu::frame" and text.startswith("present"): self.presents.append(t) continue f = FRAME.search(text) if f: self.frames.append((t, float(f.group(1)), float(f.group(3)), float(f.group(4)), int(f.group(5)))) elif text.startswith("memory: ") and MEMORY.match(text): self.memory.append((t,) + tuple(int(x) for x in MEMORY.match(text).groups())) elif text.startswith("video memory as the system counts it") and VIDEO.match(text): self.video.append((t,) + tuple(int(x) for x in VIDEO.match(text).groups())) elif text.startswith("memory, what waits to be let go") and WAITS.match(text): self.waits.append((t,) + tuple(int(x) for x in WAITS.match(text).groups())) elif text.startswith("a pipeline not made within its wait"): self.missed.append(t) elif target == "settings": self.settings = parse_settings(text) elif text.endswith("; ending the title"): self.ended_at = t self.suspend = "late" if text.startswith("title did not finish suspending in time") else "suspended" elif text.startswith("relaunched"): self.relaunched = True self.read_crash_line(text, t) def read_crash_line(self, text, t): if "host GPU failure" in text: self.crashes.append({"kind": "device_lost", "at_s": t}) elif "host command list did not close" in text and ("8007000E" in text.upper() or "E_OUTOFMEMORY" in text.upper()): self.crashes.append({"kind": "device_lost", "at_s": t}) elif PANIC.search(text): self.crashes.append({"kind": "panic", "at_s": t}) else: m = FAULT.match(text) if m: access = ACCESS.search(m.group(3)) module = m.group(2).split("+")[0] self.crashes.append({ "kind": "fault", "at_s": t, "code_hex": m.group(1).lower(), "module": module_class(module), "access": access.group(1) if access else None, "null_address": bool(access) and int(access.group(2), 16) == 0, }) def read_crashes(self, lines): # crashes.log entries carry no time this parser trusts: they count from the end of the log. for line in lines: self.read_crash_line(line.strip(), self.last_at) def event(self, name): return next((e for e in self.events if e.get("event") == name), None) def world_at(self): run = 0 for i, (t, _fps, draws, _dropped, _making) in enumerate(self.frames): run = run + 1 if draws >= WORLD_DRAWS else 0 if run == WORLD_LINES: return self.frames[i - WORLD_LINES + 1][0] return None def warm_at(self, world): """The first time in the world from which WARM_QUIET_S passed with nothing being made or waited for in vain.""" if world is None: return None quiet_from = None for t, _fps, _draws, dropped, making in self.frames: if t < world: continue busy = making > 0 or any(quiet_from is not None and quiet_from <= m <= t for m in self.missed) if busy: quiet_from = None continue if quiet_from is None: quiet_from = t elif t - quiet_from >= WARM_QUIET_S: return quiet_from return None def stop_at(self): e = self.event("stop_requested") return e["t_s"] if e else None def parse_settings(text): """{name: value} from the runtime's settings line (values it hid stay hidden).""" if "LEONIDA_ settings:" not in text: return {} body = text.split("LEONIDA_ settings:", 1)[1] out = {} for m in re.finditer(r"(LEONIDA_[A-Z0-9_]+)=(|\S+)", body): out[m.group(1)] = m.group(2) return out def module_class(module): """Which kind of code a fault was in, not its name or address.""" name = module.lower() if name.startswith("leonida"): return "runtime" if name.startswith("game_") or name.endswith("master.exe"): return "title" if name.startswith("nv") or name.startswith("amd") or name.startswith("igd"): return "driver" if name.endswith(".dll"): return "system" return "unknown" def read_precompile(lines): out = {"shaders": None, "untranslatable": None, "shaders_s": None, "pipelines_known": None, "made_before": None, "bad": None, "to_make": None, "made": None, "made_s": None, "made_median_ms": None} for line in lines: line = line.strip() m = SHADERS.match(line) if m: out["shaders"], out["shaders_s"] = int(m.group(1)), int(m.group(3)) out["untranslatable"] = int(m.group(2)) if m.group(2) else None continue m = KNOWN.match(line) if m: out["pipelines_known"], out["made_before"], out["bad"], out["to_make"] = map(int, m.groups()) continue m = MADE.match(line) if m: out["made"], out["made_s"], out["made_median_ms"] = int(m.group(1)), int(m.group(2)), float(m.group(3)) return out def since_end(rows, low): """Seconds the last rows have all been `low`, from the first of them to the last row (0.0 if the last is not).""" first = None for row in reversed(rows): if not low(row): break first = row[0] return rows[-1][0] - first if first is not None else 0.0 def memory_alarm(run): """Why scripts/game-gate.ps1 must stop the run for memory now, or None, from the latest memory lines and the limits it wrote in run.json (`memory_stop`; 0 or less turns one off).""" limits = run.meta.get("memory_stop") or {} private_max = limits.get("private_max_mb") or 0 left_min = limits.get("commit_left_min_mb") or 0 over_s = limits.get("over_budget_s") or 0 if run.memory: private = run.memory[-1][1] if private_max > 0 and private > private_max: return f"private bytes {private} MB, over {private_max} MB" low = since_end(run.memory, lambda m: m[4] < left_min) if left_min > 0 else 0.0 if low >= COMMIT_LOW_S: return f"the PC had under {left_min} MB left to commit for {low:.0f} s" if over_s > 0 and run.video: over = since_end(run.video, lambda v: v[2] > v[1]) if over >= over_s: return f"video memory over its budget for {over:.0f} s" return None def state(run): world = run.world_at() last = run.last_at return { "world_at_s": world, "world_s": (last - world) if world is not None and last is not None else 0.0, "warm_at_s": run.warm_at(world), "last_line_s": last, "frame_lines": len(run.frames), "relaunched": run.relaunched, "device_lost": any(c["kind"] == "device_lost" for c in run.crashes), "memory_stop": memory_alarm(run), } def fps_block(run, world, end): """Frame statistics over the world from AFTER_WORLD_S on, to `end`.""" out = {"source": None, "basis": f"world+{AFTER_WORLD_S:.0f}s", "frames": 0, "median": None, "p5": None, "frame_p95_ms": None, "end_median": None, "under_2_at_s": None, "longest_present_gap_s": None, "longest_gap_at_s": None, "draws_median": None} if world is None or end is None: return out begin = world + AFTER_WORLD_S draws = [d for t, _f, d, _x, _m in run.frames if begin <= t < end] out["draws_median"] = statistics.median(draws) if draws else None shown = [t for t in run.presents if world <= t <= end] if len(shown) >= 2: out["source"] = "presents" gaps = [(b - a, a) for a, b in zip(shown, shown[1:])] tail = end - shown[-1] gaps.append((tail, shown[-1])) longest = max(gaps) out["longest_present_gap_s"], out["longest_gap_at_s"] = round(longest[0], 3), round(longest[1], 3) counted = [(b - a) * 1000.0 for a, b in zip(shown, shown[1:]) if a >= begin] if counted: out["frames"] = len(counted) out["median"] = round(1000.0 / statistics.median(counted), 2) out["p5"] = round(1000.0 / percentile(counted, 95), 2) out["frame_p95_ms"] = round(percentile(counted, 95), 2) tail_frames = [(b - a) * 1000.0 for a, b in zip(shown, shown[1:]) if a >= end - END_WINDOW_S] if tail_frames: out["end_median"] = round(1000.0 / statistics.median(tail_frames), 2) per_second = {} for t in shown: per_second[int(t)] = per_second.get(int(t), 0) + 1 # From 60 s in the world on, like the median: the arrival's streaming dip is not the run's rate. second = int(begin) while second + 1 <= end: if per_second.get(second, 0) < 2: out["under_2_at_s"] = float(second) break second += 1 else: rates = [f for t, f, _d, _x, _m in run.frames if begin <= t < end] if rates: out["source"] = "frame_lines" out["frames"] = len(rates) out["median"] = round(statistics.median(rates), 2) out["p5"] = round(percentile(rates, 5), 2) tail_rates = [f for t, f, _d, _x, _m in run.frames if end - END_WINDOW_S <= t < end] out["end_median"] = round(statistics.median(tail_rates), 2) if tail_rates else None return out def slope_per_min(points): """Least-squares slope of (t in s, value) points, per minute; None under 3 points or with no time spread.""" if len(points) < 3: return None mt = sum(t for t, _ in points) / len(points) mv = sum(v for _, v in points) / len(points) spread = sum((t - mt) ** 2 for t, _ in points) if spread == 0: return None return 60.0 * sum((t - mt) * (v - mv) for t, v in points) / spread def near(rows, t, within=2.0): """The row of `rows` (sorted by time) nearest to t, if within `within` seconds.""" best = min(rows, key=lambda r: abs(r[0] - t), default=None) return best if best is not None and abs(best[0] - t) <= within else None def memory_rows(run): """One row per memory line, with the video memory and census lines written with it (`memory.csv`).""" rows = [] for t, private, in_memory, free, left in run.memory: v = near(run.video, t) w = near(run.waits, t) rows.append({"t_s": round(t, 3), "private_mb": private, "in_memory_mb": in_memory, "pc_free_mb": free, "pc_commit_left_mb": left, "vram_budget_mb": v[1] if v else None, "vram_in_use_mb": v[2] if v else None, "shared_in_use_mb": v[4] if v else None, "waiting_objects": w[1] if w else None, "reaper_queue": w[2] if w else None}) return rows def write_series(run, folder): """Writes memory.csv beside summary.json when the run has memory lines; returns its name or None. Without them it removes a memory.csv already there (a folder summarized again), so no old rows sit beside `series: null`. A file it cannot write or remove (open in another program) is said on stderr: the summary is written anyway.""" path = os.path.join(folder, SERIES) rows = memory_rows(run) try: if not rows: if os.path.exists(path): os.remove(path) return None with open(path, "w", encoding="utf-8", newline="") as f: out = csv.DictWriter(f, fieldnames=SERIES_COLUMNS, lineterminator="\n") out.writeheader() out.writerows(rows) except OSError as e: print(f"{SERIES} not written or removed: {e.__class__.__name__}: {e.strerror or e}", file=sys.stderr) return None return SERIES def memory_block(run, world=None, end=None): """Peaks of the runtime's memory lines over the whole run (none from a build without diagnostics), the reaper's queue at its longest, and how fast the private bytes grew in the world up to `end` (a pile-up's slope; the lines written while the title ends after the stop request do not count).""" out = {"source": None, "lines": 0, "private_max_mb": None, "private_max_at_s": None, "in_memory_max_mb": None, "pc_commit_left_min_mb": None, "pc_commit_left_min_at_s": None, "vram_in_use_max_mb": None, "vram_max_at_s": None, "vram_budget_at_max_mb": None, "vram_over_budget_s": None, "shared_in_use_max_mb": None, "reaper_queue_max": None, "reaper_queue_max_at_s": None, "waiting_objects_max": None, "private_mb_per_min_in_world": None, "series": None} if run.waits: t, queue = max(((w[0], w[2]) for w in run.waits), key=lambda x: x[1]) out["reaper_queue_max"], out["reaper_queue_max_at_s"] = queue, round(t, 3) out["waiting_objects_max"] = max(w[1] for w in run.waits) if run.memory and world is not None: slope = slope_per_min([(m[0], m[1]) for m in run.memory if world <= m[0] and (end is None or m[0] <= end)]) out["private_mb_per_min_in_world"] = round(slope, 1) if slope is not None else None if run.memory: out["series"] = SERIES out["source"], out["lines"] = "memory lines", len(run.memory) t, private = max(((t, p) for t, p, *_ in run.memory), key=lambda x: x[1]) out["private_max_mb"], out["private_max_at_s"] = private, round(t, 3) out["in_memory_max_mb"] = max(m[2] for m in run.memory) t, left = min(((m[0], m[4]) for m in run.memory), key=lambda x: x[1]) out["pc_commit_left_min_mb"], out["pc_commit_left_min_at_s"] = left, round(t, 3) if run.video: t, budget, used = max(((v[0], v[1], v[2]) for v in run.video), key=lambda x: x[2]) out["vram_in_use_max_mb"], out["vram_max_at_s"], out["vram_budget_at_max_mb"] = used, round(t, 3), budget # Time over the card's budget: each line counts until the next one. over = sum(b[0] - a[0] for a, b in zip(run.video, run.video[1:]) if a[2] > a[1]) out["vram_over_budget_s"] = round(over, 1) out["shared_in_use_max_mb"] = max(v[4] for v in run.video) return out def summary(run): world = run.world_at() stop = run.stop_at() end = stop if stop is not None else run.last_at exited = run.event("game_exited") killed = run.event("killed") is not None min_world = float(run.meta.get("world_seconds", 300)) reason = (run.event("stop_requested") or {}).get("reason") world_s = (end - world) if world is not None and end is not None else 0.0 fps = fps_block(run, world, end) code = exited.get("exit_code") if exited else None if code is not None and code & 0xFFFFFFFF == DEVICE_LOST: run.crashes.append({"kind": "device_lost", "at_s": exited["t_s"]}) before = [c for c in run.crashes if stop is None or c["at_s"] is None or c["at_s"] <= stop] after = [c for c in run.crashes if c not in before] for c in run.crashes: frozen = [t for t, *_ in run.frames if c["at_s"] is not None and t <= c["at_s"]] c["title_watchdog"] = (c["kind"] == "fault" and c.get("module") == "title" and c.get("access") == "write" and c.get("null_address") and bool(frozen) and c["at_s"] - frozen[-1] >= 25.0) kinds = [c["kind"] for c in run.crashes] crash_kind = next((k for k in ("device_lost", "panic", "fault") if k in kinds), "none") first = next((c for c in run.crashes if c["kind"] == crash_kind), None) exited_before_stop = exited is not None and (stop is None or exited["t_s"] < stop) and not run.relaunched last_frame = max((t for t, *_ in run.frames if stop is None or t <= stop), default=None) alive = stop is not None and not exited_before_stop and last_frame is not None and stop - last_frame <= ALIVE_S fails, errors, warnings = [], [], [] if "device_lost" in kinds: fails.append("device_lost") if "panic" in kinds: fails.append("panic") if any(c["kind"] == "fault" for c in before): fails.append("fault_before_stop") if exited_before_stop and not run.crashes: fails.append("exited_before_stop") if fps["longest_present_gap_s"] is not None and fps["longest_present_gap_s"] > GAP_FAIL_S: fails.append("present_gap") if reason == "memory": # Stopped before memory ran out: the run was on its way to a crash, not short by choice. fails.append("memory_stop") if run.relaunched: errors.append("relaunched") if run.event("game") is None and not run.frames: errors.append("not_started") elif world is None and reason != "memory": (errors if not exited_before_stop else fails).append("world_not_reached") elif world_s < min_world and reason != "memory": (errors if reason == "stop_file" else fails).append("stopped_early" if reason == "stop_file" else "world_time_short") if stop is not None and not alive and not fails and not errors: fails.append("not_alive_at_stop") if any(c["kind"] == "fault" for c in after): warnings.append("fault_after_stop") if killed: warnings.append("killed") if stop is not None and run.ended_at is None: warnings.append("cache_not_saved") if run.suspend == "late": warnings.append("suspend_late") if fps["source"] == "frame_lines": warnings.append("no_present_lines") if run.settings is None: warnings.append("no_settings_line") if run.meta.get("f1_settings_file"): warnings.append("f1_settings_file") result = "FAIL" if fails else "ERROR" if errors else "PASS" return { "schema": SCHEMA, "run": {key: run.meta.get(key) for key in ("name", "started_utc", "commit", "dirty", "untracked", "exe_sha16", "built_with", "gpu", "driver", "play_args", "world_seconds", "max_minutes")}, "settings": run.settings or {}, "precompile": run.precompile, "times": { "world_at_s": round(world, 3) if world is not None else None, "warm_at_s": round(run.warm_at(world), 3) if run.warm_at(world) is not None else None, "stop_at_s": round(stop, 3) if stop is not None else None, "world_s": round(world_s, 3), "exit_at_s": round(exited["t_s"], 3) if exited else None, }, "fps": fps, "pipelines": {"missed_waits": len(run.missed), "making_max": max((m for *_, m in run.frames), default=0)}, "memory": dict(memory_block(run, world, end), stop_limits=run.meta.get("memory_stop")), "crash": { "kind": crash_kind, "at_s": round(first["at_s"], 3) if first and first["at_s"] is not None else None, "code_hex": first.get("code_hex") if first else None, "module": first.get("module") if first else None, "access": first.get("access") if first else None, "title_watchdog": bool(first and first.get("title_watchdog")), "count": len(run.crashes), }, "exit": {"code_hex": f"0x{code & 0xFFFFFFFF:08X}" if code is not None else None, "kind": ("device_lost" if code is not None and code & 0xFFFFFFFF == DEVICE_LOST else "killed" if killed else "clean" if code == 0 else "other" if code is not None else None)}, "stop": {"reason": reason, "killed": killed, "cache_saved": run.ended_at is not None if stop is not None else None, "suspend": run.suspend, "memory_why": (run.event("stop_requested") or {}).get("why")}, "relaunched": run.relaunched, "verdict": {"result": result, "reasons": fails + errors, "warnings": warnings, "min_world_s": min_world}, } def main(argv): if len(argv) != 3 or argv[1] not in ("state", "summary"): print(__doc__.strip(), file=sys.stderr) return 2 run = Run(argv[2]) if argv[1] == "state": print(json.dumps(state(run))) return 0 out = summary(run) # `series` names the file only when it was written. out["memory"]["series"] = write_series(run, argv[2]) with open(os.path.join(argv[2], "summary.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, indent=2) f.write("\n") v = out["verdict"] print(f"{v['result']}: {out['times']['world_s']:.0f} s in the world" + (f"; {', '.join(v['reasons'])}" if v["reasons"] else "") + (f" (warnings: {', '.join(v['warnings'])})" if v["warnings"] else "")) return {"PASS": 0, "FAIL": 1}.get(v["result"], 2) if __name__ == "__main__": try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode sys.stdout.reconfigure(errors="replace") except (AttributeError, ValueError, OSError): pass sys.exit(main(sys.argv))