headroom/tests/test_learn/test_loop_weighting.py
Purva Kandalgaonkar 14e8dc4c84
feat(learn): weight loops in Headroom Learn + RTK-loop eval (#1160)
## Description

`headroom learn` ranked recommendations by a single LLM-guessed
`estimated_tokens_saved` with a flat hardcoded `confidence`, and had
**no notion of a loop**. So (1) RTK re-fetch loops were invisible - RTK
truncates a command's output, the agent re-runs larger-limit variants,
those calls *succeed* (`is_error=False`), and `analyze()` even
early-returned when a session had no failures and no events - and (2)
even when surfaced, a loop ranked no higher than a one-off mistake. This
adds loop-aware weighting plus the eval that reproduces an RTK loop,
runs it through Learn, and checks the guardrail prevents re-triggering.

Closes #1159

## Type of Change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- New `headroom/learn/loops.py`: `detect_loops()` (canonical signature
collapses RTK pagination/limit variants; classifies error vs rtk-refetch
loops; **measured** wasted tokens), `format_loops_for_digest()`,
`apply_loop_weighting()`.
- `analyzer.py`: detect loops up front (fixes the no-failure
early-return), lead the digest with them, prioritize loops in the system
prompt, re-sort after weighting.
- `models.py`: `Recommendation.is_loop_guardrail` / `loop_occurrences`.
- `benchmarks/rtk_loop_learn_eval.py` + `headroom/learn/fixtures.py`:
the two-phase RTK-loop eval and its session fixtures.
- Tests, `docs/rtk-loop-weighting.md`, CHANGELOG entry.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`) - not run (mypy not in my
minimal env; see Not tested)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ python -m pytest tests/test_learn/ -q
190 passed, 3 skipped, 1 warning in 5.85s
$ ruff check <changed files>
All checks passed!
```

## Real Behavior Proof

- Environment: macOS (Darwin 25.0), Python 3.10.18, fresh venv (`pip
install -e` minus the optional `hnswlib`/proxy extras, which are
unrelated to `learn`); real LLM via the analyzer's claude CLI backend
(`HEADROOM_LEARN_CLI=claude`, claude-cli 2.1.158) — no API key used.
- Exact command / steps: `HEADROOM_LEARN_CLI=claude python -c "from
benchmarks.rtk_loop_learn_eval import run_eval;
c=run_eval(use_real_llm=True); print(c.render())"`
- Observed result: the analyzer shelled out to a real model and produced
the "Commands" guardrail quoted below, naming the looping command. The
digest reports the measured 5,005-token waste and asks the model to rank
loops first, so the model emitted that figure; in this run the guardrail
ranked **#1** and the scorecard was all-PASS (below). Caveat — real-mode
is run-dependent: the rule's wording, and whether the post-hoc
`apply_loop_weighting` fuzzy match fires, vary across runs (in one run
it did not tag the rule). The **deterministic CI eval** (stub LLM) is
the stable, reproducible artifact; this real run corroborates it.
- Not tested: the analyzer's API-key path (ANTHROPIC/OPENAI/GEMINI) —
exercised the equivalent claude CLI backend instead; `mypy`; a live
agent *obeying* the written rule end-to-end (Phase 2 is a non-recurrence
check, not a live agent — called out in the doc).

Real model output from this run, ranked #1 at the measured 5,005-token
weight:

> **Commands** — When grepping logs (or any large file), never loop with
increasing `| head -N` limits — tool output is capped at ~4 KB
regardless of N, so repeated attempts return identical bytes. Instead:
redirect to a temp file (`grep ... > /tmp/out.txt`) then read it, or use
`grep -c` first…

```text
[PASS] loop_detected          (1 loop(s), ~5,005 tok wasted)
[PASS] guardrail_produced
[PASS] ranked_first
[PASS] names_command
[PASS] prescribes_fix
[PASS] weight_reflects_waste
[PASS] guardrail_holds
RESULT: PASS
```

(One real-mode run via the claude CLI backend. The deterministic
`pytest` eval above is the stable artifact; see the run-dependence
caveat under Observed result.)

