Claude Claude Sonnet 5 commited on
Commit
a2ff995
Β·
unverified Β·
1 Parent(s): c14468b

Fix ailab.test.js hang misdiagnosis; correct stale task numbering

Browse files

The "hang" reported for test/ailab.test.js during T-012/T-013 validation
was a diagnostic error in this session, not a real bug: node --test runs
each file as a child process, and every check looked at the parent
orchestrator's near-idle CPU instead of the child actually doing the work.
Direct measurement of the child process confirms the full 95-test file
completes in ~5 minutes (several evolutionary-archive tests individually
take 20+ seconds β€” a genuinely heavy AI bench, never a hang). TASKS.md's
T-012/T-013 rows corrected to the true full-suite count (2,555 then 2,565)
instead of excluding this file.

One real, harmless, pre-existing bug found along the way and fixed: test
9 in that file calls applyOverrides() to inject a strategy into the live
shared STRATEGIES table and never restores it β€” the exact leak pattern
the very next test's own comment already documents happening once before.
Wrapped in the same snapshotTables/restoreTables the neighboring test
uses. Nothing else in the file selects the leaked strategy by name, so
this never affected any other test's result β€” hygiene, not a fix to a
wrong number.

Also corrected three stale "T-013" cross-references in
docs/analysis/00-feasibility-spikes.md left over from before the task
numbering settled β€” the Space-hardware spike re-run is T-014 now.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PzkfXsTz4hxPfuySb1GvyS

TASKS.md CHANGED
@@ -110,8 +110,8 @@ already proven by 2,519 tests (ADR-0004).
110
  | **T-009** | Define the transport interface and session protocol shapes (tests first) | ADR-0004 | T-005 | βœ… | `net/transport.js` (Transport/TransportEvent JSDoc, no runtime code β€” same convention as `engine/types.js`) and `net/commandShapes.js` (the full `WireCommand` union for skirmish, adopted verbatim from `docs/analysis/02-command-wire-protocol.md` Β§3 so Phase 2's codec is additive, not a rewrite). "Tests fail for the right reason": `test/session.test.js` written first, failed on `ERR_MODULE_NOT_FOUND` before `server/session.js` existed |
111
  | **T-010** | `server/session.js` β€” owns one match's state, applies commands, advances the loop | ADR-0003 | T-009 | βœ… | **11/11 new tests green**, full suite **2,540/2,540**, typecheck clean. A session with both seats AI-driven (`aiSeats:["player"]`, mirroring `tools/selfplay.js`'s own proven pattern) plays a full match headlessly to a winner. `submitCommand` covers the full skirmish command surface β€” all of `engine/commands.js`'s `issue*` plus production/research (`queueProduction`, `researchUpgrade`, `researchTech`, …) β€” resolving ids and dropping dead ones gracefully, **not yet validating ownership/fog** (deliberately deferred to Phase 2's `net/commandCodec.js`, an additive layer on top of this file, not a rewrite). Found and worked around, without touching the engine: `engine/state.js`'s module-global `nextEntityId` (ADR-0011, T-016) makes two sessions ticked *interleaved* in one process mint colliding ids β€” confirmed live by a failing test, fixed by making the determinism test sequential instead, with the defect explained inline so it isn't "fixed" again by mistake. `test/static-integrity.test.js`'s reachability check correctly flagged the three new files as orphans; fixed properly, not silenced: `net/commandShapes.js`/`net/transport.js` are **permanent** exemptions (pure typedefs, same class as `engine/types.js`), `server/session.js` is a **temporary** one removed when T-012 wires `boot.js` to it β€” the exact "module lands ahead of its UI wiring" convention the file already uses for `elo.js`/`competitionLedger.js`/`pairing.js` |
112
  | **T-011** | `net/loopback.js` β€” in-process transport | ADR-0004 | T-009 | βœ… | **8/8 new tests green**, full suite **2,548/2,548**, typecheck clean. Implements `net/transport.js`'s generic contract (`submitCommand`/`onEvent`/`close`) plus two loopback-specific extensions T-012 can choose to use (`tick`, `getState`) that a real remote transport could never offer. `submitCommand` returns a `Promise` β€” genuinely resolved synchronously underneath (proven by a test asserting the mutation is visible **before** `await`), so client code written against it is already correct once a real async transport replaces it in Phase 3, and T-013 has a real gap to inject faults into. Same static-integrity exemption pattern as T-010, extended to this file |
113
- | **T-012** | Port the single-player client onto session + loopback | G3 | T-010, T-011 | βœ… | **Full inherited suite green: 2,460/2,460** (`node --test`, every file except `test/ailab.test.js` β€” see below), **typecheck clean**, **browser smoke 21/21** (one new check added). Scope, decided against the PRD's own non-goal (multiplayer Odyssey out of scope) and dossier 03: only the ordinary skirmish and a live competition fixture move onto `server/session.js` + `net/loopback.js` this pass; Odyssey, a scenario/raider/bounty, and a spectated match keep ticking on their existing path. To keep `input.js`/`inputCommands.js`/`hudSelection.js` β€” shared across every boot path β€” on ONE calling convention rather than a nullable-transport branch at ~18 call sites, **ADR-0013** adds `net/directTransport.js`: a Transport-shaped adapter with no session/tick, reusing `server/session.js`'s standalone `applyCommand`. `boot.js`'s `bootState`/`focusActivePlanet` decide which transport a boot path gets; the UI modules never branch on it. `server/session.js`'s `createSession` gained an `opts.state` escape hatch (wrap an already-built state, tested) for `saveload.js`'s loaded-skirmish path, which now sessions too. `net/transport.js`'s own `submitCommand` JSDoc was corrected in the same pass β€” it documented a `void`-returning, event-only contract that T-011's actual `net/loopback.js` already didn't match (a `Promise<CommandResult>`, silently allowed through by TS's void-return leniency); `input.js`'s `placeBuildingAt` is now the first real caller depending on that Promise (buildMode must stay armed until the result actually resolves ok β€” covered by two new tests, one proving the async gap, one proving the synchronous-failure short-circuit). `test/input.test.js` (57β†’59 tests) and `test/hudSelection.test.js`'s harnesses were converted from bare/direct engine state to a wired transport (`net/directTransport.js` reused directly in both β€” exactly the adapter it exists for); every pre-existing assertion in both files needed zero changes, confirming the synchronous-underneath guarantee holds end to end. One command-issuing site had no prior test coverage anywhere and was missed by the initial inventory: `main.js`'s minimap right-click handler (`issueMove`/`issueAttackMove` called directly, not through `input.js` at all) β€” found by a post-hoc grep sweep for stray `engine/commands.js` imports, fixed, and given its own new browser-smoke check since no Node-side harness for `main.js` exists yet. **`test/ailab.test.js` excluded from the "full suite" count above**, not silently: it hangs indefinitely (0% CPU, not just slow) on its own first test, reproducible standalone with no relation to anything this task touched β€” confirmed pre-existing via `git log` (last touched 2026-08-07, part of the verbatim-imported upstream history, ADR-0002) and unrelated via its import graph (only `engine/`/`tools/`, nothing this task changed). Flagged as a separate task rather than fixed here (out of scope: `tools/ailab.js`'s AI bench, not the client port) |
114
- | **T-013** | Fault-injection loopback: latency, reordering, drops. Covers the five client sites that resist loopback β€” chiefly `input.js:521`, which passes synchronously over loopback and **breaks over a socket**, so a sync-only path would pass every test and fail in production | FR-11 | T-011 | βœ… | **10/10 new tests green** (`test/loopbackFaults.test.js`), full suite **2,470/2,470**, typecheck clean. `net/loopbackFaults.js`'s `createFaultyTransport(inner, opts)` wraps any `Transport` (loopback today, a future `WebSocketTransport` just as well) with configurable `latencyMs`, `jitterMs` (independent per-call delay, which genuinely reorders promise *resolution* relative to submission order β€” proven with a scripted, non-random `rng` so the test is reproducible), and `dropRate` (a dropped `submitCommand` never reaches `inner` at all and its promise never resolves β€” a lost order, not a delayed one β€” and the promise channel and the broadcast `onEvent` channel drop independently of each other, proven with precisely scripted `rng` sequences). Revises T-012's own "five client sites" estimate down to **one, with evidence**: T-012's actual call-site audit (not this task's guess) found exactly one β€” `input.js`'s `placeBuildingAt` β€” that reads a `CommandResult`; every other command-issuing site is provably fire-and-forget. That one site is now proven against a REAL injected delay, not just a microtask tick: a new integration test in `test/input.test.js` drives it through `createFaultyTransport(directTransport, {latencyMs:20})` and confirms `buildMode` stays armed for the full 20ms, clearing only once the delayed promise resolves β€” the concrete demonstration that no client path depends on a synchronous reply. `net/loopbackFaults.js` gets a **permanent** static-integrity exemption (a third class, distinct from the typedef files and the temporary T-010/011/012 ones): genuine runtime code, really imported, but only ever by tests β€” never wired into `boot.js`, by design, the same standing reason `tools/ailab.js`/`selfplay-cli.js`/`serve.js` sit outside that check entirely |
115
  | **T-014** | Commit `tools/bench.js`; re-run spikes 1–2 **on Space hardware**; measure memory per match | NFR-2, NFR-4 | T-006 | βšͺ | Measured p99 tick cost and memory per match recorded in `docs/analysis/00` |
116
  | **T-015** | Measure serialization + fog-filtering cost per client per tick, and **settle NFR-3**. Already measured: full state at 800v800 on a 4Γ— map is **404 KB / 4.45 ms**, which at 20 Hz Γ— 4 seats is 32 MB/s and 18 ms of a 50 ms budget; the fog-filtered equivalent is **55 KB / 0.69 ms**. Filtering is what makes replication affordable. But 55 KB/snapshot still **exceeds NFR-3's 32 KB/s** at the pathological end | NFR-3, ADR-0009 | T-010 | βšͺ | Snapshot rate and delta-encoding (ADR-0009 M3) chosen on measured numbers; NFR-3 either met or **deliberately restated** |
117
 
 
110
  | **T-009** | Define the transport interface and session protocol shapes (tests first) | ADR-0004 | T-005 | βœ… | `net/transport.js` (Transport/TransportEvent JSDoc, no runtime code β€” same convention as `engine/types.js`) and `net/commandShapes.js` (the full `WireCommand` union for skirmish, adopted verbatim from `docs/analysis/02-command-wire-protocol.md` Β§3 so Phase 2's codec is additive, not a rewrite). "Tests fail for the right reason": `test/session.test.js` written first, failed on `ERR_MODULE_NOT_FOUND` before `server/session.js` existed |
111
  | **T-010** | `server/session.js` β€” owns one match's state, applies commands, advances the loop | ADR-0003 | T-009 | βœ… | **11/11 new tests green**, full suite **2,540/2,540**, typecheck clean. A session with both seats AI-driven (`aiSeats:["player"]`, mirroring `tools/selfplay.js`'s own proven pattern) plays a full match headlessly to a winner. `submitCommand` covers the full skirmish command surface β€” all of `engine/commands.js`'s `issue*` plus production/research (`queueProduction`, `researchUpgrade`, `researchTech`, …) β€” resolving ids and dropping dead ones gracefully, **not yet validating ownership/fog** (deliberately deferred to Phase 2's `net/commandCodec.js`, an additive layer on top of this file, not a rewrite). Found and worked around, without touching the engine: `engine/state.js`'s module-global `nextEntityId` (ADR-0011, T-016) makes two sessions ticked *interleaved* in one process mint colliding ids β€” confirmed live by a failing test, fixed by making the determinism test sequential instead, with the defect explained inline so it isn't "fixed" again by mistake. `test/static-integrity.test.js`'s reachability check correctly flagged the three new files as orphans; fixed properly, not silenced: `net/commandShapes.js`/`net/transport.js` are **permanent** exemptions (pure typedefs, same class as `engine/types.js`), `server/session.js` is a **temporary** one removed when T-012 wires `boot.js` to it β€” the exact "module lands ahead of its UI wiring" convention the file already uses for `elo.js`/`competitionLedger.js`/`pairing.js` |
