The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): time out slow context file reads
Edder Talmor972b94bd2935
diff --git a/agent/prompt_builder.py b/agent/prompt_builder.pyindex 24ea2b17967..e5ea3f5d1cd 100644--- a/agent/prompt_builder.py+++ b/agent/prompt_builder.py@@ -7,6 +7,7 @@ assemble pieces, then combines them with memory and ephemeral prompts.import jsonimport loggingimport os+import queueimport sysimport threadingimport contextvars@@ -58,6 +59,42 @@ logger = logging.getLogger(__name__)from tools.threat_patterns import scan_for_threats as _scan_for_threats+# Read deadline for context files (SOUL.md, AGENTS.md, .cursorrules, ...).+# Intentionally short: network-backed filesystems (iCloud Drive, OneDrive,+# NFS) can fault-in an evicted file and block a cold read indefinitely, which+# stalls system-prompt assembly before the first turn.+_CONTEXT_FILE_READ_TIMEOUT_SECS = 5.0+++def _read_text_with_timeout(path: Path, timeout: Optional[float] = None) -> Optional[str]:+ """``path.read_text()`` on a daemon thread so a slow file can't stall startup.++ Returns the text, or ``None`` after *timeout* seconds (logged at WARNING;+ the orphaned reader thread finishes on its own). Read errors propagate to+ the caller exactly as a direct ``read_text`` would, so existing+ ``try/except`` handling at each site is unchanged.+ """+ if timeout is None:+ timeout = _CONTEXT_FILE_READ_TIMEOUT_SECS+ result: "queue.Queue[tuple[bool, object]]" = queue.Queue(maxsize=1)++ def _reader() -> None:+ try:+ result.put((True, path.read_text(encoding="utf-8")))+ except BaseException as exc: # re-raised on the caller thread+ result.put((False, exc))++ threading.Thread(target=_reader, daemon=True, name=f"context-read:{path.name}").start()+ try:+ ok, value = result.get(timeout=timeout)+ except queue.Empty:+ logger.warning("Context file %s read timed out after %.1fs; skipping", path, timeout)+ return None+ if ok:+ return value # type: ignore[return-value]+ raise value # type: ignore[misc]++def _scan_context_content(content: str, filename: str) -> str:"""Scan context file content for injection. Returns sanitized content.@@ -2250,7 +2287,7 @@ def load_soul_md(if not soul_path.exists():return Nonetry:- content = soul_path.read_text(encoding="utf-8").strip()+ content = (_read_text_with_timeout(soul_path) or "").strip()if not content:return Nonecontent = _scan_context_content(content, "SOUL.md")@@ -2270,7 +2307,7 @@ def _load_hermes_md(cwd_path: Path, context_length: Optional[int] = None) -> strif not hermes_md_path:return ""try:- content = hermes_md_path.read_text(encoding="utf-8").strip()+ content = (_read_text_with_timeout(hermes_md_path) or "").strip()if not content:return ""content = _strip_yaml_frontmatter(content)@@ -2340,7 +2377,7 @@ def _load_agents_md(cwd_path: Path, context_length: Optional[int] = None) -> strif not candidate.exists():continuetry:- content = candidate.read_text(encoding="utf-8").strip()+ content = (_read_text_with_timeout(candidate) or "").strip()except Exception as e:logger.debug("Could not read %s: %s", candidate, e)continue@@ -2381,7 +2418,7 @@ def _load_claude_md(cwd_path: Path, context_length: Optional[int] = None) -> strcandidate = cwd_path / nameif candidate.exists():try:- content = candidate.read_text(encoding="utf-8").strip()+ content = (_read_text_with_timeout(candidate) or "").strip()if content:content = _scan_context_content(content, name)result = f"## {name}\n\n{content}"@@ -2400,7 +2437,7 @@ def _load_cursorrules(cwd_path: Path, context_length: Optional[int] = None) -> scursorrules_file = cwd_path / ".cursorrules"if cursorrules_file.exists():try:- content = cursorrules_file.read_text(encoding="utf-8").strip()+ content = (_read_text_with_timeout(cursorrules_file) or "").strip()if content:content = _scan_context_content(content, ".cursorrules")cursorrules_content += f"## .cursorrules\n\n{content}\n\n"@@ -2412,7 +2449,7 @@ def _load_cursorrules(cwd_path: Path, context_length: Optional[int] = None) -> smdc_files = sorted(cursor_rules_dir.glob("*.mdc"))for mdc_file in mdc_files:try:- content = mdc_file.read_text(encoding="utf-8").strip()+ content = (_read_text_with_timeout(mdc_file) or "").strip()if content:content = _scan_context_content(content, f".cursor/rules/{mdc_file.name}")cursorrules_content += f"## .cursor/rules/{mdc_file.name}\n\n{content}\n\n"diff --git a/agent/subdirectory_hints.py b/agent/subdirectory_hints.pyindex 11e4a7d4f9f..41fb68ba880 100644--- a/agent/subdirectory_hints.py+++ b/agent/subdirectory_hints.py@@ -20,7 +20,7 @@ import shlexfrom pathlib import Pathfrom typing import Dict, Any, Optional, Set-from agent.prompt_builder import _scan_context_content+from agent.prompt_builder import _read_text_with_timeout, _scan_context_contentlogger = logging.getLogger(__name__)@@ -105,7 +105,7 @@ class SubdirectoryHintTracker:try:if not candidate.is_file():continue- content = candidate.read_text(encoding="utf-8").strip()+ content = (_read_text_with_timeout(candidate) or "").strip()except (OSError, UnicodeDecodeError):continueif content:@@ -285,7 +285,7 @@ class SubdirectoryHintTracker:except OSError:continuetry:- content = hint_path.read_text(encoding="utf-8").strip()+ content = (_read_text_with_timeout(hint_path) or "").strip()if not content:continue# Skip content we've already injected. The same AGENTS.md isdiff --git a/tests/agent/test_prompt_builder.py b/tests/agent/test_prompt_builder.pyindex af338c08ffd..d580e4195c8 100644--- a/tests/agent/test_prompt_builder.py+++ b/tests/agent/test_prompt_builder.py@@ -5,6 +5,8 @@ import importlibimport loggingimport osimport sys+import time+from pathlib import Pathimport pytest@@ -1140,3 +1142,40 @@ class TestParallelToolCallGuidance:# =========================================================================+++class TestContextFileReadTimeout:+ def test_slow_hermes_md_is_skipped_and_agents_md_still_loads(self, tmp_path, monkeypatch, caplog):+ (tmp_path / ".git").mkdir()+ (tmp_path / ".hermes.md").write_text("Hermes project rules.")+ (tmp_path / "AGENTS.md").write_text("Agent fallback rules.")+ # Patch the module object build_context_files_prompt actually closes+ # over: an earlier test re-imports agent.prompt_builder, so the+ # sys.modules entry can be a different module object.+ pb_mod = sys.modules[build_context_files_prompt.__module__]+ monkeypatch.setattr(pb_mod, "_CONTEXT_FILE_READ_TIMEOUT_SECS", 0.05)++ original_read_text = Path.read_text++ def slow_read_text(self, *args, **kwargs):+ if self.name == ".hermes.md":+ time.sleep(0.6)+ return original_read_text(self, *args, **kwargs)++ monkeypatch.setattr(Path, "read_text", slow_read_text)++ start = time.monotonic()+ with caplog.at_level(logging.WARNING, logger=pb_mod.__name__):+ result = build_context_files_prompt(cwd=str(tmp_path))+ elapsed = time.monotonic() - start++ assert elapsed < 0.4, f"context load blocked for {elapsed:.2f}s"+ assert "Agent fallback rules" in result+ assert "Hermes project rules" not in result+ assert "timed out" in caplog.text.lower()++ def test_read_errors_still_propagate_to_caller(self, tmp_path):+ from agent.prompt_builder import _read_text_with_timeout++ with pytest.raises(FileNotFoundError):+ _read_text_with_timeout(tmp_path / "missing.md", timeout=1.0)diff --git a/tests/agent/test_subdirectory_hints.py b/tests/agent/test_subdirectory_hints.pyindex 85b89f647ef..2fe6e125d42 100644--- a/tests/agent/test_subdirectory_hints.py+++ b/tests/agent/test_subdirectory_hints.py@@ -1,5 +1,7 @@"""Tests for progressive subdirectory hint discovery."""+import time+import pytestfrom pathlib import Pathfrom unittest.mock import patch@@ -116,6 +118,40 @@ class TestSubdirectoryHintTracker:+ def test_timeout_skips_slow_hint_files(self, project, monkeypatch, caplog):+ """Slow hint reads time out instead of blocking the turn."""+ backend = project / "backend"+ (backend / "AGENTS.md").write_text("Backend-specific instructions")+ import sys++ from agent import subdirectory_hints as sh_mod++ # Patch the module object the hint tracker's helper closes over.+ pb_mod = sys.modules[sh_mod._read_text_with_timeout.__module__]+ monkeypatch.setattr(pb_mod, "_CONTEXT_FILE_READ_TIMEOUT_SECS", 0.05)++ original_read_text = Path.read_text++ def slow_read_text(self, *args, **kwargs):+ if self.name.lower() == "agents.md" and self.parent == backend:+ time.sleep(0.6)+ return original_read_text(self, *args, **kwargs)++ monkeypatch.setattr(Path, "read_text", slow_read_text)++ tracker = SubdirectoryHintTracker(working_dir=str(project))+ start = time.monotonic()+ with caplog.at_level("WARNING", logger="agent.prompt_builder"):+ result = tracker.check_tool_call(+ "read_file", {"path": str(project / "backend" / "src" / "main.py")}+ )+ elapsed = time.monotonic() - start++ assert elapsed < 0.4, f"hint load blocked for {elapsed:.2f}s"+ assert result is None+ assert "timed out" in caplog.text.lower()++class TestPermissionErrorHandling:"""Regression tests for PermissionError in filesystem checks (ref #6214)."""