The real run also caught an over-brittle check: an earlier
`names_command` required the literal "TimeoutError"; the real model
wrote a *more general* rule (grep + `head -N`) without it, so I fixed
the check to verify the looping **command** is named, not an incidental
literal.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I have updated the CHANGELOG.md if applicable

## Additional Notes

- No new dependencies. No network, no user/assistant content dropped —
operates on already-captured session digests.
- Kept as one logical change. mypy not run locally (minimal env); happy
to address anything CI's mypy flags.

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-06-22 18:49:08 -05:00

197 lines
8.1 KiB
Python

"""Tests for loop detection and loop-weighting in Headroom Learn.
Covers the gap these changes close: RTK re-fetch loops (repeated, successful
but insufficient calls) were invisible to failure-only analysis and, even when
surfaced, were ranked no higher than a one-off rule. These tests pin:
1. ``detect_loops`` finds RTK re-fetch loops and error loops, and ignores
one-offs — collapsing output-limit variants to one signature.
2. The digest surfaces detected loops as a high-priority section.
3. ``apply_loop_weighting`` lifts a loop guardrail above a one-off rule using
MEASURED waste, regardless of the LLM's guessed savings.
4. End-to-end ``SessionAnalyzer.analyze`` (LLM mocked): a re-fetch loop with no
failures is still analyzed, and its guardrail outranks a one-off rule.
"""
from pathlib import Path
from unittest.mock import MagicMock, patch
from headroom.learn.analyzer import SessionAnalyzer, _build_digest
from headroom.learn.fixtures import (
error_loop_session,
one_off_error_session,
rtk_refetch_loop_session,
)
from headroom.learn.loops import (
_canonical_signature,
apply_loop_weighting,
detect_loops,
)
from headroom.learn.models import (
ProjectInfo,
Recommendation,
RecommendationTarget,
)
def _project() -> ProjectInfo:
return ProjectInfo(
name="proj",
project_path=Path("/tmp/proj"),
data_path=Path("/tmp/proj-data"),
)
# =============================================================================
# detect_loops
# =============================================================================
class TestDetectLoops:
def test_rtk_refetch_loop_detected_despite_no_errors(self):
loops = detect_loops([rtk_refetch_loop_session(repetitions=5)])
assert len(loops) == 1
lp = loops[0]
assert lp.count == 5
assert lp.is_error_loop is False
assert lp.kind == "rtk-refetch-loop"
# Waste counts the 4 redundant re-fetches (not the first legit call).
assert lp.wasted_tokens > 0
def test_output_limit_variants_collapse_to_one_signature(self):
# The five calls differ only by `head -50/-100/...`; same signature.
session = rtk_refetch_loop_session(repetitions=5)
sigs = {_canonical_signature(tc) for tc in session.tool_calls}
assert len(sigs) == 1
def test_error_loop_detected_and_classified(self):
loops = detect_loops([error_loop_session(repetitions=4)])
assert len(loops) == 1
assert loops[0].is_error_loop is True
assert loops[0].kind == "error-loop"
def test_one_off_is_not_a_loop(self):
assert detect_loops([one_off_error_session()]) == []
def test_min_occurrences_threshold(self):
# Two repetitions is a retry, not a loop, at the default threshold.
assert detect_loops([rtk_refetch_loop_session(repetitions=2)]) == []
assert detect_loops([rtk_refetch_loop_session(repetitions=3)])
def test_error_loop_waste_exceeds_refetch_loop_first_call_credit(self):
# Error loops waste every call; re-fetch loops credit the first call.
err = detect_loops([error_loop_session(repetitions=4)])[0]
ref = detect_loops([rtk_refetch_loop_session(repetitions=4)])[0]
assert err.count == ref.count
# Same count, but error loop counts all N and re-fetch counts N-1.
assert err.wasted_tokens >= 0 and ref.wasted_tokens >= 0
# =============================================================================
# digest surfacing
# =============================================================================
class TestDigestSurfacesLoops:
def test_digest_includes_detected_loops_section(self):
digest = _build_digest(_project(), [rtk_refetch_loop_session()])
assert "Detected Loops" in digest
assert "rtk-refetch-loop" in digest
assert "tokens wasted" in digest
def test_digest_without_loops_has_no_loop_section(self):
digest = _build_digest(_project(), [one_off_error_session()])
assert "Detected Loops" not in digest
# =============================================================================
# apply_loop_weighting
# =============================================================================
class TestApplyLoopWeighting:
def _loop_rec(self) -> Recommendation:
return Recommendation(
target=RecommendationTarget.CONTEXT_FILE,
section="Grep TimeoutError loop",
content="When you need to grep TimeoutError in logs, read the full "
"result once instead of re-running with larger head limits.",
estimated_tokens_saved=200, # LLM under-estimated it
)
def _one_off_rec(self) -> Recommendation:
return Recommendation(
target=RecommendationTarget.CONTEXT_FILE,
section="Use uv",
content="Use `uv run python` instead of `python3`.",
estimated_tokens_saved=500, # LLM rated this higher
)
def test_loop_rule_boosted_above_one_off(self):
loops = detect_loops([rtk_refetch_loop_session(repetitions=5)])
recs = [self._one_off_rec(), self._loop_rec()]
apply_loop_weighting(recs, loops)
loop_rec = next(r for r in recs if r.is_loop_guardrail)
one_off = next(r for r in recs if not r.is_loop_guardrail)
# Boosted to at least the measured loop waste, which dominates the
# one-off even though the LLM originally rated the one-off higher.
assert loop_rec.estimated_tokens_saved >= loops[0].wasted_tokens
assert loop_rec.estimated_tokens_saved > one_off.estimated_tokens_saved
assert loop_rec.loop_occurrences == 5
def test_no_loops_is_noop(self):
recs = [self._one_off_rec()]
before = recs[0].estimated_tokens_saved
apply_loop_weighting(recs, [])
assert recs[0].estimated_tokens_saved == before
assert recs[0].is_loop_guardrail is False
def test_unrelated_rule_not_credited(self):
loops = detect_loops([rtk_refetch_loop_session(repetitions=5)])
recs = [self._one_off_rec()] # about uv/python, not the grep loop
apply_loop_weighting(recs, loops)
assert recs[0].is_loop_guardrail is False
# =============================================================================
# end-to-end analyze() with mocked LLM
# =============================================================================
class TestAnalyzeEndToEnd:
@patch("headroom.learn.analyzer._call_llm")
def test_refetch_loop_with_no_failures_is_still_analyzed(self, mock_call_llm: MagicMock):
# Pure re-fetch loop: zero errors, no events. Must NOT early-return.
mock_call_llm.return_value = {"context_file_rules": [], "memory_file_rules": []}
analyzer = SessionAnalyzer(model="test-model")
analyzer.analyze(_project(), [rtk_refetch_loop_session()])
mock_call_llm.assert_called_once() # the guard let it through
@patch("headroom.learn.analyzer._call_llm")
def test_loop_guardrail_outranks_one_off_in_result(self, mock_call_llm: MagicMock):
# LLM returns both rules, rating the one-off higher than the loop.
mock_call_llm.return_value = {
"context_file_rules": [
{
"section": "Use uv",
"content": "Use `uv run python` instead of `python3`.",
"estimated_tokens_saved": 800,
"evidence_count": 2,
},
{
"section": "Grep TimeoutError loop",
"content": "Grep TimeoutError in logs once with full output; "
"do not re-run with larger head limits.",
"estimated_tokens_saved": 100,
"evidence_count": 1,
},
],
"memory_file_rules": [],
}
analyzer = SessionAnalyzer(model="test-model")
result = analyzer.analyze(_project(), [rtk_refetch_loop_session(repetitions=6)])
# After weighting, the loop guardrail ranks first despite the LLM's order.
assert result.recommendations[0].is_loop_guardrail is True
assert "loop" in result.recommendations[0].section.lower()