Files
alex 7f00e9c777 Statistics: the launcher reads the engine's real session summaries
The engine's summary now says which game it was (SUMMIT_GAME, which summit
run/enhance already set) and ended_unix. The reader takes duration_s, fps_avg,
the engine's low1_fps/low01_fps (as 1% / 0.1% low), its ISO "ended" for older
files, and shows the config words (model, multiplier...) instead of the 80
settings. Tested against a real benchmark summary written by the engine on
the GPU VM (checked in as a fixture) and stats' own older real summary.
2026-11-26 05:35:10 +00:00

375 lines
17 KiB
Python

"""Summit's statistics (framegen/stats.py): the percentile and window maths, the collector, the overlay's cells and the
session summary. Everything runs on made-up frame times: no GPU, no window."""
import json
import pathlib
import sys
import types
import numpy as np
import pytest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from framegen import stats as S
def feed(c: S.Collector, ms_list, t0: float = 100.0, gen_every: int = 2):
"""Presents frames `ms` apart; every `gen_every`th is generated."""
t = t0
c.present(t, False)
for i, ms in enumerate(ms_list, 1):
t += ms / 1000.0
c.present(t, i % gen_every == 0)
return t
# ---- the maths ----------------------------------------------------------------------------------------------------
def test_low_fps_is_the_mean_of_the_worst_frames():
ms = [10.0] * 98 + [50.0, 30.0] # 100 frames: the worst 1% is one frame (50 ms)
assert S.low_fps(ms, 0.01) == pytest.approx(1000 / 50)
assert S.low_fps(ms, 0.02) == pytest.approx(1000 / 40) # worst 2: 50 and 30 -> mean 40
assert S.low_fps(ms, 0.05) == pytest.approx(1000 / ((50 + 30 + 3 * 10) / 5))
assert S.low_fps([16.0, 17.0], 0.5) == pytest.approx(1000 / 17) # at least one frame, rounded up
assert S.low_fps([], 0.01) is None
def test_lows_need_enough_frames():
assert S.lows([10.0] * 99) == (None, None)
one, tenth = S.lows([10.0] * 100)
assert one == pytest.approx(100.0) and tenth is None
ms = np.full(1000, 8.0)
ms[0] = 80.0
one, tenth = S.lows(ms)
assert tenth == pytest.approx(1000 / 80) # the worst 0.1% of 1000 is one frame
assert one == pytest.approx(1000 / ((80 + 9 * 8) / 10)) # the worst 1%: ten frames
def test_percentile_matches_numpy_and_jitter_is_mean_step():
v = list(range(1, 101))
assert S.percentile(v, 95) == pytest.approx(np.percentile(v, 95))
assert S.percentile([], 95) is None
assert S.jitter_ms([10, 10, 10]) == 0.0
assert S.jitter_ms([10, 14, 10, 14]) == pytest.approx(4.0)
assert S.jitter_ms([10]) is None
def test_window_drops_what_is_older_than_its_span():
w = S.Window(5.0)
for t in range(10):
w.add(float(t), t * 2.0)
assert list(w.values()) == [8.0, 10.0, 12.0, 14.0, 16.0, 18.0] # t = 4..9: the last 5 s, ends included
assert len(w) == 6
assert list(w.values(now=20.0)) == [] # nothing left by then
assert S.window_fps([0.0, 0.1, 0.2, 0.3, 0.4], 0.4) == pytest.approx(10.0)
assert S.window_fps([0.0], 0.0) is None
# ---- the collector ----------------------------------------------------------------------------------------------------
def test_fps_frametime_and_share_from_even_frames():
c = S.Collector(window_s=30)
c.set_target(120)
t = feed(c, [1000 / 120] * 240)
snap = c.snapshot(t)
assert snap["fps"] == pytest.approx(120.0, abs=0.5)
assert snap["ft_avg"] == pytest.approx(1000 / 120, rel=1e-3)
assert snap["jitter"] == pytest.approx(0.0, abs=1e-3)
assert snap["share"] == pytest.approx(50.0, abs=1)
assert snap["late"] == 0 and snap["frames_window"] == 240
assert snap["low1"] == pytest.approx(120.0, rel=1e-3) and snap["low01"] is None # 240 frames: no 0.1% low yet
def test_a_stutter_shows_in_the_lows_worst_jitter_and_late_count():
c = S.Collector()
c.set_target(60)
ms = [16.667] * 199 + [100.0]
t = feed(c, ms)
snap = c.snapshot(t)
assert snap["ft_worst"] == pytest.approx(100.0)
assert snap["late"] == 1 # only the 100 ms frame is more than 1.5 targets
assert snap["low1"] == pytest.approx(1000 / ((100 + 1 * 16.667) / 2), rel=1e-3) # worst 1% of 200 = 2 frames
assert snap["jitter"] == pytest.approx((100 - 16.667) / 199, rel=1e-3) # one step up, at the end
def test_a_long_gap_is_a_pause_not_a_frametime():
c = S.Collector()
c.present(0.0, False)
c.present(0.016, False)
c.present(5.0, False) # a restart, say
c.present(5.016, False)
assert c.stalls == 1 and len(c.t_all) == 2
assert c.snapshot(5.016)["ft_worst"] == pytest.approx(16.0)
def test_the_window_forgets_old_frames():
c = S.Collector(window_s=5.0)
feed(c, [50.0] * 100, t0=0.0) # five seconds of 20 fps
t = feed(c, [10.0] * 600, t0=5.5) # then six of 100 fps
snap = c.snapshot(t)
assert snap["ft_avg"] == pytest.approx(10.0, abs=0.2) and snap["ft_worst"] < 20
assert snap["fps"] == pytest.approx(100.0, abs=1)
def test_dropped_repeated_and_late_are_counted_in_the_window_and_in_total():
c = S.Collector(window_s=10.0)
c.set_target(60)
c.drop(2, 1.0)
c.repeat(1, 2.0)
c.drop(1, 30.0) # (10 s window: the first two are gone by then)
snap = c.snapshot(30.0)
assert snap["dropped"] == 1 and snap["repeated"] == 0
assert c.dropped_total == 3 and c.repeated_total == 1
def test_stage_costs_average_and_worst():
c = S.Collector()
for ms in (4.0, 6.0, 5.0, 9.0):
c.stage("interp", ms, t=1.0)
c.stage("present", 0.5, t=1.0)
c.stage("nonsense", 1.0, t=1.0) # not a stage: ignored
st = c.snapshot(2.0)["stages"]
assert st["interp"]["avg"] == pytest.approx(6.0) and st["interp"]["worst"] == 9.0 and st["interp"]["n"] == 4
assert "upscale" not in st and "nonsense" not in st
def test_delay_comes_from_the_attached_stats():
c = S.Collector()
c.attach(types.SimpleNamespace(real_delay_ms=[20.0, 22.0, 40.0]))
snap = c.snapshot(1.0)
assert snap["delay"] == pytest.approx(22.0) and snap["delay_p95"] == pytest.approx(np.percentile([20, 22, 40], 95))
assert S.Collector().snapshot(1.0)["delay"] is None
def test_gathering_costs_little_and_says_how_much():
c = S.Collector()
t = feed(c, [8.3] * 2000)
snap = c.snapshot(t)
assert 0 < snap["cost_us"] < 200 # a few microseconds a frame (generous: shared CI hosts)
c.snapshot(t)
assert c.snap_ms < 50
assert c.summary()["stats_cost"]["per_frame_us"] == pytest.approx(snap["cost_us"], rel=0.5)
# ---- changes of settings --------------------------------------------------------------------------------------------
def test_a_setting_change_gets_before_and_after_numbers():
c = S.Collector()
c.set_target(60)
t = feed(c, [20.0] * 500, t0=0.0) # 10 s at 50 fps
c.setting_changed("scaler", "Upscaler", "FSR 1", "Off", now=t)
t = feed(c, [10.0] * 1000, t0=t + 0.01) # then 10 s at 100 fps
c.setting_changed("overlay_style", "Stats overlay style", "Minimal", "Bar", now=t) # not a performance setting
s = c.summary(now=t)
assert len(s["changes"]) == 1
ch = s["changes"][0]
assert (ch["key"], ch["from"], ch["to"]) == ("scaler", "FSR 1", "Off")
assert ch["before"]["fps"] == pytest.approx(50.0, abs=0.5)
assert ch["after"]["fps"] == pytest.approx(100.0, abs=1.0)
assert "_t" not in ch
def test_a_dragged_slider_is_one_change_and_a_too_early_summary_has_no_after():
c = S.Collector()
t = feed(c, [10.0] * 300, t0=0.0)
for k, v in enumerate(("1x", "2x", "3x")):
c.setting_changed("hz", "Frame multiplier", "60", v, now=t + 0.1 * k)
assert len(c.changes) == 1 and c.changes[0]["to"] == "3x" and c.changes[0]["from"] == "60"
s = c.summary(now=t + 0.5)
assert s["changes"][0]["after"] == {} # under a second of frames since: nothing to say
# ---- what the overlay shows ---------------------------------------------------------------------------------------
def snap_for(**over):
c = S.Collector()
c.set_target(120)
c.set_config(model="RIFE 4.22", multiplier="4x", hz=120, upscaler="FSR 1", output="2560x1440", source="1920x1080",
frame_generation=True)
t = feed(c, [1000 / 120] * 400)
for st, v in (("capture", 1.0), ("interp", 5.0), ("upscale", 1.2), ("look", 0.2), ("present", 0.7)):
c.stage(st, v, t=t)
c.sampler = types.SimpleNamespace(latest={"cpu": 31.0, "gpu": {"util": 83.0, "power": 210.0, "temp": 71.0, "mem": 5120.0,
"mem_total": 24576.0, "clock": 1900.0}})
c.attach(types.SimpleNamespace(real_delay_ms=[25.0] * 50))
snap = c.snapshot(t, game_fps=30.0)
snap.update(over)
return snap
def test_every_item_makes_cells_and_the_minimal_ones_match_the_old_line():
snap = snap_for()
for item in S.ITEMS:
assert S.cells(snap, item), item
mini = S.all_cells(snap, S.wanted("minimal", lambda k: "auto"), True, True)
assert [c.key for c in mini] == ["fps", "game", "delay"]
assert mini[0].value == "120" and mini[0].unit == "fps" and mini[2].value == "25"
def test_wanted_follows_the_style_and_each_stat_setting():
auto = lambda k: "auto" # noqa: E731
assert S.wanted("minimal", auto) == ["fps", "game", "delay"]
assert "lows" in S.wanted("bar", auto) and "stages" not in S.wanted("bar", auto)
assert set(S.wanted("detailed", auto)) == set(S.ITEMS)
pick = lambda k: {"temp": "on", "game": "off"}.get(k, "auto") # noqa: E731
assert S.wanted("minimal", pick) == ["fps", "delay", "temp"] # in the menu's order, whatever was turned on
def test_colours_follow_the_thresholds():
snap = snap_for()
level = lambda item: S.cells(snap, item)[0].level # noqa: E731
assert level("fps") == "good" and level("temp") == "good" and level("gpu") == "good"
snap["fps"], snap["gpu"]["temp"], snap["gpu"]["util"] = 80.0, 80.0, 99.0 # 120 target: 80 is "tight"
assert level("fps") == "tight" and level("temp") == "tight" and level("gpu") == "bad"
snap["fps"], snap["gpu"]["temp"] = 40.0, 90.0
assert level("fps") == "bad" and level("temp") == "bad"
assert S.cells(snap, "fps", colours=False)[0].level == "" # the setting that turns colours off
assert S.level_of(None, 1, 2) == ""
assert S.level_of(10, 20, 30) == "good" and S.level_of(25, 20, 30) == "tight" and S.level_of(31, 20, 30) == "bad"
assert S.level_of(50, 60, 30, True) == "tight" and S.level_of(70, 60, 30, True) == "good"
def test_unknown_numbers_show_dashes_not_zero():
snap = snap_for(fps=None, ft_avg=None, low1=None, low01=None)
assert S.cells(snap, "fps")[0].value == "--" and S.cells(snap, "frametime")[0].value == "--"
assert [c.value for c in S.cells(snap, "lows")] == ["--", "--"]
snap["gpu"] = None
assert S.cells(snap, "gpu") == [] and S.cells(snap, "vram") == []
def test_configuration_in_words():
cfg = {"model": "RIFE 4.22", "frame_generation": True, "multiplier": "4x", "hz": 120, "upscaler": "RTX VSR",
"quality": "quality 3", "output": "3840x2160", "source": "1920x1080"}
assert S.config_line(cfg) == "RIFE 4.22 · 4x (120 fps) · RTX VSR quality 3 · 3840x2160 from 1920x1080"
rows = dict(S.config_lines(cfg))
assert rows["Frame generation"] == "4x (120 fps out)" and rows["Upscaler"] == "RTX VSR, quality 3"
assert rows["Source size"] == "1920x1080"
assert dict(S.config_lines({"frame_generation": False}))["Frame generation"] == "Off"
# ---- the summary ------------------------------------------------------------------------------------------------------
def test_summary_has_the_numbers_and_a_one_screen_table(tmp_path):
c = S.Collector()
c.set_target(120)
c.set_config(model="RIFE 4.22", frame_generation=True, multiplier="4x", hz=120, upscaler="FSR 1")
c.sampler = types.SimpleNamespace(latest={}, history=[
{"cpu": 20.0, "gpu": {"util": 60.0, "power": 200.0, "temp": 65.0, "mem": 4000.0, "mem_total": 24000.0}},
{"cpu": 40.0, "gpu": {"util": 90.0, "power": 240.0, "temp": 70.0, "mem": 4400.0, "mem_total": 24000.0}}])
for _ in range(300):
c.tick(True)
c.tick(False)
c.attach(types.SimpleNamespace(real_delay_ms=[20.0, 30.0, 25.0]))
feed(c, [1000 / 120] * 600)
for ms in (4.0, 5.0, 6.0):
c.stage("interp", ms)
s = c.summary(reason="the Stop button", settings={"hz": 120})
assert s["fps_avg"] == pytest.approx(120.0, abs=0.1) and s["frames"]["presented"] == 601
assert s["frames"]["generated_share_pct"] == pytest.approx(50.0, abs=0.2)
assert s["frames"]["game_fps_avg"] == pytest.approx(30.0, abs=0.1) # 1 in 2 ticks new, 60 ticks/s
assert s["frametime"]["low1_fps"] == pytest.approx(120.0, abs=0.1) and s["frametime"]["low01_fps"] is None
assert s["stages"]["interp"]["avg_ms"] == pytest.approx(5.0) and s["stages"]["interp"]["worst_ms"] == 6.0
assert s["delay"]["median_ms"] == 25.0 and s["system"]["gpu_util_avg_pct"] == 75.0 and s["system"]["vram_max_mb"] == 4400.0
assert s["config"]["settings"] == {"hz": 120}
table = S.format_table(s)
assert len(table.splitlines()) <= 36 and max(len(x) for x in table.splitlines()) <= 120
assert "Frames per second" in table and "AI frame" in table and "120.0 fps" in table
json_path, txt_path = S.write_summary(s, tmp_path, "t")
assert json.loads(json_path.read_text())["fps_avg"] == s["fps_avg"] and txt_path.read_text().startswith("Summit session")
json.dumps(s) # all plain values
def test_an_empty_session_still_summarises():
s = S.Collector().summary()
assert s["frames"]["presented"] == 0 and s["fps_avg"] is None and s["duration_s"] == 0
assert "Summit session summary" in S.format_table(s)
# ---- the CSV log ---------------------------------------------------------------------------------------------------------
def test_csv_log_has_mangohuds_columns(tmp_path):
c = S.Collector()
c.sampler = types.SimpleNamespace(latest={"cpu": 12.0, "ram": 8.0, "swap": 0.0, "rss": 1.5, "gpu": {
"util": 50.0, "power": 100.0, "temp": 60.0, "mem": 2048.0, "mem_total": 24576.0, "clock": 1800.0}})
c.csv = S.CsvLog(tmp_path / "log.csv", {"os": "Linux", "cpu": "Some, CPU", "kernel": "7.0"})
feed(c, [10.0, 20.0, 10.0])
c.csv.close()
lines = (tmp_path / "log.csv").read_text().splitlines()
assert lines[0] == "os,cpu,gpu,ram,kernel,driver,cpuscheduler" and lines[1].startswith("Linux,Some CPU,")
assert lines[2] == ",".join(S.MANGOHUD_COLUMNS) + ",generated"
first = lines[3].split(",")
assert len(first) == len(S.MANGOHUD_COLUMNS) + 1
assert float(first[0]) == pytest.approx(100.0, abs=0.1) and float(first[1]) == pytest.approx(10.0, abs=0.01)
assert first[3] == "50" and first[8] == "2.00"
assert [float(x.split(",")[1]) for x in lines[3:]] == pytest.approx([10.0, 20.0, 10.0], abs=0.01)
elapsed = [int(x.split(",")[13]) for x in lines[3:]]
assert elapsed == sorted(elapsed) and elapsed[-1] == pytest.approx(40e6, rel=0.01) # ns since the first frame
def test_cpu_load_parses_proc_stat():
a = S.SystemSampler.parse_stat("cpu 100 0 100 800 0 0 0 0 0 0\ncpu0 1 2 3")
b = S.SystemSampler.parse_stat("cpu 200 0 200 1000 0 0 0 0 0 0\n")
assert a == (200, 1000) and b == (400, 1400)
assert 100.0 * (b[0] - a[0]) / (b[1] - a[1]) == pytest.approx(50.0)
assert S.SystemSampler.parse_stat("garbage") is None
def test_a_benchmark_leaves_out_its_warm_up():
c = S.Collector()
stats = types.SimpleNamespace(real_delay_ms=[3000.0, 2500.0]) # the start-up's
c.attach(stats)
c.start_benchmark(10.0)
assert c.bench_left(5.0) == 10.0 # the clock hasn't started
c.present(0.0, False)
c.stage("interp", 3600.0, 0.0)
c.present(3.7, False) # the slow start
c.drop(2, 3.7)
c.present(3.72, False) # third frame: the benchmark proper
stats.real_delay_ms += [20.0, 22.0]
for k in range(1, 100):
c.present(3.72 + k * 0.01, False)
c.stage("interp", 5.0, 3.72 + k * 0.01)
s = c.summary()
assert c.benchmark["start"] == 3.72 and s["frames"]["presented"] == 100
assert s["frames"]["dropped"] == 0 and s["frametime"]["worst_ms"] == pytest.approx(10.0, abs=0.01)
assert s["stages"]["interp"]["worst_ms"] == 5.0 and s["delay"]["max_ms"] == 22.0
assert s["frames"]["stalls"] == 0 and c.bench_left(8.72) == pytest.approx(5.0)
def test_warm_up_frames_are_left_out_of_a_normal_session_too():
c = S.Collector(warmup=S.WARMUP_FRAMES)
c.present(0.0, False)
c.stage("capture", 3500.0, 0.0)
c.present(3.5, False)
c.stage("capture", 2.0, 3.51) # (the backlog is gone)
c.present(3.516, False) # the third: counting starts here
c.present(3.532, False)
assert c.frames == 2 and len(c.t_all) == 1 and c.stage_all["capture"].buffer_info()[1] == 0
assert c.snapshot(3.532)["ft_worst"] == pytest.approx(16.0, abs=0.1)
def test_warm_up_waits_out_a_start_up_backlog_but_not_forever():
c = S.Collector(warmup=3)
t = 0.0
for k in range(40): # frames whose capture wait is still high: not counted yet
c.stage("capture", 500.0, t)
c.present(t, False)
t += 0.01
assert c.frames == 0
c.stage("capture", 5.0, t)
c.present(t, False)
t += 0.01
c.stage("capture", 5.0, t)
c.present(t, False)
assert c.frames == 2 # counting began with the first frame that was no longer waiting
d = S.Collector(warmup=3)
for k in range(40): # a backlog that never clears: counting begins after WARMUP_MAX_S anyway
d.stage("capture", 500.0, k)
d.present(float(k), False)
assert d.frames > 20
def test_the_summary_names_the_game_the_launcher_started(monkeypatch):
"""The launcher's Statistics view finds a game's summaries by "game" (SUMMIT_GAME, set by summit run/enhance)
and sorts them by "ended_unix" (crates/summit-core/src/sessions.rs)."""
c = S.Collector()
feed(c, [1000 / 60] * 120)
monkeypatch.setenv("SUMMIT_GAME", "Voidrunner")
s = c.summary()
assert s["game"] == "Voidrunner" and isinstance(s["ended_unix"], int) and s["ended_unix"] > 1.6e9
monkeypatch.delenv("SUMMIT_GAME")
assert c.summary()["game"] is None