codegraph
codegraph copied to clipboard
Fix watcher degradation on watch exhaustion and prolonged lock contention
Closes #876
Summary
This PR hardens the live file watcher around two reliability failure modes:
- Watch-resource exhaustion (EMFILE / ENFILE) now disables live watching cleanly instead of leaving the watcher half-broken.
- Prolonged sync lock contention (LockUnavailableError) no longer retries forever at the normal debounce cadence; it now uses bounded backoff and eventually degrades auto-sync explicitly.
The goal is to fail closed and clearly once live watching is no longer trustworthy, while preserving the current behavior for normal edits and short-lived contention.
What changed
Watch exhaustion
- Detects watch-resource exhaustion more explicitly
- Degrades/stops the watcher instead of just logging forever
- Emits a single actionable warning
- Adds an
onDegradedcallback so callers can observe permanent watcher degradation
Lock contention
- Keeps the current quiet behavior for brief lock contention
- Adds bounded retry backoff for repeated
LockUnavailableError - Stops infinite normal-debounce retries under long-lived contention
- Degrades auto-sync after the retry threshold is crossed
Internal cleanup
- Separates normal debounce scheduling from retry scheduling
- Tightens exhaustion detection so message matching is only used as a fallback when no
err.codeis available
Why
Before this change, the watcher could remain "alive" after it had effectively stopped being trustworthy:
- EMFILE / ENFILE could leave live watching unusable without a clean degraded/off transition
- Prolonged lock contention could keep the watcher retrying forever with no terminal state
- Callers could continue assuming auto-sync was still working even while the index drifted stale
This is especially problematic for long-running MCP/daemon sessions.
Tests
Added / extended watcher tests for:
- Startup watch exhaustion
- Runtime recursive watcher exhaustion
- Prolonged
LockUnavailableErrordegradation - Degraded-state callback notification
Verified with:
npx vitest run __tests__/watcher.test.ts __tests__/watch-policy.test.ts