Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions docs/game_gate.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,9 @@ A crash after the stop request is a warning, except a device loss or a panic, wh

## Not in this version

- A driver for the menus and a fixed route (a Lua mod).
- An ABBA runner over several runs.
- A fixed route from a saved place. The driver mod (`mods/gate_driver`, docs/lua-modding.md) gets through the menus
and walks a loop from wherever control comes. The ABBA runner over gate runs is `scripts/game-abba.ps1`
(docs/measuring_fps.md, section 3).
- A time series beside the summary (memory, census, reaping queue).
- A "memory rising" warning.
- VRAM and RAM peaks.
Expand Down
7 changes: 7 additions & 0 deletions docs/measuring_fps.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@ A change of code, or a switch that cannot be turned in play, needs separate runs
reads the runs in that order (logs, or the game gate's run folders with their `summary.json`): one value a run (its
world median frame time), neighbouring pairs, the effect with its standard error and 95 % interval from at least
4 balanced pairs, and "B faster" or "B slower" only when the interval leaves 0 out and all pairs but one agree.
- `scripts/game-abba.ps1` does all of it in game: the gate runs in that order, for one exe with two settings
(`-Data`, `-MoreA`, `-MoreB`) or two builds (`-CheckoutA`, `-DataA`, `-CheckoutB`, `-DataB`: a data folder each, their
caches differ), then `abba` into `<Out>\comparison.txt`. It leaves out a measured run whose gate failed, whose
pipeline cache was not warm before the measured window, whose exe is not its arm's, or whose `-MoreA`/`-MoreB`
settings do not show in the runtime's settings line, and runs that slot again (`-Retry`, 1). `-DryRun` prints the
plan and the gate commands. Set both arms' switch explicitly (`LEONIDA_X=0` against `LEONIDA_X=1`): only what an
arm sets is checked. At 4 pairs and 300 s in the world it is 11 or 12 runs, about an hour.

## 4. Which number means what

Expand Down
130 changes: 130 additions & 0 deletions scripts/game-abba.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
#Requires -Version 7.0
# An ABBA comparison of the D3D12 runtime in game (docs/measuring_fps.md, section 3): gate runs
# (scripts\game-gate.ps1) in a balanced order, then tools\d3d12_ab_compare.py over the measured ones.
#
# One exe, two settings (this checkout's exe, one data folder):
# pwsh -NoProfile -File scripts\game-abba.ps1 -Game <dir> -DataTemplate <dir> -Out <dir> -Data <dir> -MoreA 'LEONIDA_X=0' -MoreB 'LEONIDA_X=1'
# Two builds (each arm runs its own checkout's gate and exe, with a data folder of its own: their caches differ):
# pwsh -NoProfile -File scripts\game-abba.ps1 -Game <dir> -DataTemplate <dir> -Out <dir> -CheckoutA <dir> -DataA <dir> -CheckoutB <dir> -DataB <dir>
#
# The order comes from `d3d12_ab_compare.py plan`: warm-up runs of each arm, discarded runs, then -Pairs pairs in
# ABBA order. Each measured run is checked with `d3d12_ab_compare.py check`: its gate passed, the pipeline cache was
# warm before the measured window, its exe is the one its arm started with, and its arm's own -MoreA/-MoreB settings
# show in the runtime's settings line when the runtime writes one. A run that fails a check gets an ab-excluded.txt
# (the comparison leaves it out) and its slot runs again, -Retry times (1). Runs go to <Out>\runs; <Out> gets
# abba.json (what ran, what was left out and why), comparison.txt and comparison.json.
# Options: -Pairs (4), -WorldSeconds (300), -MaxMinutes (45), -More (both arms), -PlayArgs, -Python, -DryRun (prints
# the plan and every gate command, starts nothing). Two arms at 4 pairs and 300 s are 11 or 12 runs: about an hour.
param(
[string]$Game = '',
[string]$DataTemplate = '',
[string]$Out = '',
[string]$Data = '',
[string]$DataA = '',
[string]$DataB = '',
[string]$CheckoutA = '',
[string]$CheckoutB = '',
[string]$MoreA = '',
[string]$MoreB = '',
[string]$More = '',
[int]$Pairs = 4,
[int]$WorldSeconds = 300,
[int]$MaxMinutes = 45,
[string]$PlayArgs = '',
[int]$Retry = 1,
[string]$Python = '',
[switch]$DryRun
)
$ErrorActionPreference = 'Stop'
$repo = Split-Path -Parent $PSScriptRoot
$compare = Join-Path $repo 'tools\d3d12_ab_compare.py'
if (-not $Python) { $Python = (Get-Command python -ErrorAction Stop).Source }
$pwsh = (Get-Process -Id $PID).Path

