Skip to content

test: fix flaky stdio auto-refresh polling timeout (partial evidence for #654) - #682

Merged
mohanagy merged 1 commit into
mainfrom
roadmap/654-vitest-gate
Aug 12, 2026
Merged

mohanagy merged 1 commit into
mainfrom
roadmap/654-vitest-gate

Conversation

@mohanagy

@mohanagy mohanagy commented Aug 12, 2026 •

Copy link
Copy Markdown
Owner

Summary

Partial, evidence-based progress on #654. This PR fixes one real, deterministic test flakiness bug and adds diagnostic output. It does not close #654 — the broader complete-suite "Failed to start forks worker" symptom that #654 exists to resolve remains unexplained by a repository-level cause and unresolved.

Problem and evidence

Issue #654's baseline flagged four files near a timeout/worker-start failure: compare-native-agent.test.ts, extract-frameworks.test.ts, retrieve.test.ts, stdio-server.test.ts.

What I found and fixed: in the 4-file flagged group at --maxWorkers=4, stdio-server.test.ts > stdio runtime > refreshes an active stdio session after an agent changes its workspace intermittently timed out at its 10s limit. Debug instrumentation showed it was blocked in event_mode: 'polling', waiting on the production default auto-refresh poll interval to observe a workspace-watcher event — too slow to reliably land inside the test's timeout under concurrent load. Injecting a fast poll interval through the pre-existing autoRefreshStarter seam made the failure disappear deterministically (verified across repeated runs, file-alone and in-group).

What is NOT fixed and remains open: repeated full-suite runs — both before and after this fix — show Error: [vitest-pool]: Failed to start forks worker for test files ..., traced to Caused by: Error: [vitest-pool-runner]: Timeout waiting for worker to respond (an IPC handshake timeout — not EMFILE/ENOMEM; ulimit -n is 1048576 on this machine). The affected files are different and effectively random on every run (12+ distinct file sets observed across 6 full runs, see Validation below), which argues against any single broken test and for suite-level/environmental worker-startup starvation. During one failing run, lsof at the time of failure showed multiple unrelated concurrent node processes (a different worktree's checkout, plus other agent/test workloads) competing for CPU on this shared machine. An independent teammate reproduced the identical signature (Failed to start forks worker + compare-native-agent.test.ts timeouts) on a completely unrelated branch/codebase at a wider batch width (21 files), with zero failures in small batches — cross-branch, cross-code reproduction that further points to local machine contention rather than a defect in this repository's code or tests.

No mechanism has been demonstrated that connects the stdio-server.test.ts polling fix to the broader worker-start-failure symptom, and no other narrowly-scoped repository correction is evidenced yet.

Exact scope

  • tests/unit/stdio-server.test.ts: fix one flaky test's dependency on the production default poll interval; add timeout-detail diagnostics to the local waitFor() helper; close the stdio input stream (end() before destroy()) in the test's finally block.
  • .gitignore: ignore the .issue-654-artifacts/ investigation-evidence directory (raw logs, an isolated repo clone used for controlled full-suite reruns, lsof/memory snapshots) so it is never accidentally committed.

Explicit non-goals (per issue contract, honored)

  • No product/graph/retrieval/Pack/extraction semantic changes — confirmed zero production files touched.
  • No global --maxWorkers=1 forced — not applied; no evidence justifies it as global policy.
  • No assertion skipped, quarantined, or weakened — the only test-code changes strictly add diagnostic detail and fix a real polling dependency; nothing was removed or loosened.
  • Did not retry until a run happened to pass and call it resolved — the full-suite worker-start failure was reproduced fresh, myself, after this fix (see Validation), and is reported as unresolved rather than papered over.

Files and symbols changed

  • tests/unit/stdio-server.test.ts
    • waitFor(condition, timeoutMs, timeoutDetail?) — new optional third parameter (string or thunk) included in the thrown timeout error.
    • Test 'refreshes an active stdio session after an agent changes its workspace': passes autoRefreshStarter: (watchPath, debounceSeconds, options) => startGraphAutoRefresh(watchPath, debounceSeconds, { ...options, pollIntervalMs: 10, maxPollIntervalMs: 20 }), using the pre-existing autoRefreshStarter injection point already present in src/runtime/stdio-server.ts and the pre-existing pollIntervalMs/maxPollIntervalMs options already present in src/infrastructure/watch.ts's startGraphAutoRefresh. No new seam was added to production code — both injection points already existed at origin/main.
    • finally block: input.end() added before the existing input.destroy().
  • .gitignore: added .issue-654-artifacts/.

No src/ files changed.

Tests

  • tests/unit/stdio-server.test.ts alone: 41/41 passing.
  • 4-file flagged group (compare-native-agent.test.ts, extract-frameworks.test.ts, retrieve.test.ts, stdio-server.test.ts) at --maxWorkers=1/2/4: before fix, 1 failure (the timeout above) at --maxWorkers=4; after fix, 303/303 passing at --maxWorkers=1/2/4, repeated.

Differential behavior

None for production code (unchanged). Test-only: the fixed test no longer depends on the production default poll interval to complete within its timeout; a future timeout in this waitFor() helper will report the pending watcher state instead of a bare "Timed out waiting for expected condition".

Validation commands and results

Environment: worktree /Users/mohammednaji/Desktop/projects/works/madar-654, branch roadmap/654-vitest-gate, base 06b373a447acfce895412ac10eb4e5228c5df0b7. Node v22.22.3 (matches issue reference). npm 12.0.2 — the issue names 12.0.1; this is an unresolved, flagged discrepancy, not normalized away. package-lock.json SHA-256 0144eb0ddf92f78c69f10089d0e0414485594966ff5be4f36f655c7aa5cff53e — matches the issue's audited value exactly; unchanged by this PR.

Command Result Notes
npm ci ✅ exit 0 88 packages, 0 vulnerabilities, lockfile unmodified
npm run typecheck ✅ exit 0
npm run build ✅ exit 0
npm run verify:pack-parity ✅ exit 0 "Packed retrieval parity passed for @lubab/madar 0.32.1"
npm pack --dry-run ✅ exit 0 398 files, 782.0 kB package
npm run registry:validate ✅ exit 0
npm run release:verify ✅ exit 0
tests/unit/stdio-server.test.ts alone ✅ 41/41
4-file flagged group, w=1/2/4, after fix ✅ 303/303 each before fix: 1 failure at w=4
npm run test:run (full suite, after fix, my own fresh run) ❌ exit 1 191/192 files passed as files, 2605 passed / 2 failed / 2 skipped tests, plus 12 unhandled Failed to start forks worker errors on: benchmark-artifact, extract-go, generate-spi-flag, mcp-registry-metadata, pack-quality-fixtures, pipeline, spi-cache, spi-calls, spi-framework-nextjs, spi-framework-route-metadata, spi-projector, spi-symbols. The 2 direct test failures were 60s timeouts in compare-native-agent.test.ts (matches the issue's originally recorded symptom). Duration 511s.
npm run test:run / npm run test:coverage (5 additional full-suite runs across the investigation, 3 before this fix, 2 after, captured with full logs/env/lsof/vm snapshots) ❌ all exit 1 Every run hit Failed to start forks worker on a different, non-overlapping set of 3–29 files. No two runs failed on the same file set.

Not completed: npm run test:coverage was not run as a final post-fix check in this session (the plain test:run runs above already demonstrate the unresolved symptom without adding coverage-instrumentation overhead); three-consecutive-clean-full-runs was attempted and did not succeed even once post-fix, so it was not repeated a third time once the pattern was established.

Compatibility impact

None. No production code, public API, CLI, MCP surface, or artifact format changed.

Risks

  • Low risk for the merged change itself: test-only, uses pre-existing seams, adds diagnostics, does not touch assertions.
  • Risk of this PR being misread as "the suite is now reliable": explicitly it is not — see Problem and evidence.

Rollback

Revert this commit; stdio-server.test.ts and .gitignore return to their prior state. No source regeneration, migration, or data changes are involved.

Ready for review verdict

Ready for review. The diff is small, narrowly scoped, uses pre-existing production seams, does not weaken any assertion, and is independently verified (by both the implementing session and this reviewing session, on two separate full local reproductions).

Ready for merge verdict

Not ready for merge as a resolution to #654. The PR's own change is safe to merge as a standalone flakiness fix, but #654's acceptance criteria (three consecutive clean full-suite runs, or a documented local-resource distinction plus repeated protected-CI success) are not met, and closing #654 on this evidence would be an overclaim. Recommend: merge this PR as a partial improvement (does not close #654), then continue #654 with either (a) evidence from the actual protected CI matrix (dedicated, non-shared runners) to establish whether the worker-start-starvation symptom is exclusively a local/shared-machine artifact, or (b) further investigation into whether a Vitest/tinypool configuration change (e.g., a longer worker-handshake timeout, or a lower default maxWorkers) is justified — neither of which is evidenced yet.

Related issues

Refs #654 (not closing — see verdicts above)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Tests

    • Improved auto-refresh test reliability with faster polling and clearer timeout diagnostics.
    • Added explicit input stream cleanup during test teardown.
  • Chores

    • Updated ignored files to exclude generated issue-related test artifacts.

…t diagnostics

Partial evidence for #654 — does not close the issue.

The 'refreshes an active stdio session after an agent changes its
workspace' test in tests/unit/stdio-server.test.ts intermittently timed
out at its 10s limit when run alongside other files (observed in the
4-file group compare-native-agent/extract-frameworks/retrieve/stdio-server
at --maxWorkers=4). Root cause: the test relied on the production default
auto-refresh poll interval to observe a workspace-watcher event, which is
too slow under concurrent load to reliably land inside the test timeout.

Fix (test-only, uses pre-existing production seams, no product-semantic
change):
- inject a fast pollIntervalMs/maxPollIntervalMs via the existing
  autoRefreshStarter injection point (src/runtime/stdio-server.ts) and
  startGraphAutoRefresh options (src/infrastructure/watch.ts)
- add timeout-detail diagnostics to the local waitFor() helper so a
  future recurrence reports the pending watcher state instead of a bare
  'Timed out waiting for expected condition'
- end() the stdio input stream before destroy() in the test's finally
  block to close it cleanly

Verified: the fix deterministically resolves this test's flakiness
(4-file flagged group: 1 failure -> 0 failures across repeated runs;
file alone: 41/41 passing).

This does NOT resolve the broader full-suite symptom. Repeated
npm run test:run / test:coverage runs on this machine still show
'[vitest-pool]: Failed to start forks worker' (IPC handshake timeout,
not EMFILE/ENOMEM) on 3-29 different, effectively random test files per
run, including a run taken after this fix. Evidence points to worker
handshake timeouts under local machine contention (concurrent unrelated
node/vitest processes were confirmed running via lsof during a failing
run), independently corroborated by a teammate reproducing the identical
signature on an unrelated branch/codebase at wider batch width. No
narrowly-scoped repository fix for that broader symptom is evidenced yet.
Acceptance criteria for #654 (three consecutive clean full-suite runs,
or a documented local-resource distinction plus repeatable protected CI
success) are not met. Full findings posted as an evidence-only comment
on #654.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 5a6c4f0c-f2f2-4a1b-bba4-4cda6d55cb1a

📥 Commits

Reviewing files that changed from the base of the PR and between 06b373a and af16e41.

📒 Files selected for processing (2)
  • .gitignore
  • tests/unit/stdio-server.test.ts

📝 Walkthrough

Walkthrough

The pull request updates stdio auto-refresh test synchronization and cleanup. It adds configurable timeout diagnostics, short watcher polling intervals, and explicit input stream termination. It also ignores issue-specific artifacts.

Changes

Stdio test synchronization

Layer / File(s) Summary
Auto-refresh test synchronization
tests/unit/stdio-server.test.ts
The test supports dynamic waitFor timeout messages, uses 10–20 ms watcher polling intervals, reports watcher state on timeout, and ends the input stream during cleanup.

Issue artifact exclusion

Layer / File(s) Summary
Issue artifact ignore rule
.gitignore
The ignore configuration excludes .issue-654-artifacts/.

Estimated code review effort: 2 (Simple) | ~10 minutes

✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch roadmap/654-vitest-gate

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

@mohanagy mohanagy left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Review verdict: the submitted diff is acceptable as a standalone, test-only flakiness improvement, but it is not a resolution of #654.

The scope is narrow: .gitignore plus tests/unit/stdio-server.test.ts; no production source changed. The existing protected CI run completed successfully across the six OS/Node jobs, which supports reviewing this PR independently from the broader worker-start investigation.

Two conditions remain:

  1. Keep Refs #654, not Closes #654, and leave #654 open. Closing #654 still requires the issue's documented local-resource distinction plus repeated protected-CI success, or the alternative clean-local-run criterion.
  2. Correct the orchestration record before merge: the remote PR/branch head is currently af16e41b14a4e63f2dc6b92025c520effc79ecfc, while the final #648 comment reports db7300ce. GitHub has no remote commit matching that latter prefix. Either push the intended later commit or amend the record to the actual reviewed head.

Subject to resolving that provenance mismatch, I support merging this PR as a standalone flakiness fix. Do not treat the merge as satisfying #654.

@mohanagy
mohanagy marked this pull request as ready for review August 12, 2026 14:45
@mohanagy
mohanagy merged commit 3371ada into main Aug 12, 2026
17 of 19 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.

[P0] Stabilize the complete Vitest suite and protected CI merge gate

1 participant