ChimeraBot_garage: M5 — probe scheduler, advisory wiring, G6 ablation ON/OFF, G5 interventional eval

This commit is contained in:
2026-10-07 00:33:31 +02:00
parent da9a66aab8
commit 6a3ba390ee
10 changed files with 944 additions and 5 deletions
+220
View File
@@ -0,0 +1,220 @@
## G6 ablation ladder — probes ON vs OFF (CHIMERA M5). LIVE, Java required.
##
## Runs the same 8×5 pinned-opponent protocol (bench_g4's set) for both builds:
## * ON — default build, probe scheduler wired (spec §9)
## * OFF — `-d:chimeraNoProbes`, probe advisory removed (command path == M1 copy)
## repeated `Repeat` (default 3) full runs each, and reports the MEDIAN
## identification tick per opponent (spec G4: median over >= 3 runs, to survive
## the sample-bot spawn variance) plus the G6 pass bar: probes cut the median
## identification ticks by >= 20%.
##
## A round that never crosses the threshold is censored at its own tick count,
## so "never identified" cannot masquerade as a fast round; the identification
## rate is reported separately.
##
## ON telemetry is archived to /tmp/chimera_g6_on (input to bench_g5p.nim).
## Throwaway output only under /tmp. Run:
## `nim c -r --hints:off -d:release tests/bench_g6.nim`
import std/[os, osproc, strutils, sequtils, math, tables, algorithm]
import test_framework/server_manager
import test_framework/runner_process
const
SampleRoot = getEnv(
"TR_SAMPLE_BOTS",
"/home/davide/Downloads/robocode-tankroyale/sample-bots-nim-linux-1.0.7")
GarageSrc = currentSourcePath().parentDir.parentDir / "src"
StageDir = getTempDir() / "chimera_g6_stage"
Telemetry = getTempDir() / "chimera_twin"
OnDir = getTempDir() / "chimera_g6_on"
OffDir = getTempDir() / "chimera_g6_off"
Rounds = 5
Repeat = 3
Threshold = 0.8
TargetTicks = 300
MaxAttempts = 4
const Expected = {
"Crazy": "ZIGZAG",
"SpinBot": "ORBIT_BALLIST",
"RamFire": "STATIC",
"Corners": "STATIC",
"Walls": "WALLCRAWL",
"TrackFire": "STATIC",
"Fire": "STATIC",
"VelociBot": "STOP_AND_GO",
}.toTable
proc guardSkip() =
let serverOk = fileExists(getEnv("TR_SERVER_JAR",
"/home/davide/Downloads/robocode-tankroyale/robocode-tankroyale-server.jar"))
let runnerOk = fileExists(getEnv("TR_BATTLE_RUNNER",
"/home/davide/Projects/tank-royale/runner/examples/lib/robocode-tankroyale-runner.jar"))
if not serverOk or not runnerOk or not dirExists(SampleRoot):
echo "Skipping G6 bench: TR_SERVER_JAR / TR_BATTLE_RUNNER / sample bots missing."
quit(0)
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, off: bool): string =
let botDir = StageDir / tag / "ChimeraBot"
removeDir(StageDir / tag)
createDir(botDir)
let bin = botDir / "ChimeraBot"
var cmd = "nim c -d:release --hints:off "
if off: cmd.add "-d:chimeraNoProbes "
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])
type
RoundStat = object
idTick: int # first tick weight(expected) >= Threshold, else -1
sumTicks: int
identified: bool
proc parseFile(path, expectedKernel: string): RoundStat =
result.idTick = -1
for ln in readFile(path).splitLines():
if ln.len == 0: continue
if ln.startsWith("{\"event\":\"round_summary\""):
result.sumTicks = extract(ln, "ticks").value.parseInt()
elif ln.startsWith("{\"tick\""):
let top = ln.substr(ln.find("posteriorTop5"))
let nameI = top.find("\"name\":\"" & expectedKernel & "\",\"w\":")
if nameI >= 0:
let wI = top.find("\"w\":", nameI) + len("\"w\":")
var j = wI
while j < top.len and (top[j] in Digits or top[j] == '.'): inc j
let w = top[wI ..< j].parseFloat()
let tick = extract(ln, "tick").value.parseInt()
if w >= Threshold and (result.idTick < 0 or tick < result.idTick):
result.idTick = tick
result.identified = result.idTick > 0
proc median(xs: seq[int]): int =
if xs.len == 0: return -1
var s = xs; s.sort()
s[s.len div 2]
proc runArm(tag: string, off: bool): Table[string, seq[int]] =
let botDir = stageBot(tag, off)
removeDir(Telemetry)
let armDir = if off: OffDir else: OnDir
removeDir(armDir)
createDir(armDir)
ensureServer()
let url = getServerUrl()
for opp in sorted(toSeq(Expected.keys)):
putEnv("CHIMERA_OPPONENT", opp)
putEnv("CHIMERA_TELEMETRY_DIR", Telemetry)
let sampleBot = SampleRoot / opp
for run in 1 .. Repeat:
var ok = false
for attempt in 1 .. MaxAttempts:
removeDir(Telemetry)
sleep(1200)
try:
discard runBattleRunner(url, @[botDir, sampleBot], rounds = Rounds,
timeout = 300000)
ok = true
break
except CatchableError:
if attempt >= MaxAttempts:
echo " ", tag, " ", opp, " run", run, ": battle failed"
if not ok: continue
copyDir(Telemetry, armDir / (opp & "-run" & $run))
# parse everything for this opponent
var ids: seq[int]
for f in walkDirRec(armDir):
if not f.endsWith(".jsonl"): continue
if not f.extractFilename.startsWith(opp & "-"): continue
let rs = parseFile(f, Expected[opp])
if rs.sumTicks == 0: continue
ids.add (if rs.identified: rs.idTick else: rs.sumTicks)
result[opp] = ids
proc stats(ids: seq[int]): tuple[med, rate: float64, n: int] =
if ids.len == 0: return (-1.0, 0.0, 0)
var identified = 0
for x in ids:
if x <= TargetTicks: inc identified
(float(median(ids)), 100.0 * float(identified) / float(ids.len), ids.len)
proc main() =
guardSkip()
echo "[G6] staging ON/OFF builds and running ", Repeat, " full runs each"
let on = runArm("on", false)
let off = runArm("off", true)
echo "\nG6 identification ticks, median over ", Repeat, " runs x ", Rounds,
" rounds (censored rounds scored at their tick count)"
echo "Opponent onMed onID% offMed offID% cut%"
var pooledOn, pooledOff: seq[int]
var onPass, offPass = 0
var comparable = 0
var cutSum = 0.0
var cutN = 0
for opp in sorted(toSeq(Expected.keys)):
if not (opp in on and opp in off): continue
let so = stats(on[opp])
let sf = stats(off[opp])
if so.n == 0 or sf.n == 0: continue
pooledOn.add on[opp]
pooledOff.add off[opp]
inc comparable
if so.med <= TargetTicks: inc onPass
if sf.med <= TargetTicks: inc offPass
let cut = if sf.med > 0: 100.0 * (sf.med - so.med) / sf.med else: 0.0
cutSum += cut; inc cutN
echo " ", alignLeft(opp, 12),
align($int(so.med), 6), " ", align(formatFloat(so.rate, ffDecimal, 0), 5),
" ", align($int(sf.med), 7), " ", align(formatFloat(sf.rate, ffDecimal, 0), 5),
" ", align(formatFloat(cut, ffDecimal, 1), 6)
let onAll = median(pooledOn)
let offAll = median(pooledOff)
let overall = if offAll > 0: 100.0 * float(offAll - onAll) / float(offAll) else: 0.0
echo "\nPooled median ON = ", onAll, " ticks, OFF = ", offAll, " ticks"
echo "G6 probes cut median identification by ", formatFloat(overall, ffDecimal, 1),
"% (bar >= 20%): ", (if overall >= 20.0: "PASS" else: "FAIL")
echo "G4 median pass (ON, <= ", TargetTicks, "): ", onPass, "/", comparable,
" (OFF: ", offPass, "/", comparable, ")"
echo "Per-opponent cut mean = ",
formatFloat(if cutN > 0: cutSum / float(cutN) else: 0.0, ffDecimal, 1), "%"
echo "ON telemetry archived at ", OnDir, " (G5' input)"
when isMainModule:
main()