foreach ($need in 'Game', 'DataTemplate', 'Out') {
if (-not (Get-Variable $need -ValueOnly)) { throw "-$need is needed" }
}
if (-not $CheckoutA) { $CheckoutA = $repo }
if (-not $CheckoutB) { $CheckoutB = $repo }
$CheckoutA = (Resolve-Path $CheckoutA).Path
$CheckoutB = (Resolve-Path $CheckoutB).Path
$builds = $CheckoutA -ne $CheckoutB
if ($builds) {
if (-not $DataA -or -not $DataB) { throw 'two builds need -DataA and -DataB: their caches differ' }
if ([IO.Path]::GetFullPath($DataA) -eq [IO.Path]::GetFullPath($DataB)) {
throw '-DataA and -DataB are one folder: two builds would share their caches'
}
} else {
if (-not $Data) { throw 'one exe with two settings needs -Data' }
if (-not $MoreA -and -not $MoreB) { throw 'one exe and neither -MoreA nor -MoreB: the arms would be the same' }
$DataA = $Data
$DataB = $Data
}
if ($Pairs -lt 2) { throw '-Pairs is 2 or more (4 for a verdict from pairs)' }
$Out = [IO.Path]::GetFullPath($Out)
foreach ($checkout in $CheckoutA, $CheckoutB) {
if (($Out + '\').StartsWith($checkout + '\', [StringComparison]::OrdinalIgnoreCase)) { throw "-Out is inside a checkout: $Out" }
}
$root = Join-Path $Out 'runs'

$planArgs = @('-I', $compare, 'plan', '--pairs', $Pairs, '--json')
if (-not $builds) { $planArgs += '--switch' }
$order = (& $Python @planArgs | Out-String) | ConvertFrom-Json
if ($LASTEXITCODE) { throw 'd3d12_ab_compare.py plan failed' }
$slots = @($order.warm_up_and_discarded | ForEach-Object { [pscustomobject]@{ Kind = ($_ -split ' ')[0]; Arm = ($_ -split ' ')[-1] } }) +
@($order.measured | ForEach-Object { [pscustomobject]@{ Kind = 'measured'; Arm = $_ } })
"mode: $(if ($builds) { 'two builds' } else { 'one exe, two settings' }); $($slots.Count) runs, $Pairs pairs"

$record = [ordered]@{ schema = 'leonida-abba-run/1'; builds = $builds; pairs = $Pairs; world_seconds = $WorldSeconds; runs = @() }
$exes = @{}
$measured = @()
$index = 0
foreach ($slot in $slots) {
$index++
$own = if ($slot.Arm -eq 'A') { $MoreA } else { $MoreB }
$settings = (@($More, $own) | Where-Object { $_ }) -join ';'
$gate = Join-Path $(if ($slot.Arm -eq 'A') { $CheckoutA } else { $CheckoutB }) 'scripts\game-gate.ps1'
$armData = if ($slot.Arm -eq 'A') { $DataA } else { $DataB }
for ($attempt = 0; $attempt -le $Retry; $attempt++) {
$label = '{0:00}-{1}-{2}' -f $index, $slot.Kind, $slot.Arm
if ($attempt) { $label += "-retry$attempt" }
$dir = Join-Path $root $label
$gateArgs = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $gate, 'run', '-Game', $Game, '-Data', $armData,
'-DataTemplate', $DataTemplate, '-Name', $label, '-RunRoot', $root, '-RunDir', $dir, '-WorldSeconds', $WorldSeconds,
'-MaxMinutes', $MaxMinutes, '-More', $settings, '-PlayArgs', $PlayArgs, '-Python', $Python)
if ($DryRun) {
"$index $($slot.Kind) $($slot.Arm): $gate run -Name $label -Data $armData -More '$settings'"
if ($slot.Kind -eq 'measured') { $measured += "$($slot.Arm):$dir" }
break
}
"run $index/$($slots.Count) $($slot.Kind) $($slot.Arm)$(if ($attempt) { ", again" })..."
& $pwsh @gateArgs | Out-Host
$runFile = Join-Path $dir 'run.json'
if (-not (Test-Path $runFile)) { throw "the gate did not start $label (exit $LASTEXITCODE)" }
$exe = (Get-Content $runFile -Raw | ConvertFrom-Json).exe_sha16
if (-not $exes.ContainsKey($slot.Arm)) { $exes[$slot.Arm] = $exe }
$checkArgs = @('-I', $compare, 'check', $dir, '--exe', $exes[$slot.Arm])
foreach ($item in ($own -split ';' | ForEach-Object { $_.Trim() } | Where-Object { $_ })) { $checkArgs += @('--setting', $item) }
$seen = (& $Python @checkArgs | Out-String) | ConvertFrom-Json
$why = if ($slot.Kind -eq 'measured') { $seen.excluded } else { $null }
$record.runs += [ordered]@{ position = $index; kind = $slot.Kind; arm = $slot.Arm; folder = $label; exe = $exe; left_out = $why }
if ($why) {
Set-Content (Join-Path $dir 'ab-excluded.txt') $why -Encoding utf8
" left out: $why"
if ($attempt -lt $Retry) { continue }
}
if ($slot.Kind -eq 'measured') { $measured += "$($slot.Arm):$dir" }
break
}
}

if ($DryRun) {
"then: $Python -I $compare abba $($measured -join ' ')"
exit 0
}
New-Item -ItemType Directory -Force $Out | Out-Null
$record | ConvertTo-Json -Depth 5 | Set-Content (Join-Path $Out 'abba.json') -Encoding utf8
$text = & $Python -I $compare abba @measured | Out-String
& $Python -I $compare abba @measured --json | Out-String | Set-Content (Join-Path $Out 'comparison.json') -Encoding utf8
Set-Content (Join-Path $Out 'comparison.txt') $text -Encoding utf8
$text
41 changes: 41 additions & 0 deletions tests/test_d3d12_ab_compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,47 @@ def test_a_gate_folder_gives_its_world_median_and_a_failed_gate_is_left_out(self
self.assertAlmostEqual(ab.run_value(self.gate("ok", 25.0))[0], 40.0)
self.assertEqual(ab.run_value(self.gate("bad", 25.0, "FAIL"))[2], "gate FAIL")

def summary_run(self, name, result="PASS", warm=80.0, exe="1" * 16, settings=None):
"""A gate run folder with its world at 80 s."""
d = os.path.join(self.dir, name)
os.makedirs(d)
with open(os.path.join(d, "summary.json"), "w", encoding="utf-8") as f:
json.dump({"run": {"exe_sha16": exe}, "verdict": {"result": result}, "settings": settings or {},
"times": {"world_at_s": 80.0, "warm_at_s": warm}, "fps": {"median": 25.0}}, f)
return d

def test_check_keeps_a_good_run_and_gives_its_exe(self):
d = self.summary_run("ok", settings={"LEONIDA_X": "1", "LEONIDA_P": "<hidden, 9 chars>"})
self.assertEqual(ab.check_run(d, exe="1" * 16, settings=("LEONIDA_X=1", "LEONIDA_P=F:\\x")), (None, "1" * 16))

def test_check_leaves_out_what_does_not_measure_the_arm(self):
why = {
"gate FAIL": ab.check_run(self.summary_run("fail", result="FAIL")),
"the pipeline cache was never warm": ab.check_run(self.summary_run("cold", warm=None)),
"pipelines were made in the measured window": ab.check_run(self.summary_run("late", warm=150.0)),
"another exe than its arm's first run": ab.check_run(self.summary_run("exe", exe="2" * 16), exe="1" * 16),
"LEONIDA_X shows another value": ab.check_run(self.summary_run("off", settings={"LEONIDA_X": "0"}),
settings=("LEONIDA_X=1",)),
"LEONIDA_X is not in the settings line": ab.check_run(self.summary_run("gone", settings={"LEONIDA_Y": "1"}),
settings=("LEONIDA_X=1",)),
}
for expected, (got, _exe) in why.items():
self.assertEqual(got, expected)
# A runtime without the settings line: nothing to check the setting against.
self.assertIsNone(ab.check_run(self.summary_run("old"), settings=("LEONIDA_X=1",))[0])

def test_check_prints_json(self):
out = io.StringIO()
with redirect_stdout(out):
self.assertEqual(ab.main(["check", self.summary_run("cli", warm=None), "--exe", "1" * 16]), 0)
self.assertEqual(json.loads(out.getvalue()), {"excluded": "the pipeline cache was never warm", "exe": "1" * 16})

def test_a_run_the_runner_left_out_is_left_out(self):
d = self.gate("excluded", 25.0)
with open(os.path.join(d, ab.EXCLUDED), "w", encoding="utf-8") as f:
f.write("the pipeline cache was never warm\n")
self.assertEqual(ab.run_value(d), (None, None, "excluded: the pipeline cache was never warm"))

def test_a_log_gives_the_median_of_its_world_lines(self):
menus = self.log("menus.log", [60.0] * 5, 13)
world = self.log("world.log", [20.0, 25.0, 25.0], 4000)
Expand Down
107 changes: 107 additions & 0 deletions tests/test_game_abba.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
"""scripts/game-abba.ps1: its plan and gate commands (-DryRun, no game), its refusals, and a PowerShell name trap."""
import os
import re
import shutil
import subprocess
import sys
import tempfile
import unittest

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SCRIPT = os.path.join(ROOT, "scripts", "game-abba.ps1")
PWSH = shutil.which("pwsh")


class Script(unittest.TestCase):
def test_it_needs_powershell_7(self):
# Windows PowerShell 5.1 would fail on it without a clear word: it says so before running anything.
with open(SCRIPT, encoding="utf-8") as f:
self.assertEqual(f.readline().strip(), "#Requires -Version 7.0")

def test_no_variable_takes_a_parameters_name_in_another_case(self):
# PowerShell names ignore case: a variable `$out` would be the `[string]$Out` parameter.
with open(SCRIPT, encoding="utf-8") as f:
text = f.read()
block = text[text.index("param("):text.index("\n)\n")]
params = re.findall(r"\$(\w+)", block)
self.assertIn("Out", params)
for name in params:
others = {m for m in re.findall(r"\$(\w+)\b", text) if m.lower() == name.lower() and m != name}
self.assertFalse(others, f"${name} is also written {sorted(others)}")


@unittest.skipUnless(os.name == "nt" and PWSH, "needs Windows and pwsh")
class DryRun(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(prefix="abba-test-", ignore_cleanup_errors=True)
self.addCleanup(self.tmp.cleanup)
self.dir = self.tmp.name

def run_script(self, *args):
r = subprocess.run([PWSH, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", SCRIPT, "-Game", "G",
"-DataTemplate", "T", "-Out", os.path.join(self.dir, "out"), "-Python", sys.executable,
"-DryRun", *args], capture_output=True, text=True, timeout=120)
return r.returncode, r.stdout, r.stderr

def slots(self, out):
return [re.match(r"(\d+) (\S+) ([AB]): (.*)$", line).groups() for line in out.splitlines()
if re.match(r"\d+ ", line)]

def test_one_exe_two_settings(self):
code, out, err = self.run_script("-Data", os.path.join(self.dir, "data"), "-MoreA", "LEONIDA_X=0",
"-MoreB", "LEONIDA_X=1", "-More", "LEONIDA_Y=2", "-Pairs", "4")
self.assertEqual(code, 0, err)
self.assertIn("mode: one exe, two settings; 11 runs, 4 pairs", out)
slots = self.slots(out)
self.assertEqual([(k, a) for _, k, a, _ in slots],
[("warm-up", "A"), ("warm-up", "B"), ("discarded", "A")] +
[("measured", a) for a in "ABBAABBA"])
for _, _, arm, command in slots:
self.assertIn(f"-More 'LEONIDA_Y=2;LEONIDA_X={'0' if arm == 'A' else '1'}'", command)
then = [line for line in out.splitlines() if line.startswith("then: ")]
self.assertEqual(len(then), 1)
self.assertEqual(re.findall(r" ([AB]):", then[0]), list("ABBAABBA"))

def test_two_builds_run_their_own_gate_and_data(self):
a, b = os.path.join(self.dir, "a"), os.path.join(self.dir, "b")
os.makedirs(os.path.join(a, "scripts"))
os.makedirs(os.path.join(b, "scripts"))
code, out, err = self.run_script("-CheckoutA", a, "-DataA", os.path.join(self.dir, "da"),
"-CheckoutB", b, "-DataB", os.path.join(self.dir, "db"), "-Pairs", "2")
self.assertEqual(code, 0, err)
slots = self.slots(out)
self.assertEqual([(k, arm) for _, k, arm, _ in slots],
[("warm-up", "A"), ("warm-up", "B"), ("discarded", "B"), ("discarded", "A")] +
[("measured", arm) for arm in "ABBA"])
for _, _, arm, command in slots:
checkout, data = (a, "da") if arm == "A" else (b, "db")
self.assertTrue(command.startswith(os.path.join(checkout, "scripts", "game-gate.ps1")), command)
self.assertIn(os.path.join(self.dir, data), command)

def test_refusals(self):
same = os.path.join(self.dir, "d")
a, b = os.path.join(self.dir, "a"), os.path.join(self.dir, "b")
os.makedirs(a)
os.makedirs(b)
cases = {
"share their caches": ("-CheckoutA", a, "-CheckoutB", b, "-DataA", same, "-DataB", same),
"need -DataA and -DataB": ("-CheckoutA", a, "-CheckoutB", b),
"the arms would be the same": ("-Data", same),
"-Pairs is 2 or more": ("-Data", same, "-MoreB", "LEONIDA_X=1", "-Pairs", "1"),
}
for message, args in cases.items():
code, _out, err = self.run_script(*args)
self.assertNotEqual(code, 0, message)
self.assertIn(message, err)

def test_the_output_is_not_in_a_checkout(self):
r = subprocess.run([PWSH, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", SCRIPT, "-Game", "G",
"-DataTemplate", "T", "-Out", os.path.join(ROOT, "abba-out"), "-Data", "D",
"-MoreB", "LEONIDA_X=1", "-Python", sys.executable, "-DryRun"],
capture_output=True, text=True, timeout=120)
self.assertNotEqual(r.returncode, 0)
self.assertIn("-Out is inside a checkout", r.stderr)


if __name__ == "__main__":
unittest.main()
Loading
Loading