Skip to content

Clear armed reconnect timers in browser-sync-service test teardown - #2700

Merged
mstomar125 merged 1 commit into
mainfrom
issue-2684-reconnect-timer-leak
Sep 17, 2026
Merged

mstomar125 merged 1 commit into
mainfrom
issue-2684-reconnect-timer-leak

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

Problem

bun run test (full suite) intermittently failed with 1 failed test file / 1 failed test, reported as an unhandled error originating in BrowserSyncService.scheduleReconnect — a cross-file timing leak, not a genuine assertion failure. browser-sync-service.test.ts always passed 47/47 in isolation.

Root cause

BrowserSyncService's connect() catch block arms scheduleReconnect's indefinite-retry setTimeout on failure (browser-sync-service.ts:180-181, :356-367). Two gaps let that timer escape the test that armed it:

  1. The top-level afterEach in browser-sync-service.test.ts reset stores/mocks but never called browserSyncService.destroy() — the only call that clears reconnectTimeout (:392-394). A timer armed anywhere in the file could survive teardown.
  2. One test in the Reconnection Logic block (should handle EventSource creation error) swaps to real timers mid-test and only restores fake ones in a finally, without clearing any timer armed during that real-timer window. A reconnect armed there is a real setTimeout (>=1000ms) that can fire while an unrelated test file is executing later in the suite, surfacing as a misattributed unhandled-error failure.

Fix

  • Call browserSyncService.destroy() in the top-level afterEach so no reconnect timer can outlive its test.
  • Also call destroy() explicitly in the real-timer test's finally block, before vi.useFakeTimers() restores fake timers, so the real timer handle is cleared while real clearTimeout is still in effect.

Verification

  • browser-sync-service.test.ts still passes 47/47 in isolation.
  • Attempted to reproduce the flake on unfixed main first: 6 full-suite runs (~11 min), all green on the target flake (one unrelated, pre-existing perf-benchmark timing flake surfaced once, in architecture-benchmarks.test.ts, unaffected by this change). The intermittency matches the issue's own description — did not force a repro, deferred to the issue's already-solid root-cause diagnosis per task guidance.
  • Full suite (bun run test) passes clean on the fixed branch; pre-push gate (test:all, cargo build --bin nodespaced, test:e2e) passed clean.

Closes #2684

🤖 Generated with Claude Code

BrowserSyncService.connect()'s catch block arms scheduleReconnect's
indefinite-retry setTimeout on failure. The top-level afterEach reset
stores and mocks but never called browserSyncService.destroy(), the only
call that clears that timer, so a timer armed by one test could survive
into another test file's run.

One test in the Reconnection Logic block also swapped to real timers
mid-test and only restored fake ones in a finally, without clearing any
timer armed during that real-timer window — a real >=1000ms setTimeout
that could fire while an unrelated test file was executing later in the
suite, surfacing as a misattributed unhandled-error failure.

Call destroy() in the top-level afterEach so no reconnect timer outlives
its test, and destroy() explicitly in that test's finally block (while
real timers are still active) before restoring fake timers.

Closes #2684

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@mstomar125

Copy link
Copy Markdown
Contributor Author

Code Review Summary

Independent verification of the fix for #2684 (armed reconnectTimeout leaking across test files in browser-sync-service.test.ts). This is a test-only change (12 additions, 0 deletions, single file: packages/desktop-app/src/tests/services/browser-sync-service.test.ts); no production code touched.

Root-cause claim verified against source (packages/desktop-app/src/lib/services/browser-sync-service.ts):

  • connect()'s catch block (line 181) and its EventSource.onerror handler (line 176) both call scheduleReconnect().
  • scheduleReconnect() (lines 356-367) arms this.reconnectTimeout = setTimeout(...) with an exponential-backoff delay (>=1000ms), retrying indefinitely by design (no attempt cap in the actual field/logic — the reconnectAttempts counter only affects delay, confirming the issue's "retries indefinitely" framing).
  • destroy() (lines 389-404) is the only method that clears it: if (this.reconnectTimeout) { clearTimeout(this.reconnectTimeout); this.reconnectTimeout = null; }, then also closes any open eventSource and resets connectionState/reconnectAttempts. The if guard makes it a safe no-op when nothing is pending — confirmed both by reading the code and by the pre-existing "should handle EventSource onerror and schedule reconnect" test, which already calls destroy() with nothing armed and passes.

Vitest hook-ordering claim verified: the top-level afterEach (line 100, new destroy() call at line 105) is outer relative to the Reconnection Logic describe block's local afterEach (line 955, vi.useRealTimers()). Vitest runs afterEach innermost-first, so by the time the new top-level destroy() runs after any test in that block, real timers are already restored — clearTimeout operates on the correct (real) timer API. This matches the PR's own reasoning and is consistent with all 3 full-suite runs coming back clean on this specific bug (see below).

Test-file read directly (not just diffed): confirmed the "should handle EventSource creation error" test (lines 1016-1049) matches the issue's description exactly — vi.useRealTimers() at the top, connect() throws via a mocked EventSource constructor, and the new browserSyncService.destroy() call sits in the finally block before vi.useFakeTimers() restores fake timers, so the real timer handle is cleared while real clearTimeout is still in effect.

No broken assertions: grepped every getConnectionState()/isConnected()/reconnectAttempts usage in the file (14 call sites). Every assertion either expects 'disconnected'/false (which is exactly what destroy()'s new/pre-existing side effects produce) or explicitly calls connect() and simulates onopen within the same test before asserting 'connected'. Nothing relies on connection state or reconnectAttempts carrying over from a prior test — if anything, the fix makes inter-test isolation stricter and more correct than before.

Findings

🟢 Nitpick — issue text references a nonexistent method name. #2684's body suggests calling browserSyncService.disconnect() in the top-level afterEach, but the class has no disconnect() method — only destroy() (confirmed via grep of all method definitions in browser-sync-service.ts). The PR correctly used the real method (destroy()) rather than the issue's stale/incorrect name. No action needed, just noting for the record in case the issue's wording is copy-pasted elsewhere later.

🟢 Nitpick — redundant double destroy() in one test. In "should handle EventSource creation error", destroy() is called once in the test's own finally (line 1045) and then again moments later via the top-level afterEach (line 105) once that test completes. This is harmless — destroy() is idempotent and guarded — and arguably intentional belt-and-suspenders given the real/fake timer subtlety being fixed, so not requesting a change.

No 🔴 Critical or 🟡 Improvement findings. The fix is minimal, targeted, matches the issue's own suggested fix, touches no production code, and doesn't paper over the underlying design (indefinite-retry reconnect is intentional/documented) — it just ensures tests actually tear down the service they exercise, which they always should have been doing.

Full-suite verification (3x bun run test, sequential, from this worktree)

  • Run 1: 1 failed | 246 passed (247) test files, 5084 passed | 1 failed tests. The single failure was src/tests/performance/architecture-benchmarks.test.ts (render performance scales linearly with node count, a scaling-factor assertion) — the known, pre-existing, timing-sensitive perf flake called out in the PR description, unrelated to this fix. No scheduleReconnect/unhandled-error failure.
  • Run 2: 247 passed (247) test files, 5085 passed (5085) tests. Fully clean.
  • Run 3: 247 passed (247) test files, 5085 passed (5085) tests. Fully clean.

Also ran browser-sync-service.test.ts in isolation: 47 passed (47).

Across all 3 full-suite runs, there is zero occurrence of the target bug (scheduleReconnect unhandled error / stray BrowserSyncService.connect timer firing in an unrelated file). The only flake observed is the pre-existing, out-of-scope perf benchmark, exactly as anticipated.

Recommendation: APPROVE

@mstomar125 mstomar125 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

@mstomar125

Copy link
Copy Markdown
Contributor Author

Address-Review Triage

Reviewed the independent pragmatic-code-review above (verdict: APPROVE, 0 🔴 Critical, 0 🟡 Improvement, 2 🟢 Nitpicks).

  • ✅ Addressed: 0
  • ⏭️ Skipped: 2 (both informational, no code change warranted)
    1. "Issue browser-sync-service tests leak a reconnect timer, causing a cross-file flake in full-suite runs #2684's body references a disconnect() method that doesn't exist" — this is a note about the issue's own (stale) wording, not the PR. The PR already calls the real method, destroy(). Nothing to change.
    2. "destroy() is called twice in the real-timer test (once in its own finally, again via the new top-level afterEach)" — intentional belt-and-suspenders, explicitly called out as harmless (guarded/idempotent) in the review itself and in the PR description's rationale. No action needed.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: No code changes resulted from this review — both findings were informational nitpicks with no actionable follow-up, and the reviewer independently verified timer-teardown correctness, 47/47 isolated pass, and 3x clean full-suite runs before approving. Nothing new to re-verify.

The PR is ready for merge.

@mstomar125
mstomar125 merged commit c608d51 into main Sep 17, 2026
@mstomar125
mstomar125 deleted the issue-2684-reconnect-timer-leak branch September 17, 2026 08:38
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.

browser-sync-service tests leak a reconnect timer, causing a cross-file flake in full-suite runs

1 participant