Skip to content

test(runtime): stop worker-recovery retries from scanning inside later tests - #22567

Merged
nwparker merged 1 commit into
mainfrom
fix/worker-recovery-retry-test-isolation
Sep 23, 2026
Merged

nwparker merged 1 commit into
mainfrom
fix/worker-recovery-retry-test-isolation

Conversation

@nwparker

@nwparker nwparker commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​102 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​101
Prod 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​23 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​23

ELI5

A background "retry" in the app keeps re-checking for terminals it could not recover yet, over and over, forever. In the test suite nothing ever satisfies it, so one test would start that loop and it would keep running for the rest of the test file — quietly doing extra work in the middle of other tests. Every so often that stray work tipped an unrelated test's counter by one and CI went red for no real reason. This turns the loop off at the end of each test.

What Changed

Before: test / tests node 24 8/8 failed intermittently on unrelated PRs with

src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-03.spec.ts:353
AssertionError: expected "vi.fn()" to be called 3 times, but got 4 times

and, on other runs, at different assertions in worktree-setup-and-startup.spec.ts. Every one of them passed when its file was run on its own.

After: no test's background work runs inside another test, so those counters are deterministic.

Mechanism. RuntimeLegacyWorkerTerminalRecoveryController.armRetry schedules reconcile() on a 1s → 2s → 4s → … → 30s backoff and keeps re-arming while any dispatch is still deferred. reconcile() resolves worktrees, which calls listWorktrees. In orca-runtime.test.ts — one file that runs 1299 tests against one module-scoped listWorktrees stub — nothing ever materialises a deferred worker, so a single early test armed a loop that never stopped. Every 1–30 seconds of wall clock it fired one more listWorktrees call into whatever test happened to be running. Which test that was depends purely on machine speed, which is why it only showed up under full-suite CI load and never in isolation, and why the failing assertion moved around.

The change:

  • RuntimeLegacyWorkerTerminalRecoveryController gains cancelAllRetries(), and a module-level set tracks controllers while they have a timer armed — a controller joins in armRetry and leaves in cancelScope as soon as it has no scopes left, so nothing is retained past the loop it belongs to.
  • __cancelLegacyWorkerTerminalRecoveryRetriesForTests() stops every armed loop; the shared resetRuntimeTestMocks() (which already runs in both beforeEach and afterEach) calls it alongside the other per-test resets it already does.
  • A new unit test pins the retry loop, per-controller cancellation, and the cancel hook reaching every armed controller.

No production behaviour changes: the retry still arms, still backs off, and still stops the same way it did when a worker materialises.

Why

The counter in the failing test is a real invariant — scanning repo A twice and repo B once proves per-repo TTL expiry without sibling coupling — so loosening it, retrying it, or skipping it would have thrown away the assertion and left the stray scans landing on the next victim. Fixing the leak at its source makes all of the affected assertions deterministic, not just this one, which matters because the same stray call had already broken a different test (a mockResolvedValueOnce consumed early in worktree-setup-and-startup.spec.ts).

Alternatives considered:

  • Scope the assertion to its own repo paths (the pattern worktree-scan-cache-ttl.spec.ts uses). Would have fixed this one line and left the loop running for every other assertion in the file.
  • Track and dispose runtimes from test code instead of touching the controller. Needs a registry plus a cast through protected legacyWorkerRecovery in test code; more machinery, and the cancel capability belongs on the thing that owns the timer.
  • Mock the recovery module in this suite. Would have deleted the coverage the suite has for recovery.

Linked Issue

Fixes #

Visual Proof

N/A — test-isolation fix. No UI, no user-visible behaviour, and no production code path changes; the only production addition is a cancel method that nothing in the app calls yet.

Testing

Reproducing the CI flake directly needs its exact load profile, and I could not make it fail on this machine (6 repeat runs of the file under 24 saturating CPU hogs, plus a full src/main/runtime run — all green). So I measured the defect itself instead of the symptom.

I added a temporary afterEach probe to the shared runtime test lifecycle that, after every one of the 1299 tests, waits and records any listWorktrees call arriving after the test had ended:

stray post-test listWorktrees calls
before 25
after 0

