## Registration guard for the KNOWLEDGE gun (rack id 17), the learned additive ## angular residual on top of the self-consistent lead forecast ## (`common_libs/guns/gun_knowledge.nim`). ## ## Mirrors `test_lead_gain_registration.nim`: no Java, no battle, no network ## build. Covers: ## * KNOWLEDGE is APPENDED at id 17 and every pre-existing id is byte-identical ## (a rack gun that renumbered would silently re-address every ## `tools/ab/arms_*.txt` config and every `gun_stats.jsonl` column); ## * it defaults to `off`, so the shipped rack still admits exactly Pattern; ## * `TR_RACK_KNOWLEDGE=...` is what admits it, in 1v1 and in melee, and the ## live `vBulletAdmitted` spawn gate honours the membership; ## * `initKnowledgeGun()` is LAZY (0 bytes before first use) and the whole # aim+update path, EXPLORATION included, does NOT touch the global RNG, so ## a rack that admits it cannot perturb the selector's `rand` stream; ## * the gun implements the rack `Gun` concept, learns from its own feedback ## into the exact row that produced the angle, keeps its counts across a ## round boundary and persists them atomically. ## ## Run: nim c -r --path:common_libs common_libs/tests/test_knowledge_registration.nim import std/[math, os, random, strutils, tables] import gun_harness/virtual_bullets import gun_harness/selector import gun_harness/gun_interface import guns/gun_knowledge const KnowledgeId = 17 PatternId = 5 LeadGainId = 16 ## The rack as it was BEFORE this gun was appended. Pinned literal-by-literal: ## if a future edit shifts an id, this fails here instead of in a live battle. PreRack = ["HEADON", "LINEAR", "TSETLIN", "CIRCULAR", "GUESSFACTOR", "PATTERN", "WALLBOUNCE", "ACCEL", "STOPSHOT", "DISPLACE", "AVGLEAD", "DECAYGF", "KNN", "TMSELECT", "TMPATTERN", "TMHORIZON", "LEADGAIN"] var failures = 0 proc check(name: string, ok: bool) = if ok: echo "PASS: ", name else: echo "FAIL: ", name; inc failures proc clearRackEnv() = for name in RackGunNames: delEnv("TR_RACK_" & name) proc wsFor(tick: int, ex, ey, es, eh: float): WorldState = WorldState(enemyX: ex, enemyY: ey, enemySpeed: es, enemyHeading: eh, selfX: 0.0, selfY: 0.0, selfHeading: 0.0, arenaWidth: 800.0, arenaHeight: 600.0, tick: tick) # ── the rack table ─────────────────────────────────────────────────────────── proc testTable() = check "rack: KNOWLEDGE is registered at id 17", RackGunNames[KnowledgeId] == "KNOWLEDGE" check "rack: NumRackGuns grew to 18", NumRackGuns >= 18 and RackGunNames.len == NumRackGuns check "rack: KNOWLEDGE defaults to `off`", DefaultRackMembership[KnowledgeId] == rmOff check "rack: the membership table has one entry per gun", DefaultRackMembership.len == NumRackGuns # No existing id moved, and no existing name changed. (`>` not `==`: guns # appended AFTER KNOWLEDGE, e.g. WAVEELM at 18, do not move anything.) var untouched = RackGunNames.len > PreRack.len for i in 0 ..< PreRack.len: if RackGunNames[i] != PreRack[i]: untouched = false check "rack: every pre-existing id kept its name (KNOWLEDGE appended at the end)", untouched var seen = initTable[string, bool]() var allDistinct = true for n in RackGunNames: if n in seen: allDistinct = false seen[n] = true check "rack: all rack gun names are distinct", allDistinct # Id 17 was free: no shipped gun occupied it. (It is the id the RETIRED ADE+SBC # BITBRAIN gun briefly had; nothing addresses it any more — `TR_RACK_BITBRAIN` # is LEADGAIN's legacy alias, pinned by test_lead_gain_legacy.nim.) check "rack: KNOWLEDGE's id is in range for every per-gun table", KnowledgeId < NumRackGuns var onlyPattern = true for i in 0..= 0.0 and g.unknownRate <= 1.0 # Fire the virtual bullet the way the harness does, and resolve it as a HIT. # The row that produced the angle must be the row that learns. let fired = g.predict(wsFor(2, 294.0, 200.0, 3.0, 0.0), bulletSpeed(PowerBins[0])) g.onResult(FeedbackEvent(prediction: fired, bulletPower: PowerBins[0], fireTick: 2, powerBin: 0, missDistance: 4.0, hit: true, confidence: fired.confidence)) check "learn: onResult wrote an attempt into the table", g.gk.featureCount > 0 and g.gk.unknownCount <= g.gk.featureCount # A MISS resolving the same tick/bucket adds a second attempt and no hit. let fired2 = g.predict(wsFor(3, 291.0, 200.0, 3.0, 0.0), bulletSpeed(PowerBins[0])) g.onResult(FeedbackEvent(prediction: fired2, bulletPower: PowerBins[0], fireTick: 3, powerBin: 0, missDistance: 40.0, hit: false, confidence: fired2.confidence)) check "learn: a miss resolves into the same per-power-bucket record", g.gk.usedGlobalRows >= 1 # A feedback for a tick the gun never predicted (a stale / other-round bullet) # must NOT create evidence: the row is only updated for the shot taken. let before = g.gk.usedGlobalRows g.onResult(FeedbackEvent(prediction: fired2, bulletPower: PowerBins[0], fireTick: 999, powerBin: 0, missDistance: 4.0, hit: true, confidence: fired2.confidence)) check "learn: feedback for an unknown fire tick is dropped, not learned", g.gk.usedGlobalRows == before # The fallback chain has to REACH a threshold before it answers with a # residual, so a cold gun must return the plain forecast (residual 0) and # start COUNTING the situation so it can get there. var fresh = initGunKnowledge(800.0, 600.0) let fCold = fresh.featuresFor(wsFor(0, 300.0, 200.0, 3.0, 0.0), 3, 1.0, 0.0, 0.0) let aCold = fresh.aim(fCold, 0.0) check "learn: a cold table answers with no residual (the forecast alone)", aCold.hasTarget and aCold.residual == 0.0 and aCold.residualBin == -1 and aCold.source == gkSourceNone check "learn: the cold answer still counts the situation for later", fresh.usedGlobalRows == 1 and fresh.rowAttempts(fCold) == 1 # Round boundary: the counts SURVIVE (this gun's own capability), the # per-round scan track does not. let usedRows = g.gk.usedGlobalRows g.onRoundBoundary() check "persist: the learned rows survive a round boundary", g.gk.usedGlobalRows == usedRows check "persist: the per-round scan track is dropped at the boundary", g.gk.tracks.len == 0 # ── on-disk persistence, at a round boundary ───────────────────────────────── proc testPersistence() = let path = getTempDir() / "gk_registration_table.bin" if fileExists(path): removeFile(path) defer: if fileExists(path): removeFile(path) var g = initKnowledgeGun(path) check "persist: an explicit path is the memory path", g.memPath == path g.targetId = 7 # 30 ticks of ONE steady situation (tangential move, constant heading and # speed), so the SAME key accumulates 30 attempts: past the global threshold # (5) and past the opponent one (20). Fewer ticks would leave every row below # threshold and `prune` — correctly — would drop all of them at the save. for t in 0 ..< 30: discard g.predict(wsFor(t, 300.0, 200.0 + 0.5 * t.float, 3.0, 90.0), bulletSpeed(PowerBins[0])) let rows = g.gk.usedGlobalRows + g.gk.oppRows.len g.onRoundBoundary() # first boundary: load (nothing) + prune + save let saved = g.gk.usedGlobalRows + g.gk.oppRows.len check "persist: the round boundary wrote the table", fileExists(path) check "persist: the table holds learned rows after the prune", saved > 0 check "persist: prune drops the rows that never reached threshold", saved <= rows # A fresh gun in a fresh process-equivalent state picks the table back up. var g2 = initKnowledgeGun(path) g2.ensureInit() check "persist: a cold gun has no rows before the load", g2.gk.usedGlobalRows == 0 and g2.gk.oppRows.len == 0 g2.onRoundBoundary() # loads, then round-trips check "persist: the table came back off disk", g2.gk.usedGlobalRows + g2.gk.oppRows.len == saved # A truncated file is REJECTED (strict parser), never half-loaded. let full = readFile(path) writeFile(path, full[0 ..< full.len div 2]) var g3 = initKnowledgeGun(path) g3.ensureInit() check "persist: a truncated file is rejected and the table stays empty", not g3.gk.load(path) and g3.gk.usedGlobalRows == 0 writeFile(path, full) var g4 = initKnowledgeGun(path) g4.ensureInit() check "persist: the intact file is accepted again", g4.gk.load(path) and g4.gk.usedGlobalRows + g4.gk.oppRows.len == saved testTable() testEnvOverride() testLazyAndRngClean() testLearning() testPersistence() if failures > 0: echo "\n", failures, " check(s) FAILED" quit(1) echo "\nAll KNOWLEDGE registration checks passed."