Skip to content

fix(api): retain snapshot across concurrent queries and reject post-close registration - #8

Draft
robertpenner wants to merge 3 commits into
mainfrom
fix/api-snapshot-lifecycle
Draft

robertpenner wants to merge 3 commits into
mainfrom
fix/api-snapshot-lifecycle

Conversation

@robertpenner

Copy link
Copy Markdown
Owner

Closes #3

Summary

Fixes two snapshot lifecycle bugs in api.Session (tsc/internal/api/session.go, tsc/internal/api/module_resolution.go):

  1. Concurrent query handlers reading s.snapshots[handle] via getSnapshotData previously unlocked snapshotsMu.RLock() without retaining the underlying *project.Snapshot, allowing a concurrent handleRelease or Session.Close() to dispose sd.snapshot mid-query.
  2. Session.Close() cleared s.snapshots without recording a closed flag, allowing a concurrent registerSnapshot() to insert and leak a retained *project.Snapshot after Close() completed.

Fix

  • Keep sd.refCount strictly for client-owned references (registerSnapshot / handleRelease).
  • Update getSnapshotData(handle) to retain sd.snapshot via s.snapshotHost.RetainSnapshot(sd.snapshot) under s.snapshotsMu.RLock() and return an idempotent release callback (sync.OnceFunc calling sd.snapshot.Deref()). Replace retainSnapshotData with getSnapshotData so snapshot derivation is also protected against Session.Close() and duplicate handleRelease.
  • Fold snapshot release into checkerSetup.done, resolveSymbolReference's returned release callback, getEmitProgram/getEmitOptions, and all direct getSnapshotData handlers.
  • Add closed bool guarded by s.snapshotsMu: Close() sets s.closed = true before clearing s.snapshots; registerSnapshot() checks s.closed, derefs the snapshot immediately if closed, and returns an error.

Verification

  • TLA+ model (ApiSessionSnapshot_Fixed.cfg on tla-concurrency-verification): 0 errors across 36 distinct states (69 generated) with deadlock checking enabled, verifying NoUseAfterDeref, NoLeakAfterClose, NoNegativeSnapRef, and QuiescentClean.
  • go -C ./tsc test -race -count=1 ./internal/api/...: all 4 packages pass (api, encoder, requestfilesystem, wasmreactor), including TestGetSnapshotDataRetainsAcrossRelease, TestGetSnapshotDataRetainsAcrossSessionClose, and TestRegisterSnapshotAfterCloseRejectsAndDerefs.
  • gofmt and go vet ./internal/api/...: clean.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fix api.Session snapshot use-after-deref and post-close leak (tsc/internal/api/session.go)

1 participant