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>
This commit is contained in:
Istvan Matejcsok 2026-08-19 16:03:16 +02:00
commit c14e76651c
9 changed files with 763 additions and 149 deletions

View file

@ -36,8 +36,8 @@ async function loadRectifier(page: import('@playwright/test').Page): Promise<voi
for (const f of PROJECT_FILES)
await injectFileIntoMemfs(page, path.join(RECTIFIER_DIR, f), `${MEMFS_DIR}/${f}`);
await page.evaluate((sch: string) => {
(window as any).Module.kicadOpenFile(sch);
await page.evaluate(async (sch: string) => {
await (window as any).Module.kicadOpenFile(sch);
}, `${MEMFS_DIR}/rectifier.kicad_sch`);
await expect
@ -67,12 +67,9 @@ async function openSimulator(page: import('@playwright/test').Page): Promise<str
return simWin!;
}
// Run the loaded workbook's analysis and wait for the background run to
// finish (the bg 'finished' event lands after ngspice's thread joins).
async function runSimulation(page: import('@playwright/test').Page): Promise<void> {
const evtsBefore = await page.evaluate(
() => (window as any).__ngspiceEvents.length as number);
// Run the loaded workbook's analysis and await the exact native run generation
// only after its final plot, operating-point, and canvas refresh calls return.
async function runSimulation(page: import('@playwright/test').Page): Promise<number> {
// The simulator window div appears while the frame ctor is still
// suspended in the init RPC; the toolbar registers its tools only after
// init completes and the frame first paints. The Run tool's
@ -90,13 +87,53 @@ async function runSimulation(page: import('@playwright/test').Page): Promise<voi
}, { timeout: 60000 })
.toBe(true);
const generationCheckpoint = await page.evaluate(() => {
const hooks = (globalThis as any).__ngspiceServiceTestHooks;
if (!hooks || typeof hooks.appliedGenerationCheckpoint !== 'function'
|| typeof hooks.waitForAppliedGenerationAfter !== 'function') {
throw new Error('exact ngspice applied-generation hooks are missing');
}
return hooks.appliedGenerationCheckpoint() as number;
});
expect(await clickByTooltip(page, 'Run Simulation', { elementType: 'tool' }),
'Run tool').toBe(true);
await page.waitForFunction((n: number) => {
const evts = (window as any).__ngspiceEvents as Array<{ kind: string; finished?: boolean }>;
return evts.slice(n).some((e) => e.kind === 'bg' && e.finished === true);
}, evtsBefore, { timeout: 120000 });
const appliedReceipt = await page.evaluate(async (after: number) => {
const hooks = (globalThis as any).__ngspiceServiceTestHooks;
return await hooks.waitForAppliedGenerationAfter(after, 120000);
}, generationCheckpoint);
expect(appliedReceipt.generation, 'the clicked run published a newer applied generation')
.toBeGreaterThan(generationCheckpoint);
// The native receipt fires after the final refreshes. Additionally
// require the scheduler to hold no parked ngspice wait — a stale
// suspended frame here means the finish path leaked a wait. (The codex
// line awaited the execution owner's barrier; that machinery does not
// exist on the JSPI line, and wait drainage is its observable
// equivalent.)
await expect.poll(
() => page.evaluate(() => {
const scheduler = (globalThis as any).__wxScheduler;
return scheduler?.pendingWaits?.('ngspice') ?? -1;
}),
{ message: 'no ngspice wait may stay parked after the applied receipt', timeout: 30000 },
).toBe(0);
// Vector traffic is result validation only. It is deliberately not used as
// completion evidence because periodic OnSimRefresh(false) pulls can look
// identical to the final pull at the worker boundary.
const vectorReceipt = await page.evaluate(() =>
((window as any).__ngspiceLog as Array<{
sequence: number; kind: string; error?: string; length?: number;
}>).find((entry) => entry.kind === 'get_vec_info'
&& entry.error === undefined
&& (entry.length ?? -1) >= 101) ?? null,
);
expect(vectorReceipt, 'the applied run returned a non-trivial successful vector')
.not.toBeNull();
return appliedReceipt.generation;
}
function distinctColors(png: PNG): number {
@ -168,7 +205,9 @@ test.describe('eeschema simulator', () => {
const charText = evts.flatMap((e) => e.lines ?? []).join('\n');
expect(charText, 'no missing-model errors').not.toMatch(/unable to find definition/i);
// The plot pulled real vector data through get_vec_info.
// The exact final-refresh receipt and drained-waits check above prove
// this log entry belongs to a vector which reached the plot, not
// merely a worker response still waiting to copy into native memory.
const vecPulls = await page.evaluate(() =>
((window as any).__ngspiceLog as Array<{ kind: string; length?: number }>)
.filter((l) => l.kind === 'get_vec_info' && (l.length ?? 0) > 100).length);
@ -197,8 +236,10 @@ test.describe('eeschema simulator', () => {
await loadRectifier(page);
await openSimulator(page);
await runSimulation(page);
await runSimulation(page);
const firstGeneration = await runSimulation(page);
const secondGeneration = await runSimulation(page);
expect(secondGeneration, 'the second run has its own exact generation')
.toBeGreaterThan(firstGeneration);
const finishCount = await page.evaluate(() =>
((window as any).__ngspiceEvents as Array<{ kind: string; finished?: boolean }>)