Harden the AI auto-play path now that it drives live bots (#116)

PR #112 re-exported moveAI so the platform could drive bot players with it, and
boardgamers has since switched bots on for Power Grid (the descriptor now reads
meta.bots: true). That promoted moveAI from an internal helper -- reached only
when a player timed out -- to a hot production path. Three things it was not
ready for, all found by reading it from that new seat:

- engine.ts: the Building-phase capacity sum used reduce() with no initial
  value, so a player holding no power plants threw "Reduce of empty array with
  no initial value" instead of scoring zero capacity.

- engine.ts: picking the cheapest Build / the smallest UsePowerPlant sorted
  availableMoves IN PLACE. That array is player.availableMoves -- part of the
  game state, and served to clients -- so choosing a move quietly rewrote the
  order players are shown. Both now sort a copy.

- engine.ts: a per-move console.log('ai move', ...) shipped to production. Bots
  move roughly every 1.5s, so this writes a log line per bot per turn into the
  platform's log pipeline. Removed; it was also the only console.log left in the
  engine's move path.

- wrapper.ts: dropPlayer auto-plays through moveAI in `while
  (G.currentPlayers.includes(playerNum))`, an unbounded loop. A state moveAI
  cannot advance would spin a game-server worker forever at 100% CPU with no
  request ever returning. Now capped at MAX_AUTO_MOVES (1000, orders of
  magnitude above any legitimate turn) and throws a diagnostic instead: a thrown
  error is recoverable and greppable, a hung worker is neither. This matters
  more now that the platform auto-drops inactive players.

Checked and NOT changed: every availableMoves key moveAI reads is length-guarded
at the source (available-moves.ts Build :576, UsePowerPlant :695,
ChoosePowerPlant :145, DiscardResources :85), so there is no empty-array hazard
there. DiscardPowerPlant :62 is the one unguarded assignment, but it can never
be empty -- countHeldPowerPlants excludes Australia mines, so the >3 threshold
guarantees at least three candidates survive the filter.

Tests: 69 specs (+3), tsc clean, eslint unchanged at 0 errors / 30 warnings.
The two new regression specs were teeth-checked against the pre-fix engine --
the empty-plants one fails with the exact TypeError, the ordering one fails on
"the stored Build list keeps its original order". The ordering spec also asserts
its own setup is not already price-sorted, so it cannot silently lose its teeth.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
goldjohn6 2026-08-14 09:06:48 -07:00 • committed by GitHub
commit 0a15decdf2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 91 additions and 4 deletions

View file

@ -1,5 +1,6 @@
import { expect } from 'chai';
import 'mocha';
import { dropPlayer } from '../wrapper';
import { availableMoves, computeRegionGraph, regionPickable } from './available-moves';
import {
addPowerPlant,
@ -1774,4 +1775,68 @@ describe('Engine', () => {
expect(playOut()).to.deep.equal(playOut());
});
// moveAI stopped being an internal-only helper when the platform started driving
// live bot players through it (engine/index.ts re-export). These guard the two ways
// it could hurt a real game from that seat.
it('should let moveAI build for a player holding no power plants', () => {
// Regression: the capacity sum used reduce() with no initial value, so an empty
// powerPlants array threw "Reduce of empty array with no initial value" — killing
// the bot / dropped-player turn instead of scoring zero capacity.
const G = setup(3, { map: 'Germany' }, 'ai-build-no-plants');
G.phase = Phase.Building;
G.currentPlayers = [0];
const player = G.players[0];
player.powerPlants = [];
player.availableMoves = availableMoves(G, player);
expect(() => moveAI(G, 0)).to.not.throw();
});
it('should not reorder the stored available moves when moveAI picks one', () => {
// availableMoves lives on the game state and is served to clients; sorting it in
// place to find the cheapest option silently rewrote what players are shown.
const G = setup(3, { map: 'Germany' }, 'ai-build-no-sort');
G.phase = Phase.Building;
G.currentPlayers = [0];
const player = G.players[0];
// A network makes build prices vary with distance; without one every city costs
// the same opening slot price and an in-place sort would be undetectable.
player.money = 200;
player.cities = [{ name: G.map.cities[0].name, position: 0 }];
// Hold a plant so this test exercises the sort rather than tripping the
// empty-reduce covered by the test above.
player.powerPlants = [getPowerPlant(4)];
player.availableMoves = availableMoves(G, player);
const stored = player.availableMoves[MoveName.Build]!;
const before = stored.map((c) => c.name);
const prices = stored.map((c) => c.price);
// Without this the test could pass on a list that was already price-ordered.
expect(
prices.some((p, i) => i > 0 && p < prices[i - 1]),
'the natural city order is not already sorted by price, so an in-place sort would show'
).to.be.true;
moveAI(G, 0);
expect(
stored.map((c) => c.name),
'the stored Build list keeps its original order'
).to.deep.equal(before);
});
it('should finish dropping a player whose turn has no Pass available', async () => {
// Round 1 forces a purchase, so dropPlayer cannot simply Pass — it auto-plays
// through moveAI in a loop. Guards that the loop still terminates (it is now
// bounded by MAX_AUTO_MOVES rather than running forever on a stuck state).
let G = setup(3, { map: 'Germany' }, 'drop-no-pass');
const dropped = G.currentPlayers[0];
expect(G.players[dropped].availableMoves![MoveName.Pass], 'round 1 offers no Pass').to.be.undefined;
G = await dropPlayer(G, dropped);
expect(G.currentPlayers, 'the dropped player is no longer on the clock').to.not.include(dropped);
expect(G.players[dropped].isDropped).to.be.true;
});
});

