Skip to content

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

In progress

Description

@robertpenner

Parent / source

What to build

Make api.Session's snapshot registry safe under concurrent ipc.AsyncConn request handlers, handleRelease, createSnapshot, and Session.Close():

  1. Prevent use-after-deref in read/query handlers: Any handler obtaining *snapshotData for a snapshot handle must keep the underlying *project.Snapshot alive until the handler finishes using it, even if a concurrent handleRelease(handle) or Session.Close() removes the handle from s.snapshots. Once all in-flight handlers and client references have released the snapshot, sd.snapshot.Deref() must still run exactly once so no snapshot leaks.
  2. Prevent post-close snapshot leaks: If Session.Close() has already run (or runs concurrently with an in-flight snapshot creation), registerSnapshot must not leave a retained *project.Snapshot orphaned in s.snapshots; it must release (Deref()) the snapshot and report/handle the closed session cleanly.

Decisions and constraints

  • Follow all shared constraints in End-to-end red-to-green TLA+ fixes and upstream PR prep for flagship TypeScript 7 concurrency bugs #1 (clean fix branch from main at e0fce98, no unsolicited PR against microsoft/TypeScript, official tla2tools.jar only).
  • getSnapshotData is called across 480+ handlers in tsc/internal/api/session.go; preserve clean ergonomics (e.g., returning a release callback or scoped helper) and avoid holding snapshotsMu across slow checker/program work.
  • Preserve existing handleRelease error behavior when releasing an unknown or already-released snapshot handle, and preserve layered-filesystem compaction behavior tested in session_requestfilesystem_test.go.

