feat(router): tier bump on repeated failed edits (tool-error escalation, ships off) #119

Merged
alee merged 19 commits from feat/tool-error-escalation into main 2026-10-20 23:10:39 +00:00
Owner

What

When an agent keeps failing its own edits (exact-match edit errors), the router now raises the tier by one for that request. Detection is stateless and read from the request body: each role: "tool" result is paired with the assistant tool_calls entry that produced it, and consecutive edit-class argument errors at the tail are counted. Nothing is stored per session, so the signal cannot go stale and it clears the moment the model lands a good edit.

Motivating case (2026-10-17): a worker was routed to gemma-4-31b at tier 1 for 17 of 21 turns and failed 4 of its 6 edit calls; earlier workers on stronger models failed 1 in 13 and 1 in 17. Nothing in the router reacted to the failures.

Behavior

  • Counts only edit-class tools (edit, write, apply_patch, patch, multiedit) whose result matches an argument-error pattern. Tool execution aborted is neutral (neither counts nor resets); bash failures and read errors are ignored.
  • Trigger: escalation.tool_error_bump.threshold (default 3) consecutive errors. Action: min(tier + max_bump, escalation.max_tier), this request only, never lowers a tier.
  • Ships OFF (escalation.tool_error_bump.enabled: false). While off it still logs tool_error_scan id=... errors=N would_escalate=... tier=T, so the real message shape can be checked in the journal before enabling.
  • Respects the global escalation.enabled switch and iteration.max_rebill_prompt_tokens (a bump can switch models and lose the prompt cache).
  • If the bumped tier has no candidates, it falls back to the original tier and logs tool_error_escalation_skipped (a bump never turns a working request into a 422).
  • The session cache always stores the classifier's own tier, never the bumped one.

