diff --git a/admin/frontend/controls.html b/admin/frontend/controls.html
index 033d9fb..a99bb17 100644
--- a/admin/frontend/controls.html
+++ b/admin/frontend/controls.html
@@ -762,6 +762,91 @@ const KNOB_NOTES = {
cls: 'bg-info',
glyph: 'info',
},
+ // --- escalation scalars (safety_nets) ---
+ escalation_enabled: {
+ text: 'gates all escalation logic',
+ title: 'When off, none of the escalation knobs fire -- no tier bump, no tool_error_scan shadow-log. Ships off.',
+ cls: 'bg-warning',
+ glyph: 'alert',
+ },
+ 'escalation.enabled': {
+ text: 'gates all escalation logic',
+ title: 'When off, none of the escalation knobs fire -- no tier bump, no tool_error_scan shadow-log. Ships off.',
+ cls: 'bg-warning',
+ glyph: 'alert',
+ },
+ escalation_preemptive_on_low_confidence: {
+ text: 'pre-emptive tier bump',
+ title: 'When on, a low-confidence classification pre-emptively bumps the tier to widen candidate pool. Off by default.',
+ cls: 'bg-secondary',
+ glyph: 'dash',
+ },
+ 'escalation.preemptive_on_low_confidence': {
+ text: 'pre-emptive tier bump',
+ title: 'When on, a low-confidence classification pre-emptively bumps the tier to widen candidate pool. Off by default.',
+ cls: 'bg-secondary',
+ glyph: 'dash',
+ },
+ tool_error_bump_enabled: {
+ text: 'tool_error tier escalation',
+ title: 'When on, N consecutive edit-class tool errors in the trailing request body escalate the tier. Shadow-logs when off.',
+ cls: 'bg-warning',
+ glyph: 'alert',
+ },
+ 'escalation.tool_error_bump.enabled': {
+ text: 'tool_error tier escalation',
+ title: 'When on, N consecutive edit-class tool errors in the trailing request body escalate the tier. Shadow-logs when off.',
+ cls: 'bg-warning',
+ glyph: 'alert',
+ },
+ escalation_max_tier: {
+ text: 'cap escalation tier',
+ title: 'Hard cap on how high escalation can push a tier (1-3). Prevents bumping to frontier on repeated errors.',
+ cls: 'bg-secondary',
+ glyph: 'dash',
+ },
+ 'escalation.max_tier': {
+ text: 'cap escalation tier',
+ title: 'Hard cap on how high escalation can push a tier (1-3). Prevents bumping to frontier on repeated errors.',
+ cls: 'bg-secondary',
+ glyph: 'dash',
+ },
+ escalation_min_confidence_before_bump: {
+ text: 'confidence threshold',
+ title: 'Minimum confidence required to avoid pre-emptive bump. Below this threshold the tier bumps. Range 0-1.',
+ cls: 'bg-secondary',
+ glyph: 'dash',
+ },
+ 'escalation.min_confidence_before_bump': {
+ text: 'confidence threshold',
+ title: 'Minimum confidence required to avoid pre-emptive bump. Below this threshold the tier bumps. Range 0-1.',
+ cls: 'bg-secondary',
+ glyph: 'dash',
+ },
+ tool_error_bump_threshold: {
+ text: 'error count to escalate',
+ title: 'N consecutive tool errors in trailing request body triggers escalation. Range 1-10.',
+ cls: 'bg-secondary',
+ glyph: 'dash',
+ },
+ 'escalation.tool_error_bump.threshold': {
+ text: 'error count to escalate',
+ title: 'N consecutive tool errors in trailing request body triggers escalation. Range 1-10.',
+ cls: 'bg-secondary',
+ glyph: 'dash',
+ },
+ tool_error_bump_max_bump: {
+ text: 'max tier jump',
+ title: 'Maximum tier jump from a single error burst (1-2). Limits damage from aggressive escalation.',
+ cls: 'bg-secondary',
+ glyph: 'dash',
+ },
+ 'escalation.tool_error_bump.max_bump': {
+ text: 'max tier jump',
+ title: 'Maximum tier jump from a single error burst (1-2). Limits damage from aggressive escalation.',
+ cls: 'bg-secondary',
+ glyph: 'dash',
+ },
};
function noteBadge(key) {
@@ -784,6 +869,10 @@ const NUMBER_BOUNDS = {
session_cache_staleness_seconds: { min: 5, max: 7200, step: 1 },
classifier_degraded_warn_threshold: { min: 0.001, max: 1, step: 0.01 },
classifier_max_input_chars: { min: 0, step: 1000 },
+ escalation_min_confidence_before_bump: { min: 0, max: 1, step: 0.01 },
+ escalation_max_tier: { min: 1, max: 3, step: 1 },
+ tool_error_bump_threshold: { min: 1, max: 10, step: 1 },
+ tool_error_bump_max_bump: { min: 1, max: 2, step: 1 },
};
// Category definitions for the knob table section headers. Order here matches
diff --git a/admin/frontend/decisions.html b/admin/frontend/decisions.html
index 1d9e962..23d9775 100644
--- a/admin/frontend/decisions.html
+++ b/admin/frontend/decisions.html
@@ -237,11 +237,11 @@ header.navbar{padding-top:2px!important;padding-bottom:2px!important}
| Time | Category | Profile | Tier |
Source | Model | Provider | Ctx |
- Flags | Cost | Prof | Rejected |
+ Flags | Cost | Prof | Rejected | Escalation |
- | Loading… |
+ | Loading… |
@@ -592,7 +592,7 @@ function matchesFilters(d, f) {
if (f.search) {
const haystack = [
d.selected_model, d.selected_provider, d.session_key,
- d.rejected_reason, d.task_category, d.kind, d.profile,
+ d.rejected_reason, d.escalation_reason, d.task_category, d.kind, d.profile,
].filter(Boolean).join(' ').toLowerCase();
if (!haystack.includes(f.search)) return false;
}
@@ -668,7 +668,7 @@ function renderTable() {
? `No match in the newest ${_allDecisions.length} decisions. `
+ `${(_totalDecisions - _allDecisions.length).toLocaleString()} older rows were not searched.`
: 'No decisions match these filters';
- tbody.innerHTML = `| ${escapeHtml(note)} |
`;
+ tbody.innerHTML = `| ${escapeHtml(note)} |
`;
pageInfoEl.textContent = '';
prevBtn.disabled = true;
nextBtn.disabled = true;
@@ -704,6 +704,7 @@ function renderTable() {
${d.est_cost_usd != null ? '$' + Number(d.est_cost_usd).toFixed(4) : '—'} |
${d.est_proficiency != null ? Number(d.est_proficiency).toFixed(2) : '—'} |
${escapeHtml(d.rejected_reason || '')} |
+ ${d.escalation_reason ? `escalated | ` : ''}
`;
}).join('');
}
diff --git a/config/config.yaml b/config/config.yaml
index ca79b3b..0779d23 100644
--- a/config/config.yaml
+++ b/config/config.yaml
@@ -393,6 +393,12 @@ escalation:
preemptive_on_low_confidence: false
min_confidence_before_bump: 0.6
+ # Bump the tier when a tool call fails.
+ tool_error_bump:
+ enabled: false
+ threshold: 3
+ max_bump: 1
+
iteration:
# A tier is not only a capability floor, it is a budget for getting the
# answer right. These are corrective attempts AFTER a verification failure,
diff --git a/config/schema.sql b/config/schema.sql
index 94e9bda..3aa5f86 100644
--- a/config/schema.sql
+++ b/config/schema.sql
@@ -359,13 +359,16 @@ CREATE TABLE IF NOT EXISTS route_decisions (
-- its answer, accepted or not
classifier_coverage REAL, -- local_decision only: total
-- option mass behind that answer
- classifier_reject TEXT -- NULL when the answer was used,
+ classifier_reject TEXT, -- NULL when the answer was used,
-- else why not: below_confidence_min,
-- below_coverage_min, no_logprobs,
-- timeout, transport_error,
-- parse_error, primary_failed,
-- skipped_. classification_source
-- then says what routed instead.
+ escalation_reason TEXT
+ -- tool_errors:{errors}:{from}->{to} when a
+ -- tool-error escalation fires, NULL otherwise.
);
CREATE INDEX IF NOT EXISTS idx_verifications_model ON verifications (model_id, provider);
diff --git a/docs/routing.md b/docs/routing.md
index 6858bbc..99aae11 100644
--- a/docs/routing.md
+++ b/docs/routing.md
@@ -640,3 +640,49 @@ Read-only on purpose — it is a structural list in the same class as
has an editing surface, and what an operator needs from the portal is the
answer to "why does nothing ever classify as X".
+## Tool-error tier escalation
+
+A run of failed edit-tool calls is in-band evidence a model is out of its
+depth: the conversation itself says the cheap tier keeps missing the edit. When
+the trailing tool results hold `escalation.tool_error_bump.threshold` (default
+3) consecutive edit-class errors - an argument failure from `edit`, `write`,
+`apply_patch`, `patch`, or `multiedit` - the router raises **this request
+only** to `min(tier + max_bump, escalation.max_tier)`.
+
+The count is stateless. `tool_errors.count_trailing_tool_errors` walks the
+body backward, pairing each tool result with the assistant call sharing its
+`tool_call_id`, and stops at the first successful edit-class result: the signal
+decays the moment the model lands one good edit. Nothing is stored, and the
+session cache keeps the classifier's **original** tier, so a bumped turn
+never poisons the next. "Tool execution aborted" (a client restart) and bash
+non-zero exits never count: a failing test run is a legitimate result, and
+`POST /outcome` already owns that signal.
+
+The bump never lowers - a tier already at `escalation.max_tier` is unchanged
+and records nothing - and it applies on every classification path in the chat
+endpoint: the fresh-classify branch (classifier, session history, or fallback
+guess, whatever the cascade produced) and the session-cache hit alike, with a
+re-route forced by measured context carrying the bumped tier.
+
+One guard sits in front. A bump re-routes on a different model, which pays
+full price for the whole prefix instead of hitting the prompt cache (~0.92
+same-model hit rate vs ~0.35 on switch, measured), so
+`iteration.max_rebill_prompt_tokens` (0 = no limit) suppresses the bump once
+the conversation's prompt exceeds it: past the limit the router trusts the
+failing model with the cache rather than paying a cache-destroying re-bill.
+
+The feature ships **off** (`escalation.tool_error_bump.enabled: false`;
+`escalation.enabled` stays the global kill switch). While off, a request with
+at least one counted error still logs a `tool_error_scan` INFO line with the
+count and a `would_escalate` flag. Run it like that first: the error patterns
+are substring matches against real client tool results, so validate the scan
+lines against your client's wording before enabling from Admin > Controls,
+where the feature's scalars sit in the `safety_nets` group.
+
+Every bump is observable: `route_decisions.escalation_reason` records
+`tool_errors::->`, `/metrics` reports `tool_error_bumps` as
+24h counts grouped by the failing model (the previous decision's selected
+model in the same session), the TUI tags its dashboard warning with the
+`tool-error-bumps` class, and the warning text names its own lever: **Block
+model** on the Admin Models page.
+
diff --git a/src/admin.py b/src/admin.py
index 45a64ab..f049d5e 100644
--- a/src/admin.py
+++ b/src/admin.py
@@ -366,6 +366,9 @@ _BOOL_KNOBS: dict[str, tuple[str, ...]] = {
"pinch_relevance_enabled": ("pinch", "relevance", "enabled"),
"classifier_context_framing": ("classifier", "context_framing"),
"classifier_shadow_encoder": ("classifier", "shadow_encoder"),
+ "escalation_enabled": ("escalation", "enabled"),
+ "escalation_preemptive_on_low_confidence": ("escalation", "preemptive_on_low_confidence"),
+ "tool_error_bump_enabled": ("escalation", "tool_error_bump", "enabled"),
"incumbent_cache_pricing": ("objective", "incumbent_cache_pricing"),
}
@@ -408,6 +411,12 @@ _FLOAT_KNOBS: dict[str, tuple[tuple[str, ...], float, float, Optional[tuple[str,
DEGRADED_WARN_THRESHOLD_MAX,
None,
),
+ "escalation_min_confidence_before_bump": (
+ ("escalation", "min_confidence_before_bump"),
+ 0.0,
+ 1.0,
+ None,
+ ),
}
# Runtime knobs whose value is a whole number. A SEPARATE table from
@@ -458,6 +467,21 @@ _INT_KNOBS: dict[str, tuple[tuple[str, ...], int, int]] = {
DEGRADED_WARN_MIN_FLOOR,
DEGRADED_WARN_MIN_CEILING,
),
+ "escalation_max_tier": (
+ ("escalation", "max_tier"),
+ 1,
+ 3,
+ ),
+ "tool_error_bump_threshold": (
+ ("escalation", "tool_error_bump", "threshold"),
+ 1,
+ 10,
+ ),
+ "tool_error_bump_max_bump": (
+ ("escalation", "tool_error_bump", "max_bump"),
+ 1,
+ 2,
+ ),
}
_LOCAL_COMPUTE_KNOB = "local_compute_enabled"
@@ -549,8 +573,15 @@ _KNOB_CATEGORY: dict[str, dict] = {
"classifier.degraded_warn_threshold": {"category": "classification", "advanced": False},
"classifier.fallback_category": {"category": "classification", "advanced": False},
"classifier.max_input_chars": {"category": "classification", "advanced": False},
- # -------- safety_nets (1) -----------------------------------------------------
+ # -------- safety_nets (8) -----------------------------------------------------
"circuit_breaker.enabled": {"category": "safety_nets", "advanced": False},
+ "escalation.enabled": {"category": "safety_nets", "advanced": False},
+ "escalation.preemptive_on_low_confidence": {"category": "safety_nets", "advanced": True},
+ "escalation.min_confidence_before_bump": {"category": "safety_nets", "advanced": True},
+ "escalation.max_tier": {"category": "safety_nets", "advanced": True},
+ "escalation.tool_error_bump.enabled": {"category": "safety_nets", "advanced": False},
+ "escalation.tool_error_bump.threshold": {"category": "safety_nets", "advanced": True},
+ "escalation.tool_error_bump.max_bump": {"category": "safety_nets", "advanced": True},
# -------- caching_context (5) -------------------------------------------------
"session_cache.enabled": {"category": "caching_context", "advanced": False},
"session_cache.staleness_seconds": {"category": "caching_context", "advanced": False},
@@ -623,6 +654,13 @@ _CONFIG_ALLOWLIST: dict[str, tuple[str, ...]] = {
"incumbent_challenger_cache_rate",
),
"circuit_breaker.enabled": ("circuit_breaker", "enabled"),
+ "escalation.enabled": ("escalation", "enabled"),
+ "escalation.max_tier": ("escalation", "max_tier"),
+ "escalation.min_confidence_before_bump": ("escalation", "min_confidence_before_bump"),
+ "escalation.preemptive_on_low_confidence": ("escalation", "preemptive_on_low_confidence"),
+ "escalation.tool_error_bump.enabled": ("escalation", "tool_error_bump", "enabled"),
+ "escalation.tool_error_bump.threshold": ("escalation", "tool_error_bump", "threshold"),
+ "escalation.tool_error_bump.max_bump": ("escalation", "tool_error_bump", "max_bump"),
"session_cache.enabled": ("session_cache", "enabled"),
"session_cache.staleness_seconds": ("session_cache", "staleness_seconds"),
"local_compute.enabled": ("local_compute", "enabled"),
@@ -685,6 +723,14 @@ _CONFIG_GET_ORDER: list[str] = [
"local_vision.enabled",
# safety_nets
"circuit_breaker.enabled",
+ # safety_nets (escalation)
+ "escalation.enabled",
+ "escalation.max_tier",
+ "escalation.min_confidence_before_bump",
+ "escalation.preemptive_on_low_confidence",
+ "escalation.tool_error_bump.enabled",
+ "escalation.tool_error_bump.threshold",
+ "escalation.tool_error_bump.max_bump",
# watchdog
"watchdog.enabled",
"watchdog.local_llm_enabled",
@@ -1114,6 +1160,24 @@ def _runtime_state(cfg: Any) -> dict:
cfg, _BOOL_KNOBS["log_energy_observations"]
),
"circuit_breaker_enabled": _get_at(cfg, _BOOL_KNOBS["circuit_breaker_enabled"]),
+ # --- escalation scalars (safety_nets) -------------------------------------
+ "escalation_enabled": _get_at(cfg, _BOOL_KNOBS["escalation_enabled"]),
+ "escalation_preemptive_on_low_confidence": _get_at(
+ cfg, _BOOL_KNOBS["escalation_preemptive_on_low_confidence"]
+ ),
+ "tool_error_bump_enabled": _get_at(cfg, _BOOL_KNOBS["tool_error_bump_enabled"]),
+ "escalation_min_confidence_before_bump": _get_at(
+ cfg, _FLOAT_KNOBS["escalation_min_confidence_before_bump"][0]
+ ),
+ "escalation_max_tier": _get_at(
+ cfg, _INT_KNOBS["escalation_max_tier"][0]
+ ),
+ "tool_error_bump_threshold": _get_at(
+ cfg, _INT_KNOBS["tool_error_bump_threshold"][0]
+ ),
+ "tool_error_bump_max_bump": _get_at(
+ cfg, _INT_KNOBS["tool_error_bump_max_bump"][0]
+ ),
"local_compute_enabled": _get_at(cfg, _BOOL_KNOBS["local_compute_enabled"]),
"local_llm_enabled": _get_at(cfg, _BOOL_KNOBS["local_llm_enabled"]),
"session_cache_enabled": _get_at(cfg, _BOOL_KNOBS["session_cache_enabled"]),
diff --git a/src/config.py b/src/config.py
index 6c6bd5c..3f83558 100644
--- a/src/config.py
+++ b/src/config.py
@@ -687,12 +687,43 @@ class LocalVisionConfig(StrictModel):
return v
+class ToolErrorBumpConfig(StrictModel):
+ """Scalable knobs for the tool-error tier-bump.
+
+ *threshold*: minimum consecutive edit-class errors to trigger a bump.
+ *max_bump*: how many tiers the bump may climb (1 or 2).
+ """
+
+ enabled: bool = False
+ threshold: int = 3
+ max_bump: int = 1
+
+ @field_validator("threshold")
+ @classmethod
+ def threshold_non_negative(cls, v: int) -> int:
+ if v < 1:
+ raise ValueError(
+ "escalation.tool_error_bump.threshold must be >= 1"
+ )
+ return v
+
+ @field_validator("max_bump")
+ @classmethod
+ def max_bump_range(cls, v: int) -> int:
+ if v not in (1, 2):
+ raise ValueError(
+ "escalation.tool_error_bump.max_bump must be in 1..2"
+ )
+ return v
+
+
class EscalationConfig(StrictModel):
enabled: bool
max_tier: int
min_confidence_before_bump: float
# Off by default: the iteration budget escalates on evidence instead.
preemptive_on_low_confidence: bool = False
+ tool_error_bump: ToolErrorBumpConfig = ToolErrorBumpConfig()
class IterationConfig(StrictModel):
diff --git a/src/dispatcher.py b/src/dispatcher.py
index a27e362..26124ea 100644
--- a/src/dispatcher.py
+++ b/src/dispatcher.py
@@ -75,6 +75,7 @@ from classifier_rejection import (
)
import local_energy
import logs
+import tool_errors
import prefix_probe
import session_cache
import textcut
@@ -351,6 +352,50 @@ class DispatchResponse(BaseModel):
# --- infrastructure -------------------------------------------------------
+def _apply_tool_error_bump(
+ tier: int,
+ messages: list[dict],
+ prompt_tokens: int,
+) -> tuple[int, Optional[str]]:
+ """Tier bump when the trailing conversation shows repeated edit-tool errors.
+
+ Returns (new_tier, reason); reason is None when nothing changed. When
+ escalation.tool_error_bump.enabled is false this only SHADOW-LOGS: one
+ tool_error_scan INFO line when errors >= 1, no routing effect, so the
+ operator can validate the real message shape before enabling.
+ """
+ bump = cfg.escalation.tool_error_bump
+ errors = tool_errors.count_trailing_tool_errors(messages)
+ if not cfg.escalation.enabled:
+ if errors >= 1:
+ logs.info(
+ "tool_error_scan",
+ errors=errors,
+ would_escalate=errors >= bump.threshold,
+ tier=tier,
+ )
+ return tier, None
+ if not bump.enabled:
+ if errors >= 1:
+ logs.info(
+ "tool_error_scan",
+ errors=errors,
+ would_escalate=errors >= bump.threshold,
+ tier=tier,
+ )
+ return tier, None
+ if errors < bump.threshold:
+ return tier, None
+ limit = cfg.iteration.max_rebill_prompt_tokens
+ if limit and prompt_tokens > limit:
+ return tier, None
+ new_tier = min(tier + bump.max_bump, cfg.escalation.max_tier)
+ if new_tier <= tier:
+ return tier, None
+ logs.info("tool_error_escalation", tier=f"{tier}->{new_tier}", errors=errors)
+ return new_tier, f"tool_errors:{errors}:{tier}->{new_tier}"
+
+
def _ms(started: float) -> int:
"""Elapsed milliseconds since a perf_counter mark, for the latency fields.
@@ -496,7 +541,8 @@ def ensure_route_decisions(conn: sqlite3.Connection) -> None:
parent_key TEXT,
classifier_confidence REAL,
classifier_coverage REAL,
- classifier_reject TEXT
+ classifier_reject TEXT,
+ escalation_reason TEXT
)
"""
)
@@ -547,6 +593,7 @@ def ensure_route_decisions(conn: sqlite3.Connection) -> None:
("classifier_confidence", "REAL"),
("classifier_coverage", "REAL"),
("classifier_reject", "TEXT"),
+ ("escalation_reason", "TEXT"),
):
if name not in existing:
conn.execute(f"ALTER TABLE route_decisions ADD COLUMN {name} {decl}")
@@ -2433,6 +2480,7 @@ def persist_route_decision(
agent: Optional[str] = None,
parent_key: Optional[str] = None,
attempt_of: Optional[Classification] = None,
+ escalation_reason: Optional[str] = None,
) -> Optional[int]:
"""Record one routing decision to route_decisions, best-effort and gated.
@@ -2550,8 +2598,9 @@ def persist_route_decision(
request_id, pinch_original_tokens, pinch_final_tokens, profile,
prefix_divergence_index, prefix_tokens_after_divergence,
prefix_prev_message_count, agent, parent_key,
- classifier_confidence, classifier_coverage, classifier_reject
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ classifier_confidence, classifier_coverage, classifier_reject,
+ escalation_reason
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
observed_at,
@@ -2591,6 +2640,7 @@ def persist_route_decision(
attempt.confidence if attempt is not None else None,
attempt.coverage if attempt is not None else None,
attempt.reject_reason if attempt is not None else None,
+ escalation_reason,
),
)
decision_id: Optional[int] = int(cursor.lastrowid)
@@ -2645,6 +2695,7 @@ def persist_route_decision(
"classifier_reject": (
attempt.reject_reason if attempt is not None else None
),
+ "escalation_reason": escalation_reason,
}
)
return decision_id
@@ -4891,6 +4942,7 @@ def chat_completions(body: dict[str, Any], background: BackgroundTasks, request:
session_key,
staleness_seconds=cfg.session_cache.staleness_seconds,
)
+ bump_reason: Optional[str] = None
if cached is not None:
# Cache hit: skip the classifier. Capability flags (tools/images/
# json) were already read fresh from the body (caps) above — only
@@ -4900,23 +4952,42 @@ def chat_completions(body: dict[str, Any], background: BackgroundTasks, request:
classifier_attempt = None
classifier_ms = 0
ctx_src = "measured"
- decision = route(
- TaskRequest(
- task=_last_user_text(messages),
- # context omitted: the override branch (task_category +
- # task_tier + required_context_tokens all provided)
- # never reads req.context -- it skips classify().
- latency_tolerance=_effective_latency(profile_obj, None),
- tools_present=tools_present,
- has_images=caps.has_images,
- require_json_mode=caps.require_json_mode,
- task_category=cached.task_category,
- task_tier=cached.task_tier,
- required_context_tokens=measured,
- ),
- profile=profile_name,
- profile_obj=profile_obj,
+ # Tool-error bump on the cached branch. Purely request-body
+ # derived: nothing about the bump is stored per-session, so a
+ # bumped tier never poisons the cache for the next turn.
+ bumped_tier, bump_reason = _apply_tool_error_bump(
+ cached.task_tier, messages, measured
)
+ original_tier = cached.task_tier
+
+ def _route_at(tier):
+ return route(
+ TaskRequest(
+ task=_last_user_text(messages),
+ # context omitted: the override branch (task_category +
+ # task_tier + required_context_tokens all provided)
+ # never reads req.context -- it skips classify().
+ latency_tolerance=_effective_latency(profile_obj, None),
+ tools_present=tools_present,
+ has_images=caps.has_images,
+ require_json_mode=caps.require_json_mode,
+ task_category=cached.task_category,
+ task_tier=tier,
+ required_context_tokens=measured,
+ ),
+ profile=profile_name,
+ profile_obj=profile_obj,
+ )
+
+ decision = _route_at(bumped_tier)
+ if bump_reason is not None and decision.selected is None:
+ logs.info(
+ "tool_error_escalation_skipped",
+ reason="no_candidates",
+ tier=original_tier,
+ )
+ bump_reason = None
+ decision = _route_at(original_tier)
else:
# Cache miss: classify as today, then re-route on measured context
@@ -4944,12 +5015,21 @@ def chat_completions(body: dict[str, Any], background: BackgroundTasks, request:
classified_src = decision.classification.source
# Same reason as the source above: the re-route below replaces the
# Classification with an override that remembers none of this.
+ # Captured BEFORE the tool-error bump so the session cache and
+ # attribution see the classifier's original tier (M1 fix).
classifier_attempt = decision.classification
classifier_ms = _ms(classify_started)
ctx_src = "classifier"
- if measured > decision.classification.required_context_tokens:
- ctx_src = "measured"
- decision = route(
+ # Tool-error bump on the classify branch. Purely request-body
+ # derived; classifier_attempt above keeps the pre-bump tier for
+ # the session cache so a bump never poisons the next turn.
+ bump_tier, bump_reason = _apply_tool_error_bump(
+ decision.classification.task_tier, messages, measured
+ )
+ original_tier = decision.classification.task_tier
+
+ def _route_at(tier):
+ return route(
TaskRequest(
task=_last_user_text(messages),
# context omitted: the override branch (task_category +
@@ -4960,12 +5040,33 @@ def chat_completions(body: dict[str, Any], background: BackgroundTasks, request:
has_images=caps.has_images,
require_json_mode=caps.require_json_mode,
task_category=decision.classification.task_category,
- task_tier=decision.classification.task_tier,
- required_context_tokens=measured,
+ task_tier=tier,
+ required_context_tokens=max(
+ measured,
+ decision.classification.required_context_tokens,
+ ),
),
profile=profile_name,
profile_obj=profile_obj,
)
+
+ if (
+ measured > decision.classification.required_context_tokens
+ or bump_reason is not None
+ ):
+ ctx_src = "measured"
+ decision = _route_at(
+ bump_tier if bump_reason is not None
+ else decision.classification.task_tier
+ )
+ if bump_reason is not None and decision.selected is None:
+ logs.info(
+ "tool_error_escalation_skipped",
+ reason="no_candidates",
+ tier=original_tier,
+ )
+ bump_reason = None
+ decision = _route_at(original_tier)
# `classifier_cloud` is admitted alongside `classifier` because it
# is a REAL classification by a real model — and caching it is what
# bounds cloud cost to one call per session per staleness window
@@ -4979,10 +5080,14 @@ def chat_completions(body: dict[str, Any], background: BackgroundTasks, request:
and session_key is not None
and _session_cache_admits(classified_src)
):
+ # M1 fix: cache the classifier's ORIGINAL verdict
+ # (classifier_attempt), never the tool-error-bumped tier -
+ # a bumped tier written here would re-dispatch every
+ # later turn in the session at frontier prices.
session_cache.put(
session_key,
- task_category=decision.classification.task_category,
- task_tier=decision.classification.task_tier,
+ task_category=classifier_attempt.task_category,
+ task_tier=classifier_attempt.task_tier,
)
if decision.selected is None:
if (
@@ -5082,6 +5187,7 @@ def chat_completions(body: dict[str, Any], background: BackgroundTasks, request:
pinch_final_tokens=pinch_stats.get("final_tokens")
if pinch_stats is not None else None,
prefix_divergence=prefix_divergence,
+ escalation_reason=bump_reason,
)
if cfg.classifier.shadow_encoder:
background.add_task(
diff --git a/src/metrics.py b/src/metrics.py
index 23ebd74..05c6b66 100644
--- a/src/metrics.py
+++ b/src/metrics.py
@@ -1180,6 +1180,31 @@ def quota_burn(
return result
+def tool_error_bumps_by_model(conn: sqlite3.Connection) -> List[dict]:
+ """Bumps in the last 24h, grouped by the model the bump replaced.
+
+ The failing model is the PREVIOUS decision's selected_model in the same
+ session, derived via a bounded JOIN (not a full-table window scan).
+ """
+ if not _has_column(conn, "route_decisions", "escalation_reason"):
+ return []
+ rows = conn.execute(
+ """
+ SELECT prev.selected_model AS model, COUNT(*) AS bumps
+ FROM route_decisions d
+ JOIN route_decisions prev
+ ON prev.id = (SELECT MAX(p.id) FROM route_decisions p
+ WHERE p.session_key = d.session_key AND p.id < d.id)
+ WHERE d.escalation_reason IS NOT NULL
+ AND d.observed_at >= strftime('%Y-%m-%dT%H:%M:%S', 'now', '-24 hours')
+ AND prev.selected_model IS NOT NULL
+ GROUP BY prev.selected_model
+ ORDER BY bumps DESC, prev.selected_model
+ """
+ ).fetchall()
+ return [{"model": r["model"], "bumps": r["bumps"]} for r in rows]
+
+
def scoring_coverage(
conn: sqlite3.Connection,
cfg: Any,
@@ -1359,6 +1384,16 @@ def scoring_coverage(
selection = selection_coverage(conn, cfg)
warnings.extend(selection_coverage_warnings(selection))
+ bumps = tool_error_bumps_by_model(conn)
+ if bumps:
+ total = sum(b["bumps"] for b in bumps)
+ per_model = ", ".join(f"{b['model']} {b['bumps']}" for b in bumps)
+ warnings.append(
+ f"{total} tool-error tier bumps in the last 24h "
+ f"(failing models: {per_model}). The lever is Block model "
+ f"on the Admin Models page."
+ )
+
return {
"routable_models": total,
"with_energy_data": total - len(missing_energy),
@@ -1376,6 +1411,7 @@ def scoring_coverage(
# not only the warning text.
"proficiency_sample_depth": depth,
"cumulative_spend": spend,
+ "tool_error_bumps": bumps,
}
diff --git a/src/tool_errors.py b/src/tool_errors.py
new file mode 100644
index 0000000..36d1338
--- /dev/null
+++ b/src/tool_errors.py
@@ -0,0 +1,129 @@
+"""Count model-attributable edit-tool errors at the tail of a conversation.
+
+Pure stdlib, no imports from dispatcher or any I/O. The router calls
+``count_trailing_tool_errors`` on every chat request and escalates the tier
+when the trailing run of edit-tool argument errors clears the configured
+threshold (see escalation.tool_error_bump in config.yaml).
+"""
+
+import json
+from typing import Any
+
+# Edit-class tool names: only these can produce a counted "bad tool call".
+# bash non-zero exits are deliberately absent -- a failing test run is a
+# legitimate result, and /outcome already handles it.
+EDIT_TOOL_NAMES = frozenset(
+ {"edit", "write", "apply_patch", "patch", "multiedit"}
+)
+
+# Not model-attributable: caused by an opencode restart, so it must not
+# count and must not break the trailing run either.
+ABORT_STRING = "tool execution aborted"
+
+# Case-insensitive substrings. The exact error strings seen live
+# (plans/tool-error-escalation-brief.md) all normalize to these.
+ERROR_PATTERNS = (
+ "could not find oldstring",
+ "found multiple matches",
+ "oldstring cannot be empty",
+ "no changes to apply",
+)
+
+# O(trailing window) guarantee: never examine more than this many tool
+# results, so a huge history costs a bounded walk.
+MAX_TOOL_RESULTS_WALKED = 40
+
+
+def _content_text(content: Any) -> str:
+ """Tool-result content as one comparable string, lowercase.
+
+ Handles the three shapes a client actually sends: a plain string, a
+ list of {"type": "text", "text": ...} parts, and a JSON-wrapped string
+ (opencode quotes some tool results). Anything else reads as empty.
+ """
+ if isinstance(content, str):
+ text = content
+ elif isinstance(content, list):
+ parts = []
+ for part in content:
+ if isinstance(part, dict) and isinstance(part.get("text"), str):
+ parts.append(part["text"])
+ text = "\n".join(parts)
+ else:
+ return ""
+ stripped = text.strip()
+ if stripped.startswith('"') and stripped.endswith('"'):
+ try:
+ unwrapped = json.loads(stripped)
+ except (TypeError, ValueError):
+ return text.lower()
+ if isinstance(unwrapped, str):
+ return unwrapped.lower()
+ return text.lower()
+
+
+def _tool_names_by_call_id(messages: Any) -> dict:
+ """tool_call_id -> tool name, from assistant tool_calls entries."""
+ names: dict[str, str] = {}
+ if not isinstance(messages, list):
+ return names
+ for message in messages:
+ if not isinstance(message, dict):
+ continue
+ if message.get("role") != "assistant":
+ continue
+ calls = message.get("tool_calls")
+ if not isinstance(calls, list):
+ continue
+ for call in calls:
+ if not isinstance(call, dict):
+ continue
+ func = call.get("function")
+ call_id = call.get("id")
+ if not isinstance(func, dict) or not isinstance(call_id, str):
+ continue
+ name = func.get("name")
+ if isinstance(name, str):
+ names[call_id] = name
+ return names
+
+
+def count_trailing_tool_errors(messages: Any) -> int:
+ """Consecutive model-attributable edit-tool errors at the tail.
+
+ Walks the conversation backward. Each ``role: "tool"`` message is
+ paired with the assistant tool_call sharing its tool_call_id to learn
+ the tool name. Counting rules:
+
+ - edit-class tool result matching an argument-error pattern: counts.
+ - "tool execution aborted": neutral, walk continues.
+ - non-edit-class tool result (e.g. bash): neutral, walk continues.
+ - successful edit-class result: resets the run -- the walk stops.
+ - tool message with no matching assistant call: not counted.
+
+ The walk is capped at MAX_TOOL_RESULTS_WALKED tool results.
+ """
+ tool_names = _tool_names_by_call_id(messages)
+ count = 0
+ walked = 0
+ if not isinstance(messages, list):
+ return 0
+ for message in reversed(messages):
+ if not isinstance(message, dict) or message.get("role") != "tool":
+ continue
+ walked += 1
+ if walked > MAX_TOOL_RESULTS_WALKED:
+ break
+ call_id = message.get("tool_call_id")
+ if not isinstance(call_id, str) or call_id not in tool_names:
+ continue
+ if tool_names[call_id] not in EDIT_TOOL_NAMES:
+ continue
+ text = _content_text(message.get("content"))
+ if ABORT_STRING in text:
+ continue
+ if any(pattern in text for pattern in ERROR_PATTERNS):
+ count += 1
+ continue
+ break
+ return count
diff --git a/tests/fixtures/route_decision_no_header.json b/tests/fixtures/route_decision_no_header.json
index a789120..d15d021 100644
--- a/tests/fixtures/route_decision_no_header.json
+++ b/tests/fixtures/route_decision_no_header.json
@@ -6,6 +6,7 @@
"classifier_coverage": null,
"classifier_reject": null,
"confidence": 0.9,
+ "escalation_reason": null,
"est_cost_usd": 0.00016,
"est_proficiency": 0.5,
"exploration": 0,
diff --git a/tests/test_route_decisions.py b/tests/test_route_decisions.py
index f735c96..e6eb4ff 100644
--- a/tests/test_route_decisions.py
+++ b/tests/test_route_decisions.py
@@ -1523,3 +1523,120 @@ def test_session_history_lookup_excludes_classifier_soft(_session_db):
category, tier = result
assert category == "debugging"
assert tier == 3
+
+
+# =============================================================================
+# Task 4: escalation_reason column on route_decisions
+# =============================================================================
+
+
+def test_persist_round_trip_esc_reason(tmp_path, monkeypatch):
+ """persist_route_decision writes and reads back escalation_reason."""
+ db_path = tmp_path / "esc.db"
+ conn = sqlite3.connect(db_path)
+ conn.executescript(SCHEMA_SQL)
+ conn.close()
+
+ monkeypatch.setattr(dispatcher.cfg.database, "path", str(db_path))
+ monkeypatch.setattr(dispatcher.cfg.logging, "log_route_decisions", True)
+
+ dispatcher.persist_route_decision(
+ "route",
+ classification=Classification(
+ task_category="coding_general", task_tier=2,
+ required_context_tokens=100, confidence=0.9,
+ ),
+ latency_tolerance="interactive",
+ selected_model="deepseek-v4-flash",
+ selected_provider="neuralwatt",
+ escalation_reason="tool_errors:3:1->2",
+ )
+
+ # A row without escalation_reason should also write fine.
+ dispatcher.persist_route_decision(
+ "route",
+ classification=Classification(
+ task_category="coding_general", task_tier=2,
+ required_context_tokens=100, confidence=0.9,
+ ),
+ latency_tolerance="interactive",
+ selected_model="deepseek-v4-flash",
+ selected_provider="neuralwatt",
+ )
+
+ conn = sqlite3.connect(db_path)
+ conn.row_factory = sqlite3.Row
+ rows = conn.execute(
+ "SELECT escalation_reason FROM route_decisions ORDER BY id"
+ ).fetchall()
+ assert len(rows) == 2
+ assert rows[0]["escalation_reason"] == "tool_errors:3:1->2"
+ assert rows[1]["escalation_reason"] is None
+ conn.close()
+
+
+def test_esc_reason_written_on_tool_error_bump(decision_router, monkeypatch):
+ """A request that triggers a tool-error bump must have escalation_reason."""
+ client, db_path = decision_router
+ # Seed a tier 3 model so the bump (tier 2->3) has a target.
+ conn = sqlite3.connect(db_path)
+ conn.execute(
+ """
+ INSERT INTO models (
+ model_id, provider, base_model_id, tier, context_window,
+ effective_context_window, max_output_tokens,
+ cost_per_1m_prompt, cost_per_1m_completion,
+ supports_vision, supports_json_mode,
+ latency_class, reasoning_mode, context_variant,
+ access_level, availability, last_updated
+ ) VALUES ('tier3-model', 'neuralwatt', 'tier3-model', 3, 262128, 192500, 16384, 1.0, 2.0,
+ 0, 1, 'standard', 'default', 'full', 'public', 'active',
+ '2026-08-22T00:00:00+00:00')
+ """,
+ )
+ conn.execute(
+ "INSERT INTO proficiency (model_id, provider, category, blended_score, "
+ "source, last_updated, outcome_samples) VALUES ('tier3-model', 'neuralwatt', "
+ "'coding_general', 0.5, 'leaderboard', '2026-08-22T00:00:00+00:00', 50)",
+ )
+ conn.commit()
+ conn.close()
+
+ monkeypatch.setattr(dispatcher.cfg.escalation, "enabled", True)
+ monkeypatch.setattr(dispatcher.cfg.escalation.tool_error_bump, "enabled", True)
+ monkeypatch.setattr(dispatcher.cfg.escalation.tool_error_bump, "threshold", 3)
+ monkeypatch.setattr(dispatcher.cfg.escalation.tool_error_bump, "max_bump", 1)
+ monkeypatch.setattr(dispatcher.cfg.session_cache, "enabled", False)
+
+ from tests.test_tool_error_escalation import _messages_with_errors
+
+ resp = client.post(
+ "/v1/chat/completions",
+ json={"model": "auto", "messages": _messages_with_errors(3)},
+ )
+ assert resp.status_code == 200
+
+ rows = _rows(db_path)
+ assert len(rows) == 1
+ assert rows[0]["escalation_reason"] is not None
+ assert "tool_errors" in (rows[0]["escalation_reason"] or "")
+ assert rows[0]["escalation_reason"].startswith("tool_errors:")
+
+
+def test_esc_reason_null_on_no_bump(decision_router, monkeypatch):
+ """A request without tool errors must write escalation_reason=NULL."""
+ client, db_path = decision_router
+ monkeypatch.setattr(dispatcher.cfg.escalation, "enabled", True)
+ monkeypatch.setattr(dispatcher.cfg.escalation.tool_error_bump, "enabled", True)
+ monkeypatch.setattr(dispatcher.cfg.escalation.tool_error_bump, "threshold", 3)
+ monkeypatch.setattr(dispatcher.cfg.session_cache, "enabled", False)
+
+ resp = client.post(
+ "/v1/chat/completions",
+ json={"model": "auto", "messages": _messages()},
+ )
+ assert resp.status_code == 200
+
+ rows = _rows(db_path)
+ assert len(rows) == 1
+ assert rows[0]["escalation_reason"] is None
diff --git a/tests/test_tool_error_escalation.py b/tests/test_tool_error_escalation.py
new file mode 100644
index 0000000..3122e71
--- /dev/null
+++ b/tests/test_tool_error_escalation.py
@@ -0,0 +1,758 @@
+"""Wiring tests for tool-error tier escalation in the dispatcher.
+
+TestClient-driven: temp SQLite seeded from schema.sql, classify stubbed,
+provider stubbed at _provider_client boundary. Follows the pattern from
+tests/test_blocked_routing.py (no real network).
+"""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+from pathlib import Path
+
+import pytest
+from pydantic import ValidationError
+from starlette.testclient import TestClient
+
+import dispatcher
+from config import ToolErrorBumpConfig
+from dispatcher import Classification, app
+
+ROOT = Path(__file__).resolve().parent.parent
+SCHEMA_SQL = (ROOT / "config" / "schema.sql").read_text()
+
+# --- verbatim error strings ---
+
+ERR_OLDSTRING = (
+ "Could not find oldString in the file. It must match exactly, "
+ "including whitespace, indentation, and line endings."
+)
+ERR_ABORT = "Tool execution aborted"
+
+
+# --- message builders ---
+
+def _assistant_call(call_id, name):
+ return {
+ "role": "assistant",
+ "tool_calls": [
+ {
+ "id": call_id,
+ "type": "function",
+ "function": {"name": name, "arguments": "{}"},
+ }
+ ],
+ }
+
+
+def _tool_result(call_id, content):
+ return {
+ "role": "tool",
+ "tool_call_id": call_id,
+ "content": content,
+ }
+
+
+def _messages_with_errors(n):
+ """n consecutive edit-class errors at the tail."""
+ msgs = [{"role": "user", "content": "Refactor this file"}]
+ for i in range(n):
+ cid = f"call{i}"
+ msgs.append(_assistant_call(cid, "edit"))
+ msgs.append(_tool_result(cid, ERR_OLDSTRING))
+ msgs.append({"role": "user", "content": "Try again"})
+ return msgs
+
+
+def _messages_abort(n):
+ """n abort results (should NOT count as errors)."""
+ msgs = [{"role": "user", "content": "Refactor this file"}]
+ for i in range(n):
+ cid = f"call{i}"
+ msgs.append(_assistant_call(cid, "edit"))
+ msgs.append(_tool_result(cid, ERR_ABORT))
+ msgs.append({"role": "user", "content": "Try again"})
+ return msgs
+
+
+_FAKE_COMPLETION_BODY = {
+ "id": "chatcmpl-test",
+ "object": "chat.completion",
+ "created": 1000000000,
+ "model": "tier1-model",
+ "choices": [
+ {
+ "index": 0,
+ "finish_reason": "stop",
+ "message": {"role": "assistant", "content": "Done."},
+ }
+ ],
+ "usage": {"prompt_tokens": 50, "completion_tokens": 10},
+}
+
+
+class _FakeResponse:
+ status_code = 200
+ reason = "OK"
+ text = json.dumps(_FAKE_COMPLETION_BODY)
+
+ @staticmethod
+ def json():
+ return _FAKE_COMPLETION_BODY
+
+ def __bool__(self):
+ return True
+
+
+# --- fixtures ---
+
+@pytest.fixture
+def client(tmp_path, monkeypatch):
+ """Fresh DB + classify stub + provider stub."""
+ db_path = tmp_path / "te.db"
+ conn = sqlite3.connect(db_path)
+ conn.executescript(SCHEMA_SQL)
+
+ models = [
+ ("tier1-model", 1),
+ ("tier2-model", 2),
+ ("tier3-model", 3),
+ ]
+ for model_id, tier in models:
+ conn.execute(
+ """
+ INSERT INTO models (
+ model_id, provider, base_model_id, tier, context_window,
+ effective_context_window, max_output_tokens,
+ cost_per_1m_prompt, cost_per_1m_completion,
+ supports_vision, supports_json_mode,
+ latency_class, reasoning_mode, context_variant,
+ access_level, availability, last_updated
+ ) VALUES (?, 'neuralwatt', ?, ?, 262128, 192500, 16384, 1.0, 2.0,
+ 0, 1, 'standard', 'default', 'full', 'public', 'active',
+ '2026-08-22T00:00:00+00:00')
+ """,
+ (model_id, model_id, tier),
+ )
+ # Proficiency row required for candidate selection.
+ conn.execute(
+ """
+ INSERT INTO proficiency (model_id, provider, category, blended_score,
+ source, last_updated, outcome_samples)
+ VALUES (?, 'neuralwatt', 'coding_general', 0.5,
+ 'leaderboard', '2026-08-22T00:00:00+00:00', 50)
+ """,
+ (model_id,),
+ )
+ conn.commit()
+ conn.close()
+
+ monkeypatch.setattr(dispatcher.cfg.database, "path", str(db_path))
+ monkeypatch.setattr(dispatcher.cfg.verification, "local_llm_enabled", False)
+ monkeypatch.setattr(dispatcher.cfg.local_vision, "enabled", False)
+ monkeypatch.setattr(dispatcher.cfg.local_compute, "enabled", False)
+
+ # Classifier always returns tier 1 (the pre-bump tier).
+ monkeypatch.setattr(
+ dispatcher, "classify",
+ lambda task, context: Classification(
+ task_category="coding_general",
+ task_tier=1,
+ required_context_tokens=0,
+ confidence=0.9,
+ ),
+ )
+
+ monkeypatch.setattr(dispatcher.requests, "post",
+ lambda *a, **kw: _FakeResponse())
+ monkeypatch.setattr(dispatcher.requests, "post",
+ lambda *a, **kw: _FakeResponse())
+
+ return TestClient(app)
+
+
+@pytest.fixture
+def saved_cfg():
+ """Save and restore cfg fields around each test."""
+ import session_cache
+ saved = {
+ "escalation_enabled": dispatcher.cfg.escalation.enabled,
+ "bump_config": {
+ "enabled": dispatcher.cfg.escalation.tool_error_bump.enabled,
+ "threshold": dispatcher.cfg.escalation.tool_error_bump.threshold,
+ "max_bump": dispatcher.cfg.escalation.tool_error_bump.max_bump,
+ },
+ "max_rebill": dispatcher.cfg.iteration.max_rebill_prompt_tokens,
+ "cache_enabled": dispatcher.cfg.session_cache.enabled,
+ "max_tier": dispatcher.cfg.escalation.max_tier,
+ }
+ dispatcher.cfg.session_cache.enabled = False
+ yield
+ dispatcher.cfg.escalation.enabled = saved["escalation_enabled"]
+ dispatcher.cfg.escalation.tool_error_bump.enabled = saved["bump_config"]["enabled"]
+ dispatcher.cfg.escalation.tool_error_bump.threshold = saved["bump_config"]["threshold"]
+ dispatcher.cfg.escalation.tool_error_bump.max_bump = saved["bump_config"]["max_bump"]
+ dispatcher.cfg.iteration.max_rebill_prompt_tokens = saved["max_rebill"]
+ dispatcher.cfg.session_cache.enabled = saved["cache_enabled"]
+ dispatcher.cfg.escalation.max_tier = saved["max_tier"]
+ session_cache.clear()
+
+
+# --- helper: query last route_decision ---
+
+def _last_decision_row():
+ """Query the newest route_decisions row from the temp DB."""
+ db_path = dispatcher.cfg.database.path
+ conn = sqlite3.connect(db_path)
+ row = conn.execute(
+ """
+ SELECT task_tier, task_category, classification_source, required_context_tokens
+ FROM route_decisions
+ WHERE kind = 'chat'
+ ORDER BY rowid DESC
+ LIMIT 1
+ """
+ ).fetchone()
+ conn.close()
+ return row
+
+
+
+# --- tests ---
+
+def test_positive_control_bumps_tier(client, saved_cfg):
+ """Test 1: flag ON, 3 errors -> tier 2."""
+ dispatcher.cfg.escalation.enabled = True
+ dispatcher.cfg.escalation.tool_error_bump.enabled = True
+ dispatcher.cfg.escalation.tool_error_bump.threshold = 3
+ dispatcher.cfg.escalation.tool_error_bump.max_bump = 1
+
+ resp = client.post(
+ "/v1/chat/completions",
+ json={"model": "auto", "messages": _messages_with_errors(3)},
+ )
+ assert resp.status_code == 200, resp.text
+
+ row = _last_decision_row()
+ assert row is not None
+ assert row[0] == 2, f"Expected tier 2 (bumped), got {row[0]}"
+
+
+def test_flag_off_no_bump(client, saved_cfg):
+ """Test 2: flag OFF, 3 errors -> tier 1 (same as today)."""
+ dispatcher.cfg.escalation.enabled = False
+ resp = client.post(
+ "/v1/chat/completions",
+ json={"model": "auto", "messages": _messages_with_errors(3)},
+ )
+ assert resp.status_code == 200
+ row = _last_decision_row()
+ assert row is not None
+ assert row[0] == 1, f"Expected tier 1 (no bump), got {row[0]}"
+
+
+def test_shadow_mode_logs_scan(client, caplog, saved_cfg):
+ """Test 3: flag OFF, 2 errors -> shadow log, no bump."""
+ import logging
+
+ dispatcher.cfg.escalation.enabled = False
+ caplog.set_level(logging.INFO)
+
+ resp = client.post(
+ "/v1/chat/completions",
+ json={"model": "auto", "messages": _messages_with_errors(2)},
+ )
+ assert resp.status_code == 200
+
+ row = _last_decision_row()
+ assert row is not None
+ assert row[0] == 1
+
+ found = any(
+ "tool_error_scan" in record.message
+ and "errors=2" in record.message
+ and "would_escalate=0" in record.message
+ and "tier=1" in record.message
+ for record in caplog.records
+ )
+ assert found, f"No shadow scan line found. Records: {[r.message for r in caplog.records]}"
+
+
+def test_session_cache_unbumped_m1(client, saved_cfg):
+ """Test 4: session cache must hold UNBUMPED tier (the M1 fix).
+
+ MUTATION EVIDENCE: revert the put back to
+ ``decision.classification.task_tier`` (one-line edit) -> MUST FAIL
+ (cache now holds 2 instead of 1).
+ """
+ dispatcher.cfg.escalation.enabled = True
+ dispatcher.cfg.escalation.tool_error_bump.enabled = True
+ dispatcher.cfg.escalation.tool_error_bump.threshold = 3
+ dispatcher.cfg.escalation.tool_error_bump.max_bump = 1
+ dispatcher.cfg.session_cache.enabled = True
+
+ # First request: cache miss, triggers classify branch + bump -> tier 2.
+ resp = client.post(
+ "/v1/chat/completions",
+ json={"model": "auto", "messages": _messages_with_errors(3)},
+ headers={"X-Router-Conversation": "test-session-m1"},
+ )
+ assert resp.status_code == 200
+
+ row = _last_decision_row()
+ assert row[0] == 2, f"Persisted tier should be 2, got {row[0]}"
+
+ # Second request: a follow-up with a success resets error count,
+ # triggers cache hit path. The cache should hold tier 1.
+ resp2 = client.post(
+ "/v1/chat/completions",
+ json={
+ "model": "auto",
+ "messages": [
+ {"role": "user", "content": "previous"},
+ _assistant_call("c0", "edit"),
+ _tool_result("c0", "The file has been updated."),
+ {"role": "user", "content": "next"},
+ ],
+ },
+ headers={"X-Router-Conversation": "test-session-m1"},
+ )
+ assert resp2.status_code == 200
+
+ # On the cached branch, tier should be 1 (from cache), NOT 2.
+ row2 = _last_decision_row()
+ assert row2 is not None
+ assert row2[0] == 1, f"Expected cached tier 1, got {row2[0]}"
+
+
+def test_cache_write_unchanged_on_low_errors(client, saved_cfg):
+ """Test 5: 1 error (below threshold) -> cache write is normal."""
+ dispatcher.cfg.escalation.enabled = True
+ dispatcher.cfg.escalation.tool_error_bump.enabled = True
+ dispatcher.cfg.escalation.tool_error_bump.threshold = 3
+ dispatcher.cfg.session_cache.enabled = True
+
+ resp = client.post(
+ "/v1/chat/completions",
+ json={"model": "auto", "messages": _messages_with_errors(1)},
+ headers={"X-Router-Conversation": "test-cache-low-err"},
+ )
+ assert resp.status_code == 200
+
+ row = _last_decision_row()
+ assert row[0] == 1, f"Expected tier 1 (below threshold), got {row[0]}"
+
+
+def test_global_kill_switch(client, saved_cfg):
+ """Test 6: global escalation.enabled=False -> no bump."""
+ dispatcher.cfg.escalation.enabled = False
+ dispatcher.cfg.escalation.tool_error_bump.enabled = True
+ dispatcher.cfg.escalation.tool_error_bump.threshold = 3
+
+ resp = client.post(
+ "/v1/chat/completions",
+ json={"model": "auto", "messages": _messages_with_errors(3)},
+ )
+ assert resp.status_code == 200
+
+ row = _last_decision_row()
+ assert row[0] == 1, f"Expected tier 1 (global kill switch), got {row[0]}"
+
+
+def test_rebill_guard(client, saved_cfg):
+ """Test 7: max_rebill_prompt_tokens=1, prompt > 1 -> no bump."""
+ dispatcher.cfg.escalation.enabled = True
+ dispatcher.cfg.escalation.tool_error_bump.enabled = True
+ dispatcher.cfg.escalation.tool_error_bump.threshold = 3
+ dispatcher.cfg.iteration.max_rebill_prompt_tokens = 1
+
+ msgs = _messages_with_errors(3)
+ msgs[-1]["content"] = "A" * 500 # pad so measured prompt > 1
+
+ resp = client.post(
+ "/v1/chat/completions",
+ json={"model": "auto", "messages": msgs},
+ )
+ assert resp.status_code == 200
+
+ row = _last_decision_row()
+ assert row[0] == 1, f"Expected tier 1 (rebill guard), got {row[0]}"
+
+
+def test_cached_branch_bumps(client, saved_cfg):
+ """Test 8: cache hit + 3 errors -> cached-branch bump to tier 2."""
+ dispatcher.cfg.escalation.enabled = True
+ dispatcher.cfg.escalation.tool_error_bump.enabled = True
+ dispatcher.cfg.escalation.tool_error_bump.threshold = 3
+ dispatcher.cfg.session_cache.enabled = True
+ dispatcher.cfg.escalation.max_tier = 3
+
+ # Seed the session cache with tier 1.
+ dispatcher.session_cache.put(
+ "c:test-session-cache-branch",
+ "coding_general",
+ 1,
+ )
+
+ resp = client.post(
+ "/v1/chat/completions",
+ json={"model": "auto", "messages": _messages_with_errors(3)},
+ headers={"X-Router-Conversation": "test-session-cache-branch"},
+ )
+ assert resp.status_code == 200
+
+ row = _last_decision_row()
+ assert row[0] == 2, f"Expected tier 2 (cached bump), got {row[0]}"
+
+
+def test_never_lowers_tier(client, saved_cfg):
+ """Test 9: bump never lowers tier (already at max_tier=3)."""
+ dispatcher.cfg.escalation.enabled = True
+ dispatcher.cfg.escalation.tool_error_bump.enabled = True
+ dispatcher.cfg.escalation.tool_error_bump.threshold = 3
+ dispatcher.cfg.escalation.tool_error_bump.max_bump = 1
+ dispatcher.cfg.session_cache.enabled = True
+ dispatcher.cfg.escalation.max_tier = 3
+
+ # Seed the cache with tier 3 (max). Key must include 'c:' prefix since
+ # resolve_identity prefixes X-Router-Conversation with 'c:'.
+ dispatcher.session_cache.put(
+ "c:test-session-never-low",
+ "coding_general",
+ 3,
+ )
+
+ resp = client.post(
+ "/v1/chat/completions",
+ json={"model": "auto", "messages": _messages_with_errors(3)},
+ headers={"X-Router-Conversation": "test-session-never-low"},
+ )
+ assert resp.status_code == 200
+
+ row = _last_decision_row()
+ assert row[0] == 3, f"Expected tier 3 (never lowers), got {row[0]}"
+
+
+def test_abort_does_not_count(client, caplog, saved_cfg):
+ """Test 11: abort results -> no bump, no escalation log."""
+ import logging
+
+ dispatcher.cfg.escalation.enabled = True
+ dispatcher.cfg.escalation.tool_error_bump.enabled = True
+ dispatcher.cfg.escalation.tool_error_bump.threshold = 3
+
+ caplog.set_level(logging.INFO)
+
+ resp = client.post(
+ "/v1/chat/completions",
+ json={"model": "auto", "messages": _messages_abort(3)},
+ )
+ assert resp.status_code == 200
+
+ row = _last_decision_row()
+ assert row[0] == 1, f"Expected tier 1 (abort neutral), got {row[0]}"
+
+ escalation_found = any(
+ "tool_error_escalation" in record.message
+ for record in caplog.records
+ )
+ assert not escalation_found, (
+ "tool_error_escalation should NOT appear for abort-only"
+ )
+
+
+# --- validator tests ---
+
+
+def test_threshold_zero_rejected():
+ """Test 10: threshold=0 must be rejected."""
+ with pytest.raises(ValidationError) as exc:
+ ToolErrorBumpConfig(threshold=0)
+ assert "threshold must be >= 1" in str(exc.value)
+
+
+def test_max_bump_five_rejected():
+ """Test 12: max_bump=5 must be rejected (only 1 or 2 allowed)."""
+ with pytest.raises(ValidationError) as exc:
+ ToolErrorBumpConfig(max_bump=5)
+ assert "max_bump must be in 1..2" in str(exc.value)
+
+
+# --- bump-only re-route context test ---
+
+
+def test_bump_only_reoute_keeps_larger_estimate(client, saved_cfg, monkeypatch):
+ """Test 13: bump-only re-route uses max(measured, classifier_estimate).
+
+ When only the bump triggers re-route (measured <= classifier_estimate),
+ the decision's required_context_tokens should be the larger estimate
+ (classifier_estimate), not just measured.
+ """
+ dispatcher.cfg.escalation.enabled = True
+ dispatcher.cfg.escalation.tool_error_bump.enabled = True
+ dispatcher.cfg.escalation.tool_error_bump.threshold = 3
+ dispatcher.cfg.escalation.tool_error_bump.max_bump = 1
+ dispatcher.cfg.session_cache.enabled = True
+ dispatcher.cfg.escalation.max_tier = 3
+
+ # Patch the classifier to return a LARGE required_context_tokens so that
+ # measured (< 1k) is smaller -- the max() should pick the classifier value.
+ monkeypatch.setattr(
+ dispatcher, "classify",
+ lambda task, context: Classification(
+ task_category="coding_general",
+ task_tier=1,
+ required_context_tokens=50000,
+ confidence=0.9,
+ ),
+ )
+
+ # Small conversation with 3 edit-class errors -> triggers bump
+ msgs = _messages_with_errors(3)
+
+ resp = client.post(
+ "/v1/chat/completions",
+ json={"model": "auto", "messages": msgs},
+ )
+ assert resp.status_code == 200, resp.text
+
+ # The route_decision should have required_context_tokens = 50000
+ # (max of measured ~122 and classifier_estimate 50000)
+ db_path = dispatcher.cfg.database.path
+ conn = sqlite3.connect(db_path)
+ row = conn.execute(
+ """
+ SELECT required_context_tokens FROM route_decisions
+ WHERE kind = 'chat'
+ ORDER BY rowid DESC LIMIT 1
+ """
+ ).fetchone()
+ conn.close()
+
+ assert row is not None
+ assert row[0] >= 50000, f"Expected >=50000, got {row[0]}"
+
+
+# --- ITEM 0 bump-count test (moved from test_metrics.py) ---
+
+def test_tool_error_bumps_by_model_ttl(client, tmp_path, monkeypatch):
+ """A bump 30h old is excluded; one 2h old is counted."""
+ from datetime import datetime, timedelta, timezone
+ import metrics as metrics_mod
+
+ db_path = tmp_path / "bumps.db"
+ conn = sqlite3.connect(db_path)
+ conn.row_factory = sqlite3.Row
+ conn.executescript(SCHEMA_SQL)
+
+ now = datetime.now(timezone.utc)
+ two_hours_ago = (now - timedelta(hours=2)).strftime("%Y-%m-%dT%H:%M:%S")
+ thirty_hours_ago = (now - timedelta(hours=30)).strftime("%Y-%m-%dT%H:%M:%S")
+
+ # Session A: previous row at 30h, bump at 30h -> excluded (outside 24h window)
+ conn.execute(
+ "INSERT INTO route_decisions "
+ "(observed_at, kind, task_category, task_tier, selected_model, "
+ "session_key) VALUES (?, 'chat', 'coding_general', 1, 'old-model', 'sess-bump-ttl')",
+ (thirty_hours_ago,),
+ )
+ conn.execute(
+ "INSERT INTO route_decisions "
+ "(observed_at, kind, task_category, task_tier, selected_model, "
+ "session_key, escalation_reason) VALUES (?, 'chat', 'coding_general', 2, 'bumped-model', "
+ "'sess-bump-ttl', 'tool_errors:3:1->2')",
+ (thirty_hours_ago,),
+ )
+
+ # Session B: previous row at 2h, bump at 2h -> counted
+ conn.execute(
+ "INSERT INTO route_decisions "
+ "(observed_at, kind, task_category, task_tier, selected_model, "
+ "session_key) VALUES (?, 'chat', 'coding_general', 1, 'fresh-model', 'sess-bump-ttl-b')",
+ (two_hours_ago,),
+ )
+ conn.execute(
+ "INSERT INTO route_decisions "
+ "(observed_at, kind, task_category, task_tier, selected_model, "
+ "session_key, escalation_reason) VALUES (?, 'chat', 'coding_general', 2, 'bumped-model2', "
+ "'sess-bump-ttl-b', 'tool_errors:3:1->2')",
+ (two_hours_ago,),
+ )
+
+ conn.commit()
+ conn.close()
+
+ fresh_conn = sqlite3.connect(db_path)
+ fresh_conn.row_factory = sqlite3.Row
+ result = metrics_mod.tool_error_bumps_by_model(fresh_conn)
+ fresh_conn.close()
+
+ # Only the 2h bump should appear; 30h bump excluded by 24h window
+ expected = {
+ "bumps": 1,
+ }
+ # There should be exactly one row
+ assert len(result) == 1, f"Expected 1 row, got {len(result)}: {result}"
+ assert result[0]["model"] == "fresh-model"
+ assert result[0]["bumps"] == expected["bumps"]
+
+
+
+# --- ITEM A: bump falls back when bumped tier has no candidates ---
+
+def test_bump_fallback_cache_miss(client, saved_cfg):
+ """Cache-miss: 3 edit errors bump tier 1->2, but tier-3 models don't exist,
+ so the bump is skipped and the original tier (1) is used. Returns 200."""
+ import sqlite3 as sqlite3_mod
+ import dispatcher as disp_mod
+
+ disp_mod.cfg.escalation.enabled = True
+ disp_mod.cfg.escalation.tool_error_bump.enabled = True
+ disp_mod.cfg.escalation.tool_error_bump.threshold = 3
+ disp_mod.cfg.escalation.tool_error_bump.max_bump = 2
+ disp_mod.cfg.escalation.max_tier = 3
+
+ # Delete tier-3 models so bumping to tier 2+ has no candidates
+ db_path = disp_mod.cfg.database.path
+ conn = sqlite3_mod.connect(db_path)
+ conn.execute("DELETE FROM models WHERE tier = 3")
+ conn.execute("DELETE FROM proficiency WHERE model_id = 'tier3-model'")
+ conn.commit()
+ conn.close()
+
+ msgs = _messages_with_errors(3)
+ resp = client.post(
+ "/v1/chat/completions",
+ json={"model": "auto", "messages": msgs},
+ )
+ assert resp.status_code == 200, resp.text
+
+ # The persisted tier should be the ORIGINAL (1), not bumped, and
+ # escalation_reason should be NULL because the bump was skipped.
+ row = _last_decision_row()
+ assert row[0] == 1, f"Expected original tier 1, got {row[0]}"
+
+ # Check escalation_reason is NULL
+ conn = sqlite3_mod.connect(db_path)
+ row2 = conn.execute(
+ "SELECT escalation_reason FROM route_decisions "
+ "WHERE kind = 'chat' ORDER BY rowid DESC LIMIT 1"
+ ).fetchone()
+ conn.close()
+ assert row2[0] is None, f"Expected escalation_reason NULL, got {row2[0]}"
+
+
+def test_bump_fallback_cached_branch(client, saved_cfg):
+ """Cache-hit: cached tier 1, 3 errors bump to tier 2, but no tier-3 models,
+ so fallback to original tier 1. Returns 200."""
+ import sqlite3 as sqlite3_mod
+ import dispatcher as disp_mod
+
+ disp_mod.cfg.escalation.enabled = True
+ disp_mod.cfg.escalation.tool_error_bump.enabled = True
+ disp_mod.cfg.escalation.tool_error_bump.threshold = 3
+ disp_mod.cfg.escalation.tool_error_bump.max_bump = 2
+ disp_mod.cfg.escalation.max_tier = 3
+ disp_mod.cfg.session_cache.enabled = True
+
+ # Delete tier-3 models
+ db_path = disp_mod.cfg.database.path
+ conn = sqlite3_mod.connect(db_path)
+ conn.execute("DELETE FROM models WHERE tier = 3")
+ conn.execute("DELETE FROM proficiency WHERE model_id = 'tier3-model'")
+ conn.commit()
+ conn.close()
+
+ # Seed the cache with tier 1
+ disp_mod.session_cache.put(
+ "c:test-session-bump-fallback",
+ "coding_general",
+ 1,
+ )
+
+ msgs = _messages_with_errors(3)
+ resp = client.post(
+ "/v1/chat/completions",
+ json={"model": "auto", "messages": msgs},
+ headers={"X-Router-Conversation": "test-session-bump-fallback"},
+ )
+ assert resp.status_code == 200, resp.text
+
+ row = _last_decision_row()
+ assert row[0] == 1, f"Expected original tier 1, got {row[0]}"
+
+ conn = sqlite3_mod.connect(db_path)
+ row2 = conn.execute(
+ "SELECT escalation_reason FROM route_decisions "
+ "WHERE kind = 'chat' ORDER BY rowid DESC LIMIT 1"
+ ).fetchone()
+ conn.close()
+ assert row2[0] is None, f"Expected escalation_reason NULL, got {row2[0]}"
+
+
+
+# --- ITEM F: pin the never-lowers guard ---
+
+def test_never_lowers_pins_reason_null(client, saved_cfg):
+ """With cached tier 3 and escalation.max_tier = 3, bump does not
+ change the tier and escalation_reason is NULL. Same with max_tier = 2."""
+ import sqlite3 as sqlite3_mod
+ import dispatcher as disp_mod
+
+ disp_mod.cfg.escalation.enabled = True
+ disp_mod.cfg.escalation.tool_error_bump.enabled = True
+ disp_mod.cfg.escalation.tool_error_bump.threshold = 3
+ disp_mod.cfg.session_cache.enabled = True
+
+ # --- Case 1: cached tier 3, max_tier = 3 ---
+ disp_mod.cfg.escalation.max_tier = 3
+ disp_mod.session_cache.put(
+ "c:test-never-lower-pin-1",
+ "coding_general",
+ 3,
+ )
+ resp = client.post(
+ "/v1/chat/completions",
+ json={"model": "auto", "messages": _messages_with_errors(3)},
+ headers={"X-Router-Conversation": "test-never-lower-pin-1"},
+ )
+ assert resp.status_code == 200, resp.text
+
+ row = _last_decision_row()
+ assert row[0] == 3, f"Case 1: Expected tier 3, got {row[0]}"
+
+ db_path = disp_mod.cfg.database.path
+ conn = sqlite3_mod.connect(db_path)
+ row2 = conn.execute(
+ "SELECT escalation_reason FROM route_decisions "
+ "WHERE kind = 'chat' ORDER BY rowid DESC LIMIT 1"
+ ).fetchone()
+ conn.close()
+ assert row2[0] is None, f"Case 1: Expected NULL, got {row2[0]}"
+
+ # --- Case 2: cached tier 3, max_tier = 2 ---
+ # max_tier < cached tier: bump guard (new_tier <= tier) should keep tier 3
+ disp_mod.cfg.escalation.max_tier = 2
+ disp_mod.session_cache.put(
+ "c:test-never-lower-pin-2",
+ "coding_general",
+ 3,
+ )
+ resp = client.post(
+ "/v1/chat/completions",
+ json={"model": "auto", "messages": _messages_with_errors(3)},
+ headers={"X-Router-Conversation": "test-never-lower-pin-2"},
+ )
+ assert resp.status_code == 200, resp.text
+
+ # The tier should stay 3 (never lowers)
+ conn = sqlite3_mod.connect(db_path)
+ row3 = conn.execute(
+ "SELECT task_tier, escalation_reason FROM route_decisions "
+ "WHERE kind = 'chat' ORDER BY rowid DESC LIMIT 1"
+ ).fetchone()
+ conn.close()
+ assert row3[0] == 3, f"Case 2: Expected tier 3, got {row3[0]}"
+ assert row3[1] is None, f"Case 2: Expected NULL, got {row3[1]}"
+
diff --git a/tests/test_tool_errors.py b/tests/test_tool_errors.py
new file mode 100644
index 0000000..952b8cb
--- /dev/null
+++ b/tests/test_tool_errors.py
@@ -0,0 +1,143 @@
+import pytest
+from src.tool_errors import count_trailing_tool_errors
+
+ERROR_STRINGS = (
+ "could not find oldstring",
+ "found multiple matches",
+ "oldstring cannot be empty",
+ "no changes to apply",
+)
+
+def _assistant_call(call_id: str, name: str) -> dict:
+ return {
+ "role": "assistant",
+ "tool_calls": [
+ {
+ "id": call_id,
+ "function": {"name": name}
+ }
+ ]
+ }
+
+def _tool_result(call_id: str, content: str | list) -> dict:
+ return {
+ "role": "tool",
+ "tool_call_id": call_id,
+ "content": content
+ }
+
+@pytest.mark.parametrize("err", ERROR_STRINGS)
+def test_single_error_strings(err):
+ messages = [
+ _assistant_call("c1", "edit"),
+ _tool_result("c1", err)
+ ]
+ assert count_trailing_tool_errors(messages) == 1
+
+def test_abort_neutral_on_edit():
+ messages = [
+ _assistant_call("c1", "edit"),
+ _tool_result("c1", "tool execution aborted")
+ ]
+ assert count_trailing_tool_errors(messages) == 0
+
+def test_bash_non_zero_after_edit_error():
+ messages = [
+ _assistant_call("c1", "edit"),
+ _tool_result("c1", ERROR_STRINGS[0]),
+ _assistant_call("c2", "bash"),
+ _tool_result("c2", "exit 1")
+ ]
+ # bash is not an edit tool, so it's skipped (no reset).
+ assert count_trailing_tool_errors(messages) == 1
+
+def test_successful_edit_resets_count():
+ messages = [
+ _assistant_call("c1", "edit"),
+ _tool_result("c1", ERROR_STRINGS[0]),
+ _assistant_call("c2", "edit"),
+ _tool_result("c2", "Successfully applied patch.")
+ ]
+ assert count_trailing_tool_errors(messages) == 0
+
+
+def test_three_consecutive_edit_errors():
+ messages = [
+ _assistant_call("c1", "edit"),
+ _tool_result("c1", ERROR_STRINGS[0]),
+ _assistant_call("c2", "edit"),
+ _tool_result("c2", ERROR_STRINGS[1]),
+ _assistant_call("c3", "edit"),
+ _tool_result("c3", ERROR_STRINGS[2]),
+ ]
+ assert count_trailing_tool_errors(messages) == 3
+
+
+def test_err_success_err_trailing_run_is_one():
+ messages = [
+ _assistant_call("c1", "edit"),
+ _tool_result("c1", ERROR_STRINGS[0]),
+ _assistant_call("c2", "edit"),
+ _tool_result("c2", "Done."),
+ _assistant_call("c3", "edit"),
+ _tool_result("c3", ERROR_STRINGS[0]),
+ ]
+ assert count_trailing_tool_errors(messages) == 1
+
+def test_tool_call_id_with_no_assistant_call_not_counted():
+ messages = [
+ _tool_result("unknown_id", ERROR_STRINGS[0])
+ ]
+ assert count_trailing_tool_errors(messages) == 0
+
+def test_non_dict_junk_no_raise_no_count():
+ # tool_call_id with no assistant call -> skipped
+ messages = [
+ {"role": "tool", "content": ERROR_STRINGS[0]}
+ ]
+ assert count_trailing_tool_errors(messages) == 0
+
+
+def test_content_list_of_text_parts_matches():
+ messages = [
+ _assistant_call("c1", "edit"),
+ _tool_result("c1", [
+ {"type": "text", "text": "Some preamble"},
+ {"type": "text", "text": "could not find oldstring in the file."},
+ ])
+ ]
+ assert count_trailing_tool_errors(messages) == 1
+
+
+def test_content_json_wrapped_string_matches():
+ messages = [
+ _assistant_call("c1", "edit"),
+ _tool_result("c1", '"could not find oldstring"')
+ ]
+ assert count_trailing_tool_errors(messages) == 1
+
+def test_window_cap_60_errors_gives_40():
+ messages = []
+ for i in range(60):
+ cid = f"c{i}"
+ messages.append(_assistant_call(cid, "edit"))
+ messages.append(_tool_result(cid, ERROR_STRINGS[0]))
+ assert count_trailing_tool_errors(messages) == 40
+
+def test_empty_messages_list():
+ assert count_trailing_tool_errors([]) == 0
+
+def test_abort_neutral_middle():
+ # [err, err, aborted, err] walking backwards:
+ # err (count=1), aborted (skip, count stays 1), err (count=2), err (count=3)
+ messages = [
+ _assistant_call("c1", "edit"),
+ _tool_result("c1", ERROR_STRINGS[0]),
+ _assistant_call("c2", "edit"),
+ _tool_result("c2", ERROR_STRINGS[1]),
+ _assistant_call("c3", "edit"),
+ _tool_result("c3", "tool execution aborted"),
+ _assistant_call("c4", "edit"),
+ _tool_result("c4", ERROR_STRINGS[0]),
+ ]
+ assert count_trailing_tool_errors(messages) == 3
diff --git a/tests/test_tui_schema_drift.py b/tests/test_tui_schema_drift.py
index 4b53966..e72fbb0 100644
--- a/tests/test_tui_schema_drift.py
+++ b/tests/test_tui_schema_drift.py
@@ -85,6 +85,7 @@ SCHEMA_TO_MODEL_KEYS = {
# in NEITHER registry fails the drift test.
UNSURFACED_COLUMNS: set[str] = {
"parent_key", # opaque id, recorded for later lineage queries, not displayed
+ "escalation_reason", # forensics column -- why the tier was bumped, logged for audit
}
# Every column seeded non-NULL: the single source of truth for the INSERT and
diff --git a/tests/test_tui_warnings.py b/tests/test_tui_warnings.py
index b33cdc0..331fc0e 100644
--- a/tests/test_tui_warnings.py
+++ b/tests/test_tui_warnings.py
@@ -71,6 +71,7 @@ WARN_CLASS_MATCHERS = {
# lookbehind: "cache rate outlier:" never contains "cache rate: measured".
"cache-rate-premise": r"cache rate: measured",
"cache-rate-outlier": r"cache rate outlier:",
+ "tool-error-bumps": r"tool-error tier bumps in the last 24h",
}
CFG = SimpleNamespace(
@@ -301,6 +302,21 @@ def _seed_chernobyl(conn: sqlite3.Connection) -> None:
((now - timedelta(minutes=i)).isoformat(),),
)
+ # --- tool-error bump seed ---
+ # Two route_decisions rows in ONE session: the earlier row establishes the
+ # selected_model (the model that will later be replaced), then the later
+ # row fires escalation_reason='tool_errors:3:1->2'. Both must be within
+ # 24 h so the 24h window captures them. The query finds the previous
+ # decision for the session_key, reads its selected_model, and counts bumps
+ # per model.
+ _decision(session_key="tool-error-session", selected_model="gemma-4-31b")
+ _decision(
+ session_key="tool-error-session",
+ escalation_reason="tool_errors:3:1->2",
+ selected_model="gpt-4o",
+ observed_at=now.isoformat(),
+ )
+
conn.commit()