Acceptance criteria

  1. Green TLA+ model: Add a fixed configuration (and updated spec transitions on tla-concurrency-verification) checked by tla2tools.jar / TLC that verifies NoUseAfterDeref, NoLeakAfterClose, no negative refcount / double-Deref, and quiescent refcount cleanup (0 errors across all reachable states), wired into verification/tla/scripts/run-tlc.sh.
  2. Go fix and regression tests: On a clean fix branch off main (e0fce98), fix tsc/internal/api/session.go and add in-package regression tests covering:
    • Active snapshot query concurrent with handleRelease (underlying project.Snapshot stays alive until query completes, then disposes cleanly without negative refcount).
    • In-flight registerSnapshot racing Session.Close() (no entry left in s.snapshots, retained snapshot is deref'd without panic or leak).
  3. Verification: go -C ./tsc test -race -timeout=120s ./internal/api/... passes (including existing session_requestfilesystem_test.go compaction tests and new regression tests), and npx hereby check:format and npx hereby lint pass for touched files.
  4. Upstream preparation: Include a concise ready-to-file upstream bug report and PR description (referencing the fix branch on robertpenner/TypeScript) in an issue comment when done.

Dependencies

None. Independently executable.

Starting references

  • tsc/internal/api/session.go:703-743 (getSnapshotData, retainSnapshotData, releaseSnapshot)
  • tsc/internal/api/session.go:1865-1891 (registerSnapshot), 5789-5810 (Close)
  • tsc/internal/api/session_requestfilesystem_test.go
  • verification/tla/specs/ApiSessionSnapshot/ApiSessionSnapshot.tla
  • verification/tla/reproducers/api_session_repro_test.go

Activity

  1. added
    bug
    ready-for-agent
    on Nov 26, 2026
  2. robertpenner commented on Nov 26, 2026

    @robertpenner
    OwnerAuthor

    Just-in-Time Agent Brief (#3)

    • Codebase verified at: e0fce98 (main), 417e8a9 (tla-concurrency-verification).
    • Root causes confirmed:
      1. tsc/internal/api/session.go:703-711: getSnapshotData (38 call sites in session.go, including setupChecker) reads s.snapshots[handle] under snapshotsMu.RLock() and unlocks without retaining the underlying *project.Snapshot. Concurrent handleRelease or Close drops sd.snapshot to 0 and disposes it mid-query. Additionally, retainSnapshotData bumped client sd.refCount, which still raced with Close() and erroneous double handleRelease.
      2. tsc/internal/api/session.go:1865-1891, 5789-5810: Session.Close() clears s.snapshots without recording s.closed = true; a concurrent registerSnapshot() can insert a retained *project.Snapshot after Close() returns, leaking it permanently.
    • Design for green model and fix:
      • Keep sd.refCount strictly for client-owned references (registerSnapshot / handleRelease).
      • Have getSnapshotData(handle) retain sd.snapshot via s.snapshotHost.RetainSnapshot(sd.snapshot) while holding s.snapshotsMu.RLock() and return (sd, release, err) where release calls sd.snapshot.Deref() once (sync.OnceFunc). Replace retainSnapshotData with getSnapshotData as well so snapshot derivation is also safe against Close() and double handleRelease.
      • In setupChecker, release the snapshot on error paths and fold release() into setup.done().
      • Add closed bool guarded by s.snapshotsMu: Close() sets s.closed = true before clearing s.snapshots; registerSnapshot() checks s.closed, derefs the snapshot if closed, and returns an error so callers do not leak snapshots after close.
    • Verification plan: Exhaustive TLC check (ApiSessionSnapshot_Fixed.cfg, 0 errors on NoUseAfterDeref, NoLeakAfterClose, NoNegativeSnapRef, QuiescentNoLeak, deadlock-free), TDD regression tests under go -C ./tsc test -race ./internal/api/..., and gofmt / go vet.
  3. robertpenner commented on Nov 26, 2026

    @robertpenner
    OwnerAuthor

    Slice Complete: Red-to-Green Verified (#3)

    • Fix branch: fix/api-snapshot-lifecycle (based on main e0fce98)
    • Fork draft PR: opened on robertpenner/TypeScript (Closes #3)
    • Green TLA+ verification: ApiSessionSnapshot_Fixed.cfg passed with 0 errors (36 distinct states, 69 generated, deadlock checking enabled) on NoUseAfterDeref, NoLeakAfterClose, NoNegativeSnapRef, and QuiescentClean.
    • Go verification: go -C ./tsc test -race -count=1 ./internal/api/... passed (4/4 packages, including TestGetSnapshotDataRetainsAcrossRelease, TestGetSnapshotDataRetainsAcrossSessionClose, and TestRegisterSnapshotAfterCloseRejectsAndDerefs); gofmt and go vet clean.

    Draft Upstream Bug Report (for microsoft/TypeScript)

    Title: [api] Concurrent query handlers can use a disposed project.Snapshot after release or Close; registerSnapshot can leak snapshots after Close

    Description:
    In tsc/internal/api/session.go:

    1. getSnapshotData(handle) looks up *snapshotData under s.snapshotsMu.RLock() and unlocks without retaining the underlying *project.Snapshot. Because ipc.AsyncConn executes incoming requests in concurrent goroutines, a concurrent handleRelease or Session.Close() can drop sd.snapshot's refcount to zero (disposing checkerPool, dereferencing parseCache, and releasing extendedConfigCache) while an active query handler is still using sd.snapshot.
    2. Session.Close() calls clear(s.snapshots) without setting a closed flag, so an in-flight createSnapshot / updateSnapshot calling registerSnapshot() afterward inserts a retained *project.Snapshot into the emptied map and leaks it permanently.

    Pinning sd.snapshot via s.snapshotHost.RetainSnapshot(sd.snapshot) under s.snapshotsMu.RLock() (returning an idempotent Deref() release callback) and guarding registerSnapshot with a closed flag under s.snapshotsMu fixes both races while keeping read handlers on RLock().

    (Clean fix branch ready at robertpenner/TypeScript:fix/api-snapshot-lifecycle once an upstream issue is milestoned.)

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugready-for-agent

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions