# Spawn Worker Architecture ## Status Phase 1 (memory fixes) - applied, builds clean. Phase 2a (relay-proxy CheckSig) - applied, builds clean. ev.CheckSig() in wireConn onEvent drops invalid events at the network boundary. Phase 2b (spawn-based verifier) - BLOCKED. Both app and relay-proxy are callback-driven (main() sets callbacks and returns, no running goroutine). channel_recv blocks via Atomics.wait, which freezes the JS event loop if called from a callback. Needs channel_try_recv OR Atomics.waitAsync watcher support upstream in moxie jsruntime before this can be wired up. ## Phase 1: Memory Fixes (complete) 1. dom.mjs _trackEl dedup - check _nodeToId before allocating new handle 2. profile eviction handle release - ReleaseChildren + ReleaseElement after RemoveChild 3. rotate reaction/repost/zap element maps - clear noteReactionEls/noteRepostEls/noteZapEls in rotateEventCaches 4. cap notifEvents at 500 - trim oldest on exceed 5. cap _pendingRelayProxyMsgs - stop queueing when crash count >= 3, cap at 100 otherwise 6. wireConn guard - only wireConn if c.ScheduleReconnect == nil 7. evictClosed on AllConns - call evictClosed() at top of AllConns() 8. remove dead SW routing - RELAY_INFO/SIGN/BROADCAST stubs + mySeckey/identity code + schnorr import ## Phase 2: Signature Verification Worker ### Spawn point In dispatchEvent() in web/wasm/app/main.mx. Events from relay-proxy go to verifier channel, render only after verification returns. ### Message types (Codec-compliant) ```moxie type VerifyReq struct { ReqID moxie.Uint32 EvJSON moxie.Bytes } type VerifyRes struct { ReqID moxie.Uint32 Valid moxie.Bool } ``` ### Channel layout ```moxie reqCh := chan VerifyReq{} // app -> verifier (unbuffered) resCh := chan VerifyRes{} // verifier -> app (unbuffered) spawn(verifierMain, reqCh, resCh) ``` SAB slot size: 64KB minimum (events can be ~32KB with content + tags). ### App-side integration - pending-verification map: `map[uint32]*nostr.Event` keyed by ReqID - ReqID counter: monotonic uint32 - main event loop: add `case res := <-resCh:` alongside existing selects - on VerifyRes: look up event in pending map, render if Valid, drop + delete if invalid - non-constant values passed to spawn can't be used afterward (move semantics) ### Verifier-side ```moxie func verifierMain(reqCh chan VerifyReq, resCh chan VerifyRes) { for { select { case req := <-reqCh: // deserialize event from EvJSON, extract pubkey + sig + serialized content // schnorr.Verify uses wNAF precomputed tables (~64KB, stays in this worker's linear memory) valid := verifyEvent(req.EvJSON) resCh <- VerifyRes{ReqID: req.ReqID, Valid: moxie.Bool(valid)} } } } ``` No jsbridge dependencies beyond what's already in the WASM binary. Pure compute. ### Error handling If verifier worker dies (channel_recv returns -1 / channel closes), fall back to inline verification in the app worker. Log the fallback. ### Backpressure SAB channels are unbuffered at spawn boundary. App blocks on send if verifier is behind. Correct behavior - prevents unverified event accumulation. ## Phase 2 Deferred: DB Worker ### Open questions 1. Needs its own jsbridge wiring for IDB access in spawned worker's host JS. The host JS (`wasm-app-worker-host.mjs` pattern) would need the `idb_*` bridge subset wired up for the spawned worker. 2. Concurrent IDB transactions from DB worker and app worker can cause contention. IDB uses a locking model per object store - concurrent write transactions on the same store will queue. 3. Decision needed: does ALL IDB access move to the DB worker (clean but big refactor of all idb.* callsites) or only writes (simpler but split responsibility)? 4. If all IDB access moves, the app worker's existing idb.* jsbridge functions become unused. If only writes move, read contention is possible. ### Message types (draft) ```moxie type DBReq struct { ReqID moxie.Uint32 Op moxie.Uint8 // 1=save, 2=get, 3=query, 4=delete, 5=putProfile Data moxie.Bytes } type DBRes struct { ReqID moxie.Uint32 Ok moxie.Bool Data moxie.Bytes } ``` ## Phase 2 Deferred: Prefetch Worker ### Open questions 1. Needs both IDB read access AND relay-proxy message routing. 2. Relay-proxy access means three-hop path: prefetch -> main thread -> relay-proxy -> network. May not be faster than current reactive fetch from the app worker which has a one-hop path to relay-proxy. 3. Needs its own "already requested" dedup set, which duplicates state the app already tracks in seenEvents/eventCache. 4. Consider whether prefetch should be a function of the relay-proxy worker instead of a separate spawn. Relay-proxy already has WebSocket access and subscription management. ### If implemented as relay-proxy function The relay-proxy could accept a PREFETCH message type that triggers speculative REQs for referenced profiles/events. Results flow back through the existing relay-proxy -> app channel. No new worker, no new jsbridge, no IDB contention. The relay-proxy already has the connection pool. ### Message types (draft, if separate worker) ```moxie type PrefetchReq struct { Op moxie.Uint8 // 1=scan event for refs, 2=explicit profile fetch, 3=cancel Data moxie.Bytes } type PrefetchRes struct { Kind moxie.Uint8 // 1=profile_ready, 2=event_ready, 3=relay_meta_ready Data moxie.Bytes } ``` ## JS-side requirements for future workers For any spawned worker that needs jsbridge access (DB, prefetch): - Document the exact jsbridge function subset needed - The spawned worker's host JS must wire up those bridge functions - Currently createSpawnedWorker in bridge-common.mjs creates a bare Worker with only the common bridge (channels, spawn, subtle_random_bytes, time) - Additional bridges (idb_*, ws_*, dom_*) require host-specific wiring in the worker's onmessage handler - This is a one-time integration cost per bridge type, but it means the spawned worker can't use the same "thin spawn" path - it needs a richer host