codegraph icon indicating copy to clipboard operation
codegraph copied to clipboard

Fix watcher degradation on watch exhaustion and prolonged lock contention

Open thismilktea opened this issue 5 months ago • 0 comments

Closes #876

Summary

This PR hardens the live file watcher around two reliability failure modes:

  1. Watch-resource exhaustion (EMFILE / ENFILE) now disables live watching cleanly instead of leaving the watcher half-broken.
  2. 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 onDegraded callback 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.code is 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 LockUnavailableError degradation
  • Degraded-state callback notification

Verified with:

npx vitest run __tests__/watcher.test.ts __tests__/watch-policy.test.ts

thismilktea avatar Jun 14 '26 08:06 thismilktea