# BotArena — standalone, parallel bot-vs-bot duels (TICKET-035)
Runs hundreds (thousands) of WindBot-vs-WindBot duels from a terminal with **no
Unity in the loop**, using exactly the code the game ships: the `YGOLegacy.Bots`
library (WindBot, the fork's SmartExecutor brain, the character registry) and
the engine release `engine.json` pins. Same JSON report as the in-editor Bot
Arena (TICKET-030), so anything that reads `Data/BotArena/*.json` reads either.
Linux (`linux-x64`) and Windows (`win-x64`).
Two duel hosts, `--host local` (the default) and `--host server`:
| | `local` (TICKET-045) | `server` (TICKET-035) |
|---|---|---|
| what runs the duel | `YGOLegacy.Bot.LocalDuelHost` — the engine library driven from this process | the engine's `start_server`, one room per worker |
| platforms | Linux and Windows | **Windows only** (on Linux the server finds no cards: it reads `./expansions` and `./script`, which a Windows game root matches only because its file system ignores case; the arena refuses it) |
| transport | none: a loopback seam into `BinaryClient` | TCP on 127.0.0.1 |
| threads per worker | one (host + both bots + both brains) | four (server, two bots, the worker) |
| 1000 Weevil duels, 8 workers | **~20 s** (10–40 ms per duel) | ~4 min (~1.6 s per duel) |
| `--replays` | not available (no STOC_REPLAY) | yes |
Measured on the dev machine: **1000 Weevil-vs-Weevil duels, 8 workers, 33 s wall
clock with journals on, 0 errors** (`--host local --n 1000 --parallel 8`). The
same run on `--host server` takes ~4 minutes; the editor arena needs 10–25 s per
duel, serially. Almost all of the old cost was transport — WindBot's 500 ms
end-of-duel pause, the per-duel server start/stop, and the bot threads polling
their sockets — none of which the in-process host has.
## Build
The repo's `Dockerfile` publishes both builds self-contained (`docker build --target dist -o out .` ->
`out/bot-arena-linux-x64/BotArena`, `out/bot-arena-win-x64/BotArena.exe`), each with the pinned engine's native
library and C# binding next to the exe. With a dotnet 8 SDK: `build/fetch-engine.sh`, then
`dotnet publish src/BotArena -c Release -r win-x64 --self-contained` (or `linux-x64`). The release ships both
(`bot-arena-linux-x64.tar.gz`, `bot-arena-win-x64.zip`).
## Run
```
BotArena --deckA "Duelist Kingdom/Weevil Underwood DK" ^
--deckB "Duelist Kingdom/Weevil Underwood DK" ^
--execA Smart --execB Lucky --n 100 --parallel 8 --seed 1 ^
--out C:\tmp\arena.json
```
Run it from a game root (the Unity project or a built game), or pass `--root
`: `Deck/`, `Data/` and
`Expansions/` are resolved under it, and the working directory of every worker IS the root (the server reads
`./expansions`, `./script` and writes `./replay`, `./error.log` there). The root must be writable: the report
goes to `Data/BotArena/`. The engine library is the first found of `$YGOL_ENGINE_DLL`, the root's
`Assets/Plugins/Windows/ygol-engine.dll` (Linux: `Assets/Plugins/Linux/libygol-engine.so`), a built player's
plugin folder, and the copy next to the exe.
| Option | Meaning |
|---|---|
| `--deckA/--deckB "group/name"` | Deck/ path without `.ydk` (root-group decks: just `name`); `Data/Windbot/Decks/` names work too. Required. |
| `--execA/--execB Smart\|Lucky\|…` | force the seat's WindBot executor (rewrites the `Deck=` token). Default: the deck's own brain (the owning character's `brain.executor`, else Dovphin/Lucky). |
| `--n 200` | duels (default 10) |
| `--parallel 8` | worker processes (default 1) |
| `--seed 1` | base of every per-duel seed. Each Smart seat gets `seed*1000 + duel*2 + seat` for its decision noise; the duel itself (deck shuffle, `create_duel`, WindBot's `Program.Rand`) gets `ArenaReport.CoreSeedFor` = `(seed*7919 + duel*104729) & 0x7fffffff \| 1`. Both depend on the duel INDEX only, so `--host local` replays the same duels for the same command line — see "Repeatability" below. `0` = nothing is seeded (brains seed themselves, the run is not repeatable). |
| `--timeout 300` | per-duel timeout in seconds |
| `--out file.json` | extra copy of the report (the canonical one always lands in `Data/BotArena/`) |
| `--replays dir` | save every duel's `.yrp` as `duel-0001.yrp`, … **`--host server` only** — the in-process host is not a ygoserver and never sends STOC_REPLAY, so a `local` run warns and writes nothing. |
| `--journal dir` | SmartExecutor decision journal (TICKET-036): `duel-0001-A.jsonl` per **Smart** seat (Lucky seats write nothing) + `run.json` (the run's config and seat commands). Feed the dir to the Unity repo's `python .claude/skills/bot-brain/blunders.py `. Kinds are listed at the top of the journal region in `SmartExecutor.cs`; 2026-08-18 added `flipHeld` (a Flip Summon the executor chose NOT to take, with its reason — deduped per card + turn) and the `positionWhy: "flip default set"` value on `summon`/`set` lines, plus `positionWhy: "flip from hand beats weak body"` when a weak face-up summon was held so a FLIP monster could be Set instead. |
| `--port 7920` | first server port; worker *k* starts at `port + 4k` and takes the next free one (`--host server` only) |
| `--locale en-US` | `Data/locales//` for `cards.cdb` and `bot.conf` |
| `--knobsA/--knobsB "name=value,..."` | per-seat SmartExecutor knob overrides, applied ON TOP of that deck brain's knobs (and the group's) — e.g. `--knobsA "lookahead=8,lookaheadTurns=6"`. Lets one deck be measured at two settings without editing `brain.json`. Setting `lookahead` above 0 also installs the perfect-information rollout oracle for that seat (TICKET-050; `--host local` only). |
| `--decisionsA/--decisionsB ` | the decision maker that answers that seat's prompts instead of its executor (the decision seam, repo README): `random`, or a name a plug-in registered. Appends `Decisions=` to the seat's command (so the report records it). Default: the executor. |
| `--host local\|server` | which duel host plays the duels. `local` (default) = the engine's core in-process (TICKET-045); `server` = the engine's server over a TCP loopback, kept for A/B, Windows only. |
| `--insightA/--insightB ` | force that seat's duel-state-bus insight (TICKET-042), overriding the deck brain's `insight` knob. Default: the knob (none). Recorded in the report's `config.insightA/insightB`; at `hand` or above the journal's `turn` lines gain `enemyHandKnown` (the enemy's real hand ids). Both bots of a duel run in this process, so each mirrors the other's stream. |
| `--verbose` | `[YGOL bot]` decision logging on for every Smart seat (sets `SmartExecutor.Verbose`; no `verbose: 1` knob needed — the executor is otherwise muted for the run). Lines land in the worker logs. |
Exit codes: **0** at least one duel played, **1** none played (bad deck, no
worker could start, …), **2** bad arguments. The one-line summary is printed
last (`Weevil A 56 - 44 Weevil B (0 errors, avg 12.8 turns, 0m54s) -> Data/BotArena/…json`);
progress lines go to stderr.
Per-worker logs (WindBot chatter, `[YGOL bot]` lines, ygoserver's own output)
land in `Data/BotArena/logs/run--/worker-N.log` (one folder per run, so concurrent runs are safe; `-rK` suffix for a respawned worker).
### Report
`Data/BotArena/--vs-.json`, the editor arena's
schema exactly (`config`, `nameA/B`, `commandA/B`, `winsA/B`, `draws`,
`errors`, `completed`, `totalSeconds`, `averageTurns`, `summary`, `status`,
`duels[]` with `winner`, `winnerName`, `turns`, `durationSeconds`, `error`,
`verdictA/B`, `seedA/B`, `Played`) plus two trailing fields: `workers` and
`wallClockSeconds`. `totalSeconds` is the run's wall clock too;
`durationSeconds` per duel is that duel's own clock (server start → teardown).
The model and the helpers that fill it (`Summary`, `SeatCommand`, `Resolve`,
`Tally`) are ONE file of the library, shared with the game's in-editor arena:
`src/YGOLegacy.Bots/Bot/ArenaReport.cs`.
## How it works
```
BotArena (parent)
├─ validates decks the way WindBot's Program.ReadFile resolves DeckFile=
├─ CharacterRegistry.LoadFromDisk + Data/locales//bot.conf → BotRoster.ForDeck
│ → seat names " A"/" B" + WindBot commands (ArenaReport.SeatCommand)
├─ spawns --parallel copies of ITSELF with --worker k (ProcessStartInfo.ArgumentList)
├─ hands each idle worker one duel index over stdin (dynamic scheduling)
├─ reads one JSON line per duel from the worker's stdout, tallies, prints progress
├─ a dead worker's duel is re-queued once and a replacement worker is started
└─ writes the report, prints the summary, kills what is left (try/finally)
BotArena --worker k (one duel at a time)
├─ cwd = root
├─ once: ArenaHost.Install (BotHost), characters, bot.conf, WindBot.Program.InitDatas
│ (cards.cdb + every .cdb inside Expansions/*.ypk, extracted to /YGOLBotArena/cdb/,
│ + Expansions/*.cdb), then per --host: LocalHost.Install (engine + readers) or YgoServer.Locate
└─ per duel: Worker.RunOneLocal / Worker.RunOneServer (below)
→ ArenaReport.Resolve → {"type":"duel","record":{…}} on stdout
```
**`--host local` (`Worker.RunOneLocal`)** — one thread, no server, no sockets:
```
1. two seats, built strictly one after the other (WindBot.Config and the
SmartExecutor seed/journal statics are process-global and are consumed inside
the GameBehavior constructor):
Bot.PrepareInfo(command) → new GameClient(info) → new LoopbackBotSeat(...)
LoopbackBotSeat calls the [YGOL] GameClient.YGOL_StartLoopback: same
GameBehavior, same SmartExecutor, same DuelStateBus tap — but Send() lands in
an outbox instead of a socket and the host injects STOC packets directly.
2. WindBot.Game.Deck.Load for each seat (the same list the bot uploads).
3. YGOLegacy.Bot.LocalDuelHost.Run():
room handshake (JoinGame → TypeChange → HsPlayerEnter/Change → RPS/TP →
DuelStart) so _room.Position / _room.Names / Duel.IsFirst are right
create_duel → set_player_info ×2 → shuffled new_card ×N → MSG_START →
start_duel(opt 0x50000 = master rule 5) → loop process()/get_message():
split the batch into messages, route each one (broadcast / one player /
prompt), blank what that recipient may not see, inject, let the seat
answer inside its own packet handler, set_responseb.
4. the verdict is the usual GameBehavior.YGOL_DuelResult from MSG_WIN.
```
**`--host server` (`Worker.RunOneServer`)** — the TICKET-035 path, unchanged:
```
1. free port from base → start_server(" -1 5 0 F F F 8000 5 1 180 0") on a
thread (identical args to MultiplayerService.HostLocal); wait until it accepts
2. bot A: Config.Load(args) → GameClient(...).Start() on the worker thread (so the
process-global WindBot.Config, SmartExecutor.SeedOverride and SmartExecutor.JournalPath
are consumed before B's), tick loop on its own thread; wait for the socket; then bot B
the same way
3. both bots auto-ready, the host bot sends HsStart; wait for both YGOL_DuelResult
verdicts (or one + 5 s, or both sockets/server gone + 3 s, or --timeout)
4. teardown: let the server leave on its own (it stops itself after DuelEnd),
stop_server() only if it is still up, join the bot threads
```
Why processes and not threads: `WindBot.Config`, `WindBot.Program.Rand`,
`NamedCardsManager` and `SmartExecutor.SeedOverride` are process-wide statics
(that is also why the editor arena is serial). Why the server is not an exe:
the game's ygoserver is a DLL (`MDPro3.Net.YgoServer` P/Invokes
`start_server`/`stop_server`); we do the same, so a worker's exit takes its
server with it — there is no orphan `ygoserver` process to kill.
### Duel state bus (TICKET-042)
Both bots are `GameClient`s in this process, so the `[YGOL]` tap in
`GameClient.OnPacketReceived` publishes each seat's raw packets to
`YGOLegacy.Bot.DuelStateBus` (linked into this project), which mirrors them with
WindBot's own parser. That is how `--insightA/--insightB` can hand a brain the
other seat's hand. The bus is **off** until a brain resolves an insight level
above `none`, and the worker calls `DuelStateBus.Reset()` before every duel, so a
normal measurement run allocates nothing extra and behaves byte-for-byte as before.
### The in-process host (TICKET-045)
`YGOLegacy.Bot.LocalDuelHost` (`src/YGOLegacy.Bots/Bot/`, Unity-free, also
run by the game) is ygoserver's duel loop rewritten in C# for exactly two
seats and one duel, and `LoopbackBotSeat` is the WindBot adapter.
* **Where the byte layouts come from.** `Percy.Ygopro.Analyse`
(the game's `Assets/Scripts/MDPro3/Duel/CoreWrapper.cs`) is the fork's own single-seat
host and already encodes the length of every `MSG_*` and how to blank hidden
information; `LocalDuelHost.Scan` is that switch, message for message, plus
the ones a single-seat client never sees. An unknown message id throws rather
than desyncing the batch — the duel is recorded as an error and the id is
named in it.
* **What each seat is allowed to see.** Prompts (`SELECT_*`, `ANNOUNCE_*`,
`SORT_*`, `ROCK_PAPER_SCISSORS`) go to one player and block; `MSG_HINT` types
1/2/3/5 go to the hinted player, the rest is public; everything else is
broadcast. Blanked: `MSG_DRAW` and `MSG_SHUFFLE_HAND`/`SHUFFLE_EXTRA` (codes
to the owner, zeros to the opponent), `MSG_SET` (code to nobody) and
`MSG_MOVE` (a card that lands in a deck/hand or face-down keeps its code for
its NEW CONTROLLER and loses it for the other seat — you know the monster you
just set). Refreshes (`MSG_UPDATE_DATA`) re-query every zone for both players:
face-down monsters/spells collapse to an empty record for the opponent, hands
and extra decks lose their codes.
* **Card data** is not read a second time: WindBot's `NamedCardsManager` is
already loaded with the same cdbs in the same order, and
`YGOSharp.OCGWrapper.Card.Data` is that row in ocgcore's `card_data` shape, so
the core and the brains cannot disagree about a card
(`LocalHost.ReadCard`). **Scripts** resolve in the game's order
(`LocalHost.ReadScript`): loose `Expansions/script/`, then the `script/`
entries of each `Expansions/*.ypk|*.zip`, then `Data/script.zip` — which is
what keeps the loose `Expansions/script/procedure.lua` override in charge.
* **Duel options** are `0x50000` (master rule 5, LP 8000, 5 cards, draw 1),
read off a real ygoserver duel's replay header, not guessed.
* **Two `[YGOL]` seams**, both additive: `BinaryClient.{YGOL_SendHook,
YGOL_Inject,YGOL_MarkConnected}` and `GameClient.{YGOL_StartLoopback,
YGOL_Receive}`. Everything else — `GameBehavior`, `SmartExecutor`, the
journal, `DuelStateBus`, `YGOL_DuelResult`, `YGOL_Replay` — is untouched, and
the injected packets go through `OnPacketReceived`, so the bus taps still see
them.
* **Not covered**: tag duels (`MSG_TAG_SWAP`), `MSG_RELOAD_FIELD` (puzzles),
match/side decking, spectators, replays. Those throw or are absent; single
duels never produce them.
### Rollout lookahead (TICKET-050, prototype)
`--knobsA "lookahead=N"` switches a Smart seat from "answer the idle prompt with
the executor list's first preference" to "enumerate the executor's top
`lookaheadCandidates` (default 4) preferences, play each of them out `N` times,
and blend the rollout win rate into the choice". It is **off by default and off
in the game**: the knob does nothing without an `ILookaheadOracle`, and the only
implementation of that interface is `src/BotArena/ReplayOracle.cs`.
How a rollout is possible at all: ocgcore cannot clone a live duel, but this
arena's per-duel seed drives BOTH `create_duel` and the host's own deck shuffle,
so a fresh `LocalDuelHost` with the same seed deals the identical game. The
oracle replays every answer both seats have given so far
(`LocalDuelHost.Options.ScriptedResponses`, recorded by `RecordResponses`),
imposes the same turn order (`ForcedFirstSeat` — rock-paper-scissors is answered
from WindBot's RNG, not from the response log), answers the prompt under test
with the candidate, and lets two Lucky bots play on to
`StopAfterTurn = turn + lookaheadTurns`.
**It peeks.** The copy is dealt from the same shuffle, so the rollouts see the
enemy's hand and both deck orders. That is the point: it measures the CEILING of
rollout planning on this engine. A shippable version would have to rebuild the
public state and sample the hidden part instead (Phase B in the ticket).
Knobs (all read once, at executor construction):
| knob | default | meaning |
|---|---|---|
| `lookahead` | 0 | rollouts per candidate; 0 = off, and the whole feature is inert |
| `lookaheadCandidates` | 4 | how many of the executor's own preferences to consider |
| `lookaheadTurns` | 6 | horizon; 0 = play every rollout to MSG_WIN |
| `lookaheadWeight` | 1.0 | `score += weight * (winRate - 0.5) * 2000` |
| `lookaheadRankPoints` | 300 | what one place of the executor's own preference order is worth, since the walk yields an ORDER and not a score |
| `lookaheadMs` | 1500 | wall-clock ceiling per decision (all candidates together) |
Cost, measured on Weevil DK: a plain duel is ~6 ms; at `lookahead=8` it is
~14 s of CPU (one rollout ≈ 21 ms, ~20 planned decisions per duel, up to 32
rollouts each). `--verbose` prints one `lookahead:` line per planned decision
with every candidate's rollout value and blended score, and the worker log gets a
`lookahead seat A duel N: R rollouts, X abandoned, T ms` summary per duel.
The two seams this needed, both `[YGOL]`-tagged and both inert without a planner:
`GameAI.OnSelectIdleCmd` now delegates to `YGOL_WalkIdle(main, allow)` (its own
original body plus an "is this action allowed" predicate checked where it used to
`return`), and `SmartExecutor` implements `YGOLegacy.Bot.IIdlePlanner`.
Verified: `Weevil DK Smart vs Lucky --seed 7 --n 1000` gives 654-346 and
`avg 12.924` turns both before and after the change, with **0 of 1000 duels
differing**.
### Differences from the editor arena
* No observer/spectator client, no duel scene, no replay auto-save by the game;
the bots' own MSG_WIN (`GameBehavior.YGOL_DuelResult`) is the whole verdict.
Turn count = max of the two verdicts' turns (no `OcgCore.turns` backstop).
* `.yrp` files come from `GameBehavior.YGOL_Replay` (STOC_REPLAY as the server
sent it to the players), only with `--replays` and only on `--host server`.
* On `--host server` the bots tick on their own threads (1 ms, adaptive); on
`--host local` there are no bot threads at all — the host ticks each client
inline and the answer is in the outbox when the tick returns.
* Card databases: WindBot's `InitDatas` is run ONCE per worker, not once per
bot as `WindBot.Program.Main` would.
## What the arena gives the bots (`ArenaHost.cs`)
The library reaches its host only through `YGOLegacy.Bots.BotHost` (the repo README has the contract).
`ArenaHost` is the arena's side of it:
| `BotHost.` | The arena |
|---|---|
| `Log` | stderr, which the parent writes to the worker log |
| `Cards` | `Microsoft.Data.Sqlite`, read-only and shared (several workers open the same `.cdb`) |
| `Files` | `--locale`; the `.cdb` files of `Expansions/*.ypk`, extracted by `Setup.ExtractZipCdbs` |
| `BotConf` | `Data/locales//bot.conf`, parsed by `Setup.ReadBots` (the game's reader, minus the deck covers) |
| `DeckLimits` | the library default, 60 / 99 / 15: the arena has no rulesets and no `config.conf` |
## Caveats
* **Repeatability: `--host local` with `--seed N` (N ≠ 0) is deterministic; one
run is still one sample.** Three streams used to be unseeded and are now all
derived from (`--seed`, duel index) — the host's own deck shuffle and
ocgcore's `create_duel(seed)` (`LocalDuelHost.Options.Seed`), and WindBot's
process-global `Program.Rand`, reseeded before every duel (rock-paper-scissors,
`LuckyExecutor`'s coin flips, every `Rand.Next` inside a deck executor). The
index, not the worker, is the input, so `--parallel 1` and `--parallel 8` give
the same duels. Verified 2026-08-16: two back-to-back `--n 300 --seed 7` runs
on Weevil DK, and a third at `--parallel 7`, all `187 - 113`, `avg 13.177`
turns, identical winner and turn count for every duel index; and 2 × 500 duels
on each of Weevil DK, Yuma Zxl, Alister ORI, Modern/Pegasus, Yugi BC and Zane
GX — **0 differing duels out of 500** on all six.
**One known exception, and it is not the seeding.** `Zexal/Kite Tenjo Zxl`
diverges in 3–5 duels per 500 (~0.8 %), at `--parallel 1` as much as at
`--parallel 4`, so it is not scheduling and not cross-duel leakage: it is
address-space dependent behaviour below us (the engine's core iterates some
containers of pointers, and heap addresses move with ASLR). The same deck is
the only one of the seven that also throws a `NullReferenceException` mid-duel
(4 duels per 500) — the errored duel indices ARE stable across runs, so the
two are separate. Practical effect: on such a deck a pooled 2000-duel figure
can wobble by ~2 duels (0.1 points). If a deck's A/B refuses to reproduce,
check its `errors` count before blaming the change.
What this buys is a **paired A/B**: two binaries (or two brain.json files) on
the same seed face the identical openings, so the difference between them is
the change. What it does not buy is a smaller error bar on a single number —
1000 duels are still one draw, so the deck's true win rate still carries the
usual ±3 points at `--n 1000`. Use a **second seed** to see that spread and
quote the pooled figure (sum `winsA` and `completed` across the reports);
before the fix the same command line gave **63.0 % and 68.0 %** on Weevil DK.
`--seed 0` pins nothing and is not repeatable, as before. `--host server` is
never repeatable: the engine's server shuffles the decks itself with a seed this
process cannot reach (the per-duel `Program.Rand` reseed still happens there,
so at least no state leaks from the previous duel).
* **A duel that ends in `error` is not measured — check `errors` before trusting a
deck's number.** Three shapes, all seen:
* **MSG_RETRY** (the core rejected a bot's answer). The message NAMES what was
rejected — `prompt 11 SELECT_IDLECMD, seat 0, answer 07 00 00 00 (int32 7 =
idle command ToEndPhase index 0)` — because `LocalDuelHost` records the last
prompt and the last answer and reads them back before handing the packet to
the seat (WindBot's own `OnRetry` throws first otherwise, and its
"Last message is SelectIdleCmd" says nothing about WHICH command). That is
how the one known instance was found and fixed (`GameAI.OnSelectIdleCmd`
answered `ToEndPhase` without checking `CanEndPhase`): `Orichalcos/Leon
Wilson ORI` went from 85-86 errors per 1000 to **0**.
* **`turn limit reached (200)`** — a handful of boards never resolve. About
3-5 % on `5Ds/Misty Tredwell 5Ds` and `Zexal/Quattro Zxl`; expected, see
`LocalDuelHost.Options.TurnLimit`.
* **`message limit reached`** — a prompt the core keeps re-asking.
**`Orichalcos/Valon ORI` hits this in 171 of 200 duels** (measured
2026-08-16), so that deck cannot currently be measured at all. Not
diagnosed; the first step is a `--verbose` run of one failing duel index.
* The tool only READS `Deck/`, `Expansions/`, `Puzzle/` (on a designer's machine,
junctions into the Syncthing share). Reports go to `Data/BotArena/`, replays
wherever `--replays` says, the cdb cache to the temp folder.
* The engine's server writes `error.log` and `replay/` in the root, as the game does
(`--host server` only; the in-process host writes nothing outside
`Data/BotArena/`).
* Both hosts use the same process-global statics, so it is still ONE duel per
worker process — including ocgcore's `set_card_reader`/`set_script_reader`,
which are installed once per worker.
* `--host server` only: very rarely the DLL aborts a worker on teardown (a libevent assertion when a
`stop_server` races the server's own post-duel shutdown). The parent
re-queues that duel and starts a replacement worker, so the run still
completes; the crash is visible in the worker log.
* One `.yrp` per duel is 0.5–1 KB (LZMA); the server caps the buffer it sends
at 8 KB, so an extremely long duel's replay may be truncated by the server.