poker-flopsolve 0.5.0-beta.0 → 0.5.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +142 -0
- package/README.md +316 -27
- package/dist/browser-threads.js +42 -18
- package/dist/browser-threads.js.map +1 -1
- package/dist/browser.js +2187 -229
- package/dist/browser.js.map +1 -1
- package/dist/engine-worker.js +50 -19
- package/dist/engine-worker.js.map +1 -1
- package/dist/index.d.ts +423 -46
- package/dist/index.js +2247 -234
- package/dist/index.js.map +1 -1
- package/dist/threads.d.ts +4 -2
- package/dist/threads.js +54 -1
- package/dist/threads.js.map +1 -1
- package/dist/worker.js +215 -123
- package/dist/worker.js.map +1 -1
- package/docs/APPROXIMATIONS.md +22 -0
- package/package.json +6 -3
package/dist/browser-threads.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// src/engine.ts
|
|
2
2
|
var wasm = globalThis.WebAssembly;
|
|
3
|
-
var ENGINE_CONTROL = { generation: 0, done: 1, command: 2, mode: 3, traverser: 4, ready: 5, failed: 6, size: 8 };
|
|
3
|
+
var ENGINE_CONTROL = { generation: 0, done: 1, command: 2, mode: 3, traverser: 4, ready: 5, failed: 6, next: 7, size: 8 };
|
|
4
4
|
|
|
5
5
|
// src/engine-thread.ts
|
|
6
6
|
function serveEngine(setup) {
|
|
@@ -11,6 +11,7 @@ function serveEngine(setup) {
|
|
|
11
11
|
const TRAVERSER = 4;
|
|
12
12
|
const READY = 5;
|
|
13
13
|
const FAILED = 6;
|
|
14
|
+
const NEXT = 7;
|
|
14
15
|
const EXIT = 1;
|
|
15
16
|
const api = globalThis.WebAssembly;
|
|
16
17
|
const memory = setup.memory;
|
|
@@ -26,7 +27,8 @@ function serveEngine(setup) {
|
|
|
26
27
|
engine.init(setup.header);
|
|
27
28
|
engine.setMaxActions(setup.maxActions);
|
|
28
29
|
engine.setExchange(setup.exchange[0], setup.exchange[1], setup.exchange[2], setup.exchange[3]);
|
|
29
|
-
|
|
30
|
+
const [round, boards] = setup.shard;
|
|
31
|
+
engine.setShard(round, 0, 0);
|
|
30
32
|
engine.setPhase(0, 1);
|
|
31
33
|
const shared = setup.shared;
|
|
32
34
|
if (shared) engine.setShared(shared[0], shared[1], shared[2]);
|
|
@@ -37,8 +39,19 @@ function serveEngine(setup) {
|
|
|
37
39
|
const settings = new Float64Array(setup.settings);
|
|
38
40
|
const entries = setup.entryNodes.length;
|
|
39
41
|
const rowBytes = setup.stride * 4;
|
|
40
|
-
const
|
|
42
|
+
const stride = setup.stride;
|
|
41
43
|
const reach = setup.exchange[1];
|
|
44
|
+
const order = new Int32Array(setup.schedule, 0, boards);
|
|
45
|
+
const cost = new Float64Array(setup.schedule, Math.ceil(boards / 2) * 8, 2 * boards);
|
|
46
|
+
const into = setup.boardValues >>> 2;
|
|
47
|
+
const profile = new Float64Array(setup.profile[0]);
|
|
48
|
+
const busy = setup.profile[1];
|
|
49
|
+
const pages = new Uint8Array(memory.buffer);
|
|
50
|
+
if (Atomics.load(control, COMMAND) !== EXIT) {
|
|
51
|
+
for (let r = 0; r < setup.touch.length; r += 2) {
|
|
52
|
+
for (let at = setup.touch[r]; at < setup.touch[r + 1]; at += 4096) pages[at] = 0;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
42
55
|
let generation = Atomics.load(control, GENERATION);
|
|
43
56
|
Atomics.add(control, READY, 1);
|
|
44
57
|
Atomics.notify(control, READY);
|
|
@@ -57,22 +70,33 @@ function serveEngine(setup) {
|
|
|
57
70
|
try {
|
|
58
71
|
engine.setPhase(0, settings[5]);
|
|
59
72
|
if (needsIteration) engine.setIteration(settings[6], settings[7]);
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
73
|
+
const heap = new Float32Array(memory.buffer);
|
|
74
|
+
const started = performance.now();
|
|
75
|
+
for (; ; ) {
|
|
76
|
+
const taken = Atomics.add(control, NEXT, 1);
|
|
77
|
+
if (taken >= boards) break;
|
|
78
|
+
const board = order[taken];
|
|
79
|
+
engine.setShard(round, board, board + 1);
|
|
80
|
+
const boardStarted = performance.now();
|
|
81
|
+
for (let entry = 0; entry < entries; entry++) {
|
|
82
|
+
const slot = reach + entry * 2 * rowBytes;
|
|
83
|
+
const out = engine.runChance(
|
|
84
|
+
mode,
|
|
85
|
+
traverser,
|
|
86
|
+
setup.entryNodes[entry],
|
|
87
|
+
slot,
|
|
88
|
+
slot + rowBytes,
|
|
89
|
+
positive,
|
|
90
|
+
negative,
|
|
91
|
+
sum,
|
|
92
|
+
weight,
|
|
93
|
+
clamp
|
|
94
|
+
) >>> 2;
|
|
95
|
+
heap.copyWithin(into + (board * entries + entry) * stride, out, out + stride);
|
|
96
|
+
}
|
|
97
|
+
if (mode === 0 && settings[5] === 1) cost[traverser * boards + board] = performance.now() - boardStarted;
|
|
75
98
|
}
|
|
99
|
+
profile[busy] += performance.now() - started;
|
|
76
100
|
} catch (error) {
|
|
77
101
|
Atomics.store(control, FAILED, 1);
|
|
78
102
|
throw error;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/engine.ts","../src/engine-thread.ts","../src/platform/browser-threads.ts","../src/platform/browser.ts","../src/threads.ts"],"sourcesContent":["/**\n * The WebAssembly traversal engine, set up.\n *\n * Purpose: lay a prepared spot out in one WebAssembly memory for\n * `assembly/engine.ts`, and give the solver its storage and a root traversal.\n *\n * The engine keeps the accumulators in its own memory as 32-bit floats; the\n * solver's `regret` and `strategySum` are views onto them, so everything that\n * reads storage from JavaScript — strategy queries, warm starts, `valuesAt` —\n * sees the very same numbers. It runs where WebAssembly SIMD is available,\n * on one thread or several; otherwise the JavaScript traversal in cfr.ts\n * runs. A second build, which only `poker-flopsolve/wasm-storage` carries,\n * keeps 16-bit and compact storage the same way (`EngineInput.storage`).\n *\n * WebAssembly memory is one buffer, but Chromium lets it reach wasm32's full\n * 4 GiB, plain or shared, made at that size or grown to it, where it refuses\n * any ArrayBuffer over 2 GiB less 2 MiB (measured in Chromium 153 by\n * bin/memory-ceiling.ts; issue #84). So compact storage needs no chunks of\n * its own in the engine: its chunks are regions of the one memory, laid out\n * as the JavaScript engine's buffers are.\n */\n\nimport { COMBOS } from './cards.ts';\nimport type { ActiveLists, CompactPlan, Layout, PlayerIndex, RegretStore, RootTraversal, SamplingPlan, SumStore } from './cfr.ts';\nimport { dcfrFactors, Mode, treeDepth } from './cfr.ts';\nimport type { HandSpace } from './hands.ts';\nimport type { Runouts } from './runouts.ts';\nimport type { Tree } from './tree.ts';\nimport { ENGINE_WASM } from './wasm/engine.ts';\nimport { ENGINE_SHARED_WASM } from './wasm/engine-shared.ts';\nimport type { ShardPlan } from './parallel.ts';\nimport { awaitThreads, THREAD_FAILED_ERROR, WORKER_START_ERROR, WORKER_START_MS } from './parallel.ts';\n\n/** The parts of the WebAssembly API used here, typed locally: the project builds without DOM typings. */\ninterface WasmApi {\n\tvalidate(bytes: Uint8Array): boolean;\n\tModule: new (bytes: Uint8Array) => object;\n\tInstance: new (module: object, imports: object) => { exports: Record<string, unknown> };\n\tMemory: new (descriptor: { initial: number; maximum?: number; shared?: boolean }) => { buffer: ArrayBuffer };\n}\n\nconst wasm = (globalThis as unknown as { WebAssembly?: WasmApi }).WebAssembly;\nconst modules: Record<'plain' | 'shared', object | null | undefined> = { plain: undefined, shared: undefined };\n\n/** The compiled engine, over plain or shared memory; null where unavailable. */\nexport function compiledEngine(kind: 'plain' | 'shared'): object | null {\n\treturn compileInto(modules, kind, kind === 'plain' ? ENGINE_WASM : ENGINE_SHARED_WASM);\n}\n\n/** Compile base64 WebAssembly into `cache[kind]` once; null there where unavailable. */\nfunction compileInto(cache: Record<'plain' | 'shared', object | null | undefined>, kind: 'plain' | 'shared', text: string): object | null {\n\tif (cache[kind] !== undefined) return cache[kind]!;\n\tcache[kind] = null;\n\ttry {\n\t\tif (!wasm) return null;\n\t\tconst bytes = Uint8Array.from(atob(text), (c) => c.charCodeAt(0));\n\t\tif (!wasm.validate(bytes)) return null;\n\t\tcache[kind] = new wasm.Module(bytes);\n\t} catch {\n\t\tcache[kind] = null;\n\t}\n\treturn cache[kind]!;\n}\n\n/**\n * The engine with 16-bit and compact storage (issue #84), as base64 for plain\n * and shared memory. Only `poker-flopsolve/wasm-storage` holds the bytes, so\n * a build that never imports it carries none of them; a solve opts in by\n * passing it as `SolveOptions.wasmStorage`.\n */\nexport interface WasmStorage {\n\treadonly plain: string;\n\treadonly shared: string;\n}\n\nconst storageModules = new WeakMap<WasmStorage, Record<'plain' | 'shared', object | null | undefined>>();\n\n/** The storage engine compiled, over plain or shared memory; null where unavailable. */\nfunction compiledStorage(source: WasmStorage, kind: 'plain' | 'shared'): object | null {\n\tlet cache = storageModules.get(source);\n\tif (!cache) storageModules.set(source, (cache = { plain: undefined, shared: undefined }));\n\treturn compileInto(cache, kind, source[kind]);\n}\n\nfunction compiled(): object | null {\n\treturn compiledEngine('plain');\n}\n\n/** Whether this platform can run the WebAssembly engine. */\nexport function engineAvailable(): boolean {\n\treturn compiled() !== null;\n}\n\n/** What the engine needs from a prepared spot. */\nexport interface EngineInput {\n\treadonly tree: Tree;\n\treadonly runouts: Runouts;\n\treadonly players: readonly [PlayerIndex, PlayerIndex];\n\treadonly layout: Layout;\n\treadonly active: ActiveLists;\n\treadonly hands: HandSpace;\n\treadonly runoutWeight: Float64Array;\n\treadonly chipScale: number;\n\t/** Chance sampling's layout, for `Approximations.chanceSampling`; unset for none. */\n\treadonly sampling?: SamplingPlan;\n\t/** Bytes left unused below the layout, rounded up to 16; tests set it to place every pointer past 2 GiB. */\n\treadonly lowBytes?: number;\n\t/**\n\t * 16-bit or compact storage, run by the storage engine `source` holds;\n\t * unset for 32-bit storage on the default engine. `quantised` keeps\n\t * the nodes before `compact.from` (all of them without `compact`) at 16\n\t * bits, as `precision: 'i16'` does.\n\t */\n\treadonly storage?: { readonly source: WasmStorage; readonly quantised: boolean; readonly compact: CompactPlan | null };\n}\n\n/** Compact storage's arrays, per chunk, as `Context` holds them; views onto the engine's memory. */\nexport interface EngineCompact {\n\treadonly regret: (Int8Array | Float32Array)[];\n\treadonly handShift: Uint8Array[] | null;\n\treadonly sum: Uint8Array[] | null;\n\treadonly sumShift: Uint8Array[] | null;\n\treadonly scale: Float64Array | null;\n}\n\n/** A running engine. */\nexport interface Engine {\n\t/** The accumulators, as views onto the engine's memory: 32-bit, or 16-bit with `EngineInput.storage`. */\n\treadonly regret: RegretStore;\n\treadonly strategySum: SumStore;\n\t/** With 16-bit storage, the per-block scales `Context.regretScale` and `sumScale` hold; else null. */\n\treadonly regretScale: Float64Array | null;\n\treadonly sumScale: Float64Array | null;\n\t/** With compact storage, its arrays; else null. */\n\treadonly compact: EngineCompact | null;\n\t/** Chance sampling's state, as views onto the engine's memory; null without sampling. */\n\treadonly sampling: { baseline: Float32Array; lastWalk: Int32Array; lastUpdate: Int32Array } | null;\n\t/** With shared storage, `Context.discounted` as a view onto the engine's memory; else null. */\n\treadonly discounted: Int32Array | null;\n\t/** Install as the solver's root traversal; `dcfr` picks the update rule. */\n\troot(dcfr: boolean): RootTraversal;\n\t/** Release worker threads, if any. */\n\tclose(): void;\n\t/** Threads doing the work, this one included. */\n\treadonly threads: number;\n}\n\n/** What an engine worker needs; see src/engine-worker.ts. */\nexport interface EngineWorkerSetup {\n\treadonly memory: unknown;\n\treadonly module: unknown;\n\treadonly header: number;\n\treadonly maxActions: number;\n\treadonly exchange: readonly [number, number, number, number];\n\treadonly shard: readonly [number, number, number];\n\treadonly entryNodes: Int32Array;\n\treadonly rootMe: number;\n\treadonly rootOpp: number;\n\treadonly partial: number;\n\treadonly stride: number;\n\treadonly control: SharedArrayBuffer;\n\treadonly settings: SharedArrayBuffer;\n\t/** With shared storage: where the discount marks, the block table and the weighted nodes (or 0) sit. */\n\treadonly shared?: readonly [number, number, number];\n\t/** Set for the storage engine, whose updates need the iteration on every walk. */\n\treadonly storage?: boolean;\n\t/**\n\t * With chance sampling, `setSampling`'s arguments as the main thread\n\t * passed them: its state is in the shared memory, and each thread walks\n\t * and marks only its own runouts' deals.\n\t */\n\treadonly sampling?: SamplingArgs;\n}\n\n/** `EngineExports.setSampling`'s arguments, in order. */\nexport type SamplingArgs = Parameters<EngineExports['setSampling']>;\n\n/** How a pool starts its workers; the platform layer supplies it. */\nexport type SpawnEngineWorker = (setup: EngineWorkerSetup, onError: (error: Error) => void) => { terminate(): void };\n\n/** The most memory the engine lays out: just under wasm32's 4 GB. */\nconst MAX_MEMORY = 0xffff0000;\n\n/**\n * Control slots shared with engine workers. `failed` is set, never cleared,\n * once any thread's part of a step threw: the main thread waits in\n * `Atomics.wait` and so never sees a worker's error event while a step runs.\n */\nexport const ENGINE_CONTROL = { generation: 0, done: 1, command: 2, mode: 3, traverser: 4, ready: 5, failed: 6, size: 8 } as const;\n\n/**\n * Lay a spot out in a fresh memory and instantiate the engine over it, or\n * null where unavailable. With `pool`, the memory is shared and that many\n * threads split the runouts at the plan's round, as src/parallel.ts does for\n * the JavaScript engine.\n */\nexport function createEngine(\n\tinput: EngineInput,\n\tpool?: {\n\t\tplan: ShardPlan;\n\t\tthreads: number;\n\t\tspawn: SpawnEngineWorker;\n\t\t/** The shortest a step waits for the other threads; see `awaitThreads` in src/parallel.ts. */\n\t\tbackstopFloorMs?: number;\n\t},\n): Engine | null {\n\tconst shared = pool !== undefined;\n\tconst storage = input.storage ?? null;\n\tconst compiledModule = storage\n\t\t? compiledStorage(storage.source, shared ? 'shared' : 'plain')\n\t\t: compiledEngine(shared ? 'shared' : 'plain');\n\tif (!compiledModule || !wasm) return null;\n\tconst { tree, runouts, layout, active, hands } = input;\n\tconst compact = storage?.compact ?? null;\n\tconst quantised = storage?.quantised ?? false;\n\t// Its accumulators alone would pass wasm32's 4 GB, so no engine; checked\n\t// before anything is built. Such a layout is also the only kind that\n\t// holds offsets as Float64, which the engine's 32-bit offset table could\n\t// not take.\n\tconst width = quantised ? 2 : 4;\n\tconst compactBytes = !compact\n\t\t? 0\n\t\t: compact.float\n\t\t\t? layout.compactSlots * 4\n\t\t\t: (layout.compactSlots + (compact.perHand ? layout.compactHands : 0)) * (compact.sums ? 2 : 1);\n\tif (layout.totalSlots * width * 2 + compactBytes > MAX_MEMORY || !(layout.offset instanceof Int32Array)) return null;\n\tconst threads = pool ? pool.threads : 1;\n\n\tconst flatten = (parts: readonly Int32Array[]): [Int32Array, Int32Array] => {\n\t\tconst bases = new Int32Array(parts.length + 1);\n\t\tfor (let i = 0; i < parts.length; i++) bases[i + 1] = bases[i] + parts[i].length;\n\t\tconst flat = new Int32Array(bases[parts.length]);\n\t\tparts.forEach((part, i) => flat.set(part, bases[i]));\n\t\treturn [bases, flat];\n\t};\n\tconst [upRound, upStart] = flatten(hands.upStart);\n\tconst [childRound, childStart] = flatten(runouts.childStart);\n\tconst [orbitRound, orbitStart] = flatten(runouts.orbitStart);\n\tconst maxCount = Math.max(4, ...active.count);\n\tconst stride = Math.ceil(maxCount / 4) * 4;\n\tconst maxActions = Math.max(1, layout.maxActions);\n\tconst depths = treeDepth(tree) + 2;\n\tconst rowBytes = stride * 4;\n\tconst depthBytes = rowBytes * (3 + 2 * maxActions);\n\n\tconst pieces: { data: ArrayBufferView | null; bytes: number }[] = [];\n\tconst add = (data: ArrayBufferView | null, bytes = data ? data.byteLength : 0): number => {\n\t\tpieces.push({ data, bytes: Math.ceil(Math.max(bytes, 4) / 16) * 16 });\n\t\treturn pieces.length - 1;\n\t};\n\t// Shared by every thread, in header order.\n\tconst common = [\n\t\tadd(tree.kind), add(tree.round), add(Uint8Array.from(tree.player, (p) => (p < 0 ? 255 : p))), add(tree.firstEdge),\n\t\tadd(tree.numEdges), add(tree.edgeChild), add(tree.payoff), add(layout.offset), add(layout.rowStart),\n\t\tadd(active.roundBase), add(active.start), add(Int32Array.from(active.count)), add(active.cardA), add(active.cardB),\n\t\tadd(active.strength), add(active.packed), add(Float32Array.from(active.multiplicity)), add(active.memberStart),\n\t\tadd(active.memberA), add(active.memberB), add(upRound), add(upStart), add(hands.up),\n\t\tadd(hands.sameStart), add(hands.same), add(childRound), add(childStart), add(orbitRound), add(orbitStart),\n\t\tadd(input.runoutWeight),\n\t\tadd(null, layout.totalSlots * width), // regret\n\t\tadd(null, layout.totalSlots * width), // strategy sums\n\t];\n\tconst REGRET = common[common.length - 2];\n\tconst SUMS = common[common.length - 1];\n\t// Each thread's own.\n\tconst own = Array.from({ length: threads }, () => ({\n\t\tbuffers: add(null, depths * depthBytes),\n\t\tcardSums: add(null, 52 * 8 + stride * 8),\n\t\trootMe: add(null, rowBytes),\n\t\trootOpp: add(null, rowBytes),\n\t\theader: add(null, 40 * 4),\n\t}));\n\t// The exchange between threads.\n\tconst entries = pool ? pool.plan.entryNodes.length : 0;\n\tconst entryIndexOf = pool ? add(pool.plan.entryIndexOf) : -1;\n\tconst reach = pool ? add(null, entries * 2 * rowBytes) : -1;\n\tconst values = pool ? add(null, entries * rowBytes) : -1;\n\tconst partials = pool ? add(null, (threads - 1) * entries * rowBytes) : -1;\n\t// Chance sampling, only when asked for.\n\tconst plan = input.sampling;\n\tconst sample = plan\n\t\t? {\n\t\t\t\tbaseOffset: add(plan.baseOffset), boardOffset: add(plan.boardOffset), walkOffset: add(plan.walkOffset),\n\t\t\t\tblockOffset: add(layout.blockOffset), baseline: add(null, plan.values * 4), lastWalk: add(null, plan.walks * 4),\n\t\t\t\tlastUpdate: add(null, plan.blocks * 4),\n\t\t\t}\n\t\t: null;\n\t// History sharing's once-an-iteration discount marks, only when storage is shared.\n\tconst share = layout.shared\n\t\t? {\n\t\t\t\tmarks: add(null, layout.blocks * 4),\n\t\t\t\tblockOffset: sample ? sample.blockOffset : add(layout.blockOffset),\n\t\t\t\tweighted: layout.reachWeighted ? add(layout.reachWeighted) : -1,\n\t\t\t}\n\t\t: null;\n\t// 16-bit and compact storage's settings, scales and chunks, only on the storage engine.\n\tconst chunks = compact ? layout.chunkSlots.length : 0;\n\tconst stored = storage\n\t\t? {\n\t\t\t\tblock: add(null, 128),\n\t\t\t\tblockOffset: sample ? sample.blockOffset : share ? share.blockOffset : add(layout.blockOffset),\n\t\t\t\tregretScale: quantised ? add(null, layout.blocks * 8) : -1,\n\t\t\t\tsumScale: quantised ? add(null, layout.blocks * 8) : -1,\n\t\t\t\tcompactChunk: compact ? add(layout.compactChunk) : -1,\n\t\t\t\thandOffset: compact ? add(Int32Array.from(layout.handOffset!)) : -1,\n\t\t\t\ttables: compact ? add(null, chunks * 4 * 5) : -1,\n\t\t\t\tregrets: layout.chunkSlots.map((slots) => add(null, slots * (compact!.float ? 4 : 1))),\n\t\t\t\tshifts: compact?.perHand ? layout.chunkHands.map((count) => add(null, count)) : [],\n\t\t\t\tsums: compact?.sums ? layout.chunkSlots.map((slots) => add(null, slots)) : [],\n\t\t\t\tsumShifts: compact?.sums ? layout.chunkHands.map((count) => add(null, count)) : [],\n\t\t\t\tcompactScale: compact && !compact.perHand && !compact.float ? add(null, layout.blocks * 8) : -1,\n\t\t\t}\n\t\t: null;\n\n\tconst offsets: number[] = [];\n\tlet total = 64 + Math.ceil(Math.max(input.lowBytes ?? 0, 0) / 16) * 16;\n\tfor (const piece of pieces) {\n\t\toffsets.push(total);\n\t\ttotal += piece.bytes;\n\t}\n\tif (total > MAX_MEMORY) return null;\n\tconst pages = Math.ceil(total / 65536) + 1;\n\tconst memory = shared ? new wasm.Memory({ initial: pages, maximum: pages, shared: true }) : new wasm.Memory({ initial: pages });\n\tconst bytes = new Uint8Array(memory.buffer);\n\tpieces.forEach((piece, i) => {\n\t\tif (piece.data) bytes.set(new Uint8Array(piece.data.buffer, piece.data.byteOffset, piece.data.byteLength), offsets[i]);\n\t});\n\tfor (const mine of own) {\n\t\tconst head = new Uint32Array(memory.buffer, offsets[mine.header], 40);\n\t\tcommon.forEach((slot, i) => (head[i] = offsets[slot]));\n\t\thead[common.length] = offsets[mine.buffers];\n\t\thead[common.length + 1] = depthBytes;\n\t\thead[common.length + 2] = rowBytes;\n\t\thead[common.length + 3] = offsets[mine.cardSums];\n\t\thead[common.length + 4] = input.chipScale;\n\t\tif (stored) head[common.length + 5] = offsets[stored.block];\n\t}\n\tif (stored) {\n\t\tconst at = (slot: number): number => (slot >= 0 ? offsets[slot] : 0);\n\t\tconst block = new Uint32Array(memory.buffer, offsets[stored.block], 20);\n\t\tblock.set([\n\t\t\tquantised ? 1 : 0, compact ? compact.from : 255, !compact ? 0 : compact.float ? 3 : compact.perHand ? 1 : 2,\n\t\t\tcompact?.sums ? 1 : 0, compact?.stochastic ? 1 : 0, compact?.steps ?? 127,\n\t\t\tat(stored.regretScale), at(stored.sumScale), offsets[stored.blockOffset], at(stored.compactChunk),\n\t\t\tat(stored.handOffset),\n\t\t]);\n\t\tif (compact) {\n\t\t\t// Per chunk: where its regrets, hand scales, sums and sum scales sit, and its first slot.\n\t\t\tconst tables = offsets[stored.tables];\n\t\t\tconst table = new Uint32Array(memory.buffer, tables, chunks * 5);\n\t\t\tfor (let c = 0; c < chunks; c++) {\n\t\t\t\ttable[c] = offsets[stored.regrets[c]];\n\t\t\t\ttable[chunks + c] = stored.shifts.length ? offsets[stored.shifts[c]] : 0;\n\t\t\t\ttable[2 * chunks + c] = stored.sums.length ? offsets[stored.sums[c]] : 0;\n\t\t\t\ttable[3 * chunks + c] = stored.sumShifts.length ? offsets[stored.sumShifts[c]] : 0;\n\t\t\t\ttable[4 * chunks + c] = layout.chunkStart[c] >>> 0;\n\t\t\t}\n\t\t\tblock.set([tables, tables + chunks * 4, tables + chunks * 8, tables + chunks * 12, tables + chunks * 16, at(stored.compactScale)], 11);\n\t\t}\n\t}\n\t// The update rule's factors, as float64, which the storage engine reads before each walk.\n\tconst factors = stored ? new Float64Array(memory.buffer, offsets[stored.block] + 80, 4) : null;\n\n\tconst instance = new wasm.Instance(compiledModule, { env: { memory, abort: () => { throw new Error('engine abort'); } } });\n\tconst exports = instance.exports as unknown as EngineExports;\n\texports.init(offsets[own[0].header]);\n\texports.setMaxActions(maxActions);\n\tlet samplingViews: Engine['sampling'] = null;\n\tlet samplingArgs: SamplingArgs | null = null;\n\tif (plan && sample) {\n\t\tlet mask = 0;\n\t\tfor (let r = 0; r < plan.rounds.length; r++) if (plan.rounds[r]) mask |= 1 << r;\n\t\tsamplingArgs = [\n\t\t\tmask, plan.p, plan.every, plan.unbiased ? 1 : 0, plan.catchUp ? 1 : 0,\n\t\t\toffsets[sample.baseOffset], offsets[sample.boardOffset], offsets[sample.walkOffset],\n\t\t\toffsets[sample.baseline], offsets[sample.lastWalk], offsets[sample.lastUpdate], offsets[sample.blockOffset],\n\t\t];\n\t\tconst a = samplingArgs;\n\t\texports.setSampling(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11]);\n\t\tsamplingViews = {\n\t\t\tbaseline: new Float32Array(memory.buffer, offsets[sample.baseline], plan.values),\n\t\t\tlastWalk: new Int32Array(memory.buffer, offsets[sample.lastWalk], plan.walks),\n\t\t\tlastUpdate: new Int32Array(memory.buffer, offsets[sample.lastUpdate], plan.blocks),\n\t\t};\n\t}\n\n\tconst weightedAt = share && share.weighted >= 0 ? offsets[share.weighted] : 0;\n\tif (share) exports.setShared(offsets[share.marks], offsets[share.blockOffset], weightedAt);\n\tconst discounted = share ? new Int32Array(memory.buffer, offsets[share.marks], layout.blocks) : null;\n\n\tconst regret: RegretStore = quantised\n\t\t? new Int16Array(memory.buffer, offsets[REGRET], layout.totalSlots)\n\t\t: new Float32Array(memory.buffer, offsets[REGRET], layout.totalSlots);\n\tconst strategySum: SumStore = quantised\n\t\t? new Uint16Array(memory.buffer, offsets[SUMS], layout.totalSlots)\n\t\t: new Float32Array(memory.buffer, offsets[SUMS], layout.totalSlots);\n\tconst scaleView = (slot: number): Float64Array | null =>\n\t\tslot >= 0 ? new Float64Array(memory.buffer, offsets[slot], layout.blocks) : null;\n\tconst compactViews: EngineCompact | null = stored && compact\n\t\t? {\n\t\t\t\tregret: stored.regrets.map((slot, c) =>\n\t\t\t\t\tcompact.float\n\t\t\t\t\t\t? new Float32Array(memory.buffer, offsets[slot], layout.chunkSlots[c])\n\t\t\t\t\t\t: new Int8Array(memory.buffer, offsets[slot], layout.chunkSlots[c]),\n\t\t\t\t),\n\t\t\t\thandShift: compact.perHand ? stored.shifts.map((slot, c) => new Uint8Array(memory.buffer, offsets[slot], layout.chunkHands[c])) : null,\n\t\t\t\tsum: compact.sums ? stored.sums.map((slot, c) => new Uint8Array(memory.buffer, offsets[slot], layout.chunkSlots[c])) : null,\n\t\t\t\tsumShift: compact.sums ? stored.sumShifts.map((slot, c) => new Uint8Array(memory.buffer, offsets[slot], layout.chunkHands[c])) : null,\n\t\t\t\tscale: scaleView(stored.compactScale),\n\t\t\t}\n\t\t: null;\n\tconst me = new Float32Array(memory.buffer, offsets[own[0].rootMe], stride);\n\tconst opp = new Float32Array(memory.buffer, offsets[own[0].rootOpp], stride);\n\tconst result = new Float64Array(COMBOS);\n\tconst rootList = (player: 0 | 1): [number, number] => {\n\t\tconst slot = active.roundBase[0] * 2 + player;\n\t\treturn [active.start[slot], active.count[slot]];\n\t};\n\tconst settingsFor = (mode: number, iterWeight: number, dcfr: boolean): [number, number, number, number, number] => {\n\t\tif (mode === Mode.Train && dcfr) {\n\t\t\tconst { keepPositive, keepNegative, keepSum } = dcfrFactors(iterWeight);\n\t\t\treturn [keepPositive, keepNegative, keepSum, 1, 0];\n\t\t}\n\t\treturn [1, 1, 1, iterWeight, dcfr ? 0 : 1];\n\t};\n\n\t// Threads: workers over the same memory, each with its own header.\n\tlet control: Int32Array | null = null;\n\tlet settings: Float64Array | null = null;\n\tconst workers: { terminate(): void }[] = [];\n\tlet failure: Error | null = null;\n\tif (pool) {\n\t\tconst plan = pool.plan;\n\t\tconst controlBuffer = new SharedArrayBuffer(ENGINE_CONTROL.size * 4);\n\t\tconst settingsBuffer = new SharedArrayBuffer(8 * 8);\n\t\tcontrol = new Int32Array(controlBuffer);\n\t\tsettings = new Float64Array(settingsBuffer);\n\t\texports.setExchange(offsets[entryIndexOf], offsets[reach], offsets[values], stride);\n\t\tfor (let w = 1; w < threads; w++) {\n\t\t\tconst setup: EngineWorkerSetup = {\n\t\t\t\tmemory, module: compiledModule, header: offsets[own[w].header], maxActions,\n\t\t\t\texchange: [offsets[entryIndexOf], offsets[reach], offsets[values], stride],\n\t\t\t\tshard: [plan.round, plan.bounds[w], plan.bounds[w + 1]],\n\t\t\t\tentryNodes: plan.entryNodes,\n\t\t\t\trootMe: offsets[own[w].rootMe], rootOpp: offsets[own[w].rootOpp],\n\t\t\t\tpartial: offsets[partials] + (w - 1) * entries * rowBytes,\n\t\t\t\tstride, control: controlBuffer, settings: settingsBuffer,\n\t\t\t\t...(share ? { shared: [offsets[share.marks], offsets[share.blockOffset], weightedAt] as const } : {}),\n\t\t\t\t...(stored ? { storage: true } : {}),\n\t\t\t\t...(samplingArgs ? { sampling: samplingArgs } : {}),\n\t\t\t};\n\t\t\tworkers.push(pool.spawn(setup, (error) => {\n\t\t\t\tfailure ??= error;\n\t\t\t\tAtomics.store(control!, ENGINE_CONTROL.ready, threads);\n\t\t\t\tAtomics.add(control!, ENGINE_CONTROL.done, threads);\n\t\t\t\tAtomics.notify(control!, ENGINE_CONTROL.done);\n\t\t\t\tAtomics.notify(control!, ENGINE_CONTROL.ready);\n\t\t\t}));\n\t\t}\n\t\t// A worker that fails to start reports it by an event, which cannot\n\t\t// be delivered while this thread waits here, so the wait is bounded.\n\t\tconst deadline = Date.now() + WORKER_START_MS;\n\t\tfor (;;) {\n\t\t\tconst ready = Atomics.load(control, ENGINE_CONTROL.ready);\n\t\t\tif (ready >= threads - 1 || failure) break;\n\t\t\tif (Date.now() > deadline) failure = new Error(WORKER_START_ERROR);\n\t\t\telse Atomics.wait(control, ENGINE_CONTROL.ready, ready, 20);\n\t\t}\n\t\tif (failure) {\n\t\t\tfor (const worker of workers) worker.terminate();\n\t\t\tthrow failure;\n\t\t}\n\t}\n\n\tconst failed = (): Error | null =>\n\t\tfailure ?? (control && Atomics.load(control, ENGINE_CONTROL.failed) ? new Error(THREAD_FAILED_ERROR) : null);\n\n\t// The iteration a step is for, and its rule, which shared storage's threads need.\n\tlet iteration = 0;\n\tlet dcfrRule = 0;\n\tconst run = (asked: number, traverser: 0 | 1, iterWeight: number, dcfr: boolean): Float64Array => {\n\t\t// Once any thread has failed, so does every step after, before it\n\t\t// touches anything.\n\t\tconst dead = failed();\n\t\tif (dead) throw dead;\n\t\t// The engine knows three modes; the current profile is its Train\n\t\t// with updates off.\n\t\tconst apply = asked === Mode.Current ? 0 : 1;\n\t\tconst mode = asked === Mode.Current ? Mode.Train : asked;\n\t\tfor (const player of [0, 1] as const) {\n\t\t\tconst [from, count] = rootList(player);\n\t\t\tconst into = player === traverser ? me : opp;\n\t\t\tconst weights = input.players[player].weights;\n\t\t\tfor (let i = 0; i < count; i++) into[i] = weights[active.list[from + i]];\n\t\t}\n\t\tconst [positive, negative, sum, weight, clamp] = settingsFor(mode, iterWeight, dcfr);\n\t\titeration = mode === Mode.Train ? iterWeight : 0;\n\t\tdcfrRule = dcfr ? 1 : 0;\n\t\tif (plan || share || stored) exports.setIteration(iteration, dcfrRule);\n\t\t// CFR+ at 16 bits or compact floors a negative regret, as `updateQuantised`\n\t\t// and `updateCompact` do (one only a warm start could bring); 32-bit storage keeps it.\n\t\tfactors?.set([positive, mode === Mode.Train && !dcfr ? 0 : negative, sum, weight]);\n\t\tlet at: number;\n\t\tif (!pool) {\n\t\t\tif (apply === 0) exports.setPhase(0, 0);\n\t\t\ttry {\n\t\t\t\tat = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp) >>> 0;\n\t\t\t} finally {\n\t\t\t\tif (apply === 0) exports.setPhase(0, 1);\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tat = runThreaded(mode, traverser, apply, positive, negative, sum, weight, clamp);\n\t\t\t} catch (error) {\n\t\t\t\t// This thread's own part may have thrown with the workers still\n\t\t\t\t// walking; no later step may run over them.\n\t\t\t\tAtomics.store(control!, ENGINE_CONTROL.failed, 1);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tconst [, count] = rootList(traverser);\n\t\tconst values32 = new Float32Array(memory.buffer, at, count);\n\t\tfor (let i = 0; i < count; i++) result[i] = values32[i];\n\t\treturn result;\n\t};\n\n\t/** One threaded traversal, returning where the root values are. */\n\tconst runThreaded = (\n\t\tmode: number, traverser: 0 | 1, apply: number,\n\t\tpositive: number, negative: number, sum: number, weight: number, clamp: number,\n\t): number => {\n\t\tconst plan = pool!.plan;\n\t\t// Collect: walk above the split, recording what the workers need.\n\t\texports.setShard(plan.round, 0, 0);\n\t\texports.setPhase(1, 0);\n\t\texports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);\n\t\t// Every thread walks its slice of the split round.\n\t\tsettings!.set([positive, negative, sum, weight, clamp, apply, iteration, dcfrRule]);\n\t\tAtomics.store(control!, ENGINE_CONTROL.done, 0);\n\t\tAtomics.store(control!, ENGINE_CONTROL.mode, mode);\n\t\tAtomics.store(control!, ENGINE_CONTROL.traverser, traverser);\n\t\tAtomics.store(control!, ENGINE_CONTROL.command, 0);\n\t\tAtomics.add(control!, ENGINE_CONTROL.generation, 1);\n\t\tAtomics.notify(control!, ENGINE_CONTROL.generation);\n\t\tconst dispatched = performance.now();\n\t\texports.setShard(plan.round, plan.bounds[0], plan.bounds[1]);\n\t\texports.setPhase(0, apply);\n\t\tconst valueView = new Float32Array(memory.buffer, offsets[values], entries * stride);\n\t\tfor (let entry = 0; entry < entries; entry++) {\n\t\t\tconst slot = offsets[reach] + entry * 2 * rowBytes;\n\t\t\tconst out = exports.runChance(mode, traverser, plan.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp) >>> 0;\n\t\t\tvalueView.set(new Float32Array(memory.buffer, out, stride), entry * stride);\n\t\t}\n\t\t// A thread whose walk throws says so in `failed` and counts itself\n\t\t// done, as its error event cannot reach this thread while it waits.\n\t\t// One killed without unwinding does neither, hence the backstop.\n\t\tfailure ??= awaitThreads(\n\t\t\tcontrol!, ENGINE_CONTROL.done, threads - 1, dispatched, pool!.backstopFloorMs, () => failure !== null,\n\t\t);\n\t\tconst dead = failed();\n\t\tif (dead) throw dead;\n\t\tconst partialView = new Float32Array(memory.buffer, offsets[partials], (threads - 1) * entries * stride);\n\t\tfor (let w = 0; w < threads - 1; w++) {\n\t\t\tfor (let i = 0; i < entries * stride; i++) valueView[i] += partialView[w * entries * stride + i];\n\t\t}\n\t\t// Finish above the split from the totals, now applying updates\n\t\t// unless this is a current-profile read.\n\t\texports.setShard(plan.round, 0, 0);\n\t\texports.setPhase(2, apply);\n\t\tconst at = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp) >>> 0;\n\t\texports.setPhase(0, 1);\n\t\texports.setShard(-1, 0, 0);\n\t\treturn at;\n\t};\n\n\treturn {\n\t\tregret,\n\t\tstrategySum,\n\t\tregretScale: stored ? scaleView(stored.regretScale) : null,\n\t\tsumScale: stored ? scaleView(stored.sumScale) : null,\n\t\tcompact: compactViews,\n\t\tsampling: samplingViews,\n\t\tdiscounted,\n\t\tthreads,\n\t\troot(dcfr) {\n\t\t\treturn (mode, traverser, iterWeight) => run(mode, traverser, iterWeight, dcfr);\n\t\t},\n\t\tclose() {\n\t\t\tif (!control) return;\n\t\t\tAtomics.store(control, ENGINE_CONTROL.command, 1);\n\t\t\tAtomics.add(control, ENGINE_CONTROL.generation, 1);\n\t\t\tAtomics.notify(control, ENGINE_CONTROL.generation);\n\t\t\tfor (const worker of workers) worker.terminate();\n\t\t},\n\t};\n}\n\n/**\n * The engine's exports. A pointer one returns is a wasm32 `usize`, which\n * JavaScript receives as a signed 32-bit integer: read it with `>>> 0`, or\n * any address past 2 GiB comes back negative (#62).\n */\nexport interface EngineExports {\n\tinit(header: number): void;\n\tsetMaxActions(count: number): void;\n\tsetShard(round: number, start: number, end: number): void;\n\tsetExchange(entries: number, reach: number, values: number, stride: number): void;\n\tsetPhase(phase: number, apply: number): void;\n\tsetSampling(\n\t\trounds: number, p: number, every: number, unbiased: number, catchUp: number,\n\t\tbaseOffsets: number, boardOffsets: number, walkOffsets: number,\n\t\tbaselines: number, lastWalks: number, lastUpdates: number, blockOffsets: number,\n\t): void;\n\tsetIteration(t: number, dcfr: number): void;\n\tsetShared(marks: number, blockOffsets: number, weighted: number): void;\n\trun(mode: number, traverser: number, me: number, opp: number, positive: number, negative: number, sum: number, weight: number, clamp: number): number;\n\trunChance(mode: number, traverser: number, node: number, me: number, opp: number, positive: number, negative: number, sum: number, weight: number, clamp: number): number;\n}\n","/**\n * One thread of a WebAssembly solve: the loop every engine worker runs.\n *\n * Purpose: walk this thread's slice of the runouts at the split round, over\n * the memory every thread shares, each time the main thread signals, until it\n * says exit. The protocol is src/parallel.ts's: the main thread collects the\n * reach each entry needs, every thread walks its slice from each entry, the\n * main thread adds the slices up and finishes. All of it happens in shared\n * WebAssembly memory, so nothing is copied between threads but a few numbers\n * of control.\n *\n * Node runs it from `engine-worker.ts`. The browser build has no file to\n * start a worker from, so `platform/browser.ts` ships this function as its\n * own source text (`Function.prototype.toString`) inside a Blob worker. That\n * is why it must stay self-contained: no imports, no reference to anything\n * outside its body, no nested named functions (a bundler may wrap those in a\n * helper the worker would not have). The control slots are written out as\n * numbers for the same reason; a test pins them to `ENGINE_CONTROL`.\n */\n\nimport type { EngineWorkerSetup } from './engine.ts';\n\n/**\n * Serve one solve, returning once the main thread sends exit.\n * @param setup what `createEngine` hands each worker\n */\nexport function serveEngine(setup: EngineWorkerSetup): void {\n\t// ENGINE_CONTROL, inlined.\n\tconst GENERATION = 0;\n\tconst DONE = 1;\n\tconst COMMAND = 2;\n\tconst MODE = 3;\n\tconst TRAVERSER = 4;\n\tconst READY = 5;\n\tconst FAILED = 6;\n\tconst EXIT = 1;\n\n\tconst api = (globalThis as unknown as {\n\t\tWebAssembly: { Instance: new (module: unknown, imports: object) => { exports: Record<string, unknown> } };\n\t}).WebAssembly;\n\tconst memory = setup.memory as { buffer: SharedArrayBuffer };\n\tconst imports = {\n\t\tenv: {\n\t\t\tmemory,\n\t\t\tabort(): never {\n\t\t\t\tthrow new Error('engine abort');\n\t\t\t},\n\t\t},\n\t};\n\tconst engine = new api.Instance(setup.module, imports).exports as unknown as {\n\t\tinit(header: number): void;\n\t\tsetMaxActions(count: number): void;\n\t\tsetShard(round: number, start: number, end: number): void;\n\t\tsetExchange(entries: number, reach: number, values: number, stride: number): void;\n\t\tsetPhase(phase: number, apply: number): void;\n\t\tsetShared(marks: number, blockOffsets: number, weighted: number): void;\n\t\tsetSampling(\n\t\t\trounds: number, p: number, every: number, unbiased: number, catchUp: number,\n\t\t\tbaseOffsets: number, boardOffsets: number, walkOffsets: number,\n\t\t\tbaselines: number, lastWalks: number, lastUpdates: number, blockOffsets: number,\n\t\t): void;\n\t\tsetIteration(t: number, dcfr: number): void;\n\t\trunChance(\n\t\t\tmode: number, traverser: number, node: number, me: number, opp: number,\n\t\t\tpositive: number, negative: number, sum: number, weight: number, clamp: number,\n\t\t): number;\n\t};\n\tengine.init(setup.header);\n\tengine.setMaxActions(setup.maxActions);\n\tengine.setExchange(setup.exchange[0], setup.exchange[1], setup.exchange[2], setup.exchange[3]);\n\tengine.setShard(setup.shard[0], setup.shard[1], setup.shard[2]);\n\tengine.setPhase(0, 1);\n\tconst shared = setup.shared;\n\tif (shared) engine.setShared(shared[0], shared[1], shared[2]);\n\t// Chance sampling's state is in the shared memory, at the main thread's offsets.\n\tconst s = setup.sampling;\n\tif (s) engine.setSampling(s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11]);\n\t// Shared storage discounts by iteration, the storage engine's rounding\n\t// hashes it, and chance sampling picks deals and catches up by it.\n\tconst needsIteration = shared !== undefined || setup.storage === true || s !== undefined;\n\n\tconst control = new Int32Array(setup.control);\n\tconst settings = new Float64Array(setup.settings);\n\tconst entries = setup.entryNodes.length;\n\tconst rowBytes = setup.stride * 4;\n\tconst partials = new Float32Array(memory.buffer, setup.partial, entries * setup.stride);\n\tconst reach = setup.exchange[1];\n\n\t// Latch the generation before announcing readiness, so no dispatch is missed.\n\tlet generation = Atomics.load(control, GENERATION);\n\tAtomics.add(control, READY, 1);\n\tAtomics.notify(control, READY);\n\t// A solve that gave up before this thread started has already said exit.\n\tif (Atomics.load(control, COMMAND) === EXIT) return;\n\n\tfor (;;) {\n\t\tAtomics.wait(control, GENERATION, generation);\n\t\tgeneration = Atomics.load(control, GENERATION);\n\t\tif (Atomics.load(control, COMMAND) === EXIT) return;\n\t\tconst mode = Atomics.load(control, MODE);\n\t\tconst traverser = Atomics.load(control, TRAVERSER);\n\t\tconst positive = settings[0];\n\t\tconst negative = settings[1];\n\t\tconst sum = settings[2];\n\t\tconst weight = settings[3];\n\t\tconst clamp = settings[4];\n\t\ttry {\n\t\t\t// Off for a current-profile read, which updates nothing.\n\t\t\tengine.setPhase(0, settings[5]);\n\t\t\tif (needsIteration) engine.setIteration(settings[6], settings[7]);\n\t\t\tfor (let entry = 0; entry < entries; entry++) {\n\t\t\t\tconst slot = reach + entry * 2 * rowBytes;\n\t\t\t\tconst out = engine.runChance(\n\t\t\t\t\tmode, traverser, setup.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp,\n\t\t\t\t) >>> 0; // a usize, signed on its way out; see `EngineExports`\n\t\t\t\tpartials.set(new Float32Array(memory.buffer, out, setup.stride), entry * setup.stride);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// The main thread is blocked in Atomics.wait and cannot see this\n\t\t\t// thread's error event, so say so in shared memory (and count as\n\t\t\t// done, below). Then let the thread die: its engine is not to be trusted.\n\t\t\tAtomics.store(control, FAILED, 1);\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tAtomics.add(control, DONE, 1);\n\t\t\tAtomics.notify(control, DONE);\n\t\t}\n\t}\n}\n","/**\n * The browser build's engine threads: started ahead of time, borrowed by solves.\n *\n * Purpose: everything behind `enableThreads` (`poker-flopsolve/threads`), kept\n * out of `platform/browser.ts` so the main browser build carries none of it.\n * See that file for why the threads must be started before a solve.\n */\n\nimport type { EngineWorkerSetup } from '../engine.ts';\nimport { ENGINE_CONTROL } from '../engine.ts';\nimport { serveEngine } from '../engine-thread.ts';\n\n/** A spawned solver thread. */\ninterface WorkerHandle {\n\tterminate(): void;\n}\n\n/** The parts of the Web Worker API used here, typed locally: the project builds without DOM typings. */\ninterface WebWorker {\n\tpostMessage(message: unknown, transfer?: unknown[]): void;\n\tterminate(): void;\n\tonmessage: ((event: { data: unknown }) => void) | null;\n\tonerror: ((event: { message?: string; preventDefault?(): void }) => void) | null;\n}\n\ninterface MessagePortLike {\n\tpostMessage(message: unknown): void;\n}\n\ninterface BrowserGlobals {\n\tWorker?: new (url: string) => WebWorker;\n\tMessageChannel?: new () => { port1: MessagePortLike; port2: unknown };\n\tBlob?: new (parts: string[], options: { type: string }) => object;\n\tURL: { createObjectURL(blob: object): string; revokeObjectURL(url: string): void };\n\tcrossOriginIsolated?: boolean;\n\tnavigator?: { hardwareConcurrency?: number };\n\tWebAssembly?: { Memory: new (descriptor: { initial: number; maximum: number; shared: boolean }) => object };\n}\n\n/** One pre-started engine thread. */\ninterface Thread {\n\treadonly worker: WebWorker;\n\t/**\n\t * Where its solves are posted. A message posted on the Worker object\n\t * itself does not reach a running child while the parent is blocked in\n\t * `Atomics.wait` (Chromium), and a solve blocks right after posting; a\n\t * transferred MessagePort delivers regardless.\n\t */\n\treadonly port: MessagePortLike;\n\tbusy: boolean;\n}\n\n/** Where the pool is published on `globalThis`. */\nexport const THREADS_KEY = Symbol.for('poker-flopsolve.browser-threads');\n\n/** What the main build sees of the pool. */\nexport interface ThreadProvider {\n\tidle(): number;\n\ttotal(): number;\n\tspawn(setup: EngineWorkerSetup, onError: (error: Error) => void): WorkerHandle;\n}\n\ntype Holder = Record<symbol, (ThreadProvider & { threads: Thread[] }) | undefined>;\n\n/** The engine threads started so far, shared by every copy of this module. */\nfunction pool(): Thread[] {\n\tconst holder = globalThis as unknown as Holder;\n\tholder[THREADS_KEY] ??= {\n\t\tthreads: [],\n\t\tidle: () => idleThreads(),\n\t\ttotal: () => pool().length,\n\t\tspawn: (setup, onError) => spawn(setup, onError),\n\t};\n\treturn holder[THREADS_KEY]!.threads;\n}\n\nfunction idleThreads(): number {\n\treturn pool().filter((thread) => !thread.busy).length;\n}\n\n/** Stop a thread for good and forget it. */\nfunction drop(thread: Thread): void {\n\tthread.worker.terminate();\n\tthread.busy = true;\n\tconst threads = pool();\n\tconst at = threads.indexOf(thread);\n\tif (at >= 0) threads.splice(at, 1);\n}\n\n/** `ENGINE_CONTROL.command`'s value that ends a thread's solve. */\nconst COMMAND_EXIT = 1;\n\n/**\n * Hand one idle engine thread a solve's setup.\n * @param setup what the thread needs to join the solve\n * @param onError called if the thread dies, so the solve can stop waiting on it\n */\nfunction spawn(setup: EngineWorkerSetup, onError: (error: Error) => void): WorkerHandle {\n\tconst thread = pool().find((candidate) => !candidate.busy);\n\tif (!thread) throw new Error('No idle engine thread; call enableThreads() from poker-flopsolve/threads first');\n\tthread.busy = true;\n\tthread.worker.onerror = (event) => {\n\t\tevent.preventDefault?.();\n\t\tdrop(thread);\n\t\tonError(new Error(`Engine thread failed: ${event.message ?? 'unknown error'}`));\n\t};\n\tthread.port.postMessage(setup);\n\tconst control = new Int32Array(setup.control);\n\tlet released = false;\n\treturn {\n\t\tterminate() {\n\t\t\t// A run may be closed twice; by then the thread may serve another.\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tif (!pool().includes(thread)) return;\n\t\t\t// A solve a thread failed: its error event is still queued, and\n\t\t\t// would fail whichever solve borrowed the thread next. Which thread\n\t\t\t// failed is not recorded, so every one of that solve's goes;\n\t\t\t// `prepareThreads` starts replacements.\n\t\t\tif (Atomics.load(control, ENGINE_CONTROL.failed) !== 0) {\n\t\t\t\tdrop(thread);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Whether this solve finished or gave up on starting, tell the\n\t\t\t// thread its solve is over: it returns to waiting for the next\n\t\t\t// setup, having started this one or not (serveEngine checks for\n\t\t\t// exit before it first waits). A thread that died is dropped by\n\t\t\t// its error handler instead.\n\t\t\tif (Atomics.load(control, ENGINE_CONTROL.command) !== COMMAND_EXIT) {\n\t\t\t\tAtomics.store(control, ENGINE_CONTROL.command, COMMAND_EXIT);\n\t\t\t\tAtomics.add(control, ENGINE_CONTROL.generation, 1);\n\t\t\t\tAtomics.notify(control, ENGINE_CONTROL.generation);\n\t\t\t}\n\t\t\tthread.busy = false;\n\t\t\tthread.worker.onerror = () => drop(thread);\n\t\t},\n\t};\n}\n\n/** Why threads cannot run here, or null if they can. */\nexport function threadsUnavailableReason(): string | null {\n\tconst g = globalThis as unknown as BrowserGlobals;\n\tif (typeof g.Worker !== 'function' || typeof g.Blob !== 'function' || typeof g.MessageChannel !== 'function') {\n\t\treturn 'no Web Workers here';\n\t}\n\tif (g.crossOriginIsolated !== true) {\n\t\treturn 'the page is not cross-origin isolated (serve it with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp)';\n\t}\n\tif (typeof SharedArrayBuffer !== 'function') return 'no SharedArrayBuffer here';\n\ttry {\n\t\t// Throws where blocking is not allowed: a page's main thread.\n\t\tAtomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 1, 0);\n\t} catch {\n\t\treturn 'Atomics.wait is not allowed on this thread; solve inside a Web Worker';\n\t}\n\ttry {\n\t\tnew g.WebAssembly!.Memory({ initial: 1, maximum: 1, shared: true });\n\t} catch {\n\t\treturn 'no shared WebAssembly memory here';\n\t}\n\treturn null;\n}\n\n/** How long a thread may take to start before it is given up on. */\nconst START_MS = 30_000;\n\nfunction startThread(url: string): Promise<Thread | null> {\n\tconst g = globalThis as unknown as BrowserGlobals;\n\treturn new Promise((resolve) => {\n\t\tlet worker: WebWorker;\n\t\ttry {\n\t\t\tworker = new g.Worker!(url);\n\t\t} catch {\n\t\t\tresolve(null);\n\t\t\treturn;\n\t\t}\n\t\tconst timer = setTimeout(() => {\n\t\t\tworker.terminate();\n\t\t\tresolve(null);\n\t\t}, START_MS);\n\t\tconst channel = new g.MessageChannel!();\n\t\tworker.onmessage = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tworker.onmessage = null;\n\t\t\tworker.onerror = null;\n\t\t\tresolve({ worker, port: channel.port1, busy: false });\n\t\t};\n\t\tworker.postMessage(null, [channel.port2]);\n\t\tworker.onerror = (event) => {\n\t\t\tevent.preventDefault?.();\n\t\t\tclearTimeout(timer);\n\t\t\tworker.terminate();\n\t\t\tresolve(null);\n\t\t};\n\t});\n}\n\n/**\n * Start engine threads so that solves can use up to `count` threads, this one\n * included, and resolve to how many a solve can use now. Threads already\n * started are kept; idle ones beyond `count` are stopped, so `prepareThreads(1)`\n * stops every thread no open run is holding. Resolves to 1 where threads cannot run; see\n * {@link threadsUnavailableReason}.\n * @param count threads wanted, this one included; defaults to `navigator.hardwareConcurrency`\n */\nexport function prepareThreads(count?: number): Promise<number> {\n\t// One call at a time, so two calls in a row cannot both start the missing threads.\n\tconst next = pending.then(() => resize(count));\n\tpending = next.catch(() => undefined);\n\treturn next;\n}\n\nlet pending: Promise<unknown> = Promise.resolve();\n\nasync function resize(count?: number): Promise<number> {\n\tconst g = globalThis as unknown as BrowserGlobals;\n\tconst wanted = Math.max(1, Math.floor(count ?? g.navigator?.hardwareConcurrency ?? 1));\n\tconst threads = pool();\n\tfor (let i = threads.length - 1; i >= 0 && threads.length > wanted - 1; i--) {\n\t\tif (!threads[i].busy) drop(threads[i]);\n\t}\n\tconst missing = wanted - 1 - threads.length;\n\tif (missing > 0 && threadsUnavailableReason() === null) {\n\t\t// The worker is this module's own loop, as source: there is no file\n\t\t// to point a worker at that every bundler would ship.\n\t\tconst source =\n\t\t\t`const serveEngine = ${serveEngine.toString()};\\n` +\n\t\t\t'onmessage = (event) => {\\n' +\n\t\t\t'\\tevent.ports[0].onmessage = (solve) => serveEngine(solve.data);\\n' +\n\t\t\t\"\\tpostMessage('ready');\\n\" +\n\t\t\t'};\\n';\n\t\tconst url = g.URL.createObjectURL(new g.Blob!([source], { type: 'text/javascript' }));\n\t\ttry {\n\t\t\tconst started = await Promise.all(Array.from({ length: missing }, () => startThread(url)));\n\t\t\tfor (const thread of started) if (thread) threads.push(thread);\n\t\t} finally {\n\t\t\tg.URL.revokeObjectURL(url);\n\t\t}\n\t}\n\treturn threadsUnavailableReason() === null ? Math.min(wanted, 1 + idleThreads()) : 1;\n}\n","/**\n * Browser platform.\n *\n * Purpose: stand in for `node.ts` in a browser build, with the same exports.\n *\n * Out of the box the browser build is single-threaded: no worker threads, no\n * SharedArrayBuffer, and so no cross-origin isolation headers needed on the\n * page. Run the solve inside a Web Worker to keep the page responsive; see\n * `examples/browser-worker.ts`.\n *\n * Threads are opt-in, through `enableThreads` in `poker-flopsolve/threads`\n * (`prepareThreads` here). A browser starts a Web Worker only asynchronously —\n * a worker spawned and then waited on with `Atomics.wait` never starts, as\n * the thread that would start it is the one blocked — while a solve is\n * synchronous. So the workers are started ahead of time, once, and wait idle\n * between solves; a solve with `workers: n` hands n − 1 of them its setup and\n * takes them back on `close()`. Only the WebAssembly engine is threaded here:\n * its workers share the engine's memory exactly as Node's do and run the same\n * loop (`serveEngine`), so a fixed thread count gives the same answer as Node\n * at that count.\n *\n * The pool lives in `browser-threads.ts` and is found through `globalThis`\n * under a registered symbol, so the threads entry and the main build share\n * it even when bundled separately, and the main build carries none of it.\n */\n\nimport type { WorkerSetup } from '../parallel.ts';\nimport type { EngineWorkerSetup } from '../engine.ts';\nimport { compiledEngine } from '../engine.ts';\nimport type { ThreadProvider } from './browser-threads.ts';\nimport { THREADS_KEY } from './browser-threads.ts';\n\nexport { prepareThreads, threadsUnavailableReason } from './browser-threads.ts';\n\n/** Which build this is. */\nexport const PLATFORM = 'browser';\n\n/**\n * Default ceiling on solver storage. A tab gets far less memory than a Node\n * process, so an accidental flop solve fails fast with a clear message rather\n * than taking the tab down.\n */\nexport const DEFAULT_MAX_BYTES = 512 * 1024 * 1024;\n\n/** A spawned solver thread. */\nexport interface WorkerHandle {\n\tterminate(): void;\n}\n\n/** The engine threads `prepareThreads` started, if any. */\nfunction provider(): ThreadProvider | undefined {\n\treturn (globalThis as unknown as Record<symbol, ThreadProvider | undefined>)[THREADS_KEY];\n}\n\n/**\n * The most threads a solve can use now: one, plus the idle engine threads\n * when the WebAssembly engine is to run and can run over shared memory here.\n * @param engine whether the WebAssembly engine is to run\n */\nexport function threadLimit(engine: boolean): number {\n\tconst threads = provider();\n\tif (!engine || !threads || threads.idle() === 0) return 1;\n\treturn compiledEngine('shared') ? 1 + threads.idle() : 1;\n}\n\n/** One, plus every idle engine thread `prepareThreads` started. */\nexport function defaultWorkerCount(): number {\n\treturn 1 + (provider()?.idle() ?? 0);\n}\n\n/**\n * Why a solve gets fewer threads than it asked for, for the one warning.\n * @param engine whether the WebAssembly engine is to run\n */\nexport function threadAdvice(engine: boolean): string {\n\tif (!provider()) return 'call enableThreads() from poker-flopsolve/threads first, in a cross-origin isolated Web Worker';\n\tif (!engine) return 'browser threads run only the WebAssembly engine (default engine, f32 precision)';\n\treturn 'the other threads are held by open runs; close() a run to free its threads';\n}\n\n/** Never called: the browser build threads only the WebAssembly engine; see `threadLimit`. */\nexport function spawnWorker(_setup: WorkerSetup, _onError: (error: Error) => void): WorkerHandle {\n\tthrow new Error('The browser build threads only the WebAssembly engine; use workers: 1 with this solve');\n}\n\n/**\n * Hand one idle engine thread a solve's setup.\n * @param setup what the thread needs to join the solve\n * @param onError called if the thread dies, so the solve can stop waiting on it\n */\nexport function spawnEngineWorker(setup: EngineWorkerSetup, onError: (error: Error) => void): WorkerHandle {\n\tconst threads = provider();\n\tif (!threads) throw new Error('No engine threads; call enableThreads() from poker-flopsolve/threads first');\n\treturn threads.spawn(setup, onError);\n}\n","/**\n * Opt-in threads for the browser build: `poker-flopsolve/threads`.\n *\n * Purpose: let a page split a solve across cores, as Node does, without the\n * main build depending on it. Nothing here runs unless it is imported and\n * called; a solve that never asks for threads is the same, bit for bit, as\n * one in a build without this entry.\n *\n * In a browser, call `enableThreads` once, inside a Web Worker on a\n * cross-origin isolated page, and await it before solving:\n *\n * import { createRun, defineSpot } from 'poker-flopsolve';\n * import { enableThreads } from 'poker-flopsolve/threads';\n * const threads = await enableThreads(); // 1 if the page cannot thread\n * const run = createRun(defineSpot(config), { workers: threads });\n *\n * In Node this resolves to the thread count straight away: Node starts\n * threads with each solve and needs no preparation.\n */\n\nimport { prepareThreads, threadsUnavailableReason } from './platform/node.ts';\n\n/**\n * Start engine threads so that solves can use up to `count` threads, the\n * calling one included, and resolve to how many they can use: 1 where the\n * page cannot thread (see {@link threadsUnavailable}).\n *\n * Threads stay started between solves; a solve borrows them with\n * `workers: n` and returns them on `close()`. Calling again with a smaller\n * count stops the idle surplus, so `enableThreads(1)` stops them all.\n *\n * @param count threads wanted, the calling one included; defaults to the\n * machine's core count (`navigator.hardwareConcurrency` in a browser)\n */\nexport function enableThreads(count?: number): Promise<number> {\n\treturn prepareThreads(count);\n}\n\n/**\n * Why threads cannot run here, or null if they can. In a browser they need\n * a cross-origin isolated page (`Cross-Origin-Opener-Policy: same-origin`\n * and `Cross-Origin-Embedder-Policy: require-corp`) and a Web Worker to\n * solve in, since a page's main thread may not block.\n */\nexport function threadsUnavailable(): string | null {\n\treturn threadsUnavailableReason();\n}\n"],"mappings":";AAyCA,IAAM,OAAQ,WAAoD;AAmJ3D,IAAM,iBAAiB,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,WAAW,GAAG,OAAO,GAAG,QAAQ,GAAG,MAAM,EAAE;;;AClKjH,SAAS,YAAY,OAAgC;AAE3D,QAAM,aAAa;AACnB,QAAM,OAAO;AACb,QAAM,UAAU;AAChB,QAAM,OAAO;A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;AACD,QAAE,IAAI,gBAAgB,GAAG;AAAA,IAC1B;AAAA,EACD;AACA,SAAO,yBAAyB,MAAM,OAAO,KAAK,IAAI,QAAQ,IAAI,YAAY,CAAC,IAAI;AACpF;;;ACtMO,IAAM,oBAAoB,MAAM,OAAO;;;ACRvC,SAAS,cAAc,OAAiC;AAC9D,SAAO,eAAe,KAAK;AAC5B;AAQO,SAAS,qBAAoC;AACnD,SAAO,yBAAyB;AACjC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/engine.ts","../src/engine-thread.ts","../src/platform/browser-threads.ts","../src/platform/browser.ts","../src/threads.ts"],"sourcesContent":["/**\n * The WebAssembly traversal engine, set up.\n *\n * Purpose: lay a prepared spot out in one WebAssembly memory for\n * `assembly/engine.ts`, and give the solver its storage and a root traversal.\n *\n * The engine keeps the accumulators in its own memory as 32-bit floats; the\n * solver's `regret` and `strategySum` are views onto them, so everything that\n * reads storage from JavaScript — strategy queries, warm starts, `valuesAt` —\n * sees the very same numbers. It runs where WebAssembly SIMD is available,\n * on one thread or several; otherwise the JavaScript traversal in cfr.ts\n * runs. A second build, which only `poker-flopsolve/wasm-storage` carries,\n * keeps 16-bit and compact storage the same way (`EngineInput.storage`).\n *\n * WebAssembly memory is one buffer, but Chromium lets it reach wasm32's full\n * 4 GiB, plain or shared, made at that size or grown to it, where it refuses\n * any ArrayBuffer over 2 GiB less 2 MiB (measured in Chromium 153 by\n * bin/memory-ceiling.ts; issue #84). So compact storage needs no chunks of\n * its own in the engine: its chunks are regions of the one memory, laid out\n * as the JavaScript engine's buffers are.\n */\n\nimport { COMBOS } from './cards.ts';\nimport type { ActiveLists, CompactPlan, Layout, PlayerIndex, RegretStore, RootTraversal, SamplingPlan, SumStore } from './cfr.ts';\nimport { dcfrFactors, Mode, treeDepth } from './cfr.ts';\nimport type { HandSpace } from './hands.ts';\nimport type { Runouts } from './runouts.ts';\nimport type { Tree } from './tree.ts';\nimport { ENGINE_WASM } from './wasm/engine.ts';\nimport { ENGINE_SHARED_WASM } from './wasm/engine-shared.ts';\nimport type { ShardPlan } from './parallel.ts';\nimport { awaitThreads, THREAD_FAILED_ERROR, WORKER_START_ERROR, WORKER_START_MS } from './parallel.ts';\n\n/** The parts of the WebAssembly API used here, typed locally: the project builds without DOM typings. */\ninterface WasmApi {\n\tvalidate(bytes: Uint8Array): boolean;\n\tModule: new (bytes: Uint8Array) => object;\n\tInstance: new (module: object, imports: object) => { exports: Record<string, unknown> };\n\tMemory: new (descriptor: { initial: number; maximum?: number; shared?: boolean }) => { buffer: ArrayBuffer };\n}\n\nconst wasm = (globalThis as unknown as { WebAssembly?: WasmApi }).WebAssembly;\nconst modules: Record<'plain' | 'shared', object | null | undefined> = { plain: undefined, shared: undefined };\n\n/** The compiled engine, over plain or shared memory; null where unavailable. */\nexport function compiledEngine(kind: 'plain' | 'shared'): object | null {\n\treturn compileInto(modules, kind, kind === 'plain' ? ENGINE_WASM : ENGINE_SHARED_WASM);\n}\n\n/** Compile base64 WebAssembly into `cache[kind]` once; null there where unavailable. */\nfunction compileInto(cache: Record<'plain' | 'shared', object | null | undefined>, kind: 'plain' | 'shared', text: string): object | null {\n\tif (cache[kind] !== undefined) return cache[kind]!;\n\tcache[kind] = null;\n\ttry {\n\t\tif (!wasm) return null;\n\t\tconst bytes = Uint8Array.from(atob(text), (c) => c.charCodeAt(0));\n\t\tif (!wasm.validate(bytes)) return null;\n\t\tcache[kind] = new wasm.Module(bytes);\n\t} catch {\n\t\tcache[kind] = null;\n\t}\n\treturn cache[kind]!;\n}\n\n/**\n * The engine with 16-bit and compact storage (issue #84), as base64 for plain\n * and shared memory. Only `poker-flopsolve/wasm-storage` holds the bytes, so\n * a build that never imports it carries none of them; a solve opts in by\n * passing it as `SolveOptions.wasmStorage`.\n */\nexport interface WasmStorage {\n\treadonly plain: string;\n\treadonly shared: string;\n}\n\nconst storageModules = new WeakMap<WasmStorage, Record<'plain' | 'shared', object | null | undefined>>();\n\n/** The storage engine compiled, over plain or shared memory; null where unavailable. */\nfunction compiledStorage(source: WasmStorage, kind: 'plain' | 'shared'): object | null {\n\tlet cache = storageModules.get(source);\n\tif (!cache) storageModules.set(source, (cache = { plain: undefined, shared: undefined }));\n\treturn compileInto(cache, kind, source[kind]);\n}\n\nfunction compiled(): object | null {\n\treturn compiledEngine('plain');\n}\n\n/** Whether this platform can run the WebAssembly engine. */\nexport function engineAvailable(): boolean {\n\treturn compiled() !== null;\n}\n\n/** What the engine needs from a prepared spot. */\nexport interface EngineInput {\n\treadonly tree: Tree;\n\treadonly runouts: Runouts;\n\treadonly players: readonly [PlayerIndex, PlayerIndex];\n\treadonly layout: Layout;\n\treadonly active: ActiveLists;\n\treadonly hands: HandSpace;\n\treadonly runoutWeight: Float64Array;\n\treadonly chipScale: number;\n\t/** Chance sampling's layout, for `Approximations.chanceSampling`; unset for none. */\n\treadonly sampling?: SamplingPlan;\n\t/** Bytes left unused below the layout, rounded up to 16; tests set it to place every pointer past 2 GiB. */\n\treadonly lowBytes?: number;\n\t/**\n\t * 16-bit or compact storage, run by the storage engine `source` holds;\n\t * unset for 32-bit storage on the default engine. `quantised` keeps\n\t * the nodes before `compact.from` (all of them without `compact`) at 16\n\t * bits, as `precision: 'i16'` does.\n\t */\n\treadonly storage?: { readonly source: WasmStorage; readonly quantised: boolean; readonly compact: CompactPlan | null };\n}\n\n/** Compact storage's arrays, per chunk, as `Context` holds them; views onto the engine's memory. */\nexport interface EngineCompact {\n\treadonly regret: (Int8Array | Float32Array)[];\n\treadonly handShift: Uint8Array[] | null;\n\treadonly sum: Uint8Array[] | null;\n\treadonly sumShift: Uint8Array[] | null;\n\treadonly scale: Float64Array | null;\n}\n\n/** A running engine. */\nexport interface Engine {\n\t/** The accumulators, as views onto the engine's memory: 32-bit, or 16-bit with `EngineInput.storage`. */\n\treadonly regret: RegretStore;\n\treadonly strategySum: SumStore;\n\t/** With 16-bit storage, the per-block scales `Context.regretScale` and `sumScale` hold; else null. */\n\treadonly regretScale: Float64Array | null;\n\treadonly sumScale: Float64Array | null;\n\t/** With compact storage, its arrays; else null. */\n\treadonly compact: EngineCompact | null;\n\t/** Chance sampling's state, as views onto the engine's memory; null without sampling. */\n\treadonly sampling: { baseline: Float32Array; lastWalk: Int32Array; lastUpdate: Int32Array } | null;\n\t/** With shared storage, `Context.discounted` as a view onto the engine's memory; else null. */\n\treadonly discounted: Int32Array | null;\n\t/** Install as the solver's root traversal; `dcfr` picks the update rule. */\n\troot(dcfr: boolean): RootTraversal;\n\t/** Release worker threads, if any. */\n\tclose(): void;\n\t/** Threads doing the work, this one included. */\n\treadonly threads: number;\n\t/** With threads, where each traversal's time went (see `PROFILE`); null on one thread. */\n\treadonly profile: Float64Array | null;\n}\n\n/**\n * Slots of `Engine.profile`, milliseconds summed over every threaded\n * traversal (issue #133): the main thread's walk above the split before\n * the threads start (`collect`) and after they finish (`override`), its\n * wait for the others, adding their partial values, and from `busy` on\n * the time each thread spent walking boards, the main thread's first;\n * `run` is the whole threaded traversal. A few clock reads a thread a\n * traversal, so it is always on.\n */\nexport const PROFILE = { traversals: 0, collect: 1, override: 2, wait: 3, reduce: 4, run: 5, busy: 6 } as const;\n\n/** Each threaded run's profile, by the solver it runs for: read by benches, not part of the API. */\nexport const threadProfiles = new WeakMap<object, Float64Array>();\n\n/** The split round's boards in the order threads take them, and each board's last walk time, per traverser. */\nexport interface ScheduleViews {\n\treadonly order: Int32Array;\n\treadonly cost: Float64Array;\n}\n\n/** Bytes of a schedule for `boards` boards. */\nexport function scheduleBytes(boards: number): number {\n\treturn Math.ceil(boards / 2) * 8 + 2 * boards * 8;\n}\n\n/** A schedule's views onto its buffer. */\nexport function scheduleViews(buffer: SharedArrayBuffer, boards: number): ScheduleViews {\n\treturn {\n\t\torder: new Int32Array(buffer, 0, boards),\n\t\tcost: new Float64Array(buffer, Math.ceil(boards / 2) * 8, 2 * boards),\n\t};\n}\n\n/** What an engine worker needs; see src/engine-worker.ts. */\nexport interface EngineWorkerSetup {\n\treadonly memory: unknown;\n\treadonly module: unknown;\n\treadonly header: number;\n\treadonly maxActions: number;\n\treadonly exchange: readonly [number, number, number, number];\n\t/** The split round and its number of boards. */\n\treadonly shard: readonly [number, number];\n\treadonly entryNodes: Int32Array;\n\treadonly rootMe: number;\n\treadonly rootOpp: number;\n\t/** Where each board's values for each entry go: `boards × entries` rows, board-major. */\n\treadonly boardValues: number;\n\t/** The boards' walking order and their last costs; see `scheduleViews`. */\n\treadonly schedule: SharedArrayBuffer;\n\treadonly stride: number;\n\treadonly control: SharedArrayBuffer;\n\treadonly settings: SharedArrayBuffer;\n\t/** With shared storage: where the discount marks, the block table and the weighted nodes (or 0) sit. */\n\treadonly shared?: readonly [number, number, number];\n\t/** Set for the storage engine, whose updates need the iteration on every walk. */\n\treadonly storage?: boolean;\n\t/**\n\t * With chance sampling, `setSampling`'s arguments as the main thread\n\t * passed them: its state is in the shared memory, and each thread walks\n\t * and marks only its own runouts' deals.\n\t */\n\treadonly sampling?: SamplingArgs;\n\t/** `Engine.profile`'s buffer and this thread's slot in it. */\n\treadonly profile: readonly [SharedArrayBuffer, number];\n\t/** This thread's share of the storage to touch before it reports ready: `from, to` byte pairs; see `touchShares`. */\n\treadonly touch: readonly number[];\n}\n\n/** Bytes between two touches: a page of memory, the smallest a platform here maps. */\nconst TOUCH_STEP = 4096;\n\n/**\n * Split empty storage into one share a thread, as `from, to` byte pairs.\n *\n * Fresh memory is mapped page by page as it is first written, and left to\n * the first iteration that happens with every thread writing at once, each\n * waiting on the others: measured on a flop on 4 threads, it took 380 ms\n * where later ones took 75, and 1.3 s against 70 ms under chance sampling,\n * whose first iteration walks every deal. Written once up front, a share a\n * thread and in order, the same pages took 50–250 ms.\n *\n * @param ranges the pieces, as `[from, to]` in bytes\n * @param shares how many threads share them\n */\nfunction touchShares(ranges: readonly (readonly [number, number])[], shares: number): number[][] {\n\tconst total = ranges.reduce((sum, [from, to]) => sum + (to - from), 0);\n\tconst each = Math.ceil(total / shares / TOUCH_STEP) * TOUCH_STEP;\n\tconst out: number[][] = Array.from({ length: shares }, () => []);\n\tlet share = 0;\n\tlet room = each;\n\tfor (const [start, to] of ranges) {\n\t\tlet from = start;\n\t\twhile (from < to) {\n\t\t\tconst take = Math.min(room, to - from);\n\t\t\tout[share].push(from, from + take);\n\t\t\tfrom += take;\n\t\t\troom -= take;\n\t\t\tif (room === 0 && share < shares - 1) {\n\t\t\t\tshare++;\n\t\t\t\troom = each;\n\t\t\t}\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * Write a zero to each page of a share of empty storage, so the memory is\n * mapped before the solve needs it. Only over pieces still all zeros, which\n * `createEngine` marks: reading a byte to write it back would be safe on any\n * piece, but maps each page twice, once to read and once to write, and an\n * atomic write took several times as long. Nothing else writes to a share\n * between the engine's memory being filled and its threads being ready.\n */\nfunction touchStorage(bytes: Uint8Array, share: readonly number[]): void {\n\tfor (let r = 0; r < share.length; r += 2) {\n\t\tfor (let at = share[r]; at < share[r + 1]; at += TOUCH_STEP) bytes[at] = 0;\n\t}\n}\n\n/** `EngineExports.setSampling`'s arguments, in order. */\nexport type SamplingArgs = Parameters<EngineExports['setSampling']>;\n\n/** How a pool starts its workers; the platform layer supplies it. */\nexport type SpawnEngineWorker = (setup: EngineWorkerSetup, onError: (error: Error) => void) => { terminate(): void };\n\n/** The most memory the engine lays out: just under wasm32's 4 GB. */\nconst MAX_MEMORY = 0xffff0000;\n\n/**\n * Control slots shared with engine workers. `failed` is set, never cleared,\n * once any thread's part of a step threw: the main thread waits in\n * `Atomics.wait` and so never sees a worker's error event while a step runs.\n */\nexport const ENGINE_CONTROL = { generation: 0, done: 1, command: 2, mode: 3, traverser: 4, ready: 5, failed: 6, next: 7, size: 8 } as const;\n\n/**\n * Lay a spot out in a fresh memory and instantiate the engine over it, or\n * null where unavailable. With `pool`, the memory is shared and that many\n * threads split the plan's round between them, each taking the next board\n * off a shared queue (`runThreaded`), where the JavaScript engine's pool in\n * src/parallel.ts gives each worker a fixed slice.\n */\nexport function createEngine(\n\tinput: EngineInput,\n\tpool?: {\n\t\tplan: ShardPlan;\n\t\tthreads: number;\n\t\tspawn: SpawnEngineWorker;\n\t\t/** The shortest a step waits for the other threads; see `awaitThreads` in src/parallel.ts. */\n\t\tbackstopFloorMs?: number;\n\t},\n): Engine | null {\n\tconst shared = pool !== undefined;\n\tconst storage = input.storage ?? null;\n\tconst compiledModule = storage\n\t\t? compiledStorage(storage.source, shared ? 'shared' : 'plain')\n\t\t: compiledEngine(shared ? 'shared' : 'plain');\n\tif (!compiledModule || !wasm) return null;\n\tconst { tree, runouts, layout, active, hands } = input;\n\tconst compact = storage?.compact ?? null;\n\tconst quantised = storage?.quantised ?? false;\n\t// Its accumulators alone would pass wasm32's 4 GB, so no engine; checked\n\t// before anything is built. Such a layout is also the only kind that\n\t// holds offsets as Float64, which the engine's 32-bit offset table could\n\t// not take.\n\tconst width = quantised ? 2 : 4;\n\tconst compactBytes = !compact\n\t\t? 0\n\t\t: compact.float\n\t\t\t? layout.compactSlots * 4\n\t\t\t: (layout.compactSlots + (compact.perHand ? layout.compactHands : 0)) * (compact.sums ? 2 : 1);\n\tif (layout.totalSlots * width * 2 + compactBytes > MAX_MEMORY || !(layout.offset instanceof Int32Array)) return null;\n\tconst threads = pool ? pool.threads : 1;\n\n\tconst flatten = (parts: readonly Int32Array[]): [Int32Array, Int32Array] => {\n\t\tconst bases = new Int32Array(parts.length + 1);\n\t\tfor (let i = 0; i < parts.length; i++) bases[i + 1] = bases[i] + parts[i].length;\n\t\tconst flat = new Int32Array(bases[parts.length]);\n\t\tparts.forEach((part, i) => flat.set(part, bases[i]));\n\t\treturn [bases, flat];\n\t};\n\tconst [upRound, upStart] = flatten(hands.upStart);\n\tconst [childRound, childStart] = flatten(runouts.childStart);\n\tconst [orbitRound, orbitStart] = flatten(runouts.orbitStart);\n\tlet maxCount = 4;\n\tfor (let i = 0; i < active.count.length; i++) if (active.count[i] > maxCount) maxCount = active.count[i];\n\tconst stride = Math.ceil(maxCount / 4) * 4;\n\tconst maxActions = Math.max(1, layout.maxActions);\n\tconst depths = treeDepth(tree) + 2;\n\tconst rowBytes = stride * 4;\n\tconst depthBytes = rowBytes * (3 + 2 * maxActions);\n\n\t// `empty`: allocated as zeros and left so until the first iteration, which\n\t// is what `touchStorage` may write zeros over. A piece filled in below,\n\t// before the threads start, says false.\n\tconst pieces: { data: ArrayBufferView | null; bytes: number; empty: boolean }[] = [];\n\tconst add = (data: ArrayBufferView | null, bytes = data ? data.byteLength : 0, empty = data === null): number => {\n\t\tpieces.push({ data, bytes: Math.ceil(Math.max(bytes, 4) / 16) * 16, empty });\n\t\treturn pieces.length - 1;\n\t};\n\t// Shared by every thread, in header order.\n\tconst common = [\n\t\tadd(tree.kind), add(tree.round), add(Uint8Array.from(tree.player, (p) => (p < 0 ? 255 : p))), add(tree.firstEdge),\n\t\tadd(tree.numEdges), add(tree.edgeChild), add(tree.payoff), add(layout.offset), add(layout.rowStart),\n\t\tadd(active.roundBase), add(active.start), add(new Int32Array(active.count)), add(active.cardA), add(active.cardB),\n\t\tadd(active.strength), add(active.packed), add(new Float32Array(active.multiplicity)), add(active.memberStart),\n\t\tadd(active.memberA), add(active.memberB), add(upRound), add(upStart), add(hands.up),\n\t\tadd(hands.sameStart), add(hands.same), add(childRound), add(childStart), add(orbitRound), add(orbitStart),\n\t\tadd(input.runoutWeight),\n\t\tadd(null, layout.totalSlots * width), // regret\n\t\tadd(null, layout.totalSlots * width), // strategy sums\n\t];\n\tconst REGRET = common[common.length - 2];\n\tconst SUMS = common[common.length - 1];\n\t// Each thread's own.\n\tconst own = Array.from({ length: threads }, () => ({\n\t\tbuffers: add(null, depths * depthBytes),\n\t\tcardSums: add(null, 52 * 8 + stride * 8),\n\t\trootMe: add(null, rowBytes),\n\t\trootOpp: add(null, rowBytes),\n\t\theader: add(null, 40 * 4, false),\n\t}));\n\t// The exchange between threads.\n\tconst entries = pool ? pool.plan.entryNodes.length : 0;\n\tconst entryIndexOf = pool ? add(pool.plan.entryIndexOf) : -1;\n\tconst reach = pool ? add(null, entries * 2 * rowBytes) : -1;\n\tconst values = pool ? add(null, entries * rowBytes) : -1;\n\t// Each board's values, apart, so their sum does not depend on which thread walked which.\n\tconst boardValues = pool ? add(null, pool.plan.boards * entries * rowBytes) : -1;\n\t// Chance sampling, only when asked for.\n\tconst plan = input.sampling;\n\tconst sample = plan\n\t\t? {\n\t\t\t\tbaseOffset: add(plan.baseOffset), boardOffset: add(plan.boardOffset), walkOffset: add(plan.walkOffset),\n\t\t\t\tblockOffset: add(layout.blockOffset), baseline: add(null, plan.values * 4), lastWalk: add(null, plan.walks * 4),\n\t\t\t\tlastUpdate: add(null, plan.blocks * 4),\n\t\t\t}\n\t\t: null;\n\t// History sharing's once-an-iteration discount marks, only when storage is shared.\n\tconst share = layout.shared\n\t\t? {\n\t\t\t\tmarks: add(null, layout.blocks * 4),\n\t\t\t\tblockOffset: sample ? sample.blockOffset : add(layout.blockOffset),\n\t\t\t\tweighted: layout.reachWeighted ? add(layout.reachWeighted) : -1,\n\t\t\t}\n\t\t: null;\n\t// 16-bit and compact storage's settings, scales and chunks, only on the storage engine.\n\tconst chunks = compact ? layout.chunkSlots.length : 0;\n\tconst stored = storage\n\t\t? {\n\t\t\t\tblock: add(null, 128, false),\n\t\t\t\tblockOffset: sample ? sample.blockOffset : share ? share.blockOffset : add(layout.blockOffset),\n\t\t\t\tregretScale: quantised ? add(null, layout.blocks * 8) : -1,\n\t\t\t\tsumScale: quantised ? add(null, layout.blocks * 8) : -1,\n\t\t\t\tcompactChunk: compact ? add(layout.compactChunk) : -1,\n\t\t\t\thandOffset: compact ? add(new Int32Array(layout.handOffset!)) : -1,\n\t\t\t\ttables: compact ? add(null, chunks * 4 * 5, false) : -1,\n\t\t\t\tregrets: layout.chunkSlots.map((slots) => add(null, slots * (compact!.float ? 4 : 1))),\n\t\t\t\tshifts: compact?.perHand ? layout.chunkHands.map((count) => add(null, count)) : [],\n\t\t\t\tsums: compact?.sums ? layout.chunkSlots.map((slots) => add(null, slots)) : [],\n\t\t\t\tsumShifts: compact?.sums ? layout.chunkHands.map((count) => add(null, count)) : [],\n\t\t\t\tcompactScale: compact && !compact.perHand && !compact.float ? add(null, layout.blocks * 8) : -1,\n\t\t\t}\n\t\t: null;\n\n\tconst offsets: number[] = [];\n\tlet total = 64 + Math.ceil(Math.max(input.lowBytes ?? 0, 0) / 16) * 16;\n\tfor (const piece of pieces) {\n\t\toffsets.push(total);\n\t\ttotal += piece.bytes;\n\t}\n\tif (total > MAX_MEMORY) return null;\n\tconst pages = Math.ceil(total / 65536) + 1;\n\tconst memory = shared ? new wasm.Memory({ initial: pages, maximum: pages, shared: true }) : new wasm.Memory({ initial: pages });\n\tconst bytes = new Uint8Array(memory.buffer);\n\tpieces.forEach((piece, i) => {\n\t\tif (piece.data) bytes.set(new Uint8Array(piece.data.buffer, piece.data.byteOffset, piece.data.byteLength), offsets[i]);\n\t});\n\t// The accumulators and whatever else is allocated empty and large: the\n\t// pages the first iteration would otherwise map as it met them.\n\tconst touch = touchShares(\n\t\tpieces.flatMap((piece, i) => (piece.empty && piece.bytes >= 16 * TOUCH_STEP ? [[offsets[i], offsets[i] + piece.bytes] as const] : [])),\n\t\tthreads,\n\t);\n\tfor (const mine of own) {\n\t\tconst head = new Uint32Array(memory.buffer, offsets[mine.header], 40);\n\t\tcommon.forEach((slot, i) => (head[i] = offsets[slot]));\n\t\thead[common.length] = offsets[mine.buffers];\n\t\thead[common.length + 1] = depthBytes;\n\t\thead[common.length + 2] = rowBytes;\n\t\thead[common.length + 3] = offsets[mine.cardSums];\n\t\thead[common.length + 4] = input.chipScale;\n\t\tif (stored) head[common.length + 5] = offsets[stored.block];\n\t}\n\tif (stored) {\n\t\tconst at = (slot: number): number => (slot >= 0 ? offsets[slot] : 0);\n\t\tconst block = new Uint32Array(memory.buffer, offsets[stored.block], 20);\n\t\tblock.set([\n\t\t\tquantised ? 1 : 0, compact ? compact.from : 255, !compact ? 0 : compact.float ? 3 : compact.perHand ? 1 : 2,\n\t\t\tcompact?.sums ? 1 : 0, compact?.stochastic ? 1 : 0, compact?.steps ?? 127,\n\t\t\tat(stored.regretScale), at(stored.sumScale), offsets[stored.blockOffset], at(stored.compactChunk),\n\t\t\tat(stored.handOffset),\n\t\t]);\n\t\tif (compact) {\n\t\t\t// Per chunk: where its regrets, hand scales, sums and sum scales sit, and its first slot.\n\t\t\tconst tables = offsets[stored.tables];\n\t\t\tconst table = new Uint32Array(memory.buffer, tables, chunks * 5);\n\t\t\tfor (let c = 0; c < chunks; c++) {\n\t\t\t\ttable[c] = offsets[stored.regrets[c]];\n\t\t\t\ttable[chunks + c] = stored.shifts.length ? offsets[stored.shifts[c]] : 0;\n\t\t\t\ttable[2 * chunks + c] = stored.sums.length ? offsets[stored.sums[c]] : 0;\n\t\t\t\ttable[3 * chunks + c] = stored.sumShifts.length ? offsets[stored.sumShifts[c]] : 0;\n\t\t\t\ttable[4 * chunks + c] = layout.chunkStart[c] >>> 0;\n\t\t\t}\n\t\t\tblock.set([tables, tables + chunks * 4, tables + chunks * 8, tables + chunks * 12, tables + chunks * 16, at(stored.compactScale)], 11);\n\t\t}\n\t}\n\t// The update rule's factors, as float64, which the storage engine reads before each walk.\n\tconst factors = stored ? new Float64Array(memory.buffer, offsets[stored.block] + 80, 4) : null;\n\n\tconst instance = new wasm.Instance(compiledModule, { env: { memory, abort: () => { throw new Error('engine abort'); } } });\n\tconst exports = instance.exports as unknown as EngineExports;\n\texports.init(offsets[own[0].header]);\n\texports.setMaxActions(maxActions);\n\tlet samplingViews: Engine['sampling'] = null;\n\tlet samplingArgs: SamplingArgs | null = null;\n\tif (plan && sample) {\n\t\tlet mask = 0;\n\t\tfor (let r = 0; r < plan.rounds.length; r++) if (plan.rounds[r]) mask |= 1 << r;\n\t\tsamplingArgs = [\n\t\t\tmask, plan.p, plan.every, plan.unbiased ? 1 : 0, plan.catchUp ? 1 : 0,\n\t\t\toffsets[sample.baseOffset], offsets[sample.boardOffset], offsets[sample.walkOffset],\n\t\t\toffsets[sample.baseline], offsets[sample.lastWalk], offsets[sample.lastUpdate], offsets[sample.blockOffset],\n\t\t];\n\t\tconst a = samplingArgs;\n\t\texports.setSampling(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11]);\n\t\tsamplingViews = {\n\t\t\tbaseline: new Float32Array(memory.buffer, offsets[sample.baseline], plan.values),\n\t\t\tlastWalk: new Int32Array(memory.buffer, offsets[sample.lastWalk], plan.walks),\n\t\t\tlastUpdate: new Int32Array(memory.buffer, offsets[sample.lastUpdate], plan.blocks),\n\t\t};\n\t}\n\n\tconst weightedAt = share && share.weighted >= 0 ? offsets[share.weighted] : 0;\n\tif (share) exports.setShared(offsets[share.marks], offsets[share.blockOffset], weightedAt);\n\tconst discounted = share ? new Int32Array(memory.buffer, offsets[share.marks], layout.blocks) : null;\n\n\tconst regret: RegretStore = quantised\n\t\t? new Int16Array(memory.buffer, offsets[REGRET], layout.totalSlots)\n\t\t: new Float32Array(memory.buffer, offsets[REGRET], layout.totalSlots);\n\tconst strategySum: SumStore = quantised\n\t\t? new Uint16Array(memory.buffer, offsets[SUMS], layout.totalSlots)\n\t\t: new Float32Array(memory.buffer, offsets[SUMS], layout.totalSlots);\n\tconst scaleView = (slot: number): Float64Array | null =>\n\t\tslot >= 0 ? new Float64Array(memory.buffer, offsets[slot], layout.blocks) : null;\n\tconst compactViews: EngineCompact | null = stored && compact\n\t\t? {\n\t\t\t\tregret: stored.regrets.map((slot, c) =>\n\t\t\t\t\tcompact.float\n\t\t\t\t\t\t? new Float32Array(memory.buffer, offsets[slot], layout.chunkSlots[c])\n\t\t\t\t\t\t: new Int8Array(memory.buffer, offsets[slot], layout.chunkSlots[c]),\n\t\t\t\t),\n\t\t\t\thandShift: compact.perHand ? stored.shifts.map((slot, c) => new Uint8Array(memory.buffer, offsets[slot], layout.chunkHands[c])) : null,\n\t\t\t\tsum: compact.sums ? stored.sums.map((slot, c) => new Uint8Array(memory.buffer, offsets[slot], layout.chunkSlots[c])) : null,\n\t\t\t\tsumShift: compact.sums ? stored.sumShifts.map((slot, c) => new Uint8Array(memory.buffer, offsets[slot], layout.chunkHands[c])) : null,\n\t\t\t\tscale: scaleView(stored.compactScale),\n\t\t\t}\n\t\t: null;\n\tconst me = new Float32Array(memory.buffer, offsets[own[0].rootMe], stride);\n\tconst opp = new Float32Array(memory.buffer, offsets[own[0].rootOpp], stride);\n\tconst result = new Float64Array(COMBOS);\n\tconst rootList = (player: 0 | 1): [number, number] => {\n\t\tconst slot = active.roundBase[0] * 2 + player;\n\t\treturn [active.start[slot], active.count[slot]];\n\t};\n\tconst settingsFor = (mode: number, iterWeight: number, dcfr: boolean): [number, number, number, number, number] => {\n\t\tif (mode === Mode.Train && dcfr) {\n\t\t\tconst { keepPositive, keepNegative, keepSum } = dcfrFactors(iterWeight);\n\t\t\treturn [keepPositive, keepNegative, keepSum, 1, 0];\n\t\t}\n\t\treturn [1, 1, 1, iterWeight, dcfr ? 0 : 1];\n\t};\n\n\t// Threads: workers over the same memory, each with its own header.\n\tlet control: Int32Array | null = null;\n\tlet settings: Float64Array | null = null;\n\tlet profile: Float64Array | null = null;\n\tlet schedule: ScheduleViews | null = null;\n\tconst workers: { terminate(): void }[] = [];\n\tlet failure: Error | null = null;\n\tif (!pool) touchStorage(bytes, touch[0]);\n\tif (pool) {\n\t\tconst plan = pool.plan;\n\t\tconst controlBuffer = new SharedArrayBuffer(ENGINE_CONTROL.size * 4);\n\t\tconst settingsBuffer = new SharedArrayBuffer(8 * 8);\n\t\tcontrol = new Int32Array(controlBuffer);\n\t\tsettings = new Float64Array(settingsBuffer);\n\t\tconst profileBuffer = new SharedArrayBuffer(8 * (PROFILE.busy + threads));\n\t\tprofile = new Float64Array(profileBuffer);\n\t\tconst scheduleBuffer = new SharedArrayBuffer(scheduleBytes(plan.boards));\n\t\tschedule = scheduleViews(scheduleBuffer, plan.boards);\n\t\tfor (let i = 0; i < plan.boards; i++) schedule.order[i] = i;\n\t\texports.setExchange(offsets[entryIndexOf], offsets[reach], offsets[values], stride);\n\t\tfor (let w = 1; w < threads; w++) {\n\t\t\tconst setup: EngineWorkerSetup = {\n\t\t\t\tmemory, module: compiledModule, header: offsets[own[w].header], maxActions,\n\t\t\t\texchange: [offsets[entryIndexOf], offsets[reach], offsets[values], stride],\n\t\t\t\tshard: [plan.round, plan.boards],\n\t\t\t\tentryNodes: plan.entryNodes,\n\t\t\t\trootMe: offsets[own[w].rootMe], rootOpp: offsets[own[w].rootOpp],\n\t\t\t\tboardValues: offsets[boardValues], schedule: scheduleBuffer,\n\t\t\t\tstride, control: controlBuffer, settings: settingsBuffer,\n\t\t\t\t...(share ? { shared: [offsets[share.marks], offsets[share.blockOffset], weightedAt] as const } : {}),\n\t\t\t\t...(stored ? { storage: true } : {}),\n\t\t\t\t...(samplingArgs ? { sampling: samplingArgs } : {}),\n\t\t\t\tprofile: [profileBuffer, PROFILE.busy + w],\n\t\t\t\ttouch: touch[w],\n\t\t\t};\n\t\t\tworkers.push(pool.spawn(setup, (error) => {\n\t\t\t\tfailure ??= error;\n\t\t\t\tAtomics.store(control!, ENGINE_CONTROL.ready, threads);\n\t\t\t\tAtomics.add(control!, ENGINE_CONTROL.done, threads);\n\t\t\t\tAtomics.notify(control!, ENGINE_CONTROL.done);\n\t\t\t\tAtomics.notify(control!, ENGINE_CONTROL.ready);\n\t\t\t}));\n\t\t}\n\t\t// This thread's share, while the others start and touch theirs.\n\t\ttouchStorage(bytes, touch[0]);\n\t\t// A worker that fails to start reports it by an event, which cannot\n\t\t// be delivered while this thread waits here, so the wait is bounded.\n\t\tconst deadline = Date.now() + WORKER_START_MS;\n\t\tfor (;;) {\n\t\t\tconst ready = Atomics.load(control, ENGINE_CONTROL.ready);\n\t\t\tif (ready >= threads - 1 || failure) break;\n\t\t\tif (Date.now() > deadline) failure = new Error(WORKER_START_ERROR);\n\t\t\telse Atomics.wait(control, ENGINE_CONTROL.ready, ready, 20);\n\t\t}\n\t\tif (failure) {\n\t\t\tfor (const worker of workers) worker.terminate();\n\t\t\tthrow failure;\n\t\t}\n\t}\n\n\tconst failed = (): Error | null =>\n\t\tfailure ?? (control && Atomics.load(control, ENGINE_CONTROL.failed) ? new Error(THREAD_FAILED_ERROR) : null);\n\n\t// The iteration a step is for, and its rule, which shared storage's threads need.\n\tlet iteration = 0;\n\tlet dcfrRule = 0;\n\tconst run = (asked: number, traverser: 0 | 1, iterWeight: number, dcfr: boolean): Float64Array => {\n\t\t// Once any thread has failed, so does every step after, before it\n\t\t// touches anything.\n\t\tconst dead = failed();\n\t\tif (dead) throw dead;\n\t\t// The engine knows three modes; the current profile is its Train\n\t\t// with updates off.\n\t\tconst apply = asked === Mode.Current ? 0 : 1;\n\t\tconst mode = asked === Mode.Current ? Mode.Train : asked;\n\t\tfor (const player of [0, 1] as const) {\n\t\t\tconst [from, count] = rootList(player);\n\t\t\tconst into = player === traverser ? me : opp;\n\t\t\tconst weights = input.players[player].weights;\n\t\t\tfor (let i = 0; i < count; i++) into[i] = weights[active.list[from + i]];\n\t\t}\n\t\tconst [positive, negative, sum, weight, clamp] = settingsFor(mode, iterWeight, dcfr);\n\t\titeration = mode === Mode.Train ? iterWeight : 0;\n\t\tdcfrRule = dcfr ? 1 : 0;\n\t\tif (plan || share || stored) exports.setIteration(iteration, dcfrRule);\n\t\t// CFR+ at 16 bits or compact floors a negative regret, as `updateQuantised`\n\t\t// and `updateCompact` do (one only a warm start could bring); 32-bit storage keeps it.\n\t\tfactors?.set([positive, mode === Mode.Train && !dcfr ? 0 : negative, sum, weight]);\n\t\tlet at: number;\n\t\tif (!pool) {\n\t\t\tif (apply === 0) exports.setPhase(0, 0);\n\t\t\ttry {\n\t\t\t\tat = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp) >>> 0;\n\t\t\t} finally {\n\t\t\t\tif (apply === 0) exports.setPhase(0, 1);\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tat = runThreaded(mode, traverser, apply, positive, negative, sum, weight, clamp);\n\t\t\t} catch (error) {\n\t\t\t\t// This thread's own part may have thrown with the workers still\n\t\t\t\t// walking; no later step may run over them.\n\t\t\t\tAtomics.store(control!, ENGINE_CONTROL.failed, 1);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tconst [, count] = rootList(traverser);\n\t\tconst values32 = new Float32Array(memory.buffer, at, count);\n\t\tfor (let i = 0; i < count; i++) result[i] = values32[i];\n\t\treturn result;\n\t};\n\n\t/** One threaded traversal, returning where the root values are. */\n\tconst runThreaded = (\n\t\tmode: number, traverser: 0 | 1, apply: number,\n\t\tpositive: number, negative: number, sum: number, weight: number, clamp: number,\n\t): number => {\n\t\tconst plan = pool!.plan;\n\t\tconst { order, cost } = schedule!;\n\t\tconst clock = performance.now();\n\t\t// Collect: walk above the split, recording what the workers need.\n\t\texports.setShard(plan.round, 0, 0);\n\t\texports.setPhase(1, 0);\n\t\texports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);\n\t\tconst collected = performance.now();\n\t\t// Costliest boards first, by what they took on this traverser's last\n\t\t// training walk, so the last boards anyone takes are the cheap ones.\n\t\t// Only training walks record costs: a best-response or current-profile\n\t\t// pass, unsampled and without updates, costs a board differently.\n\t\tconst costs = cost.subarray(traverser * plan.boards, (traverser + 1) * plan.boards);\n\t\tconst timed = mode === Mode.Train && apply === 1;\n\t\torder.sort((a, b) => costs[b] - costs[a] || a - b);\n\t\t// Every thread takes boards off the order until none are left.\n\t\tsettings!.set([positive, negative, sum, weight, clamp, apply, iteration, dcfrRule]);\n\t\tAtomics.store(control!, ENGINE_CONTROL.done, 0);\n\t\tAtomics.store(control!, ENGINE_CONTROL.next, 0);\n\t\tAtomics.store(control!, ENGINE_CONTROL.mode, mode);\n\t\tAtomics.store(control!, ENGINE_CONTROL.traverser, traverser);\n\t\tAtomics.store(control!, ENGINE_CONTROL.command, 0);\n\t\tAtomics.add(control!, ENGINE_CONTROL.generation, 1);\n\t\tAtomics.notify(control!, ENGINE_CONTROL.generation);\n\t\tconst dispatched = performance.now();\n\t\texports.setPhase(0, apply);\n\t\tconst heap = new Float32Array(memory.buffer);\n\t\tconst into = offsets[boardValues] >>> 2;\n\t\tfor (;;) {\n\t\t\tconst taken = Atomics.add(control!, ENGINE_CONTROL.next, 1);\n\t\t\tif (taken >= plan.boards) break;\n\t\t\tconst board = order[taken];\n\t\t\texports.setShard(plan.round, board, board + 1);\n\t\t\tconst started = performance.now();\n\t\t\tfor (let entry = 0; entry < entries; entry++) {\n\t\t\t\tconst slot = offsets[reach] + entry * 2 * rowBytes;\n\t\t\t\tconst out = exports.runChance(mode, traverser, plan.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp) >>> 2;\n\t\t\t\theap.copyWithin(into + (board * entries + entry) * stride, out, out + stride);\n\t\t\t}\n\t\t\tif (timed) costs[board] = performance.now() - started;\n\t\t}\n\t\tconst walked = performance.now();\n\t\t// A thread whose walk throws says so in `failed` and counts itself\n\t\t// done, as its error event cannot reach this thread while it waits.\n\t\t// One killed without unwinding does neither, hence the backstop.\n\t\tfailure ??= awaitThreads(\n\t\t\tcontrol!, ENGINE_CONTROL.done, threads - 1, dispatched, pool!.backstopFloorMs, () => failure !== null,\n\t\t);\n\t\tconst dead = failed();\n\t\tif (dead) throw dead;\n\t\tconst waited = performance.now();\n\t\t// The boards' values summed in board order, whoever walked them.\n\t\tconst valueView = new Float32Array(memory.buffer, offsets[values], entries * stride);\n\t\tvalueView.fill(0);\n\t\tfor (let board = 0; board < plan.boards; board++) {\n\t\t\tconst rows = into + board * entries * stride;\n\t\t\tfor (let i = 0; i < entries * stride; i++) valueView[i] += heap[rows + i];\n\t\t}\n\t\tconst reduced = performance.now();\n\t\t// Finish above the split from the totals, now applying updates\n\t\t// unless this is a current-profile read.\n\t\texports.setShard(plan.round, 0, 0);\n\t\texports.setPhase(2, apply);\n\t\tconst at = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp) >>> 0;\n\t\texports.setPhase(0, 1);\n\t\texports.setShard(-1, 0, 0);\n\t\tconst p = profile!;\n\t\tconst finished = performance.now();\n\t\tp[PROFILE.traversals]++;\n\t\tp[PROFILE.collect] += collected - clock;\n\t\tp[PROFILE.busy] += walked - dispatched;\n\t\tp[PROFILE.wait] += waited - walked;\n\t\tp[PROFILE.reduce] += reduced - waited;\n\t\tp[PROFILE.override] += finished - reduced;\n\t\tp[PROFILE.run] += finished - clock;\n\t\treturn at;\n\t};\n\n\treturn {\n\t\tregret,\n\t\tstrategySum,\n\t\tregretScale: stored ? scaleView(stored.regretScale) : null,\n\t\tsumScale: stored ? scaleView(stored.sumScale) : null,\n\t\tcompact: compactViews,\n\t\tsampling: samplingViews,\n\t\tdiscounted,\n\t\tthreads,\n\t\tprofile,\n\t\troot(dcfr) {\n\t\t\treturn (mode, traverser, iterWeight) => run(mode, traverser, iterWeight, dcfr);\n\t\t},\n\t\tclose() {\n\t\t\tif (!control) return;\n\t\t\tAtomics.store(control, ENGINE_CONTROL.command, 1);\n\t\t\tAtomics.add(control, ENGINE_CONTROL.generation, 1);\n\t\t\tAtomics.notify(control, ENGINE_CONTROL.generation);\n\t\t\tfor (const worker of workers) worker.terminate();\n\t\t},\n\t};\n}\n\n/**\n * The engine's exports. A pointer one returns is a wasm32 `usize`, which\n * JavaScript receives as a signed 32-bit integer: read it with `>>> 0`, or\n * any address past 2 GiB comes back negative (#62).\n */\nexport interface EngineExports {\n\tinit(header: number): void;\n\tsetMaxActions(count: number): void;\n\tsetShard(round: number, start: number, end: number): void;\n\tsetExchange(entries: number, reach: number, values: number, stride: number): void;\n\tsetPhase(phase: number, apply: number): void;\n\tsetSampling(\n\t\trounds: number, p: number, every: number, unbiased: number, catchUp: number,\n\t\tbaseOffsets: number, boardOffsets: number, walkOffsets: number,\n\t\tbaselines: number, lastWalks: number, lastUpdates: number, blockOffsets: number,\n\t): void;\n\tsetIteration(t: number, dcfr: number): void;\n\tsetShared(marks: number, blockOffsets: number, weighted: number): void;\n\trun(mode: number, traverser: number, me: number, opp: number, positive: number, negative: number, sum: number, weight: number, clamp: number): number;\n\trunChance(mode: number, traverser: number, node: number, me: number, opp: number, positive: number, negative: number, sum: number, weight: number, clamp: number): number;\n}\n","/**\n * One thread of a WebAssembly solve: the loop every engine worker runs.\n *\n * Purpose: walk this thread's slice of the runouts at the split round, over\n * the memory every thread shares, each time the main thread signals, until it\n * says exit. The protocol is src/parallel.ts's: the main thread collects the\n * reach each entry needs, every thread walks its slice from each entry, the\n * main thread adds the slices up and finishes. All of it happens in shared\n * WebAssembly memory, so nothing is copied between threads but a few numbers\n * of control.\n *\n * Node runs it from `engine-worker.ts`. The browser build has no file to\n * start a worker from, so `platform/browser.ts` ships this function as its\n * own source text (`Function.prototype.toString`) inside a Blob worker. That\n * is why it must stay self-contained: no imports, no reference to anything\n * outside its body, no nested named functions (a bundler may wrap those in a\n * helper the worker would not have). The control slots are written out as\n * numbers for the same reason; a test pins them to `ENGINE_CONTROL`.\n */\n\nimport type { EngineWorkerSetup } from './engine.ts';\n\n/**\n * Serve one solve, returning once the main thread sends exit.\n * @param setup what `createEngine` hands each worker\n */\nexport function serveEngine(setup: EngineWorkerSetup): void {\n\t// ENGINE_CONTROL, inlined.\n\tconst GENERATION = 0;\n\tconst DONE = 1;\n\tconst COMMAND = 2;\n\tconst MODE = 3;\n\tconst TRAVERSER = 4;\n\tconst READY = 5;\n\tconst FAILED = 6;\n\tconst NEXT = 7;\n\tconst EXIT = 1;\n\n\tconst api = (globalThis as unknown as {\n\t\tWebAssembly: { Instance: new (module: unknown, imports: object) => { exports: Record<string, unknown> } };\n\t}).WebAssembly;\n\tconst memory = setup.memory as { buffer: SharedArrayBuffer };\n\tconst imports = {\n\t\tenv: {\n\t\t\tmemory,\n\t\t\tabort(): never {\n\t\t\t\tthrow new Error('engine abort');\n\t\t\t},\n\t\t},\n\t};\n\tconst engine = new api.Instance(setup.module, imports).exports as unknown as {\n\t\tinit(header: number): void;\n\t\tsetMaxActions(count: number): void;\n\t\tsetShard(round: number, start: number, end: number): void;\n\t\tsetExchange(entries: number, reach: number, values: number, stride: number): void;\n\t\tsetPhase(phase: number, apply: number): void;\n\t\tsetShared(marks: number, blockOffsets: number, weighted: number): void;\n\t\tsetSampling(\n\t\t\trounds: number, p: number, every: number, unbiased: number, catchUp: number,\n\t\t\tbaseOffsets: number, boardOffsets: number, walkOffsets: number,\n\t\t\tbaselines: number, lastWalks: number, lastUpdates: number, blockOffsets: number,\n\t\t): void;\n\t\tsetIteration(t: number, dcfr: number): void;\n\t\trunChance(\n\t\t\tmode: number, traverser: number, node: number, me: number, opp: number,\n\t\t\tpositive: number, negative: number, sum: number, weight: number, clamp: number,\n\t\t): number;\n\t};\n\tengine.init(setup.header);\n\tengine.setMaxActions(setup.maxActions);\n\tengine.setExchange(setup.exchange[0], setup.exchange[1], setup.exchange[2], setup.exchange[3]);\n\tconst [round, boards] = setup.shard;\n\tengine.setShard(round, 0, 0);\n\tengine.setPhase(0, 1);\n\tconst shared = setup.shared;\n\tif (shared) engine.setShared(shared[0], shared[1], shared[2]);\n\t// Chance sampling's state is in the shared memory, at the main thread's offsets.\n\tconst s = setup.sampling;\n\tif (s) engine.setSampling(s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11]);\n\t// Shared storage discounts by iteration, the storage engine's rounding\n\t// hashes it, and chance sampling picks deals and catches up by it.\n\tconst needsIteration = shared !== undefined || setup.storage === true || s !== undefined;\n\n\tconst control = new Int32Array(setup.control);\n\tconst settings = new Float64Array(setup.settings);\n\tconst entries = setup.entryNodes.length;\n\tconst rowBytes = setup.stride * 4;\n\tconst stride = setup.stride;\n\tconst reach = setup.exchange[1];\n\t// `scheduleViews` in src/engine.ts, inlined.\n\tconst order = new Int32Array(setup.schedule, 0, boards);\n\tconst cost = new Float64Array(setup.schedule, Math.ceil(boards / 2) * 8, 2 * boards);\n\tconst into = setup.boardValues >>> 2;\n\tconst profile = new Float64Array(setup.profile[0]);\n\tconst busy = setup.profile[1];\n\n\t// This thread's share of the empty storage, mapped before the solve needs\n\t// it; `touchStorage` in src/engine.ts, inlined.\n\t// Not for a solve that gave up before this thread started.\n\tconst pages = new Uint8Array(memory.buffer);\n\tif (Atomics.load(control, COMMAND) !== EXIT) {\n\t\tfor (let r = 0; r < setup.touch.length; r += 2) {\n\t\t\tfor (let at = setup.touch[r]; at < setup.touch[r + 1]; at += 4096) pages[at] = 0;\n\t\t}\n\t}\n\n\t// Latch the generation before announcing readiness, so no dispatch is missed.\n\tlet generation = Atomics.load(control, GENERATION);\n\tAtomics.add(control, READY, 1);\n\tAtomics.notify(control, READY);\n\t// A solve that gave up before this thread started has already said exit.\n\tif (Atomics.load(control, COMMAND) === EXIT) return;\n\n\tfor (;;) {\n\t\tAtomics.wait(control, GENERATION, generation);\n\t\tgeneration = Atomics.load(control, GENERATION);\n\t\tif (Atomics.load(control, COMMAND) === EXIT) return;\n\t\tconst mode = Atomics.load(control, MODE);\n\t\tconst traverser = Atomics.load(control, TRAVERSER);\n\t\tconst positive = settings[0];\n\t\tconst negative = settings[1];\n\t\tconst sum = settings[2];\n\t\tconst weight = settings[3];\n\t\tconst clamp = settings[4];\n\t\ttry {\n\t\t\t// Off for a current-profile read, which updates nothing.\n\t\t\tengine.setPhase(0, settings[5]);\n\t\t\tif (needsIteration) engine.setIteration(settings[6], settings[7]);\n\t\t\tconst heap = new Float32Array(memory.buffer);\n\t\t\tconst started = performance.now();\n\t\t\t// Boards off the shared order until none are left; each board's\n\t\t\t// values in its own rows, so whoever walks it gives the same sum.\n\t\t\tfor (;;) {\n\t\t\t\tconst taken = Atomics.add(control, NEXT, 1);\n\t\t\t\tif (taken >= boards) break;\n\t\t\t\tconst board = order[taken];\n\t\t\t\tengine.setShard(round, board, board + 1);\n\t\t\t\tconst boardStarted = performance.now();\n\t\t\t\tfor (let entry = 0; entry < entries; entry++) {\n\t\t\t\t\tconst slot = reach + entry * 2 * rowBytes;\n\t\t\t\t\tconst out = engine.runChance(\n\t\t\t\t\t\tmode, traverser, setup.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp,\n\t\t\t\t\t) >>> 2; // a usize, signed on its way out; see `EngineExports`\n\t\t\t\t\theap.copyWithin(into + (board * entries + entry) * stride, out, out + stride);\n\t\t\t\t}\n\t\t\t\t// Training walks only, as `runThreaded` in src/engine.ts.\n\t\t\t\tif (mode === 0 && settings[5] === 1) cost[traverser * boards + board] = performance.now() - boardStarted;\n\t\t\t}\n\t\t\tprofile[busy] += performance.now() - started;\n\t\t} catch (error) {\n\t\t\t// The main thread is blocked in Atomics.wait and cannot see this\n\t\t\t// thread's error event, so say so in shared memory (and count as\n\t\t\t// done, below). Then let the thread die: its engine is not to be trusted.\n\t\t\tAtomics.store(control, FAILED, 1);\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tAtomics.add(control, DONE, 1);\n\t\t\tAtomics.notify(control, DONE);\n\t\t}\n\t}\n}\n","/**\n * The browser build's engine threads: started ahead of time, borrowed by solves.\n *\n * Purpose: everything behind `enableThreads` (`poker-flopsolve/threads`), kept\n * out of `platform/browser.ts` so the main browser build carries none of it.\n * See that file for why the threads must be started before a solve.\n */\n\nimport type { EngineWorkerSetup } from '../engine.ts';\nimport { ENGINE_CONTROL } from '../engine.ts';\nimport { serveEngine } from '../engine-thread.ts';\n\n/** A spawned solver thread. */\ninterface WorkerHandle {\n\tterminate(): void;\n}\n\n/** The parts of the Web Worker API used here, typed locally: the project builds without DOM typings. */\ninterface WebWorker {\n\tpostMessage(message: unknown, transfer?: unknown[]): void;\n\tterminate(): void;\n\tonmessage: ((event: { data: unknown }) => void) | null;\n\tonerror: ((event: { message?: string; preventDefault?(): void }) => void) | null;\n}\n\ninterface MessagePortLike {\n\tpostMessage(message: unknown): void;\n}\n\ninterface BrowserGlobals {\n\tWorker?: new (url: string) => WebWorker;\n\tMessageChannel?: new () => { port1: MessagePortLike; port2: unknown };\n\tBlob?: new (parts: string[], options: { type: string }) => object;\n\tURL: { createObjectURL(blob: object): string; revokeObjectURL(url: string): void };\n\tcrossOriginIsolated?: boolean;\n\tnavigator?: { hardwareConcurrency?: number };\n\tWebAssembly?: { Memory: new (descriptor: { initial: number; maximum: number; shared: boolean }) => object };\n}\n\n/** One pre-started engine thread. */\ninterface Thread {\n\treadonly worker: WebWorker;\n\t/**\n\t * Where its solves are posted. A message posted on the Worker object\n\t * itself does not reach a running child while the parent is blocked in\n\t * `Atomics.wait` (Chromium), and a solve blocks right after posting; a\n\t * transferred MessagePort delivers regardless.\n\t */\n\treadonly port: MessagePortLike;\n\tbusy: boolean;\n}\n\n/** Where the pool is published on `globalThis`. */\nexport const THREADS_KEY = Symbol.for('poker-flopsolve.browser-threads');\n\n/** What the main build sees of the pool. */\nexport interface ThreadProvider {\n\tidle(): number;\n\ttotal(): number;\n\tspawn(setup: EngineWorkerSetup, onError: (error: Error) => void): WorkerHandle;\n}\n\ntype Holder = Record<symbol, (ThreadProvider & { threads: Thread[] }) | undefined>;\n\n/** The engine threads started so far, shared by every copy of this module. */\nfunction pool(): Thread[] {\n\tconst holder = globalThis as unknown as Holder;\n\tholder[THREADS_KEY] ??= {\n\t\tthreads: [],\n\t\tidle: () => idleThreads(),\n\t\ttotal: () => pool().length,\n\t\tspawn: (setup, onError) => spawn(setup, onError),\n\t};\n\treturn holder[THREADS_KEY]!.threads;\n}\n\nfunction idleThreads(): number {\n\treturn pool().filter((thread) => !thread.busy).length;\n}\n\n/** Stop a thread for good and forget it. */\nfunction drop(thread: Thread): void {\n\tthread.worker.terminate();\n\tthread.busy = true;\n\tconst threads = pool();\n\tconst at = threads.indexOf(thread);\n\tif (at >= 0) threads.splice(at, 1);\n}\n\n/** `ENGINE_CONTROL.command`'s value that ends a thread's solve. */\nconst COMMAND_EXIT = 1;\n\n/**\n * Hand one idle engine thread a solve's setup.\n * @param setup what the thread needs to join the solve\n * @param onError called if the thread dies, so the solve can stop waiting on it\n */\nfunction spawn(setup: EngineWorkerSetup, onError: (error: Error) => void): WorkerHandle {\n\tconst thread = pool().find((candidate) => !candidate.busy);\n\tif (!thread) throw new Error('No idle engine thread; call enableThreads() from poker-flopsolve/threads first');\n\tthread.busy = true;\n\tthread.worker.onerror = (event) => {\n\t\tevent.preventDefault?.();\n\t\tdrop(thread);\n\t\tonError(new Error(`Engine thread failed: ${event.message ?? 'unknown error'}`));\n\t};\n\tthread.port.postMessage(setup);\n\tconst control = new Int32Array(setup.control);\n\tlet released = false;\n\treturn {\n\t\tterminate() {\n\t\t\t// A run may be closed twice; by then the thread may serve another.\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tif (!pool().includes(thread)) return;\n\t\t\t// A solve a thread failed: its error event is still queued, and\n\t\t\t// would fail whichever solve borrowed the thread next. Which thread\n\t\t\t// failed is not recorded, so every one of that solve's goes;\n\t\t\t// `prepareThreads` starts replacements.\n\t\t\tif (Atomics.load(control, ENGINE_CONTROL.failed) !== 0) {\n\t\t\t\tdrop(thread);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Whether this solve finished or gave up on starting, tell the\n\t\t\t// thread its solve is over: it returns to waiting for the next\n\t\t\t// setup, having started this one or not (serveEngine checks for\n\t\t\t// exit before it first waits). A thread that died is dropped by\n\t\t\t// its error handler instead.\n\t\t\tif (Atomics.load(control, ENGINE_CONTROL.command) !== COMMAND_EXIT) {\n\t\t\t\tAtomics.store(control, ENGINE_CONTROL.command, COMMAND_EXIT);\n\t\t\t\tAtomics.add(control, ENGINE_CONTROL.generation, 1);\n\t\t\t\tAtomics.notify(control, ENGINE_CONTROL.generation);\n\t\t\t}\n\t\t\tthread.busy = false;\n\t\t\tthread.worker.onerror = () => drop(thread);\n\t\t},\n\t};\n}\n\n/** Why threads cannot run here, or null if they can. */\nexport function threadsUnavailableReason(): string | null {\n\tconst g = globalThis as unknown as BrowserGlobals;\n\tif (typeof g.Worker !== 'function' || typeof g.Blob !== 'function' || typeof g.MessageChannel !== 'function') {\n\t\treturn 'no Web Workers here';\n\t}\n\tif (g.crossOriginIsolated !== true) {\n\t\treturn 'the page is not cross-origin isolated (serve it with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp)';\n\t}\n\tif (typeof SharedArrayBuffer !== 'function') return 'no SharedArrayBuffer here';\n\ttry {\n\t\t// Throws where blocking is not allowed: a page's main thread.\n\t\tAtomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 1, 0);\n\t} catch {\n\t\treturn 'Atomics.wait is not allowed on this thread; solve inside a Web Worker';\n\t}\n\ttry {\n\t\tnew g.WebAssembly!.Memory({ initial: 1, maximum: 1, shared: true });\n\t} catch {\n\t\treturn 'no shared WebAssembly memory here';\n\t}\n\treturn null;\n}\n\n/** How long a thread may take to start before it is given up on. */\nconst START_MS = 30_000;\n\nfunction startThread(url: string): Promise<Thread | null> {\n\tconst g = globalThis as unknown as BrowserGlobals;\n\treturn new Promise((resolve) => {\n\t\tlet worker: WebWorker;\n\t\ttry {\n\t\t\tworker = new g.Worker!(url);\n\t\t} catch {\n\t\t\tresolve(null);\n\t\t\treturn;\n\t\t}\n\t\tconst timer = setTimeout(() => {\n\t\t\tworker.terminate();\n\t\t\tresolve(null);\n\t\t}, START_MS);\n\t\tconst channel = new g.MessageChannel!();\n\t\tworker.onmessage = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tworker.onmessage = null;\n\t\t\tworker.onerror = null;\n\t\t\tresolve({ worker, port: channel.port1, busy: false });\n\t\t};\n\t\tworker.postMessage(null, [channel.port2]);\n\t\tworker.onerror = (event) => {\n\t\t\tevent.preventDefault?.();\n\t\t\tclearTimeout(timer);\n\t\t\tworker.terminate();\n\t\t\tresolve(null);\n\t\t};\n\t});\n}\n\n/**\n * Start engine threads so that solves can use up to `count` threads, this one\n * included, and resolve to how many a solve can use now. Threads already\n * started are kept; idle ones beyond `count` are stopped, so `prepareThreads(1)`\n * stops every thread no open run is holding. Resolves to 1 where threads cannot run; see\n * {@link threadsUnavailableReason}.\n * @param count threads wanted, this one included; defaults to `navigator.hardwareConcurrency`\n */\nexport function prepareThreads(count?: number): Promise<number> {\n\t// One call at a time, so two calls in a row cannot both start the missing threads.\n\tconst next = pending.then(() => resize(count));\n\tpending = next.catch(() => undefined);\n\treturn next;\n}\n\nlet pending: Promise<unknown> = Promise.resolve();\n\nasync function resize(count?: number): Promise<number> {\n\tconst g = globalThis as unknown as BrowserGlobals;\n\tconst wanted = Math.max(1, Math.floor(count ?? g.navigator?.hardwareConcurrency ?? 1));\n\tconst threads = pool();\n\tfor (let i = threads.length - 1; i >= 0 && threads.length > wanted - 1; i--) {\n\t\tif (!threads[i].busy) drop(threads[i]);\n\t}\n\tconst missing = wanted - 1 - threads.length;\n\tif (missing > 0 && threadsUnavailableReason() === null) {\n\t\t// The worker is this module's own loop, as source: there is no file\n\t\t// to point a worker at that every bundler would ship.\n\t\tconst source =\n\t\t\t`const serveEngine = ${serveEngine.toString()};\\n` +\n\t\t\t'onmessage = (event) => {\\n' +\n\t\t\t'\\tevent.ports[0].onmessage = (solve) => serveEngine(solve.data);\\n' +\n\t\t\t\"\\tpostMessage('ready');\\n\" +\n\t\t\t'};\\n';\n\t\tconst url = g.URL.createObjectURL(new g.Blob!([source], { type: 'text/javascript' }));\n\t\ttry {\n\t\t\tconst started = await Promise.all(Array.from({ length: missing }, () => startThread(url)));\n\t\t\tfor (const thread of started) if (thread) threads.push(thread);\n\t\t} finally {\n\t\t\tg.URL.revokeObjectURL(url);\n\t\t}\n\t}\n\treturn threadsUnavailableReason() === null ? Math.min(wanted, 1 + idleThreads()) : 1;\n}\n","/**\n * Browser platform.\n *\n * Purpose: stand in for `node.ts` in a browser build, with the same exports.\n *\n * Out of the box the browser build is single-threaded: no worker threads, no\n * SharedArrayBuffer, and so no cross-origin isolation headers needed on the\n * page. Run the solve inside a Web Worker to keep the page responsive; see\n * `examples/browser-worker.ts`.\n *\n * Threads are opt-in, through `enableThreads` in `poker-flopsolve/threads`\n * (`prepareThreads` here). A browser starts a Web Worker only asynchronously —\n * a worker spawned and then waited on with `Atomics.wait` never starts, as\n * the thread that would start it is the one blocked — while a solve is\n * synchronous. So the workers are started ahead of time, once, and wait idle\n * between solves; a solve with `workers: n` hands n − 1 of them its setup and\n * takes them back on `close()`. Only the WebAssembly engine is threaded here:\n * its workers share the engine's memory exactly as Node's do and run the same\n * loop (`serveEngine`), so a fixed thread count gives the same answer as Node\n * at that count.\n *\n * The pool lives in `browser-threads.ts` and is found through `globalThis`\n * under a registered symbol, so the threads entry and the main build share\n * it even when bundled separately, and the main build carries none of it.\n */\n\nimport type { WorkerSetup } from '../parallel.ts';\nimport type { EngineWorkerSetup } from '../engine.ts';\nimport { compiledEngine } from '../engine.ts';\nimport type { ThreadProvider } from './browser-threads.ts';\nimport { THREADS_KEY } from './browser-threads.ts';\n\nexport { prepareThreads, threadsUnavailableReason } from './browser-threads.ts';\n\n/** Which build this is. */\nexport const PLATFORM = 'browser';\n\n/**\n * Default ceiling on solver storage. A tab gets far less memory than a Node\n * process, so an accidental flop solve fails fast with a clear message rather\n * than taking the tab down.\n */\nexport const DEFAULT_MAX_BYTES = 512 * 1024 * 1024;\n\n/** A spawned solver thread. */\nexport interface WorkerHandle {\n\tterminate(): void;\n}\n\n/** The engine threads `prepareThreads` started, if any. */\nfunction provider(): ThreadProvider | undefined {\n\treturn (globalThis as unknown as Record<symbol, ThreadProvider | undefined>)[THREADS_KEY];\n}\n\n/**\n * The most threads a solve can use now: one, plus the idle engine threads\n * when the WebAssembly engine is to run and can run over shared memory here.\n * @param engine whether the WebAssembly engine is to run\n */\nexport function threadLimit(engine: boolean): number {\n\tconst threads = provider();\n\tif (!engine || !threads || threads.idle() === 0) return 1;\n\treturn compiledEngine('shared') ? 1 + threads.idle() : 1;\n}\n\n/** One, plus every idle engine thread `prepareThreads` started. */\nexport function defaultWorkerCount(): number {\n\treturn 1 + (provider()?.idle() ?? 0);\n}\n\n/**\n * Why a solve gets fewer threads than it asked for, for the one warning.\n * @param engine whether the WebAssembly engine is to run\n */\nexport function threadAdvice(engine: boolean): string {\n\tif (!provider()) return 'call enableThreads() from poker-flopsolve/threads first, in a cross-origin isolated Web Worker';\n\tif (!engine) return 'browser threads run only the WebAssembly engine (default engine, f32 precision)';\n\treturn 'the other threads are held by open runs; close() a run to free its threads';\n}\n\n/** Never called: the browser build threads only the WebAssembly engine; see `threadLimit`. */\nexport function spawnWorker(_setup: WorkerSetup, _onError: (error: Error) => void): WorkerHandle {\n\tthrow new Error('The browser build threads only the WebAssembly engine; use workers: 1 with this solve');\n}\n\n/**\n * Nothing to do in a browser, whose engine threads `prepareThreads` started\n * and keeps; Node starts a run's threads here, ahead of its need for them.\n * @param _count idle engine threads wanted\n */\nexport function warmEngineThreads(_count: number): void {}\n\n/**\n * Hand one idle engine thread a solve's setup.\n * @param setup what the thread needs to join the solve\n * @param onError called if the thread dies, so the solve can stop waiting on it\n */\nexport function spawnEngineWorker(setup: EngineWorkerSetup, onError: (error: Error) => void): WorkerHandle {\n\tconst threads = provider();\n\tif (!threads) throw new Error('No engine threads; call enableThreads() from poker-flopsolve/threads first');\n\treturn threads.spawn(setup, onError);\n}\n","/**\n * Opt-in threads for the browser build: `poker-flopsolve/threads`.\n *\n * Purpose: let a page split a solve across cores, as Node does, without the\n * main build depending on it. Nothing here runs unless it is imported and\n * called; a solve that never asks for threads is the same, bit for bit, as\n * one in a build without this entry.\n *\n * In a browser, call `enableThreads` once, inside a Web Worker on a\n * cross-origin isolated page, and await it before solving:\n *\n * import { createRun, defineSpot } from 'poker-flopsolve';\n * import { enableThreads } from 'poker-flopsolve/threads';\n * const threads = await enableThreads(); // 1 if the page cannot thread\n * const run = createRun(defineSpot(config), { workers: threads });\n *\n * In Node this is optional: a run starts the threads it lacks, beside its\n * own setup, and when it closes, replacements start and wait 30 seconds for\n * the next run. Calling it starts them ahead of the first run and keeps\n * that many waiting for good.\n */\n\nimport { prepareThreads, threadsUnavailableReason } from './platform/node.ts';\n\n/**\n * Start engine threads so that solves can use up to `count` threads, the\n * calling one included, and resolve to how many they can use: 1 where the\n * page cannot thread (see {@link threadsUnavailable}).\n *\n * Threads stay started between solves; a solve borrows them with\n * `workers: n` and returns them on `close()`. Calling again with a smaller\n * count stops the idle surplus, so `enableThreads(1)` stops them all.\n *\n * @param count threads wanted, the calling one included; defaults to the\n * machine's core count (`navigator.hardwareConcurrency` in a browser)\n */\nexport function enableThreads(count?: number): Promise<number> {\n\treturn prepareThreads(count);\n}\n\n/**\n * Why threads cannot run here, or null if they can. In a browser they need\n * a cross-origin isolated page (`Cross-Origin-Opener-Policy: same-origin`\n * and `Cross-Origin-Embedder-Policy: require-corp`) and a Web Worker to\n * solve in, since a page's main thread may not block.\n */\nexport function threadsUnavailable(): string | null {\n\treturn threadsUnavailableReason();\n}\n"],"mappings":";AAyCA,IAAM,OAAQ,WAAoD;AAkP3D,IAAM,iBAAiB,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,WAAW,GAAG,OAAO,GAAG,QAAQ,GAAG,MAAM,GAAG,MAAM,EAAE;;;ACjQ1H,SAAS,YAAY,OAAgC;AAE3D,QAAM,aAAa;AACnB,QAAM,OAAO;AACb,QAAM,UAAU;AAChB,QAAM,OAAO;AACb,QAAM,YAAY;AAClB,QAAM,QAAQ;AACd,QAAM,SAAS;AACf,QAAM,OAAO;AACb,QAAM,OAAO;AAEb,QAAM,MAAO,WAEV;AACH,QAAM,SAAS,MAAM;AACrB,QAAM,UAAU;AAAA,IACf,KAAK;AAAA,MACJ;AAAA,MACA,QAAe;AACd,cAAM,IAAI,MAAM,cAAc;AAAA,MAC/B;AAAA,IACD;AAAA,EACD;AACA,QAAM,SAAS,IAAI,IAAI,SAAS,MAAM,QAAQ,OAAO,EAAE;AAkBvD,SAAO,KAAK,MAAM,MAAM;AACxB,SAAO,cAAc,MAAM,UAAU;AACrC,SAAO,YAAY,MAAM,SAAS,CAAC,GAAG,MAAM,SAAS,CAAC,GAAG,MAA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