pcbjam/tests/kicad/3d-viewer-models.spec.ts

304 lines
16 KiB
TypeScript
Raw Normal View History

import type { Page } from '@playwright/test';
import { test, expect } from './fixtures';
e2e/CI: dual-engine suites, per-engine screenshots, SwiftShader retired, prod web suite, CI-coverage gate Squash of experiment/ff-big-modules vs main. Big-module routing removed: native-EH shrank kicad_editor below SpiderMonkey's x86-64 code budget (runs 29355049705/29356152413 green on stock Firefox), so BIG_MODULE_SPECS routing and the baseline-only-JIT crutch are gone — kicad-firefox and kicad-chromium both run the full suite, with the module compiled the way real users' browsers compile it. Per-engine screenshots end to end: stableShot/shotPath write test-results/<engine>/<name>.png; baselines move to baseline-screenshots/{chromium,firefox}/ and the whole tools/screenshots pipeline (compare/promote/manifest/spec-map/changelog/Discord) keys on <engine>/<name>. Previously Firefox and Chromium renders of one spec overwrote each other and Firefox renders were never actually gated. Seeded from CI run 29421380806 (92 new firefox baselines, +24 chromium web-suite shots); manifest generated from the baseline tree. One merged playwright.config.ts (kicad/asyncify/coroutine/perf as projects); ~25 dead npm scripts dropped. The web suite is gated in CI for the first time ever (4 rotted specs fixed, 5 broken lib-bridge specs triaged as fixme in docs/features/web-e2e-rot/); cheap lint step after npm ci; last 26 blind-sleep violations fixed. SwiftShader retired: CI Chromium renders WebGL on ANGLE → Mesa llvmpipe (--use-gl=angle --use-angle=gl --ignore-gpu-blocklist; the blocklist flag is mandatory — llvmpipe is blocklisted and WebGL is silently unavailable without it) in BOTH configs. Under WORKERS=4 congestion SwiftShader transiently failed the first post-board-load draw and the recovery cascade ended in a silent permanent Cairo fallback — that engine flip was the "~1.2% changedRatio both directions" occ-export baseline flake. Validated 160/160 across two 80-repeat rigs; full analysis in docs/features/wx-parity-bugs/occ-export-context-eviction.md. Chromium baselines shift slightly on llvmpipe — promote once from the first green run. Deflakes the new coverage exposed: presence baselines settle before capture; presence fixtures declare current file formats; perf gets its own outputDir so CI evidence survives; occ-export settles the board paint before the export dialog; menu-item waits (waitForRenderedByLabel before clickMenuItem) in 4 specs + the TESTING.md rule. Web suite runs the PROD build, in parallel: webServer becomes backend `start` + the standalone's e2e:preview (build-preview.mjs: link-wasm → stash the public/wasm symlink aside during vite build, build-demo.mjs's move — then vite preview as the persistent server). The wasm middleware serves /wasm/* in preview and emits COOP/COEP/CORP itself (a pthread worker script's own response must carry COEP or Chrome kills it with ERR_BLOCKED_BY_RESPONSE). VITE_* flags bake at build time; VITE_ALLOW_USER_OVERRIDE joins turbo globalEnv. fullyParallel + default workers: 5.2m → 1.4m. Determinism fixes the parallel run exposed: shared-page specs become serial groups; locks.spec grabs alice's exact item via the new kicadCollabTestSelectByUuid hook (cross-tab "first footprint" order is not a ysync invariant); quit specs poll page.url() (quit supersedes its own navigation — NS_BINDING_ABORTED on Firefox). Suite: 51 passed / 12 skipped / 0 failed in 1.6m. CI-coverage gate (lint:ci-coverage): every tests/**/*.spec.ts must be reachable from the npm scripts the workflows invoke — scraped from .github/workflows/, resolved through package.json, coverage asked from playwright --list itself. Rules: uncovered-spec + orphan-project (with a documented LOCAL_ONLY_PROJECTS allowlist). Gating next to lint:determinism; 138 spec files / 13 projects accounted for. Product fixes kept from the investigations (reachable on real GPUs too): wx 7799fd1be5 — paint flags clear before dispatch + Invalidate always propagates; kicad 3dcfea5e45 — SwiftShader pass-boundary flush + per-instance font texture + first-frame GL-error drain (GAL recovery recovers instead of falling back to Cairo) + the user-facing eeschema switch navigates again under __EMSCRIPTEN__ (project-sync's FaceRegistered gate had rerouted it into the hidden sync player; caught by the newly-gated web suite). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018eUxiPApHgGiu9NFyQfhAq
2026-07-17 12:10:40 +02:00
import { clickMenuBarItem, clickMenuItem, clickMenuItemByText, waitForEditorReady, waitForRenderedByLabel, waitUntil, shotPath } from '../e2e/utils/element-tracker';
import { injectFromSubmodule } from './utils/fs-inject';
import { waitForBoardLoaded } from './utils/board-ready';
fix(e2e): rescope the 3D fixes for the webgl-era viewer (rebased onto main) The 3d-webgl merge (kicad eb13ff3bdc: the viewer now defaults to the real OpenGL renderer via wasm/gl1, and occ-split moves STEP parsing into the occ_service worker) made the raytracer-era orchestration on this branch moot — main's chromium-ci phase is green at 15-way parallelism (28666407570 / 28698861536). Drop what no longer earns its complexity, keep the diagnostics, fix main's live flake, and make the deadlock spec test what it was written for. - REVERT the chromium-ci-3d serial project, the two-phase test:kicad:ci, the SwiftShader GPU-process flags, and the resize-drag/models skips: config and package.json are byte-for-byte back to main's shape. The raytracer contention they guarded is no longer on the CI path. - FIX main's live flake: run 28698861536 is green only via retry (3d-viewer.spec:26 flaky) and 28666407570's deadlock red sampled an ALL-ZERO pixel signature — the viewer's first frame lags the canvas's creation on software WebGL under parallel load, and sampling too early reads an all-black backbuffer. New waitForThreeDRender() gates render assertions on actual pixels (1s-interval full-frame CPU reads) instead of fixed sleeps, used by 3d-viewer.spec:26 and the models render tail. - KEEP the storm-proofed samplers (one full-frame getImageData on a willReadFrequently canvas replacing 256 per-pixel GPU round-trips per sample — the "GPU stall due to ReadPixels" trigger) and the logThreeDDiag instrumentation: engine-independent, and they de-risk every remaining software-GL pixel read. - models spec: bridge assertions stay front-loaded (the protocol regression signal is independent of the render); the occ_service parse verdict is now POLLED — it lands async relative to the bridge ensures, so asserting it immediately raced the worker; the render tail runs again everywhere. (The pre-webgl raytracer+models renderer-death documented in a17f3be does not affect the OpenGL default path — the raytracer-toggle+models combination remains untested product surface, tracked outside this branch.) - deadlock spec: the deadlock it guards is raytracer-specific and the viewer now defaults to OpenGL — on the GL engine it either passes vacuously (fast renders make every liveness assertion trivial, 28698861536) or fails on the black first frame (28666407570). It now flips the engine via the "Use raytracing" toolbar toggle (loud assert if the toggle moved) and cross-checks engagement by requiring the canvas pixels to CHANGE after the flip with no input in between (the raytraced frame is lit differently; a GL re-render reproduces identical pixels; heap growth is unusable — mimalloc satisfies the raytracer from freed arena pages). That guard immediately caught a REAL defect: on the webgl-era wasm build the toggle is INERT (the click lands and "Reload time" updates, but the canvas never changes — suspects: DoRePaint's silent catch(runtime_error) freezing the canvas after a raytracer Redraw throw, or ToggleRaytracing writing m_boardAdapter.m_Cfg while RenderEngineChanged() reads GetAppSettings<…>(), possibly different instances in the merged bundle). The spec is therefore test.skip-annotated as a KNOWN ISSUE with the full engine-force machinery in place — unskipping it self-validates the product fix. The CI-skip also stays (raytracer liveness needs real-GPU pacing; the Worker-boot deadlock mechanism is covered on CI by the standalone wx harnesses). - 180s viewer-open waits kept as pure CI headroom (never slow a passing run). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 11:37:27 +02:00
import { logThreeDDiag, waitForThreeDRender } from './utils/threed-viewer';
test(determinism): deterministic waits + stableShot screenshots; drop blind sleeps/ifs/retries Make the Playwright e2e + kicad suites deterministic so screenshot flake stops tracing to timing races. - Blind page.waitForTimeout -> condition waits (expect.poll, web-first assertions, waitUntil) + readiness helpers (waitForWxApp, waitForCanvasApp). Remaining sleeps are documented interaction dwells (annotated). - Defensive "if element exists" branches -> loud asserts; label-fallback chains -> normalized clickMenuItemByText. First-run wizard for/if loops removed by seeding calculator/gerbview/pcbnew HTMLs. - Screenshots: new stableShot(page, name) settles the render in-page (canvas hash over rAF) then writes a raw PNG to test-results/ for the existing offline gate (tools/screenshots vs baseline-screenshots). Replaces toHaveScreenshot, which did inline compare + its own baselines and had decoupled the specs from the real gate. scale:'css' pinned. - retries: 0 in both configs. - Guard: tests/tools/lint-determinism.ts (npm run lint:determinism) bans blind sleeps / toHaveScreenshot / inline retries / swallowed catches in specs; documented exceptions carry a marker. Rules in tests/TESTING.md. Assertions, coverage, and renders unchanged (semantic-equivalence reviewed; captures pixel-identical modulo inherent timer/timestamp/3d-raytrace variance). Both suites green at retries:0 (e2e 340, kicad 92); ~35-61% faster. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BVX1pHMvRPYHdp6ZfEawrk
2026-07-07 10:50:24 +02:00
/** Wait for a rendered popup menu to have its items (replaces a fixed post-menu-click sleep). */
async function waitForMenuItems(page: Page): Promise<void> {
await waitUntil(
page,
() => {
const r = window.wxElementRegistry;
if (!r?.findAllRendered) return false;
return r.findAllRendered({ elementType: 'menuitem' }).length > 3;
},
'popup menu items rendered',
);
}
/**
* 3D viewer COMPONENT MODELS e2e (docs/features/3d-models): load pic_programmer,
* open the 3D viewer, and verify the model-delivery machinery end to end at the
* KiCad/wasm level:
*
* 1. Statically linked format plugins (vrml + oce upstream loads them via
* dlopen, which wasm doesn't have) parse real model files.
* 2. Project-local models resolve exactly as upstream: the board references
* `${KIPRJMOD}/libs/3d_shapes/*.wrl`, injected with the project.
* 3. The lazy-fetch fallback (S3D_CACHE::load PCBJAM_3D::EnsureModelFile
* `kicadLibs.request("ensure", …, "model3d")`) asks JS for every
* `${KICAD*_3DMODEL_DIR}` ref, with the ref NORMALIZED to
* `<lib>.3dshapes/<name>.<ext>` and a served ref (the stub writes the
* bytes into MEMFS and answers "1") then resolves and renders.
*
* The stub provider stands in for the standalone's models-bridge (which fetches
* from the CDN into IDB); here it serves ONE in-repo STEP fixture under a
* board-referenced name geometry is a USB-C connector where a DIP-8 socket
* belongs, which is irrelevant: the assertion is parse+render, not fidelity.
*/
const KICAD_VERSION_DIR = '10.0';
const PROJECT_DIR_MEMFS = `/home/kicad/documents/kicad/${KICAD_VERSION_DIR}/projects`;
// The JS-owned MEMFS root the stub writes model bodies under — the same dir
// the standalone's models-bridge uses (constants.ts MODELS_3D_ROOT). Its exact
// location is immaterial: the ensure protocol answers with the ABSOLUTE path
// and S3D_CACHE loads it directly (env-var expansion never resolves
// ${KICAD*_3DMODEL_DIR} refs in the wasm runtime — see
// docs/features/3d-models/0001).
const MODELS_ROOT_MEMFS = '/pcbjam/3dmodels';
// The board ref the stub provider serves (normalized form the bridge must ask
// for), and the in-repo STEP whose bytes stand in for it.
const SERVED_REF = 'Package_DIP.3dshapes/DIP-8_W7.62mm.step';
const STEP_FIXTURE = 'kicad/demos/openair-max/Libraries/HRO_TYPE-C-31-M-12.step';
const DEMO = { name: 'pic_programmer', dir: 'pic_programmer', stem: 'pic_programmer' } as const;
declare global {
interface Window {
__modelEnsures?: Array<{ op: string; arg: string; kind: string }>;
__stepFixtureB64?: string;
}
}
/** Record every model3d bridge request; serve SERVED_REF from the fixture. */
async function installModelProviderStub(page: Page, serveAll = false): Promise<void> {
await page.evaluate(
({ stockDir, servedRef, serveAll }) => {
window.__modelEnsures = [];
(globalThis as any).kicadLibs = {
request: async (op: string, _lib: string, arg: string, kind: string) => {
if (kind !== 'model3d') return null;
window.__modelEnsures!.push({ op, arg, kind });
console.log(`[TEST-3D] ensure request: ${op} ${arg}`);
if (op !== 'ensure' || (!serveAll && arg !== servedRef)) return null;
const b64 = window.__stepFixtureB64!;
const binary = atob(b64);
const data = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) data[i] = binary.charCodeAt(i);
// Mirror models-bridge.ts ensureModelInMemfs: write under the
// JS-owned model root and answer with the ABSOLUTE path —
// S3D_CACHE loads it directly (no env-var expansion needed).
// @ts-expect-error — Emscripten FS lives on window
const FS = (window as any).FS;
const dest = `${stockDir}/${arg}`;
FS.mkdirTree(dest.slice(0, dest.lastIndexOf('/')));
FS.writeFile(dest, data);
console.log(`[TEST-3D] served ${arg}${dest} (${data.length} bytes)`);
return dest;
},
};
},
{ stockDir: MODELS_ROOT_MEMFS, servedRef: SERVED_REF, serveAll },
);
}
async function loadBoard(page: Page, testLogger: { consoleLogs: string[]; errors: string[] }): Promise<void> {
const pcbFilename = `${DEMO.stem}.kicad_pcb`;
const proFilename = `${DEMO.stem}.kicad_pro`;
await injectFromSubmodule(page, `kicad/demos/${DEMO.dir}/${pcbFilename}`,
`${PROJECT_DIR_MEMFS}/${pcbFilename}`);
await injectFromSubmodule(page, `kicad/demos/${DEMO.dir}/${proFilename}`,
`${PROJECT_DIR_MEMFS}/${proFilename}`);
// Project-local 3D models — the board references them as
// ${KIPRJMOD}/libs/3d_shapes/<name>.wrl; resolved by the stock resolver, so
// they must NOT go through the ensure bridge (asserted below).
await injectFromSubmodule(page, `kicad/demos/${DEMO.dir}/libs/3d_shapes/textool_40.wrl`,
`${PROJECT_DIR_MEMFS}/libs/3d_shapes/textool_40.wrl`);
await injectFromSubmodule(page, `kicad/demos/${DEMO.dir}/libs/3d_shapes/adjustable_rx2v4.wrl`,
`${PROJECT_DIR_MEMFS}/libs/3d_shapes/adjustable_rx2v4.wrl`);
expect(await clickMenuBarItem(page, 'File'), 'File menu should be findable').toBe(true);
test(determinism): deterministic waits + stableShot screenshots; drop blind sleeps/ifs/retries Make the Playwright e2e + kicad suites deterministic so screenshot flake stops tracing to timing races. - Blind page.waitForTimeout -> condition waits (expect.poll, web-first assertions, waitUntil) + readiness helpers (waitForWxApp, waitForCanvasApp). Remaining sleeps are documented interaction dwells (annotated). - Defensive "if element exists" branches -> loud asserts; label-fallback chains -> normalized clickMenuItemByText. First-run wizard for/if loops removed by seeding calculator/gerbview/pcbnew HTMLs. - Screenshots: new stableShot(page, name) settles the render in-page (canvas hash over rAF) then writes a raw PNG to test-results/ for the existing offline gate (tools/screenshots vs baseline-screenshots). Replaces toHaveScreenshot, which did inline compare + its own baselines and had decoupled the specs from the real gate. scale:'css' pinned. - retries: 0 in both configs. - Guard: tests/tools/lint-determinism.ts (npm run lint:determinism) bans blind sleeps / toHaveScreenshot / inline retries / swallowed catches in specs; documented exceptions carry a marker. Rules in tests/TESTING.md. Assertions, coverage, and renders unchanged (semantic-equivalence reviewed; captures pixel-identical modulo inherent timer/timestamp/3d-raytrace variance). Both suites green at retries:0 (e2e 340, kicad 92); ~35-61% faster. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BVX1pHMvRPYHdp6ZfEawrk
2026-07-07 10:50:24 +02:00
await waitForMenuItems(page);
e2e/CI: dual-engine suites, per-engine screenshots, SwiftShader retired, prod web suite, CI-coverage gate Squash of experiment/ff-big-modules vs main. Big-module routing removed: native-EH shrank kicad_editor below SpiderMonkey's x86-64 code budget (runs 29355049705/29356152413 green on stock Firefox), so BIG_MODULE_SPECS routing and the baseline-only-JIT crutch are gone — kicad-firefox and kicad-chromium both run the full suite, with the module compiled the way real users' browsers compile it. Per-engine screenshots end to end: stableShot/shotPath write test-results/<engine>/<name>.png; baselines move to baseline-screenshots/{chromium,firefox}/ and the whole tools/screenshots pipeline (compare/promote/manifest/spec-map/changelog/Discord) keys on <engine>/<name>. Previously Firefox and Chromium renders of one spec overwrote each other and Firefox renders were never actually gated. Seeded from CI run 29421380806 (92 new firefox baselines, +24 chromium web-suite shots); manifest generated from the baseline tree. One merged playwright.config.ts (kicad/asyncify/coroutine/perf as projects); ~25 dead npm scripts dropped. The web suite is gated in CI for the first time ever (4 rotted specs fixed, 5 broken lib-bridge specs triaged as fixme in docs/features/web-e2e-rot/); cheap lint step after npm ci; last 26 blind-sleep violations fixed. SwiftShader retired: CI Chromium renders WebGL on ANGLE → Mesa llvmpipe (--use-gl=angle --use-angle=gl --ignore-gpu-blocklist; the blocklist flag is mandatory — llvmpipe is blocklisted and WebGL is silently unavailable without it) in BOTH configs. Under WORKERS=4 congestion SwiftShader transiently failed the first post-board-load draw and the recovery cascade ended in a silent permanent Cairo fallback — that engine flip was the "~1.2% changedRatio both directions" occ-export baseline flake. Validated 160/160 across two 80-repeat rigs; full analysis in docs/features/wx-parity-bugs/occ-export-context-eviction.md. Chromium baselines shift slightly on llvmpipe — promote once from the first green run. Deflakes the new coverage exposed: presence baselines settle before capture; presence fixtures declare current file formats; perf gets its own outputDir so CI evidence survives; occ-export settles the board paint before the export dialog; menu-item waits (waitForRenderedByLabel before clickMenuItem) in 4 specs + the TESTING.md rule. Web suite runs the PROD build, in parallel: webServer becomes backend `start` + the standalone's e2e:preview (build-preview.mjs: link-wasm → stash the public/wasm symlink aside during vite build, build-demo.mjs's move — then vite preview as the persistent server). The wasm middleware serves /wasm/* in preview and emits COOP/COEP/CORP itself (a pthread worker script's own response must carry COEP or Chrome kills it with ERR_BLOCKED_BY_RESPONSE). VITE_* flags bake at build time; VITE_ALLOW_USER_OVERRIDE joins turbo globalEnv. fullyParallel + default workers: 5.2m → 1.4m. Determinism fixes the parallel run exposed: shared-page specs become serial groups; locks.spec grabs alice's exact item via the new kicadCollabTestSelectByUuid hook (cross-tab "first footprint" order is not a ysync invariant); quit specs poll page.url() (quit supersedes its own navigation — NS_BINDING_ABORTED on Firefox). Suite: 51 passed / 12 skipped / 0 failed in 1.6m. CI-coverage gate (lint:ci-coverage): every tests/**/*.spec.ts must be reachable from the npm scripts the workflows invoke — scraped from .github/workflows/, resolved through package.json, coverage asked from playwright --list itself. Rules: uncovered-spec + orphan-project (with a documented LOCAL_ONLY_PROJECTS allowlist). Gating next to lint:determinism; 138 spec files / 13 projects accounted for. Product fixes kept from the investigations (reachable on real GPUs too): wx 7799fd1be5 — paint flags clear before dispatch + Invalidate always propagates; kicad 3dcfea5e45 — SwiftShader pass-boundary flush + per-instance font texture + first-frame GL-error drain (GAL recovery recovers instead of falling back to Cairo) + the user-facing eeschema switch navigates again under __EMSCRIPTEN__ (project-sync's FaceRegistered gate had rerouted it into the hidden sync player; caught by the newly-gated web suite). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018eUxiPApHgGiu9NFyQfhAq
2026-07-17 12:10:40 +02:00
// Items register progressively while the popup paints — wait for the one
// we click (clickMenuItem is single-shot; the >3-items gate isn't enough).
await waitForRenderedByLabel(page, 'Open...', { elementType: 'menuitem' });
expect(await clickMenuItem(page, 'Open...'), 'Open… menu item should be findable').toBe(true);
await page.waitForFunction(() => {
const registry = window.wxElementRegistry;
return !!registry && registry.findAll({ visible: true })
.some((el) => el.typeName === 'wxFileDialog');
}, null, { timeout: 15000 });
test(determinism): deterministic waits + stableShot screenshots; drop blind sleeps/ifs/retries Make the Playwright e2e + kicad suites deterministic so screenshot flake stops tracing to timing races. - Blind page.waitForTimeout -> condition waits (expect.poll, web-first assertions, waitUntil) + readiness helpers (waitForWxApp, waitForCanvasApp). Remaining sleeps are documented interaction dwells (annotated). - Defensive "if element exists" branches -> loud asserts; label-fallback chains -> normalized clickMenuItemByText. First-run wizard for/if loops removed by seeding calculator/gerbview/pcbnew HTMLs. - Screenshots: new stableShot(page, name) settles the render in-page (canvas hash over rAF) then writes a raw PNG to test-results/ for the existing offline gate (tools/screenshots vs baseline-screenshots). Replaces toHaveScreenshot, which did inline compare + its own baselines and had decoupled the specs from the real gate. scale:'css' pinned. - retries: 0 in both configs. - Guard: tests/tools/lint-determinism.ts (npm run lint:determinism) bans blind sleeps / toHaveScreenshot / inline retries / swallowed catches in specs; documented exceptions carry a marker. Rules in tests/TESTING.md. Assertions, coverage, and renders unchanged (semantic-equivalence reviewed; captures pixel-identical modulo inherent timer/timestamp/3d-raytrace variance). Both suites green at retries:0 (e2e 340, kicad 92); ~35-61% faster. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BVX1pHMvRPYHdp6ZfEawrk
2026-07-07 10:50:24 +02:00
// Wait for the filename text input to paint (replaces a fixed 1000ms).
await waitUntil(page, () => {
const r = window.wxElementRegistry;
return !!r && r.findAll({ visible: true }).some((el) => el.typeName === 'wxTextCtrl' && el.name === 'text');
}, 'file dialog filename input');
const filenameInput = await page.evaluate(() => {
const registry = window.wxElementRegistry;
if (!registry) return null;
const text = registry.findAll({ visible: true })
.find((el) => el.typeName === 'wxTextCtrl' && el.name === 'text');
return text ? { x: text.centerX, y: text.centerY } : null;
});
expect(filenameInput, 'filename text input should be visible').not.toBeNull();
if (!filenameInput) throw new Error('filename text input not found');
await page.mouse.click(filenameInput.x, filenameInput.y);
test(determinism): deterministic waits + stableShot screenshots; drop blind sleeps/ifs/retries Make the Playwright e2e + kicad suites deterministic so screenshot flake stops tracing to timing races. - Blind page.waitForTimeout -> condition waits (expect.poll, web-first assertions, waitUntil) + readiness helpers (waitForWxApp, waitForCanvasApp). Remaining sleeps are documented interaction dwells (annotated). - Defensive "if element exists" branches -> loud asserts; label-fallback chains -> normalized clickMenuItemByText. First-run wizard for/if loops removed by seeding calculator/gerbview/pcbnew HTMLs. - Screenshots: new stableShot(page, name) settles the render in-page (canvas hash over rAF) then writes a raw PNG to test-results/ for the existing offline gate (tools/screenshots vs baseline-screenshots). Replaces toHaveScreenshot, which did inline compare + its own baselines and had decoupled the specs from the real gate. scale:'css' pinned. - retries: 0 in both configs. - Guard: tests/tools/lint-determinism.ts (npm run lint:determinism) bans blind sleeps / toHaveScreenshot / inline retries / swallowed catches in specs; documented exceptions carry a marker. Rules in tests/TESTING.md. Assertions, coverage, and renders unchanged (semantic-equivalence reviewed; captures pixel-identical modulo inherent timer/timestamp/3d-raytrace variance). Both suites green at retries:0 (e2e 340, kicad 92); ~35-61% faster. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BVX1pHMvRPYHdp6ZfEawrk
2026-07-07 10:50:24 +02:00
// Documented interaction dwells: focus + typed-text registration have no observable signal.
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
await page.waitForTimeout(200); // eslint-disable-line -- documented interaction dwell: focus registration has no observable signal
await page.keyboard.type(pcbFilename);
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
await page.waitForTimeout(300); // eslint-disable-line -- documented interaction dwell: typed-text registration has no observable signal
await page.keyboard.press('Enter');
const result = await waitForBoardLoaded(page, testLogger, 60000);
console.log(`[TEST] ${DEMO.name} board-ready result: ${result}`);
}
function countGlCanvases(page: Page): Promise<number> {
return page.evaluate(() => document.querySelectorAll('canvas[id^="glcanvas-"]').length);
}
async function openThreeDViewer(page: Page, glBefore: number): Promise<number> {
test(determinism): deterministic waits + stableShot screenshots; drop blind sleeps/ifs/retries Make the Playwright e2e + kicad suites deterministic so screenshot flake stops tracing to timing races. - Blind page.waitForTimeout -> condition waits (expect.poll, web-first assertions, waitUntil) + readiness helpers (waitForWxApp, waitForCanvasApp). Remaining sleeps are documented interaction dwells (annotated). - Defensive "if element exists" branches -> loud asserts; label-fallback chains -> normalized clickMenuItemByText. First-run wizard for/if loops removed by seeding calculator/gerbview/pcbnew HTMLs. - Screenshots: new stableShot(page, name) settles the render in-page (canvas hash over rAF) then writes a raw PNG to test-results/ for the existing offline gate (tools/screenshots vs baseline-screenshots). Replaces toHaveScreenshot, which did inline compare + its own baselines and had decoupled the specs from the real gate. scale:'css' pinned. - retries: 0 in both configs. - Guard: tests/tools/lint-determinism.ts (npm run lint:determinism) bans blind sleeps / toHaveScreenshot / inline retries / swallowed catches in specs; documented exceptions carry a marker. Rules in tests/TESTING.md. Assertions, coverage, and renders unchanged (semantic-equivalence reviewed; captures pixel-identical modulo inherent timer/timestamp/3d-raytrace variance). Both suites green at retries:0 (e2e 340, kicad 92); ~35-61% faster. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BVX1pHMvRPYHdp6ZfEawrk
2026-07-07 10:50:24 +02:00
// Open View → 3D Viewer deterministically; assert the menu path (an Alt+3 fallback
// would mask a real menu regression).
expect(await clickMenuBarItem(page, 'View'), 'View menu should be findable').toBe(true);
await clickMenuItemByText(page, '3D Viewer');
fix(ci): 3D specs back to headless SwiftShader + GPU hardening; skip real-GPU drags on CI and the models render tail everywhere (product bug) The headed Mesa-llvmpipe switch (ce44636) was built on a misdiagnosis. With --use-gl=angle --use-angle=gl under Xvfb, Chromium gets NO WebGL AT ALL on the GPU-less CI VM: runs 28652367347 + 28664038296 both log `glcanvas count before opening 3D viewer: 0` (even the pcbnew board's own GAL canvas fails to create) and every failure is the FIRST viewer-open wait timing out. "Timeouts instead of crashes" meant no GL context existed to crash, not that llvmpipe was stable-but-slow. The Mesa/GLX path works for the Firefox project, but not for Chromium on this image. Headless SwiftShader is the environment where GL provably works — the serialized run 28649537489 opened the viewer and rendered/sampled 56 colours (viewer:26/130/209 all passed single-tab). Its remaining failures split into two families, each addressed on its own evidence: 1) SwiftShader GPU-process kills (deadlock spec's lost canvas/black frame): - chromium-ci-3d back to headless + --enable-unsafe-swiftshader, plus --disable-gpu-watchdog and --disable-gpu-process-crash-limit: heavy churn stalls the software-GL GPU process until the watchdog shoots it (CONTEXT_LOST -> removed GL canvas -> "Target crashed"); with the watchdog off a slow op completes, and without the crash limit a lost GPU process keeps restarting for later tests. Same args locally (no-ops on a healthy real GPU). - Storm-proof every canvas sampler (3d-viewer, models, deadlock specs): one full-frame getImageData on a willReadFrequently (CPU-backed) 2D canvas + JS grid sampling, replacing 256 per-pixel getImageData GPU round-trips per sample — the "GPU stall due to ReadPixels" trigger, worst in the deadlock spec's 1.5s-interval settle polling. Sampled pixels and sig order are unchanged. - edge-resize spec: keep the open + 5-resize-handles assertions on CI, then test.skip the drag — each resize step re-raytraces synchronously on the wasm main thread and the 12-step drag blocked mouse.move past the 240s budget even single-tab. Real-GPU-paced; still runs locally (deadlock spec's CI-skip from d9900fe unchanged, same rationale). 2) KNOWN PRODUCT BUG uncovered in the models spec (NOT SwiftShader, NOT CI): raytracing a scene WITH component models kills the Chromium renderer process outright ~6s after scene build — silent process death with a FLAT wasm heap (531-637 MB watched at 2s intervals; not OOM), no console error, no wasm abort, no crash report. Deterministic on a real GPU (5/5), fixture-independent (700 KB USB-C and 61 KB USON-8 STEP crash identically); the same death hits CI SwiftShader at ~66s. Board-only raytraces complete and stay alive, so the bug is specific to the model path. The spec's one historical green ended at raytrace-age ~6s — inside the death window by luck; every CI run of it ever died. Fix here: front-load the bridge assertions (ensure requests fire during scene BUILD, before the raytrace), so protocol regressions still fail the suite everywhere, and test.skip the render tail unconditionally with the bug documented at the skip site. The raytrace->blit pipeline stays gated on CI by 3d-viewer.spec's board-only render. Bug tracked for a dedicated fix session. Correct the now-wrong llvmpipe comments (config, open-wait rationale, deadlock skip reason). Expected CI matrix: viewer open/render/stacking/titlebar + models-bridge on SwiftShader serial; edge-resize drag + camera-move deadlock on real GPUs locally; the Worker-boot deadlock mechanism stays covered on CI by the standalone wx harnesses. Locally validated on a real GPU (--project=chromium): 5 passed + 1 skipped (the documented models render tail). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 10:40:40 +02:00
// 180s (not 60s): CI headroom for the scene build + first raytrace on software WebGL
// (real GPU ~2s). See threed-viewer.ts openThreeDViewer for the rationale.
await page.waitForFunction(() => {
return !!document.querySelector('#window-container [id^="window-"]')
|| document.querySelectorAll('canvas[id^="glcanvas-"]').length > 0;
}, null, { timeout: 180000 });
await page.waitForFunction((before: number) =>
document.querySelectorAll('canvas[id^="glcanvas-"]').length > before,
glBefore, { timeout: 180000 });
const glAfter = await countGlCanvases(page);
console.log(`[TEST] glcanvas count after opening 3D viewer: ${glAfter}`);
expect(glAfter, 'a new WebGL canvas should appear for the 3D viewer').toBeGreaterThan(glBefore);
return glAfter;
}
test.describe('3D viewer component models', () => {
test.describe.configure({ mode: 'serial' });
test.setTimeout(240000);
test('resolves project models, lazy-fetches lib models via the bridge, renders', async ({ page, testLogger }) => {
await page.goto('/kicad/pcbnew.html');
test(determinism): deterministic waits + stableShot screenshots; drop blind sleeps/ifs/retries Make the Playwright e2e + kicad suites deterministic so screenshot flake stops tracing to timing races. - Blind page.waitForTimeout -> condition waits (expect.poll, web-first assertions, waitUntil) + readiness helpers (waitForWxApp, waitForCanvasApp). Remaining sleeps are documented interaction dwells (annotated). - Defensive "if element exists" branches -> loud asserts; label-fallback chains -> normalized clickMenuItemByText. First-run wizard for/if loops removed by seeding calculator/gerbview/pcbnew HTMLs. - Screenshots: new stableShot(page, name) settles the render in-page (canvas hash over rAF) then writes a raw PNG to test-results/ for the existing offline gate (tools/screenshots vs baseline-screenshots). Replaces toHaveScreenshot, which did inline compare + its own baselines and had decoupled the specs from the real gate. scale:'css' pinned. - retries: 0 in both configs. - Guard: tests/tools/lint-determinism.ts (npm run lint:determinism) bans blind sleeps / toHaveScreenshot / inline retries / swallowed catches in specs; documented exceptions carry a marker. Rules in tests/TESTING.md. Assertions, coverage, and renders unchanged (semantic-equivalence reviewed; captures pixel-identical modulo inherent timer/timestamp/3d-raytrace variance). Both suites green at retries:0 (e2e 340, kicad 92); ~35-61% faster. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BVX1pHMvRPYHdp6ZfEawrk
2026-07-07 10:50:24 +02:00
await waitForEditorReady(page);
// Stash the STEP fixture bytes + install the provider stub BEFORE the
// viewer can issue any ensure request.
const fs = require('fs') as typeof import('fs');
const path = require('path') as typeof import('path');
const fixtureAbs = path.resolve(__dirname, '..', '..', STEP_FIXTURE);
await page.evaluate(
(b64: string) => { window.__stepFixtureB64 = b64; },
fs.readFileSync(fixtureAbs).toString('base64'),
);
await installModelProviderStub(page);
feat(wasm): occ-split — lazy occ_service worker; kicad_editor drops OCC (−31%) Move OpenCASCADE out of the merged editor image into occ_service: a separate emscripten module (-sASYNCIFY=0, MODULARIZE, in-container -Oz finalize, 2N+8 pre-warmed pthread pool) booted lazily in a dedicated Web Worker on the first STEP export or STEP/IGES model parse. kicad_editor.wasm ~190 MB -> 130 MB; sessions that never touch OCC never fetch its 57 MB. STEP export works in the browser for the first time: the unchanged desktop dialog runs EXPORTER_STEP, whose wasm shadow suspends into globalThis.occService and the export bytes go straight to a browser download (never entering the editor heap). STEP/IGES 3D models parse in the worker via the oce shadow (S3D WriteCache/ReadCache wire). - wasm/occ-service/: service CMake target (hooked from the kicad fork's top-level CMakeLists, wasm/editor pattern), embind entry (occExport/occLoadModel), wxConfig pre-js. - wasm/stubs/{exporter_step,oce_plugin}_stub.cpp: EM_ASYNC_JS worker bridges (callee-shadowing; no caller #ifdefs). - web/standalone: provider installed whenever the kicad_editor bundle boots (cross-face safe); ONE shared worker-boot source occ-worker.js (vite ?raw; the e2e stub reads the same file) — blob worker with locateFile absolutized against the glue URL; export download-name guard. - deps: OCC builds with RapidJSON so its glTF/GLB writer exists — pinned to the vcpkg master snapshot 2025-02-26 (24b5e7a8b27f), the same code official KiCad consumes via vcpkg.json's opencascade[rapidjson]; rapidjson's latest tag (v1.1.0, 2016) is ill-formed under modern clang. - tests: occ-export dialog e2e (lazy-fetch boundary + STEP download bytes), occ-probe incl. a 9-format matrix (step/stpz/brep/xao/ply/stl/glb/u3d/pdf), 3d-viewer-models hard-asserts the worker parse; occ provider stub installed ambiently by the kicad fixtures. Validated against desktop kicad-cli 10.0.4: geometric exact equality (bbox delta 0 um, volume delta 0.0000%) for STEP/GLB/STL/BREP/STPZ across three boards and option sweeps — with desktop OCC 7.9 vs wasm OCC 7.8; PLY/XAO/PDF structurally equal; U3D same-size (quantizer float LSBs differ). Full kicad e2e green on Firefox and Chromium; standalone verified end to end (lazy fetch only on the Export click; export.step 60,628 B ISO-10303-21; loadModel 700 KB STEP -> 569 KB scenegraph cache). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 12:39:58 +02:00
// (.step models parse in the occ_service worker — the oce3d_Load shadow
// suspends on globalThis.occService, installed ambiently by fixtures.)
await loadBoard(page, testLogger);
const glBefore = await countGlCanvases(page);
await openThreeDViewer(page, glBefore);
fix(e2e): rescope the 3D fixes for the webgl-era viewer (rebased onto main) The 3d-webgl merge (kicad eb13ff3bdc: the viewer now defaults to the real OpenGL renderer via wasm/gl1, and occ-split moves STEP parsing into the occ_service worker) made the raytracer-era orchestration on this branch moot — main's chromium-ci phase is green at 15-way parallelism (28666407570 / 28698861536). Drop what no longer earns its complexity, keep the diagnostics, fix main's live flake, and make the deadlock spec test what it was written for. - REVERT the chromium-ci-3d serial project, the two-phase test:kicad:ci, the SwiftShader GPU-process flags, and the resize-drag/models skips: config and package.json are byte-for-byte back to main's shape. The raytracer contention they guarded is no longer on the CI path. - FIX main's live flake: run 28698861536 is green only via retry (3d-viewer.spec:26 flaky) and 28666407570's deadlock red sampled an ALL-ZERO pixel signature — the viewer's first frame lags the canvas's creation on software WebGL under parallel load, and sampling too early reads an all-black backbuffer. New waitForThreeDRender() gates render assertions on actual pixels (1s-interval full-frame CPU reads) instead of fixed sleeps, used by 3d-viewer.spec:26 and the models render tail. - KEEP the storm-proofed samplers (one full-frame getImageData on a willReadFrequently canvas replacing 256 per-pixel GPU round-trips per sample — the "GPU stall due to ReadPixels" trigger) and the logThreeDDiag instrumentation: engine-independent, and they de-risk every remaining software-GL pixel read. - models spec: bridge assertions stay front-loaded (the protocol regression signal is independent of the render); the occ_service parse verdict is now POLLED — it lands async relative to the bridge ensures, so asserting it immediately raced the worker; the render tail runs again everywhere. (The pre-webgl raytracer+models renderer-death documented in a17f3be does not affect the OpenGL default path — the raytracer-toggle+models combination remains untested product surface, tracked outside this branch.) - deadlock spec: the deadlock it guards is raytracer-specific and the viewer now defaults to OpenGL — on the GL engine it either passes vacuously (fast renders make every liveness assertion trivial, 28698861536) or fails on the black first frame (28666407570). It now flips the engine via the "Use raytracing" toolbar toggle (loud assert if the toggle moved) and cross-checks engagement by requiring the canvas pixels to CHANGE after the flip with no input in between (the raytraced frame is lit differently; a GL re-render reproduces identical pixels; heap growth is unusable — mimalloc satisfies the raytracer from freed arena pages). That guard immediately caught a REAL defect: on the webgl-era wasm build the toggle is INERT (the click lands and "Reload time" updates, but the canvas never changes — suspects: DoRePaint's silent catch(runtime_error) freezing the canvas after a raytracer Redraw throw, or ToggleRaytracing writing m_boardAdapter.m_Cfg while RenderEngineChanged() reads GetAppSettings<…>(), possibly different instances in the merged bundle). The spec is therefore test.skip-annotated as a KNOWN ISSUE with the full engine-force machinery in place — unskipping it self-validates the product fix. The CI-skip also stays (raytracer liveness needs real-GPU pacing; the Worker-boot deadlock mechanism is covered on CI by the standalone wx harnesses). - 180s viewer-open waits kept as pure CI headroom (never slow a passing run). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 11:37:27 +02:00
// The ensure requests fire during the scene BUILD (S3D_CACHE::load), i.e. BEFORE any
// rendering — wait for the served ref to cross the bridge, then give the rest of the
// enumeration a moment to flush. Front-loading the bridge assertions keeps the
// protocol regression signal independent of the render below.
fix(ci): 3D specs back to headless SwiftShader + GPU hardening; skip real-GPU drags on CI and the models render tail everywhere (product bug) The headed Mesa-llvmpipe switch (ce44636) was built on a misdiagnosis. With --use-gl=angle --use-angle=gl under Xvfb, Chromium gets NO WebGL AT ALL on the GPU-less CI VM: runs 28652367347 + 28664038296 both log `glcanvas count before opening 3D viewer: 0` (even the pcbnew board's own GAL canvas fails to create) and every failure is the FIRST viewer-open wait timing out. "Timeouts instead of crashes" meant no GL context existed to crash, not that llvmpipe was stable-but-slow. The Mesa/GLX path works for the Firefox project, but not for Chromium on this image. Headless SwiftShader is the environment where GL provably works — the serialized run 28649537489 opened the viewer and rendered/sampled 56 colours (viewer:26/130/209 all passed single-tab). Its remaining failures split into two families, each addressed on its own evidence: 1) SwiftShader GPU-process kills (deadlock spec's lost canvas/black frame): - chromium-ci-3d back to headless + --enable-unsafe-swiftshader, plus --disable-gpu-watchdog and --disable-gpu-process-crash-limit: heavy churn stalls the software-GL GPU process until the watchdog shoots it (CONTEXT_LOST -> removed GL canvas -> "Target crashed"); with the watchdog off a slow op completes, and without the crash limit a lost GPU process keeps restarting for later tests. Same args locally (no-ops on a healthy real GPU). - Storm-proof every canvas sampler (3d-viewer, models, deadlock specs): one full-frame getImageData on a willReadFrequently (CPU-backed) 2D canvas + JS grid sampling, replacing 256 per-pixel getImageData GPU round-trips per sample — the "GPU stall due to ReadPixels" trigger, worst in the deadlock spec's 1.5s-interval settle polling. Sampled pixels and sig order are unchanged. - edge-resize spec: keep the open + 5-resize-handles assertions on CI, then test.skip the drag — each resize step re-raytraces synchronously on the wasm main thread and the 12-step drag blocked mouse.move past the 240s budget even single-tab. Real-GPU-paced; still runs locally (deadlock spec's CI-skip from d9900fe unchanged, same rationale). 2) KNOWN PRODUCT BUG uncovered in the models spec (NOT SwiftShader, NOT CI): raytracing a scene WITH component models kills the Chromium renderer process outright ~6s after scene build — silent process death with a FLAT wasm heap (531-637 MB watched at 2s intervals; not OOM), no console error, no wasm abort, no crash report. Deterministic on a real GPU (5/5), fixture-independent (700 KB USB-C and 61 KB USON-8 STEP crash identically); the same death hits CI SwiftShader at ~66s. Board-only raytraces complete and stay alive, so the bug is specific to the model path. The spec's one historical green ended at raytrace-age ~6s — inside the death window by luck; every CI run of it ever died. Fix here: front-load the bridge assertions (ensure requests fire during scene BUILD, before the raytrace), so protocol regressions still fail the suite everywhere, and test.skip the render tail unconditionally with the bug documented at the skip site. The raytrace->blit pipeline stays gated on CI by 3d-viewer.spec's board-only render. Bug tracked for a dedicated fix session. Correct the now-wrong llvmpipe comments (config, open-wait rationale, deadlock skip reason). Expected CI matrix: viewer open/render/stacking/titlebar + models-bridge on SwiftShader serial; edge-resize drag + camera-move deadlock on real GPUs locally; the Worker-boot deadlock mechanism stays covered on CI by the standalone wx harnesses. Locally validated on a real GPU (--project=chromium): 5 passed + 1 skipped (the documented models render tail). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 10:40:40 +02:00
await page.waitForFunction(
(ref: string) => (window.__modelEnsures ?? []).some((e) => e.arg === ref),
SERVED_REF, { timeout: 120000 });
test(determinism): deterministic waits + stableShot screenshots; drop blind sleeps/ifs/retries Make the Playwright e2e + kicad suites deterministic so screenshot flake stops tracing to timing races. - Blind page.waitForTimeout -> condition waits (expect.poll, web-first assertions, waitUntil) + readiness helpers (waitForWxApp, waitForCanvasApp). Remaining sleeps are documented interaction dwells (annotated). - Defensive "if element exists" branches -> loud asserts; label-fallback chains -> normalized clickMenuItemByText. First-run wizard for/if loops removed by seeding calculator/gerbview/pcbnew HTMLs. - Screenshots: new stableShot(page, name) settles the render in-page (canvas hash over rAF) then writes a raw PNG to test-results/ for the existing offline gate (tools/screenshots vs baseline-screenshots). Replaces toHaveScreenshot, which did inline compare + its own baselines and had decoupled the specs from the real gate. scale:'css' pinned. - retries: 0 in both configs. - Guard: tests/tools/lint-determinism.ts (npm run lint:determinism) bans blind sleeps / toHaveScreenshot / inline retries / swallowed catches in specs; documented exceptions carry a marker. Rules in tests/TESTING.md. Assertions, coverage, and renders unchanged (semantic-equivalence reviewed; captures pixel-identical modulo inherent timer/timestamp/3d-raytrace variance). Both suites green at retries:0 (e2e 340, kicad 92); ~35-61% faster. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BVX1pHMvRPYHdp6ZfEawrk
2026-07-07 10:50:24 +02:00
// Let the rest of the model-enumeration ensures flush after the served ref lands —
// the total count isn't known up front, so this is a documented settle interval.
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
await page.waitForTimeout(3000); // eslint-disable-line -- documented interaction dwell: model-enumeration ensures flush; total count unknown up front
fix(ci): 3D specs back to headless SwiftShader + GPU hardening; skip real-GPU drags on CI and the models render tail everywhere (product bug) The headed Mesa-llvmpipe switch (ce44636) was built on a misdiagnosis. With --use-gl=angle --use-angle=gl under Xvfb, Chromium gets NO WebGL AT ALL on the GPU-less CI VM: runs 28652367347 + 28664038296 both log `glcanvas count before opening 3D viewer: 0` (even the pcbnew board's own GAL canvas fails to create) and every failure is the FIRST viewer-open wait timing out. "Timeouts instead of crashes" meant no GL context existed to crash, not that llvmpipe was stable-but-slow. The Mesa/GLX path works for the Firefox project, but not for Chromium on this image. Headless SwiftShader is the environment where GL provably works — the serialized run 28649537489 opened the viewer and rendered/sampled 56 colours (viewer:26/130/209 all passed single-tab). Its remaining failures split into two families, each addressed on its own evidence: 1) SwiftShader GPU-process kills (deadlock spec's lost canvas/black frame): - chromium-ci-3d back to headless + --enable-unsafe-swiftshader, plus --disable-gpu-watchdog and --disable-gpu-process-crash-limit: heavy churn stalls the software-GL GPU process until the watchdog shoots it (CONTEXT_LOST -> removed GL canvas -> "Target crashed"); with the watchdog off a slow op completes, and without the crash limit a lost GPU process keeps restarting for later tests. Same args locally (no-ops on a healthy real GPU). - Storm-proof every canvas sampler (3d-viewer, models, deadlock specs): one full-frame getImageData on a willReadFrequently (CPU-backed) 2D canvas + JS grid sampling, replacing 256 per-pixel getImageData GPU round-trips per sample — the "GPU stall due to ReadPixels" trigger, worst in the deadlock spec's 1.5s-interval settle polling. Sampled pixels and sig order are unchanged. - edge-resize spec: keep the open + 5-resize-handles assertions on CI, then test.skip the drag — each resize step re-raytraces synchronously on the wasm main thread and the 12-step drag blocked mouse.move past the 240s budget even single-tab. Real-GPU-paced; still runs locally (deadlock spec's CI-skip from d9900fe unchanged, same rationale). 2) KNOWN PRODUCT BUG uncovered in the models spec (NOT SwiftShader, NOT CI): raytracing a scene WITH component models kills the Chromium renderer process outright ~6s after scene build — silent process death with a FLAT wasm heap (531-637 MB watched at 2s intervals; not OOM), no console error, no wasm abort, no crash report. Deterministic on a real GPU (5/5), fixture-independent (700 KB USB-C and 61 KB USON-8 STEP crash identically); the same death hits CI SwiftShader at ~66s. Board-only raytraces complete and stay alive, so the bug is specific to the model path. The spec's one historical green ended at raytrace-age ~6s — inside the death window by luck; every CI run of it ever died. Fix here: front-load the bridge assertions (ensure requests fire during scene BUILD, before the raytrace), so protocol regressions still fail the suite everywhere, and test.skip the render tail unconditionally with the bug documented at the skip site. The raytrace->blit pipeline stays gated on CI by 3d-viewer.spec's board-only render. Bug tracked for a dedicated fix session. Correct the now-wrong llvmpipe comments (config, open-wait rationale, deadlock skip reason). Expected CI matrix: viewer open/render/stacking/titlebar + models-bridge on SwiftShader serial; edge-resize drag + camera-move deadlock on real GPUs locally; the Worker-boot deadlock mechanism stays covered on CI by the standalone wx harnesses. Locally validated on a real GPU (--project=chromium): 5 passed + 1 skipped (the documented models render tail). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 10:40:40 +02:00
// --- bridge assertions (run on CI too) ---------------------------------
const ensures = await page.evaluate(() => window.__modelEnsures ?? []);
console.log(`[TEST] ensure requests: ${ensures.length}`);
for (const e of ensures.slice(0, 30)) console.log(`[TEST] ${e.op} ${e.arg}`);
// Every ${KICAD*_3DMODEL_DIR} ref crossed the bridge, normalized.
const args = ensures.map((e) => e.arg);
expect(args, 'the served lib ref must cross the bridge normalized')
.toContain(SERVED_REF);
expect(args.every((a) => /^[^/${]+\.3dshapes\//.test(a)),
'every bridge ref is a normalized <lib>.3dshapes/<file> path').toBe(true);
// Project-local (${KIPRJMOD}) models resolve natively — never bridged.
expect(args.some((a) => a.includes('textool_40') || a.includes('adjustable_rx2v4')),
'project-local models must not go through the ensure bridge').toBe(false);
// Board refs are unique per model file — the C++ memo must not re-ask.
expect(new Set(args).size, 'ensure requests are deduplicated').toBe(args.length);
// The served model landed in MEMFS where the resolver looks.
const servedSize = await page.evaluate(
({ stockDir, servedRef }) => {
// @ts-expect-error — Emscripten FS lives on window
const FS = (window as any).FS;
try { return FS.stat(`${stockDir}/${servedRef}`).size as number; }
catch { return -1; }
},
{ stockDir: MODELS_ROOT_MEMFS, servedRef: SERVED_REF },
);
expect(servedSize, 'served STEP written into the model root').toBeGreaterThan(1000);
feat(wasm): occ-split — lazy occ_service worker; kicad_editor drops OCC (−31%) Move OpenCASCADE out of the merged editor image into occ_service: a separate emscripten module (-sASYNCIFY=0, MODULARIZE, in-container -Oz finalize, 2N+8 pre-warmed pthread pool) booted lazily in a dedicated Web Worker on the first STEP export or STEP/IGES model parse. kicad_editor.wasm ~190 MB -> 130 MB; sessions that never touch OCC never fetch its 57 MB. STEP export works in the browser for the first time: the unchanged desktop dialog runs EXPORTER_STEP, whose wasm shadow suspends into globalThis.occService and the export bytes go straight to a browser download (never entering the editor heap). STEP/IGES 3D models parse in the worker via the oce shadow (S3D WriteCache/ReadCache wire). - wasm/occ-service/: service CMake target (hooked from the kicad fork's top-level CMakeLists, wasm/editor pattern), embind entry (occExport/occLoadModel), wxConfig pre-js. - wasm/stubs/{exporter_step,oce_plugin}_stub.cpp: EM_ASYNC_JS worker bridges (callee-shadowing; no caller #ifdefs). - web/standalone: provider installed whenever the kicad_editor bundle boots (cross-face safe); ONE shared worker-boot source occ-worker.js (vite ?raw; the e2e stub reads the same file) — blob worker with locateFile absolutized against the glue URL; export download-name guard. - deps: OCC builds with RapidJSON so its glTF/GLB writer exists — pinned to the vcpkg master snapshot 2025-02-26 (24b5e7a8b27f), the same code official KiCad consumes via vcpkg.json's opencascade[rapidjson]; rapidjson's latest tag (v1.1.0, 2016) is ill-formed under modern clang. - tests: occ-export dialog e2e (lazy-fetch boundary + STEP download bytes), occ-probe incl. a 9-format matrix (step/stpz/brep/xao/ply/stl/glb/u3d/pdf), 3d-viewer-models hard-asserts the worker parse; occ provider stub installed ambiently by the kicad fixtures. Validated against desktop kicad-cli 10.0.4: geometric exact equality (bbox delta 0 um, volume delta 0.0000%) for STEP/GLB/STL/BREP/STPZ across three boards and option sweeps — with desktop OCC 7.9 vs wasm OCC 7.8; PLY/XAO/PDF structurally equal; U3D same-size (quantizer float LSBs differ). Full kicad e2e green on Firefox and Chromium; standalone verified end to end (lazy fetch only on the Export click; export.step 60,628 B ISO-10303-21; loadModel 700 KB STEP -> 569 KB scenegraph cache). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 12:39:58 +02:00
// OCC split: the .step parse runs in the occ_service worker (the oce3d
// shadow bridges to it) and must SUCCEED — a boot/bridge failure logs
// 'oce Load FAILED' and silently skips the model, which the render
fix(e2e): rescope the 3D fixes for the webgl-era viewer (rebased onto main) The 3d-webgl merge (kicad eb13ff3bdc: the viewer now defaults to the real OpenGL renderer via wasm/gl1, and occ-split moves STEP parsing into the occ_service worker) made the raytracer-era orchestration on this branch moot — main's chromium-ci phase is green at 15-way parallelism (28666407570 / 28698861536). Drop what no longer earns its complexity, keep the diagnostics, fix main's live flake, and make the deadlock spec test what it was written for. - REVERT the chromium-ci-3d serial project, the two-phase test:kicad:ci, the SwiftShader GPU-process flags, and the resize-drag/models skips: config and package.json are byte-for-byte back to main's shape. The raytracer contention they guarded is no longer on the CI path. - FIX main's live flake: run 28698861536 is green only via retry (3d-viewer.spec:26 flaky) and 28666407570's deadlock red sampled an ALL-ZERO pixel signature — the viewer's first frame lags the canvas's creation on software WebGL under parallel load, and sampling too early reads an all-black backbuffer. New waitForThreeDRender() gates render assertions on actual pixels (1s-interval full-frame CPU reads) instead of fixed sleeps, used by 3d-viewer.spec:26 and the models render tail. - KEEP the storm-proofed samplers (one full-frame getImageData on a willReadFrequently canvas replacing 256 per-pixel GPU round-trips per sample — the "GPU stall due to ReadPixels" trigger) and the logThreeDDiag instrumentation: engine-independent, and they de-risk every remaining software-GL pixel read. - models spec: bridge assertions stay front-loaded (the protocol regression signal is independent of the render); the occ_service parse verdict is now POLLED — it lands async relative to the bridge ensures, so asserting it immediately raced the worker; the render tail runs again everywhere. (The pre-webgl raytracer+models renderer-death documented in a17f3be does not affect the OpenGL default path — the raytracer-toggle+models combination remains untested product surface, tracked outside this branch.) - deadlock spec: the deadlock it guards is raytracer-specific and the viewer now defaults to OpenGL — on the GL engine it either passes vacuously (fast renders make every liveness assertion trivial, 28698861536) or fails on the black first frame (28666407570). It now flips the engine via the "Use raytracing" toolbar toggle (loud assert if the toggle moved) and cross-checks engagement by requiring the canvas pixels to CHANGE after the flip with no input in between (the raytraced frame is lit differently; a GL re-render reproduces identical pixels; heap growth is unusable — mimalloc satisfies the raytracer from freed arena pages). That guard immediately caught a REAL defect: on the webgl-era wasm build the toggle is INERT (the click lands and "Reload time" updates, but the canvas never changes — suspects: DoRePaint's silent catch(runtime_error) freezing the canvas after a raytracer Redraw throw, or ToggleRaytracing writing m_boardAdapter.m_Cfg while RenderEngineChanged() reads GetAppSettings<…>(), possibly different instances in the merged bundle). The spec is therefore test.skip-annotated as a KNOWN ISSUE with the full engine-force machinery in place — unskipping it self-validates the product fix. The CI-skip also stays (raytracer liveness needs real-GPU pacing; the Worker-boot deadlock mechanism is covered on CI by the standalone wx harnesses). - 180s viewer-open waits kept as pure CI headroom (never slow a passing run). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 11:37:27 +02:00
// assertions below can miss (hollow green). The worker parse is async
// relative to the bridge ensures asserted above, so poll for its verdict
// instead of assuming it already landed.
await expect.poll(
() => testLogger.consoleLogs.some((l) => l.includes('oce Load')),
{ timeout: 90000, message: 'the occ_service worker should report the served STEP parse' },
).toBe(true);
feat(wasm): occ-split — lazy occ_service worker; kicad_editor drops OCC (−31%) Move OpenCASCADE out of the merged editor image into occ_service: a separate emscripten module (-sASYNCIFY=0, MODULARIZE, in-container -Oz finalize, 2N+8 pre-warmed pthread pool) booted lazily in a dedicated Web Worker on the first STEP export or STEP/IGES model parse. kicad_editor.wasm ~190 MB -> 130 MB; sessions that never touch OCC never fetch its 57 MB. STEP export works in the browser for the first time: the unchanged desktop dialog runs EXPORTER_STEP, whose wasm shadow suspends into globalThis.occService and the export bytes go straight to a browser download (never entering the editor heap). STEP/IGES 3D models parse in the worker via the oce shadow (S3D WriteCache/ReadCache wire). - wasm/occ-service/: service CMake target (hooked from the kicad fork's top-level CMakeLists, wasm/editor pattern), embind entry (occExport/occLoadModel), wxConfig pre-js. - wasm/stubs/{exporter_step,oce_plugin}_stub.cpp: EM_ASYNC_JS worker bridges (callee-shadowing; no caller #ifdefs). - web/standalone: provider installed whenever the kicad_editor bundle boots (cross-face safe); ONE shared worker-boot source occ-worker.js (vite ?raw; the e2e stub reads the same file) — blob worker with locateFile absolutized against the glue URL; export download-name guard. - deps: OCC builds with RapidJSON so its glTF/GLB writer exists — pinned to the vcpkg master snapshot 2025-02-26 (24b5e7a8b27f), the same code official KiCad consumes via vcpkg.json's opencascade[rapidjson]; rapidjson's latest tag (v1.1.0, 2016) is ill-formed under modern clang. - tests: occ-export dialog e2e (lazy-fetch boundary + STEP download bytes), occ-probe incl. a 9-format matrix (step/stpz/brep/xao/ply/stl/glb/u3d/pdf), 3d-viewer-models hard-asserts the worker parse; occ provider stub installed ambiently by the kicad fixtures. Validated against desktop kicad-cli 10.0.4: geometric exact equality (bbox delta 0 um, volume delta 0.0000%) for STEP/GLB/STL/BREP/STPZ across three boards and option sweeps — with desktop OCC 7.9 vs wasm OCC 7.8; PLY/XAO/PDF structurally equal; U3D same-size (quantizer float LSBs differ). Full kicad e2e green on Firefox and Chromium; standalone verified end to end (lazy fetch only on the Export click; export.step 60,628 B ISO-10303-21; loadModel 700 KB STEP -> 569 KB scenegraph cache). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 12:39:58 +02:00
const oceLoadLines = testLogger.consoleLogs.filter((l) => l.includes('oce Load'));
expect(oceLoadLines.some((l) => l.includes('oce Load ok')),
'the served STEP must parse in the occ_service worker').toBe(true);
expect(oceLoadLines.some((l) => l.includes('oce Load FAILED')),
'no oce model parse may fail').toBe(false);
fix(e2e): rescope the 3D fixes for the webgl-era viewer (rebased onto main) The 3d-webgl merge (kicad eb13ff3bdc: the viewer now defaults to the real OpenGL renderer via wasm/gl1, and occ-split moves STEP parsing into the occ_service worker) made the raytracer-era orchestration on this branch moot — main's chromium-ci phase is green at 15-way parallelism (28666407570 / 28698861536). Drop what no longer earns its complexity, keep the diagnostics, fix main's live flake, and make the deadlock spec test what it was written for. - REVERT the chromium-ci-3d serial project, the two-phase test:kicad:ci, the SwiftShader GPU-process flags, and the resize-drag/models skips: config and package.json are byte-for-byte back to main's shape. The raytracer contention they guarded is no longer on the CI path. - FIX main's live flake: run 28698861536 is green only via retry (3d-viewer.spec:26 flaky) and 28666407570's deadlock red sampled an ALL-ZERO pixel signature — the viewer's first frame lags the canvas's creation on software WebGL under parallel load, and sampling too early reads an all-black backbuffer. New waitForThreeDRender() gates render assertions on actual pixels (1s-interval full-frame CPU reads) instead of fixed sleeps, used by 3d-viewer.spec:26 and the models render tail. - KEEP the storm-proofed samplers (one full-frame getImageData on a willReadFrequently canvas replacing 256 per-pixel GPU round-trips per sample — the "GPU stall due to ReadPixels" trigger) and the logThreeDDiag instrumentation: engine-independent, and they de-risk every remaining software-GL pixel read. - models spec: bridge assertions stay front-loaded (the protocol regression signal is independent of the render); the occ_service parse verdict is now POLLED — it lands async relative to the bridge ensures, so asserting it immediately raced the worker; the render tail runs again everywhere. (The pre-webgl raytracer+models renderer-death documented in a17f3be does not affect the OpenGL default path — the raytracer-toggle+models combination remains untested product surface, tracked outside this branch.) - deadlock spec: the deadlock it guards is raytracer-specific and the viewer now defaults to OpenGL — on the GL engine it either passes vacuously (fast renders make every liveness assertion trivial, 28698861536) or fails on the black first frame (28666407570). It now flips the engine via the "Use raytracing" toolbar toggle (loud assert if the toggle moved) and cross-checks engagement by requiring the canvas pixels to CHANGE after the flip with no input in between (the raytraced frame is lit differently; a GL re-render reproduces identical pixels; heap growth is unusable — mimalloc satisfies the raytracer from freed arena pages). That guard immediately caught a REAL defect: on the webgl-era wasm build the toggle is INERT (the click lands and "Reload time" updates, but the canvas never changes — suspects: DoRePaint's silent catch(runtime_error) freezing the canvas after a raytracer Redraw throw, or ToggleRaytracing writing m_boardAdapter.m_Cfg while RenderEngineChanged() reads GetAppSettings<…>(), possibly different instances in the merged bundle). The spec is therefore test.skip-annotated as a KNOWN ISSUE with the full engine-force machinery in place — unskipping it self-validates the product fix. The CI-skip also stays (raytracer liveness needs real-GPU pacing; the Worker-boot deadlock mechanism is covered on CI by the standalone wx harnesses). - 180s viewer-open waits kept as pure CI headroom (never slow a passing run). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 11:37:27 +02:00
// Gate on the scene actually being ON the canvas (not a fixed sleep) before
// reading pixels — see waitForThreeDRender for the all-black-first-frame flake.
await waitForThreeDRender(page);
fix(ci): 3D specs back to headless SwiftShader + GPU hardening; skip real-GPU drags on CI and the models render tail everywhere (product bug) The headed Mesa-llvmpipe switch (ce44636) was built on a misdiagnosis. With --use-gl=angle --use-angle=gl under Xvfb, Chromium gets NO WebGL AT ALL on the GPU-less CI VM: runs 28652367347 + 28664038296 both log `glcanvas count before opening 3D viewer: 0` (even the pcbnew board's own GAL canvas fails to create) and every failure is the FIRST viewer-open wait timing out. "Timeouts instead of crashes" meant no GL context existed to crash, not that llvmpipe was stable-but-slow. The Mesa/GLX path works for the Firefox project, but not for Chromium on this image. Headless SwiftShader is the environment where GL provably works — the serialized run 28649537489 opened the viewer and rendered/sampled 56 colours (viewer:26/130/209 all passed single-tab). Its remaining failures split into two families, each addressed on its own evidence: 1) SwiftShader GPU-process kills (deadlock spec's lost canvas/black frame): - chromium-ci-3d back to headless + --enable-unsafe-swiftshader, plus --disable-gpu-watchdog and --disable-gpu-process-crash-limit: heavy churn stalls the software-GL GPU process until the watchdog shoots it (CONTEXT_LOST -> removed GL canvas -> "Target crashed"); with the watchdog off a slow op completes, and without the crash limit a lost GPU process keeps restarting for later tests. Same args locally (no-ops on a healthy real GPU). - Storm-proof every canvas sampler (3d-viewer, models, deadlock specs): one full-frame getImageData on a willReadFrequently (CPU-backed) 2D canvas + JS grid sampling, replacing 256 per-pixel getImageData GPU round-trips per sample — the "GPU stall due to ReadPixels" trigger, worst in the deadlock spec's 1.5s-interval settle polling. Sampled pixels and sig order are unchanged. - edge-resize spec: keep the open + 5-resize-handles assertions on CI, then test.skip the drag — each resize step re-raytraces synchronously on the wasm main thread and the 12-step drag blocked mouse.move past the 240s budget even single-tab. Real-GPU-paced; still runs locally (deadlock spec's CI-skip from d9900fe unchanged, same rationale). 2) KNOWN PRODUCT BUG uncovered in the models spec (NOT SwiftShader, NOT CI): raytracing a scene WITH component models kills the Chromium renderer process outright ~6s after scene build — silent process death with a FLAT wasm heap (531-637 MB watched at 2s intervals; not OOM), no console error, no wasm abort, no crash report. Deterministic on a real GPU (5/5), fixture-independent (700 KB USB-C and 61 KB USON-8 STEP crash identically); the same death hits CI SwiftShader at ~66s. Board-only raytraces complete and stay alive, so the bug is specific to the model path. The spec's one historical green ended at raytrace-age ~6s — inside the death window by luck; every CI run of it ever died. Fix here: front-load the bridge assertions (ensure requests fire during scene BUILD, before the raytrace), so protocol regressions still fail the suite everywhere, and test.skip the render tail unconditionally with the bug documented at the skip site. The raytrace->blit pipeline stays gated on CI by 3d-viewer.spec's board-only render. Bug tracked for a dedicated fix session. Correct the now-wrong llvmpipe comments (config, open-wait rationale, deadlock skip reason). Expected CI matrix: viewer open/render/stacking/titlebar + models-bridge on SwiftShader serial; edge-resize drag + camera-move deadlock on real GPUs locally; the Worker-boot deadlock mechanism stays covered on CI by the standalone wx harnesses. Locally validated on a real GPU (--project=chromium): 5 passed + 1 skipped (the documented models render tail). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 10:40:40 +02:00
await logThreeDDiag(page, 'models: before screenshot');
e2e/CI: dual-engine suites, per-engine screenshots, SwiftShader retired, prod web suite, CI-coverage gate Squash of experiment/ff-big-modules vs main. Big-module routing removed: native-EH shrank kicad_editor below SpiderMonkey's x86-64 code budget (runs 29355049705/29356152413 green on stock Firefox), so BIG_MODULE_SPECS routing and the baseline-only-JIT crutch are gone — kicad-firefox and kicad-chromium both run the full suite, with the module compiled the way real users' browsers compile it. Per-engine screenshots end to end: stableShot/shotPath write test-results/<engine>/<name>.png; baselines move to baseline-screenshots/{chromium,firefox}/ and the whole tools/screenshots pipeline (compare/promote/manifest/spec-map/changelog/Discord) keys on <engine>/<name>. Previously Firefox and Chromium renders of one spec overwrote each other and Firefox renders were never actually gated. Seeded from CI run 29421380806 (92 new firefox baselines, +24 chromium web-suite shots); manifest generated from the baseline tree. One merged playwright.config.ts (kicad/asyncify/coroutine/perf as projects); ~25 dead npm scripts dropped. The web suite is gated in CI for the first time ever (4 rotted specs fixed, 5 broken lib-bridge specs triaged as fixme in docs/features/web-e2e-rot/); cheap lint step after npm ci; last 26 blind-sleep violations fixed. SwiftShader retired: CI Chromium renders WebGL on ANGLE → Mesa llvmpipe (--use-gl=angle --use-angle=gl --ignore-gpu-blocklist; the blocklist flag is mandatory — llvmpipe is blocklisted and WebGL is silently unavailable without it) in BOTH configs. Under WORKERS=4 congestion SwiftShader transiently failed the first post-board-load draw and the recovery cascade ended in a silent permanent Cairo fallback — that engine flip was the "~1.2% changedRatio both directions" occ-export baseline flake. Validated 160/160 across two 80-repeat rigs; full analysis in docs/features/wx-parity-bugs/occ-export-context-eviction.md. Chromium baselines shift slightly on llvmpipe — promote once from the first green run. Deflakes the new coverage exposed: presence baselines settle before capture; presence fixtures declare current file formats; perf gets its own outputDir so CI evidence survives; occ-export settles the board paint before the export dialog; menu-item waits (waitForRenderedByLabel before clickMenuItem) in 4 specs + the TESTING.md rule. Web suite runs the PROD build, in parallel: webServer becomes backend `start` + the standalone's e2e:preview (build-preview.mjs: link-wasm → stash the public/wasm symlink aside during vite build, build-demo.mjs's move — then vite preview as the persistent server). The wasm middleware serves /wasm/* in preview and emits COOP/COEP/CORP itself (a pthread worker script's own response must carry COEP or Chrome kills it with ERR_BLOCKED_BY_RESPONSE). VITE_* flags bake at build time; VITE_ALLOW_USER_OVERRIDE joins turbo globalEnv. fullyParallel + default workers: 5.2m → 1.4m. Determinism fixes the parallel run exposed: shared-page specs become serial groups; locks.spec grabs alice's exact item via the new kicadCollabTestSelectByUuid hook (cross-tab "first footprint" order is not a ysync invariant); quit specs poll page.url() (quit supersedes its own navigation — NS_BINDING_ABORTED on Firefox). Suite: 51 passed / 12 skipped / 0 failed in 1.6m. CI-coverage gate (lint:ci-coverage): every tests/**/*.spec.ts must be reachable from the npm scripts the workflows invoke — scraped from .github/workflows/, resolved through package.json, coverage asked from playwright --list itself. Rules: uncovered-spec + orphan-project (with a documented LOCAL_ONLY_PROJECTS allowlist). Gating next to lint:determinism; 138 spec files / 13 projects accounted for. Product fixes kept from the investigations (reachable on real GPUs too): wx 7799fd1be5 — paint flags clear before dispatch + Invalidate always propagates; kicad 3dcfea5e45 — SwiftShader pass-boundary flush + per-instance font texture + first-frame GL-error drain (GAL recovery recovers instead of falling back to Cairo) + the user-facing eeschema switch navigates again under __EMSCRIPTEN__ (project-sync's FaceRegistered gate had rerouted it into the hidden sync player; caught by the newly-gated web suite). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018eUxiPApHgGiu9NFyQfhAq
2026-07-17 12:10:40 +02:00
await page.screenshot({ path: shotPath(page, `3d-viewer-models-${DEMO.name}.png`), scale: 'css' });
fix(ci): 3D specs back to headless SwiftShader + GPU hardening; skip real-GPU drags on CI and the models render tail everywhere (product bug) The headed Mesa-llvmpipe switch (ce44636) was built on a misdiagnosis. With --use-gl=angle --use-angle=gl under Xvfb, Chromium gets NO WebGL AT ALL on the GPU-less CI VM: runs 28652367347 + 28664038296 both log `glcanvas count before opening 3D viewer: 0` (even the pcbnew board's own GAL canvas fails to create) and every failure is the FIRST viewer-open wait timing out. "Timeouts instead of crashes" meant no GL context existed to crash, not that llvmpipe was stable-but-slow. The Mesa/GLX path works for the Firefox project, but not for Chromium on this image. Headless SwiftShader is the environment where GL provably works — the serialized run 28649537489 opened the viewer and rendered/sampled 56 colours (viewer:26/130/209 all passed single-tab). Its remaining failures split into two families, each addressed on its own evidence: 1) SwiftShader GPU-process kills (deadlock spec's lost canvas/black frame): - chromium-ci-3d back to headless + --enable-unsafe-swiftshader, plus --disable-gpu-watchdog and --disable-gpu-process-crash-limit: heavy churn stalls the software-GL GPU process until the watchdog shoots it (CONTEXT_LOST -> removed GL canvas -> "Target crashed"); with the watchdog off a slow op completes, and without the crash limit a lost GPU process keeps restarting for later tests. Same args locally (no-ops on a healthy real GPU). - Storm-proof every canvas sampler (3d-viewer, models, deadlock specs): one full-frame getImageData on a willReadFrequently (CPU-backed) 2D canvas + JS grid sampling, replacing 256 per-pixel getImageData GPU round-trips per sample — the "GPU stall due to ReadPixels" trigger, worst in the deadlock spec's 1.5s-interval settle polling. Sampled pixels and sig order are unchanged. - edge-resize spec: keep the open + 5-resize-handles assertions on CI, then test.skip the drag — each resize step re-raytraces synchronously on the wasm main thread and the 12-step drag blocked mouse.move past the 240s budget even single-tab. Real-GPU-paced; still runs locally (deadlock spec's CI-skip from d9900fe unchanged, same rationale). 2) KNOWN PRODUCT BUG uncovered in the models spec (NOT SwiftShader, NOT CI): raytracing a scene WITH component models kills the Chromium renderer process outright ~6s after scene build — silent process death with a FLAT wasm heap (531-637 MB watched at 2s intervals; not OOM), no console error, no wasm abort, no crash report. Deterministic on a real GPU (5/5), fixture-independent (700 KB USB-C and 61 KB USON-8 STEP crash identically); the same death hits CI SwiftShader at ~66s. Board-only raytraces complete and stay alive, so the bug is specific to the model path. The spec's one historical green ended at raytrace-age ~6s — inside the death window by luck; every CI run of it ever died. Fix here: front-load the bridge assertions (ensure requests fire during scene BUILD, before the raytrace), so protocol regressions still fail the suite everywhere, and test.skip the render tail unconditionally with the bug documented at the skip site. The raytrace->blit pipeline stays gated on CI by 3d-viewer.spec's board-only render. Bug tracked for a dedicated fix session. Correct the now-wrong llvmpipe comments (config, open-wait rationale, deadlock skip reason). Expected CI matrix: viewer open/render/stacking/titlebar + models-bridge on SwiftShader serial; edge-resize drag + camera-move deadlock on real GPUs locally; the Worker-boot deadlock mechanism stays covered on CI by the standalone wx harnesses. Locally validated on a real GPU (--project=chromium): 5 passed + 1 skipped (the documented models render tail). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 10:40:40 +02:00
// --- render assertion --------------------------------------------------
const render = await page.evaluate(() => {
const list = document.querySelectorAll('canvas[id^="glcanvas-"]');
const el = list[list.length - 1] as HTMLCanvasElement;
const tmp = document.createElement('canvas');
tmp.width = el.width;
tmp.height = el.height;
fix(ci): 3D specs back to headless SwiftShader + GPU hardening; skip real-GPU drags on CI and the models render tail everywhere (product bug) The headed Mesa-llvmpipe switch (ce44636) was built on a misdiagnosis. With --use-gl=angle --use-angle=gl under Xvfb, Chromium gets NO WebGL AT ALL on the GPU-less CI VM: runs 28652367347 + 28664038296 both log `glcanvas count before opening 3D viewer: 0` (even the pcbnew board's own GAL canvas fails to create) and every failure is the FIRST viewer-open wait timing out. "Timeouts instead of crashes" meant no GL context existed to crash, not that llvmpipe was stable-but-slow. The Mesa/GLX path works for the Firefox project, but not for Chromium on this image. Headless SwiftShader is the environment where GL provably works — the serialized run 28649537489 opened the viewer and rendered/sampled 56 colours (viewer:26/130/209 all passed single-tab). Its remaining failures split into two families, each addressed on its own evidence: 1) SwiftShader GPU-process kills (deadlock spec's lost canvas/black frame): - chromium-ci-3d back to headless + --enable-unsafe-swiftshader, plus --disable-gpu-watchdog and --disable-gpu-process-crash-limit: heavy churn stalls the software-GL GPU process until the watchdog shoots it (CONTEXT_LOST -> removed GL canvas -> "Target crashed"); with the watchdog off a slow op completes, and without the crash limit a lost GPU process keeps restarting for later tests. Same args locally (no-ops on a healthy real GPU). - Storm-proof every canvas sampler (3d-viewer, models, deadlock specs): one full-frame getImageData on a willReadFrequently (CPU-backed) 2D canvas + JS grid sampling, replacing 256 per-pixel getImageData GPU round-trips per sample — the "GPU stall due to ReadPixels" trigger, worst in the deadlock spec's 1.5s-interval settle polling. Sampled pixels and sig order are unchanged. - edge-resize spec: keep the open + 5-resize-handles assertions on CI, then test.skip the drag — each resize step re-raytraces synchronously on the wasm main thread and the 12-step drag blocked mouse.move past the 240s budget even single-tab. Real-GPU-paced; still runs locally (deadlock spec's CI-skip from d9900fe unchanged, same rationale). 2) KNOWN PRODUCT BUG uncovered in the models spec (NOT SwiftShader, NOT CI): raytracing a scene WITH component models kills the Chromium renderer process outright ~6s after scene build — silent process death with a FLAT wasm heap (531-637 MB watched at 2s intervals; not OOM), no console error, no wasm abort, no crash report. Deterministic on a real GPU (5/5), fixture-independent (700 KB USB-C and 61 KB USON-8 STEP crash identically); the same death hits CI SwiftShader at ~66s. Board-only raytraces complete and stay alive, so the bug is specific to the model path. The spec's one historical green ended at raytrace-age ~6s — inside the death window by luck; every CI run of it ever died. Fix here: front-load the bridge assertions (ensure requests fire during scene BUILD, before the raytrace), so protocol regressions still fail the suite everywhere, and test.skip the render tail unconditionally with the bug documented at the skip site. The raytrace->blit pipeline stays gated on CI by 3d-viewer.spec's board-only render. Bug tracked for a dedicated fix session. Correct the now-wrong llvmpipe comments (config, open-wait rationale, deadlock skip reason). Expected CI matrix: viewer open/render/stacking/titlebar + models-bridge on SwiftShader serial; edge-resize drag + camera-move deadlock on real GPUs locally; the Worker-boot deadlock mechanism stays covered on CI by the standalone wx harnesses. Locally validated on a real GPU (--project=chromium): 5 passed + 1 skipped (the documented models render tail). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 10:40:40 +02:00
// One full-frame read on a CPU-backed canvas, then sample in JS — not 256
// per-pixel getImageData GPU round-trips (see 3d-viewer.spec.ts for why).
const ctx = tmp.getContext('2d', { willReadFrequently: true })!;
ctx.drawImage(el, 0, 0);
fix(ci): 3D specs back to headless SwiftShader + GPU hardening; skip real-GPU drags on CI and the models render tail everywhere (product bug) The headed Mesa-llvmpipe switch (ce44636) was built on a misdiagnosis. With --use-gl=angle --use-angle=gl under Xvfb, Chromium gets NO WebGL AT ALL on the GPU-less CI VM: runs 28652367347 + 28664038296 both log `glcanvas count before opening 3D viewer: 0` (even the pcbnew board's own GAL canvas fails to create) and every failure is the FIRST viewer-open wait timing out. "Timeouts instead of crashes" meant no GL context existed to crash, not that llvmpipe was stable-but-slow. The Mesa/GLX path works for the Firefox project, but not for Chromium on this image. Headless SwiftShader is the environment where GL provably works — the serialized run 28649537489 opened the viewer and rendered/sampled 56 colours (viewer:26/130/209 all passed single-tab). Its remaining failures split into two families, each addressed on its own evidence: 1) SwiftShader GPU-process kills (deadlock spec's lost canvas/black frame): - chromium-ci-3d back to headless + --enable-unsafe-swiftshader, plus --disable-gpu-watchdog and --disable-gpu-process-crash-limit: heavy churn stalls the software-GL GPU process until the watchdog shoots it (CONTEXT_LOST -> removed GL canvas -> "Target crashed"); with the watchdog off a slow op completes, and without the crash limit a lost GPU process keeps restarting for later tests. Same args locally (no-ops on a healthy real GPU). - Storm-proof every canvas sampler (3d-viewer, models, deadlock specs): one full-frame getImageData on a willReadFrequently (CPU-backed) 2D canvas + JS grid sampling, replacing 256 per-pixel getImageData GPU round-trips per sample — the "GPU stall due to ReadPixels" trigger, worst in the deadlock spec's 1.5s-interval settle polling. Sampled pixels and sig order are unchanged. - edge-resize spec: keep the open + 5-resize-handles assertions on CI, then test.skip the drag — each resize step re-raytraces synchronously on the wasm main thread and the 12-step drag blocked mouse.move past the 240s budget even single-tab. Real-GPU-paced; still runs locally (deadlock spec's CI-skip from d9900fe unchanged, same rationale). 2) KNOWN PRODUCT BUG uncovered in the models spec (NOT SwiftShader, NOT CI): raytracing a scene WITH component models kills the Chromium renderer process outright ~6s after scene build — silent process death with a FLAT wasm heap (531-637 MB watched at 2s intervals; not OOM), no console error, no wasm abort, no crash report. Deterministic on a real GPU (5/5), fixture-independent (700 KB USB-C and 61 KB USON-8 STEP crash identically); the same death hits CI SwiftShader at ~66s. Board-only raytraces complete and stay alive, so the bug is specific to the model path. The spec's one historical green ended at raytrace-age ~6s — inside the death window by luck; every CI run of it ever died. Fix here: front-load the bridge assertions (ensure requests fire during scene BUILD, before the raytrace), so protocol regressions still fail the suite everywhere, and test.skip the render tail unconditionally with the bug documented at the skip site. The raytrace->blit pipeline stays gated on CI by 3d-viewer.spec's board-only render. Bug tracked for a dedicated fix session. Correct the now-wrong llvmpipe comments (config, open-wait rationale, deadlock skip reason). Expected CI matrix: viewer open/render/stacking/titlebar + models-bridge on SwiftShader serial; edge-resize drag + camera-move deadlock on real GPUs locally; the Worker-boot deadlock mechanism stays covered on CI by the standalone wx harnesses. Locally validated on a real GPU (--project=chromium): 5 passed + 1 skipped (the documented models render tail). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 10:40:40 +02:00
const img = ctx.getImageData(0, 0, el.width, el.height).data;
const colors = new Set<string>();
for (let i = 0; i < 16; i++) {
for (let j = 0; j < 16; j++) {
fix(ci): 3D specs back to headless SwiftShader + GPU hardening; skip real-GPU drags on CI and the models render tail everywhere (product bug) The headed Mesa-llvmpipe switch (ce44636) was built on a misdiagnosis. With --use-gl=angle --use-angle=gl under Xvfb, Chromium gets NO WebGL AT ALL on the GPU-less CI VM: runs 28652367347 + 28664038296 both log `glcanvas count before opening 3D viewer: 0` (even the pcbnew board's own GAL canvas fails to create) and every failure is the FIRST viewer-open wait timing out. "Timeouts instead of crashes" meant no GL context existed to crash, not that llvmpipe was stable-but-slow. The Mesa/GLX path works for the Firefox project, but not for Chromium on this image. Headless SwiftShader is the environment where GL provably works — the serialized run 28649537489 opened the viewer and rendered/sampled 56 colours (viewer:26/130/209 all passed single-tab). Its remaining failures split into two families, each addressed on its own evidence: 1) SwiftShader GPU-process kills (deadlock spec's lost canvas/black frame): - chromium-ci-3d back to headless + --enable-unsafe-swiftshader, plus --disable-gpu-watchdog and --disable-gpu-process-crash-limit: heavy churn stalls the software-GL GPU process until the watchdog shoots it (CONTEXT_LOST -> removed GL canvas -> "Target crashed"); with the watchdog off a slow op completes, and without the crash limit a lost GPU process keeps restarting for later tests. Same args locally (no-ops on a healthy real GPU). - Storm-proof every canvas sampler (3d-viewer, models, deadlock specs): one full-frame getImageData on a willReadFrequently (CPU-backed) 2D canvas + JS grid sampling, replacing 256 per-pixel getImageData GPU round-trips per sample — the "GPU stall due to ReadPixels" trigger, worst in the deadlock spec's 1.5s-interval settle polling. Sampled pixels and sig order are unchanged. - edge-resize spec: keep the open + 5-resize-handles assertions on CI, then test.skip the drag — each resize step re-raytraces synchronously on the wasm main thread and the 12-step drag blocked mouse.move past the 240s budget even single-tab. Real-GPU-paced; still runs locally (deadlock spec's CI-skip from d9900fe unchanged, same rationale). 2) KNOWN PRODUCT BUG uncovered in the models spec (NOT SwiftShader, NOT CI): raytracing a scene WITH component models kills the Chromium renderer process outright ~6s after scene build — silent process death with a FLAT wasm heap (531-637 MB watched at 2s intervals; not OOM), no console error, no wasm abort, no crash report. Deterministic on a real GPU (5/5), fixture-independent (700 KB USB-C and 61 KB USON-8 STEP crash identically); the same death hits CI SwiftShader at ~66s. Board-only raytraces complete and stay alive, so the bug is specific to the model path. The spec's one historical green ended at raytrace-age ~6s — inside the death window by luck; every CI run of it ever died. Fix here: front-load the bridge assertions (ensure requests fire during scene BUILD, before the raytrace), so protocol regressions still fail the suite everywhere, and test.skip the render tail unconditionally with the bug documented at the skip site. The raytrace->blit pipeline stays gated on CI by 3d-viewer.spec's board-only render. Bug tracked for a dedicated fix session. Correct the now-wrong llvmpipe comments (config, open-wait rationale, deadlock skip reason). Expected CI matrix: viewer open/render/stacking/titlebar + models-bridge on SwiftShader serial; edge-resize drag + camera-move deadlock on real GPUs locally; the Worker-boot deadlock mechanism stays covered on CI by the standalone wx harnesses. Locally validated on a real GPU (--project=chromium): 5 passed + 1 skipped (the documented models render tail). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 10:40:40 +02:00
const p = (Math.floor(el.height * j / 16) * el.width
+ Math.floor(el.width * i / 16)) * 4;
colors.add(`${img[p]},${img[p + 1]},${img[p + 2]}`);
}
}
return { id: el.id, w: el.width, h: el.height, distinctColors: colors.size,
dataUrl: tmp.toDataURL('image/png') };
});
console.log(`[TEST] 3D canvas ${render.id} ${render.w}x${render.h}, distinct colours: ${render.distinctColors}`);
const b64 = render.dataUrl.replace(/^data:image\/png;base64,/, '');
e2e/CI: dual-engine suites, per-engine screenshots, SwiftShader retired, prod web suite, CI-coverage gate Squash of experiment/ff-big-modules vs main. Big-module routing removed: native-EH shrank kicad_editor below SpiderMonkey's x86-64 code budget (runs 29355049705/29356152413 green on stock Firefox), so BIG_MODULE_SPECS routing and the baseline-only-JIT crutch are gone — kicad-firefox and kicad-chromium both run the full suite, with the module compiled the way real users' browsers compile it. Per-engine screenshots end to end: stableShot/shotPath write test-results/<engine>/<name>.png; baselines move to baseline-screenshots/{chromium,firefox}/ and the whole tools/screenshots pipeline (compare/promote/manifest/spec-map/changelog/Discord) keys on <engine>/<name>. Previously Firefox and Chromium renders of one spec overwrote each other and Firefox renders were never actually gated. Seeded from CI run 29421380806 (92 new firefox baselines, +24 chromium web-suite shots); manifest generated from the baseline tree. One merged playwright.config.ts (kicad/asyncify/coroutine/perf as projects); ~25 dead npm scripts dropped. The web suite is gated in CI for the first time ever (4 rotted specs fixed, 5 broken lib-bridge specs triaged as fixme in docs/features/web-e2e-rot/); cheap lint step after npm ci; last 26 blind-sleep violations fixed. SwiftShader retired: CI Chromium renders WebGL on ANGLE → Mesa llvmpipe (--use-gl=angle --use-angle=gl --ignore-gpu-blocklist; the blocklist flag is mandatory — llvmpipe is blocklisted and WebGL is silently unavailable without it) in BOTH configs. Under WORKERS=4 congestion SwiftShader transiently failed the first post-board-load draw and the recovery cascade ended in a silent permanent Cairo fallback — that engine flip was the "~1.2% changedRatio both directions" occ-export baseline flake. Validated 160/160 across two 80-repeat rigs; full analysis in docs/features/wx-parity-bugs/occ-export-context-eviction.md. Chromium baselines shift slightly on llvmpipe — promote once from the first green run. Deflakes the new coverage exposed: presence baselines settle before capture; presence fixtures declare current file formats; perf gets its own outputDir so CI evidence survives; occ-export settles the board paint before the export dialog; menu-item waits (waitForRenderedByLabel before clickMenuItem) in 4 specs + the TESTING.md rule. Web suite runs the PROD build, in parallel: webServer becomes backend `start` + the standalone's e2e:preview (build-preview.mjs: link-wasm → stash the public/wasm symlink aside during vite build, build-demo.mjs's move — then vite preview as the persistent server). The wasm middleware serves /wasm/* in preview and emits COOP/COEP/CORP itself (a pthread worker script's own response must carry COEP or Chrome kills it with ERR_BLOCKED_BY_RESPONSE). VITE_* flags bake at build time; VITE_ALLOW_USER_OVERRIDE joins turbo globalEnv. fullyParallel + default workers: 5.2m → 1.4m. Determinism fixes the parallel run exposed: shared-page specs become serial groups; locks.spec grabs alice's exact item via the new kicadCollabTestSelectByUuid hook (cross-tab "first footprint" order is not a ysync invariant); quit specs poll page.url() (quit supersedes its own navigation — NS_BINDING_ABORTED on Firefox). Suite: 51 passed / 12 skipped / 0 failed in 1.6m. CI-coverage gate (lint:ci-coverage): every tests/**/*.spec.ts must be reachable from the npm scripts the workflows invoke — scraped from .github/workflows/, resolved through package.json, coverage asked from playwright --list itself. Rules: uncovered-spec + orphan-project (with a documented LOCAL_ONLY_PROJECTS allowlist). Gating next to lint:determinism; 138 spec files / 13 projects accounted for. Product fixes kept from the investigations (reachable on real GPUs too): wx 7799fd1be5 — paint flags clear before dispatch + Invalidate always propagates; kicad 3dcfea5e45 — SwiftShader pass-boundary flush + per-instance font texture + first-frame GL-error drain (GAL recovery recovers instead of falling back to Cairo) + the user-facing eeschema switch navigates again under __EMSCRIPTEN__ (project-sync's FaceRegistered gate had rerouted it into the hidden sync player; caught by the newly-gated web suite). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018eUxiPApHgGiu9NFyQfhAq
2026-07-17 12:10:40 +02:00
fs.writeFileSync(shotPath(page, `3d-viewer-models-${DEMO.name}-render.png`),
Buffer.from(b64, 'base64'));
expect(render.distinctColors,
'the 3D viewer canvas should render the board + models, not a blank fill')
.toBeGreaterThan(8);
expect(testLogger.errors, 'no page errors during the model flow').toEqual([]);
});
});