Files
SirRoboGarage/ChimeraBot_garage/tests/bench_common.nim
T

290 lines
11 KiB
Nim

## Shared benchmark plumbing for the M5.5 unified identification metric.
##
## Source of truth: `docs/chimera-spec.md` §12 G4/G6 (M5.5 metric unification).
## `idTicks` is defined ONE way everywhere: per round, the ROUND-RELATIVE tick
## at which `max_kernel posterior > 0.8` first holds. Per opponent the benches
## report median / p90 / id-fraction over ALL rounds in the protocol. Whether the
## argmax equals the expected kernel is a separate diagnostic column.
##
## Live battles need Java + the TR server/runner JARs + the unpacked Nim sample
## bots; callers must guard-skip when absent. Throwaway output lives under /tmp.
import std/[os, osproc, strutils, sequtils, math, tables, algorithm, times, net, streams]
const
RunnerJar* = "/home/davide/Projects/tank-royale/runner/examples/lib/robocode-tankroyale-runner.jar"
RunnerDir* = currentSourcePath().parentDir.parentDir / ".." / "tools" / "battle_runner"
ServerJar* = "/home/davide/Downloads/robocode-tankroyale/robocode-tankroyale-server.jar"
# ── restartable server (the shared test server degrades after many battles,
# hanging some opponents; benches therefore own and recycle the server) ────
var serverProc: Process = nil
var serverPort = 0
proc findFreePort(): int =
let s = newSocket()
s.bindAddr(Port(0))
let (_, port) = s.getLocalAddr()
s.close()
port.int
proc restartServer*() =
if serverProc != nil:
serverProc.terminate()
sleep(300)
if serverProc.peekExitCode() == -1: serverProc.kill()
serverProc.close()
serverProc = nil
serverPort = findFreePort()
serverProc = startProcess("java", args = @["-jar",
getEnv("TR_SERVER_JAR", ServerJar), "--port", $serverPort,
"--enable-initial-position", "--tps", "-1"],
options = {poUsePath, poStdErrToStdOut})
let deadline = epochTime() + 20.0
var ready = false
while epochTime() < deadline:
var line: string
if not serverProc.outputStream.readLine(line): break
if "Starting server on port" in line:
ready = true
break
if not ready:
quit("TR server did not start")
proc serverUrl*(): string = "ws://localhost:" & $serverPort
proc killStaleBots*() =
## SIGKILL any lingering runner/bot from a timed-out battle. The bracket
## patterns keep pkill from matching this process's own command line.
discard execCmdEx("pkill -9 -f '[T]estBattleRunner' 2>/dev/null")
discard execCmdEx("pkill -9 -f '[C]himeraBot' 2>/dev/null")
const
SampleRoot* = getEnv(
"TR_SAMPLE_BOTS",
"/home/davide/Downloads/robocode-tankroyale/sample-bots-nim-linux-1.0.7")
GarageSrc* = currentSourcePath().parentDir.parentDir / "src"
Threshold* = 0.8 ## unified identification threshold (spec G4)
TargetTicks* = 300 ## unified G4 tick budget
MaxAttempts* = 4
## The 8 behavior-diverse ground-truth targets and the kernel each is expected
## to identify (§12 verified mapping; v0.2 STATIC refinement documented in
## bench_g4's history).
const Expected* = {
"Crazy": "ZIGZAG",
"SpinBot": "ORBIT_BALLIST",
"RamFire": "STATIC",
"Corners": "STATIC",
"Walls": "WALLCRAWL",
"TrackFire": "STATIC",
"Fire": "STATIC",
"VelociBot": "STOP_AND_GO",
}.toTable
## G5' v2 subsets (M5.5): persistence is not optimal for the MOVING set.
const MovingOpponents* = @["Crazy", "SpinBot", "VelociBot", "Walls"]
const StaticOpponents* = @["RamFire", "Corners", "TrackFire", "Fire"]
proc guardSkip*() =
let serverOk = fileExists(getEnv("TR_SERVER_JAR", ServerJar))
let runnerOk = fileExists(getEnv("TR_BATTLE_RUNNER", RunnerJar))
if not serverOk or not runnerOk or not dirExists(SampleRoot):
echo "Skipping bench: TR_SERVER_JAR / TR_BATTLE_RUNNER / sample bots missing."
quit(0)
proc runBattleHard*(serverUrl: string, botDirs: seq[string], rounds: int,
timeoutMs = 90000, maxSpeed = true): bool =
## Hard-timeout battle: `test_framework.runBattleRunner` can block forever when
## the Java runner stops emitting output while still alive, so benches use this
## wrapper (shell redirect to a log, poll, then kill). Battles normally take
## 1-3 s, so 90 s is generous and bounds a hang.
let jar = getEnv("TR_BATTLE_RUNNER", RunnerJar)
let classDir = getEnv("TR_BATTLE_RUNNER_DIR", RunnerDir)
let logf = getTempDir() / "chimera_runner.log"
var args = "--server-url " & quoteShell(serverUrl) &
" --rounds " & $rounds &
" --bot-dirs " & quoteShell(botDirs.join(","))
if maxSpeed: args.add " --max-speed"
# coreutils `timeout -s KILL` is the hard guarantee: if the Java runner blocks
# and ignores SIGTERM (shutdown hooks), the shell still kills it at the limit.
let hardSec = int(timeoutMs div 1000) + 5
let cmd = "timeout -s KILL " & $hardSec & " java -cp " &
quoteShell(classDir & ":" & jar) &
" TestBattleRunner " & args & " > " & quoteShell(logf) & " 2>&1"
let p = startProcess("sh", args = @["-c", cmd], options = {poUsePath})
let deadline = epochTime() + float(timeoutMs) / 1000.0
var done = false
while epochTime() < deadline:
if p.peekExitCode() != -1:
done = true
break
sleep(100)
if not done:
p.terminate()
sleep(200)
if p.peekExitCode() == -1: p.kill()
p.close()
return false
result = p.peekExitCode() == 0
p.close()
proc deps*(): seq[string] =
for p in ["robocode_tankroyale_botapi", "jsony"]:
let (outp, _) = execCmdEx("nimble path " & p)
var line = ""
for l in outp.splitLines():
if l.len > 0: line = l; break
if line.len == 0: quit("Cannot resolve dependency: " & p)
result.add "--path:" & line
proc stageBot*(tag: string, defines: seq[string] = @[]): string =
## Compile ChimeraBot into a throwaway /tmp dir with its json + boot script.
let botDir = getTempDir() / ("chimera_stage_" & tag) / "ChimeraBot"
removeDir(getTempDir() / ("chimera_stage_" & tag))
createDir(botDir)
let bin = botDir / "ChimeraBot"
var cmd = "nim c -d:release --hints:off "
for d in defines: cmd.add d & " "
cmd.add deps().join(" ") & " --out:\"" & bin & "\" " &
quoteShell(GarageSrc / "ChimeraBot.nim")
let (outp, code) = execCmdEx(cmd, options = {poEvalCommand})
if code != 0 or not fileExists(bin):
quit("ChimeraBot (" & tag & ") compile failed:\n" & outp)
copyFile(GarageSrc / "ChimeraBot.json", botDir / "ChimeraBot.json")
writeFile(botDir / "ChimeraBot.sh",
"#!/bin/sh\ncd -- \"$(dirname -- \"$0\")\"\nexec \"./ChimeraBot\"\n")
let sh = botDir / "ChimeraBot.sh"
setFilePermissions(sh, getFilePermissions(sh) + {fpUserExec, fpGroupExec, fpOthersExec})
botDir
proc extract*(line: string, key: string): tuple[found: bool, value: string] =
let needle = "\"" & key & "\":"
let i = line.find(needle)
if i < 0: return (false, "")
let rest = line[i + needle.len .. ^1]
var j = 0
while j < rest.len and rest[j] in {' ', '\t'}: inc j
if j < rest.len and rest[j] == '"':
let start = j + 1
var k = start
while k < rest.len and rest[k] != '"': inc k
return (true, rest[start ..< k])
var k = j
while k < rest.len and (rest[k].isAlphaNumeric or rest[k] in {'.', '-', 'e', 'E'}):
inc k
return (true, rest[j ..< k])
proc topWeights(line: string): seq[tuple[name: string, w: float64]] =
## Parse the `posteriorTop5` array entries `{"name":"X","w":W}` in order.
let start = line.find("\"posteriorTop5\":")
if start < 0: return
let seg = line[start .. ^1]
var i = 0
while true:
let ni = seg.find("\"name\":\"", i)
if ni < 0: break
let ns = ni + len("\"name\":\"")
var ne = ns
while ne < seg.len and seg[ne] != '"': inc ne
let name = seg[ns ..< ne]
let wi = seg.find("\"w\":", ne)
if wi < 0: break
var j = wi + len("\"w\":")
while j < seg.len and (seg[j] in Digits or seg[j] in {'.', '-', 'e', 'E'}): inc j
var w = 0.0
try: w = parseFloat(seg[wi + len("\"w\":") ..< j])
except ValueError: w = 0.0
result.add (name, w)
i = j
type
RoundStat* = object
idTick*: int ## round-relative tick max posterior first > Threshold
expIdTick*: int ## same for the EXPECTED kernel (diagnostic)
argmaxCorrect*: bool ## at the crossing tick, argmax == expected kernel
identified*: bool
sumTicks*: int
censorRate*: float64
finalPosterior*: float64
finalKernel*: string
ade*, fde*: float64
gapMax*, gapViolations*: int
proc parseFile*(path, expectedKernel: string): RoundStat =
## Unified idTicks parse. Round-relative: the first tick line of the round is
## tick 1, so carry-over can identify at round start.
result.idTick = -1
result.expIdTick = -1
result.argmaxCorrect = false
var t0 = -1
for ln in readFile(path).splitLines():
if ln.len == 0: continue
if ln.startsWith("{\"event\":\"round_summary\""):
result.finalPosterior = extract(ln, "finalPosterior").value.parseFloat()
result.finalKernel = extract(ln, "finalKernel").value
result.sumTicks = extract(ln, "ticks").value.parseInt()
result.censorRate = extract(ln, "censorRate").value.parseFloat()
result.ade = extract(ln, "ade").value.parseFloat()
result.fde = extract(ln, "fde").value.parseFloat()
result.gapMax = extract(ln, "scanGapMax").value.parseInt()
result.gapViolations = extract(ln, "scanGapViolations").value.parseInt()
elif ln.startsWith("{\"tick\""):
let (tf, ts) = extract(ln, "tick")
if not tf: continue
let tick = ts.parseInt()
if t0 < 0: t0 = tick
let rel = tick - t0 + 1
let tw = topWeights(ln)
if tw.len == 0: continue
var maxW = 0.0
var maxName = ""
var expW = 0.0
for (name, w) in tw:
if w > maxW:
maxW = w; maxName = name
if name == expectedKernel and w > expW: expW = w
if result.idTick < 0 and maxW > Threshold:
result.idTick = rel
result.argmaxCorrect = maxName == expectedKernel
if result.expIdTick < 0 and expW > Threshold:
result.expIdTick = rel
result.identified = result.idTick > 0
proc p90*(xs: seq[int]): int =
if xs.len == 0: return -1
var s = xs
s.sort()
s[max(0, int(ceil(0.9 * float(s.len))) - 1)]
proc medianIndex*(xs: seq[int]): int =
if xs.len == 0: return -1
var s = xs
s.sort()
s[s.len div 2]
type
IdStats* = object
median*: int
p90*: int
idFraction*: float64 ## % of rounds identified
n*: int
proc idStats*(ids: seq[int]): IdStats =
## `ids[i]` is the round idTick, or -1 when the round never identified.
if ids.len == 0: return IdStats(median: -1, p90: -1, idFraction: 0.0, n: 0)
var identified: seq[int]
for x in ids:
if x > 0: identified.add x
result.n = ids.len
result.median = medianIndex(identified)
result.p90 = p90(identified)
result.idFraction = 100.0 * float(identified.len) / float(ids.len)
proc fmt*(s: IdStats): string =
## `med p90 id%` columns, `-` for an empty set.
let m = if s.median < 0: "-" else: $s.median
let p = if s.p90 < 0: "-" else: $s.p90
align(m, 6) & align(p, 6) & align(formatFloat(s.idFraction, ffDecimal, 0), 6)