Skip to content

Co-Simulation Plugins

LabWired owns deterministic firmware execution, board topology, traces, and fault orchestration. Physical plant models can be declared as co-simulation models and stepped through an adapter.

Browser circuit workflow: The online circuit simulator explains how supported MCU firmware interacts with R/L/C networks, independent sources, and switches. The built-in adapter: analog is a limited deterministic subset: it does not import vendor SPICE device libraries or perform AC/DC sweeps. For nonlinear or vendor transient models, use adapter: ngspice, which has native and browser callback hosts described below. The browser host requires the caller to provide the netlist and ngspice-WASM callback. A passing model test does not certify the physical board.

The first supported manifest shape is:

cosim_models:
  - id: "plant_model"
    adapter: "external_process" # external_process | fmi | mock
    model: "./models/mock-plant.py"
    step_ns: 10000
    inputs:
      controller_enable: "control.enable"
      load_torque_nm: "plant.load.torque_nm"
    outputs:
      shaft_speed_rpm: "observables.shaft_speed_rpm"
      plant_ready: "observables.plant_ready"
    config:
      protocol: "jsonl"

external_process and fmi adapters require model. step_ns must be greater than zero. The mock adapter is intended for deterministic tests and dry-runs; its static outputs are declared under config.outputs so the top-level outputs map can stay dedicated to LabWired signal routing.

The core runtime now exposes a small co-sim registry and runner:

  • build_cosim_adapter(config) constructs mock and external_process adapters from a CosimModelConfig.
  • adapter: fmi intentionally returns a clear unsupported error until the FMI import path is selected.
  • CosimRunner::step_until(time_ns, inputs) steps models only at their configured step_ns boundaries.
  • CosimRunner::step_until_with_signals(time_ns, signals) applies the manifest inputs and outputs maps against a signal store. For example, controller_enable: control.enable feeds the model-local controller_enable input from the control.enable store path, and shaft_speed_rpm: observables.shaft_speed_rpm writes the model output back to observables.shaft_speed_rpm.
  • CosimRunner::from_configs_with_base(configs, base_dir) resolves relative external model paths against the manifest directory, so example manifests can keep local ./models/... references.
  • cosim::routing maps store paths onto real machine state — see Board signal paths — and cosim::CosimSession is the runner, the routing, and the cycle ↔ nanosecond time base bound to one machine, which is what labwired test steps.

This contract is intentionally domain-neutral. A model can represent a motor, thermal plant, hydraulic system, sensor array, battery pack, power stage, or any other external process as long as it consumes named inputs and returns named outputs.

The examples/cosim-plant-demo manifest exercises this generic contract with a reduced-order discrete plant: per-channel enabled/disabled states, a scenario-driven disabled_channels list, and voltage/current/active-channel observables. Higher-fidelity behavior (loss, thermal, semiconductor stress, grid-compliance validation) belongs in a later adapter-backed model.

Drive any manifest-declared model from the command line with labwired cosim-step <system.yaml> --set <path>=<value>, which builds the runner from the manifest and prints the routed outputs after stepping.

Mixed-signal: ngspice as a model

tools/cosim/labwired_ngspice.py turns any SPICE netlist into an external_process model. It hosts libngspice in-process, and on every step alters the mapped voltage sources to the requested values, places a breakpoint at the step's end time and resumes the transient analysis to it; the probed node voltages come back as outputs. There are no threads and no wall clock, so the same input sequence always produces the same voltages.

  • Inputs: true/false map to vdd / 0 V (a GPIO pin), numbers are volts.
  • Outputs: last value of the probed vector (v(node), i(vsrc)) at step end.
  • The operating point is solved from the netlist's own defaults first; inputs are applied once time is running, like a real pin edge.
  • Open-source and vendor device models work through the netlist's .include and .lib lines; check each library's licence before bundling it.
  • One circuit per wrapper process (libngspice is process-global). A second circuit is a second cosim_models entry.

Worked example: examples/cosim-spice-rc (GPIO into a 10 kΩ / 100 nF low-pass, τ = 1 ms). Requires libngspice0 (Debian/Ubuntu: apt install libngspice0). Tests: python3 -m pytest tools/cosim/test_labwired_ngspice.py.

Declaring an input's valid domain

A deck is only an electrical model over the input range its parameters were extracted from. config.input_ranges states that domain; the adapter refuses a boundary outside it before the frame reaches either host, on native and in the browser:

config:
  input_sources:
    lux: { element: Vlux, scale: 1, offset: 0 }
  input_ranges:
    lux: { min: 1, max: 100, unit: lx }
  • min and max are inclusive and finite; give one or both. unit is printed in the message and is not converted.
  • The check reads the routed signal value, not the netlist volts, and runs after input_sampling: with previous_boundary a value stops the run at the boundary where it first drives the circuit.
  • A value absent from the boundary is left to input_sources.*.default_value.
  • An out-of-range value fails the run: ngspice model 'ldr' input 'lux' is 150, outside the declared 1..100 lx range.
  • input_ranges on a board.gpio* route is refused: a logic level has no numeric domain.

This replaces an in-deck clamp such as max(V(lux), 0.01): the clamp still keeps the solver finite, but the run now stops instead of reporting a plausible voltage for an input the model was not fitted to. It is what lets a circuit that the in-core engine modelled as a bounded element (a photoresistors or thermistors entry) run as a behavioural deck with the same explicit stop. Two differential tests compare both engines and assert both refuse a value outside the declared range:

  • cosim_ngspice::a_photoresistor_deck_matches_the_in_core_curve_within_its_range compares a GL5528 power law at 1, 10 and 100 lx and refuses 150 lx;
  • cosim_ngspice::a_thermistor_deck_matches_the_in_core_curve_within_its_range compares an NCP18XH103F03RB beta curve at 10, 25 and 60 °C and refuses 61 °C.

The committed decks are examples/cosim-ngspice-ldr and examples/cosim-ngspice-ntc.

The same parity now holds at project level, not only per element. The source-pinned HeyPCB ESP32-S3 NTC fixture carries system-ngspice.yaml and ntc.cir beside the in-core system.yaml, and three ngspice-*.yaml scripts repeat the in-core sequences through labwired test --script. Measured on 2026-11-25: every firmware loop result, the console text, the asserted scope values and the instrument counts are identical on both engines; settled scope samples agree within 2·10⁻⁷ V (f32), and the range script's fastest transient sample differs by 1.05·10⁻² V because the in-core backward-Euler curve lags the analytic one, which ngspice follows within 0.1 mV. The scripts are not named test-*.yaml because the generic fixture matrix and the browser receipt run without a solver host; labwired_test_runs_the_heypcb_ntc_deck_on_ngspice runs them on both engines and also requires the source.sha256 netlist pin and the 61 °C stop on both.

The HeyPCB ESP32-S3 LDR sensor-network fixture repeats the pattern with ldr.cir and two ngspice-*.yaml scripts. Measured on 2026-11-25: the ADC count of both scripts and both instrument counts are identical, the bright 3.95 ms sample agrees within 4·10⁻⁷ V, and the bright 350 µs transient differs by 3.6·10⁻³ V for the same backward-Euler reason. 0, 0.5 and 100000 lx stop both engines. labwired_test_runs_the_heypcb_ldr_network_deck_on_ngspice requires that, plus the source.sha256 pin; the in-core manifest keeps the committed browser receipt because the receipt has no solver host.