Each stray call was attributed to the timer that fired it. All 25 came back to RuntimeLegacyWorkerTerminalRecoveryController.armRetry at delays of 16000 ms and 30000 ms, armed during a much earlier test — direct confirmation of the mechanism. Splitting the probe into a microtask phase and a real-clock phase showed micro=0 macro=1 for every one, proving a wall-clock timer, not an unawaited promise, was driving them.

The probe was removed before committing; only the fix and its unit test are in this PR.

Then, on the committed change:

  • pnpm tc — pass
  • pnpm run check:code-quality:changed — pass (0 new findings across 5 changed files)
  • npx vitest run src/main/runtime — 846 files / 8614 tests passed, 3 files / 31 tests skipped
  • npx vitest run src/main/runtime/orca-runtime.test.ts — 1298 passed, 1 skipped
  • New runtime-legacy-worker-terminal-recovery-retry.test.ts — 3 passed

Platform: macOS (arm64), Node 24. The change is platform-agnostic test-lifecycle and timer bookkeeping — no paths, shells, or process spawning — so there is nothing Linux/Windows/SSH-specific to exercise.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Security: none — no new input, I/O, or process surface.
  • Cross-platform: timer bookkeeping only; identical on macOS/Linux/Windows.
  • Remote SSH: the retry is already scoped per connection (ssh:<id> vs local); cancellation iterates those same scopes and is only reachable from tests.
  • Mobile: unaffected.
  • Backwards compatibility: no wire, storage, or API change.
  • Performance: the tracking set holds at most one entry per controller that currently has a timer armed and drops it as soon as the controller has none, so it cannot grow with time.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

…r tests

The legacy worker terminal recovery retry re-arms itself on a 1s..30s backoff
for as long as a dispatch stays deferred. Nothing in the runtime suite ever
resolves one, so a single test armed a loop that kept re-running recovery --
and the worktree scans it issues -- through the shared `listWorktrees` stub for
the rest of the file's run, landing inside whichever test was executing when the
timer fired. That is what made `lineage-and-scan-cache-part-03`'s per-repo TTL
test see 4 scans instead of 3 only under CI load.

Give the controller a `cancelAllRetries`, track controllers while they have a
timer armed, and cancel them from the shared runtime test lifecycle reset.

Measured over the whole 1299-test file with an afterEach probe: 25 stray
post-test `listWorktrees` calls before, 0 after.
@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

The controller now tracks controllers with armed retry timers and provides a test-only hook to cancel their retries. The test-mock facade exposes the hook, and runtime test setup calls it during reset. New fake-timer tests cover retry firing and cancellation.

Priority: ⬇️ Low

Merge Risk: 🔵 Low · up to 3c9f4

Tests can still intermittently scan the shared worktree stub after cleanup when a reconciliation is in flight. This is a bounded test-stability risk to address or explicitly accept before merging.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 3 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: preventing legacy worker-recovery retries from affecting later tests.
Description check ✅ Passed The description is comprehensive and covers the change, cause, alternatives, testing, platform impact, and checklist. The required Linked Issue field remains empty because no tracking issue exists, bu…
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.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: f409d206-dbe1-46bc-82a8-b4090db5e593

📥 Commits

Reviewing files that changed from the base of the PR and between 6847390 and 3c9f409.

📒 Files selected for processing (5)
  • src/main/runtime/orca-runtime-test-lifecycle.spec.ts
  • src/main/runtime/orca-runtime-test-mocks.spec.ts
  • src/main/runtime/orca-runtime-test-mocks/imported-values.spec.ts
  • src/main/runtime/runtime-legacy-worker-terminal-recovery-controller.ts
  • src/main/runtime/runtime-legacy-worker-terminal-recovery-retry.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.

