From 016554bef3697bcb705f9ea3360fabeb9a4841b5 Mon Sep 17 00:00:00 2001 From: owenjbendon-creator <281052257+owenjbendon-creator@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:15:08 +0000 Subject: [PATCH] d3d12_run_fps: no argument comes back in an error, frame lines only where the logger wrote them, an unfinished last line skipped (TOOLS-D3D12-RUN-FPS) From the review of 9f7587e19: - An argument error named what was typed: a second log given without --compare came back as "unrecognized arguments: ", and a bad --min-samples value was quoted. Unknown arguments are now counted, not quoted, --min-samples has its own type whose message is fixed text, and options cannot be abbreviated. - A frame line counts only at the start of a line or after the time stamp, level and target of the host's INFO message (leonida_gpu::host, and victory_gpu::host of the forks this runtime came from). The same words inside another message are not read. - A last line the writer did not finish (no line end) is skipped whatever it holds, and the pattern asks for the words that follow the draw count, so a line cut after the count gives no sample. - The text gives the textures' MB and the copy-back's MB too, as the JSON does. Test: python -I tests/test_d3d12_run_fps.py (19 tests). New: a frame line counts only where the logger wrote it; a last line without its end; no error gives back what was typed. Co-Authored-By: Claude Fable 5.2 --- tests/test_d3d12_run_fps.py | 77 ++++++++++++++++++++++++++++++++----- tools/d3d12_run_fps.py | 53 +++++++++++++++++-------- 2 files changed, 105 insertions(+), 25 deletions(-) diff --git a/tests/test_d3d12_run_fps.py b/tests/test_d3d12_run_fps.py index 4c4a931ea..aa8afc547 100644 --- a/tests/test_d3d12_run_fps.py +++ b/tests/test_d3d12_run_fps.py @@ -45,10 +45,10 @@ def frame_line(fps, draws, colour=False, **fields): return f"{STAMP} INFO leonida_gpu::host: {text}" -def write_log(folder, name, lines, encoding="utf-8"): +def write_log(folder, name, lines, encoding="utf-8", end="\n"): path = os.path.join(folder, name) with open(path, "wb") as f: - f.write(("\n".join(lines) + "\n").encode(encoding)) + f.write(("\n".join(lines) + end).encode(encoding)) return path @@ -83,6 +83,39 @@ class ReadSamples(unittest.TestCase): samples = run_fps.read_samples(write_log(tmp, "a.log", lines)) self.assertEqual([(s["fps"], s["draws"]) for s in samples], [(30.0, 12), (18.0, 6000)]) + def test_a_frame_line_counts_only_where_the_logger_wrote_it(self): + text = frame_text(20.0, 4000) + lines = [ + f"{STAMP} INFO leonida_gpu::host: {frame_text(21.0, 4100)}", # the runtime's own message + frame_text(22.0, 4200), # the message alone + f"{STAMP} INFO victory_gpu::host: {frame_text(23.0, 4300)}", # the forks this runtime came from + f"{STAMP} INFO leonida_hle: the title says: {text}", # the same words in another message + f"{STAMP} INFO leonida_gpu::host: before it, {text}", # not at the message's start + f"{STAMP} WARN leonida_gpu::host: {text}", # not the INFO line + f"{STAMP} INFO leonida_gpu::hostile: {text}", # another target + " " + text, # not at the line's start + f"{SECRET} {text}", + ] + with tempfile.TemporaryDirectory() as tmp: + samples = run_fps.read_samples(write_log(tmp, "a.log", lines)) + self.assertEqual([(s["fps"], s["draws"]) for s in samples], [(21.0, 4100), (22.0, 4200), (23.0, 4300)]) + + def test_a_last_line_without_its_end_is_skipped(self): + first, last = frame_line(20.0, 4000), frame_line(15.0, 9000) + after_draws = last[:last.index(" draws/frame") + len(" draws/frame")] # the cut falls after the draw count + with tempfile.TemporaryDirectory() as tmp: + cut = run_fps.read_samples(write_log(tmp, "a.log", [first, after_draws], end="")) + cut_with_end = run_fps.read_samples(write_log(tmp, "b.log", [first, after_draws])) + whole_no_end = run_fps.read_samples(write_log(tmp, "c.log", [first, last], end="")) + whole = run_fps.read_samples(write_log(tmp, "d.log", [first, last])) + wide = run_fps.read_samples(write_log(tmp, "e.log", [first, last], encoding="utf-16", end="")) + only_first = [(20.0, 4000)] + self.assertEqual([(s["fps"], s["draws"]) for s in cut], only_first) + self.assertEqual([(s["fps"], s["draws"]) for s in cut_with_end], only_first) # ends before ", dropped" + self.assertEqual([(s["fps"], s["draws"]) for s in whole_no_end], only_first) # whole, but not finished + self.assertEqual([(s["fps"], s["draws"]) for s in wide], only_first) + self.assertEqual([(s["fps"], s["draws"]) for s in whole], only_first + [(15.0, 9000)]) + def test_a_utf16_log_reads_the_same(self): lines = [frame_line(20.0, 4000), frame_line(10.0, 9500)] with tempfile.TemporaryDirectory() as tmp: @@ -160,10 +193,10 @@ class Summarize(unittest.TestCase): class OneRun(unittest.TestCase): LINES = ( [frame_line(30.0, 13)] - + [frame_line(f, 4000, preparing=30.0, copies_ms=12.0, copies_mb=50.0, textures_ms=2.0, gpu=0.5, back_ms=5.0) - for f in (24.0, 26.0, 28.0)] - + [frame_line(12.0, 9500, preparing=44.0, copies_ms=20.0, copies_mb=80.0, textures_ms=3.0, gpu=1.5, - back_ms=7.0)] + + [frame_line(f, 4000, preparing=30.0, copies_ms=12.0, copies_mb=50.0, textures_ms=2.0, textures_mb=6.0, + gpu=0.5, back_ms=5.0, back_mb=0.7) for f in (24.0, 26.0, 28.0)] + + [frame_line(12.0, 9500, preparing=44.0, copies_ms=20.0, copies_mb=80.0, textures_ms=3.0, textures_mb=9.0, + gpu=1.5, back_ms=7.0, back_mb=1.1)] + [f"{STAMP} INFO leonida_hle: {SECRET}"] ) @@ -174,8 +207,8 @@ class OneRun(unittest.TestCase): self.assertEqual(text, ( "5 frame lines, 4 in the world (1000+ draws a frame)\n" "frame rate: median 25.0 fps, slowest tenth 12.0, fastest tenth 28.0\n" - "a frame (medians): 40.1 ms; preparing 30.0 ms (copies 12.0 ms, 50.0 MB; textures 2.0 ms); waiting on " - "the GPU 0.5 ms; copying back 5.0 ms; 4000 draws\n" + "a frame (medians): 40.1 ms; preparing 30.0 ms (copies 12.0 ms, 50.0 MB; textures 2.0 ms, 6.0 MB); " + "waiting on the GPU 0.5 ms; copying back 5.0 ms, 0.7 MB; 4000 draws\n" "by draws a frame:\n" " 1000-2999 - fps (0 samples)\n" " 3000-4999 26.0 fps (3 samples)\n" @@ -198,6 +231,10 @@ class OneRun(unittest.TestCase): self.assertEqual(data["a"]["fps"], {"median": 26.0, "slowest_tenth": 12.0, "fastest_tenth": 30.0}) self.assertEqual(data["a"]["buckets"], [{"draws": "0-4999", "samples": 4, "median_fps": 27.0}, {"draws": "5000+", "samples": 1, "median_fps": 12.0}]) + # The text gives every median the JSON gives. + self.assertEqual(sorted(data["a"]["medians"]), sorted(f for f in run_fps.FIELDS if f != "fps")) + self.assertIn("textures 2.0 ms, 6.0 MB", text) + self.assertIn("copying back 5.0 ms, 0.7 MB", text) for out in (text, as_json): self.assertNotIn(SECRET, out) self.assertNotIn(tmp, out) @@ -298,9 +335,31 @@ class CommandLine(unittest.TestCase): self.assertIn("ascending", self.fails(log, "--edges=-5,1000")) self.assertIn("whole numbers", self.fails(log, "--edges", "1000,many")) self.assertIn("whole numbers", self.fails(log, "--edges", "")) - self.assertIn("--min-samples must be 1 or more", self.fails(log, "--compare", log, "--min-samples", "0")) + self.assertIn("a whole number, 1 or more", self.fails(log, "--compare", log, "--min-samples", "0")) + self.assertIn("a whole number, 1 or more", self.fails(log, "--compare", log, "--min-samples=-2")) self.assertIn("--min-samples needs --compare", self.fails(log, "--min-samples", "3")) + def test_no_error_gives_back_what_was_typed(self): + with tempfile.TemporaryDirectory() as tmp: + log = write_log(tmp, "a.log", [frame_line(20.0, 4000)]) + other = write_log(tmp, "other.log", [frame_line(21.0, 4000)]) + errors = [ + self.fails(log, other), # the second log without --compare + self.fails(log, other, os.path.join(tmp, "third.log")), + self.fails(log, "--compare", other, "--min-samples", other), + self.fails(log, "--edges", other), + self.fails(log, "--unknown", other), + self.fails(log, "--comp", other), # no abbreviations: not --compare + ] + self.assertIn("1 argument not understood: one log, and a second after --compare", errors[0]) + self.assertIn("2 arguments not understood", errors[1]) + self.assertIn("argument --min-samples: a whole number, 1 or more", errors[2]) + self.assertIn("argument --edges: whole numbers separated by commas", errors[3]) + for err in errors: + self.assertNotIn(tmp, err) + self.assertNotIn("other.log", err) + self.assertNotIn("third.log", err) + if __name__ == "__main__": unittest.main() diff --git a/tools/d3d12_run_fps.py b/tools/d3d12_run_fps.py index bfd0bc2fd..8cf48930d 100644 --- a/tools/d3d12_run_fps.py +++ b/tools/d3d12_run_fps.py @@ -6,7 +6,7 @@ Reads the frame line the D3D12 runtime logs every few seconds (d3d12/crates/leon launchers keep (`play-.log`, d3d12/scripts/play-nvidia.ps1): fps, ms/frame ( preparing: copies ms MB, textures ms MB; on the GPU; - copying back MB), draws/frame, ... + copying back MB), draws/frame, dropped ... and prints, for the samples in the world, how many there are, the frame rate (median, slowest tenth, fastest tenth), the medians of a frame's time, of the time preparing, of the copies and of the time waiting on the GPU, and @@ -19,12 +19,17 @@ changed. `--compare` puts a second run beside the first, bucket by bucket, and g with at least `--min-samples` samples (5 by default) in both runs: the comparison of an A and a B that a game-run test asks for (two `RUN` blocks, docs/agent_collaboration.md). -It never prints a log line, nor the path of a log. The log can quote what the title prints, so it stays on the -machine that made it: share these numbers in issues and pull requests, not the file (AGENTS.md, "No game data"). +It never prints a log line, nor the path of a log, nor an argument it was given: an error names the kind of +mistake only. The log can quote what the title prints, so it stays on the machine that made it: share these numbers +in issues and pull requests, not the file (AGENTS.md, "No game data"). + +A frame line counts only where the runtime's logger wrote it: at the start of a line, or after the time stamp, +level and target of the `leonida_gpu::host` message (`victory_gpu::host` in the forks this runtime came from). The +same words inside another message are not read. A last line the writer did not finish (no line end: the shape a +crash leaves) is skipped. Standard library only; reads files, never runs them. The log may be UTF-8 or UTF-16 with a byte-order mark (what a -PowerShell redirection writes) and may carry terminal colour codes; a truncated last line (the shape a crash -leaves) is skipped. +PowerShell redirection writes) and may carry terminal colour codes. """ from __future__ import annotations @@ -36,13 +41,13 @@ import statistics import sys ANSI = re.compile(r"\x1b\[[0-9;]*m") -# What the runtime's `{:.1}` and `{:.0}` print. The lengths are bounded and the first number must not continue a -# word, a sign or another number, so that no other text in a log reads as a frame line or costs time to refuse. +# What the runtime's `{:.1}` and `{:.0}` print, with bounded lengths. NUMBER = r"(\d{1,12}(?:\.\d{1,3})?)" FRAME_LINE = re.compile( - rf"(? list[dict]: """One dict per frame line of the log, in the order logged.""" samples = [] for line in _lines(path): - m = FRAME_LINE.search(ANSI.sub("", line)) + if not line.endswith("\n"): # the last line, cut short: not a whole frame line whatever it holds + continue + m = FRAME_LINE.match(ANSI.sub("", line)) if m: sample = {name: float(value) for name, value in zip(FIELDS, m.groups())} sample["draws"] = int(m.group(len(FIELDS))) @@ -129,8 +136,9 @@ def render_run(s: dict, label: str = "") -> str: out.append(f"frame rate: median {s['fps']['median']:.1f} fps, slowest tenth {s['fps']['slowest_tenth']:.1f}, " f"fastest tenth {s['fps']['fastest_tenth']:.1f}") out.append(f"a frame (medians): {m['frame_ms']:.1f} ms; preparing {m['preparing_ms']:.1f} ms (copies " - f"{m['copies_ms']:.1f} ms, {m['copies_mb']:.1f} MB; textures {m['textures_ms']:.1f} ms); waiting on " - f"the GPU {m['gpu_wait_ms']:.1f} ms; copying back {m['copy_back_ms']:.1f} ms; {m['draws']:.0f} draws") + f"{m['copies_ms']:.1f} ms, {m['copies_mb']:.1f} MB; textures {m['textures_ms']:.1f} ms, " + f"{m['textures_mb']:.1f} MB); waiting on the GPU {m['gpu_wait_ms']:.1f} ms; copying back " + f"{m['copy_back_ms']:.1f} ms, {m['copy_back_mb']:.1f} MB; {m['draws']:.0f} draws") out.append("by draws a frame:") for b in s["buckets"]: out.append(f" {b['draws']:>11} {_fps(b['median_fps']):>5} fps ({_count(b['samples'], 'sample')})") @@ -148,6 +156,8 @@ def render_compare(c: dict) -> str: return "\n".join(out) + "\n" +# The two argument types say what is wrong without the text given: argparse's own message for a bad `type=int` +# quotes it, and a path typed in the wrong place must not come back in an error. def _edges(text: str) -> tuple[int, ...]: try: edges = tuple(int(part) for part in text.split(",")) @@ -158,8 +168,19 @@ def _edges(text: str) -> tuple[int, ...]: return edges +def _samples(text: str) -> int: + try: + n = int(text) + except ValueError: + n = 0 + if n < 1: + raise argparse.ArgumentTypeError("a whole number, 1 or more") + return n + + def main(argv=None) -> int: parser = argparse.ArgumentParser( + allow_abbrev=False, description="Frame rate of a D3D12-runtime run from the frame lines of its log, overall and by draws a " "frame, so that two runs compare like for like. It never prints a log line: the log can quote " "what the title prints and stays local; share these numbers, not the file.") @@ -168,14 +189,14 @@ def main(argv=None) -> int: parser.add_argument("--edges", type=_edges, default=DEFAULT_EDGES, help="the buckets' lower bounds in draws a frame; samples under the first are left out " "(default 1000,3000,5000,7000,9000)") - parser.add_argument("--min-samples", type=int, + parser.add_argument("--min-samples", type=_samples, help="with --compare, the samples a bucket needs in both runs (default 5)") parser.add_argument("--json", action="store_true", help="print the numbers as JSON") - args = parser.parse_args(argv) + args, unknown = parser.parse_known_args(argv) + if unknown: # argparse would quote them, and one of them may be a path + parser.error(f"{_count(len(unknown), 'argument')} not understood: one log, and a second after --compare") if args.min_samples is not None and not args.compare: parser.error("--min-samples needs --compare") - if args.min_samples is not None and args.min_samples < 1: - parser.error("--min-samples must be 1 or more") runs = [] for which, path in (("the log", args.log), ("the second log", args.compare)): if path is None: