From 7e6cb997e2908eab319dfeb65a2dae0044027a31 Mon Sep 17 00:00:00 2001 From: OGMods <3816927+OGMods@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:49:04 +0300 Subject: [PATCH] Finish every layout past the deadline, report it, and drop Cryo cooling links The cleanup after the search (prune, right-size, pooled-cooler evacuation and sweep, empty-tile gathering) is no longer capped: a budget shared across the shortlist was spent by the first alternate, leaving the rest ungathered. Each pass terminates on its own. The wait is reported: SearchHooks.onFinalizing -> ISLAND_FINALIZING -> the coordinator's summed, monotonic count -> "finalizing d/t" in the readout, and each report re-arms the watchdog. A STOP during the search keeps the whole shortlist; only one during the cleanup cuts it. Under Cryo Nexus the board no longer draws cooler links: the pool serves everyone, so the flows were a complete bipartite graph. --- packages/solver/CLAUDE.md | 42 ++++++++-- packages/solver/src/solver/pacer.ts | 19 +++++ packages/solver/src/solver/placementSearch.ts | 79 +++++++++---------- .../solver/src/solver/search/emptyTiles.ts | 16 +--- .../solver/src/solver/search/pooledCoolers.ts | 40 +++------- packages/solver/src/solver/types.ts | 16 ++++ src/lib/components/canvas/PixiCanvas.svelte | 4 +- .../inspector/BoardStatsCard.svelte | 22 +++++- src/lib/simulation/simulator.test.ts | 9 +-- src/lib/simulation/simulator.ts | 16 +++- src/lib/state/CLAUDE.md | 8 ++ src/lib/state/solver.svelte.ts | 60 +++++++++++--- src/lib/worker/islandWorker.ts | 3 + src/lib/worker/solverCoordinator.test.ts | 50 +++++++++++- src/lib/worker/solverCoordinator.ts | 56 +++++++++++++ src/lib/worker/workerClient.ts | 10 ++- 16 files changed, 336 insertions(+), 114 deletions(-) diff --git a/packages/solver/CLAUDE.md b/packages/solver/CLAUDE.md index 8ca7b70..0c80429 100644 --- a/packages/solver/CLAUDE.md +++ b/packages/solver/CLAUDE.md @@ -208,9 +208,9 @@ CoolingPerSec` — it is what a cooler is worth and what the game shows for it, landmasses with no producer count as nearest of all. A move onto an empty tile is exact. A swap with a producer is re-simulated and kept only if power, every producer and the upgrade plan all hold, so the pass cannot cost a watt. - It is capped at 150ms for the primary and 150ms shared across the - alternates; on the shipped maps one layout takes 15-110ms. Map 1 goes from - five cooler clusters to one. + **It is not timed against the run**, and neither is anything else past the + deadline — see "The cleanup past the deadline is untimed" below. Map 1 goes + from five cooler clusters to one. **Before the sweep, hubs leave the smaller landmasses** (`evacuateMinorLandmasses`). One tile at a time cannot move a hub: a @@ -221,8 +221,7 @@ CoolingPerSec` — it is what a cooler is worth and what the game shows for it, tiles, and each displaced cooler crosses to the tile its producer left, so composition and pool are unchanged. A swap descent over the main landmass then restores power. The move is kept only on the same three tests as a swap, - and the emptied landmass then fills with coolers like any scrap. It has its - own 1s cap on top of the sweep's (`EVACUATE_BUDGET_MS`), sized for a phone; a + and the emptied landmass then fills with coolers like any scrap. A 15-producer hub takes about 170ms on a desktop. On the eight maps with obstacles cleared it brings seven to a single producing landmass at the same power. Shadowspire keeps two, because its 29-producer second landmass does @@ -672,7 +671,38 @@ pass: it moves the holes a layout leaves inside the land out to the shore and into corners, a nearer-the-edge building stepping into each, re-simulated and kept only if power holds, no producer goes offline, nothing new goes idle and the plan holds. Under a pool it leaves coolers where `gatherPooledCoolers` put -them. Its budget (`EMPTY_GATHER_BUDGET_MS`) is added to a run. +them. + +**The cleanup past the deadline is untimed.** Pruning, right-sizing, the +pooled coolers' evacuation and sweep, and `gatherEmptyTiles` all run to +completion on the primary and on every alternate. Each pass terminates on its +own — every accepted move strictly lowers a summed distance or depth, except in +the evacuation's swap descent, where every accepted swap strictly raises power +over a finite set of layouts. That descent is the one pass with no cheap bound +(a pass is O(pairs) simulations and it runs to a local optimum when the floor is +never reached), so it is what to measure first if a phone's cleanup outlasts +`FINALIZING_GRACE_MS`. Their +`deadlineMs` parameters default to `Infinity`, kept only for a caller that +wants a bound. They used to be capped, and the cap is what went wrong: shared +across a shortlist, the first alternate's evacuation spent it, so every later +variant the player stepped through came back with its coolers wherever the walk +had left them. Uncapped, it adds 0.1s on most maps and 3-4s on a desktop on the +largest under a pool (0.1-0.9s per layout, eleven layouts). + +So the wait is reported rather than hidden: `SearchHooks.onFinalizing(done, +total)` fires as the cleanup starts and after each layout (the last at +`total/total`), the worker posts it as `ISLAND_FINALIZING`, the coordinator sums +it over the tasks that have reached their cleanup — a finished one counted whole +until none is left, so the count never goes backwards — and the readout's clock +reads "finalizing 3/11" once its countdown is out. Each report also re-arms the +app's watchdog (`FINALIZING_GRACE_MS`), which would otherwise stop a slow phone +mid-shortlist and lose the layouts not yet tidied. + +STOP lands between layouts and never cuts the primary's cleanup short. Only a +STOP that arrives **during** the cleanup cuts the shortlist; one already in hand +when the search ended asked for what it had found, alternates included, so the +shortlist is finished — cutting there returned every stopped run with no +variants at all. **`distribution.ts` is a port of Unity's `FlowNetwork.cs`.** Two shapes in it are load-bearing and look like details: diff --git a/packages/solver/src/solver/pacer.ts b/packages/solver/src/solver/pacer.ts index 33e6e70..c400834 100755 --- a/packages/solver/src/solver/pacer.ts +++ b/packages/solver/src/solver/pacer.ts @@ -81,4 +81,23 @@ export class Pacer { if (!this.stopped && this.hooks?.shouldStop?.()) this.stopped = true; } + + /** + * Reports that the cleanup past the deadline has finished `done` of `total` + * layouts, and yields. Unconditionally rather than when `due()`: a layout's + * cleanup can take most of a second, and both the report and a STOP should + * land between layouts rather than whenever the interval happens to say so. + */ + async finalizing(done: number, total: number): Promise { + this.hooksFinalizing(done, total); + await this.pump(performance.now()); + } + + /** + * The same report without the yield — for the last one, after which the + * solve returns at once and there is nothing left for a STOP to cut. + */ + hooksFinalizing(done: number, total: number): void { + this.hooks?.onFinalizing?.(done, total); + } } diff --git a/packages/solver/src/solver/placementSearch.ts b/packages/solver/src/solver/placementSearch.ts index b097725..450a9ba 100755 --- a/packages/solver/src/solver/placementSearch.ts +++ b/packages/solver/src/solver/placementSearch.ts @@ -29,7 +29,7 @@ import { targetCanBeat, targetCompositions, } from "./search/composition"; -import { EMPTY_GATHER_BUDGET_MS, gatherEmptyTiles } from "./search/emptyTiles"; +import { gatherEmptyTiles } from "./search/emptyTiles"; import { emptyPlacement, isDirectProducer, @@ -37,11 +37,7 @@ import { put, toPlacedBuildings, } from "./search/placement"; -import { - EVACUATE_BUDGET_MS, - GATHER_BUDGET_MS, - gatherPooledCoolers, -} from "./search/pooledCoolers"; +import { gatherPooledCoolers } from "./search/pooledCoolers"; import { greedyPolish, polishCandidates, @@ -185,37 +181,38 @@ export interface IslandSolution extends IslandLayout { * the last place the layouts change shape. */ async function finalizeAlternates( - collector: AlternateCollector, + layouts: Placement[], primaryRows: PlacedBuilding[], primaryPower: number, effectiveBuildings: EffectiveBuilding[], ctx: IslandContext, pacer: Pacer, + stoppedBeforeCleanup: boolean, ): Promise { const kept: PlacedBuilding[][] = [primaryRows]; const out: IslandLayout[] = []; - // One gathering budget for the whole shortlist rather than one each, so a - // long shortlist cannot add a second to the run. An alternate the deadline - // cuts short is still valid, only less gathered. - const gatherDeadlineMs = - performance.now() + EVACUATE_BUDGET_MS + GATHER_BUDGET_MS; - // And one for the holes, counted in time actually spent: the coolers' pass - // is a no-op under every rule but a pool, and its unused budget is not this - // one's to take. - let emptyLeftMs = EMPTY_GATHER_BUDGET_MS; - - for (const layout of collector.layouts()) { - // This runs after the search's deadline, and each alternate is a few - // hundred simulations — up to a second under a cooling pool — so come up - // for air between them: a STOP that arrives here ends the shortlist where - // it stands rather than waiting for ten more layouts to be finished. - const now = performance.now(); - if (pacer.due(now)) { - await pacer.pump(now); - if (pacer.stopRequested) break; + const total = 1 + layouts.length; + let cut = false; + + // Every alternate is finished as fully as the primary, with no time cap: + // the variants are what the player steps through, and a shared budget left + // all but the first with their coolers where the walk dropped them. The + // primary was layout 1 of `1 + layouts.length`; each pass here is the next. + for (let i = 0; i < layouts.length; i++) { + // Each alternate is a few hundred simulations — most of a second under a + // cooling pool — so come up for air between them: the progress report + // goes out, and a STOP pressed during the cleanup ends the shortlist where + // it stands rather than waiting for ten more layouts to be finished. A + // STOP that arrived during the search does not: it asked for the layouts + // found so far, and the shortlist is part of them — cutting here returned + // a stopped run with no variants at all. + await pacer.finalizing(1 + i, total); + if (pacer.stopRequested && !stoppedBeforeCleanup) { + cut = true; + break; } - const pruned = pruneDeadWeight(layout, ctx); + const pruned = pruneDeadWeight(layouts[i], ctx); const downsized = downgradeOversized( pruned.rows, pruned.power, @@ -227,17 +224,13 @@ async function finalizeAlternates( downsized.power, effectiveBuildings, ctx, - gatherDeadlineMs, ); - const emptyStartedMs = performance.now(); const tidied = gatherEmptyTiles( sized.rows, sized.power, effectiveBuildings, ctx, - emptyStartedMs + emptyLeftMs, ); - emptyLeftMs -= performance.now() - emptyStartedMs; if (!powerTies(tidied.power, primaryPower)) continue; const rows = toPlacedBuildings(tidied.rows); @@ -246,6 +239,8 @@ async function finalizeAlternates( out.push({ placements: rows, powerOutput: tidied.power }); } + // The last layout is done too: say so, so a caller's count reaches its end. + if (!cut) pacer.hooksFinalizing(total, total); return out; } @@ -722,13 +717,16 @@ export async function solveIsland( if (annealMs < minRoundMs) break; } - // Everything from here runs past the deadline and none of it yields on its - // own, so yield once before it: the walk's last pump may be most of a yield - // interval ago, and the cleanup below is a second of work under a pool. - { - const now = performance.now(); - if (pacer.due(now)) await pacer.pump(now); - } + // Everything from here runs past the deadline, untimed — a finished layout + // is worth finishing — and none of it yields on its own, so say so and yield + // before it: the caller's countdown has run out, and this is what explains + // the wait. The STOP that may arrive here does not cut the primary short; + // pruning is what makes it an answer. + const shortlist = collector.layouts(); + // A STOP already in hand asked for what the search found, alternates + // included; only one that lands during the cleanup cuts the shortlist. + const stoppedBeforeCleanup = pacer.stopRequested; + await pacer.finalizing(0, 1 + shortlist.length); // Post-search cleanup pass... const pruned = pruneDeadWeight(placement, ctx); @@ -748,7 +746,6 @@ export async function solveIsland( downsized.power, effectiveBuildings, ctx, - performance.now() + EVACUATE_BUDGET_MS + GATHER_BUDGET_MS, ); // Then push the holes the layout leaves out to the shore and the corners. const tidied = gatherEmptyTiles( @@ -756,16 +753,16 @@ export async function solveIsland( sized.power, effectiveBuildings, ctx, - performance.now() + EMPTY_GATHER_BUDGET_MS, ); const placements = toPlacedBuildings(tidied.rows); const alternates = await finalizeAlternates( - collector, + shortlist, placements, tidied.power, effectiveBuildings, ctx, pacer, + stoppedBeforeCleanup, ); // Every one of these ties on power, so the cheapest to build goes first and // is the one the island shows. Stable, so equal costs keep the walk's order. diff --git a/packages/solver/src/solver/search/emptyTiles.ts b/packages/solver/src/solver/search/emptyTiles.ts index 8c9ccf9..734b0aa 100644 --- a/packages/solver/src/solver/search/emptyTiles.ts +++ b/packages/solver/src/solver/search/emptyTiles.ts @@ -10,15 +10,6 @@ import { anyOfflineProducer, layoutHolds } from "./stability"; * and into its corners. */ -/** - * How long `gatherEmptyTiles` may spend, per solve on the primary layout and - * once more shared across its alternates. It runs after the search's deadline, - * so this is time added to a run; out of time, the holes stay where the sweep - * left them. On a desktop the largest shipped island under Singularity takes - * 105-145ms and the rest 0-60ms, so this leaves a phone room to finish. - */ -export const EMPTY_GATHER_BUDGET_MS = 300; - /** A tile's 8-neighbourhood is complete when every neighbour is buildable. */ const FULL_NEIGHBOURHOOD = 8; @@ -93,15 +84,16 @@ function idleCount(placement: Placement, rows: SimPlacedBuilding[]): number { * * Under a cooling pool coolers are not moved, since `gatherPooledCoolers` has * just put them where they are. Every accepted move strictly lowers the holes' - * summed `interiority`, so the sweep terminates; the deadline only bounds how - * far it gets. + * summed `interiority`, so the sweep terminates on its own. It runs after the + * search's deadline and is not timed against it — a finished layout is worth + * finishing, so `deadlineMs` is only for a caller that wants to bound it. */ export function gatherEmptyTiles( rows: SimPlacedBuilding[], power: number, effectiveBuildings: EffectiveBuilding[], ctx: IslandContext, - deadlineMs: number, + deadlineMs = Infinity, ): { rows: SimPlacedBuilding[]; power: number } { if (rows.length === 0 || rows.length >= ctx.n) return { rows, power }; diff --git a/packages/solver/src/solver/search/pooledCoolers.ts b/packages/solver/src/solver/search/pooledCoolers.ts index 90b2af2..8bcf930 100644 --- a/packages/solver/src/solver/search/pooledCoolers.ts +++ b/packages/solver/src/solver/search/pooledCoolers.ts @@ -18,26 +18,6 @@ import { anyOfflineProducer, layoutHolds } from "./stability"; * after moving hubs off the smaller landmasses so those can hold them. */ -/** - * How long `gatherPooledCoolers` may spend, per solve on the primary layout and - * once more shared across its alternates. It runs after the search's deadline, - * so this is time added to a run. Moving a cooler onto an empty tile costs - * nothing. The cap is for the cooler-to-producer swaps, which mostly fail and - * cost a simulation each. On the shipped maps one layout finishes in 15-110ms. - */ -export const GATHER_BUDGET_MS = 150; - -/** - * How long `evacuateMinorLandmasses` may spend, on top of `GATHER_BUDGET_MS` - * and taken first. Spent only on a board with producers on more than one - * landmass, and the pass stops as soon as a hub is placed — moving a - * 15-producer hub costs about 170ms on a desktop. The cap is sized for a phone, - * several times slower, where a tight one would make the pass silently do - * nothing; a second is small beside a 10-30s attempt. Out of time, the layout - * stays as it was. - */ -export const EVACUATE_BUDGET_MS = 1000; - /** Chebyshev radius of the patch `gatherPooledCoolers` anchors on. */ const GATHER_ANCHOR_RADIUS = 2; @@ -279,18 +259,24 @@ function relocateHub( * landmass with no producer is a scrap nothing else can use, and counts as * nearer than any tile on a working landmass, so empty scraps fill first. Every * accepted move strictly lowers the coolers' summed distance, so the sweep - * terminates; the deadline only bounds how far it gets. + * terminates on its own. + * + * **Neither pass is timed against the run.** Both run after the search's + * deadline, and a cap there left the layouts unfinished: shared across a + * shortlist, the first alternate's evacuation spent it and every later variant + * came back with its coolers where the walk left them. Run to completion it is + * 0.1-0.9s per layout on the largest shipped maps (a 15-producer evacuation + * about 170ms of that), a few seconds over a shortlist of ten; the run reports + * that it is finalizing (`SearchHooks.onFinalizing`) so the wait is explained. + * The deadlines remain for a caller that wants to bound it. */ export function gatherPooledCoolers( rows: SimPlacedBuilding[], power: number, effectiveBuildings: EffectiveBuilding[], ctx: IslandContext, - deadlineMs: number, - evacuateDeadlineMs = Math.min( - deadlineMs, - performance.now() + EVACUATE_BUDGET_MS, - ), + deadlineMs = Infinity, + evacuateDeadlineMs = deadlineMs, ): { rows: SimPlacedBuilding[]; power: number } { if (ctx.anomaly.rule !== "shared_cooling" || rows.length === 0) return { rows, power }; @@ -304,8 +290,6 @@ export function gatherPooledCoolers( } const { component, count } = landmasses(ctx); - // The callers' deadline covers both budgets; capping the evacuation at its - // own (the default) leaves the sweep at least `GATHER_BUDGET_MS`. evacuateMinorLandmasses( current, ctx, diff --git a/packages/solver/src/solver/types.ts b/packages/solver/src/solver/types.ts index 6366134..de8130a 100755 --- a/packages/solver/src/solver/types.ts +++ b/packages/solver/src/solver/types.ts @@ -420,6 +420,15 @@ export interface SearchHooks { onProgress?: (placements: PlacedBuilding[], powerOutput: number) => void; shouldStop?: () => boolean; reportIntervalMs?: number; + /** + * The search's deadline has passed and the finished layouts are being + * tidied: `done` of `total` (the primary and its alternates) so far. Called + * once with `done` 0 as the cleanup starts, then after each layout, the + * last at `total` unless a STOP during the cleanup cut it short. The + * cleanup is not timed against the run, so this is how a caller explains the + * wait past its countdown. + */ + onFinalizing?: (done: number, total: number) => void; } /** @@ -541,6 +550,13 @@ export type IslandWorkerResponse = placements: PlacedBuilding[]; powerOutput: number; } + | { + /** Past the deadline, tidying the finished layouts — `SearchHooks.onFinalizing`. */ + id: string; + type: "ISLAND_FINALIZING"; + done: number; + total: number; + } | { id: string; type: "ISLAND_DONE"; diff --git a/src/lib/components/canvas/PixiCanvas.svelte b/src/lib/components/canvas/PixiCanvas.svelte index 8352742..13e9458 100755 --- a/src/lib/components/canvas/PixiCanvas.svelte +++ b/src/lib/components/canvas/PixiCanvas.svelte @@ -861,7 +861,9 @@ /* * Lines from the inspected building — hovered on a mouse, pinned on touch, * which `inspectedTile` already decides — to every building it sends heat or - * cooling to or takes it from, and on through theirs with `chainLinks`. Only + * cooling to or takes it from (no cooling under a shared pool, where no + * cooler serves anyone in particular — see `placementFlows`), and on through + * theirs with `chainLinks`. Only * a building standing on the tile has flows: hovering grass draws nothing. */ $effect(() => { diff --git a/src/lib/components/inspector/BoardStatsCard.svelte b/src/lib/components/inspector/BoardStatsCard.svelte index 853c461..24ab516 100755 --- a/src/lib/components/inspector/BoardStatsCard.svelte +++ b/src/lib/components/inspector/BoardStatsCard.svelte @@ -61,8 +61,20 @@ let runMode = $derived(solverState.runMode); let remaining = $derived(solverState.remainingMs); + /* + * Past the countdown the search is over and its layouts are being tidied — + * coolers grouped, holes moved to the shore — which is untimed, so it says + * how far it has got rather than a bare "finishing" that reads as a hang. + * Only once the countdown is out: on a deep run an early attempt finalizes + * while the rest still search, and the time left is the truer figure then. + */ + let finalizing = $derived(solverState.finalizing); let countdown = $derived( - remaining === null ? "finishing" : `${formatDuration(remaining)} left`, + remaining !== null + ? `${formatDuration(remaining)} left` + : finalizing + ? `finalizing ${finalizing.done}/${finalizing.total}` + : "finishing", ); /* @@ -722,9 +734,11 @@ {#if solverState.isOptimizing} {#if runMode}{runMode.label}{/if} diff --git a/src/lib/simulation/simulator.test.ts b/src/lib/simulation/simulator.test.ts index 0271b70..2be2802 100755 --- a/src/lib/simulation/simulator.test.ts +++ b/src/lib/simulation/simulator.test.ts @@ -720,14 +720,9 @@ describe("a flow is drawn only where something moved", () => { ).toEqual([]); }); - it("feeds every source from every working cooler under Cryo Nexus", () => { + it("draws no cooling links under Cryo Nexus, where the pool serves everyone", () => { const far: Spec = [...contested, [6, 6, "cooler", VALUES.cooler]]; - expect(pairsOf(far, getAnomaly("cryo_nexus"))).toEqual([ - "0,1>1,1", - "1,0>1,1", - "1,2>1,1", - "6,6>1,1", - ]); + expect(pairsOf(far, getAnomaly("cryo_nexus"))).toEqual(["0,1>1,1"]); }); }); diff --git a/src/lib/simulation/simulator.ts b/src/lib/simulation/simulator.ts index 089d5ff..60e9e3b 100755 --- a/src/lib/simulation/simulator.ts +++ b/src/lib/simulation/simulator.ts @@ -417,13 +417,21 @@ export function linksFrom( /** * Every pair of buildings on the board that actually moved something on the * last tick: a reactor's heat into a generator, a cooler's cooling into a power - * source. The board draws the ones touching the building under the pointer. + * source (except under a shared pool, below). The board draws the ones touching + * the building under the pointer. * * Read off the same distribution that scores the board, not re-derived from * adjacency, because being *beside* a partner is not using it: a reactor whose * generators are already full sends nothing, and neither does a cooler beside a - * source another cooler has covered. Under Cryo Nexus every working cooler - * feeds every source the pool served, which is what the pool does. + * source another cooler has covered. + * + * Under a shared cooling pool (Cryo Nexus) the cooling flows are left out. The + * engine reports every working cooler paying into every source the pool + * served, which is true, but drawn it is a complete bipartite graph — coolers + * times sources, hundreds of lines on a full board, and with the chain followed + * every hover reaches every building. No cooler serves any particular source + * there, so there is no line worth drawing; heat stays adjacency-bound and its + * links are kept. */ export function placementFlows( grid: Tile[][], @@ -442,10 +450,12 @@ export function placementFlows( const pairs: number[] = []; simulateIsland(placement, ctx, true, pairs); + const pooled = ctx.anomaly.rule === "shared_cooling"; const flows: Flow[] = []; for (let k = 0; k < pairs.length; k += 2) { const a = pairs[k]; const b = pairs[k + 1]; + if (pooled && placement[a]?.type === "cooler") continue; flows.push({ from: { x: ctx.xs[a], y: ctx.ys[a] }, to: { x: ctx.xs[b], y: ctx.ys[b] }, diff --git a/src/lib/state/CLAUDE.md b/src/lib/state/CLAUDE.md index 2fc0575..f5448f8 100644 --- a/src/lib/state/CLAUDE.md +++ b/src/lib/state/CLAUDE.md @@ -162,6 +162,14 @@ themselves, and it only fires (with a grace period, via the graceful run's **serial** cost, not the parallel estimate: a machine that reports eight cores and gives two must not have its run cut short. +The one thing past the budget is the cleanup — pruning, the pooled coolers' +gathering, the holes moved to the shore — which runs untimed on every layout +the search kept (`packages/solver/CLAUDE.md`). It reports as it goes, and the +coordinator's sum lands in `solverState.finalizing`, which the readout's clock +shows as "finalizing d/t" once its countdown is out. Each report re-arms the +watchdog `FINALIZING_GRACE_MS` out (`#armWatchdog`, which never shortens it), so +a slow phone is not stopped mid-shortlist while it is visibly making progress. + **How the budget is spent is the player's choice** — `SOLVE_MODES` in `worker/solveModes.ts`, persisted as `solveModeId` (README states what the three modes buy). Ties from different attempts are pooled, which is where a deep run's diff --git a/src/lib/state/solver.svelte.ts b/src/lib/state/solver.svelte.ts index eaf21ba..52f3bda 100755 --- a/src/lib/state/solver.svelte.ts +++ b/src/lib/state/solver.svelte.ts @@ -13,7 +13,10 @@ import { type SolveTaskHandle, } from "../worker/workerClient"; import { MAX_SOLVE_VARIANTS } from "../worker/variants"; -import { defaultPoolSize } from "../worker/solverCoordinator"; +import { + defaultPoolSize, + type FinalizingStatus, +} from "../worker/solverCoordinator"; import { DEFAULT_SOLVE_MODE, SOLVE_MODES, @@ -61,6 +64,15 @@ import { layoutState } from "./layout.svelte"; */ const WATCHDOG_GRACE_MS = 5_000; +/** + * How long a finalizing run may go between reports before the watchdog stops + * it. The cleanup past the deadline is untimed, so the budget-based watchdog + * would cut a slow phone off mid-shortlist and lose the alternates not yet + * tidied. Each report — one per layout, 0.1-0.9s apiece on a desktop — proves + * the run alive and pushes the watchdog out by this much instead. + */ +const FINALIZING_GRACE_MS = 30_000; + /** * What a finished run does to the shortlist already held for this island. * @@ -465,6 +477,15 @@ class SolverState { runMode = $state(null); runEstimateMs = $state(0); + /** + * The run's searches are past their deadline and tidying their layouts — + * grouping the coolers under a pool, moving holes to the shore: how many of + * the layouts they hold are done. Null while every task is still searching, + * and when nothing is running. The cleanup is not timed against the run, so + * this is what the readout shows once its countdown has run out. + */ + finalizing = $state(null); + /** * Time left in the run, ms. Null once a run outlasts its estimate, which a * machine that reports more cores than it gives can do. @@ -499,6 +520,8 @@ class SolverState { }); #watchdog: ReturnType | null = null; + /** When `#watchdog` fires, `performance.now()` ms. */ + #watchdogAt = 0; /** Settles once the run in flight has filed its result; null between runs. */ #runEnded: Promise | null = null; @@ -1364,6 +1387,7 @@ class SolverState { this.lastRunDurationMs = null; this.runMode = this.solveMode; this.runEstimateMs = this.estimatedRunMs; + this.finalizing = null; this.#startClock(); // `pool` as well as `cores`, because the pool is capped at eight and the @@ -1455,6 +1479,11 @@ class SolverState { prestige: configState.prestige, upgradePlan: runPlan?.along, cashBudget: runBudget, + onFinalizing: (status) => { + this.finalizing = status; + // Proof the run is alive past its budget; see FINALIZING_GRACE_MS. + if (status !== null) this.#armWatchdog(FINALIZING_GRACE_MS); + }, }, ); this.activeTask = handle; @@ -1478,6 +1507,7 @@ class SolverState { this.activeTask = null; this.runMode = null; this.runEstimateMs = 0; + this.finalizing = null; if ( finalVariants && @@ -1640,16 +1670,26 @@ class SolverState { * outlast this only if the browser started the workers one after another. */ #startWatchdog(mode: SolveMode) { + this.#armWatchdog(mode.attempts * mode.attemptBudgetMs + WATCHDOG_GRACE_MS); + } + + /** + * (Re)sets the watchdog to fire `delayMs` from now. A finalizing report + * re-arms it, so a run tidying its layouts past its budget is not stopped + * while it is still visibly making progress — but never shortens it. + */ + #armWatchdog(delayMs: number) { + if (!this.isOptimizing || this.isStopping) return; + const firesAt = performance.now() + delayMs; + if (this.#watchdog !== null && firesAt <= this.#watchdogAt) return; this.#stopWatchdog(); - this.#watchdog = setTimeout( - () => { - this.#watchdog = null; - // The same graceful stop the button performs: in-flight workers finish - // the pass they are on rather than dropping the layout they have. - this.stopOptimizer(); - }, - mode.attempts * mode.attemptBudgetMs + WATCHDOG_GRACE_MS, - ); + this.#watchdogAt = firesAt; + this.#watchdog = setTimeout(() => { + this.#watchdog = null; + // The same graceful stop the button performs: in-flight workers finish + // the pass they are on rather than dropping the layout they have. + this.stopOptimizer(); + }, delayMs); } #stopWatchdog() { diff --git a/src/lib/worker/islandWorker.ts b/src/lib/worker/islandWorker.ts index cb22eed..31a3c9d 100755 --- a/src/lib/worker/islandWorker.ts +++ b/src/lib/worker/islandWorker.ts @@ -41,6 +41,9 @@ self.addEventListener( powerOutput, }); }, + onFinalizing: (done, total) => { + post({ id: req.id, type: "ISLAND_FINALIZING", done, total }); + }, }, req.rngSeed, getAnomaly(req.anomalyId), diff --git a/src/lib/worker/solverCoordinator.test.ts b/src/lib/worker/solverCoordinator.test.ts index 11e5f99..07892b2 100755 --- a/src/lib/worker/solverCoordinator.test.ts +++ b/src/lib/worker/solverCoordinator.test.ts @@ -48,7 +48,12 @@ function installFakeWorker( * Progress powers each task streams, all at once, before it finishes — * and how long after that it finishes. Omitted, a task only finishes. */ - stream: { progress: number[]; doneAfterMs: number } = { + stream: { + progress: number[]; + doneAfterMs: number; + /** `ISLAND_FINALIZING` reports, as [done, total], sent after progress. */ + finalizing?: [number, number][]; + } = { progress: [], doneAfterMs: 0, }, @@ -96,6 +101,12 @@ function installFakeWorker( } as MessageEvent; for (const fn of listeners.get(this.#self) ?? []) fn(msg); } + for (const [done, total] of stream.finalizing ?? []) { + const msg = { + data: { id: req.id, type: "ISLAND_FINALIZING", done, total }, + } as MessageEvent; + for (const fn of listeners.get(this.#self) ?? []) fn(msg); + } }, 0); setTimeout(() => { const msg = { @@ -125,6 +136,43 @@ afterEach(() => { }); describe("SolverCoordinator", () => { + it("sums the finalizing tasks' layouts, and clears once none is left", async () => { + // A finalizing report is a task still running, not a finished one: the + // run waits for every DONE, and the count is the sum over the tasks that + // have reached their cleanup, a finished one counted whole until none is + // left — so it never goes backwards. + installFakeWorker(() => 1, { + progress: [], + doneAfterMs: 20, + finalizing: [ + [0, 3], + [2, 3], + ], + }); + const coordinator = new SolverCoordinator(4); + const reports: ({ done: number; total: number } | null)[] = []; + + const variants = await coordinator.solve( + board(2), + [...BUILDINGS], + UPGRADES, + 30, + { attempts: 1, onFinalizing: (s) => reports.push(s) }, + ); + coordinator.destroy(); + + expect(variants.length).toBeGreaterThan(0); + expect(reports).toEqual([ + { done: 0, total: 3 }, + { done: 2, total: 3 }, + { done: 2, total: 6 }, + { done: 4, total: 6 }, + // The first task finishes: counted whole, never dropped from the sum. + { done: 5, total: 6 }, + null, + ]); + }); + it("dispatches one task per island for a single-attempt run", async () => { installFakeWorker(() => 1); const coordinator = new SolverCoordinator(4); diff --git a/src/lib/worker/solverCoordinator.ts b/src/lib/worker/solverCoordinator.ts index 9c9ca83..dbcb1f4 100755 --- a/src/lib/worker/solverCoordinator.ts +++ b/src/lib/worker/solverCoordinator.ts @@ -52,6 +52,20 @@ export interface CoordinatorSolveOptions extends SolveOptions { * wall-clock only once the pool is full. */ attempts?: number; + /** + * How far the tasks past their deadline have got tidying their layouts — + * summed over every task currently finalizing — or null once none is. The + * cleanup is not timed against the run, so this is what the page shows + * after its countdown runs out. Not throttled: a task sends one report per + * layout, a dozen at most. + */ + onFinalizing?: (status: FinalizingStatus | null) => void; +} + +/** Layouts tidied so far, of those the finalizing tasks hold. */ +export interface FinalizingStatus { + done: number; + total: number; } /** @@ -245,6 +259,39 @@ export class SolverCoordinator { else progressTimer = setTimeout(flushProgress, waitMs); }; + /** + * Each task that has passed its deadline, by id: how far its cleanup has + * got. A task that finishes stays in the sum at `done === total` while any + * other is still tidying, so the count never goes backwards; the map + * empties once none is left. + */ + const finalizing = new Map(); + /** The ids in `finalizing` whose task has not yet finished. */ + const stillFinalizing = new Set(); + const reportFinalizing = () => { + if (!options?.onFinalizing || settled) return; + if (stillFinalizing.size === 0) { + finalizing.clear(); + options.onFinalizing(null); + return; + } + let done = 0; + let total = 0; + for (const s of finalizing.values()) { + done += s.done; + total += s.total; + } + options.onFinalizing({ done, total }); + }; + /** The task has finished, one way or another. */ + const finalizingEnded = (taskId: string) => { + const s = finalizing.get(taskId); + if (!s) return; + finalizing.set(taskId, { done: s.total, total: s.total }); + stillFinalizing.delete(taskId); + reportFinalizing(); + }; + /** Monotonic: only a layout that beats what is drawn replaces it. */ const show = ( index: number, @@ -353,7 +400,15 @@ export class SolverCoordinator { return; } + if (msg.type === "ISLAND_FINALIZING") { + finalizing.set(taskId, { done: msg.done, total: msg.total }); + stillFinalizing.add(taskId); + reportFinalizing(); + return; + } + // ISLAND_DONE or ERROR: the task is finished either way. + finalizingEnded(taskId); if (msg.type === "ISLAND_DONE") { finals[index].offer({ placements: msg.placements, @@ -375,6 +430,7 @@ export class SolverCoordinator { slot.worker.addEventListener("message", onMessage); slot.onDeath = () => { slot.worker.removeEventListener("message", onMessage); + finalizingEnded(taskId); workerDied(); }; const baseSeed = plan.seeds[index]; diff --git a/src/lib/worker/workerClient.ts b/src/lib/worker/workerClient.ts index a81995a..0761113 100755 --- a/src/lib/worker/workerClient.ts +++ b/src/lib/worker/workerClient.ts @@ -6,7 +6,7 @@ import type { OptimizationResult, PrestigeScales, } from "@reactor2/solver"; -import { SolverCoordinator } from "./solverCoordinator"; +import { SolverCoordinator, type FinalizingStatus } from "./solverCoordinator"; interface PendingEntry { resolve: (value: OptimizationResult[]) => void; @@ -88,6 +88,11 @@ export interface SolveRunOptions { * no layout that would cost more than this to build from the board standing. */ cashBudget?: CashBudget; + /** + * Called as the run's tasks pass their deadline and tidy their layouts, and + * with null once none is — see `CoordinatorSolveOptions.onFinalizing`. + */ + onFinalizing?: (status: FinalizingStatus | null) => void; } export interface SolveTaskHandle { @@ -159,6 +164,9 @@ export class SolverWorkerClient { onProgress: (result) => { if (!entry.stopped) entry.onProgress?.(result); }, + // Unlike progress, still delivered after a stop: the tasks go on + // finishing their layouts, and the wait is still worth explaining. + onFinalizing: run?.onFinalizing, shouldStop: () => entry.stopped, }) .finally(() => {