The same replacement is verified for the deck shape most board examples share. examples/nucleo-f401re/analog-ntc-diode-ngspice.yaml solves the generic Beta NTC divider and Shockley diode load line of analog-ntc-diode-system.yaml with adapter: ngspice, ntc-beta.cir and diode-load-line.cir; names, routes, nets and model parameters are unchanged. labwired cosim-step drives both manifests through the STM32F401 ADC pad routes. Measured on 2026-11-25 with ngspice-42 at 0, 25 and 60 °C: the NTC route agrees to 4.4·10⁻¹⁶ V and the diode route to 2.1·10⁻⁷ V. The diode deck must pin .options temp=26.85 tnom=26.85 because the in-core engine solves at 300.00 K; ngspice's 27 °C default alone moves the forward voltage by 0.3 mV, 1,500 times the agreement measured here. ngspice_solves_the_generic_ntc_and_diode_decks_the_in_core_engine_solves checks both routes and requires the NTC output to move with temperature, so agreement on a flat wrong value cannot pass. The same pair, with the same netlists and only the published pads moved, runs on examples/wch-ch32v003evt/analog-ntc-diode-ngspice.yaml through the WCH CH32V003 10-bit ADC map. Measured on 2026-11-26 at −20, 25 and 85 °C: the NTC route agrees to 4.4·10⁻¹⁶ V and the diode route to 2.1·10⁻⁷ V; ngspice_solves_the_wch_ch32v003_generic_decks_the_in_core_engine_solves checks it. This covers one deck shape and its manifest routing on two register families — the STM32F401 12-bit map and the CH32V003 10-bit map — not every board that shares it.

Pinning the circuit a Flex run solved

A Flex manifest's manifest_sha256 covers the manifest bytes. It cannot cover an external netlist, so run_report() carries one source pin per model whose adapter loaded such a source:

"source": {
  "kind": "spice_netlist",
  "origin": "file",
  "bytes": 231,
  "sha256": "…",
  "path": "./rc.cir"
}
  • origin: file: an adapter: ngspice netlist named by model: and read by the native host. path is the manifest's declared path.
  • origin: inline: an adapter: analog netlist_text. The digest names the exact text the solver parsed.
  • A model with no external source reports no pin. The browser ngspice host also reports none: the page supplies the netlist text, not the runtime, so the runtime does not claim a digest it did not compute.

Editing the netlist changes source.sha256 while manifest_sha256 stays the same. Record both to reproduce a run.

Shared analog in a multi-controller world

An environment can own one inline adapter: analog model with instance-qualified node.<id>.board.* / node.<id>.adc.* routes. The existing world scheduler advances one shared circuit and applies all observations at its declared boundaries. Per-node co-simulation models remain refused. See One shared analog circuit in a world for the manifest, voltage and reset semantics, trace API, validation, and sampling limits.

Board signal paths

A model that only speaks abstract observables can be driven from the command line but never by firmware. The board. / adc. path grammar is how a cosim_models: entry names something real on the chip, so labwired test steps the model against the pins the firmware is actually driving:

Path Direction Type What it is
board.gpio.<pad> machine → model bool The level the firmware is driving on an output pad.
board.gpio_output.<pad> machine → model bool Whether the firmware has configured <pad> as a general-purpose output.
board.gpio_pad.<pad> machine → model bool The live level a logic probe clipped to <pad> sees: the GPIO latch for a plain output, the peripheral's wire for an alternate-function pad, the input register for an input.
board.gpio_pad_volts.<pad> machine → model volts The live pad driver amplitude from the routed VDD, or the descriptor I/O voltage when VDD is not routed. Use a separate direction switch for high impedance.
board.gpio_driven.<pad> machine → model bool Whether the MCU's own output stage drives <pad>, through a GPIO output OR an alternate-function peripheral. False for an input, an analog pad, or a released open-drain line.
board.gpio_in.<pad> model → machine bool or volts An externally held level on an input pad (also readable). A number is volts, turned into a level with the chip's input thresholds.
board.analog.<pad>_volts model → machine number The analog level on the ADC channel belonging to <pad>.
adc.<peripheral>.<channel>_volts model → machine number The analog level on an explicitly named ADC channel.
board.power.vdd_volts model → machine number The MCU's supply. The chip's supply_monitor: holds the core in reset below its power-on threshold and resets it on power-down or brown-out; a chip without one refuses the route.
board.reset.<pin>_volts model → machine volts The descriptor-declared reset pin, with absolute or VDD-ratio thresholds and valid/invalid pulse limits. Holds execution independently of the supply supervisor.
board.motor.<id>.back_emf_v machine → model number The back-EMF of an armature: circuit DC motor (Ke·ω, volts), for the netlist's series EMF source.
board.motor.<id>.current_a model → machine number The winding current the netlist solved for an armature: circuit DC motor (amps, positive = forward torque). Until it is routed the motor holds still and reports no current.
board.motor.<id>.phase_{a,b,c}_back_emf_v machine → model volts The three phase EMFs of a circuit BLDC winding.
board.motor.<id>.phase_{a,b,c}_current_a model → machine amps A complete solved three-phase current vector, positive toward the floating star.
board.motor.<id>.supply_v model → machine volts Optional measured supply for a circuit DC/BLDC motor; absent remains unknown.
ui.<partId>.<field> outside → model bool or number Set from outside the engine (a canvas part, a test stimulus); 0 / false until set.

For the complete winding, ownership, timing and readback contract, see Circuit-driven three-phase BLDC motors.

<pad> is a pad label in whatever form the chip speaks — pa5 / PA5 on STM32, pd2 on the ATmega328P, p0.13 on Nordic, gpio5 or a bare 5 on ESP32. Labels resolve through the same pin resolution every other pad-addressed feature uses: a chip's declared pins: map first, then the standard STM32/Nordic parse, then the ATmega port<letter> windows, then the ESP32 forms. Case does not matter. Board aliases such as Arduino D2 are not pad labels; the playground resolves them before a manifest is written.

board.gpio_output.<pad> reads the GPIO model's direction register through Peripheral::read_gpio_is_output, the same register truth the logic analyzer's pin routing reads: ATmega DDRx, STM32 MODER (F1 CRL/CRH), nRF DIR, Kinetis PDDR, SAM DIR/PINCFG, EFR32 mode nibbles, and on the ESP32 family GPIO_ENABLE plus the output-matrix selector. It is true only for a plain GPIO output. Input, analog and alternate-function pads read false, because the latch board.gpio.<pad> reads is not what drives them. The two paths together describe a pin electrically. A circuit that treats board.gpio.<pad> as a source needs to know whether that source is connected, or an input pad would clamp the net to its idle output latch:

inputs:
  drv_pa0: board.gpio.pa0          # level of the driver
  ctl_pa0: board.gpio_output.pa0   # the driver's switch control
