/** * Headless host adapter: drives SimEngine from plain Node with no worker, no * transport, and no DOM. * * WHAT A HOST DOES (and why this class exists) * SimEngine is a solver, not a loop: it exposes load()/step(h) and reports * Newton/MNA trouble through `lastConverged` instead of throwing, because * only the host knows whether to retry smaller, roll back, or stop. The * choose-h / attempt / accept-or-rollback policy therefore lives OUTSIDE the * engine, and every host reimplements it. de:volt's browser host is * packages/simcore/src/sim/sim.worker.ts; this is the Node equivalent of its * step loop with the transport removed. * * ADAPTIVE STEPPING IS PORTED, NOT REINVENTED * The controller below is sim.worker.ts's, using the same exported * estimateStepError/nextStepFactor and the same constants. Correspondence to * that file, so the two can be diffed: * * - attemptStep() <- sim.worker.ts attemptStep() * - sourceStepLimit() <- sim.worker.ts sourceStepLimit() * - sourceEventDescriptors(), nextSourceEventTime() and the source-event * clamp in run() <- sim.worker.ts, same names and clamp * - circuitSupportsStepReplay() <- sim.worker.ts, same name * - the accept/reject arms <- sim.worker.ts's batch `while` loop * - H_MIN/H_MAX/H_INITIAL/MCU_H_MAX, and the 0.25 reject factor and the * >15 / <=3 Newton-iteration heuristic, are its values verbatim. * * DELIBERATELY NOT PORTED (a headless run has different pressures than a * 60 Hz browser frame — each omission is a behavior difference, not an * oversight): * * - The 16 ms wall budget and batch cadence. A headless run has no frame to * protect and no consumer waiting on a tick; it runs to completion. The * runaway guard is `maxSteps` instead, mirroring runSpice's maxTranSteps * rationale: a typo'd duration must fail fast, not hang the caller. * - The error-check gap (worker: errorCheckCountdown / validatedStepFactor * reuse, which skips the doubled trial on most steps to buy frame time). * This runner checks EVERY error-controlled step. That is strictly more * conservative — it costs ~3 solves per step and can only tighten h — and * it makes the worker's postDiscontinuityChecks bookkeeping moot, since * that exists solely to force checks the gap would otherwise skip. * - Probe acquisition (uniform sample grid + interpolation). onSample fires * on ACCEPTED STEP BOUNDARIES, which under adaptive control are not * uniformly spaced — see HeadlessSample. * * MCU circuits are handled exactly as the worker handles them: the external * CPU emulators are not snapshot-rewindable, so a circuit containing one gets * the conservative controller with no trial replay, capped at MCU_H_MAX. * * ENGINE SELECTION (brownout/core, W0) * `HeadlessRunnerOptions.engine` opts a runner into trying the Rust/WASM * core (brownout/core) instead of the classic engine above. This is ADDITIVE: * with `engine` absent or `"classic"`, every code path below is exactly what * it was before the core existed — same fields, same control flow, same * error messages. In `"core"` mode, `load()`/`run()` take a completely * different path (see `_tryLoadCore`/`_runCore`): the adaptive step * controller above is entirely a classic-engine concern and has no * involvement once `activeEngine` is `"core"`. `"auto"` loads as `"core"` * does and adds one thing: a core failure in the middle of a run is replayed * on classic (see `_runCoreOrReplay`). */ import { SimEngine } from "../sim/engine/sim-engine.js"; import type { SimCircuit, SimFailure, SimWarning, SolverDiagnosticsSnapshot } from "../sim/engine/sim-engine.js"; import type { EngineReadout } from "../core/surface.js"; /** Run-invariant, pre-parsed source breakpoint description. */ type SourceEventDescriptor = { kind: "periodic"; startAt: number; origin: number; period: number; offsets: readonly number[]; } | { kind: "fixed"; startAt: number | null; times: readonly number[]; }; /** One accepted step's committed readout, delivered to HeadlessRunOptions.onSample. */ export interface HeadlessSample { /** Simulation time (s) at the END of the accepted step. */ simTime: number; /** * The accepted step interval (s) that produced this sample. It VARIES, so * samples are not a uniform grid and must not be treated as one (no fixed * sample rate, no FFT without resampling). Under adaptive control it * changes step to step. With `adaptive: false` it is `fixedStepS` only * away from events: a step lands 10 ns before each source edge, corner or * PWL point, a 10 ns step crosses it, and the grid restarts there (a 1 kHz * clock at 10 us steps takes 9.99 us and 10 ns at each edge). Callers * wanting a uniform grid should use the `.tran` runner in brownout/spice, * which owns SPICE's fixed-grid semantics. */ h: number; /** Net id -> volts. A per-sample copy: the engine's own map is live and is mutated in place by the next step. */ netV: Record; /** Component id -> amps (pin0 -> pin1 through the element). Copied for the same reason as netV. */ elementI: Record; } /** Committed engine readout at an instant, via HeadlessRunner.snapshot(). */ export interface HeadlessSnapshot { simTime: number; /** False when the last solve did not converge; every readout below is then the last TRUSTED state, not the failed iterate. */ converged: boolean; netV: Record; elementI: Record; digitalState: Record; failures: Record; /** Latched engine advisories (SimEngine.getWarnings()); inert to the solve. */ warnings: Record; solver: SolverDiagnosticsSnapshot; } export interface HeadlessRunnerOptions { /** * Integration method for the initial load. Must be settled BEFORE * engine.load(): the load seed solve and the first step's backward-Euler * anchoring read the method already in force (sim.worker.ts load handler). * Default "be", matching that handler's default. */ integrationMethod?: "be" | "trap"; /** * Which engine drives load()/run(). Default "classic" — every existing * caller is unaffected; the classic path below is byte-for-byte what it * was before this option existed. * * "core" attempts the Rust/WASM core (brownout/core) first and falls back * to classic when: `initCore()` hasn't been awaited yet * ("core-not-initialized"), the live instance is poisoned by an earlier * trap and hasn't been re-initialised yet ("core-poisoned" — a fresh * `CoreEngine` is built automatically the next time `initCore()` succeeds * again, so this is transient, not permanent), or the circuit uses a kind * not in `coreSupportedKinds` (`"unsupported-kind:"`, one per kind), * or the core itself rejects the circuit's topology (`"topology:"`) * or a malformed parameter (`compileCircuit`'s own `"malformed::"`). * See `activeEngine` / `engineFallbackReasons` to observe which happened. * Once a circuit is running on the core, `"core"` keeps it there: a failed * advance is reported on the run's result (`hitMinStep`), and a trap is * thrown to the caller. * * "auto" chooses at each `load()` exactly as "core" does (until a run has * fallen back, see below), and also covers * the run: when the core fails part-way (an advance that does not converge, * a livelock, a trap or a poisoned instance), the runner finishes on * classic and records why. No state is carried between the two engines, so * the replay starts from the load: classic loads every circuit this runner * gave the core since classic last ran, runs again every `run()` the core * completed, then the run that failed, whose samples all come from classic. * The readings afterwards are the ones a classic runner gives for the same * calls. `engineFallbackReasons` is then the failure * (`"mid-run:solve-failed:"`, `"mid-run:livelock:"`, * `"core-trap"`, ...) followed by `"restarted-from-load"`, and by * `"replay-incomplete"` if classic stopped early in one of the earlier * runs. After that the runner stays on classic for the rest of its life: * classic carries element state across `load()`, and a core load of the * same circuit would start it cold. Each later `load()` records * `"staying-classic-after-fallback"` as its reason. To make this possible the runner * keeps a copy of each circuit loaded on the core and the options of each * run, and it holds a run's samples until the core has finished that run, * so `onSample` is called at the end of a core run rather than during it. * A circuit is replayed as `load()` took it: an edit made in place and * never loaded reached neither engine. */ engine?: "classic" | "core" | "auto"; /** * Overrides which kinds `engine: "core"` and `"auto"` are allowed to route to the core. * Defaults to `CORE_SUPPORTED_KINDS`, the kinds that have cleared * brownout's accuracy gates (kinds.ts). This option exists for * the dual-engine equivalence harness and this package's own tests: passing * a wider set (e.g. `CORE_IMPLEMENTED_KINDS`) routes kinds that have NOT * cleared those gates to the core, which is exactly what proving them out * requires but is never something a normal host should do. */ coreSupportedKinds?: ReadonlySet; } export interface HeadlessRunOptions { /** Simulated seconds to advance. Added to whatever time already elapsed — successive run() calls continue. */ durationS: number; /** * Error-controlled adaptive stepping (default true). False steps at * `fixedStepS` and disables trial replay entirely, the equivalent of the * worker's manualStepH path: no controller overrides the caller's step, * but the source step ceiling still caps it, and steps still land on * source and device events, so the samples around an event are not * evenly spaced (see HeadlessSample.h). On the core this is a uniform grid * of `fixedStepS` (never coarser than the source step ceiling) with one * sample per grid point; `adaptive: true` there is one advance, one sample. */ adaptive?: boolean; /** Step size (s) when `adaptive` is false. Required in that mode; clamped to [H_MIN, H_MAX]. */ fixedStepS?: number; /** * Re-select the integration method for this run. Only legal at t=0: the * method must precede the load seed, so applying it re-loads the circuit * (see HeadlessRunnerOptions.integrationMethod). Throws if the engine has * already stepped and the request differs from the method in force. */ integrationMethod?: "be" | "trap"; /** Called once per ACCEPTED step, in time order. Rejected trials never surface. */ onSample?: (sample: HeadlessSample) => void; /** Runaway ceiling on attempted steps (default 1e6). */ maxSteps?: number; } export interface HeadlessRunResult { /** Simulation time (s) after the run. */ simTime: number; /** Simulated seconds actually covered. Short of durationS only when a stop flag below is set. */ simulatedS: number; acceptedSteps: number; /** Trials rolled back for exceeding the error tolerance. Healthy runs have a few; they cost time, not accuracy. */ rejectedSteps: number; /** Trials rolled back because Newton/MNA did not converge. */ failedSteps: number; /** * Largest local-error ratio among ACCEPTED steps; 1.0 is the accept * threshold, so a run reporting well under 1.0 never had to work for its * accuracy. Rejected trials are excluded (they show up in rejectedSteps). * Always 0 when errorControlled is false — there was no estimate to report. */ maxLocalErrorRatio: number; /** * Step size (s) the CONTROLLER finished on — the useful read on how far it * opened up. Individual steps may have been smaller than this: the source * density floor, an event clamp, and the final partial step all shrink h * for one step without moving the controller. */ finalH: number; /** True when trial replay was in force. False for MCU circuits and fixed-step runs — maxLocalErrorRatio is then meaningless (0). */ errorControlled: boolean; /** * The run stopped early at the H_MIN floor: neither a converged nor an * in-tolerance state was reachable. The last trusted state is preserved and * simulatedS reports how far it got. This is the honest failure signal — * check it. */ hitMinStep: boolean; /** The run stopped early on the maxSteps ceiling. */ hitStepCap: boolean; } /** * A minimal Node host for SimEngine. * * ```ts * const runner = new HeadlessRunner(); * runner.load(circuit); // or a SPICE netlist string * runner.run({ durationS: 5e-3, onSample: (s) => console.log(s.simTime) }); * console.log(runner.snapshot().netV); * ``` */ export declare class HeadlessRunner { private readonly _engine; private _circuit; /** Mirrors the engine's method so the controller can pick the matching error-order exponent, exactly as the worker mirrors it. */ private _integrationMethod; private _adaptiveH; private _errorReplay; /** Whether the last error estimate said the circuit is changing (see ACTIVE_H_MAX). */ private _changing; private readonly _engineChoice; private readonly _coreSupportedKinds; /** * Created lazily on the first successful core load, then reused across * every later load() call — see HeadlessRunnerOptions.engine's doc comment. * `_tryLoadCore` drops and replaces it (best-effort dispose(), then a fresh * `new CoreEngine()`) the moment `isCurrent()` says it no longer belongs to * the live core instance — e.g. a trap poisoned the instance and the host * re-initialised — so this field can silently change identity across two * `load()` calls; nothing outside `_tryLoadCore` may assume otherwise. * Never explicitly disposed by this class on its own initiative: HeadlessRunner * has no existing lifecycle/close hook to hang a deterministic dispose() off * of (it never needed one for the classic engine), so this relies on * CoreEngine's own FinalizationRegistry safety net instead. A host that * wants deterministic disposal should own a CoreEngine directly rather than * go through this convenience path. */ private _coreEngine; private _activeEngine; private _engineFallbackReasons; /** * "auto" only: every load and completed run since the core took over from * classic, oldest first. Its first entry is always a load. Empty whenever * classic is the active engine: classic's own state is then current, and a * replay has nothing to redo. */ private _coreHistory; /** * "auto" only: set when a run fell back to classic part-way, and never * cleared. Classic carries element state across load() and the core * cannot be given classic's, so every later load stays on classic. */ private _stayClassic; constructor(options?: HeadlessRunnerOptions); /** * The hosted classic engine, for readouts this class does not wrap * (getServoState, getPtcTripped, dcOperatingPoint, ...). Stepping it * directly bypasses the controller and desynchronizes `adaptiveH` from the * state it was measured against; use run() to advance time. * * Throws in core mode: the classic SimEngine held here is never loaded and * never runs while `activeEngine === "core"` (see load()), so returning it * would silently hand back a stale, unloaded engine instead of the one * actually simulating the circuit. Use `readout` for the active engine's * read surface, or construct/hold your own CoreEngine for core-specific APIs. */ get engine(): SimEngine; /** Which engine actually loaded the current circuit. "classic" until a "core" load succeeds; reverts to "classic" on any fallback. */ get activeEngine(): "classic" | "core"; /** * Why load() fell back to classic, in the vocabulary select.ts/compile.ts/ * CoreUnsupportedError all share (`"core-not-initialized"`, * `"core-poisoned"`, `"unsupported-kind:"`, `"malformed::"`, * `"topology:"`). Empty when `engine: "core"` landed on the core, * or when `engine` is `"classic"`/absent (no fallback was ever attempted). * Under `"auto"` it is also why a run() left the core part-way: the * failure, then `"restarted-from-load"` (see HeadlessRunnerOptions.engine). */ get engineFallbackReasons(): readonly string[]; /** The active engine's read-only surface — works in both classic and core mode, unlike `engine` (classic-only). */ get readout(): EngineReadout; /** Simulation time (s), from whichever engine is active. */ get simTime(): number; /** * Load a circuit, or a SPICE netlist to parse into one. Throws * SpiceParseError (line + card attached) for a netlist outside the * documented subset. * * The netlist path uses the parser's converted circuit only; netlist * ANALYSES (.tran/.ac/.op) are ignored here, because the whole point of * this runner is that the caller drives the loop. Use runSpice() from * brownout/spice to execute directives as written. */ load(source: SimCircuit | string): void; /** * Attempts to load `circuit` onto the core engine, creating one (or * replacing a superseded one — see below) as needed. Returns `null` on * success, or the fallback reasons to report (and to fall back to classic * over) otherwise. Only a genuinely unexpected error (anything but * `CoreUnsupportedError`) propagates, per HeadlessRunnerOptions.engine's * doc comment. * * `seedSimTime`, when given (a "classic to core" engine switch — see * load()), is passed through to `CoreEngine.load()`'s own `options.simTime` * so the newly-core circuit starts at the runner's carried-over time * instead of wherever this engine's own clock last stood. * * Always passes `this._integrationMethod` through too: W1b gave the core * real dynamics (capacitors, stepped partitions choosing BE/trapezoidal via * the program's INTEGRATION option — load-time only, like classic's own * seed), so a caller's requested method must reach the compiled program * here, not just the classic engine's `setIntegrationMethod`. */ private _tryLoadCore; /** Net id carrying a component pin, or undefined if the pin is unwired/unknown — from whichever engine is active. */ netIdFor(componentId: string, pinId: string): string | undefined; /** Committed readout at the current instant, from whichever engine is active. All maps are copies; the engines' own are live. */ snapshot(): HeadlessSnapshot; /** * Attempt one physical interval of length h. * * sim.worker.ts attemptStep(), with its solveUs accounting dropped (nothing * here reports per-batch throughput). Unchecked intervals take no snapshot * at all: SimEngine publishes no state from a failed solve and performs its * own rollback for a failed NE555 split, so the expensive deep snapshot is * reserved for the replay path that actually rewinds. */ private attemptStep; /** * The source events this run lands its steps on. A subclass returning an * empty list steps exactly the path from before source events existed, * which is how the regression tests compute their reference on the * platform under test instead of against numbers captured elsewhere. */ protected _sourceEvents(circuit: SimCircuit): SourceEventDescriptor[]; /** * Apply a run's integrationMethod request. See * HeadlessRunOptions.integrationMethod for why t=0 is the only legal point. * The legality rule is the SAME regardless of which engine is active — * `this.simTime` reads whichever one is (see the `simTime` getter). W1b * gave the core real dynamics (capacitors; stepped partitions pick BE or * trapezoidal from the program's INTEGRATION option), so — unlike W0/W1a, * when the core had nothing to seed and this only recorded the request — * core mode now needs the SAME re-seed classic gets: load() again, whose * `_tryLoadCore` bakes `_integrationMethod` into the program (see its own * doc comment). Lossless at t=0: nothing has been stepped yet on either * engine. */ private applyIntegrationMethod; /** Advance the simulation by `durationS` seconds. Throws only on misuse; solver trouble is reported on the result. */ run(options: HeadlessRunOptions): HeadlessRunResult; /** * run()'s core path under `engine: "auto"` (ruling R116): the same two core * runs as under "core", and a replay on classic when the core fails in * one. A failure is an advance that did not converge (`hitMinStep` from * either core run) or a thrown core failure (a trap, a poisoned or stale * instance, a load code); a caller bug (a RangeError) still surfaces. * * The run's samples are held until the core has finished it, so a failed * run delivers classic's samples only, each once. */ private _runCoreOrReplay; /** * Puts classic where it would be had every call in `_coreHistory` gone to * it: each load (classic's own load carries its state from one to the * next), each completed run, in order. No state crosses from the core (W2 * design D9b (a)); what the core computed is dropped. * * The first load is seeded with the time the core was given for it, the * same seed load() gives classic on any other switch from the core. */ private _replayOnClassic; /** * run()'s core-mode path for `adaptive: false` (W2 design 2.7, D15 (a)): * Learn's fixed-`dt` sampling. The grid spacing `gridH` is what classic's * fixed-step loop steps at away from events (`min(fixedStepS, H_MAX, the * source step ceiling)`, computed by the caller), so the core is never * sampled coarser than classic is stepped. The core advances to each grid * point and `onSample` fires after each, with the solved values at that * point (not interpolated from a later one). Classic's extra steps that land * on source edges are a step-size artifact and are not reproduced: the core * handles those instants inside its own advance. * * The grid is anchored at the run's start time and each point is computed as * `start + k * gridH`, not by accumulating, so it does not drift; the last * point is exactly `start + durationS` and may be a short step. `maxSteps` * bounds the number of grid points as it bounds classic's attempted steps. * * Each advance is a clamp on the core's trajectory (D6); the corpus gate at * 1/60 s, 1 ms and 10 ms frames is what keeps that within W0. * * A failed advance stops the run there: the failed point gets no sample * (the readouts are still the last trusted instant), `failedSteps` is 1 and * `hitMinStep` is set, the same honest-failure signal `_runCore` uses. */ private _runCoreGrid; /** * run()'s core-mode path. The core has no step loop in W0/W1a — * bo_engine_advance jumps straight to tEnd (core/README.md, "W0 kernel * semantics" #6: "Everything in W0 is static, so advancing only moves * time") — so there is nothing here for adaptive/fixedStepS/maxSteps to * control, and integrationMethod has already been validated/recorded (not * applied — the core has no dynamics to seed) by run() before this is * called; run() validates all of them (misuse is still caught) but this * method ignores every one of them. (`adaptive: false` is `_runCoreGrid`'s.) * * NON-CONVERGENCE. `CoreEngine.advance` does not throw for a -4/-7 result * (core/README.md, "A failed advance") — it sets `lastConverged = false` * and reads `simTime` back as however far Rust actually got. This method's * own doc-inherited contract ("Throws only on misuse; solver trouble is * reported on the result", run()'s doc comment) therefore holds here too: * a non-converged advance is reported via `hitMinStep`/`simulatedS`, the * SAME honest-failure signal the classic step loop above uses when it hits * the H_MIN floor, rather than propagating a `CoreLoadError` out of run(). */ private _runCore; } export {};