112
  | **T-011** | `net/loopback.js` β€” in-process transport | ADR-0004 | T-009 | βœ… | **8/8 new tests green**, full suite **2,548/2,548**, typecheck clean. Implements `net/transport.js`'s generic contract (`submitCommand`/`onEvent`/`close`) plus two loopback-specific extensions T-012 can choose to use (`tick`, `getState`) that a real remote transport could never offer. `submitCommand` returns a `Promise` β€” genuinely resolved synchronously underneath (proven by a test asserting the mutation is visible **before** `await`), so client code written against it is already correct once a real async transport replaces it in Phase 3, and T-013 has a real gap to inject faults into. Same static-integrity exemption pattern as T-010, extended to this file |
113
+ | **T-012** | Port the single-player client onto session + loopback | G3 | T-010, T-011 | βœ… | **Full inherited suite green: 2,555/2,555**, **typecheck clean**, **browser smoke 21/21** (one new check added). Scope, decided against the PRD's own non-goal (multiplayer Odyssey out of scope) and dossier 03: only the ordinary skirmish and a live competition fixture move onto `server/session.js` + `net/loopback.js` this pass; Odyssey, a scenario/raider/bounty, and a spectated match keep ticking on their existing path. To keep `input.js`/`inputCommands.js`/`hudSelection.js` β€” shared across every boot path β€” on ONE calling convention rather than a nullable-transport branch at ~18 call sites, **ADR-0013** adds `net/directTransport.js`: a Transport-shaped adapter with no session/tick, reusing `server/session.js`'s standalone `applyCommand`. `boot.js`'s `bootState`/`focusActivePlanet` decide which transport a boot path gets; the UI modules never branch on it. `server/session.js`'s `createSession` gained an `opts.state` escape hatch (wrap an already-built state, tested) for `saveload.js`'s loaded-skirmish path, which now sessions too. `net/transport.js`'s own `submitCommand` JSDoc was corrected in the same pass β€” it documented a `void`-returning, event-only contract that T-011's actual `net/loopback.js` already didn't match (a `Promise<CommandResult>`, silently allowed through by TS's void-return leniency); `input.js`'s `placeBuildingAt` is now the first real caller depending on that Promise (buildMode must stay armed until the result actually resolves ok β€” covered by two new tests, one proving the async gap, one proving the synchronous-failure short-circuit). `test/input.test.js` (57β†’59 tests) and `test/hudSelection.test.js`'s harnesses were converted from bare/direct engine state to a wired transport (`net/directTransport.js` reused directly in both β€” exactly the adapter it exists for); every pre-existing assertion in both files needed zero changes, confirming the synchronous-underneath guarantee holds end to end. One command-issuing site had no prior test coverage anywhere and was missed by the initial inventory: `main.js`'s minimap right-click handler (`issueMove`/`issueAttackMove` called directly, not through `input.js` at all) β€” found by a post-hoc grep sweep for stray `engine/commands.js` imports, fixed, and given its own new browser-smoke check since no Node-side harness for `main.js` exists yet. **Note, corrected after this task closed:** an earlier version of this row said `test/ailab.test.js` (95 tests) was excluded from the count as an apparently hanging file. That was wrong β€” a diagnostic error in this same session (checking `node --test`'s parent orchestrator process for CPU activity instead of the child process actually running the test file, which was busy the whole time). The full 95-test file completes in ~5 minutes (several of its evolutionary-archive tests individually take 20+ seconds β€” a real, if slow, AI bench, never a hang) and is included in the 2,555 total above. See T-013's own note and TASKS.md's commit history for the correction |
114
+ | **T-013** | Fault-injection loopback: latency, reordering, drops. Covers the five client sites that resist loopback β€” chiefly `input.js:521`, which passes synchronously over loopback and **breaks over a socket**, so a sync-only path would pass every test and fail in production | FR-11 | T-011 | βœ… | **10/10 new tests green** (`test/loopbackFaults.test.js`), full suite **2,565/2,565**, typecheck clean. `net/loopbackFaults.js`'s `createFaultyTransport(inner, opts)` wraps any `Transport` (loopback today, a future `WebSocketTransport` just as well) with configurable `latencyMs`, `jitterMs` (independent per-call delay, which genuinely reorders promise *resolution* relative to submission order β€” proven with a scripted, non-random `rng` so the test is reproducible), and `dropRate` (a dropped `submitCommand` never reaches `inner` at all and its promise never resolves β€” a lost order, not a delayed one β€” and the promise channel and the broadcast `onEvent` channel drop independently of each other, proven with precisely scripted `rng` sequences). Revises T-012's own "five client sites" estimate down to **one, with evidence**: T-012's actual call-site audit (not this task's guess) found exactly one β€” `input.js`'s `placeBuildingAt` β€” that reads a `CommandResult`; every other command-issuing site is provably fire-and-forget. That one site is now proven against a REAL injected delay, not just a microtask tick: a new integration test in `test/input.test.js` drives it through `createFaultyTransport(directTransport, {latencyMs:20})` and confirms `buildMode` stays armed for the full 20ms, clearing only once the delayed promise resolves β€” the concrete demonstration that no client path depends on a synchronous reply. `net/loopbackFaults.js` gets a **permanent** static-integrity exemption (a third class, distinct from the typedef files and the temporary T-010/011/012 ones): genuine runtime code, really imported, but only ever by tests β€” never wired into `boot.js`, by design, the same standing reason `tools/ailab.js`/`selfplay-cli.js`/`serve.js` sit outside that check entirely. **Also, unrelated to this task's own scope but found while re-verifying `test/ailab.test.js`** (wrongly reported as hanging when T-012 closed β€” corrected in that row above): a genuinely pre-existing, harmless leak in that file's test 9 (`applyOverrides` with no matching `restoreTables`, the exact pattern the very next test's own comment already warned about) β€” fixed with the same `snapshotTables`/`restoreTables` wrap that test already uses, one line of real change |
115
  | **T-014** | Commit `tools/bench.js`; re-run spikes 1–2 **on Space hardware**; measure memory per match | NFR-2, NFR-4 | T-006 | βšͺ | Measured p99 tick cost and memory per match recorded in `docs/analysis/00` |
116
  | **T-015** | Measure serialization + fog-filtering cost per client per tick, and **settle NFR-3**. Already measured: full state at 800v800 on a 4Γ— map is **404 KB / 4.45 ms**, which at 20 Hz Γ— 4 seats is 32 MB/s and 18 ms of a 50 ms budget; the fog-filtered equivalent is **55 KB / 0.69 ms**. Filtering is what makes replication affordable. But 55 KB/snapshot still **exceeds NFR-3's 32 KB/s** at the pathological end | NFR-3, ADR-0009 | T-010 | βšͺ | Snapshot rate and delta-encoding (ADR-0009 M3) chosen on measured numbers; NFR-3 either met or **deliberately restated** |
117
 
docs/analysis/00-feasibility-spikes.md CHANGED
@@ -7,7 +7,7 @@ executable evidence rather than argument.
7
  Both spikes were run on the session container: **4 Γ— Intel Xeon @ 2.10 GHz, 16.9 GB RAM, Node
8
  v22.22.2** β€” deliberately modest hardware, in the same class as a Hugging Face free-tier Space
9
  (2 vCPU). Numbers below should be read as *indicative of*, not measured on, the real target; the
10
- Space-hardware re-run is task **T-013** in [`TASKS.md`](../../TASKS.md).
11
 
12
  ---
13
 
@@ -111,7 +111,7 @@ At 20 Hz the wall-clock budget is **50 ms per tick**. A match consuming *x* ms p
111
  (see ADR-0009), and where the next measurement should go.
112
 
113
  ### Follow-on measurements needed
114
- - **T-013:** re-run both spikes on the actual Space hardware.
115
  - Cost of `serializeGame`/fog-filtering per client per tick β€” likely dominant; measure before
116
  choosing a replication strategy.
117
  - Memory per match (drives the concurrent-match ceiling as much as CPU does).
@@ -121,4 +121,4 @@ At 20 Hz the wall-clock budget is **50 ms per tick**. A match consuming *x* ms p
121
  ## Reproducing
122
  Both spikes live in the session scratchpad rather than the repo, because they are throwaway
123
  evidence, not shipped code. The stress harness is worth re-creating as a committed benchmark under
124
- `tools/` once the server exists β€” task **T-013**.
 
7
  Both spikes were run on the session container: **4 Γ— Intel Xeon @ 2.10 GHz, 16.9 GB RAM, Node
8
  v22.22.2** β€” deliberately modest hardware, in the same class as a Hugging Face free-tier Space
9
  (2 vCPU). Numbers below should be read as *indicative of*, not measured on, the real target; the
10
+ Space-hardware re-run is task **T-014** in [`TASKS.md`](../../TASKS.md).
11
 
12
  ---
13
 
 
111
  (see ADR-0009), and where the next measurement should go.
112
 
113
  ### Follow-on measurements needed
114
+ - **T-014:** re-run both spikes on the actual Space hardware.
115
  - Cost of `serializeGame`/fog-filtering per client per tick β€” likely dominant; measure before
116
  choosing a replication strategy.
117
  - Memory per match (drives the concurrent-match ceiling as much as CPU does).
 
121
  ## Reproducing
122
  Both spikes live in the session scratchpad rather than the repo, because they are throwaway
123
  evidence, not shipped code. The stress harness is worth re-creating as a committed benchmark under
124
+ `tools/` once the server exists β€” task **T-014**.
test/ailab.test.js CHANGED
@@ -133,12 +133,24 @@ test("the tech bot climbs past the Barracks and fields more than Skiffs β€” the
133
  test("an overrides row reaches the sim β€” a strategy that never initiates commits no waves", () => {
134
  // The seam the whole search loop rests on: STRATEGIES is a plain object read through
135
  // strategyFor(), so writing a row into it before a run IS the experiment.
136
- applyOverrides({ strategies: { labPacifist: { neverInitiates: true } } });
137
- assert.ok(STRATEGIES.labPacifist, "applyOverrides must add the row to the live table");
138
- const pacifist = run(short({ strategy: "labPacifist", world: "korrath", minutes: 12 }));
139
- const baseline = run(short({ strategy: "default", world: "korrath", minutes: 12 }));
140
- assert.equal(pacifist.waves, 0, "a neverInitiates strategy must commit zero waves");
141
- assert.ok(baseline.waves > 0, "the korrath baseline should commit at least one wave in 12 minutes");
 
 
 
 
 
 
 
 
 
 
 
 
142
  });
143
 
144
  test("applyOverrides merges into an existing row rather than replacing it", () => {
 
133
  test("an overrides row reaches the sim β€” a strategy that never initiates commits no waves", () => {
134
  // The seam the whole search loop rests on: STRATEGIES is a plain object read through
135
  // strategyFor(), so writing a row into it before a run IS the experiment.
136
+ //
137
+ // snapshotTables/restoreTables, same as the very next test below: applyOverrides writes
138
+ // straight into the LIVE shipped table with no undo of its own, and this test used to have
139
+ // none either β€” labPacifist stayed in STRATEGIES for the rest of the file, an inert but real
140
+ // leak (nothing else selects strategy "labPacifist", so no other test's result was affected β€”
141
+ // unlike the aggressive.garrisonMult leak the next test's own comment documents, which DID
142
+ // corrupt 21 later tests before it was caught).
143
+ const snap = snapshotTables();
144
+ try {
145
+ applyOverrides({ strategies: { labPacifist: { neverInitiates: true } } });
146
+ assert.ok(STRATEGIES.labPacifist, "applyOverrides must add the row to the live table");
147
+ const pacifist = run(short({ strategy: "labPacifist", world: "korrath", minutes: 12 }));
148
+ const baseline = run(short({ strategy: "default", world: "korrath", minutes: 12 }));
149
+ assert.equal(pacifist.waves, 0, "a neverInitiates strategy must commit zero waves");
150
+ assert.ok(baseline.waves > 0, "the korrath baseline should commit at least one wave in 12 minutes");
151
+ } finally {
152
+ restoreTables(snap);
153
+ }
154
  });
155
 
156
  test("applyOverrides merges into an existing row rather than replacing it", () => {