config:
  netlist_text: |
    Vdrv_pa0 drv_pa0 0 dc 0
    Sdrv_pa0 drv_pa0 v_rc ctl_pa0 ron=25 roff=1e12
  sources: { drv_pa0: Vdrv_pa0 }

board.gpio_output and board.gpio describe a plain GPIO output. An alternate-function pad (SPI SCK, a timer PWM) is driven by the peripheral, not by the output latch, so a circuit that needs the pin's real waveform (an oscilloscope on an SPI clock) uses board.gpio_pad.<pad> as the source and board.gpio_driven.<pad> as the switch control. The latter is true for a GPIO output and for an AF output, and false for an input or a released open-drain line. board.gpio_pad reads the same live-pad truth the logic analyzer uses, so an AF pin follows the peripheral's wire instead of a flat latch.

A pad whose GPIO model cannot report direction fails when the session is built with "the GPIO model that owns pad … does not report pin direction". It never reads as false, which would disconnect the firmware from the circuit for the whole run. Every GPIO family board.gpio.<pad> resolves on reports it. A pad board.gpio.<pad> cannot resolve (RP2040 pads, for example) fails the same way for both paths, as "does not resolve on this chip".

On the ATmega328P the AVR core owns PINx/DDRx/PORTx and mirrors them to the descriptor's portb, portc and portd windows, which is where both paths read them; an 8-bit port has no pd8.

Direction is enforced. board.gpio.<pad> is what the firmware drives, so a model output routed to it is a config error rather than a write that silently does nothing; drive a pin with board.gpio_in.<pad> instead, which goes through the same seam a board_io button uses. Likewise an analog path is a sink only and cannot be read back into a model input.

board.analog.<pad>_volts resolves the pad through the chip descriptor's analog_pins: map, transcribed from the datasheet pinout:

analog_pins:
  PA0: { peripheral: "adc1", channel: 0 }

It is data, not a built-in table, because the assignment differs between families: PA0 is ADC1_IN0 on an F401, ADC1_IN5 on an L476 and ADC1_IN1 on a G474. The F1/F4/F7 descriptors in-tree (stm32f103, stm32f401, stm32f401cdu6, stm32f405, stm32f407, stm32f411ceu6, stm32f767) carry it; the 48-pin packages list PA0..PA7 and PB0/PB1 only, since they bond out no PC0..PC5. A pad with no entry — every pad on a chip that declares none — fails at startup with "the chip descriptor names no ADC input for pad …", and adc.<peripheral>.<channel>_volts is the form to use there. analog_pins: is kept apart from pins: because pins: is the authoritative GPIO map: declaring it makes every unlisted pad unresolvable.

Both forms write through SystemBus::seed_adc_channel, the single choke point every analog stimulus (thermistor, potentiometer, battery divider) already goes through; the ADC model owns volts → counts, at 3.3 V full scale and 12 bits (1.65 V is 2047).

Both forms are also checked against the converter when the session is built. The named peripheral must exist, must be an ADC, and must have the channel. A model reports its channel count from its own register layout: 0..=18 for the STM32 F1/F4 and L4/H5/F7/G0 blocks, 0..=19 for the H7. A failing route is a startup error that names the path, the peripheral and the valid range, e.g. co-sim path 'adc.adc1.99_volts': ADC 'adc1' has channels 0..=18; there is no channel 99. Without this check the ADC model would drop a channel it does not have, and the route would write nothing for the whole run.

Paths outside this grammar — control.enable, plant.output.voltage — stay plain signal-store keys routed between models, exactly as before.

Volts on an input pad

A number routed to board.gpio_in.<pad> is a voltage, and the pad is a Schmitt-trigger input: it reads high once the voltage is at or above VIH, low once it is at or below VIL, and between the two it keeps the level it read last. It starts low. A boolean keeps meaning the level itself, exactly as before. This is what lets a circuit node charging through a megohm reach digitalRead at the right time, instead of flipping at a guessed midpoint.

The thresholds are chip data, transcribed from the datasheet into the chip descriptor as slopes of the I/O supply with optional voltage offsets:

io_voltage_v: 5.0          # the rail the GPIO pads run from
gpio_input_thresholds:     # zero-offset limits: slope * supply
  vil: 0.3                 # highest input guaranteed to read low
  vih: 0.6                 # lowest input guaranteed to read high

Optional vil_offset_v and vih_offset_v add volts to the corresponding slope-times-supply limit. They default to zero, preserving existing ratio-only documents. The slopes satisfy 0 < vil < vih < 1; finite offsets satisfy 0 <= vil_offset_v <= vih_offset_v. A routed board.power.vdd_volts supplies the actual reference for each boundary; io_voltage_v applies only when VDD is unrouted. An absent or non-positive routed rail cannot read as a logic high. The shared-world electrical contract includes an affine datasheet example and the zero-VDDA capability boundary.

In-tree they are declared for atmega328p (5.0 V, 0.3 / 0.6, Microchip DS40002061B Table 30-1), stm32f103 (3.3 V, 0.35 / 0.65, DS5319 Table 36), and stm32f401, stm32f401cdu6, stm32f405, stm32f407, stm32f411ceu6 (3.3 V, 0.3 / 0.7, DS10086 Table 54, DS8626 Table 48, DS10314 Table 53). Each descriptor cites its table. On any other chip, volts routed to a pin fail when the session is built, naming the missing key: co-sim path 'board.gpio_in.pd2' is driven with volts, but the chip descriptor declares no `gpio_input_thresholds` …. An adapter: analog model's outputs are always volts, so that check happens before the first step; a model whose value type is only known at run time gets the same error when the first number arrives.

Signals set from outside

ui.<partId>.<field> paths belong to neither the machine nor a model. A model reads one like any other input, every one of them exists from the first step at 0 / false, and something outside the engine sets it:

inputs:
  ctl_touch: ui.touch.pressed      # a canvas touch pad, pressed or not
config:
  netlist_text: |
    Stouch pad finger ctl_touch ron=1k roff=1e12
  • Rust: CosimSession::set_signal(path, CosimSignalValue), or CosimSession::set_signal_number(path, f64) for a caller that only has a number.
  • Browser: WasmSimulator::set_cosim_signal(path, value); it throws rather than returning quietly.
  • Test scripts: a cosim_signal stimulus (below).

A number means what the input it feeds expects. For a logic-level input (an analog switch control) 0 is false and anything else true, so a press is 1 whatever the circuit's supply. A voltage or current source takes the number as given. A value lands in the store at once and every model reading the path sees it from its next step. It is refused when no model input reads the path (a typo would otherwise do nothing and report success), when the path is a board path the machine rewrites every boundary, and for NaN or an infinity. A model output routed to a ui. path is a startup error.

A test script sets one with the stimulus trigger forms every other stimulus uses:

schema_version: "1.2"
stimuli:
  - cosim_signal: { path: ui.touch.pressed, value: 1 }
    trigger: !after_cycles { cycles: 8000000 }
  - cosim_signal: { path: ui.bench.level, value: 2.5 }   # at_start

labwired test applies it through the run's CosimSession, and reports it in result.json's stimuli block with "cosim_signal": true and the path as channel. A signal that no model reads, or a cosim_signal in a run with no cosim_models, is a rejected stimulus, and the run is invalid rather than a pass.

In the run loop

labwired test and the browser engine build a CosimSession when, and only when, the manifest declares cosim_models. A manifest without them runs the identical loop it ran before this existed.

Both advance the machine through the session: CosimSession::advance(machine, request) is one lockstep step, and CosimSession::advance_budget(machine, request) repeats it until the request's own fuel or cycle budget is spent. labwired test calls advance once per loop iteration; WasmSimulator's step, step_single, step_batch, step_batch_profile and step_with_esp32_aids call advance_budget, so step_batch(n) still runs n with every model boundary inside it stepped. One advance:

  1. caps the advance request's simulated-cycle budget at the cycles left before the next model boundary, so the machine can never run past a boundary and hand a model pin levels from its future;
  2. advances the machine to that boundary;
  3. samples every routed board.gpio* path off the bus into the signal store;
  4. steps every model whose step_ns boundary the machine has reached (CosimRunner::step_until_with_signals);
  5. writes the routed outputs back — GPIO input levels onto pins, volts onto ADC channels — so the firmware's next instruction sees the model's answer.

Models are not stepped after a firmware exit or an advance that made no progress. A routed path that fails at apply time is returned once per distinct failure rather than once per step.

The lockstep granularity is the finest declared step_ns. Simulated time comes from the machine's own cycle counter (Machine::total_cycles) and the bus's cpu_hz, so it is the same clock every trace, after_cycles trigger, max_cycles limit and reported at_cycle is expressed in. On Cortex-M, RISC-V and Xtensa that counter advances one cycle per retired instruction. On the ATmega328P it advances by the core's datasheet cycles (1–4 per step), the same cycles Timer0 counts, so millis() and the circuit agree about time. There are no threads and no wall clock anywhere in this path: the same firmware produces the same model inputs on every run.

Multi-node worlds (labwired test on an environment, and the browser's WasmWorld) step their nodes without a session, so they refuse to build a node whose system declares cosim_models: "co-simulation models are not supported in multi-node worlds yet; node '' declares ".

A path that does not resolve fails the run at startup instead of degrading it — a co-simulation whose pin never reached the firmware would otherwise still print a verdict that is evidence of nothing. A model that errors mid-run ends the run rather than letting the firmware keep executing against a plant that stopped answering. Routed outputs are logged under the cosim target:

RUST_LOG=info,cosim=debug labwired test --script examples/cosim-spice-rc/rc-blink.yaml

labwired cosim-step <system.yaml> --set <path>=<value> still drives a model directly, without firmware, for probing a manifest.

In-core analog engine (adapter: analog)

The browser cannot spawn a process, so external_process has no browser counterpart. The separate adapter: ngspice uses an external-process host natively and a caller-owned ngspice-WASM callback in the browser. The existing labwired_core::analog adapter is a small deterministic MNA transient subset compiled into the engine; it runs in the browser and natively. Keep it for existing manifests until ngspice replacement coverage is verified; it is not a replacement for ngspice or a second host for vendor SPICE models.

A manifest switches engines by changing one line. The netlist, vdd, probes and sources config keys are spelled exactly as the ngspice wrapper spells them:

cosim_models:
  - id: rc_lowpass
    adapter: analog            # was: external_process + model: ./models/rc_lowpass.py
    step_ns: 100000
    inputs:  { gpio: board.gpio.pa5 }
    outputs: { v_out: board.analog.pa0_volts }
    config:
      netlist: ./rc.cir        # or inline: netlist_text: |
      vdd: 3.3                 # volts a boolean input maps to (default 3.3)
      substeps: 10             # internal solver steps per co-sim step
      integration: be          # be (default) | trap
      probes:  { v_out: "v(out)" }   # output name <- voltage / element current
      sources: { gpio: Vgpio }       # input name -> V, I, S, or R (ohms / Celsius)
      trace: ["v(in)", "i(Vgpio)"]   # extra oscilloscope channels
      trace_samples: 20000           # ring depth (default 20000)

Worked example: examples/cosim-spice-rc/system-analog.yaml, the same circuit and the same routing as system.yaml.

Probes accept a node name, v(node), or i(element), with case-insensitive names. Current probes support voltage sources, inductors, E/H sources, and diodes, including the i(D...) emitted for an analog LED. A diode probe reports amperes flowing from anode to cathode, evaluated at the solved internal junction voltage with the same device law as the solver. It includes RS, configured reverse breakdown, and GMIN; reverse current is negative. Diode observations add no MNA branch unknown and do not make a diode a valid F/H control branch. Unknown or unsupported probes fail at construction.

Netlist subset

Element Line
Resistor R<name> n1 n2 <value>
Capacitor C<name> n1 n2 <value> [ic=<v>]
Inductor L<name> n1 n2 <value> [ic=<i>]
Voltage source V<name> n+ n- <source>
Current source I<name> n+ n- <source>
Switch S<name> n1 n2 <ctrl> ron=<r> roff=<r>
Diode D<name> n+ n- <model>
BJT Q<name> nc nb ne <model>
MOSFET M<name> nd ng ns nb <model> [w=<m>] [l=<m>] [nrd=<squares>] [nrs=<squares>]
JFET J<name> nd ng ns <model>
Op-amp / comparator X<name> in+ in- v+ v- out <model>

Plus * comment lines, ; / $ trailing comments, .end, and .ic V(node)=<v>. Node 0 and gnd are ground. Values take the usual SPICE suffixes (k, meg, m, u, n, p, f, g, t), and trailing unit letters are ignored, so 100nF and 10kohm read as written. Unlike a classic SPICE deck, line 1 is NOT a title — put a * on it, because silently dropping an element line is the worst thing a netlist parser can do.

A switch's <ctrl> is the name of a routed boolean input, not a circuit node, so it needs no sources: entry.

A sources: entry may also target a resistor with beta= or tc1=/tc2=. The routed number is its external temperature in degrees Celsius; a value change rebuilds that resistor's MNA conductance on the next step.

Op-amp and comparator macros

X instances use .model <name> OPAMP(...) or .model <name> COMP(...). Both cards model finite gain and bandwidth, output resistance, offset voltage, constant input bias and offset currents, fixed input capacitances, fixed quiescent supply current, RIN, a fixed differential resistance between in+ and in-, and RINCM, a fixed resistance from each input to V−. RIN=0 or RINCM=0, or omission, disables those paths. Both cards accept CMRR in dB. It converts common-mode input voltage relative to the supply midpoint into input-referred differential voltage by 10^(−CMRR/20); omission means ideal common-mode rejection. OPAMP cards also accept output rail drops, optional IOLIM, and optional SR in volts per second. SR caps the gain-node capacitor current to Cg·SR, so large-signal ramps are slew limited while settled DC gain and smaller-signal finite-GBW response are preserved. COMP cards accept hysteresis and open-collector or push-pull outputs. These parameters have no temperature dependence. Signal- or load-dependent supply current is not modeled. The hand-calculated macro tests are in crates/core/tests/analog/analog_macros.rs.

.tran, .op, .print, .plot, .save, .probe, .width, .nodeset, .title, and non-temperature .options settings are accepted and ignored by the in-core adapter; run length, step and outputs come from the manifest. .temp, .options temp=... / tnom=..., and .control … .endc are rejected: the adapter runs at a fixed temperature and cannot execute ngspice scripts. For a deck shared with ngspice, keep those directives in the ngspice copy and remove them from the adapter: analog copy. Other unsupported directives are hard errors that point to the ngspice adapter, so a typo cannot quietly drop an element line.

Independent sources

<source> is one of:

Form Meaning
[dc] <value> a constant
SIN(vo va freq [td [theta]]) vo + va·exp(−(t−td)·theta)·sin(2π·freq·(t−td)) after td, vo before
PULSE(v1 v2 [td [tr [tf [pw [per]]]]]) a trapezoidal pulse train
EXP(v1 v2 td1 tau1 td2 tau2) v1 until td1, then v1 + (v2−v1)·(1−exp(−(t−td1)/tau1)); from td2 add (v1−v2)·(1−exp(−(t−td2)/tau2)). All six values are required: the SPICE defaults depend on the .tran step, which this engine does not read
PWL(t1 v1 [t2 v2 ...]) straight lines between the points; v1 before t1, the last value after the last point. Times must increase. The ngspice r= and td= options are rejected
SFFM(vo va fm mdi fc) 0 at t <= 0, then vo + va·sin(2π·fc·t + mdi·sin(2π·fm·t)). This is the ngspice-43 and later order (native CI runs ngspice-45, the browser ngspice-47); ngspice-42 and earlier swap fm and fc. All five values are required, and 0 <= mdi <= fc/fm. The delay and phase values are rejected. The source starts at 0 V, so the operating point does not see vo
AM(...) rejected: ngspice-43 changed its argument order, so one deck means two waveforms

Sources are evaluated at the END of each internal step, which is the point the companion models are written about, and is what SPICE does. The operating point uses the value at t = 0.

A source that carries a function is driven by the clock, so it cannot also be a routed input: a sources: entry pointing at one is a config error rather than a race between two owners. Give that element a plain dc value, or route the input at a different element.

Semiconductor models

.model <name> D    (IS=<a> N=<n> ISR=<a> NR=<n> RS=<ohms> BV=<v> IBV=<a> NBV=<n>)
.model <name> NPN  (IS=<a> BF=<n> BR=<n> NF=<n> NR=<n> IKF=<a> IKR=<a> NKF=<n> RB=<ohms> RBM=<ohms> IRB=<a>)
.model <name> PNP  (...)
.model <name> NMOS (VTO=<v> KP=<a/v2> LAMBDA=<1/v> GAMMA=<sqrt(v)> PHI=<v> RD=<ohms> RS=<ohms> RSH=<ohms/square> CBD=<f> CBS=<f> CJ=<f/m²> CJSW=<f/m> PB=<v> MJ=<ratio> MJSW=<ratio> FC=<ratio> TOX=<m> W=<m> L=<m> [CHARGEMOD=MEYER|WARD_DUTTON])
.model <name> PMOS (...)      ; VTO is negative, as in ngspice
.model <name> NJF  (VTO=<v> BETA=<a/v2> LAMBDA=<1/v> RD=<ohms> RS=<ohms> IS=<a>)
.model <name> PJF  (...)      ; VTO is negative for a depletion PJF too, as in ngspice

The parentheses are optional, parameters may be separated by spaces or commas, and a card may be written after the elements that use it. For model behavior supported by both engines, an omitted parameter takes ngspice's default.

This engine models diode recombination current from ISR/NR when ISR is supplied, diode depletion capacitance from CJO/VJ/M/FC, BJT base-junction depletion capacitance from CJE/VJE/MJE, CJC/VJC/MJC, and shared FC, and level-1 MOSFET bulk-drain and bulk-source depletion capacitance from CBD/CBS with shared PB/MJ/FC, or from bottom-area CJ times instance AD/AS plus sidewall CJSW times instance PD/PS, graded with MJ and MJSW respectively. Explicit CBD or CBS replaces that terminal's CJ area term; sidewall capacitance remains additive. Level-1 MOSFET TOX enables intrinsic channel charge. CHARGEMOD defaults to MEYER, which follows ngspice's piecewise capacitance model. The engine-specific CHARGEMOD=WARD_DUTTON selects a charge-based long-channel inversion model with Ward–Dutton drain/source partitioning and a charge-conserving terminal Jacobian. It requires TOX. Without TOX, only explicit overlap and bulk-junction capacitances are present. CHARGEMOD=WARD_DUTTON is an in-core extension and is not a portable ngspice model-card parameter. For a model used by a device, any model parameter not modeled here is recorded by the netlist parser and causes adapter: analog to refuse the run with the model, parameter and source line. This prevents the adapter from silently running an incomplete vendor card; use the ngspice adapter for such models. The lower-level parse_netlist plus Solver API does not apply the adapter guard, so callers using it directly should inspect Circuit::ignored_model_parameters. BJT RB/RC/RE are modeled as series resistors; RBM/IRB make RB fall with base current. JFET RD/RS and MOSFET RD/RS or RSH times the per-instance NRD/NRS are modeled as series resistors. An explicitly supplied direct MOSFET RD or RS takes precedence for that terminal, including an explicit zero that disables its sheet-resistance path. NRD and NRS default to one square and may be set to zero to disable the matching sheet-resistance path. Level-1 MOSFET GAMMA and PHI model body effect; their defaults are 0 and 0.6 V. MOSFET LEVEL other than 1 and JFET LEVEL other than 1 or B other than 1 are refused by name because they use different channel equations.

Seven built-in cards need no .model line at all, which is what a catalog part emits: D (1N4148-class, IS=2.52n N=1.752), NPN, PNP (β = 100), NMOS, PMOS (VTO=±1 V, KP=20u, LAMBDA=0.02), and NJF, PJF (level-1 model defaults). The MOSFET values are this engine's convenience values; the JFET values use ngspice's level-1 defaults.

What is modelled: Shockley diode with RS and SPICE's GMIN; optional forward high-injection current limiting from IK (also named IKF) and reverse high-injection limiting from IKR (both default to disabled); optional recombination current from ISR/NR, clamped in reverse bias at the −3·N·Vt boundary; diode depletion charge in transient runs from CJO/VJ/M/FC (CJO defaults to zero) and quasi-static diffusion charge from TT (defaults to zero), including first-order soft reverse recovery when TT > 0 and VP > 0; diode breakdown when BV is set, with IBV setting the knee current and optional NBV selecting its reverse exponential coefficient (default N). Gummel–Poon BJT transport with VAF/VAR base-width modulation, optional IKF/IKR high-injection rolloff (both default to infinity) with optional NKF (also NK) exponent (0.5 when omitted), and B-E/B-C base recombination currents from ISE/NE and ISC/NC; BJT base-emitter and base-collector depletion charge from CJE/VJE/MJE and CJC/VJC/MJC, plus forward transit-time charge from TF with its XTF/VTF/ITF bias adjustment and reverse transit-time charge from TR (all default to zero; XTF/ITF default to zero and VTF to infinity; shared FC defaults to 0.5) and ohmic terminal resistances RB/RC/RE (all default to zero). RBM defaults to RB and IRB defaults to infinity, so omitting either leaves the base resistance fixed; with RBM < RB and finite IRB, the base resistance falls from RB toward RBM as base current rises. Nonzero BJT terminal resistances add probeable internal collector, base, or emitter nodes. Nonzero JFET and MOSFET terminal resistances add probeable <element>#drain and <element>#source nodes, respectively. Shichman–Hodges MOSFET level 1 with RD/RS ohmic terminal resistances (both default to zero) or RSH times instance NRD/NRS (RSH defaults to zero), GAMMA/PHI body effect, nonlinear drain/body and source/body junction charge from CBD/CBS or CJ/CJSW with instance AD/AS/PD/PS, plus PB/MJ/MJSW/FC, linear gate overlap charge from CGSO/CGDO/CGBO, and TOX-enabled intrinsic channel charge using either ngspice's piecewise Meyer formulation or the opt-in Ward–Dutton charge partition; and SPICE JFET level 1 with the Parker–Skellern B fit, including its two gate junctions and depletion charge. Tests exercise non-unit B in the linear and saturation regions for both channel polarities. Other tests cover MOSFET/JFET channel-length modulation, reverse-channel operation, MOSFET body effect, Meyer bias regions, and Ward–Dutton charge conservation and transient terminal response are covered by tests. The diode's forward and reverse knee reduction, non-default reverse-breakdown emission coefficient, and first-order soft-recovery response are exercised in tests/analog_devices.rs. BJT NKF is checked against solved forward/reverse terminal currents and its effect on transit charge. Every parameter is taken at 300.00 K; there is no temperature model, which is why decks handed to ngspice pin temp/tnom to 26.85 °C.

What is not modeled: Ward–Dutton mode includes strong-inversion channel charge only; it omits intrinsic accumulation/depletion charge. Select Meyer mode when that piecewise channel capacitance is needed. Non-quasi-static MOSFET effects, and JFET levels other than level 1, remain unsupported. The diode's TT term is a quasi-static transit-time charge model, with the first-order VP soft-recovery extension when enabled. More detailed non-quasi-static effects are not modeled. Circuits needing those features belong on adapter: external_process with tools/cosim/labwired_ngspice.py.

RS > 0 on a diode adds one internal node named <element>#internal, exactly as SPICE does. Nonzero BJT RB, RC, and RE add <element>#base, <element>#collector, and <element>#emitter nodes, respectively. Nonzero JFET and MOSFET drain/source terminal resistances add <element>#drain and <element>#source. These nodes count against the 128-unknown ceiling and can be probed.

Solver

  • Modified nodal analysis with companion models. Backward Euler by default; integration: trap selects trapezoidal, about two orders of magnitude closer to the closed form at the same step (0.29 % vs 0.002 % at one tau on the RC example) but able to ring on a hard edge. The first internal step after any source or switch change is taken with backward Euler, as SPICE does at a breakpoint, so an edge does not leave trapezoidal a half-step behind.
  • Fixed internal step h = step_ns / substeps. Dense LU, own implementation. N nodes + M branch currents is capped at 128; a bigger circuit is an error naming the ngspice adapter. Extracted PCB copper resistance retains its terminal nodes under this same bound. The matrix and elimination-factor buffers together use at most 256 KiB; factorization remains O(n³).
  • The solver caches elimination pivots and multipliers until a switch, step length, or integration rule changes. Source and reactive-history changes refresh only the right-hand side. Multipliers replay in the original order, preserving floating-point results. Exactly stationary reactive states reuse the previous solution; there is no epsilon cutoff. Every co-simulation boundary still samples inputs, routes outputs, and records its waveform row. None of these caches adds work to a machine without co-simulation.
  • The operating point is solved at t = 0 from the netlist's own DC values, capacitors open and inductors shorted, then .ic / ic= override it. Routed inputs apply only once time runs — the same ordering the ngspice wrapper gets by pausing its transient just after t = 0, so a pull-up sits at Vdd and a GPIO at 0 before the firmware has done anything.
  • CosimStep::time_ns is the END of the interval being simulated, matching tools/cosim/labwired_ngspice.py.
  • A circuit holding a diode, BJT, JFET or MOSFET is solved by Newton–Raphson inside each step: the device stamps are re-linearised, re-factorised and re-solved until every unknown stops moving, damped by SPICE's DEVpnjlim, DEVfetlim and DEVlimvds. The limiters change the path, never the point: the converged answer is bit-identical whatever state the iteration started from. Running out of iterations is a coded error naming the step, the time and the unknown that was still moving — never a NaN written into the trace.
  • Diode series resistance uses an equivalent KCL row reduction to avoid subtracting large voltage / RS terms when the actual diode current is tiny. The transform includes the completed charge, dependent-source and gmin stamps; it preserves the authored element values, internal node voltages, current-probe semantics and unknown count. Internal-node chains are reduced from their leaves. Cycles, self-links and shared internal rows retain their original conductance stamps. The 128-unknown bound, Newton iteration limit and convergence tolerances remain unchanged.
  • A circuit with no nonlinear element takes the pre-Newton code path unchanged, down to the floating-point operation order. crates/core/tests/analog/analog_linear_golden.rs pins that against bit patterns captured from the engine before any of this existed.
  • Agreement with ngspice on nonlinear and reactive decks is measured, not asserted: crates/cli/tests/analog_vs_ngspice_differential.rs hands the same SPICE text to both engines for a half-wave rectifier, a common-emitter amplifier, an NMOS inverter, an RL low-pass at its corner, a JFET source follower, and two pulsed-sag decks in the shape the regulator fixture records, and compares every sample. Measured worst disagreement: 2.5e-3 %, 4.0e-5 %, 1.0e-6 %, 1.1e-3 %, 6.1e-5 %, 1.2e-3 % and 7.3e-3 % of full scale. The pulsed-sag pair is what holds the trapezoidal restart rule: restarting backward Euler wherever a source value changes measured 6.5e-2 % and 9.8e-2 % on the same decks, over the 0.05 % tolerance.
  • Deterministic: f64 only, Vec indices in the hot path, BTreeMap for names, no threads and no wall clock.

Waveform trace

Every config.probes entry is an oscilloscope channel, whether or not the manifest's outputs: routes it anywhere, and config.trace adds more. A probe with no route is how a circuit publishes a node only an instrument looks at: it is solved and traced every step and never written into the machine. Samples go into a bounded ring (config.trace_samples, default 20 000 — two seconds at a 100 µs step), read by cursor like logic_read_edges:

  • core: Machine::analog_trace_snapshot(cursor) and Machine::analog_channels(), after Machine::attach_analog_trace(...) with CosimRunner::analog_trace_registry() or CosimSession::analog_trace_registry().
  • WASM: WasmSimulator::analog_channels() and WasmSimulator::analog_trace_snapshot(cursor). new_from_config builds the session from the manifest's cosim_models and attaches this ring. The browser refuses two shapes at construction: adapter: external_process ("needs a native build; use adapter: analog in the browser") and an analog model whose netlist is a file (netlist:; put it inline as netlist_text). mock and analog with netlist_text run as they do natively.
  • CLI: --analog-trace <path> on run, test and cosim-step. A .csv extension writes time_ns,<channel>...; anything else writes a VCD with one real variable per channel, so the analog curve opens in GTKWave / PulseView beside the digital logic capture. labwired test attaches its co-simulation session's ring, so the file holds the waveform of the firmware-driven run:
labwired test --firmware tests/fixtures/stm32f401-blinky.elf \
    --system examples/cosim-spice-rc/system-analog.yaml \
    --max-steps 1500000 --analog-trace rc.csv

labwired run steps no co-simulation models, so there the file has channels only when something else attached a runner; cosim-step writes its own runner's ring.

All analog models on one runner share one ring, each owning a block of channels; a model that steps writes a full row and carries the other models' channels forward, which is what a scope shows between updates. Every channel is named <model id>.<name> (the probe name, or the trace: expression), however many analog models are declared. A consumer can then compute a channel name from the manifest alone, and adding a second circuit does not rename the first circuit's channels. The CSV header and VCD variables use the same names.

The boundary

The in-core engine supports the linear elements, switches, and diode, BJT, level-1 JFET and level-1 MOSFET models listed above. Its semiconductor models have the limitations described in Semiconductor models, including omitted device charge terms and temperature effects. Subcircuits, .include / .lib device libraries, other MOSFET or JFET levels, other JFET B values, and AC/DC sweeps are not supported by the in-core engine. Unsupported netlist constructs fail validation with guidance to use the native ngspice adapter.

Use adapter: ngspice (below) or adapter: external_process with tools/cosim/labwired_ngspice.py for circuits needing those capabilities. The browser runs adapter: analog with an inline netlist_text, and adapter: ngspice through a host callback; it cannot run the external-process adapter.

Browser-hosted ngspice callback

The browser can supply a synchronous ngspice callback to WasmSimulator::new_from_config_with_ngspice_callback. Models using adapter: ngspice require a model path and a positive step_ns. The host loads the circuit and owns the solver; the callback exchanges JSON containing model_id, time_ns, dt_ns, and named inputs, and returns an object of named numeric or boolean outputs. Each declared output must be present. The callback and solver state are released with the simulator. Snapshot and replay and binary runtime snapshot capture/restore are unavailable for these externally owned solver sessions.

The existing board.analog.<pad>_volts, adc.<peripheral>.<channel>_volts, and board.power.<rail>_volts routes publish their returned values as voltage scope channels named <model id>.<output name>. To expose other solver outputs as volts, list their names in config.trace_volts; each listed output must be returned by the callback, in volts. For example, trace_volts: [probe] can publish an output named probe without routing it into an MCU. Non-finite values and voltages that cannot be represented by the scope trace are errors.

A model failure or routing failure stops browser execution at the boundary. In a session containing ngspice, any routing failure stops the entire session, including failures from other models, so the firmware cannot continue against a partially disconnected circuit. The older pwm.duty:, adc.input_mv:, gpio.pad:, and gpio.input: route forms are not supported and are rejected; use the board signal paths described above.

adapter: ngspice contract (browser and native)

One manifest entry runs on both hosts. Keys (shared with the app's prepareBrowserNgspiceModels):

- id: ldr
  adapter: ngspice
  model: ./ldr.cir            # netlist inside the manifest directory; .tran and .end, no .control/.include/.inc/.lib
  step_ns: 100000
  inputs:  { supply: board.gpio.pa5, lux: ui.ldr.lux }
  outputs: { v_out: board.analog.pa0_volts }
  config:
    input_sources:            # one entry per input: volts = value * scale + offset
      supply: { element: Vsup, scale: 3.3, offset: 0 }           # board.gpio* = logic level
      lux:    { element: Vlux, scale: 1, offset: 0, default_value: 100 }
    output_nodes:             # one entry per output and trace_volts name
      v_out:  { node: out, scale: 1, offset: 0 }                 # threshold: makes it a logic level
    trace_volts: []
    input_sampling: current_boundary   # optional; or previous_boundary

Each boundary: every mapped source is altered (alter <element> = <volts>), the netlist's own .tran runs or resumes to exactly time_ns, the solver time is checked (32 ulp), and each node is read as raw * scale + offset (>= threshold for a logic output). An absent input uses default_value, or 0 / false. Time must increase strictly.

config.input_sampling selects which inputs integrate the interval that ends at time_ns. current_boundary (the default) holds the inputs routed at this boundary over the whole interval. previous_boundary holds the inputs latched at the previous boundary, as the analog adapter's mode of the same name does: an input written in the middle of an interval reaches the circuit at the next boundary, never before the write. Use it for Flex firmware tests. It needs the (time_ns = 0, dt_ns = 0) initialization step first; Flex sends that step. A machine co-simulation session (CosimSession, native or WasmSimulator) does not send it, so it refuses previous_boundary before any adapter starts, and labwired validate reports it for a machine manifest. The latch is in labwired_core::cosim::ngspice::NgspiceInputLatch, in front of both hosts, so the browser callback and the native host receive the same frames.

Native host. The core factory validates the entry (labwired_core::cosim::ngspice::NgspiceModelSpec; labwired validate reports the same issues), then starts the libngspice host from tools/cosim/labwired_ngspice.py (embedded in labwired-core, run as python3 -I -c ... --bridge-spec <json>) over the external_process JSONL transport: one process per model, a 20 s bound per exchange, and the process group is killed on failure. A host failure is one {"error": "..."} frame; the transport reports it and the adapter is terminally failed. Requirements: python3 and libngspice on the host (apt install libngspice0, or LABWIRED_NGSPICE_LIB); set LABWIRED_NGSPICE_LOG=1 to see ngspice's own output. The native host places a solver breakpoint (ngSpice_SetBkpt) at each boundary: on ngspice-42, stop when time = t alone stepped past a 200 us boundary to the .tran end time.

Confinement of the native host:

  • model: must be a relative path that resolves inside the manifest directory (the Flex file's or the system manifest's directory; FlexRuntime::from_yaml_with_base takes it explicitly). An absolute path, a .. path that leaves the directory, and a symlink to a file outside it are refused before any process starts.
  • The netlist may not contain .control / .endc (a control block can run shell commands) or .include, .inc or .lib (an included file is not checked and could carry a control block or read any file). The check is case-insensitive, after leading whitespace. Put device models in the netlist itself. The browser host has no host file system to include from.
  • Core sends the validated netlist text in the --bridge-spec JSON ("netlist"); the host does not read the path again, repeats the directive check, and does not change its working directory.
  • Python runs isolated (-I): the working directory, PYTHONPATH and the user site directory add no module to the host, so a json.py or ctypes/ beside the manifest cannot replace the standard library.

A standalone Python caller of BridgeCircuit may pass "netlist_path" instead of "netlist"; the same directive check applies.

Native differences from the browser runtime, both deliberate: routes are not limited to board.* / ui.* paths (a CPU-free Flex manifest uses flat signal names), and threshold is accepted on any output (it stays required for board.gpio_in). The runner's (time_ns = 0, dt_ns = 0) initialization step (Flex primes its outputs with it) is answered natively by starting the netlist's own .tran with the initial inputs and reporting its first stored point, so the next boundary continues from the reported state. Without uic that point is the t = 0 operating point; with uic ngspice stores no t = 0 point and the first point is its first internal step (10 ns for .tran 1u), which must fall before the first boundary or the step fails. A separate DC op is not used: under uic it reported 3.3 V for an RC whose transient starts at 0 V. The browser's history/sample budgets are browser memory guards and are not applied natively.

Flex in the browser. WasmFlexRuntime::new_from_yaml_with_ngspice_callback builds Flex models through the same browser adapter factory as WasmSimulator (WasmFlexRuntime::new_from_yaml refuses adapter: ngspice because it has no callback). Its first exchange is the (0, 0) priming step. The app exchange of w1ne/labwired#3897 (head 1ba5b33f6, merged to the app's main branch as 590744b4d2 on 2026-11-21) answers that step: prepareBrowserFlexNgspiceModels prepares the Flex models, and createBrowserNgspiceExchange stops the netlist's own .tran early in the first interval and reports its first stored point, as the native host does. The app exchange at 325616353 rejects the priming step (received an invalid simulation time).

Flex test scripts with ngspice. A labwired test Flex script runs on the same runner on both hosts. labwired_core::flex_script::run_script keeps the default native factory; run_script_with_factory takes the factory that FlexRuntime::from_yaml_with_factory takes. In the browser, WasmFlexTestRun::run_with_ngspice_callback(script_name, script_yaml, manifest_yaml, firmware, callback) runs the script with the browser adapter factory, so adapter: ngspice models exchange each boundary with callback. WasmFlexTestRun::run takes no callback and uses the same browser factory, so it refuses an adapter: ngspice model with co-sim model <id> needs an ngspice callback (config_error), as WasmFlexRuntime::new_from_yaml does; it never falls through to the native host. Failures stay in the result, never a fabricated pass:

  • a model that fails while the models are built (for example, the solver refuses a source element) gives stop_reason: config_error with no firmware step;
  • a callback that throws, returns text that is not JSON, or omits a declared output at a boundary gives status: error, stop_reason: model_error and the adapter's message;
  • a callback that is not a function is an error of the call itself.

Each ngspice boundary is synchronized with the firmware as for any Flex model: the firmware's advance_ns runs the models to each boundary in order. With input_sampling: previous_boundary, a port the firmware writes reaches the circuit at the next boundary.

The worked fixture is crates/wasm/tests/fixtures/flex-mixed-signal: system-ngspice.yaml is system.yaml with the RC solved by ngspice (rc.cir, 10 kΩ / 100 nF, .tran 1u 10m 0 1u uic), driven by the same control behavior rule block. ngspice-enable.yaml (firmware mode 0) and ngspice-disabled.yaml (mode 1, the wrong command) run the committed firmware.wasm. labwired test --script resolves a relative model: from the directory of the Flex manifest (inputs.flex), so model: ./rc.cir works from any working directory. FlexRuntime::from_yaml has no base directory and resolves it from the process working directory, so the core test substitutes an absolute path. The browser host receives the netlist text under the name ./rc.cir. The scripts are not named test-*.yaml, because the CLI matrix and the browser script receipt run every test-*.yaml without a solver host. The in-core analog fixture and its scripts are unchanged; ngspice is opt-in per model and does not replace adapter: analog.

Expected response: the drive written at 1 µs is latched at the 25 µs boundary, so v(t) = 3.3 V · (1 − e^−(t − 25 µs)/1 ms). It crosses the firmware threshold (0.632 · 3.3 V = 2.0856 V) at 1024.67 µs, so the firmware returns 1025 at the 1025 µs sample. The in-core backward-Euler engine on system.yaml lags this curve and returns 1050 (test-enable.yaml). Native measurement on 2026-11-23 (libngspice 42): entry_result 1025, 2.055265 V at 1000 µs and 2.085998 V at 1025 µs (analytic 2.055265 V and 2.085998 V), worst deviation 1.86e-7 V over 42 scope samples (tolerance 1e-5 V; the scope stores f32). Mode 1 keeps every sample at exactly 0 V and returns 0 at 4 ms. Native tests: LABWIRED_REQUIRE_NGSPICE=1 cargo test -p labwired-core --features flex-script --test cosim cosim_ngspice:: (14 pass), and LABWIRED_REQUIRE_NGSPICE=1 cargo test -p labwired-cli --test cosim_pin_routing (9 pass), which runs labwired test --script on ngspice-enable.yaml (entry_result 1025) and ngspice-disabled.yaml (entry_result 0) from a working directory outside the fixture.

Browser execution check. scripts/test_browser_ngspice.mjs runs both browser constructors and WasmFlexTestRun::run_with_ngspice_callback in headless Chrome with the web build of this crate, a real ngspice WASM build and the host's exchange module (all named by environment variables; a missing one is an error, not a skip). The Flex test cases prepare their models with the host's prepareBrowserFlexNgspiceModels; no case mocks the solver. Measured on 2026-11-23 (Chrome 156.0.8078.79, ngspice-47 WASM, app exchange bundled from w1ne/labwired#3897 head 1ba5b33f6, merged as 590744b4d2), 11 of 11 cases pass:

  • machine: the F401 firmware-driven LDR settles to 0.548914 V (100 lx) and 2.751073 V (1 lx); a missing source element stops the run; take_runtime_snapshot is refused;
  • Flex runtime (models from prepareBrowserFlexNgspiceModels(flexYaml, { './ldr.cir': netlist })): the LDR divider gives 0.548914 V bright and 2.751073 V dark;
  • Flex test, mode 0: status: pass, entry_result 1025, 2.055265 V at 1000 µs and 2.085998 V at 1025 µs, worst deviation from the analytic curve 1.86e-7 V over 42 samples (tolerance 1e-5 V), the same values as native;
  • Flex test, mode 1: status: pass, entry_result 0, every one of 161 samples at 0 V;
  • a callback that throws, omits v_out, or returns text that is not JSON at the 39th boundary: model_error at 950 µs with the adapter's message; a callback that is not a function is refused; WasmFlexTestRun::run without a callback gives config_error with co-sim model rc needs an ngspice callback.

The app has no production Flex caller of these helpers yet; this check exercises the helpers directly.

Not supported on either host: snapshot/restore of solver state. It is refused, not approximated, through labwired_core::cosim::ngspice::runtime_snapshot_refusal: the browser's take_runtime_snapshot / apply_runtime_snapshot return the reason, and native labwired test --capture-app-entry / --resume-snapshot with an ngspice model exit with the config error before any solver starts. Browser Flex (WasmFlexRuntime, WasmFlexTestRun) has no snapshot API at all, so a Flex run with ngspice cannot be saved or resumed; it runs from t = 0 each time. Multi-node worlds and transport: shm are not supported either. Worked example and tests: examples/cosim-ngspice-ldr, cargo test -p labwired-core --test cosim cosim_ngspice::.