fix(viewer): give each collab join its own attempt token

Merged
LO
21d ago
+670-256

Defect

startCollab (apps/viewer/src/store/slices/collabSlice.ts) awaits about a dozen times between "join" and "session live". It recognised its own continuation by collabRoomId === roomId, which is a room key, not an attempt token. The code admitted it ("cannot tell a rejoin of the SAME room from this join still being live").

A Leave + rejoin of the same room, or a second start of it, sets the same id, so the abandoned first attempt:

  • passed every re-check;
  • wired its remote-apply / annotation / reconstruct listeners into the ~12 module-level singletons the live join was using (docApi, placementApi, placementApplied*, geomApiRef, makeBlobStore, cachedBlobStore, annotationDocApi, remoteApplyTeardown, recipientLiveTeardown, annotationInboundTeardown);
  • committed a second session over the live one.

If the first attempt failed to start instead, its catch cleared the live join's collabRoomId / collabRole / collabSelfToken. On the stale path, the else branch also reset the live join's collabConnecting.

Concrete scenario

  1. Click Share. The owner join is parked waiting for relay sync.
  2. Click Leave, then Share again on the same room.
  3. The first join's sync lands. It passes collabRoomId === 'room-1' and commits its own session (collabSession.clientId = the first session's), and the rejoin later overwrites it. Two sessions are wired, one of them leaked.

Variant: the first join's createCollabSession rejects after the rejoin started, and the user is silently kicked out of the room they just rejoined (collabRoomId → null).

Fix

  • New apps/viewer/src/lib/collab/session-attempt.ts.
    • beginCollabAttempt(roomId) returns a CollabAttempt that owns everything one join wires: the doc helpers (built once by collabAttemptApis), the placement render bookkeeping, the blob-store factory and promise cache, the cleanups and the session.
    • attempt.live is the only currency check in startCollab.
    • attempt.adopt(session) disposes a session that arrives for a retired attempt.
    • attempt.onRetire(cleanup) runs at once if the attempt has already retired. That replaces the #3016 ownLiveTeardown bookkeeping.
  • stopCollab retires the live attempt. A session committed without an attempt (test seeding) is still disposed.
  • The mirror actions read the live attempt's helpers instead of module globals.
  • runOwnerSeed returns null for an abandoned join that throws, instead of logging and reporting a failure nobody reads. The "abandoned" case is what happens once #9532 makes whenSynced reject on dispose.
  • The recipient reconstruct catch returns quietly for a retired attempt. With #9532, a Leave before the room synced makes await session.whenSynced reject, and the catch used to log a misleading model reconstruction failed: CollabSessionDisposedError.
  • The fire-and-forget geometry shares in mirrorEntityCreate and mirrorEntityGeometry check attempt.live in three places: after the blob-store await, after the upload, and at the top of the catch. A Leave or rejoin during an upload used to surface "could not be shared with the room" for a room the user had left, or in the new join's state. With #9532, the retired session's transact throws CollabSessionDisposedError, and after retire() the blob store always rejects, so the catch always ran.
  • scripts/check-collab-room-model-target.test.mjs: the mutation anchors follow the new mirrorEntityRemove shape. The RED case still deletes the real roomStoreFor(get(), modelId) call and fails the guard, and the guard itself still finds every required call.
  • collabSlice.ts shrinks 1312 → 1201 lines; the allowlist budget is lowered to match.

Independent of #9532 (collab package lifecycle). With both merged, the stale continuation's await session.whenSynced rejects promptly instead of parking forever.

Tests

  • collabSlice.same-room-rejoin.test.ts (new), driving the real startCollab through the session-race loader hook:
    • the stale first join resuming after a same-room rejoin commits nothing, and the rejoin's session goes live;
    • the stale first join's failed start leaves the rejoin's room, role, token and connecting flag alone;
    • the stale first join whose session arrives after the rejoin disposes it and returns.
  • The hook gains __collabCreateHold to park or fail a single createCollabSession call.
  • owner-seed.test.ts: an abandoned join's throwing seed reports null and stamps no interrupted marker.
  • collabSlice.leave-during-upload.test.ts (new) uses the real startCollab, mirrorEntityGeometry / mirrorEntityCreate and stopCollab. A Leave while the upload is in flight raises no collabGeometryNotice.
    • Verified on a local merge of #9532 + #9554: with the attempt.live gates, 2/2 pass. With the gates removed, 0/2 pass, and the log shows [collab] mirror resize geometry failed: CollabSessionDisposedError … (transact), i.e. exactly the post-Leave toast.
    • On #9554 alone the test passes either way: without #9532, the retired session still accepts the write, so no error is raised.
  • collabSlice.leave-during-join-race.test.ts now lets the session's own sync land before Leave. Leave now disposes the in-flight session, and before #9532 a provider disposed before its first sync never settles whenSynced (the very hang that test's message names).

