Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(learn): make live traffic learning use the shared error classifier (#4110)

Tejas Choprae6eaa4117917
diff --git a/headroom/learn/_shared.py b/headroom/learn/_shared.py
index ba6f9944e..0d54d03ea 100644
--- a/headroom/learn/_shared.py
+++ b/headroom/learn/_shared.py
@@ -69,7 +69,14 @@ _ERROR_PATTERNS: list[tuple[re.Pattern[str], ErrorCategory]] = [
ErrorCategory.USER_REJECTED,
),
(re.compile(r"[Ss]ibling tool call errored", re.I), ErrorCategory.SIBLING_ERROR),
- (re.compile(r"exit code|non-zero|exited with", re.I), ErrorCategory.EXIT_CODE),
+ # A signal kill is the shell's exit status 128+N, so it shares EXIT_CODE.
+ (
+ re.compile(
+ r"exit code|non-zero|exited with|killed by signal|^\s*Killed(?::\s*\d+)?\s*$",
+ re.I | re.M,
+ ),
+ ErrorCategory.EXIT_CODE,
+ ),
(
re.compile(r"BUILD FAILED|compilation error|compile error", re.I),
ErrorCategory.BUILD_FAILURE,
diff --git a/headroom/memory/traffic_learner.py b/headroom/memory/traffic_learner.py
index 2939b06a9..adef33610 100644
--- a/headroom/memory/traffic_learner.py
+++ b/headroom/memory/traffic_learner.py
@@ -33,6 +33,8 @@ from enum import Enum
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar
+from headroom.learn._shared import classify_error
+
if TYPE_CHECKING:
from headroom.learn.models import ProjectInfo
from headroom.memory.backends.local import LocalBackend
@@ -207,40 +209,64 @@ def _strip_leading_cd(cmd: str) -> str:
# =============================================================================
-# Error Classification (reused from learn/scanner.py patterns)
+# Error Detection
# =============================================================================
-_ERROR_PATTERNS: list[tuple[re.Pattern[str], str]] = [
- (
- re.compile(r"No such file or directory|ENOENT|FileNotFoundError|does not exist", re.I),
- "file_not_found",
- ),
- (re.compile(r"ModuleNotFoundError|ImportError|No module named", re.I), "module_not_found"),
- (re.compile(r"command not found", re.I), "command_not_found"),
- (re.compile(r"Permission denied|EACCES|EPERM|auto-denied", re.I), "permission_denied"),
- (re.compile(r"file is too large|too many lines|exceeds.*limit", re.I), "file_too_large"),
- (re.compile(r"SyntaxError|IndentationError", re.I), "syntax_error"),
- (re.compile(r"Traceback \(most recent|Exception:|Error:", re.I), "runtime_error"),
- (re.compile(r"timed? ?out|TimeoutError|deadline exceeded", re.I), "timeout"),
- (re.compile(r"exit code|non-zero|exited with", re.I), "exit_code"),
- (re.compile(r"BUILD FAILED|compilation error|compile error", re.I), "build_failure"),
-]
-
-
-def _classify_error(content: str) -> str | None:
- """Classify error content. Returns category or None if not an error."""
- snippet = content[:2000]
- for pattern, category in _ERROR_PATTERNS:
- if pattern.search(snippet):
- return category
- return None
+# OpenAI-format tool results carry no is_error flag, so failures are sniffed
+# from the output. Categories come from headroom.learn._shared.classify_error;
+# these patterns only decide *whether* the output is an error.
+_ERROR_SIGNALS: tuple[re.Pattern[str], ...] = (
+ re.compile(r"No such file or directory|ENOENT|FileNotFoundError|does not exist", re.I),
+ re.compile(r"ModuleNotFoundError|ImportError|No module named", re.I),
+ re.compile(r"command not found", re.I),
+ re.compile(r"Permission denied|EACCES|EPERM|auto-denied", re.I),
+ re.compile(r"file is too large|too many lines|exceeds.*limit", re.I),
+ re.compile(r"SyntaxError|IndentationError", re.I),
+ re.compile(r"Traceback \(most recent|Exception:|Error:", re.I),
+ re.compile(r"timed? ?out|TimeoutError|deadline exceeded", re.I),
+ re.compile(r"BUILD FAILED|compilation error|compile error", re.I),
+)
+
+# Agent harnesses (Codex, Grok, opencode, ...) append "exit code 0" to every
+# SUCCESSFUL shell command, so an exit code only signals an error when it is
+# nonzero (signed codes such as -9 included). Status evidence belongs to its own
+# line: a zero code never hides a separate explicit failure elsewhere in the
+# output (a nonzero code, "non-zero", a signal kill, or an "exited with ..." line
+# that carries no code of its own). A line that ends at "exited with" continues
+# on the next line ("Process exited with\nexit code 0"), so it is not a failure.
+# A standalone "Killed" line is the shell's SIGKILL message, but a successful
+# command can also print that word, so it counts only when no exit status is
+# reported at all. It is recognized even below the short-content cut-off.
+_EXIT_STATUS_RE = re.compile(
+ r"\bexit(?:ed)?(?:\s+with)?(?:\s+exit)?\s+(?:code|status)\s*:?\s*([+-]?\d+)", re.I
+)
+_EXIT_FAILURE_RE = re.compile(r"non-zero|nonzero|exited with signal|killed by signal", re.I)
+_KILLED_LINE_RE = re.compile(r"^\s*Killed(?::\s*\d+)?\s*$", re.M)
+_EXITED_WITH_RE = re.compile(r"exited with(?=\s*\S)", re.I)
+
+
+def _exit_status_is_error(snippet: str) -> bool:
+ codes = _EXIT_STATUS_RE.findall(snippet)
+ if any(int(code) != 0 for code in codes) or _EXIT_FAILURE_RE.search(snippet):
+ return True
+ if any(
+ _EXITED_WITH_RE.search(line) and not _EXIT_STATUS_RE.search(line)
+ for line in snippet.splitlines()
+ ):
+ return True
+ return not codes and bool(_KILLED_LINE_RE.search(snippet))
def _is_error(content: str) -> bool:
"""Quick check if tool output looks like an error."""
- if not content or len(content) < 10:
+ if not content:
return False
- return _classify_error(content) is not None
+ if len(content) < 10:
+ return bool(_KILLED_LINE_RE.fullmatch(content))
+ snippet = content[:2000]
+ if any(pattern.search(snippet) for pattern in _ERROR_SIGNALS):
+ return True
+ return _exit_status_is_error(snippet)
# =============================================================================
@@ -769,7 +795,7 @@ class TrafficLearner:
"input": tool_input,
"output": tool_output[:2000], # Cap for memory
"is_error": is_error,
- "error_category": _classify_error(tool_output) if is_error else None,
+ "error_category": classify_error(tool_output).value if is_error else None,
"timestamp": time.time(),
"agent_type": agent_type,
}
diff --git a/tests/test_memory/test_traffic_learner.py b/tests/test_memory/test_traffic_learner.py
index fd1c13472..ab7d0baf4 100644
--- a/tests/test_memory/test_traffic_learner.py
+++ b/tests/test_memory/test_traffic_learner.py
@@ -18,10 +18,8 @@ from headroom.memory.traffic_learner import (
TrafficLearner,
_bash_binaries_match,
_bash_first_binary,
- _classify_error,
_commands_related_as_retry,
_drop_contradictions,
- _is_error,
_levenshtein,
_load_persisted_patterns_from_sqlite,
_normalize_bash_for_hash,
@@ -40,28 +38,145 @@ UTC = timezone.utc
class TestErrorClassification:
- def test_file_not_found(self):
- assert _classify_error("No such file or directory: foo.py") == "file_not_found"
- assert _classify_error("FileNotFoundError: [Errno 2]") == "file_not_found"
+ """The learner classifies tool output with the shared learn classifier."""
- def test_command_not_found(self):
- assert _classify_error("zsh: command not found: ruff") == "command_not_found"
+ @pytest.fixture
+ def learner(self):
+ return TrafficLearner(backend=None, user_id="test-user", min_evidence=1)
- def test_module_not_found(self):
- assert _classify_error("ModuleNotFoundError: No module named 'foo'") == "module_not_found"
+ @staticmethod
+ def _openai_result(learner: TrafficLearner, output: str) -> dict:
+ messages = [
+ {
+ "role": "assistant",
+ "tool_calls": [
+ {"id": "c1", "function": {"name": "shell", "arguments": '{"command": "ls"}'}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "c1", "content": output},
+ ]
+ return learner.extract_tool_results_from_openai_messages(messages)[0]
- def test_permission_denied(self):
- assert _classify_error("Permission denied: /etc/shadow") == "permission_denied"
+ @pytest.mark.parametrize(
+ ("output", "is_error"),
+ [
+ # Successful shell commands from Codex/Grok/opencode end in "exit code 0".
+ ("Process exited with exit code 0\nall tests passed", False),
+ ("README.md\nsrc\nexit code 0", False),
+ # Nonzero exit codes and other exit-failure wording.
+ ("Exit code: 1\nWall time: 0.2s\nOutput:\nfail", True),
+ ("exit code 2", True),
+ ("Command failed with non-zero status 1", True),
+ ("process exited with status 1", True),
+ ("x" * 1500 + "\nexit code 3", True),
+ ("command terminated\nexit code -9", True),
+ ("Process exited with exit code -1", True),
+ # A zero wrapper status must not hide a separate failure.
+ ("worker exited with signal 9\nexit code 0", True),
+ ("child exit code 2\nwrapper exit code 0", True),
+ ("python train.py\nKilled\n", True),
+ # A successful command may print the word; exit code 0 then wins.
+ ("grep result:\nKilled\nexit code 0", False),
+ ("task killed by signal SIGKILL\nexit code 0", True),
+ # A bare Killed is an error even below the short-content cut-off,
+ # but a reported zero status wins over a printed "Killed".
+ ("Killed", True),
+ ("Killed\nexit code 0", False),
+ # The wrapper's zero status belongs to its own line.
+ ("worker exited with an error\nwrapper exit code 0", True),
+ # One status phrase wrapped across lines is still one zero status.
+ ("Process exited with\nexit code 0", False),
+ ("Killed: 9", True),
+ # Case-insensitive signals the shared is_error_content would miss.
+ ("zsh: no such file or directory: ./run.sh", True),
+ ("fatal: path 'x' does not exist in 'HEAD'", True),
+ ("open /etc/shadow: permission denied", True),
+ ("EACCES: permission denied, open '/x'", True),
+ ("Operation not permitted (EPERM) on /x", True),
+ ("File content exceeds maximum allowed tokens limit (25000)", True),
+ ("file is too large to read", True),
+ ("Exception: something broke badly", True),
+ ("context deadline exceeded while dialing", True),
+ ("x" * 1500 + "\nTraceback (most recent call last):\nValueError: late", True),
+ # Signals the old detector already caught.
+ ("No such file or directory: foo.py", True),
+ ("ModuleNotFoundError: No module named 'foo'", True),
+ ("zsh: command not found: ruff", True),
+ ("Tool call auto-denied by policy", True),
+ ("IndentationError: unexpected indent here", True),
+ ("TimeoutError: deadline exceeded after 30s", True),
+ ("Command timed out after 120s", True),
+ ("BUILD FAILED in 3s", True),
+ # Not errors.
+ ("All tests passed, everything is fine", False),
+ ("2 failed, 10 passed in 1.2s", False),
+ ("Checked 4 files, no errors found in output", False),
+ ("short", False),
+ ("", False),
+ ],
+ )
+ def test_error_detection(self, learner: TrafficLearner, output: str, is_error: bool):
+ assert self._openai_result(learner, output)["is_error"] is is_error
- def test_not_an_error(self):
- assert _classify_error("Everything is fine, tests passed!") is None
- assert _classify_error("") is None
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("output", "category"),
+ [
+ ("No such file or directory: foo.py", "file_not_found"),
+ ("zsh: command not found: ruff", "command_not_found"),
+ ("ModuleNotFoundError: No module named 'foo'", "module_not_found"),
+ ("Permission denied: /etc/shadow", "permission_denied"),
+ ("TimeoutError: deadline exceeded after 30s", "timeout"),
+ ("ConnectionError: [Errno 111] Connection refused", "connection_error"),
+ ("task killed by signal SIGKILL", "exit_code"),
+ ("python train.py\nKilled", "exit_code"),
+ ("Killed: 9", "exit_code"),
+ ],
+ )
+ async def test_error_category_recorded(
+ self, learner: TrafficLearner, output: str, category: str
+ ):
+ await learner.on_tool_result(
+ tool_name="Bash", tool_input={"command": "x"}, tool_output=output, is_error=True
+ )
+ assert learner._tool_history[-1]["error_category"] == category
- def test_is_error_helper(self):
- assert _is_error("No such file or directory")
- assert not _is_error("All tests passed")
- assert not _is_error("")
- assert not _is_error("short")
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("output", "is_error", "category"),
+ [
+ ("Killed", True, "exit_code"),
+ ("worker exited with an error\nwrapper exit code 0", True, "exit_code"),
+ ("Killed\nexit code 0", False, None),
+ ("README.md\nsrc\nexit code 0", False, None),
+ ("worker killed by signal SIGKILL\nwrapper exit code 0", True, "exit_code"),
+ ("command terminated\nexit code -9", True, "exit_code"),
+ ],
+ )
+ async def test_openai_result_recorded_through_on_tool_result(
+ self, learner: TrafficLearner, output: str, is_error: bool, category: str | None
+ ):
+ """End to end: the OpenAI extractor's verdict is what on_tool_result records."""
+ result = self._openai_result(learner, output)
+ await learner.on_tool_result(
+ tool_name=result["tool_name"],
+ tool_input=result["input"],
+ tool_output=result["output"],
+ is_error=result["is_error"],
+ )
+ recorded = learner._tool_history[-1]
+ assert recorded["is_error"] is is_error
+ assert recorded["error_category"] == category
+
+ @pytest.mark.asyncio
+ async def test_success_has_no_error_category(self, learner: TrafficLearner):
+ await learner.on_tool_result(
+ tool_name="Bash",
+ tool_input={"command": "x"},
+ tool_output="Everything is fine, tests passed!",
+ is_error=False,
+ )
+ assert learner._tool_history[-1]["error_category"] is None
# =============================================================================