Comment on lines +25 to +26
for (const controller of Array.from(controllersWithArmedRetries)) {
controller.cancelAllRetries()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- changed file outline ---'
ast-grep outline src/main/runtime/runtime-legacy-worker-terminal-recovery-controller.ts
printf '%s\n' '--- changed file ---'
cat -n src/main/runtime/runtime-legacy-worker-terminal-recovery-controller.ts
printf '%s\n' '--- diff base..head ---'
git diff --stat 6847390c0a4ff47f3ca4984953d650b973dc506e 3c9f40900acd1d644970648c263b8bd0e24593dc
git diff --unified=40 6847390c0a4ff47f3ca4984953d650b973dc506e 3c9f40900acd1d644970648c263b8bd0e24593dc -- src/main/runtime/runtime-legacy-worker-terminal-recovery-controller.ts
printf '%s\n' '--- controller references ---'
rg -n -C 5 'RuntimeLegacyWorkerTerminalRecoveryController|updateRetry|cancelAllRetries|ports\.reconcile|reconcile\(' src/main

Repository: stablyai/orca

Length of output: 41097


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions

Length of output: 33899


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- recovery files ---'
rg -l 'runLegacyWorkerTerminalRecovery|LegacyWorkerRecoveryPorts|reconcileLegacyWorkerTerminals|updateRetry|__cancelLegacyWorkerTerminalRecoveryRetriesForTests' src/main/runtime
printf '%s\n' '--- runner ---'
cat -n src/main/runtime/runtime-legacy-worker-terminal-recovery-runner.ts
printf '%s\n' '--- types ---'
cat -n src/main/runtime/runtime-legacy-worker-terminal-recovery-types.ts
printf '%s\n' '--- production wiring ---'
rg -n -C 12 'reconcileLegacyWorkerTerminals|legacyWorkerRecovery|RuntimeLegacyWorkerTerminalRecoveryController|updateRetry' src/main/runtime --glob '*.ts' --glob '!*.test.ts'
printf '%s\n' '--- changed retry test ---'
cat -n src/main/runtime/runtime-legacy-worker-terminal-recovery-retry.test.ts

Repository: stablyai/orca

Length of output: 41731


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- exact production port wiring ---'
rg -n -C 25 'LegacyWorkerRecoveryPorts|reconcileLegacyWorkerTerminals|updateLegacyWorkerTerminalRecoveryRetry|legacyWorkerRecovery' src/main/runtime/orca-runtime-preserved-branch-cleanup.ts src/main/runtime/orca-runtime-automation-operations.ts src/main/runtime/orca-runtime-service.ts src/main/runtime --glob '*.ts' --glob '!*.test.ts'
printf '%s\n' '--- test hook lifecycle callers ---'
rg -n -C 12 '__cancelLegacyWorkerTerminalRecoveryRetriesForTests' src/main

Repository: stablyai/orca

Length of output: 42593


Prevent pending reconciliation from re-arming cancelled retries.

armRetry starts ports.reconcile without awaiting it. Production wiring routes that call back through legacyWorkerRecovery.reconcile, and the recovery runner calls ports.updateRetry after asynchronous recovery work. If cancellation occurs while reconciliation is pending, cancelAllRetries() deletes the retry, but a deferred result later reaches updateRetry, which creates and arms a new retry. Invalidate pending retries during cancellation and add a regression test that resolves a deferred reconciliation after cancellation, then advances timers.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

  • Controller gains a test-only cancel path: runtime-legacy-worker-terminal-recovery-controller.ts adds a module-level controllersWithArmedRetries set — joined in armRetry, left in cancelScope once no scopes remain — plus cancelAllRetries() and the exported __cancelLegacyWorkerTerminalRecoveryRetriesForTests() hook.
  • Shared test lifecycle stops armed retries: resetRuntimeTestMocks() (already registered as both beforeEach and afterEach) now calls the hook, so a replay loop armed in one test cannot fire inside the next.
  • Facade plumbing: the new test-only export is threaded through orca-runtime-test-mocks.spec.ts and imported-values.spec.ts, keeping the two-layer compatibility facade in sync.
  • New unit coverage: runtime-legacy-worker-terminal-recovery-retry.test.ts pins the 1000ms first fire, per-controller cancellation, and the hook reaching every armed controller.

I verified the bookkeeping invariants directly: every armed timer is added to the set in armRetry, the only removal path is cancelScope, and the .catch re-arm is gated on retries.get(scopeKey) === retry, so a cancelled scope cannot resurrect. The production cancelScope caller in orca-runtime-notify-ssh-state-changed.ts:24 stays consistent, and the set holds at most one entry per controller with a live retry, so there is no new unbounded retention. Tests 2 and 3 genuinely fail if the cancellation or the hook regresses, so the fix is real coverage rather than a loosened assertion.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker merged commit 12a7ffd into main Sep 23, 2026
31 checks passed
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.

1 participant