View file

@ -2147,10 +2147,14 @@ export function moveAI(G: GameState, playerNumber: number): GameState {
}
case Phase.Building: {
const capacity = player.powerPlants.map((pp) => pp.citiesPowered).reduce((a, b) => a + b);
// Seed the sum: reduce() with no initial value throws on an empty array, so a
// plant-less player would crash the auto-play path instead of scoring zero capacity.
const capacity = player.powerPlants.map((pp) => pp.citiesPowered).reduce((a, b) => a + b, 0);
if (availableMoves?.Build && (player.money >= 30 || capacity > player.cities.length)) {
const minPrice = availableMoves.Build.sort((a, b) => a.price - b.price)[0].price;
// Sort a copy: `availableMoves` is `player.availableMoves`, which lives on the
// game state and is served to clients — choosing a move must not reorder it.
const minPrice = [...availableMoves.Build].sort((a, b) => a.price - b.price)[0].price;
const cheapestCities = availableMoves.Build.filter((x) => x.price == minPrice);
chosenMove = { name: MoveName.Build, data: chooseRandom(cheapestCities) };
}
@ -2162,7 +2166,8 @@ export function moveAI(G: GameState, playerNumber: number): GameState {
if (availableMoves?.UsePowerPlant && player.cities.length > player.citiesPowered) {
chosenMove = {
name: MoveName.UsePowerPlant,
data: availableMoves.UsePowerPlant.sort((a, b) => a.citiesPowered - b.citiesPowered)[0],
// Sorted on a copy, for the same reason as Build above.
data: [...availableMoves.UsePowerPlant].sort((a, b) => a.citiesPowered - b.citiesPowered)[0],
};
}
@ -2170,7 +2175,6 @@ export function moveAI(G: GameState, playerNumber: number): GameState {
}
}
console.log('ai move', chosenMove);
// Stamp the move so the per-player clocks keep advancing across auto-played
// turns (bots, and dropped players auto-played by dropPlayer). Without this the
// clock chain breaks: no clock starts, so the next human to move sits on an

View file

@ -77,6 +77,11 @@ export function round(G: GameState): number {
return G.round;
}
// Ceiling on the moves auto-played for one dropped player's turn. Real turns resolve in
// a handful — the longest is a Resources phase bought one cube at a time — so this sits
// orders of magnitude above any legitimate turn and only ever trips on a stuck state.
const MAX_AUTO_MOVES = 1000;
export async function dropPlayer(G: GameState, playerNum: number): Promise<GameState> {
const player = G.players[playerNum];
player.isDropped = true;
@ -89,7 +94,20 @@ export async function dropPlayer(G: GameState, playerNum: number): Promise<GameS
if (player.availableMoves![MoveName.Pass]) {
G = engine.move(G, { name: MoveName.Pass, data: true }, playerNum);
} else {
let autoMoves = 0;
while (G.currentPlayers.includes(playerNum)) {
if (++autoMoves > MAX_AUTO_MOVES) {
// A state moveAI cannot advance would otherwise spin this loop forever,
// pinning a game-server worker at 100% CPU with no request ever
// returning. Fail loudly instead: a thrown error is recoverable and
// diagnosable, a hung worker is neither.
throw new Error(
`dropPlayer: player ${playerNum} is still current after ${MAX_AUTO_MOVES} auto-played ` +
`moves (phase ${G.phase}, round ${G.round}) — aborting to avoid an infinite loop`
);
}
G = engine.moveAI(G, playerNum);
}
}