Observability and controls

  • route_decisions.escalation_reason (e.g. tool_errors:3:1->2), additive migration, shown as a badge in the admin Decisions log.
  • /metrics tool_error_bumps plus a warning class in the TUI warnings panel, grouped by the model that was failing (the previous decision's model in the same session). The query is bounded and uses idx_route_decisions_observed (EXPLAIN QUERY PLAN: SEARCH d USING INDEX, no SCAN d).
  • Admin controls (runtime and persisted) for all seven escalation settings, in the safety_nets category; the knob-coverage gate passes unchanged.
  • docs/routing.md: new "Tool-error tier escalation" section.

Verification

  • Full suite: 2777 passed (baseline 2741).
  • 11 mutation checks all fail the new tests: both call sites, the session-cache write, abort handling, kill switch, rebill guard, threshold, both no-candidates fallbacks, the never-lowers guard.
  • tests/test_metrics.py and tests/test_conversation_wiring.py are identical to main; no existing test lines are removed.

Notes for review

  • Commit c2aa1b4 has a mangled message (two items squashed into one subject line, with a literal \n\n). Content is correct; not rewritten.
  • The Task 3 wiring tests were folded into the commit titled "fix: validate tool_error_bump config and tidy wiring" by an amend during the run.
  • Not in this PR: a plugin header carrying tool-error counts (possible v2 if body parsing proves unreliable), per-model blocklisting, counting bash failures.

Deploy (operator)

  1. git pull --ff-only origin main, then back up config/config.local.yaml (command cp -f).
  2. systemctl --user restart llm-router.service.
  3. Leave the knob OFF and read journalctl --user -u llm-router.service | grep tool_error_scan for a day: errors= should be nonzero on real failed-edit turns and reset after a good edit.
  4. Then turn escalation.tool_error_bump.enabled on from Admin > Controls (runtime + persisted).

🤖 Generated with Claude Code

## What When an agent keeps failing its own edits (exact-match `edit` errors), the router now raises the tier by one for that request. Detection is stateless and read from the request body: each `role: "tool"` result is paired with the assistant `tool_calls` entry that produced it, and consecutive edit-class argument errors at the tail are counted. Nothing is stored per session, so the signal cannot go stale and it clears the moment the model lands a good edit. Motivating case (2026-10-17): a worker was routed to `gemma-4-31b` at tier 1 for 17 of 21 turns and failed 4 of its 6 `edit` calls; earlier workers on stronger models failed 1 in 13 and 1 in 17. Nothing in the router reacted to the failures. ## Behavior - Counts only edit-class tools (`edit`, `write`, `apply_patch`, `patch`, `multiedit`) whose result matches an argument-error pattern. `Tool execution aborted` is neutral (neither counts nor resets); `bash` failures and read errors are ignored. - Trigger: `escalation.tool_error_bump.threshold` (default 3) consecutive errors. Action: `min(tier + max_bump, escalation.max_tier)`, this request only, never lowers a tier. - **Ships OFF** (`escalation.tool_error_bump.enabled: false`). While off it still logs `tool_error_scan id=... errors=N would_escalate=... tier=T`, so the real message shape can be checked in the journal before enabling. - Respects the global `escalation.enabled` switch and `iteration.max_rebill_prompt_tokens` (a bump can switch models and lose the prompt cache). - If the bumped tier has no candidates, it falls back to the original tier and logs `tool_error_escalation_skipped` (a bump never turns a working request into a 422). - The session cache always stores the classifier's own tier, never the bumped one. ## Observability and controls - `route_decisions.escalation_reason` (e.g. `tool_errors:3:1->2`), additive migration, shown as a badge in the admin Decisions log. - `/metrics` `tool_error_bumps` plus a warning class in the TUI warnings panel, grouped by the model that was failing (the previous decision's model in the same session). The query is bounded and uses `idx_route_decisions_observed` (EXPLAIN QUERY PLAN: `SEARCH d USING INDEX`, no `SCAN d`). - Admin controls (runtime and persisted) for all seven `escalation` settings, in the `safety_nets` category; the knob-coverage gate passes unchanged. - `docs/routing.md`: new "Tool-error tier escalation" section. ## Verification - Full suite: 2777 passed (baseline 2741). - 11 mutation checks all fail the new tests: both call sites, the session-cache write, abort handling, kill switch, rebill guard, threshold, both no-candidates fallbacks, the never-lowers guard. - `tests/test_metrics.py` and `tests/test_conversation_wiring.py` are identical to main; no existing test lines are removed. ## Notes for review - Commit `c2aa1b4` has a mangled message (two items squashed into one subject line, with a literal `\n\n`). Content is correct; not rewritten. - The Task 3 wiring tests were folded into the commit titled "fix: validate tool_error_bump config and tidy wiring" by an amend during the run. - Not in this PR: a plugin header carrying tool-error counts (possible v2 if body parsing proves unreliable), per-model blocklisting, counting `bash` failures. ## Deploy (operator) 1. `git pull --ff-only origin main`, then back up `config/config.local.yaml` (`command cp -f`). 2. `systemctl --user restart llm-router.service`. 3. Leave the knob OFF and read `journalctl --user -u llm-router.service | grep tool_error_scan` for a day: `errors=` should be nonzero on real failed-edit turns and reset after a good edit. 4. Then turn `escalation.tool_error_bump.enabled` on from Admin > Controls (runtime + persisted). 🤖 Generated with [Claude Code](https://claude.com/claude-code)
alee added 19 commits 2026-10-20 23:09:46 +00:00
Add escalation_reason TEXT to route_decisions table so bump_reason
from tool-error tier bumps is persisted. Wire it through
persist_route_decision, events.publish_decision, and the chat
completions endpoint. Add round-trip and bump tests. Update the
no-header snapshot fixture. Fix prefix_probe state leakage by
clearing the store before and after the conversation_wiring module.
The last commit (a6656d3) rewrote unrelated parts of
tests/test_metrics.py (quota burn assertions,
expected_period_start, context messages). Restore the file to
origin/main's version.

The bump-count test (tool_error_bumps_by_model) with TTL gating
(30h excluded, 2h counted via timedelta offsets) lives in this
repo's escalation test file instead.
A bump 30h old is excluded (outside 24h window); one 2h old is
counted. Uses timedelta offsets (never day-of-month arithmetic).
Kept src/metrics.py as-is (a6656d3 query is correct).
VERIFIED BUG: with no tier>=3 models, 3 edit errors bumped tier
1->3 (max_bump=2, max_tier=3) returned HTTP 422 'No model
satisfies the hard filters (tier >= 3 ...)', while with the knob
off the same request returned 200.

Fix in src/dispatcher.py chat_completions, BOTH the cached branch
and the classify branch: after the bump re-route, if
bump_reason is not None and decision.selected is None, log
tool_error_escalation_skipped, reset bump_reason to None, and
route() AGAIN with the ORIGINAL tier.

Avoids 12-line TaskRequest duplication via local _route_at(tier)
function next to each route() call.

Tests appended to tests/test_tool_error_escalation.py:
(1) cache-miss path: delete tier-3 rows, bump enabled, threshold
    3, max_bump 2 -> status 200, UNBUMPED tier (1), escalation_reason
    IS NULL
(2) cached branch: same with seeded session cache
Mutation evidence: removing the fallback if block causes test (1)
to FAIL with 422 at tests/test_tool_error_escalation.py:629.
The classifier_reject column comment lost its first line
('-- NULL when the answer was used,') and was re-indented by 3
spaces. Restore the ORIGINAL comment block exactly as in
origin/main. The only change to the column line is adding the
comma after 'classifier_reject TEXT' (no longer the last column).
Keep the escalation_reason column and its short comment after it.
(1) src/dispatcher.py persist_route_decision INSERT: the column-list
continuation lines and the ") VALUES (...)" / closing lines were
re-indented by 4 spaces; restored to match original indentation,
only adding escalation_reason to the list and one ? to VALUES.

(2) admin/frontend/controls.html NUMBER_BOUNDS: the new entries and
the existing classifier_max_input_chars line are 3-space indented,
fixed to 2-space like their neighbors.

(3) admin/frontend/decisions.html: the .filter(Boolean) block lines
gained one extra leading space; removed it.
Append test_never_lowers_pins_reason_null to tests/test_tool_error_escalation.py.
Asserts that with cached tier 3 and escalation.max_tier = 3, and
with cached tier 3 and escalation.max_tier = 2, the persisted tier
stays 3 and escalation_reason IS NULL.

MUTATION EVIDENCE: removing the if new_tier <= tier: return tier,
None guard from _apply_tool_error_bump causes the test to FAIL at
tests/test_tool_error_escalation.py:732 with escalation_reason
='tool_errors:3:3->3' instead of NULL. Guard restored, git diff
empty.
alee merged commit 5fe26cae86 into main 2026-10-20 23:10:39 +00:00
Sign in to join this conversation.
No Reviewers
No Label
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: alee/6krrt#119