codex-multi-auth icon indicating copy to clipboard operation
codex-multi-auth copied to clipboard

test: stop leaked-spy cascades across the whole test runner

Open ndycode opened this issue 5 months ago • 3 comments

Summary

  • Isolation hardening for the whole test runner, fixing a cross-test contamination class discovered while writing #585's rename-retry tests: a test that fails before its inline mockRestore() leaks its spy into every later test of the file.

What Changed

The failure mechanics, observed live in sandboxed environments where the EACCES-baseline tests die mid-run:

  1. An early test spies a method (e.g. fs.rename) and crashes before reaching its mockRestore() (no try/finally).
  2. A later test calls vi.spyOn on the same method — vitest returns the same leaked spy rather than wrapping again.
  3. That test's "original" passthrough binding (fs.rename.bind(fs)) therefore captures the spy itself, and calling through recurses into the test's own mock — a RangeError: Maximum call stack size exceeded crash with a confusing stack.

Two layers land here:

  • test/storage.test.ts (first commit): the file's top-level afterEach restored env vars but never mocks; it now calls vi.restoreAllMocks(), with a comment documenting the mechanism and (per review) its relationship to the global hook. The storage suite is where the cascade was observed.
  • test/helpers/global-sandbox.ts (second commit): a repo scan found 16 more test files with the same shape (bare mockRestore() at the end of a test body, no global restore hook). Rather than patching each, the shared setup file — already loaded by every suite — registers one global afterEach(() => vi.restoreAllMocks()), containing the cascade everywhere. No suite creates spies in beforeAll (verified by scan), so an after-each restore cannot strand intentional cross-test spies.

No assertions change anywhere; the per-test mockRestore() calls remain as harmless redundancy.

Validation

  • [x] npm run typecheck + npx eslint on both files (pre-commit hook re-runs both)
  • [x] npm test -- test/storage.test.ts with the file-level hook — failure names a strict subset (19) of the 23-name environment baseline block, zero new names
  • [x] Scan proof for the global hook: beforeAll + spyOn co-occurrence search over test/ returns nothing, so no suite relies on a spy surviving past a test
  • [x] Full-suite run with the global hook (all 317 files, --maxWorkers=1): 54 failing names, all in the 58-name docs/audits/evidence/test-baseline-2026-06-10.txt environment baseline, zero new names — and four baseline names now PASS (the storage rotation/backup/artifact tests that were cascade victims, not genuine environment failures). Strict improvement; full name-diff posted as a PR comment.
  • [ ] npm run build deferred to CI

Docs and Governance Checklist

  • [x] No user-visible behavior changed; test isolation only

Risk and Rollback

  • Risk level: low — vi.restoreAllMocks() only affects vi.spyOn spies, which every suite already restores per-test on the success path; the hooks merely cover the failure path. The one theoretical hazard (a suite depending on a beforeAll spy across tests) is excluded by scan.
  • Rollback plan: revert either commit independently; they are belt-and-braces layers of the same defense.

https://claude.ai/code/session_01XNtnkLbBiXZxfQQYLMpucB

ndycode avatar Jun 11 '26 08:06 ndycode

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. Credits must be used to enable repository wide code reviews.

[!WARNING]

Review limit reached

@ndycode, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 33 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 0b1a024f-24dd-4d68-b366-1951b1f21a0a

📥 Commits

Reviewing files that changed from the base of the PR and between 7204596d0fd30b8abd1dfd00a70315b7af1e0475 and 2915d4a35082e756638a39303dca98a0e5fbab70.

📒 Files selected for processing (1)
  • test/storage.test.ts
📝 Walkthrough

Walkthrough

Test infrastructure adds global and per-test-file afterEach hooks that call vi.restoreAllMocks() after each test to prevent leaked mock spies from affecting later test runs.

Changes

Vitest Mock Spy Cleanup

Layer / File(s) Summary
Mock restoration in afterEach hooks
test/helpers/global-sandbox.ts, test/storage.test.ts
Global sandbox helper registers a suite-level afterEach hook that restores all mocks, and test/storage.test.ts adds explicit unconditional vi.restoreAllMocks() in its own afterEach cleanup to prevent spy leakage between tests.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~5 minutes

Possibly related PRs

  • ndycode/codex-multi-auth#585: Both PRs touch test/storage.test.ts to add/guard vi.restoreAllMocks() cleanup to prevent leaked fs.rename spies from affecting later tests.
  • ndycode/codex-multi-auth#321: Both PRs adjust Vitest mock/spies lifecycle to prevent cross-test leakage (main adds vi.restoreAllMocks() in afterEach, retrieved strengthens CLI test isolation by fully resetting/hardening mocks before each test).

Suggested labels

bug

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed title follows conventional commits format with 'test' type, includes scope context about spy cascades, and is 59 chars under the 72-char limit.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed pr description is thorough and addresses all template sections with clear technical detail on the cross-test contamination issue and validation evidence.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests
  • [ ] Commit unit tests in branch claude/audit-71-storage-spy-hygiene
✨ Simplify code
  • [ ] Create PR with simplified code
  • [ ] Commit simplified code in branch claude/audit-71-storage-spy-hygiene

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar Jun 11 '26 08:06 coderabbitai[bot]

Full-suite validation of the global hook is in (npx vitest run --maxWorkers=1 on this branch, all 317 files):

  • 54 failing test names, every one of them in the §7 environment baseline — zero new names. The suite-wide afterEach(vi.restoreAllMocks) changes no test outcome anywhere outside the fix's target.
  • Four baseline names now pass that previously failed: keeps rotating backup order deterministic across parallel saves, preserves historical backups when creating the latest backup fails, removes primary, backup, and wal artifacts, and rotates backups and retains historical snapshots. These are exactly the storage-suite cascade victims — they were never genuine environment failures, they were collateral of the spy leaked by the EACCES-failing test ahead of them. The baseline shrinks from 58 to 54.

So the change is a strict improvement: file-level failures stay at the known 8 environment files, and the only name-level deltas are recoveries. Validation evidence retained at /tmp/global-restore-run.txt name-diff against docs/audits/evidence/test-baseline-2026-06-10.txt.


Generated by Claude Code

ndycode avatar Jun 11 '26 08:06 ndycode