pcbjam/wasm/stubs/sharedspice_client.cpp

649 lines
22 KiB
C++
Raw Normal View History

/*
* sharedspice client stub the editor side of the ngspice_service split
* (docs/features/ngspice-split/; the SPICE analog of exporter_step_stub.cpp).
*
* eeschema's NGSPICE class normally dlopens libngspice and binds ~10 function
* pointers; in WASM the simulator engine lives in a separate worker module
* (wasm/ngspice-service/), and NGSPICE::init_dll()'s __EMSCRIPTEN__ branch
* binds its pointers to the pcbjam_ngSpice_* functions here instead. Each
* forwards over the `globalThis.ngspiceService` provider
* (web/standalone/src/wasm/ngspice-service.ts) via EM_ASYNC_JS the editor
jspi cleanup: remove the asyncify-era residue — dead code, conditionals, pipeline scaffolding, stale prose The runtime is JSPI-only; this removes everything that still pretended otherwise. Three exhaustive sweeps (C++/JS+build+CI/tests+docs) drove the inventory; every deletion verified by grep closure + full gates. Broken-right-now fixes: - deploy-staging.yml passed the retired opt_level input — the workflow could not even start. Removed. - env.sh carried dead exports with a live -sASYNCIFY=1 inside (WASM_LDFLAGS/PTHREAD_LDFLAGS, zero consumers). Removed; the WASM_LEGACY_EXCEPTIONS rationale rewritten to the real reason. - docker/build.sh exported PCBJAM_ASYNC_BACKEND (read nowhere). Gone. Dead weight removed: - binaryen submodule (nothing builds or invokes it), wasm-opt-bench workflow + scripts/bench/, get-wasm-opt.sh, diagnostics.js (242 lines of Asyncify-API-only code), the KICAD_PIPELINE background-postprocess scaffolding (existed to parallelize the deleted wasm-opt phase; the postprocess is a seconds-long node script and now runs inline), build-monitor's dead asyncify rows, sched-context orphan build output, dead .gitignore entries, the .jspi-assets spike dir (the two wf-result research JSONs moved to docs/features/async/migration-evidence/). - bindings: fiber_park.h + its 12 embind registrations (broken-if- called under JSPI), the kicadOpenFileStart/OPEN_JOB starter route, main_stack_runner.h + 5 includes, the always-null context-sleep weak hook in nanosleep_yield.c. - shim: the backend field (installed-flag idempotency instead), noteContextWait (dead both sides), the __wxAsyncifyDump alias (+ the WasmTool fallback and string-dump normalize branch). - web: the emscripten-6-ignored mainScriptUrlOrBlob option in boot.ts (gerber-demo keeps it: it loads the deployed CDN release, which predates emscripten 6 — noted inline). Conditionals: all 'backend === jspi' checks reduced to scheduler- presence checks; races_quiescent re-keyed from Asyncify.state (vacuous) to real backlog quiescence (resumeReady/mutatorQueue — NOT _windowLive, which is the probing activation's own window by definition). Renames (identifiers only, no file renames): ASYNC_LINK_FLAGS→ JSPI_LINK_FLAGS and Makefile ASYNC_LDFLAGS→JSPI_LDFLAGS, kicadCollabFiberBusy→kicadCollabBusy (embind + web + tests), collab_common.h fiber*→apply*/coroutine naming, asyncifySignatures→ wasmTrapSignatures (lists byte-identical). Tests: the two remaining vacuous [wx-asyncify]/fiber-resume-refused asserts re-keyed to live JSPI beacons; eeschema-load's failure message no longer sends the developer to a deleted script; wait-beacons' dead families/parser deleted; lane-0 legacy-glue guards removed (lane 0 is unconstructible); the embind test.fail re-gated with the JSPI reason (plain embind invokers cannot suspend — verified still failing); lint-determinism now scans tests/jspi (166 files clean); eeschema-collab local-move gated to chromium (~50% flaky on FF even solo; pcbnew twin covers both engines). Docs: DEBUG.md rewritten as the JSPI debugging guide; build.md describes the single-phase build; docs/features/async/README.md banner-marked historical and repointed at the NEW 23-jspi-runtime.md (current architecture: export census, turnstile, libcontext ownership + refusal contract, embind call shapes, the em-pthread service-wrapper trick, exception policy, known gaps). Gates on the cleaned tree: test:e2e 725 passed / 0 failed (after the quiescence-probe fix; the 3 other reds were verified contention flakes solo-green or the documented FF gate), web 76/0, jspi 18/18 both engines, vitest 295/295 + 17/17, all lints green, live-app census clean. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016X9eh1s5sTx1o9Em9KBuwR
2026-08-14 09:25:32 +02:00
* suspends (JSPI) while the worker answers.
*
* Callbacks: KiCad registers its cbSendChar/cbSendStat/cbControlledExit/
* cbBGThreadRunning with pcbjam_ngSpice_Init; the worker streams `{ evt }`
* frames which the provider hands to `globalThis.__ngspiceOnEvent` (installed
* here). The dispatcher calls the exported pcbjam_ngspice_event a fresh
jspi cleanup: remove the asyncify-era residue — dead code, conditionals, pipeline scaffolding, stale prose The runtime is JSPI-only; this removes everything that still pretended otherwise. Three exhaustive sweeps (C++/JS+build+CI/tests+docs) drove the inventory; every deletion verified by grep closure + full gates. Broken-right-now fixes: - deploy-staging.yml passed the retired opt_level input — the workflow could not even start. Removed. - env.sh carried dead exports with a live -sASYNCIFY=1 inside (WASM_LDFLAGS/PTHREAD_LDFLAGS, zero consumers). Removed; the WASM_LEGACY_EXCEPTIONS rationale rewritten to the real reason. - docker/build.sh exported PCBJAM_ASYNC_BACKEND (read nowhere). Gone. Dead weight removed: - binaryen submodule (nothing builds or invokes it), wasm-opt-bench workflow + scripts/bench/, get-wasm-opt.sh, diagnostics.js (242 lines of Asyncify-API-only code), the KICAD_PIPELINE background-postprocess scaffolding (existed to parallelize the deleted wasm-opt phase; the postprocess is a seconds-long node script and now runs inline), build-monitor's dead asyncify rows, sched-context orphan build output, dead .gitignore entries, the .jspi-assets spike dir (the two wf-result research JSONs moved to docs/features/async/migration-evidence/). - bindings: fiber_park.h + its 12 embind registrations (broken-if- called under JSPI), the kicadOpenFileStart/OPEN_JOB starter route, main_stack_runner.h + 5 includes, the always-null context-sleep weak hook in nanosleep_yield.c. - shim: the backend field (installed-flag idempotency instead), noteContextWait (dead both sides), the __wxAsyncifyDump alias (+ the WasmTool fallback and string-dump normalize branch). - web: the emscripten-6-ignored mainScriptUrlOrBlob option in boot.ts (gerber-demo keeps it: it loads the deployed CDN release, which predates emscripten 6 — noted inline). Conditionals: all 'backend === jspi' checks reduced to scheduler- presence checks; races_quiescent re-keyed from Asyncify.state (vacuous) to real backlog quiescence (resumeReady/mutatorQueue — NOT _windowLive, which is the probing activation's own window by definition). Renames (identifiers only, no file renames): ASYNC_LINK_FLAGS→ JSPI_LINK_FLAGS and Makefile ASYNC_LDFLAGS→JSPI_LDFLAGS, kicadCollabFiberBusy→kicadCollabBusy (embind + web + tests), collab_common.h fiber*→apply*/coroutine naming, asyncifySignatures→ wasmTrapSignatures (lists byte-identical). Tests: the two remaining vacuous [wx-asyncify]/fiber-resume-refused asserts re-keyed to live JSPI beacons; eeschema-load's failure message no longer sends the developer to a deleted script; wait-beacons' dead families/parser deleted; lane-0 legacy-glue guards removed (lane 0 is unconstructible); the embind test.fail re-gated with the JSPI reason (plain embind invokers cannot suspend — verified still failing); lint-determinism now scans tests/jspi (166 files clean); eeschema-collab local-move gated to chromium (~50% flaky on FF even solo; pcbnew twin covers both engines). Docs: DEBUG.md rewritten as the JSPI debugging guide; build.md describes the single-phase build; docs/features/async/README.md banner-marked historical and repointed at the NEW 23-jspi-runtime.md (current architecture: export census, turnstile, libcontext ownership + refusal contract, embind call shapes, the em-pthread service-wrapper trick, exception policy, known gaps). Gates on the cleaned tree: test:e2e 725 passed / 0 failed (after the quiescence-probe fix; the 3 other reds were verified contention flakes solo-green or the documented FF gate), web 76/0, jspi 18/18 both engines, vitest 295/295 + 17/17, all lints green, live-app census clean. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016X9eh1s5sTx1o9Em9KBuwR
2026-08-14 09:25:32 +02:00
* WASM entry from JS, safe while the main C++ stack is suspended (the wx-dom
* DOM-event mechanism, wxwidgets/src/wasm/domevents.cpp); KiCad's callbacks
* only take a mutex and wxQueueEvent, so nothing on this path can suspend.
*
* ngSpice_running stays cheap: a client-side atomic mirror maintained from
* command results and bg events the simulator UI polls it on a refresh
* timer and an RPC per poll would be pure overhead.
*
* Netlist file shipping: NETLIST_EXPORTER_SPICE emits `.include "<abs path>"`
* lines (Sim.Library models, the IBIS cache) that ngspice opens from ITS
* filesystem pcbjam_ngSpice_Circ scans the deck, reads those files from the
* editor MEMFS (recursively, bounded), and ships them with the circ request
* so the service stages them at identical paths.
*/
#ifdef __EMSCRIPTEN__
#include <atomic>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <set>
#include <string>
#include <vector>
#include <emscripten.h>
#include <nlohmann/json.hpp>
#include <ngspice/sharedspice.h>
using nlohmann::json;
// -------------------------------------------------------------------------
// JS bridges
// -------------------------------------------------------------------------
// Generic request: JSON in, JSON out (malloc'd; caller frees). Vector data
// never travels this path — see js_ngspice_get_vec.
//
jspi cleanup: remove the asyncify-era residue — dead code, conditionals, pipeline scaffolding, stale prose The runtime is JSPI-only; this removes everything that still pretended otherwise. Three exhaustive sweeps (C++/JS+build+CI/tests+docs) drove the inventory; every deletion verified by grep closure + full gates. Broken-right-now fixes: - deploy-staging.yml passed the retired opt_level input — the workflow could not even start. Removed. - env.sh carried dead exports with a live -sASYNCIFY=1 inside (WASM_LDFLAGS/PTHREAD_LDFLAGS, zero consumers). Removed; the WASM_LEGACY_EXCEPTIONS rationale rewritten to the real reason. - docker/build.sh exported PCBJAM_ASYNC_BACKEND (read nowhere). Gone. Dead weight removed: - binaryen submodule (nothing builds or invokes it), wasm-opt-bench workflow + scripts/bench/, get-wasm-opt.sh, diagnostics.js (242 lines of Asyncify-API-only code), the KICAD_PIPELINE background-postprocess scaffolding (existed to parallelize the deleted wasm-opt phase; the postprocess is a seconds-long node script and now runs inline), build-monitor's dead asyncify rows, sched-context orphan build output, dead .gitignore entries, the .jspi-assets spike dir (the two wf-result research JSONs moved to docs/features/async/migration-evidence/). - bindings: fiber_park.h + its 12 embind registrations (broken-if- called under JSPI), the kicadOpenFileStart/OPEN_JOB starter route, main_stack_runner.h + 5 includes, the always-null context-sleep weak hook in nanosleep_yield.c. - shim: the backend field (installed-flag idempotency instead), noteContextWait (dead both sides), the __wxAsyncifyDump alias (+ the WasmTool fallback and string-dump normalize branch). - web: the emscripten-6-ignored mainScriptUrlOrBlob option in boot.ts (gerber-demo keeps it: it loads the deployed CDN release, which predates emscripten 6 — noted inline). Conditionals: all 'backend === jspi' checks reduced to scheduler- presence checks; races_quiescent re-keyed from Asyncify.state (vacuous) to real backlog quiescence (resumeReady/mutatorQueue — NOT _windowLive, which is the probing activation's own window by definition). Renames (identifiers only, no file renames): ASYNC_LINK_FLAGS→ JSPI_LINK_FLAGS and Makefile ASYNC_LDFLAGS→JSPI_LDFLAGS, kicadCollabFiberBusy→kicadCollabBusy (embind + web + tests), collab_common.h fiber*→apply*/coroutine naming, asyncifySignatures→ wasmTrapSignatures (lists byte-identical). Tests: the two remaining vacuous [wx-asyncify]/fiber-resume-refused asserts re-keyed to live JSPI beacons; eeschema-load's failure message no longer sends the developer to a deleted script; wait-beacons' dead families/parser deleted; lane-0 legacy-glue guards removed (lane 0 is unconstructible); the embind test.fail re-gated with the JSPI reason (plain embind invokers cannot suspend — verified still failing); lint-determinism now scans tests/jspi (166 files clean); eeschema-collab local-move gated to chromium (~50% flaky on FF even solo; pcbnew twin covers both engines). Docs: DEBUG.md rewritten as the JSPI debugging guide; build.md describes the single-phase build; docs/features/async/README.md banner-marked historical and repointed at the NEW 23-jspi-runtime.md (current architecture: export census, turnstile, libcontext ownership + refusal contract, embind call shapes, the em-pthread service-wrapper trick, exception policy, known gaps). Gates on the cleaned tree: test:e2e 725 passed / 0 failed (after the quiescence-probe fix; the 3 other reds were verified contention flakes solo-green or the documented FF gate), web 76/0, jspi 18/18 both engines, vitest 295/295 + 17/17, all lints green, live-app census clean. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016X9eh1s5sTx1o9Em9KBuwR
2026-08-14 09:25:32 +02:00
// Phase E shape (docs/features/async/22 §5, K6): token wait instead of
// suspending the stack in place; resolution ALWAYS deferred to at least a
// microtask (the early-resolve contract, doc 22 §10 Phase E retry entry).
// clang-format off
EM_JS( void, js_ngspice_request_start, ( int aToken, const char* aReqJson ), {
findings(E-5,E-8,E-9): module-identity ngspice events + runWaitCompletion admission gate E-8 (re-implemented for JSPI — the codex gate is entangled with the dropped execution owner; under JSPI a fresh non-suspending JS→wasm entry while another activation is suspended is structurally safe on its own stack, so the admission boundary for worker completions is liveness + trap state, not execution ownership): - jspi-scheduler.js grows `terminal` (trapped instance; distinct from `dead`), canTouchNative(), _terminalizeNativeTrap() (WebAssembly.RuntimeError + cross-realm string classification), and runWaitCompletion(site, token, prepare, inertResult): prepare runs immediately and owns ALL native work; stale tokens and dead/terminal instances drop loudly without resolving (resolving would resume the parked frame inside the damaged module); a trap latches terminal; a plain JS bug resolves inertResult so the wait fails instead of stranding. beginWait refuses (token 0) when dead/terminal. - all four delayed completion sites route their native work through the gate: 'OCC export completion' (exporter_step_stub), 'OCC model completion' (oce_plugin_stub — the MEMFS cache write moves inside the gate too), 'ngspice request completion' and 'ngspice vector completion' (sharedspice_client — every HEAP32/HEAPF64/malloc write inside prepare, inertResult 1 = transport error). Every wxWasmBeginWait caller in the stubs bails on token <= 0. - deliberately NOT ported from codex: ownerModule, enqueueNativeCompletion, executionBarrier, the byte-credit native-entry FIFO — completions are one-shot per wait token and stream volume is bounded at the E-6 transport credit window. Cross-refs logged for group M (M-2/M-6/M-8). E-5 (re-implemented; codex shape kept, owner APIs replaced with the E-8 gate): js_ngspice_install_events binds the handler to the EXACT installing module (handler.__pcbjamNgspiceOwnerModule stamp; presence is not identity), re-installation replaces a foreign module's handler, a superseded handler disarms itself, native entry goes through installingModule._malloc/ ._pcbjam_ngspice_event (never lexical Module), each dispatch checks canTouchNative() (loud drop on a dead/terminal module), and a trap on the per-line entry latches the terminal gate. Tests: scheduler-shim.test.ts +7 (gate happy/stale/dead/terminal/cross-realm/ js-bug/beginWait-refusal). e2e specs updated from the codex line: occ-export decode-fault recovery (real onmessageerror transition via failDecode, J-4), ngspice-probe direct-service coverage, eeschema-sim rewritten onto the E-7 applied-generation receipt (codex's executionBarrier await replaced with a pendingWaits('ngspice') drain poll — the JSPI-line equivalent). Also bumps the kicad submodule to the E-7/E-9 commit (dd5751038f7). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:03:16 +02:00
// E-8: the malloc + heap writes run inside the scheduler's completion
// gate — a dead or trapped instance drops the completion loudly instead
// of re-entering wasm.
const finish = ( res ) => {
findings(E-5,E-8,E-9): module-identity ngspice events + runWaitCompletion admission gate E-8 (re-implemented for JSPI — the codex gate is entangled with the dropped execution owner; under JSPI a fresh non-suspending JS→wasm entry while another activation is suspended is structurally safe on its own stack, so the admission boundary for worker completions is liveness + trap state, not execution ownership): - jspi-scheduler.js grows `terminal` (trapped instance; distinct from `dead`), canTouchNative(), _terminalizeNativeTrap() (WebAssembly.RuntimeError + cross-realm string classification), and runWaitCompletion(site, token, prepare, inertResult): prepare runs immediately and owns ALL native work; stale tokens and dead/terminal instances drop loudly without resolving (resolving would resume the parked frame inside the damaged module); a trap latches terminal; a plain JS bug resolves inertResult so the wait fails instead of stranding. beginWait refuses (token 0) when dead/terminal. - all four delayed completion sites route their native work through the gate: 'OCC export completion' (exporter_step_stub), 'OCC model completion' (oce_plugin_stub — the MEMFS cache write moves inside the gate too), 'ngspice request completion' and 'ngspice vector completion' (sharedspice_client — every HEAP32/HEAPF64/malloc write inside prepare, inertResult 1 = transport error). Every wxWasmBeginWait caller in the stubs bails on token <= 0. - deliberately NOT ported from codex: ownerModule, enqueueNativeCompletion, executionBarrier, the byte-credit native-entry FIFO — completions are one-shot per wait token and stream volume is bounded at the E-6 transport credit window. Cross-refs logged for group M (M-2/M-6/M-8). E-5 (re-implemented; codex shape kept, owner APIs replaced with the E-8 gate): js_ngspice_install_events binds the handler to the EXACT installing module (handler.__pcbjamNgspiceOwnerModule stamp; presence is not identity), re-installation replaces a foreign module's handler, a superseded handler disarms itself, native entry goes through installingModule._malloc/ ._pcbjam_ngspice_event (never lexical Module), each dispatch checks canTouchNative() (loud drop on a dead/terminal module), and a trap on the per-line entry latches the terminal gate. Tests: scheduler-shim.test.ts +7 (gate happy/stale/dead/terminal/cross-realm/ js-bug/beginWait-refusal). e2e specs updated from the codex line: occ-export decode-fault recovery (real onmessageerror transition via failDecode, J-4), ngspice-probe direct-service coverage, eeschema-sim rewritten onto the E-7 applied-generation receipt (codex's executionBarrier await replaced with a pendingWaits('ngspice') drain poll — the JSPI-line equivalent). Also bumps the kicad submodule to the E-7/E-9 commit (dd5751038f7). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:03:16 +02:00
globalThis.__wxScheduler.runWaitCompletion( 'ngspice request completion', aToken, () => {
const s = JSON.stringify( res ?? {} );
const n = lengthBytesUTF8( s ) + 1;
const p = _malloc( n );
stringToUTF8( s, p, n );
return p;
} );
};
let req;
try {
const svc = globalThis.ngspiceService;
if( !svc )
req = Promise.resolve( { error: 'ngspiceService provider not installed' } );
else
req = Promise.resolve( svc.request( JSON.parse( UTF8ToString( aReqJson ) ) ) );
} catch( e ) {
req = Promise.resolve( { error: String( e ) } );
}
req.then( finish ).catch( ( e ) => finish( { error: String( e ) } ) );
} );
// Vector fetch: fills editor-heap buffers directly (no JSON for MB arrays).
// aMeta: int[4] = { found, vtype, flags, length }; aReal/aComp receive
// malloc'd double buffers (comp interleaved re,im — the ngcomplex_t layout);
// aVName receives a malloc'd name string. The wait result is non-zero on
// transport error. All output writes happen in the resolve callback, BEFORE
// resolveWait — the parked caller reads them only after it resumes, the same
// ordering the in-place park had. Phase E shape, resolution always deferred.
EM_JS( void, js_ngspice_get_vec_start,
( int aToken, const char* aName, int* aMeta, double** aReal, double** aComp,
char** aVName ), {
let req;
try {
const svc = globalThis.ngspiceService;
req = svc ? Promise.resolve( svc.request( { kind: 'get_vec_info',
name: UTF8ToString( aName ) } ) )
: Promise.resolve( { error: 'ngspiceService provider not installed' } );
} catch( e ) {
req = Promise.resolve( { error: String( e ) } );
}
findings(E-5,E-8,E-9): module-identity ngspice events + runWaitCompletion admission gate E-8 (re-implemented for JSPI — the codex gate is entangled with the dropped execution owner; under JSPI a fresh non-suspending JS→wasm entry while another activation is suspended is structurally safe on its own stack, so the admission boundary for worker completions is liveness + trap state, not execution ownership): - jspi-scheduler.js grows `terminal` (trapped instance; distinct from `dead`), canTouchNative(), _terminalizeNativeTrap() (WebAssembly.RuntimeError + cross-realm string classification), and runWaitCompletion(site, token, prepare, inertResult): prepare runs immediately and owns ALL native work; stale tokens and dead/terminal instances drop loudly without resolving (resolving would resume the parked frame inside the damaged module); a trap latches terminal; a plain JS bug resolves inertResult so the wait fails instead of stranding. beginWait refuses (token 0) when dead/terminal. - all four delayed completion sites route their native work through the gate: 'OCC export completion' (exporter_step_stub), 'OCC model completion' (oce_plugin_stub — the MEMFS cache write moves inside the gate too), 'ngspice request completion' and 'ngspice vector completion' (sharedspice_client — every HEAP32/HEAPF64/malloc write inside prepare, inertResult 1 = transport error). Every wxWasmBeginWait caller in the stubs bails on token <= 0. - deliberately NOT ported from codex: ownerModule, enqueueNativeCompletion, executionBarrier, the byte-credit native-entry FIFO — completions are one-shot per wait token and stream volume is bounded at the E-6 transport credit window. Cross-refs logged for group M (M-2/M-6/M-8). E-5 (re-implemented; codex shape kept, owner APIs replaced with the E-8 gate): js_ngspice_install_events binds the handler to the EXACT installing module (handler.__pcbjamNgspiceOwnerModule stamp; presence is not identity), re-installation replaces a foreign module's handler, a superseded handler disarms itself, native entry goes through installingModule._malloc/ ._pcbjam_ngspice_event (never lexical Module), each dispatch checks canTouchNative() (loud drop on a dead/terminal module), and a trap on the per-line entry latches the terminal gate. Tests: scheduler-shim.test.ts +7 (gate happy/stale/dead/terminal/cross-realm/ js-bug/beginWait-refusal). e2e specs updated from the codex line: occ-export decode-fault recovery (real onmessageerror transition via failDecode, J-4), ngspice-probe direct-service coverage, eeschema-sim rewritten onto the E-7 applied-generation receipt (codex's executionBarrier await replaced with a pendingWaits('ngspice') drain poll — the JSPI-line equivalent). Also bumps the kicad submodule to the E-7/E-9 commit (dd5751038f7). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:03:16 +02:00
// E-8: every output-pointer write happens inside the scheduler's
// completion gate, so a dead or trapped instance is never written to.
// A plain JS failure inside the prepare resolves the inertResult (1 =
// transport error) so the parked caller fails instead of stranding.
req.catch( ( e ) => ( { error: String( e ) } ) ).then( ( res ) => {
findings(E-5,E-8,E-9): module-identity ngspice events + runWaitCompletion admission gate E-8 (re-implemented for JSPI — the codex gate is entangled with the dropped execution owner; under JSPI a fresh non-suspending JS→wasm entry while another activation is suspended is structurally safe on its own stack, so the admission boundary for worker completions is liveness + trap state, not execution ownership): - jspi-scheduler.js grows `terminal` (trapped instance; distinct from `dead`), canTouchNative(), _terminalizeNativeTrap() (WebAssembly.RuntimeError + cross-realm string classification), and runWaitCompletion(site, token, prepare, inertResult): prepare runs immediately and owns ALL native work; stale tokens and dead/terminal instances drop loudly without resolving (resolving would resume the parked frame inside the damaged module); a trap latches terminal; a plain JS bug resolves inertResult so the wait fails instead of stranding. beginWait refuses (token 0) when dead/terminal. - all four delayed completion sites route their native work through the gate: 'OCC export completion' (exporter_step_stub), 'OCC model completion' (oce_plugin_stub — the MEMFS cache write moves inside the gate too), 'ngspice request completion' and 'ngspice vector completion' (sharedspice_client — every HEAP32/HEAPF64/malloc write inside prepare, inertResult 1 = transport error). Every wxWasmBeginWait caller in the stubs bails on token <= 0. - deliberately NOT ported from codex: ownerModule, enqueueNativeCompletion, executionBarrier, the byte-credit native-entry FIFO — completions are one-shot per wait token and stream volume is bounded at the E-6 transport credit window. Cross-refs logged for group M (M-2/M-6/M-8). E-5 (re-implemented; codex shape kept, owner APIs replaced with the E-8 gate): js_ngspice_install_events binds the handler to the EXACT installing module (handler.__pcbjamNgspiceOwnerModule stamp; presence is not identity), re-installation replaces a foreign module's handler, a superseded handler disarms itself, native entry goes through installingModule._malloc/ ._pcbjam_ngspice_event (never lexical Module), each dispatch checks canTouchNative() (loud drop on a dead/terminal module), and a trap on the per-line entry latches the terminal gate. Tests: scheduler-shim.test.ts +7 (gate happy/stale/dead/terminal/cross-realm/ js-bug/beginWait-refusal). e2e specs updated from the codex line: occ-export decode-fault recovery (real onmessageerror transition via failDecode, J-4), ngspice-probe direct-service coverage, eeschema-sim rewritten onto the E-7 applied-generation receipt (codex's executionBarrier await replaced with a pendingWaits('ngspice') drain poll — the JSPI-line equivalent). Also bumps the kicad submodule to the E-7/E-9 commit (dd5751038f7). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:03:16 +02:00
globalThis.__wxScheduler.runWaitCompletion( 'ngspice vector completion', aToken, () => {
HEAP32[aMeta >> 2] = 0;
HEAPU32[aReal >> 2] = 0;
HEAPU32[aComp >> 2] = 0;
HEAPU32[aVName >> 2] = 0;
if( !res || res.error )
return 1;
if( !res.found )
return 0;
HEAP32[( aMeta >> 2 ) + 1] = res.vtype | 0;
HEAP32[( aMeta >> 2 ) + 2] = res.flags | 0;
findings(E-10..E-22): fix the defects a code review found in the E-1..E-9 work A review of the group-E fixes found 13 further defects; ten were introduced by those fixes, two pre-existed and were merely relocated, one is deferred. Services / transport E-10 retireWorker synthesized no bg/exit frame, so sharedspice's s_bgRunning mirror stayed latched true after a mid-run worker death: Run stayed disabled and the promised fresh-worker restart was unreachable for the whole session. Retirement now dispatches a synthetic controlled-exit straight to the installed handler (never through dispatchEvt — a fabricated frame must not touch the credit ledger). Driving the repro exposed two further defects, both fixed here: a replacement worker trapped on pre-init engine reads, and the rerun's cm_input_path/circ hit that uninitialized engine before KiCad's validate() re-init (the native flow assumes a crashed engine survives in-process — true for the dll, false for a dead worker). Reads now answer their empty shapes pre-init, writes lazy-init, and init is idempotent per worker engine. E-19 dispatchEvt acked only AFTER handler(evt) returned, and the sharedspice client deliberately rethrows non-trap errors — so each throw leaked one unit of the 64-frame credit window until the stream died with a misattributed "transport exceeded". The ack moves to a finally in both service copies; the throw still propagates (the trap machinery needs it). E-20 the oversize-line path promises to transfer the accepted prefix, but with the window full that flush only DEFERS, and stopEventStream wiped the deferred queue — losing the diagnostics that explain the failure. The terminal notice now carries them as pendingEvents; both hosts deliver them in order, unacked (the fatal frame is outside the credit protocol). E-21 the 30s prefetch deadline discarded every model already collected and reported nothing. A caller-owned progress sink ships the partials and the omission reaches the export report. (Awaiting the aborted collection was rejected: an in-flight source fetch is not abortable — E-4's original disease.) Plus a serving-candidate memo, so a .wrl ref served by its .step fallback stops re-probing the miss on every export. Scheduler E-14 _terminalizeNativeTrap classified by message substring, so any plain JS error QUOTING 'Aborted(' or 'out of bounds' permanently bricked a healthy instance. Now structural only: instanceof RuntimeError plus a duck-typed name check (verified in this build's glue that abort() throws a genuine RuntimeError both pre- and post-runtime-init). Module.onAbort now latches the gate — the authoritative notification, previously ignored. E-15 the shim half: _pumpResume gates on terminal (catching wakes already queued at latch time) and resolveWait refuses on terminal WITHOUT consuming the entry, so a frame stays visibly parked rather than resuming inside a trapped module. E-16 the E-5 handler read the realm-global scheduler at dispatch instead of its installing module's; also frees the per-line buffer on the non-trap rethrow path. E-11 get_vec trusted the worker's res.length over the transferred arrays. Observed death shape: a 4 GiB std::vector threw an unhandled std::length_error that exited the editor's main loop. Now clamped, with the buffers freed on every failure path. Guardrails (replacing two deferred refactors: e2e→production-code injection and collapsing the four copies of the worker-lifecycle machinery) E-18 the source contract asserted comment-string counts — rewording failed CI while moving a guard outside its #ifdef passed. It now parses the #ifdef regions and asserts on code. service-stub-parity.ts pins what the four lifecycle copies must share: credit-window equality parsed from source, the finally-ack, boot deadlines, terminal-notice consumption. The transport numbers are now single-sourced from the worker. CI actually runs the gates: the web/standalone vitest suites (which had NEVER run in CI), the reducer, the source contract and the parity tool — with a NON_PLAYWRIGHT_GATES check so deleting a step re-fails the lint. E-22 the e2e occ stub's 60s boot watchdog, deleted in a66e109, is restored in the ngspice-stub shape with a wedgeNextBoot() repro hook. Every behavioral fix has red-then-green evidence (the reds were captured first). E-17 (a stale RUNNING cross-stamping the next run's generation under E-6's transport deferral) is DEFERRED with its analysis recorded — a real fix needs run identity on the bg frames. Test hygiene: the dwell lint now requires the mandated ": <why>" and all 47 bare markers carry their reason; three export-report dwells became modal-lease polls; exact-ledger assertions became relative deltas; the dead data-wx-dom-id branch, an unused fault hook and unused receipt plumbing are gone; abort scans, wx dialog drivers, the sim harness and the vitest FakeWorker are each one copy now. Bumps kicad and wxwidgets to their findings-group-e tips. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-27 12:27:12 +02:00
// E-11: v_length must describe what was actually TRANSFERRED,
// never the worker's self-reported count — a corrupted worker
// answering a huge length with small arrays otherwise drives the
// native consumer through a multi-gigabyte copy (observed dying
// as an unhandled std::length_error that exits the main loop).
// Interleaved re,im doubles: 2 per complex element.
let length = Math.max( 0, res.length | 0 );
const nReal = ( res.real && res.real.length ) | 0;
const nComp = ( res.comp && res.comp.length ) | 0;
if( nReal ) length = Math.min( length, nReal );
if( nComp ) length = Math.min( length, nComp >> 1 );
if( !nReal && !nComp ) length = 0;
HEAP32[( aMeta >> 2 ) + 3] = length;
if( nReal ) {
const p = _malloc( nReal * 8 );
findings(E-5,E-8,E-9): module-identity ngspice events + runWaitCompletion admission gate E-8 (re-implemented for JSPI — the codex gate is entangled with the dropped execution owner; under JSPI a fresh non-suspending JS→wasm entry while another activation is suspended is structurally safe on its own stack, so the admission boundary for worker completions is liveness + trap state, not execution ownership): - jspi-scheduler.js grows `terminal` (trapped instance; distinct from `dead`), canTouchNative(), _terminalizeNativeTrap() (WebAssembly.RuntimeError + cross-realm string classification), and runWaitCompletion(site, token, prepare, inertResult): prepare runs immediately and owns ALL native work; stale tokens and dead/terminal instances drop loudly without resolving (resolving would resume the parked frame inside the damaged module); a trap latches terminal; a plain JS bug resolves inertResult so the wait fails instead of stranding. beginWait refuses (token 0) when dead/terminal. - all four delayed completion sites route their native work through the gate: 'OCC export completion' (exporter_step_stub), 'OCC model completion' (oce_plugin_stub — the MEMFS cache write moves inside the gate too), 'ngspice request completion' and 'ngspice vector completion' (sharedspice_client — every HEAP32/HEAPF64/malloc write inside prepare, inertResult 1 = transport error). Every wxWasmBeginWait caller in the stubs bails on token <= 0. - deliberately NOT ported from codex: ownerModule, enqueueNativeCompletion, executionBarrier, the byte-credit native-entry FIFO — completions are one-shot per wait token and stream volume is bounded at the E-6 transport credit window. Cross-refs logged for group M (M-2/M-6/M-8). E-5 (re-implemented; codex shape kept, owner APIs replaced with the E-8 gate): js_ngspice_install_events binds the handler to the EXACT installing module (handler.__pcbjamNgspiceOwnerModule stamp; presence is not identity), re-installation replaces a foreign module's handler, a superseded handler disarms itself, native entry goes through installingModule._malloc/ ._pcbjam_ngspice_event (never lexical Module), each dispatch checks canTouchNative() (loud drop on a dead/terminal module), and a trap on the per-line entry latches the terminal gate. Tests: scheduler-shim.test.ts +7 (gate happy/stale/dead/terminal/cross-realm/ js-bug/beginWait-refusal). e2e specs updated from the codex line: occ-export decode-fault recovery (real onmessageerror transition via failDecode, J-4), ngspice-probe direct-service coverage, eeschema-sim rewritten onto the E-7 applied-generation receipt (codex's executionBarrier await replaced with a pendingWaits('ngspice') drain poll — the JSPI-line equivalent). Also bumps the kicad submodule to the E-7/E-9 commit (dd5751038f7). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:03:16 +02:00
HEAPF64.set( res.real, p >> 3 );
HEAPU32[aReal >> 2] = p;
}
findings(E-10..E-22): fix the defects a code review found in the E-1..E-9 work A review of the group-E fixes found 13 further defects; ten were introduced by those fixes, two pre-existed and were merely relocated, one is deferred. Services / transport E-10 retireWorker synthesized no bg/exit frame, so sharedspice's s_bgRunning mirror stayed latched true after a mid-run worker death: Run stayed disabled and the promised fresh-worker restart was unreachable for the whole session. Retirement now dispatches a synthetic controlled-exit straight to the installed handler (never through dispatchEvt — a fabricated frame must not touch the credit ledger). Driving the repro exposed two further defects, both fixed here: a replacement worker trapped on pre-init engine reads, and the rerun's cm_input_path/circ hit that uninitialized engine before KiCad's validate() re-init (the native flow assumes a crashed engine survives in-process — true for the dll, false for a dead worker). Reads now answer their empty shapes pre-init, writes lazy-init, and init is idempotent per worker engine. E-19 dispatchEvt acked only AFTER handler(evt) returned, and the sharedspice client deliberately rethrows non-trap errors — so each throw leaked one unit of the 64-frame credit window until the stream died with a misattributed "transport exceeded". The ack moves to a finally in both service copies; the throw still propagates (the trap machinery needs it). E-20 the oversize-line path promises to transfer the accepted prefix, but with the window full that flush only DEFERS, and stopEventStream wiped the deferred queue — losing the diagnostics that explain the failure. The terminal notice now carries them as pendingEvents; both hosts deliver them in order, unacked (the fatal frame is outside the credit protocol). E-21 the 30s prefetch deadline discarded every model already collected and reported nothing. A caller-owned progress sink ships the partials and the omission reaches the export report. (Awaiting the aborted collection was rejected: an in-flight source fetch is not abortable — E-4's original disease.) Plus a serving-candidate memo, so a .wrl ref served by its .step fallback stops re-probing the miss on every export. Scheduler E-14 _terminalizeNativeTrap classified by message substring, so any plain JS error QUOTING 'Aborted(' or 'out of bounds' permanently bricked a healthy instance. Now structural only: instanceof RuntimeError plus a duck-typed name check (verified in this build's glue that abort() throws a genuine RuntimeError both pre- and post-runtime-init). Module.onAbort now latches the gate — the authoritative notification, previously ignored. E-15 the shim half: _pumpResume gates on terminal (catching wakes already queued at latch time) and resolveWait refuses on terminal WITHOUT consuming the entry, so a frame stays visibly parked rather than resuming inside a trapped module. E-16 the E-5 handler read the realm-global scheduler at dispatch instead of its installing module's; also frees the per-line buffer on the non-trap rethrow path. E-11 get_vec trusted the worker's res.length over the transferred arrays. Observed death shape: a 4 GiB std::vector threw an unhandled std::length_error that exited the editor's main loop. Now clamped, with the buffers freed on every failure path. Guardrails (replacing two deferred refactors: e2e→production-code injection and collapsing the four copies of the worker-lifecycle machinery) E-18 the source contract asserted comment-string counts — rewording failed CI while moving a guard outside its #ifdef passed. It now parses the #ifdef regions and asserts on code. service-stub-parity.ts pins what the four lifecycle copies must share: credit-window equality parsed from source, the finally-ack, boot deadlines, terminal-notice consumption. The transport numbers are now single-sourced from the worker. CI actually runs the gates: the web/standalone vitest suites (which had NEVER run in CI), the reducer, the source contract and the parity tool — with a NON_PLAYWRIGHT_GATES check so deleting a step re-fails the lint. E-22 the e2e occ stub's 60s boot watchdog, deleted in a66e109, is restored in the ngspice-stub shape with a wedgeNextBoot() repro hook. Every behavioral fix has red-then-green evidence (the reds were captured first). E-17 (a stale RUNNING cross-stamping the next run's generation under E-6's transport deferral) is DEFERRED with its analysis recorded — a real fix needs run identity on the bg frames. Test hygiene: the dwell lint now requires the mandated ": <why>" and all 47 bare markers carry their reason; three export-report dwells became modal-lease polls; exact-ledger assertions became relative deltas; the dead data-wx-dom-id branch, an unused fault hook and unused receipt plumbing are gone; abort scans, wx dialog drivers, the sim harness and the vitest FakeWorker are each one copy now. Bumps kicad and wxwidgets to their findings-group-e tips. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-27 12:27:12 +02:00
if( nComp ) {
const p = _malloc( nComp * 8 );
findings(E-5,E-8,E-9): module-identity ngspice events + runWaitCompletion admission gate E-8 (re-implemented for JSPI — the codex gate is entangled with the dropped execution owner; under JSPI a fresh non-suspending JS→wasm entry while another activation is suspended is structurally safe on its own stack, so the admission boundary for worker completions is liveness + trap state, not execution ownership): - jspi-scheduler.js grows `terminal` (trapped instance; distinct from `dead`), canTouchNative(), _terminalizeNativeTrap() (WebAssembly.RuntimeError + cross-realm string classification), and runWaitCompletion(site, token, prepare, inertResult): prepare runs immediately and owns ALL native work; stale tokens and dead/terminal instances drop loudly without resolving (resolving would resume the parked frame inside the damaged module); a trap latches terminal; a plain JS bug resolves inertResult so the wait fails instead of stranding. beginWait refuses (token 0) when dead/terminal. - all four delayed completion sites route their native work through the gate: 'OCC export completion' (exporter_step_stub), 'OCC model completion' (oce_plugin_stub — the MEMFS cache write moves inside the gate too), 'ngspice request completion' and 'ngspice vector completion' (sharedspice_client — every HEAP32/HEAPF64/malloc write inside prepare, inertResult 1 = transport error). Every wxWasmBeginWait caller in the stubs bails on token <= 0. - deliberately NOT ported from codex: ownerModule, enqueueNativeCompletion, executionBarrier, the byte-credit native-entry FIFO — completions are one-shot per wait token and stream volume is bounded at the E-6 transport credit window. Cross-refs logged for group M (M-2/M-6/M-8). E-5 (re-implemented; codex shape kept, owner APIs replaced with the E-8 gate): js_ngspice_install_events binds the handler to the EXACT installing module (handler.__pcbjamNgspiceOwnerModule stamp; presence is not identity), re-installation replaces a foreign module's handler, a superseded handler disarms itself, native entry goes through installingModule._malloc/ ._pcbjam_ngspice_event (never lexical Module), each dispatch checks canTouchNative() (loud drop on a dead/terminal module), and a trap on the per-line entry latches the terminal gate. Tests: scheduler-shim.test.ts +7 (gate happy/stale/dead/terminal/cross-realm/ js-bug/beginWait-refusal). e2e specs updated from the codex line: occ-export decode-fault recovery (real onmessageerror transition via failDecode, J-4), ngspice-probe direct-service coverage, eeschema-sim rewritten onto the E-7 applied-generation receipt (codex's executionBarrier await replaced with a pendingWaits('ngspice') drain poll — the JSPI-line equivalent). Also bumps the kicad submodule to the E-7/E-9 commit (dd5751038f7). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:03:16 +02:00
HEAPF64.set( res.comp, p >> 3 );
HEAPU32[aComp >> 2] = p;
}
const s = res.vname || '';
const n = lengthBytesUTF8( s ) + 1;
const vp = _malloc( n );
stringToUTF8( s, vp, n );
HEAPU32[aVName >> 2] = vp;
HEAP32[aMeta >> 2] = 1;
return 0;
}, /* inertResult = */ 1 );
} );
} );
// Token waits live in the wx wasm port (evtloop.cpp).
extern "C" int wxWasmBeginWait( const char* aKind );
extern "C" int wxWasmYieldUntil( int aToken );
// Event dispatcher: provider `{ evt }` frames -> KiCad's registered callbacks
// via the exported pcbjam_ngspice_event (fresh wasm entries; see header
findings(E-5,E-8,E-9): module-identity ngspice events + runWaitCompletion admission gate E-8 (re-implemented for JSPI — the codex gate is entangled with the dropped execution owner; under JSPI a fresh non-suspending JS→wasm entry while another activation is suspended is structurally safe on its own stack, so the admission boundary for worker completions is liveness + trap state, not execution ownership): - jspi-scheduler.js grows `terminal` (trapped instance; distinct from `dead`), canTouchNative(), _terminalizeNativeTrap() (WebAssembly.RuntimeError + cross-realm string classification), and runWaitCompletion(site, token, prepare, inertResult): prepare runs immediately and owns ALL native work; stale tokens and dead/terminal instances drop loudly without resolving (resolving would resume the parked frame inside the damaged module); a trap latches terminal; a plain JS bug resolves inertResult so the wait fails instead of stranding. beginWait refuses (token 0) when dead/terminal. - all four delayed completion sites route their native work through the gate: 'OCC export completion' (exporter_step_stub), 'OCC model completion' (oce_plugin_stub — the MEMFS cache write moves inside the gate too), 'ngspice request completion' and 'ngspice vector completion' (sharedspice_client — every HEAP32/HEAPF64/malloc write inside prepare, inertResult 1 = transport error). Every wxWasmBeginWait caller in the stubs bails on token <= 0. - deliberately NOT ported from codex: ownerModule, enqueueNativeCompletion, executionBarrier, the byte-credit native-entry FIFO — completions are one-shot per wait token and stream volume is bounded at the E-6 transport credit window. Cross-refs logged for group M (M-2/M-6/M-8). E-5 (re-implemented; codex shape kept, owner APIs replaced with the E-8 gate): js_ngspice_install_events binds the handler to the EXACT installing module (handler.__pcbjamNgspiceOwnerModule stamp; presence is not identity), re-installation replaces a foreign module's handler, a superseded handler disarms itself, native entry goes through installingModule._malloc/ ._pcbjam_ngspice_event (never lexical Module), each dispatch checks canTouchNative() (loud drop on a dead/terminal module), and a trap on the per-line entry latches the terminal gate. Tests: scheduler-shim.test.ts +7 (gate happy/stale/dead/terminal/cross-realm/ js-bug/beginWait-refusal). e2e specs updated from the codex line: occ-export decode-fault recovery (real onmessageerror transition via failDecode, J-4), ngspice-probe direct-service coverage, eeschema-sim rewritten onto the E-7 applied-generation receipt (codex's executionBarrier await replaced with a pendingWaits('ngspice') drain poll — the JSPI-line equivalent). Also bumps the kicad submodule to the E-7/E-9 commit (dd5751038f7). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:03:16 +02:00
// comment).
//
// E-5: the handler is bound to the EXACT installing module, not to whatever
// `Module` lexically means when an event later arrives. Presence is not
// identity: the old install-once guard let a replacement module (trap
// recovery is module replacement — cross-ref G-8) keep the retired module's
// handler, whose closure drove the dead instance's heap. Re-installation is
// idempotent only for the same module; a different module replaces the
// handler, and a superseded handler disarms itself.
EM_JS( void, js_ngspice_install_events, (), {
findings(E-5,E-8,E-9): module-identity ngspice events + runWaitCompletion admission gate E-8 (re-implemented for JSPI — the codex gate is entangled with the dropped execution owner; under JSPI a fresh non-suspending JS→wasm entry while another activation is suspended is structurally safe on its own stack, so the admission boundary for worker completions is liveness + trap state, not execution ownership): - jspi-scheduler.js grows `terminal` (trapped instance; distinct from `dead`), canTouchNative(), _terminalizeNativeTrap() (WebAssembly.RuntimeError + cross-realm string classification), and runWaitCompletion(site, token, prepare, inertResult): prepare runs immediately and owns ALL native work; stale tokens and dead/terminal instances drop loudly without resolving (resolving would resume the parked frame inside the damaged module); a trap latches terminal; a plain JS bug resolves inertResult so the wait fails instead of stranding. beginWait refuses (token 0) when dead/terminal. - all four delayed completion sites route their native work through the gate: 'OCC export completion' (exporter_step_stub), 'OCC model completion' (oce_plugin_stub — the MEMFS cache write moves inside the gate too), 'ngspice request completion' and 'ngspice vector completion' (sharedspice_client — every HEAP32/HEAPF64/malloc write inside prepare, inertResult 1 = transport error). Every wxWasmBeginWait caller in the stubs bails on token <= 0. - deliberately NOT ported from codex: ownerModule, enqueueNativeCompletion, executionBarrier, the byte-credit native-entry FIFO — completions are one-shot per wait token and stream volume is bounded at the E-6 transport credit window. Cross-refs logged for group M (M-2/M-6/M-8). E-5 (re-implemented; codex shape kept, owner APIs replaced with the E-8 gate): js_ngspice_install_events binds the handler to the EXACT installing module (handler.__pcbjamNgspiceOwnerModule stamp; presence is not identity), re-installation replaces a foreign module's handler, a superseded handler disarms itself, native entry goes through installingModule._malloc/ ._pcbjam_ngspice_event (never lexical Module), each dispatch checks canTouchNative() (loud drop on a dead/terminal module), and a trap on the per-line entry latches the terminal gate. Tests: scheduler-shim.test.ts +7 (gate happy/stale/dead/terminal/cross-realm/ js-bug/beginWait-refusal). e2e specs updated from the codex line: occ-export decode-fault recovery (real onmessageerror transition via failDecode, J-4), ngspice-probe direct-service coverage, eeschema-sim rewritten onto the E-7 applied-generation receipt (codex's executionBarrier await replaced with a pendingWaits('ngspice') drain poll — the JSPI-line equivalent). Also bumps the kicad submodule to the E-7/E-9 commit (dd5751038f7). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:03:16 +02:00
const installingModule = Module;
findings(E-10..E-22): fix the defects a code review found in the E-1..E-9 work A review of the group-E fixes found 13 further defects; ten were introduced by those fixes, two pre-existed and were merely relocated, one is deferred. Services / transport E-10 retireWorker synthesized no bg/exit frame, so sharedspice's s_bgRunning mirror stayed latched true after a mid-run worker death: Run stayed disabled and the promised fresh-worker restart was unreachable for the whole session. Retirement now dispatches a synthetic controlled-exit straight to the installed handler (never through dispatchEvt — a fabricated frame must not touch the credit ledger). Driving the repro exposed two further defects, both fixed here: a replacement worker trapped on pre-init engine reads, and the rerun's cm_input_path/circ hit that uninitialized engine before KiCad's validate() re-init (the native flow assumes a crashed engine survives in-process — true for the dll, false for a dead worker). Reads now answer their empty shapes pre-init, writes lazy-init, and init is idempotent per worker engine. E-19 dispatchEvt acked only AFTER handler(evt) returned, and the sharedspice client deliberately rethrows non-trap errors — so each throw leaked one unit of the 64-frame credit window until the stream died with a misattributed "transport exceeded". The ack moves to a finally in both service copies; the throw still propagates (the trap machinery needs it). E-20 the oversize-line path promises to transfer the accepted prefix, but with the window full that flush only DEFERS, and stopEventStream wiped the deferred queue — losing the diagnostics that explain the failure. The terminal notice now carries them as pendingEvents; both hosts deliver them in order, unacked (the fatal frame is outside the credit protocol). E-21 the 30s prefetch deadline discarded every model already collected and reported nothing. A caller-owned progress sink ships the partials and the omission reaches the export report. (Awaiting the aborted collection was rejected: an in-flight source fetch is not abortable — E-4's original disease.) Plus a serving-candidate memo, so a .wrl ref served by its .step fallback stops re-probing the miss on every export. Scheduler E-14 _terminalizeNativeTrap classified by message substring, so any plain JS error QUOTING 'Aborted(' or 'out of bounds' permanently bricked a healthy instance. Now structural only: instanceof RuntimeError plus a duck-typed name check (verified in this build's glue that abort() throws a genuine RuntimeError both pre- and post-runtime-init). Module.onAbort now latches the gate — the authoritative notification, previously ignored. E-15 the shim half: _pumpResume gates on terminal (catching wakes already queued at latch time) and resolveWait refuses on terminal WITHOUT consuming the entry, so a frame stays visibly parked rather than resuming inside a trapped module. E-16 the E-5 handler read the realm-global scheduler at dispatch instead of its installing module's; also frees the per-line buffer on the non-trap rethrow path. E-11 get_vec trusted the worker's res.length over the transferred arrays. Observed death shape: a 4 GiB std::vector threw an unhandled std::length_error that exited the editor's main loop. Now clamped, with the buffers freed on every failure path. Guardrails (replacing two deferred refactors: e2e→production-code injection and collapsing the four copies of the worker-lifecycle machinery) E-18 the source contract asserted comment-string counts — rewording failed CI while moving a guard outside its #ifdef passed. It now parses the #ifdef regions and asserts on code. service-stub-parity.ts pins what the four lifecycle copies must share: credit-window equality parsed from source, the finally-ack, boot deadlines, terminal-notice consumption. The transport numbers are now single-sourced from the worker. CI actually runs the gates: the web/standalone vitest suites (which had NEVER run in CI), the reducer, the source contract and the parity tool — with a NON_PLAYWRIGHT_GATES check so deleting a step re-fails the lint. E-22 the e2e occ stub's 60s boot watchdog, deleted in a66e109, is restored in the ngspice-stub shape with a wedgeNextBoot() repro hook. Every behavioral fix has red-then-green evidence (the reds were captured first). E-17 (a stale RUNNING cross-stamping the next run's generation under E-6's transport deferral) is DEFERRED with its analysis recorded — a real fix needs run identity on the bg frames. Test hygiene: the dwell lint now requires the mandated ": <why>" and all 47 bare markers carry their reason; three export-report dwells became modal-lease polls; exact-ledger assertions became relative deltas; the dead data-wx-dom-id branch, an unused fault hook and unused receipt plumbing are gone; abort scans, wx dialog drivers, the sim harness and the vitest FakeWorker are each one copy now. Bumps kicad and wxwidgets to their findings-group-e tips. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-27 12:27:12 +02:00
// E-16: capture the installing module's SCHEDULER too — the liveness gate
// and trap latch below must describe the exact instance this handler
// drives, not whatever scheduler the realm holds at dispatch time (under
// same-realm module replacement the realm-global would belong to the
// successor).
const installingScheduler = globalThis.__wxScheduler;
findings(E-5,E-8,E-9): module-identity ngspice events + runWaitCompletion admission gate E-8 (re-implemented for JSPI — the codex gate is entangled with the dropped execution owner; under JSPI a fresh non-suspending JS→wasm entry while another activation is suspended is structurally safe on its own stack, so the admission boundary for worker completions is liveness + trap state, not execution ownership): - jspi-scheduler.js grows `terminal` (trapped instance; distinct from `dead`), canTouchNative(), _terminalizeNativeTrap() (WebAssembly.RuntimeError + cross-realm string classification), and runWaitCompletion(site, token, prepare, inertResult): prepare runs immediately and owns ALL native work; stale tokens and dead/terminal instances drop loudly without resolving (resolving would resume the parked frame inside the damaged module); a trap latches terminal; a plain JS bug resolves inertResult so the wait fails instead of stranding. beginWait refuses (token 0) when dead/terminal. - all four delayed completion sites route their native work through the gate: 'OCC export completion' (exporter_step_stub), 'OCC model completion' (oce_plugin_stub — the MEMFS cache write moves inside the gate too), 'ngspice request completion' and 'ngspice vector completion' (sharedspice_client — every HEAP32/HEAPF64/malloc write inside prepare, inertResult 1 = transport error). Every wxWasmBeginWait caller in the stubs bails on token <= 0. - deliberately NOT ported from codex: ownerModule, enqueueNativeCompletion, executionBarrier, the byte-credit native-entry FIFO — completions are one-shot per wait token and stream volume is bounded at the E-6 transport credit window. Cross-refs logged for group M (M-2/M-6/M-8). E-5 (re-implemented; codex shape kept, owner APIs replaced with the E-8 gate): js_ngspice_install_events binds the handler to the EXACT installing module (handler.__pcbjamNgspiceOwnerModule stamp; presence is not identity), re-installation replaces a foreign module's handler, a superseded handler disarms itself, native entry goes through installingModule._malloc/ ._pcbjam_ngspice_event (never lexical Module), each dispatch checks canTouchNative() (loud drop on a dead/terminal module), and a trap on the per-line entry latches the terminal gate. Tests: scheduler-shim.test.ts +7 (gate happy/stale/dead/terminal/cross-realm/ js-bug/beginWait-refusal). e2e specs updated from the codex line: occ-export decode-fault recovery (real onmessageerror transition via failDecode, J-4), ngspice-probe direct-service coverage, eeschema-sim rewritten onto the E-7 applied-generation receipt (codex's executionBarrier await replaced with a pendingWaits('ngspice') drain poll — the JSPI-line equivalent). Also bumps the kicad submodule to the E-7/E-9 commit (dd5751038f7). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:03:16 +02:00
const installed = globalThis.__ngspiceOnEvent;
if( installed && installed.__pcbjamNgspiceOwnerModule === installingModule )
return;
findings(E-5,E-8,E-9): module-identity ngspice events + runWaitCompletion admission gate E-8 (re-implemented for JSPI — the codex gate is entangled with the dropped execution owner; under JSPI a fresh non-suspending JS→wasm entry while another activation is suspended is structurally safe on its own stack, so the admission boundary for worker completions is liveness + trap state, not execution ownership): - jspi-scheduler.js grows `terminal` (trapped instance; distinct from `dead`), canTouchNative(), _terminalizeNativeTrap() (WebAssembly.RuntimeError + cross-realm string classification), and runWaitCompletion(site, token, prepare, inertResult): prepare runs immediately and owns ALL native work; stale tokens and dead/terminal instances drop loudly without resolving (resolving would resume the parked frame inside the damaged module); a trap latches terminal; a plain JS bug resolves inertResult so the wait fails instead of stranding. beginWait refuses (token 0) when dead/terminal. - all four delayed completion sites route their native work through the gate: 'OCC export completion' (exporter_step_stub), 'OCC model completion' (oce_plugin_stub — the MEMFS cache write moves inside the gate too), 'ngspice request completion' and 'ngspice vector completion' (sharedspice_client — every HEAP32/HEAPF64/malloc write inside prepare, inertResult 1 = transport error). Every wxWasmBeginWait caller in the stubs bails on token <= 0. - deliberately NOT ported from codex: ownerModule, enqueueNativeCompletion, executionBarrier, the byte-credit native-entry FIFO — completions are one-shot per wait token and stream volume is bounded at the E-6 transport credit window. Cross-refs logged for group M (M-2/M-6/M-8). E-5 (re-implemented; codex shape kept, owner APIs replaced with the E-8 gate): js_ngspice_install_events binds the handler to the EXACT installing module (handler.__pcbjamNgspiceOwnerModule stamp; presence is not identity), re-installation replaces a foreign module's handler, a superseded handler disarms itself, native entry goes through installingModule._malloc/ ._pcbjam_ngspice_event (never lexical Module), each dispatch checks canTouchNative() (loud drop on a dead/terminal module), and a trap on the per-line entry latches the terminal gate. Tests: scheduler-shim.test.ts +7 (gate happy/stale/dead/terminal/cross-realm/ js-bug/beginWait-refusal). e2e specs updated from the codex line: occ-export decode-fault recovery (real onmessageerror transition via failDecode, J-4), ngspice-probe direct-service coverage, eeschema-sim rewritten onto the E-7 applied-generation receipt (codex's executionBarrier await replaced with a pendingWaits('ngspice') drain poll — the JSPI-line equivalent). Also bumps the kicad submodule to the E-7/E-9 commit (dd5751038f7). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:03:16 +02:00
const handler = ( evt ) => {
if( globalThis.__ngspiceOnEvent !== handler )
return; // superseded install — never drive a retired module
findings(E-10..E-22): fix the defects a code review found in the E-1..E-9 work A review of the group-E fixes found 13 further defects; ten were introduced by those fixes, two pre-existed and were merely relocated, one is deferred. Services / transport E-10 retireWorker synthesized no bg/exit frame, so sharedspice's s_bgRunning mirror stayed latched true after a mid-run worker death: Run stayed disabled and the promised fresh-worker restart was unreachable for the whole session. Retirement now dispatches a synthetic controlled-exit straight to the installed handler (never through dispatchEvt — a fabricated frame must not touch the credit ledger). Driving the repro exposed two further defects, both fixed here: a replacement worker trapped on pre-init engine reads, and the rerun's cm_input_path/circ hit that uninitialized engine before KiCad's validate() re-init (the native flow assumes a crashed engine survives in-process — true for the dll, false for a dead worker). Reads now answer their empty shapes pre-init, writes lazy-init, and init is idempotent per worker engine. E-19 dispatchEvt acked only AFTER handler(evt) returned, and the sharedspice client deliberately rethrows non-trap errors — so each throw leaked one unit of the 64-frame credit window until the stream died with a misattributed "transport exceeded". The ack moves to a finally in both service copies; the throw still propagates (the trap machinery needs it). E-20 the oversize-line path promises to transfer the accepted prefix, but with the window full that flush only DEFERS, and stopEventStream wiped the deferred queue — losing the diagnostics that explain the failure. The terminal notice now carries them as pendingEvents; both hosts deliver them in order, unacked (the fatal frame is outside the credit protocol). E-21 the 30s prefetch deadline discarded every model already collected and reported nothing. A caller-owned progress sink ships the partials and the omission reaches the export report. (Awaiting the aborted collection was rejected: an in-flight source fetch is not abortable — E-4's original disease.) Plus a serving-candidate memo, so a .wrl ref served by its .step fallback stops re-probing the miss on every export. Scheduler E-14 _terminalizeNativeTrap classified by message substring, so any plain JS error QUOTING 'Aborted(' or 'out of bounds' permanently bricked a healthy instance. Now structural only: instanceof RuntimeError plus a duck-typed name check (verified in this build's glue that abort() throws a genuine RuntimeError both pre- and post-runtime-init). Module.onAbort now latches the gate — the authoritative notification, previously ignored. E-15 the shim half: _pumpResume gates on terminal (catching wakes already queued at latch time) and resolveWait refuses on terminal WITHOUT consuming the entry, so a frame stays visibly parked rather than resuming inside a trapped module. E-16 the E-5 handler read the realm-global scheduler at dispatch instead of its installing module's; also frees the per-line buffer on the non-trap rethrow path. E-11 get_vec trusted the worker's res.length over the transferred arrays. Observed death shape: a 4 GiB std::vector threw an unhandled std::length_error that exited the editor's main loop. Now clamped, with the buffers freed on every failure path. Guardrails (replacing two deferred refactors: e2e→production-code injection and collapsing the four copies of the worker-lifecycle machinery) E-18 the source contract asserted comment-string counts — rewording failed CI while moving a guard outside its #ifdef passed. It now parses the #ifdef regions and asserts on code. service-stub-parity.ts pins what the four lifecycle copies must share: credit-window equality parsed from source, the finally-ack, boot deadlines, terminal-notice consumption. The transport numbers are now single-sourced from the worker. CI actually runs the gates: the web/standalone vitest suites (which had NEVER run in CI), the reducer, the source contract and the parity tool — with a NON_PLAYWRIGHT_GATES check so deleting a step re-fails the lint. E-22 the e2e occ stub's 60s boot watchdog, deleted in a66e109, is restored in the ngspice-stub shape with a wedgeNextBoot() repro hook. Every behavioral fix has red-then-green evidence (the reds were captured first). E-17 (a stale RUNNING cross-stamping the next run's generation under E-6's transport deferral) is DEFERRED with its analysis recorded — a real fix needs run identity on the bg frames. Test hygiene: the dwell lint now requires the mandated ": <why>" and all 47 bare markers carry their reason; three export-report dwells became modal-lease polls; exact-ledger assertions became relative deltas; the dead data-wx-dom-id branch, an unused fault hook and unused receipt plumbing are gone; abort scans, wx dialog drivers, the sim harness and the vitest FakeWorker are each one copy now. Bumps kicad and wxwidgets to their findings-group-e tips. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-27 12:27:12 +02:00
const sched = installingScheduler;
findings(E-5,E-8,E-9): module-identity ngspice events + runWaitCompletion admission gate E-8 (re-implemented for JSPI — the codex gate is entangled with the dropped execution owner; under JSPI a fresh non-suspending JS→wasm entry while another activation is suspended is structurally safe on its own stack, so the admission boundary for worker completions is liveness + trap state, not execution ownership): - jspi-scheduler.js grows `terminal` (trapped instance; distinct from `dead`), canTouchNative(), _terminalizeNativeTrap() (WebAssembly.RuntimeError + cross-realm string classification), and runWaitCompletion(site, token, prepare, inertResult): prepare runs immediately and owns ALL native work; stale tokens and dead/terminal instances drop loudly without resolving (resolving would resume the parked frame inside the damaged module); a trap latches terminal; a plain JS bug resolves inertResult so the wait fails instead of stranding. beginWait refuses (token 0) when dead/terminal. - all four delayed completion sites route their native work through the gate: 'OCC export completion' (exporter_step_stub), 'OCC model completion' (oce_plugin_stub — the MEMFS cache write moves inside the gate too), 'ngspice request completion' and 'ngspice vector completion' (sharedspice_client — every HEAP32/HEAPF64/malloc write inside prepare, inertResult 1 = transport error). Every wxWasmBeginWait caller in the stubs bails on token <= 0. - deliberately NOT ported from codex: ownerModule, enqueueNativeCompletion, executionBarrier, the byte-credit native-entry FIFO — completions are one-shot per wait token and stream volume is bounded at the E-6 transport credit window. Cross-refs logged for group M (M-2/M-6/M-8). E-5 (re-implemented; codex shape kept, owner APIs replaced with the E-8 gate): js_ngspice_install_events binds the handler to the EXACT installing module (handler.__pcbjamNgspiceOwnerModule stamp; presence is not identity), re-installation replaces a foreign module's handler, a superseded handler disarms itself, native entry goes through installingModule._malloc/ ._pcbjam_ngspice_event (never lexical Module), each dispatch checks canTouchNative() (loud drop on a dead/terminal module), and a trap on the per-line entry latches the terminal gate. Tests: scheduler-shim.test.ts +7 (gate happy/stale/dead/terminal/cross-realm/ js-bug/beginWait-refusal). e2e specs updated from the codex line: occ-export decode-fault recovery (real onmessageerror transition via failDecode, J-4), ngspice-probe direct-service coverage, eeschema-sim rewritten onto the E-7 applied-generation receipt (codex's executionBarrier await replaced with a pendingWaits('ngspice') drain poll — the JSPI-line equivalent). Also bumps the kicad submodule to the E-7/E-9 commit (dd5751038f7). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:03:16 +02:00
if( !sched || !sched.canTouchNative || !sched.canTouchNative() ) {
// E-8/M-2: a dead or terminal instance takes no native entry; the
// drop is loud, never silent.
console.warn( '[sharedspice_client] dropping ngspice event for a '
+ 'dead/terminal module' );
return;
}
findings(E-10..E-22): fix the defects a code review found in the E-1..E-9 work A review of the group-E fixes found 13 further defects; ten were introduced by those fixes, two pre-existed and were merely relocated, one is deferred. Services / transport E-10 retireWorker synthesized no bg/exit frame, so sharedspice's s_bgRunning mirror stayed latched true after a mid-run worker death: Run stayed disabled and the promised fresh-worker restart was unreachable for the whole session. Retirement now dispatches a synthetic controlled-exit straight to the installed handler (never through dispatchEvt — a fabricated frame must not touch the credit ledger). Driving the repro exposed two further defects, both fixed here: a replacement worker trapped on pre-init engine reads, and the rerun's cm_input_path/circ hit that uninitialized engine before KiCad's validate() re-init (the native flow assumes a crashed engine survives in-process — true for the dll, false for a dead worker). Reads now answer their empty shapes pre-init, writes lazy-init, and init is idempotent per worker engine. E-19 dispatchEvt acked only AFTER handler(evt) returned, and the sharedspice client deliberately rethrows non-trap errors — so each throw leaked one unit of the 64-frame credit window until the stream died with a misattributed "transport exceeded". The ack moves to a finally in both service copies; the throw still propagates (the trap machinery needs it). E-20 the oversize-line path promises to transfer the accepted prefix, but with the window full that flush only DEFERS, and stopEventStream wiped the deferred queue — losing the diagnostics that explain the failure. The terminal notice now carries them as pendingEvents; both hosts deliver them in order, unacked (the fatal frame is outside the credit protocol). E-21 the 30s prefetch deadline discarded every model already collected and reported nothing. A caller-owned progress sink ships the partials and the omission reaches the export report. (Awaiting the aborted collection was rejected: an in-flight source fetch is not abortable — E-4's original disease.) Plus a serving-candidate memo, so a .wrl ref served by its .step fallback stops re-probing the miss on every export. Scheduler E-14 _terminalizeNativeTrap classified by message substring, so any plain JS error QUOTING 'Aborted(' or 'out of bounds' permanently bricked a healthy instance. Now structural only: instanceof RuntimeError plus a duck-typed name check (verified in this build's glue that abort() throws a genuine RuntimeError both pre- and post-runtime-init). Module.onAbort now latches the gate — the authoritative notification, previously ignored. E-15 the shim half: _pumpResume gates on terminal (catching wakes already queued at latch time) and resolveWait refuses on terminal WITHOUT consuming the entry, so a frame stays visibly parked rather than resuming inside a trapped module. E-16 the E-5 handler read the realm-global scheduler at dispatch instead of its installing module's; also frees the per-line buffer on the non-trap rethrow path. E-11 get_vec trusted the worker's res.length over the transferred arrays. Observed death shape: a 4 GiB std::vector threw an unhandled std::length_error that exited the editor's main loop. Now clamped, with the buffers freed on every failure path. Guardrails (replacing two deferred refactors: e2e→production-code injection and collapsing the four copies of the worker-lifecycle machinery) E-18 the source contract asserted comment-string counts — rewording failed CI while moving a guard outside its #ifdef passed. It now parses the #ifdef regions and asserts on code. service-stub-parity.ts pins what the four lifecycle copies must share: credit-window equality parsed from source, the finally-ack, boot deadlines, terminal-notice consumption. The transport numbers are now single-sourced from the worker. CI actually runs the gates: the web/standalone vitest suites (which had NEVER run in CI), the reducer, the source contract and the parity tool — with a NON_PLAYWRIGHT_GATES check so deleting a step re-fails the lint. E-22 the e2e occ stub's 60s boot watchdog, deleted in a66e109, is restored in the ngspice-stub shape with a wedgeNextBoot() repro hook. Every behavioral fix has red-then-green evidence (the reds were captured first). E-17 (a stale RUNNING cross-stamping the next run's generation under E-6's transport deferral) is DEFERRED with its analysis recorded — a real fix needs run identity on the bg frames. Test hygiene: the dwell lint now requires the mandated ": <why>" and all 47 bare markers carry their reason; three export-report dwells became modal-lease polls; exact-ledger assertions became relative deltas; the dead data-wx-dom-id branch, an unused fault hook and unused receipt plumbing are gone; abort scans, wx dialog drivers, the sim harness and the vitest FakeWorker are each one copy now. Bumps kicad and wxwidgets to their findings-group-e tips. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-27 12:27:12 +02:00
// E-16: a plain-JS throw between the malloc and the native entry
// leaks the line buffer — track it so the non-trap rethrow path can
// free it (never free on the trap path: freeing re-enters a trapped
// module).
let pendingText = 0;
const call = ( kind, text, a, b ) => {
let p = 0;
if( text != null ) {
const n = lengthBytesUTF8( text ) + 1;
findings(E-5,E-6): validation-round fixes — live e2e falsified two ported shapes E-5: the module-identity bridge called installingModule._malloc, but this build exposes _malloc only as a bare glue-closure export (Module._malloc is absent) — every char/stat event entry threw TypeError, which also starved the E-6 credit window (thrown dispatches never acked) and wedged the queued bg-finished frame behind them. The bridge now uses the bare closure exports (identity is still exact: the EM_JS body IS the installing module's closure; the __ngspiceOnEvent self-disarm covers supersession). E-6 (codex reference design corrected — its validation matrix never ran): a FULL credit window was terminal (stopEventStream at 64 in-flight frames). Under live e2e that killed a real simulation: bg-thread emissions proxy one per task, so each line ships as its own frame and a normal transient outruns a busy main thread. A full window now DEFERS into a bounded FIFO (512 events / 4 MiB) drained in order as acks free credit; only true overload or an invalid ack is terminal. Retention stays bounded (8 MiB in flight + 4 MiB deferred + 1 MiB open batch). And the service/harness mirror queue now acks at ENQUEUE — placing a frame in the bounded pre-handler queue is taking ownership; without that, a stream starting before the C++ handler installs (the ngspice-probe page) starves the worker window forever. Test updates: worker-batch reducer — new "a full credit window defers and drains in order, never terminal" case pinning the regression; the storm case now proves the deferred caps are the terminal edge. board-ready.ts gains the owner-free openBoardProgrammatically (codex helper the ported occ-export spec needs; the barrier-based waitForUiBoardReady was NOT taken). occ-export.spec: domId is optional on this line's registry (coordinate fallback is the supported path). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 17:53:11 +02:00
// Bare closure exports: this EM_JS body is compiled into the
// installing module's glue closure, so _malloc/stringToUTF8
// ARE that exact module's (Module._malloc is not populated in
// this build). The identity guarantee is the handler capture
// plus the __ngspiceOnEvent self-disarm above.
p = _malloc( n );
stringToUTF8( text, p, n );
}
findings(E-10..E-22): fix the defects a code review found in the E-1..E-9 work A review of the group-E fixes found 13 further defects; ten were introduced by those fixes, two pre-existed and were merely relocated, one is deferred. Services / transport E-10 retireWorker synthesized no bg/exit frame, so sharedspice's s_bgRunning mirror stayed latched true after a mid-run worker death: Run stayed disabled and the promised fresh-worker restart was unreachable for the whole session. Retirement now dispatches a synthetic controlled-exit straight to the installed handler (never through dispatchEvt — a fabricated frame must not touch the credit ledger). Driving the repro exposed two further defects, both fixed here: a replacement worker trapped on pre-init engine reads, and the rerun's cm_input_path/circ hit that uninitialized engine before KiCad's validate() re-init (the native flow assumes a crashed engine survives in-process — true for the dll, false for a dead worker). Reads now answer their empty shapes pre-init, writes lazy-init, and init is idempotent per worker engine. E-19 dispatchEvt acked only AFTER handler(evt) returned, and the sharedspice client deliberately rethrows non-trap errors — so each throw leaked one unit of the 64-frame credit window until the stream died with a misattributed "transport exceeded". The ack moves to a finally in both service copies; the throw still propagates (the trap machinery needs it). E-20 the oversize-line path promises to transfer the accepted prefix, but with the window full that flush only DEFERS, and stopEventStream wiped the deferred queue — losing the diagnostics that explain the failure. The terminal notice now carries them as pendingEvents; both hosts deliver them in order, unacked (the fatal frame is outside the credit protocol). E-21 the 30s prefetch deadline discarded every model already collected and reported nothing. A caller-owned progress sink ships the partials and the omission reaches the export report. (Awaiting the aborted collection was rejected: an in-flight source fetch is not abortable — E-4's original disease.) Plus a serving-candidate memo, so a .wrl ref served by its .step fallback stops re-probing the miss on every export. Scheduler E-14 _terminalizeNativeTrap classified by message substring, so any plain JS error QUOTING 'Aborted(' or 'out of bounds' permanently bricked a healthy instance. Now structural only: instanceof RuntimeError plus a duck-typed name check (verified in this build's glue that abort() throws a genuine RuntimeError both pre- and post-runtime-init). Module.onAbort now latches the gate — the authoritative notification, previously ignored. E-15 the shim half: _pumpResume gates on terminal (catching wakes already queued at latch time) and resolveWait refuses on terminal WITHOUT consuming the entry, so a frame stays visibly parked rather than resuming inside a trapped module. E-16 the E-5 handler read the realm-global scheduler at dispatch instead of its installing module's; also frees the per-line buffer on the non-trap rethrow path. E-11 get_vec trusted the worker's res.length over the transferred arrays. Observed death shape: a 4 GiB std::vector threw an unhandled std::length_error that exited the editor's main loop. Now clamped, with the buffers freed on every failure path. Guardrails (replacing two deferred refactors: e2e→production-code injection and collapsing the four copies of the worker-lifecycle machinery) E-18 the source contract asserted comment-string counts — rewording failed CI while moving a guard outside its #ifdef passed. It now parses the #ifdef regions and asserts on code. service-stub-parity.ts pins what the four lifecycle copies must share: credit-window equality parsed from source, the finally-ack, boot deadlines, terminal-notice consumption. The transport numbers are now single-sourced from the worker. CI actually runs the gates: the web/standalone vitest suites (which had NEVER run in CI), the reducer, the source contract and the parity tool — with a NON_PLAYWRIGHT_GATES check so deleting a step re-fails the lint. E-22 the e2e occ stub's 60s boot watchdog, deleted in a66e109, is restored in the ngspice-stub shape with a wedgeNextBoot() repro hook. Every behavioral fix has red-then-green evidence (the reds were captured first). E-17 (a stale RUNNING cross-stamping the next run's generation under E-6's transport deferral) is DEFERRED with its analysis recorded — a real fix needs run identity on the bg frames. Test hygiene: the dwell lint now requires the mandated ": <why>" and all 47 bare markers carry their reason; three export-report dwells became modal-lease polls; exact-ledger assertions became relative deltas; the dead data-wx-dom-id branch, an unused fault hook and unused receipt plumbing are gone; abort scans, wx dialog drivers, the sim harness and the vitest FakeWorker are each one copy now. Bumps kicad and wxwidgets to their findings-group-e tips. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-27 12:27:12 +02:00
pendingText = p;
findings(E-5,E-8,E-9): module-identity ngspice events + runWaitCompletion admission gate E-8 (re-implemented for JSPI — the codex gate is entangled with the dropped execution owner; under JSPI a fresh non-suspending JS→wasm entry while another activation is suspended is structurally safe on its own stack, so the admission boundary for worker completions is liveness + trap state, not execution ownership): - jspi-scheduler.js grows `terminal` (trapped instance; distinct from `dead`), canTouchNative(), _terminalizeNativeTrap() (WebAssembly.RuntimeError + cross-realm string classification), and runWaitCompletion(site, token, prepare, inertResult): prepare runs immediately and owns ALL native work; stale tokens and dead/terminal instances drop loudly without resolving (resolving would resume the parked frame inside the damaged module); a trap latches terminal; a plain JS bug resolves inertResult so the wait fails instead of stranding. beginWait refuses (token 0) when dead/terminal. - all four delayed completion sites route their native work through the gate: 'OCC export completion' (exporter_step_stub), 'OCC model completion' (oce_plugin_stub — the MEMFS cache write moves inside the gate too), 'ngspice request completion' and 'ngspice vector completion' (sharedspice_client — every HEAP32/HEAPF64/malloc write inside prepare, inertResult 1 = transport error). Every wxWasmBeginWait caller in the stubs bails on token <= 0. - deliberately NOT ported from codex: ownerModule, enqueueNativeCompletion, executionBarrier, the byte-credit native-entry FIFO — completions are one-shot per wait token and stream volume is bounded at the E-6 transport credit window. Cross-refs logged for group M (M-2/M-6/M-8). E-5 (re-implemented; codex shape kept, owner APIs replaced with the E-8 gate): js_ngspice_install_events binds the handler to the EXACT installing module (handler.__pcbjamNgspiceOwnerModule stamp; presence is not identity), re-installation replaces a foreign module's handler, a superseded handler disarms itself, native entry goes through installingModule._malloc/ ._pcbjam_ngspice_event (never lexical Module), each dispatch checks canTouchNative() (loud drop on a dead/terminal module), and a trap on the per-line entry latches the terminal gate. Tests: scheduler-shim.test.ts +7 (gate happy/stale/dead/terminal/cross-realm/ js-bug/beginWait-refusal). e2e specs updated from the codex line: occ-export decode-fault recovery (real onmessageerror transition via failDecode, J-4), ngspice-probe direct-service coverage, eeschema-sim rewritten onto the E-7 applied-generation receipt (codex's executionBarrier await replaced with a pendingWaits('ngspice') drain poll — the JSPI-line equivalent). Also bumps the kicad submodule to the E-7/E-9 commit (dd5751038f7). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:03:16 +02:00
installingModule._pcbjam_ngspice_event( kind, p, a | 0, b | 0 );
findings(E-10..E-22): fix the defects a code review found in the E-1..E-9 work A review of the group-E fixes found 13 further defects; ten were introduced by those fixes, two pre-existed and were merely relocated, one is deferred. Services / transport E-10 retireWorker synthesized no bg/exit frame, so sharedspice's s_bgRunning mirror stayed latched true after a mid-run worker death: Run stayed disabled and the promised fresh-worker restart was unreachable for the whole session. Retirement now dispatches a synthetic controlled-exit straight to the installed handler (never through dispatchEvt — a fabricated frame must not touch the credit ledger). Driving the repro exposed two further defects, both fixed here: a replacement worker trapped on pre-init engine reads, and the rerun's cm_input_path/circ hit that uninitialized engine before KiCad's validate() re-init (the native flow assumes a crashed engine survives in-process — true for the dll, false for a dead worker). Reads now answer their empty shapes pre-init, writes lazy-init, and init is idempotent per worker engine. E-19 dispatchEvt acked only AFTER handler(evt) returned, and the sharedspice client deliberately rethrows non-trap errors — so each throw leaked one unit of the 64-frame credit window until the stream died with a misattributed "transport exceeded". The ack moves to a finally in both service copies; the throw still propagates (the trap machinery needs it). E-20 the oversize-line path promises to transfer the accepted prefix, but with the window full that flush only DEFERS, and stopEventStream wiped the deferred queue — losing the diagnostics that explain the failure. The terminal notice now carries them as pendingEvents; both hosts deliver them in order, unacked (the fatal frame is outside the credit protocol). E-21 the 30s prefetch deadline discarded every model already collected and reported nothing. A caller-owned progress sink ships the partials and the omission reaches the export report. (Awaiting the aborted collection was rejected: an in-flight source fetch is not abortable — E-4's original disease.) Plus a serving-candidate memo, so a .wrl ref served by its .step fallback stops re-probing the miss on every export. Scheduler E-14 _terminalizeNativeTrap classified by message substring, so any plain JS error QUOTING 'Aborted(' or 'out of bounds' permanently bricked a healthy instance. Now structural only: instanceof RuntimeError plus a duck-typed name check (verified in this build's glue that abort() throws a genuine RuntimeError both pre- and post-runtime-init). Module.onAbort now latches the gate — the authoritative notification, previously ignored. E-15 the shim half: _pumpResume gates on terminal (catching wakes already queued at latch time) and resolveWait refuses on terminal WITHOUT consuming the entry, so a frame stays visibly parked rather than resuming inside a trapped module. E-16 the E-5 handler read the realm-global scheduler at dispatch instead of its installing module's; also frees the per-line buffer on the non-trap rethrow path. E-11 get_vec trusted the worker's res.length over the transferred arrays. Observed death shape: a 4 GiB std::vector threw an unhandled std::length_error that exited the editor's main loop. Now clamped, with the buffers freed on every failure path. Guardrails (replacing two deferred refactors: e2e→production-code injection and collapsing the four copies of the worker-lifecycle machinery) E-18 the source contract asserted comment-string counts — rewording failed CI while moving a guard outside its #ifdef passed. It now parses the #ifdef regions and asserts on code. service-stub-parity.ts pins what the four lifecycle copies must share: credit-window equality parsed from source, the finally-ack, boot deadlines, terminal-notice consumption. The transport numbers are now single-sourced from the worker. CI actually runs the gates: the web/standalone vitest suites (which had NEVER run in CI), the reducer, the source contract and the parity tool — with a NON_PLAYWRIGHT_GATES check so deleting a step re-fails the lint. E-22 the e2e occ stub's 60s boot watchdog, deleted in a66e109, is restored in the ngspice-stub shape with a wedgeNextBoot() repro hook. Every behavioral fix has red-then-green evidence (the reds were captured first). E-17 (a stale RUNNING cross-stamping the next run's generation under E-6's transport deferral) is DEFERRED with its analysis recorded — a real fix needs run identity on the bg frames. Test hygiene: the dwell lint now requires the mandated ": <why>" and all 47 bare markers carry their reason; three export-report dwells became modal-lease polls; exact-ledger assertions became relative deltas; the dead data-wx-dom-id branch, an unused fault hook and unused receipt plumbing are gone; abort scans, wx dialog drivers, the sim harness and the vitest FakeWorker are each one copy now. Bumps kicad and wxwidgets to their findings-group-e tips. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-27 12:27:12 +02:00
pendingText = 0; // the native entry freed it
};
findings(E-5,E-8,E-9): module-identity ngspice events + runWaitCompletion admission gate E-8 (re-implemented for JSPI — the codex gate is entangled with the dropped execution owner; under JSPI a fresh non-suspending JS→wasm entry while another activation is suspended is structurally safe on its own stack, so the admission boundary for worker completions is liveness + trap state, not execution ownership): - jspi-scheduler.js grows `terminal` (trapped instance; distinct from `dead`), canTouchNative(), _terminalizeNativeTrap() (WebAssembly.RuntimeError + cross-realm string classification), and runWaitCompletion(site, token, prepare, inertResult): prepare runs immediately and owns ALL native work; stale tokens and dead/terminal instances drop loudly without resolving (resolving would resume the parked frame inside the damaged module); a trap latches terminal; a plain JS bug resolves inertResult so the wait fails instead of stranding. beginWait refuses (token 0) when dead/terminal. - all four delayed completion sites route their native work through the gate: 'OCC export completion' (exporter_step_stub), 'OCC model completion' (oce_plugin_stub — the MEMFS cache write moves inside the gate too), 'ngspice request completion' and 'ngspice vector completion' (sharedspice_client — every HEAP32/HEAPF64/malloc write inside prepare, inertResult 1 = transport error). Every wxWasmBeginWait caller in the stubs bails on token <= 0. - deliberately NOT ported from codex: ownerModule, enqueueNativeCompletion, executionBarrier, the byte-credit native-entry FIFO — completions are one-shot per wait token and stream volume is bounded at the E-6 transport credit window. Cross-refs logged for group M (M-2/M-6/M-8). E-5 (re-implemented; codex shape kept, owner APIs replaced with the E-8 gate): js_ngspice_install_events binds the handler to the EXACT installing module (handler.__pcbjamNgspiceOwnerModule stamp; presence is not identity), re-installation replaces a foreign module's handler, a superseded handler disarms itself, native entry goes through installingModule._malloc/ ._pcbjam_ngspice_event (never lexical Module), each dispatch checks canTouchNative() (loud drop on a dead/terminal module), and a trap on the per-line entry latches the terminal gate. Tests: scheduler-shim.test.ts +7 (gate happy/stale/dead/terminal/cross-realm/ js-bug/beginWait-refusal). e2e specs updated from the codex line: occ-export decode-fault recovery (real onmessageerror transition via failDecode, J-4), ngspice-probe direct-service coverage, eeschema-sim rewritten onto the E-7 applied-generation receipt (codex's executionBarrier await replaced with a pendingWaits('ngspice') drain poll — the JSPI-line equivalent). Also bumps the kicad submodule to the E-7/E-9 commit (dd5751038f7). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:03:16 +02:00
try {
if( evt.kind === 'char' || evt.kind === 'stat' ) {
for( const line of evt.lines || [] )
call( evt.kind === 'char' ? 0 : 1, line, 0, 0 );
} else if( evt.kind === 'bg' ) {
call( 2, null, evt.finished ? 1 : 0, 0 );
} else if( evt.kind === 'exit' ) {
call( 3, null, evt.status | 0,
( evt.immediate ? 1 : 0 ) | ( evt.quit ? 2 : 0 ) );
}
} catch( e ) {
// A trap on this fresh entry poisons the instance: latch the
// terminal gate so no later completion re-enters it.
if( !sched._terminalizeNativeTrap
findings(E-10..E-22): fix the defects a code review found in the E-1..E-9 work A review of the group-E fixes found 13 further defects; ten were introduced by those fixes, two pre-existed and were merely relocated, one is deferred. Services / transport E-10 retireWorker synthesized no bg/exit frame, so sharedspice's s_bgRunning mirror stayed latched true after a mid-run worker death: Run stayed disabled and the promised fresh-worker restart was unreachable for the whole session. Retirement now dispatches a synthetic controlled-exit straight to the installed handler (never through dispatchEvt — a fabricated frame must not touch the credit ledger). Driving the repro exposed two further defects, both fixed here: a replacement worker trapped on pre-init engine reads, and the rerun's cm_input_path/circ hit that uninitialized engine before KiCad's validate() re-init (the native flow assumes a crashed engine survives in-process — true for the dll, false for a dead worker). Reads now answer their empty shapes pre-init, writes lazy-init, and init is idempotent per worker engine. E-19 dispatchEvt acked only AFTER handler(evt) returned, and the sharedspice client deliberately rethrows non-trap errors — so each throw leaked one unit of the 64-frame credit window until the stream died with a misattributed "transport exceeded". The ack moves to a finally in both service copies; the throw still propagates (the trap machinery needs it). E-20 the oversize-line path promises to transfer the accepted prefix, but with the window full that flush only DEFERS, and stopEventStream wiped the deferred queue — losing the diagnostics that explain the failure. The terminal notice now carries them as pendingEvents; both hosts deliver them in order, unacked (the fatal frame is outside the credit protocol). E-21 the 30s prefetch deadline discarded every model already collected and reported nothing. A caller-owned progress sink ships the partials and the omission reaches the export report. (Awaiting the aborted collection was rejected: an in-flight source fetch is not abortable — E-4's original disease.) Plus a serving-candidate memo, so a .wrl ref served by its .step fallback stops re-probing the miss on every export. Scheduler E-14 _terminalizeNativeTrap classified by message substring, so any plain JS error QUOTING 'Aborted(' or 'out of bounds' permanently bricked a healthy instance. Now structural only: instanceof RuntimeError plus a duck-typed name check (verified in this build's glue that abort() throws a genuine RuntimeError both pre- and post-runtime-init). Module.onAbort now latches the gate — the authoritative notification, previously ignored. E-15 the shim half: _pumpResume gates on terminal (catching wakes already queued at latch time) and resolveWait refuses on terminal WITHOUT consuming the entry, so a frame stays visibly parked rather than resuming inside a trapped module. E-16 the E-5 handler read the realm-global scheduler at dispatch instead of its installing module's; also frees the per-line buffer on the non-trap rethrow path. E-11 get_vec trusted the worker's res.length over the transferred arrays. Observed death shape: a 4 GiB std::vector threw an unhandled std::length_error that exited the editor's main loop. Now clamped, with the buffers freed on every failure path. Guardrails (replacing two deferred refactors: e2e→production-code injection and collapsing the four copies of the worker-lifecycle machinery) E-18 the source contract asserted comment-string counts — rewording failed CI while moving a guard outside its #ifdef passed. It now parses the #ifdef regions and asserts on code. service-stub-parity.ts pins what the four lifecycle copies must share: credit-window equality parsed from source, the finally-ack, boot deadlines, terminal-notice consumption. The transport numbers are now single-sourced from the worker. CI actually runs the gates: the web/standalone vitest suites (which had NEVER run in CI), the reducer, the source contract and the parity tool — with a NON_PLAYWRIGHT_GATES check so deleting a step re-fails the lint. E-22 the e2e occ stub's 60s boot watchdog, deleted in a66e109, is restored in the ngspice-stub shape with a wedgeNextBoot() repro hook. Every behavioral fix has red-then-green evidence (the reds were captured first). E-17 (a stale RUNNING cross-stamping the next run's generation under E-6's transport deferral) is DEFERRED with its analysis recorded — a real fix needs run identity on the bg frames. Test hygiene: the dwell lint now requires the mandated ": <why>" and all 47 bare markers carry their reason; three export-report dwells became modal-lease polls; exact-ledger assertions became relative deltas; the dead data-wx-dom-id branch, an unused fault hook and unused receipt plumbing are gone; abort scans, wx dialog drivers, the sim harness and the vitest FakeWorker are each one copy now. Bumps kicad and wxwidgets to their findings-group-e tips. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-27 12:27:12 +02:00
|| !sched._terminalizeNativeTrap( 'ngspice event entry', e ) ) {
if( pendingText )
_free( pendingText );
findings(E-5,E-8,E-9): module-identity ngspice events + runWaitCompletion admission gate E-8 (re-implemented for JSPI — the codex gate is entangled with the dropped execution owner; under JSPI a fresh non-suspending JS→wasm entry while another activation is suspended is structurally safe on its own stack, so the admission boundary for worker completions is liveness + trap state, not execution ownership): - jspi-scheduler.js grows `terminal` (trapped instance; distinct from `dead`), canTouchNative(), _terminalizeNativeTrap() (WebAssembly.RuntimeError + cross-realm string classification), and runWaitCompletion(site, token, prepare, inertResult): prepare runs immediately and owns ALL native work; stale tokens and dead/terminal instances drop loudly without resolving (resolving would resume the parked frame inside the damaged module); a trap latches terminal; a plain JS bug resolves inertResult so the wait fails instead of stranding. beginWait refuses (token 0) when dead/terminal. - all four delayed completion sites route their native work through the gate: 'OCC export completion' (exporter_step_stub), 'OCC model completion' (oce_plugin_stub — the MEMFS cache write moves inside the gate too), 'ngspice request completion' and 'ngspice vector completion' (sharedspice_client — every HEAP32/HEAPF64/malloc write inside prepare, inertResult 1 = transport error). Every wxWasmBeginWait caller in the stubs bails on token <= 0. - deliberately NOT ported from codex: ownerModule, enqueueNativeCompletion, executionBarrier, the byte-credit native-entry FIFO — completions are one-shot per wait token and stream volume is bounded at the E-6 transport credit window. Cross-refs logged for group M (M-2/M-6/M-8). E-5 (re-implemented; codex shape kept, owner APIs replaced with the E-8 gate): js_ngspice_install_events binds the handler to the EXACT installing module (handler.__pcbjamNgspiceOwnerModule stamp; presence is not identity), re-installation replaces a foreign module's handler, a superseded handler disarms itself, native entry goes through installingModule._malloc/ ._pcbjam_ngspice_event (never lexical Module), each dispatch checks canTouchNative() (loud drop on a dead/terminal module), and a trap on the per-line entry latches the terminal gate. Tests: scheduler-shim.test.ts +7 (gate happy/stale/dead/terminal/cross-realm/ js-bug/beginWait-refusal). e2e specs updated from the codex line: occ-export decode-fault recovery (real onmessageerror transition via failDecode, J-4), ngspice-probe direct-service coverage, eeschema-sim rewritten onto the E-7 applied-generation receipt (codex's executionBarrier await replaced with a pendingWaits('ngspice') drain poll — the JSPI-line equivalent). Also bumps the kicad submodule to the E-7/E-9 commit (dd5751038f7). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:03:16 +02:00
throw e;
findings(E-10..E-22): fix the defects a code review found in the E-1..E-9 work A review of the group-E fixes found 13 further defects; ten were introduced by those fixes, two pre-existed and were merely relocated, one is deferred. Services / transport E-10 retireWorker synthesized no bg/exit frame, so sharedspice's s_bgRunning mirror stayed latched true after a mid-run worker death: Run stayed disabled and the promised fresh-worker restart was unreachable for the whole session. Retirement now dispatches a synthetic controlled-exit straight to the installed handler (never through dispatchEvt — a fabricated frame must not touch the credit ledger). Driving the repro exposed two further defects, both fixed here: a replacement worker trapped on pre-init engine reads, and the rerun's cm_input_path/circ hit that uninitialized engine before KiCad's validate() re-init (the native flow assumes a crashed engine survives in-process — true for the dll, false for a dead worker). Reads now answer their empty shapes pre-init, writes lazy-init, and init is idempotent per worker engine. E-19 dispatchEvt acked only AFTER handler(evt) returned, and the sharedspice client deliberately rethrows non-trap errors — so each throw leaked one unit of the 64-frame credit window until the stream died with a misattributed "transport exceeded". The ack moves to a finally in both service copies; the throw still propagates (the trap machinery needs it). E-20 the oversize-line path promises to transfer the accepted prefix, but with the window full that flush only DEFERS, and stopEventStream wiped the deferred queue — losing the diagnostics that explain the failure. The terminal notice now carries them as pendingEvents; both hosts deliver them in order, unacked (the fatal frame is outside the credit protocol). E-21 the 30s prefetch deadline discarded every model already collected and reported nothing. A caller-owned progress sink ships the partials and the omission reaches the export report. (Awaiting the aborted collection was rejected: an in-flight source fetch is not abortable — E-4's original disease.) Plus a serving-candidate memo, so a .wrl ref served by its .step fallback stops re-probing the miss on every export. Scheduler E-14 _terminalizeNativeTrap classified by message substring, so any plain JS error QUOTING 'Aborted(' or 'out of bounds' permanently bricked a healthy instance. Now structural only: instanceof RuntimeError plus a duck-typed name check (verified in this build's glue that abort() throws a genuine RuntimeError both pre- and post-runtime-init). Module.onAbort now latches the gate — the authoritative notification, previously ignored. E-15 the shim half: _pumpResume gates on terminal (catching wakes already queued at latch time) and resolveWait refuses on terminal WITHOUT consuming the entry, so a frame stays visibly parked rather than resuming inside a trapped module. E-16 the E-5 handler read the realm-global scheduler at dispatch instead of its installing module's; also frees the per-line buffer on the non-trap rethrow path. E-11 get_vec trusted the worker's res.length over the transferred arrays. Observed death shape: a 4 GiB std::vector threw an unhandled std::length_error that exited the editor's main loop. Now clamped, with the buffers freed on every failure path. Guardrails (replacing two deferred refactors: e2e→production-code injection and collapsing the four copies of the worker-lifecycle machinery) E-18 the source contract asserted comment-string counts — rewording failed CI while moving a guard outside its #ifdef passed. It now parses the #ifdef regions and asserts on code. service-stub-parity.ts pins what the four lifecycle copies must share: credit-window equality parsed from source, the finally-ack, boot deadlines, terminal-notice consumption. The transport numbers are now single-sourced from the worker. CI actually runs the gates: the web/standalone vitest suites (which had NEVER run in CI), the reducer, the source contract and the parity tool — with a NON_PLAYWRIGHT_GATES check so deleting a step re-fails the lint. E-22 the e2e occ stub's 60s boot watchdog, deleted in a66e109, is restored in the ngspice-stub shape with a wedgeNextBoot() repro hook. Every behavioral fix has red-then-green evidence (the reds were captured first). E-17 (a stale RUNNING cross-stamping the next run's generation under E-6's transport deferral) is DEFERRED with its analysis recorded — a real fix needs run identity on the bg frames. Test hygiene: the dwell lint now requires the mandated ": <why>" and all 47 bare markers carry their reason; three export-report dwells became modal-lease polls; exact-ledger assertions became relative deltas; the dead data-wx-dom-id branch, an unused fault hook and unused receipt plumbing are gone; abort scans, wx dialog drivers, the sim harness and the vitest FakeWorker are each one copy now. Bumps kicad and wxwidgets to their findings-group-e tips. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-27 12:27:12 +02:00
}
}
};
findings(E-5,E-8,E-9): module-identity ngspice events + runWaitCompletion admission gate E-8 (re-implemented for JSPI — the codex gate is entangled with the dropped execution owner; under JSPI a fresh non-suspending JS→wasm entry while another activation is suspended is structurally safe on its own stack, so the admission boundary for worker completions is liveness + trap state, not execution ownership): - jspi-scheduler.js grows `terminal` (trapped instance; distinct from `dead`), canTouchNative(), _terminalizeNativeTrap() (WebAssembly.RuntimeError + cross-realm string classification), and runWaitCompletion(site, token, prepare, inertResult): prepare runs immediately and owns ALL native work; stale tokens and dead/terminal instances drop loudly without resolving (resolving would resume the parked frame inside the damaged module); a trap latches terminal; a plain JS bug resolves inertResult so the wait fails instead of stranding. beginWait refuses (token 0) when dead/terminal. - all four delayed completion sites route their native work through the gate: 'OCC export completion' (exporter_step_stub), 'OCC model completion' (oce_plugin_stub — the MEMFS cache write moves inside the gate too), 'ngspice request completion' and 'ngspice vector completion' (sharedspice_client — every HEAP32/HEAPF64/malloc write inside prepare, inertResult 1 = transport error). Every wxWasmBeginWait caller in the stubs bails on token <= 0. - deliberately NOT ported from codex: ownerModule, enqueueNativeCompletion, executionBarrier, the byte-credit native-entry FIFO — completions are one-shot per wait token and stream volume is bounded at the E-6 transport credit window. Cross-refs logged for group M (M-2/M-6/M-8). E-5 (re-implemented; codex shape kept, owner APIs replaced with the E-8 gate): js_ngspice_install_events binds the handler to the EXACT installing module (handler.__pcbjamNgspiceOwnerModule stamp; presence is not identity), re-installation replaces a foreign module's handler, a superseded handler disarms itself, native entry goes through installingModule._malloc/ ._pcbjam_ngspice_event (never lexical Module), each dispatch checks canTouchNative() (loud drop on a dead/terminal module), and a trap on the per-line entry latches the terminal gate. Tests: scheduler-shim.test.ts +7 (gate happy/stale/dead/terminal/cross-realm/ js-bug/beginWait-refusal). e2e specs updated from the codex line: occ-export decode-fault recovery (real onmessageerror transition via failDecode, J-4), ngspice-probe direct-service coverage, eeschema-sim rewritten onto the E-7 applied-generation receipt (codex's executionBarrier await replaced with a pendingWaits('ngspice') drain poll — the JSPI-line equivalent). Also bumps the kicad submodule to the E-7/E-9 commit (dd5751038f7). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:03:16 +02:00
handler.__pcbjamNgspiceOwnerModule = installingModule;
globalThis.__ngspiceOnEvent = handler;
} );
// clang-format on
// -------------------------------------------------------------------------
// Client state
// -------------------------------------------------------------------------
namespace
{
SendChar* s_sendChar = nullptr;
SendStat* s_sendStat = nullptr;
ControlledExit* s_controlledExit = nullptr;
BGThreadRunning* s_bgThreadRunning = nullptr;
void* s_user = nullptr;
// Mirror of the service's bg-run state (see header comment).
std::atomic<bool> s_bgRunning{ false };
json rpc( const json& aReq )
{
const int token = wxWasmBeginWait( "ngspice" );
findings(E-5,E-8,E-9): module-identity ngspice events + runWaitCompletion admission gate E-8 (re-implemented for JSPI — the codex gate is entangled with the dropped execution owner; under JSPI a fresh non-suspending JS→wasm entry while another activation is suspended is structurally safe on its own stack, so the admission boundary for worker completions is liveness + trap state, not execution ownership): - jspi-scheduler.js grows `terminal` (trapped instance; distinct from `dead`), canTouchNative(), _terminalizeNativeTrap() (WebAssembly.RuntimeError + cross-realm string classification), and runWaitCompletion(site, token, prepare, inertResult): prepare runs immediately and owns ALL native work; stale tokens and dead/terminal instances drop loudly without resolving (resolving would resume the parked frame inside the damaged module); a trap latches terminal; a plain JS bug resolves inertResult so the wait fails instead of stranding. beginWait refuses (token 0) when dead/terminal. - all four delayed completion sites route their native work through the gate: 'OCC export completion' (exporter_step_stub), 'OCC model completion' (oce_plugin_stub — the MEMFS cache write moves inside the gate too), 'ngspice request completion' and 'ngspice vector completion' (sharedspice_client — every HEAP32/HEAPF64/malloc write inside prepare, inertResult 1 = transport error). Every wxWasmBeginWait caller in the stubs bails on token <= 0. - deliberately NOT ported from codex: ownerModule, enqueueNativeCompletion, executionBarrier, the byte-credit native-entry FIFO — completions are one-shot per wait token and stream volume is bounded at the E-6 transport credit window. Cross-refs logged for group M (M-2/M-6/M-8). E-5 (re-implemented; codex shape kept, owner APIs replaced with the E-8 gate): js_ngspice_install_events binds the handler to the EXACT installing module (handler.__pcbjamNgspiceOwnerModule stamp; presence is not identity), re-installation replaces a foreign module's handler, a superseded handler disarms itself, native entry goes through installingModule._malloc/ ._pcbjam_ngspice_event (never lexical Module), each dispatch checks canTouchNative() (loud drop on a dead/terminal module), and a trap on the per-line entry latches the terminal gate. Tests: scheduler-shim.test.ts +7 (gate happy/stale/dead/terminal/cross-realm/ js-bug/beginWait-refusal). e2e specs updated from the codex line: occ-export decode-fault recovery (real onmessageerror transition via failDecode, J-4), ngspice-probe direct-service coverage, eeschema-sim rewritten onto the E-7 applied-generation receipt (codex's executionBarrier await replaced with a pendingWaits('ngspice') drain poll — the JSPI-line equivalent). Also bumps the kicad submodule to the E-7/E-9 commit (dd5751038f7). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:03:16 +02:00
// Token 0 = the scheduler refused the wait (dead or terminal instance):
// never start an RPC whose completion could not be admitted.
if( token <= 0 )
return json{ { "error", "wx scheduler unavailable" } };
js_ngspice_request_start( token, aReq.dump().c_str() );
// The malloc'd JSON pointer rides the wait as an int32.
char* raw = (char*) (uintptr_t) (uint32_t) wxWasmYieldUntil( token );
json res = json::parse( raw ? raw : "{}", nullptr, /* allow_exceptions */ false );
std::free( raw );
if( res.is_discarded() )
res = json::object();
if( res.contains( "error" ) )
{
fprintf( stderr, "[sharedspice_client] %s: %s\n",
aReq.value( "kind", "?" ).c_str(),
res["error"].dump().c_str() );
}
return res;
}
// Read an editor-MEMFS file; returns false if it doesn't exist.
bool readFile( const std::string& aPath, std::string* aOut )
{
FILE* fp = fopen( aPath.c_str(), "rb" );
if( !fp )
return false;
fseek( fp, 0, SEEK_END );
long size = ftell( fp );
fseek( fp, 0, SEEK_SET );
aOut->resize( size > 0 ? (size_t) size : 0 );
if( size > 0 && fread( aOut->data(), 1, (size_t) size, fp ) != (size_t) size )
{
fclose( fp );
return false;
}
fclose( fp );
return true;
}
// Extract the file path from a `.include "<path>"` / `.inc` / `.lib "<path>"
// [section]` deck line; empty if the line is not an include directive.
std::string includePathFromLine( const std::string& aLine )
{
size_t i = 0;
while( i < aLine.size() && isspace( (unsigned char) aLine[i] ) )
i++;
if( i >= aLine.size() || aLine[i] != '.' )
return std::string();
size_t wordEnd = i;
while( wordEnd < aLine.size() && !isspace( (unsigned char) aLine[wordEnd] ) )
wordEnd++;
std::string word = aLine.substr( i, wordEnd - i );
for( char& c : word )
c = (char) tolower( (unsigned char) c );
if( word != ".include" && word != ".inc" && word != ".lib" )
return std::string();
size_t p = wordEnd;
while( p < aLine.size() && isspace( (unsigned char) aLine[p] ) )
p++;
if( p >= aLine.size() )
return std::string();
if( aLine[p] == '"' || aLine[p] == '\'' )
{
char quote = aLine[p++];
size_t end = aLine.find( quote, p );
return end == std::string::npos ? std::string() : aLine.substr( p, end - p );
}
size_t end = p;
while( end < aLine.size() && !isspace( (unsigned char) aLine[end] ) )
end++;
return aLine.substr( p, end - p );
}
// Collect the deck's referenced model files (recursively — a shipped library
// may itself .include others), bounded against cycles and runaway depth.
void collectIncludeFiles( const std::vector<std::string>& aLines, json* aFiles,
std::set<std::string>* aSeen, int aDepth )
{
if( aDepth > 4 )
return;
for( const std::string& line : aLines )
{
std::string path = includePathFromLine( line );
if( path.empty() || aSeen->count( path ) )
continue;
aSeen->insert( path );
std::string text;
if( !readFile( path, &text ) )
continue; // ngspice will report the miss with its native error
aFiles->push_back( { { "path", path }, { "text", text } } );
std::vector<std::string> nested;
size_t start = 0;
while( start <= text.size() )
{
size_t nl = text.find( '\n', start );
if( nl == std::string::npos )
{
nested.push_back( text.substr( start ) );
break;
}
nested.push_back( text.substr( start, nl - start ) );
start = nl + 1;
}
collectIncludeFiles( nested, aFiles, aSeen, aDepth + 1 );
}
}
} // namespace
// -------------------------------------------------------------------------
// Event entry from JS (fresh wasm entry; must never suspend)
// -------------------------------------------------------------------------
extern "C" EMSCRIPTEN_KEEPALIVE void pcbjam_ngspice_event( int aKind, char* aText, int aA, int aB )
{
switch( aKind )
{
case 0: // char
if( s_sendChar )
s_sendChar( aText ? aText : const_cast<char*>( "" ), 0, s_user );
break;
case 1: // stat
if( s_sendStat )
s_sendStat( aText ? aText : const_cast<char*>( "" ), 0, s_user );
break;
case 2: // bg: aA = finished
s_bgRunning.store( aA == 0 );
if( s_bgThreadRunning )
s_bgThreadRunning( aA != 0, 0, s_user );
break;
case 3: // exit: aA = status, aB = immediate|quit<<1
s_bgRunning.store( false );
if( s_controlledExit )
s_controlledExit( aA, ( aB & 1 ) != 0, ( aB & 2 ) != 0, 0, s_user );
break;
}
std::free( aText );
}
findings(E-5,E-8,E-9): module-identity ngspice events + runWaitCompletion admission gate E-8 (re-implemented for JSPI — the codex gate is entangled with the dropped execution owner; under JSPI a fresh non-suspending JS→wasm entry while another activation is suspended is structurally safe on its own stack, so the admission boundary for worker completions is liveness + trap state, not execution ownership): - jspi-scheduler.js grows `terminal` (trapped instance; distinct from `dead`), canTouchNative(), _terminalizeNativeTrap() (WebAssembly.RuntimeError + cross-realm string classification), and runWaitCompletion(site, token, prepare, inertResult): prepare runs immediately and owns ALL native work; stale tokens and dead/terminal instances drop loudly without resolving (resolving would resume the parked frame inside the damaged module); a trap latches terminal; a plain JS bug resolves inertResult so the wait fails instead of stranding. beginWait refuses (token 0) when dead/terminal. - all four delayed completion sites route their native work through the gate: 'OCC export completion' (exporter_step_stub), 'OCC model completion' (oce_plugin_stub — the MEMFS cache write moves inside the gate too), 'ngspice request completion' and 'ngspice vector completion' (sharedspice_client — every HEAP32/HEAPF64/malloc write inside prepare, inertResult 1 = transport error). Every wxWasmBeginWait caller in the stubs bails on token <= 0. - deliberately NOT ported from codex: ownerModule, enqueueNativeCompletion, executionBarrier, the byte-credit native-entry FIFO — completions are one-shot per wait token and stream volume is bounded at the E-6 transport credit window. Cross-refs logged for group M (M-2/M-6/M-8). E-5 (re-implemented; codex shape kept, owner APIs replaced with the E-8 gate): js_ngspice_install_events binds the handler to the EXACT installing module (handler.__pcbjamNgspiceOwnerModule stamp; presence is not identity), re-installation replaces a foreign module's handler, a superseded handler disarms itself, native entry goes through installingModule._malloc/ ._pcbjam_ngspice_event (never lexical Module), each dispatch checks canTouchNative() (loud drop on a dead/terminal module), and a trap on the per-line entry latches the terminal gate. Tests: scheduler-shim.test.ts +7 (gate happy/stale/dead/terminal/cross-realm/ js-bug/beginWait-refusal). e2e specs updated from the codex line: occ-export decode-fault recovery (real onmessageerror transition via failDecode, J-4), ngspice-probe direct-service coverage, eeschema-sim rewritten onto the E-7 applied-generation receipt (codex's executionBarrier await replaced with a pendingWaits('ngspice') drain poll — the JSPI-line equivalent). Also bumps the kicad submodule to the E-7/E-9 commit (dd5751038f7). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:03:16 +02:00
// E-9: a destroyed NGSPICE must unregister its callbacks — a late worker
// event otherwise reaches s_sendChar( text, 0, s_user ) with s_user pointing
// at the destroyed object (use-after-free after simulator close; the E-7
// run-generation gate sits downstream in the wx event queue and cannot cover
// this entry). Identity-checked so a stale destructor never clears a
// successor instance's registration.
extern "C" EMSCRIPTEN_KEEPALIVE void pcbjam_ngspice_reset_callbacks( void* aUser )
{
if( s_user != aUser )
return;
s_sendChar = nullptr;
s_sendStat = nullptr;
s_controlledExit = nullptr;
s_bgThreadRunning = nullptr;
s_user = nullptr;
}
findings(E-10..E-22): fix the defects a code review found in the E-1..E-9 work A review of the group-E fixes found 13 further defects; ten were introduced by those fixes, two pre-existed and were merely relocated, one is deferred. Services / transport E-10 retireWorker synthesized no bg/exit frame, so sharedspice's s_bgRunning mirror stayed latched true after a mid-run worker death: Run stayed disabled and the promised fresh-worker restart was unreachable for the whole session. Retirement now dispatches a synthetic controlled-exit straight to the installed handler (never through dispatchEvt — a fabricated frame must not touch the credit ledger). Driving the repro exposed two further defects, both fixed here: a replacement worker trapped on pre-init engine reads, and the rerun's cm_input_path/circ hit that uninitialized engine before KiCad's validate() re-init (the native flow assumes a crashed engine survives in-process — true for the dll, false for a dead worker). Reads now answer their empty shapes pre-init, writes lazy-init, and init is idempotent per worker engine. E-19 dispatchEvt acked only AFTER handler(evt) returned, and the sharedspice client deliberately rethrows non-trap errors — so each throw leaked one unit of the 64-frame credit window until the stream died with a misattributed "transport exceeded". The ack moves to a finally in both service copies; the throw still propagates (the trap machinery needs it). E-20 the oversize-line path promises to transfer the accepted prefix, but with the window full that flush only DEFERS, and stopEventStream wiped the deferred queue — losing the diagnostics that explain the failure. The terminal notice now carries them as pendingEvents; both hosts deliver them in order, unacked (the fatal frame is outside the credit protocol). E-21 the 30s prefetch deadline discarded every model already collected and reported nothing. A caller-owned progress sink ships the partials and the omission reaches the export report. (Awaiting the aborted collection was rejected: an in-flight source fetch is not abortable — E-4's original disease.) Plus a serving-candidate memo, so a .wrl ref served by its .step fallback stops re-probing the miss on every export. Scheduler E-14 _terminalizeNativeTrap classified by message substring, so any plain JS error QUOTING 'Aborted(' or 'out of bounds' permanently bricked a healthy instance. Now structural only: instanceof RuntimeError plus a duck-typed name check (verified in this build's glue that abort() throws a genuine RuntimeError both pre- and post-runtime-init). Module.onAbort now latches the gate — the authoritative notification, previously ignored. E-15 the shim half: _pumpResume gates on terminal (catching wakes already queued at latch time) and resolveWait refuses on terminal WITHOUT consuming the entry, so a frame stays visibly parked rather than resuming inside a trapped module. E-16 the E-5 handler read the realm-global scheduler at dispatch instead of its installing module's; also frees the per-line buffer on the non-trap rethrow path. E-11 get_vec trusted the worker's res.length over the transferred arrays. Observed death shape: a 4 GiB std::vector threw an unhandled std::length_error that exited the editor's main loop. Now clamped, with the buffers freed on every failure path. Guardrails (replacing two deferred refactors: e2e→production-code injection and collapsing the four copies of the worker-lifecycle machinery) E-18 the source contract asserted comment-string counts — rewording failed CI while moving a guard outside its #ifdef passed. It now parses the #ifdef regions and asserts on code. service-stub-parity.ts pins what the four lifecycle copies must share: credit-window equality parsed from source, the finally-ack, boot deadlines, terminal-notice consumption. The transport numbers are now single-sourced from the worker. CI actually runs the gates: the web/standalone vitest suites (which had NEVER run in CI), the reducer, the source contract and the parity tool — with a NON_PLAYWRIGHT_GATES check so deleting a step re-fails the lint. E-22 the e2e occ stub's 60s boot watchdog, deleted in a66e109, is restored in the ngspice-stub shape with a wedgeNextBoot() repro hook. Every behavioral fix has red-then-green evidence (the reds were captured first). E-17 (a stale RUNNING cross-stamping the next run's generation under E-6's transport deferral) is DEFERRED with its analysis recorded — a real fix needs run identity on the bg frames. Test hygiene: the dwell lint now requires the mandated ": <why>" and all 47 bare markers carry their reason; three export-report dwells became modal-lease polls; exact-ledger assertions became relative deltas; the dead data-wx-dom-id branch, an unused fault hook and unused receipt plumbing are gone; abort scans, wx dialog drivers, the sim harness and the vitest FakeWorker are each one copy now. Bumps kicad and wxwidgets to their findings-group-e tips. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-27 12:27:12 +02:00
// E-7: the browser harness's final-refresh receipt — called by
// SIMULATOR_FRAME::onSimFinished after every final native refresh (one
// ifdef'd line there; the JS-side knowledge lives HERE, in the stub layer).
// Optional test evidence, no mainline behavior.
// clang-format off
EM_JS( void, js_ngspice_sim_run_applied, ( uint32_t aGeneration ), {
const hook = globalThis.__pcbjamNgspiceFinalRefreshApplied;
if( typeof hook === 'function' )
{
try
{
hook( aGeneration >>> 0 );
}
catch( error )
{
console.error( '[ngspice] final-refresh hook failed', error );
}
}
} );
// clang-format on
extern "C" EMSCRIPTEN_KEEPALIVE void pcbjam_sim_run_applied( uint32_t aGeneration )
{
js_ngspice_sim_run_applied( aGeneration );
}
// -------------------------------------------------------------------------
// The sharedspice API surface NGSPICE::init_dll binds to
// -------------------------------------------------------------------------
void pcbjam_ngSpice_Init( SendChar* aSendChar, SendStat* aSendStat, ControlledExit* aExit,
SendData*, SendInitData*, BGThreadRunning* aBgRunning, void* aUser )
{
s_sendChar = aSendChar;
s_sendStat = aSendStat;
s_controlledExit = aExit;
s_bgThreadRunning = aBgRunning;
s_user = aUser;
js_ngspice_install_events();
// Boots the worker lazily; a failure surfaces on the first command too
// (KiCad ignores ngSpice_Init's status, matching its native call).
rpc( { { "kind", "init" } } );
}
int pcbjam_ngSpice_Circ( char** aCircArray )
{
std::vector<std::string> lines;
for( int i = 0; aCircArray && aCircArray[i]; i++ )
lines.emplace_back( aCircArray[i] );
json files = json::array();
std::set<std::string> seen;
collectIncludeFiles( lines, &files, &seen, 0 );
json req = { { "kind", "circ" }, { "lines", lines }, { "files", std::move( files ) } };
return rpc( req ).value( "ret", 1 );
}
int pcbjam_ngSpice_Command( char* aCommand )
{
std::string cmd = aCommand ? aCommand : "";
int ret = rpc( { { "kind", "command" }, { "cmd", cmd } } ).value( "ret", 1 );
// The bg 'started' event arrives asynchronously; flip the mirror at the
// acceptance edge so an immediate IsRunning() poll already sees it.
if( ret == 0 && cmd.rfind( "bg_run", 0 ) == 0 )
s_bgRunning.store( true );
return ret;
}
pvector_info pcbjam_ngGet_Vec_Info( char* aVecName )
{
// Per-call arena: valid until the next call, matching every NGSPICE
// consumer (they copy within the same call).
static vector_info s_vi;
static char* s_name = nullptr;
static double* s_real = nullptr;
static double* s_comp = nullptr;
std::free( s_name );
std::free( s_real );
std::free( s_comp );
s_name = nullptr;
s_real = nullptr;
s_comp = nullptr;
int meta[4] = { 0, 0, 0, 0 };
double* real = nullptr;
double* comp = nullptr;
char* vname = nullptr;
const int token = wxWasmBeginWait( "ngspice" );
findings(E-5,E-8,E-9): module-identity ngspice events + runWaitCompletion admission gate E-8 (re-implemented for JSPI — the codex gate is entangled with the dropped execution owner; under JSPI a fresh non-suspending JS→wasm entry while another activation is suspended is structurally safe on its own stack, so the admission boundary for worker completions is liveness + trap state, not execution ownership): - jspi-scheduler.js grows `terminal` (trapped instance; distinct from `dead`), canTouchNative(), _terminalizeNativeTrap() (WebAssembly.RuntimeError + cross-realm string classification), and runWaitCompletion(site, token, prepare, inertResult): prepare runs immediately and owns ALL native work; stale tokens and dead/terminal instances drop loudly without resolving (resolving would resume the parked frame inside the damaged module); a trap latches terminal; a plain JS bug resolves inertResult so the wait fails instead of stranding. beginWait refuses (token 0) when dead/terminal. - all four delayed completion sites route their native work through the gate: 'OCC export completion' (exporter_step_stub), 'OCC model completion' (oce_plugin_stub — the MEMFS cache write moves inside the gate too), 'ngspice request completion' and 'ngspice vector completion' (sharedspice_client — every HEAP32/HEAPF64/malloc write inside prepare, inertResult 1 = transport error). Every wxWasmBeginWait caller in the stubs bails on token <= 0. - deliberately NOT ported from codex: ownerModule, enqueueNativeCompletion, executionBarrier, the byte-credit native-entry FIFO — completions are one-shot per wait token and stream volume is bounded at the E-6 transport credit window. Cross-refs logged for group M (M-2/M-6/M-8). E-5 (re-implemented; codex shape kept, owner APIs replaced with the E-8 gate): js_ngspice_install_events binds the handler to the EXACT installing module (handler.__pcbjamNgspiceOwnerModule stamp; presence is not identity), re-installation replaces a foreign module's handler, a superseded handler disarms itself, native entry goes through installingModule._malloc/ ._pcbjam_ngspice_event (never lexical Module), each dispatch checks canTouchNative() (loud drop on a dead/terminal module), and a trap on the per-line entry latches the terminal gate. Tests: scheduler-shim.test.ts +7 (gate happy/stale/dead/terminal/cross-realm/ js-bug/beginWait-refusal). e2e specs updated from the codex line: occ-export decode-fault recovery (real onmessageerror transition via failDecode, J-4), ngspice-probe direct-service coverage, eeschema-sim rewritten onto the E-7 applied-generation receipt (codex's executionBarrier await replaced with a pendingWaits('ngspice') drain poll — the JSPI-line equivalent). Also bumps the kicad submodule to the E-7/E-9 commit (dd5751038f7). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:03:16 +02:00
// Token 0 = the scheduler refused the wait (dead or terminal instance).
if( token <= 0 )
return nullptr;
js_ngspice_get_vec_start( token, aVecName ? aVecName : "", meta, &real, &comp, &vname );
findings(E-10..E-22): fix the defects a code review found in the E-1..E-9 work A review of the group-E fixes found 13 further defects; ten were introduced by those fixes, two pre-existed and were merely relocated, one is deferred. Services / transport E-10 retireWorker synthesized no bg/exit frame, so sharedspice's s_bgRunning mirror stayed latched true after a mid-run worker death: Run stayed disabled and the promised fresh-worker restart was unreachable for the whole session. Retirement now dispatches a synthetic controlled-exit straight to the installed handler (never through dispatchEvt — a fabricated frame must not touch the credit ledger). Driving the repro exposed two further defects, both fixed here: a replacement worker trapped on pre-init engine reads, and the rerun's cm_input_path/circ hit that uninitialized engine before KiCad's validate() re-init (the native flow assumes a crashed engine survives in-process — true for the dll, false for a dead worker). Reads now answer their empty shapes pre-init, writes lazy-init, and init is idempotent per worker engine. E-19 dispatchEvt acked only AFTER handler(evt) returned, and the sharedspice client deliberately rethrows non-trap errors — so each throw leaked one unit of the 64-frame credit window until the stream died with a misattributed "transport exceeded". The ack moves to a finally in both service copies; the throw still propagates (the trap machinery needs it). E-20 the oversize-line path promises to transfer the accepted prefix, but with the window full that flush only DEFERS, and stopEventStream wiped the deferred queue — losing the diagnostics that explain the failure. The terminal notice now carries them as pendingEvents; both hosts deliver them in order, unacked (the fatal frame is outside the credit protocol). E-21 the 30s prefetch deadline discarded every model already collected and reported nothing. A caller-owned progress sink ships the partials and the omission reaches the export report. (Awaiting the aborted collection was rejected: an in-flight source fetch is not abortable — E-4's original disease.) Plus a serving-candidate memo, so a .wrl ref served by its .step fallback stops re-probing the miss on every export. Scheduler E-14 _terminalizeNativeTrap classified by message substring, so any plain JS error QUOTING 'Aborted(' or 'out of bounds' permanently bricked a healthy instance. Now structural only: instanceof RuntimeError plus a duck-typed name check (verified in this build's glue that abort() throws a genuine RuntimeError both pre- and post-runtime-init). Module.onAbort now latches the gate — the authoritative notification, previously ignored. E-15 the shim half: _pumpResume gates on terminal (catching wakes already queued at latch time) and resolveWait refuses on terminal WITHOUT consuming the entry, so a frame stays visibly parked rather than resuming inside a trapped module. E-16 the E-5 handler read the realm-global scheduler at dispatch instead of its installing module's; also frees the per-line buffer on the non-trap rethrow path. E-11 get_vec trusted the worker's res.length over the transferred arrays. Observed death shape: a 4 GiB std::vector threw an unhandled std::length_error that exited the editor's main loop. Now clamped, with the buffers freed on every failure path. Guardrails (replacing two deferred refactors: e2e→production-code injection and collapsing the four copies of the worker-lifecycle machinery) E-18 the source contract asserted comment-string counts — rewording failed CI while moving a guard outside its #ifdef passed. It now parses the #ifdef regions and asserts on code. service-stub-parity.ts pins what the four lifecycle copies must share: credit-window equality parsed from source, the finally-ack, boot deadlines, terminal-notice consumption. The transport numbers are now single-sourced from the worker. CI actually runs the gates: the web/standalone vitest suites (which had NEVER run in CI), the reducer, the source contract and the parity tool — with a NON_PLAYWRIGHT_GATES check so deleting a step re-fails the lint. E-22 the e2e occ stub's 60s boot watchdog, deleted in a66e109, is restored in the ngspice-stub shape with a wedgeNextBoot() repro hook. Every behavioral fix has red-then-green evidence (the reds were captured first). E-17 (a stale RUNNING cross-stamping the next run's generation under E-6's transport deferral) is DEFERRED with its analysis recorded — a real fix needs run identity on the bg frames. Test hygiene: the dwell lint now requires the mandated ": <why>" and all 47 bare markers carry their reason; three export-report dwells became modal-lease polls; exact-ledger assertions became relative deltas; the dead data-wx-dom-id branch, an unused fault hook and unused receipt plumbing are gone; abort scans, wx dialog drivers, the sim harness and the vitest FakeWorker are each one copy now. Bumps kicad and wxwidgets to their findings-group-e tips. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-27 12:27:12 +02:00
// E-11: a plain-JS throw mid-prepare (after some mallocs landed) resolves
// the inertResult without adopting the buffers into the arena — free
// whatever was written on EVERY failure path (free(nullptr) is a no-op,
// so this covers all partial orderings).
if( wxWasmYieldUntil( token ) != 0 || !meta[0] )
{
std::free( vname );
std::free( real );
std::free( comp );
return nullptr;
findings(E-10..E-22): fix the defects a code review found in the E-1..E-9 work A review of the group-E fixes found 13 further defects; ten were introduced by those fixes, two pre-existed and were merely relocated, one is deferred. Services / transport E-10 retireWorker synthesized no bg/exit frame, so sharedspice's s_bgRunning mirror stayed latched true after a mid-run worker death: Run stayed disabled and the promised fresh-worker restart was unreachable for the whole session. Retirement now dispatches a synthetic controlled-exit straight to the installed handler (never through dispatchEvt — a fabricated frame must not touch the credit ledger). Driving the repro exposed two further defects, both fixed here: a replacement worker trapped on pre-init engine reads, and the rerun's cm_input_path/circ hit that uninitialized engine before KiCad's validate() re-init (the native flow assumes a crashed engine survives in-process — true for the dll, false for a dead worker). Reads now answer their empty shapes pre-init, writes lazy-init, and init is idempotent per worker engine. E-19 dispatchEvt acked only AFTER handler(evt) returned, and the sharedspice client deliberately rethrows non-trap errors — so each throw leaked one unit of the 64-frame credit window until the stream died with a misattributed "transport exceeded". The ack moves to a finally in both service copies; the throw still propagates (the trap machinery needs it). E-20 the oversize-line path promises to transfer the accepted prefix, but with the window full that flush only DEFERS, and stopEventStream wiped the deferred queue — losing the diagnostics that explain the failure. The terminal notice now carries them as pendingEvents; both hosts deliver them in order, unacked (the fatal frame is outside the credit protocol). E-21 the 30s prefetch deadline discarded every model already collected and reported nothing. A caller-owned progress sink ships the partials and the omission reaches the export report. (Awaiting the aborted collection was rejected: an in-flight source fetch is not abortable — E-4's original disease.) Plus a serving-candidate memo, so a .wrl ref served by its .step fallback stops re-probing the miss on every export. Scheduler E-14 _terminalizeNativeTrap classified by message substring, so any plain JS error QUOTING 'Aborted(' or 'out of bounds' permanently bricked a healthy instance. Now structural only: instanceof RuntimeError plus a duck-typed name check (verified in this build's glue that abort() throws a genuine RuntimeError both pre- and post-runtime-init). Module.onAbort now latches the gate — the authoritative notification, previously ignored. E-15 the shim half: _pumpResume gates on terminal (catching wakes already queued at latch time) and resolveWait refuses on terminal WITHOUT consuming the entry, so a frame stays visibly parked rather than resuming inside a trapped module. E-16 the E-5 handler read the realm-global scheduler at dispatch instead of its installing module's; also frees the per-line buffer on the non-trap rethrow path. E-11 get_vec trusted the worker's res.length over the transferred arrays. Observed death shape: a 4 GiB std::vector threw an unhandled std::length_error that exited the editor's main loop. Now clamped, with the buffers freed on every failure path. Guardrails (replacing two deferred refactors: e2e→production-code injection and collapsing the four copies of the worker-lifecycle machinery) E-18 the source contract asserted comment-string counts — rewording failed CI while moving a guard outside its #ifdef passed. It now parses the #ifdef regions and asserts on code. service-stub-parity.ts pins what the four lifecycle copies must share: credit-window equality parsed from source, the finally-ack, boot deadlines, terminal-notice consumption. The transport numbers are now single-sourced from the worker. CI actually runs the gates: the web/standalone vitest suites (which had NEVER run in CI), the reducer, the source contract and the parity tool — with a NON_PLAYWRIGHT_GATES check so deleting a step re-fails the lint. E-22 the e2e occ stub's 60s boot watchdog, deleted in a66e109, is restored in the ngspice-stub shape with a wedgeNextBoot() repro hook. Every behavioral fix has red-then-green evidence (the reds were captured first). E-17 (a stale RUNNING cross-stamping the next run's generation under E-6's transport deferral) is DEFERRED with its analysis recorded — a real fix needs run identity on the bg frames. Test hygiene: the dwell lint now requires the mandated ": <why>" and all 47 bare markers carry their reason; three export-report dwells became modal-lease polls; exact-ledger assertions became relative deltas; the dead data-wx-dom-id branch, an unused fault hook and unused receipt plumbing are gone; abort scans, wx dialog drivers, the sim harness and the vitest FakeWorker are each one copy now. Bumps kicad and wxwidgets to their findings-group-e tips. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-27 12:27:12 +02:00
}
s_name = vname;
s_real = real;
s_comp = comp;
s_vi.v_name = s_name;
s_vi.v_type = meta[1];
s_vi.v_flags = (short) meta[2];
s_vi.v_length = meta[3];
s_vi.v_realdata = s_real;
// Interleaved re,im doubles ARE the ngcomplex_t array layout.
s_vi.v_compdata = reinterpret_cast<ngcomplex_t*>( s_comp );
return &s_vi;
}
char* pcbjam_ngSpice_CurPlot( void )
{
static std::string s_plot;
s_plot = rpc( { { "kind", "cur_plot" } } ).value( "name", "" );
return s_plot.data();
}
namespace
{
// Shared marshalling for the two NULL-terminated string-array calls.
char** stringArrayResult( const json& aRes )
{
static std::vector<std::string> s_store;
static std::vector<char*> s_ptrs;
s_store.clear();
s_ptrs.clear();
if( aRes.contains( "names" ) && aRes["names"].is_array() )
{
for( const auto& n : aRes["names"] )
s_store.push_back( n.get<std::string>() );
}
for( std::string& s : s_store )
s_ptrs.push_back( s.data() );
s_ptrs.push_back( nullptr );
return s_ptrs.data();
}
} // namespace
char** pcbjam_ngSpice_AllPlots( void )
{
return stringArrayResult( rpc( { { "kind", "all_plots" } } ) );
}
char** pcbjam_ngSpice_AllVecs( char* aPlotName )
{
return stringArrayResult(
rpc( { { "kind", "all_vecs" }, { "plot", aPlotName ? aPlotName : "" } } ) );
}
bool pcbjam_ngSpice_Running( void )
{
return s_bgRunning.load();
}
char* pcbjam_ngCM_Input_Path( const char* aPath )
{
static std::string s_path;
s_path = aPath ? aPath : "";
rpc( { { "kind", "cm_input_path" }, { "path", s_path } } );
return s_path.data();
}
#endif // __EMSCRIPTEN__