feat(wasm-lifecycle): shared createWorkerRpc dead latch; migrate worker clients
Implicit-state-machines audit, section 2 item 3: one shared worker RPC with a dead latch. Before this, four packages each kept their own request map (pointcloud WorkerSession, geometry RemeshClient, ids-agent createWorkerModelBridge, embed-sdk IFCLiteEmbed). Each copy had to get the same failure paths right on its own, and two did not.
Defects (verified by reading, then reproduced with red tests)
| Where | Scenario | Before |
|---|---|---|
ids-agent createWorkerModelBridge | bridge.dispose(), then bridge.stats(signal) | The call posts, then waits forever: dispose() only cleared the map, and later calls were never refused |
ids-agent createWorkerModelBridge | The model worker crashes or sends an unreadable message mid-call | Pending calls hang: no error/messageerror handling at all |
embed-sdk request() | postMessage throws (e.g. DataCloneError on a transfer) | The promise rejects, but its pending entry and 30 s timer stay behind |
Red runs before the fix: the 3 ids-agent hangs timed out at 2000 ms, and the embed test failed with expected 1 to be +0 on vi.getTimerCount().
Pointcloud (#9483 P3) and remesh (#9483 P5) were already correct. They move onto the primitive unchanged, and their existing P3/P5 tests pass unmodified apart from the fake worker now using addEventListener.
Fix
@ifc-lite/wasm-lifecycle gains createWorkerRpc:
- Dead latch: the first fatal reason wins:
fail,dispose, workererror/messageerror, a missed deadline in'kill'mode, or a failedstart. It terminates the worker (or callsclose), rejects everything pending and a pendingstart, runsonDeathonce, and every laterrequestrejects at once. - Post-throw cleanup: the request's entry, deadline and abort listener are dropped.
- Deadlines: uses #9483's
armDeadlineclamping. That file moved here fromgeometry/src/remesh/deadline.ts, together with its test.'kill'is for work that cannot be interrupted (remesh);'reject'fails only the late request (embed's 30 s per command). - Abort, and a
starthandshake under its own deadline (remesh init). - Worker mode wires
message/error/messageerroritself. Port mode (post+receive) is for transports the caller listens on (embed's window, ids-agent'sBridgePort).
Home: I put it in wasm-lifecycle because it has zero runtime dependencies and geometry already depends on it. Pointcloud, ids-agent and embed-sdk gain one edge to a ~2 KB dependency-free package. Clash, the parser and anything else heavy stay out of their graphs.
ids-agent API: BridgePort now accepts 'error' | 'messageerror' too. Worker-death handling is opt-in (createWorkerModelBridge(port, { watchErrors: true })). The reason: an adapter that ignores the event type, as the repo's own test adapter did, would otherwise route ordinary messages into the error handler.
The in-place copies are deleted: WorkerSession and RemeshClient are now thin typed facades, and the embed and ids-agent pending maps are gone.
Notes for reviewers and consumers
- Custom worker doubles:
RemeshClient(and everycreateWorkerRpcworker) now subscribes withaddEventListener('message' | 'error' | 'messageerror')instead of assigningonmessage/onerror. A hand-written worker double passed throughcreateWorkermust implementaddEventListener/removeEventListener. A realWorkeris unaffected. - Cleanup order:
fail()rejects every pending call before it detaches, terminates or notifies, and runs each of those steps even if one throws; the first error still reaches the caller offail/dispose. Abort rejects the call before runningonAbort, so a throwing cancel post cannot leave it pending. - Changesets: #9483's unreleased
.changeset/worker-rpc-dead-latch.mdis unchanged from main. This PR's notes are in.changeset/shared-worker-rpc.md. @ifc-lite/wasm-lifecycledeclares"sideEffects": false: its modules hold only constants and functions at top level.- CI:
export-schema-conformance.ymlnow buildsturbo --filter='@ifc-lite/export^...'before the export test. An aliased package's own imports resolve fromdist/, and pointcloud now importswasm-lifecycle.
Perf verdict (packages/geometry is perf-sensitive)
No hot-path change. The only geometry code touched is RemeshClient, the Model-workspace re-mesh worker client. It runs per edit request, not in model load or the mesh pipeline. Per request it does the same Map get/set, one timer and one postMessage as before. geometry-parallel, geometry.worker, the bridge and mesh extraction are untouched, so no probe was run.
Commands and results (local, Pop, under an 8 GiB memory cap)
vitest runin wasm-lifecycle: 64/64; pointcloud: 420 passed, 5 skipped; ids-agent: 78/78; embed-sdk: 81/81; geometrysrc/remesh: 37/37node scripts/typecheck-tests.mjspasses for wasm-lifecycle, ids-agent and embed-sdk;tsc --noEmitis clean for those packages- Full geometry suite: 667/669. The 2 failures are
ifc-lite-bridge-init-lifecycleP6 #1/#2, which time out at 5 s on a cold import under full-suite load. They pass in isolation, and this PR does not touch the bridge. check-changesets,check-module-sizeandcheck-source-text-assertionspass;oxlinton changed files is clean;pnpm api-surface:updatewas run (11 exports added, none removed)- Root
pnpm typecheckplusturbo testfor the 5 packages: submitted to the fleet on 415801c1af, still queued when this PR was opened. CI will run the full gates.
Mutation table
Each guard in worker-rpc.ts was removed one at a time, and its named test failed:
| Mutation | Killed by |
|---|---|
| fail first-wins / detach / close / reject pending / death listeners | a worker crash rejects everything pending, terminates once, … |
| unknown-id answer ignored | a late reply for a request whose post threw is ignored |
| onDeath immediate / unsubscribe | an onDeath listener added after death runs at once; … |
| start: dead guard / re-entry guard | start on a dead endpoint … / a second start while one runs … |
| start: death or ready cancels deadline | a crash during start clears the start deadline / resolves with the ready payload, disarms the start deadline … |
| start: init-error fatal / post-throw fatal | an init error, a crash, an unreadable message or a throwing post … |
| request dead guard / pre-aborted | … later requests reject at once / an already-aborted signal posts nothing |
| abort drops entry / runs onAbort | an aborted request rejects, drops its entry, runs onAbort, … |
| timeout kill mode / reject drops entry | 'kill': … / 'reject': … |
| post-throw drop entry / cleanup; settle cleanup | a late reply … / a throwing post rejects that request alone and leaves no deadline … |
| reject pending after close / without per-step guarding | a throwing terminate still rejects everything pending and runs the death listeners / a throwing death listener does not stop pending rejections or later listeners |
| last cleanup error wins instead of the first | a throwing close and a throwing listener: the first error reaches the caller, everything still runs |
onAbort before reject | a throwing onAbort (e.g. the cancel post) still rejects the call |
embed onRequestTimeout: 'reject' → 'kill' (reviewer survivor) | a command that times out fails alone: the next command still resolves |
| notify dead guard | a call after dispose rejects instead of hanging, and notify is a no-op |
Survivors: none. The one initial survivor (ready not disarming the start deadline) got a test. Two guards that were unreachable (abort/timeout re-checking an entry that settling already removed) were deleted, not kept.
Unverified
- Root typecheck and turbo test are still queued on the fleet (see above).
- No real browser run of the embed SDK or a real
Workercrash; covered by fake-worker tests only.
🤖 Generated with Claude Code
Summary by CodeRabbit
- New Features
- Added reusable worker and message-port request handling with request correlation, timeouts, cancellation, and failure reporting.
- Worker model bridges now offer optional monitoring for worker errors and unreadable messages. Disposed bridges reject pending and future calls.
- Bug Fixes
- Worker-backed embed, remeshing, and point-cloud operations now handle request failures and timeouts consistently; a failed request does not block later requests.
- Documentation
- Expanded guidance on worker RPC behavior, bridge disposal, and optional error monitoring.