feat(wasm-lifecycle): shared createWorkerRpc dead latch; migrate worker clients

Merged
LO
22d ago
+1239-286

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)

WhereScenarioBefore
ids-agent createWorkerModelBridgebridge.dispose(), then bridge.stats(signal)The call posts, then waits forever: dispose() only cleared the map, and later calls were never refused
ids-agent createWorkerModelBridgeThe model worker crashes or sends an unreadable message mid-callPending 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, worker error/messageerror, a missed deadline in 'kill' mode, or a failed start. It terminates the worker (or calls close), rejects everything pending and a pending start, runs onDeath once, and every later request rejects at once.
  • Post-throw cleanup: the request's entry, deadline and abort listener are dropped.
  • Deadlines: uses #9483's armDeadline clamping. That file moved here from geometry/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 start handshake under its own deadline (remesh init).
  • Worker mode wires message/error/messageerror itself. Port mode (post + receive) is for transports the caller listens on (embed's window, ids-agent's BridgePort).

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 every createWorkerRpc worker) now subscribes with addEventListener('message' | 'error' | 'messageerror') instead of assigning onmessage/onerror. A hand-written worker double passed through createWorker must implement addEventListener/removeEventListener. A real Worker is 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 of fail/dispose. Abort rejects the call before running onAbort, so a throwing cancel post cannot leave it pending.
  • Changesets: #9483's unreleased .changeset/worker-rpc-dead-latch.md is unchanged from main. This PR's notes are in .changeset/shared-worker-rpc.md.
  • @ifc-lite/wasm-lifecycle declares "sideEffects": false: its modules hold only constants and functions at top level.
  • CI: export-schema-conformance.yml now builds turbo --filter='@ifc-lite/export^...' before the export test. An aliased package's own imports resolve from dist/, and pointcloud now imports wasm-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 run in wasm-lifecycle: 64/64; pointcloud: 420 passed, 5 skipped; ids-agent: 78/78; embed-sdk: 81/81; geometry src/remesh: 37/37
  • node scripts/typecheck-tests.mjs passes for wasm-lifecycle, ids-agent and embed-sdk; tsc --noEmit is clean for those packages
  • Full geometry suite: 667/669. The 2 failures are ifc-lite-bridge-init-lifecycle P6 #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-size and check-source-text-assertions pass; oxlint on changed files is clean; pnpm api-surface:update was run (11 exports added, none removed)
  • Root pnpm typecheck plus turbo test for 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:

MutationKilled by
fail first-wins / detach / close / reject pending / death listenersa worker crash rejects everything pending, terminates once, …
unknown-id answer ignoreda late reply for a request whose post threw is ignored
onDeath immediate / unsubscribean onDeath listener added after death runs at once; …
start: dead guard / re-entry guardstart on a dead endpoint … / a second start while one runs …
start: death or ready cancels deadlinea crash during start clears the start deadline / resolves with the ready payload, disarms the start deadline …
start: init-error fatal / post-throw fatalan 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 onAbortan aborted request rejects, drops its entry, runs onAbort, …
timeout kill mode / reject drops entry'kill': … / 'reject': …
post-throw drop entry / cleanup; settle cleanupa late reply … / a throwing post rejects that request alone and leaves no deadline …
reject pending after close / without per-step guardinga 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 firsta throwing close and a throwing listener: the first error reaches the caller, everything still runs
onAbort before rejecta 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 guarda 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 Worker crash; 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.