On the original slice, the new tests fail for the stated reasons: actual: 3794919734, expected: null for the committed stale session, and null !== 'room-1' for the stale failure.

Commands

All test commands ran under systemd-run --user --scope -p MemoryMax=8G -p MemorySwapMax=0; tsc used 12G and lint 24G. Results are for head c49c55a9.

  • Collab test family (55 files: every collabSlice.*, lib/collab/*, collab-publish, presence, and every test importing the slice):
    • #9554 alone: 494 tests, 493 pass, 0 fail.
    • Local merge of #9532 + #9554: 494 tests, 493 pass, 0 fail, and no model reconstruction failed logs.
  • Typecheck: tsc --noEmit passes for both apps/viewer and apps/viewer-embed (tests included).
  • node --test scripts/*.test.mjs: 2181 tests, 2176 pass, 2 fail, neither from this change.
    • All 6 check-collab-room-model-target tests pass, and node scripts/check-collab-room-model-target.mjs reports OK (10 entity actions self-gated, 15 call sites bound to modelId).
    • The 2 failures are local-environment only. viewer-embed unused-locals baseline failed because embed didn't compile against my stale local @ifc-lite/collab dist; after rebuilding that dist, embed compiles and measures 182 = baseline. The smlib native-worker "poison deadline" timing test is unrelated.
  • Lint:
    • Every pnpm lint step passes: i18n-literals, jsx-a11y, type-scale, and check-lint-ran (no errors).
    • unused-locals: apps/viewer is within baseline and apps/viewer-embed measures 182 = baseline. cache / create / mutations can't be compiled here after the rebase (stale local dists that need a wasm rebuild), so CI's lint job is the check for those.
  • Module size: node scripts/check-module-size.mjs passes, with collabSlice lowered 1312 → 1201.
  • Source-text assertions: node scripts/check-source-text-assertions.mjs passes.
  • Revert oracle (local, base origin/main): OBSERVED.

Mutation table

The tests run against each mutant were the rejoin, leave-during-join, leave-after-reconstruct, seed-phase, session-failure and owner-seed tests.

Guard removedResult
if (!attempt.adopt(session)) returnkilled (rejoin: session arrives after rejoin)
adopt disposing for a retired attemptkilled (same test; the leaked session hangs the file)
catch gated on current()killed (stale failed start)
post-seed if (!current()) returnkilled (leave-during-join, stale rejoin)
onRetire immediate run when retiredkilled (leave-after-reconstruct ×2)
stopCollab → attempt.retire()killed (leave-after-reconstruct)
retire() disposing the sessionkilled (three files hang)
runOwnerSeed abandoned early returnkilled (owner-seed)

| attempt.live gates on the geometry-share paths | killed on the #9532 + #9554 merge (leave-during-upload, both cases). Not observable on #9554 alone; see Tests. |

Two first-draft guards survived: current() checks inside the presence and status listeners. I deleted them. To correct my earlier wording: those listeners are registered right after adopt, before the session is committed, not only by a committed attempt. Deleting the guards is still safe for two reasons:

  • Every return after adopt happens on a retired attempt, whose session retire() has already disposed.
  • stopCollab disposes the session before resetting collabPeers / collabStatus, so a late emit is overwritten.

Defence in depth once #9532 lands. Two guards are mutation-killed today but become redundant once #9532 merges, because a disposed session's whenSynced then rejects and its writes throw:

  • the if (!attempt.adopt(session)) return early return;
  • the liveAttempt === this clear in retire().
    I've kept both deliberately, so this PR is correct without #9532 and the stale path stays short-circuited.

Not verified

  • No browser run. Covered by the node test harness (real @ifc-lite/collab, fake-indexeddb) only.

Out of scope, pre-existing

  • Existing local annotations are never pushed when sharing. The loop in startCollab (~941-952) calls mirrorAnnotationUpsert before collabSession is committed, so every call is a no-op. This change leaves that behaviour as it was.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Leaving or rejoining a collaboration room while a connection is starting no longer lets an earlier attempt overwrite the current room or connection state.
    • Inactive connection attempts are cleaned up, and sessions created by them are discarded.
    • Uploads and room setup from an inactive attempt no longer affect the active collaboration or mark it as interrupted.