Skip to content

test/capture-sid-race.test.ts leaks session→repo scope into the next test file (order-dependent failures) #146

Closed

Description

@abogartz

test/capture-sid-race.test.ts mutates module-global state in src/repokey.ts and src/state.ts but its afterEach only deletes env vars and removes the temp dir. It never undoes what its beforeEach does, so whichever test file the runner schedules after it inherits a poisoned session→repo mapping and fails with another file's repo key.

Reproduction (works on unmodified main)

$ bun test ./test/capture-sid-race.test.ts ./test/repo-scope.test.ts
(fail) stamping (appendMemory) > a write in repo A carries A's key and path on disk
(fail) stamping (appendMemory) > an unscoped process stamps nothing (viewer / legacy semantics)
(fail) visibility at the model-facing sinks > injection: repo A row is invisible from B; …
…9 failures, all of test/repo-scope.test.ts

Run in the opposite order it passes, which is why nobody noticed:

$ bun test ./test/repo-scope.test.ts ./test/capture-sid-race.test.ts
 15 pass

Observed on main @ 61e01b0, Bun 1.4.4, macOS and on CI (ubuntu-latest).

Mechanism

beforeEach clears shared state defensively — setRepoScope(null), resetSessionScopes(), resetState() — and the tests then call rememberSessionDir("ses-capture", <tmp>/repo-a) / rememberSessionDir("ses-other", <tmp>/repo-b) and setCurrent({ sessionID: "ses-other" }).

afterEach leaves all of that in place. bySession is module state shared by every test file in the process, and repoScopeFor() prefers a session entry over the ambient scope:

export function repoScopeFor(sid?: string): RepoScope | null {
  if (sid && sid !== "?") {
    const e = bySession.get(sid);
    if (e) return e.scope;      // ← stale "ses-other" → <tmp>/repo-b wins
  }
  return current;               // ← what the next file set via setRepoScope()
}

So the next file's setRepoScope(REPO_A) is silently overridden by the leaked getCurrent().sid, and its rows come out stamped repo=<hash-of-/tmp/osi-capture-sid-XXXX/repo-b>. The failure message points at the victim, not the leaker, which is what makes this expensive to diagnose.

Why it is surfacing now

PR #145 added test/containment.test.ts. bun test enumerates files by directory order, so adding one file reshuffled the schedule and put repo-scope.test.ts after capture-sid-race.test.ts on the Linux runner. The CI job failed 2/2 — deterministically, not a flake — while every local run passed, because the local directory order differed.

The fix

Mirror the setup in the teardown. Of the two test files that call rememberSessionDir, test/repo-scope-session.test.ts already tears down correctly and test/capture-sid-race.test.ts is the one that forgot. (Several other files call setCurrent() without a matching resetState(); that alone is harmless, because a leaked session id with no bySession entry just falls back to the ambient scope — but it is the same class of omission.)

afterEach(() => {
  setRepoScope(null);
  resetSessionScopes();
  resetState();
  …
});

#145 carries that fix, verified by running the suite in CI's exact file order: 9 failures before, 0 after.

The part worth thinking about

The one-line teardown fixes this instance, but the shape is the problem: test outcome depends on which file the runner happened to execute first, and the runner's order depends on directory enumeration. Two things follow:

  1. A leak in file N is reported as a failure in file N+1, so the suite's error messages lie about where the bug is.
  2. Any PR that adds, renames or deletes a test file can flip unrelated checks — which is how a security PR ended up debugging repo-scoping.

Worth deciding whether module-global registries like bySession should expose a single resetAllForTests() that every file calls in beforeEach, rather than each file remembering the specific set of globals it happens to know about. That makes the suite order-independent by construction instead of by luck.

Activity

  1. added
    test-integrity
    on Oct 27, 2026
  2. abogartz commented on Oct 27, 2026

    @abogartz
    OwnerAuthor

    Fixed in #145 (second commit, test: tear down session scope in capture-sid-race), verified against all 50 files in the CI job's exact order: 9 failures before, 0 after.

    While landing it I checked whether the same omission exists elsewhere. Three files still leak, all confirmed by reading their teardowns:

    file leaks teardown
    test/portable.test.ts 6 setRepoScope(…) calls; the last one (line 369) leaves a real scope set afterEach at :50 deletes env vars and the temp dir only — no setRepoScope(null)
    test/scenarios.test.ts 17 setCurrent(…) calls afterEach at :37 — no resetState()
    test/realrepo.test.ts 3 setCurrent(…) calls, and OPENCODE_MEMORY_DIR is assigned inside a test body (line 43) imports afterEach and never registers one; nothing ever deletes the env var

    I tried to weaponize all three against plausible victims (portable → scenarios, realrepo → scenarios, realrepo → repo-scope, portable → epoch, and four more orderings) and every combination is green today, so these are latent rather than biting — which is exactly the state capture-sid-race was in until #145 added a file and changed the directory order under them.

    setCurrent() alone is weaker than the bug in this issue: a leaked session id with no bySession entry just falls back to the ambient scope in repoScopeFor(). portable.test.ts's leaked setRepoScope is the one with real teeth — it is the same ambient-scope poisoning, in the other direction.

    Twenty test files touch these registries; eleven have no teardown that resets them. Most are harmless today because they never leave anything dirty — which is exactly the argument for making this structural rather than per-file: capture-sid-race.test.ts was also "harmless today" right up until #145 added a file, changed the directory order under it, and turned it into nine failures in a stranger's test suite. Defensive beforeEach cleanup (which several of the eleven rely on) protects the file that writes it and nobody who runs after it.

    One resetAllForTests() called from a shared beforeEach — or, better, a beforeEach that asserts the registries are empty so a leak fails at the boundary instead of three files later — makes the suite order-independent by construction instead of by each author's memory.

  3. added
    verified-on-main
    on Oct 30, 2026
  4. abogartz commented on Oct 30, 2026

    @abogartz
    OwnerAuthor

    Fixed — teardown mirrors setup

    test/capture-sid-race.test.ts:47-56 now resets the module-global state its beforeEach mutates:

    afterEach(() => {
      setRepoScope(null);
      resetSessionScopes();
      resetState();
      ...
    });

    Landed in 9a9cb71 ("test: tear down session scope in capture-sid-race (#146)"). The full suite is green at 525ed89, including in CI's file order.

    The structural point in "the part worth thinking about" is NOT fixed. There is still no single resetAllForTests() on the module-global registries (bySession in src/repokey.ts, the current-session state in src/state.ts), so order-independence is maintained per-file by each file remembering which globals it happens to know about — exactly the shape you identified as the problem.

    Mitigating context since filing: the suite moved to four isolated parallel workers (dba2a7a, "ci: run test files with four isolated workers"), which shrinks the leak surface considerably compared to one process running every file. But the by-construction fix is still unbuilt.

    Suggest folding resetAllForTests() in as a #68-epic child rather than holding this ticket open for it — it's a suite-design change, not this leak.


    Severity triage 2026-10-30 — reviewed against main @ 525ed89 (v0.14.24). Labeled verified-on-main: the behavior this ticket describes no longer exists, so there is nothing to build. Full-suite baseline at that commit: 722 pass / 12 skip / 0 fail. Closing is your call; the evidence is here so the claim is checkable rather than asserted.

  5. abogartz commented on Nov 2, 2026

    @abogartz
    OwnerAuthor

    Closing on the verified-on-main call. test/capture-sid-race.test.ts now calls resetSessionScopes() around the file (line 38, comment: 'bySession is module state shared across test files') with an afterEach at line 48.

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

    test-integrityverified-on-main

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions