From 5b85f05b6f723668ea1b34c738c913e56d8f2891 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 18 Oct 2026 00:40:42 -0400 Subject: [PATCH 01/19] feat: tool_errors module counts trailing edit-tool errors --- src/tool_errors.py | 129 ++++++++++++++++++++++++++++++++++ tests/test_tool_errors.py | 143 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 272 insertions(+) create mode 100644 src/tool_errors.py create mode 100644 tests/test_tool_errors.py 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/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 -- 2.49.1 From 864cd6f15465b029639804b47f24c2f843400b4a Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 18 Oct 2026 00:46:43 -0400 Subject: [PATCH 02/19] feat: implement tool error bump config and dispatcher wiring --- config/config.yaml | 6 ++++ src/config.py | 7 +++++ src/dispatcher.py | 75 ++++++++++++++++++++++++++++++++++++++++++---- 3 files changed, 83 insertions(+), 5 deletions(-) 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/src/config.py b/src/config.py index 6c6bd5c..1b76491 100644 --- a/src/config.py +++ b/src/config.py @@ -687,12 +687,19 @@ class LocalVisionConfig(StrictModel): return v +class ToolErrorBumpConfig(StrictModel): + enabled: bool = False + threshold: int = 3 + max_bump: int = 1 + + 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..584bebe 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,43 @@ class DispatchResponse(BaseModel): # --- infrastructure ------------------------------------------------------- +def _apply_tool_error_bump( + tier: int, + messages: list[dict], + prompt_tokens: int, +) -> tuple[int, Optional[str]]: + 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. @@ -4891,6 +4929,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,6 +4939,12 @@ def chat_completions(body: dict[str, Any], background: BackgroundTasks, request: classifier_attempt = None classifier_ms = 0 ctx_src = "measured" + # 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 + ) decision = route( TaskRequest( task=_last_user_text(messages), @@ -4911,12 +4956,14 @@ def chat_completions(body: dict[str, Any], background: BackgroundTasks, request: has_images=caps.has_images, require_json_mode=caps.require_json_mode, task_category=cached.task_category, - task_tier=cached.task_tier, + task_tier=bumped_tier, required_context_tokens=measured, ), profile=profile_name, profile_obj=profile_obj, ) + if bump_reason is not None: + pass # handled inline above else: # Cache miss: classify as today, then re-route on measured context @@ -4944,10 +4991,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: + # 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 + ) + if ( + measured > decision.classification.required_context_tokens + or bump_reason is not None + ): ctx_src = "measured" decision = route( TaskRequest( @@ -4960,7 +5018,10 @@ 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, + task_tier=( + bump_tier if bump_reason is not None + else decision.classification.task_tier + ), required_context_tokens=measured, ), profile=profile_name, @@ -4979,10 +5040,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 ( -- 2.49.1 From 80683843407585eace2deeddf1cee501f9e55060 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 18 Oct 2026 01:35:05 -0400 Subject: [PATCH 03/19] fix: validate tool_error_bump config and tidy wiring --- src/config.py | 24 ++ src/dispatcher.py | 16 +- tests/test_tool_error_escalation.py | 534 ++++++++++++++++++++++++++++ 3 files changed, 570 insertions(+), 4 deletions(-) create mode 100644 tests/test_tool_error_escalation.py diff --git a/src/config.py b/src/config.py index 1b76491..3f83558 100644 --- a/src/config.py +++ b/src/config.py @@ -688,10 +688,34 @@ class LocalVisionConfig(StrictModel): 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 diff --git a/src/dispatcher.py b/src/dispatcher.py index 584bebe..4d7313d 100644 --- a/src/dispatcher.py +++ b/src/dispatcher.py @@ -357,6 +357,13 @@ def _apply_tool_error_bump( 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: @@ -4962,8 +4969,6 @@ def chat_completions(body: dict[str, Any], background: BackgroundTasks, request: profile=profile_name, profile_obj=profile_obj, ) - if bump_reason is not None: - pass # handled inline above else: # Cache miss: classify as today, then re-route on measured context @@ -5022,7 +5027,10 @@ def chat_completions(body: dict[str, Any], background: BackgroundTasks, request: bump_tier if bump_reason is not None else decision.classification.task_tier ), - required_context_tokens=measured, + required_context_tokens=max( + measured, + decision.classification.required_context_tokens, + ), ), profile=profile_name, profile_obj=profile_obj, @@ -5041,7 +5049,7 @@ def chat_completions(body: dict[str, Any], background: BackgroundTasks, request: and _session_cache_admits(classified_src) ): # M1 fix: cache the classifier's ORIGINAL verdict - # (classifier_attempt), never the tool-error-bumped tier — + # (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( diff --git a/tests/test_tool_error_escalation.py b/tests/test_tool_error_escalation.py new file mode 100644 index 0000000..33c2cca --- /dev/null +++ b/tests/test_tool_error_escalation.py @@ -0,0 +1,534 @@ +"""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]}" -- 2.49.1 From 9352adc4a7f24a66ae1838c0e75428564396a6fd Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 18 Oct 2026 01:59:04 -0400 Subject: [PATCH 04/19] feat: escalation_reason column on route_decisions 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. --- config/schema.sql | 17 +-- src/dispatcher.py | 17 ++- tests/fixtures/route_decision_no_header.json | 1 + tests/test_conversation_wiring.py | 13 ++- tests/test_route_decisions.py | 117 +++++++++++++++++++ tests/test_tui_schema_drift.py | 1 + 6 files changed, 148 insertions(+), 18 deletions(-) diff --git a/config/schema.sql b/config/schema.sql index 94e9bda..d873852 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, - -- 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. + classifier_reject TEXT, + -- 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/src/dispatcher.py b/src/dispatcher.py index 4d7313d..049fec0 100644 --- a/src/dispatcher.py +++ b/src/dispatcher.py @@ -541,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 ) """ ) @@ -592,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}") @@ -2478,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. @@ -2594,10 +2597,11 @@ def persist_route_decision( flex_preference, flex_swapped, flex_forced, exploration, 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - """, + prefix_prev_message_count, agent, parent_key, + classifier_confidence, classifier_coverage, classifier_reject, + escalation_reason + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, ( observed_at, decision_kind, @@ -2636,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) @@ -2690,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 @@ -5155,6 +5161,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/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_conversation_wiring.py b/tests/test_conversation_wiring.py index 4644504..be7a2cf 100644 --- a/tests/test_conversation_wiring.py +++ b/tests/test_conversation_wiring.py @@ -31,14 +31,15 @@ DEAR = "dear-model" @pytest.fixture(autouse=True, scope="module") def _clear_prefix_probe_state(): - """Clean up ``prefix_probe._store`` after our module so the snapshot - test (runs alphabetically after us) sees a clean prefix-probe cache. - The probe stores per-session fingerprints in process-memory and a - POST with the snapshot's payload here would otherwise make a later - test see a prior turn and report non-NULL prefix divergence.""" - yield + """Clear ``prefix_probe._store`` before and after our module so no + test inherits stale fingerprints from a previous pytest run. + The probe stores per-session fingerprints in process memory — a POST + with the snapshot's payload after another module would otherwise see + a prior turn and report non-NULL prefix divergence.""" import prefix_probe prefix_probe._store.clear() + yield + prefix_probe._store.clear() _SYS = "You work in /home/user/proj and follow the design docs." 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_tui_schema_drift.py b/tests/test_tui_schema_drift.py index 4b53966..8cbfd37 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 -- 2.49.1 From 89a1c0b537def14fe3f7a0cac19f48f051608ee0 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 18 Oct 2026 02:15:37 -0400 Subject: [PATCH 05/19] feat: tool-error bump warning in /metrics and admin decisions --- admin/frontend/decisions.html | 13 +++++++------ src/metrics.py | 36 +++++++++++++++++++++++++++++++++++ tests/test_tui_warnings.py | 16 ++++++++++++++++ 3 files changed, 59 insertions(+), 6 deletions(-) diff --git a/admin/frontend/decisions.html b/admin/frontend/decisions.html index 1d9e962..50bfdc6 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} TimeCategoryProfileTier SourceModelProviderCtx - FlagsCostProfRejected + FlagsCostProfRejectedEscalation - Loading… + Loading… @@ -591,9 +591,9 @@ function matchesFilters(d, f) { if (f.tier && String(d.task_tier || '') !== f.tier) return false; if (f.search) { const haystack = [ - d.selected_model, d.selected_provider, d.session_key, - d.rejected_reason, d.task_category, d.kind, d.profile, - ].filter(Boolean).join(' ').toLowerCase(); + d.selected_model, d.selected_provider, d.session_key, + d.rejected_reason, d.escalation_reason, d.task_category, d.kind, d.profile, + ].filter(Boolean).join(' ').toLowerCase(); if (!haystack.includes(f.search)) return false; } return true; @@ -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/src/metrics.py b/src/metrics.py index 23ebd74..66b5646 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 julianday(d.observed_at) >= julianday('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/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() -- 2.49.1 From 86f0c4411f393d23cc22b4c1442bc951dcd36c93 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 18 Oct 2026 02:29:01 -0400 Subject: [PATCH 06/19] feat: admin controls for all escalation scalars --- admin/frontend/controls.html | 91 +++++++++++++++++++++++++++++++++++- src/admin.py | 66 +++++++++++++++++++++++++- 2 files changed, 155 insertions(+), 2 deletions(-) diff --git a/admin/frontend/controls.html b/admin/frontend/controls.html index 033d9fb..40be16d 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) { @@ -783,7 +868,11 @@ const NUMBER_BOUNDS = { // still caches and the classifier-failure cascade still replays the entry. 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 }, + 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/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"]), -- 2.49.1 From 99de89c203a459b63b30439e97a09a00dddd8e49 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 18 Oct 2026 02:37:30 -0400 Subject: [PATCH 07/19] docs: tool-error tier escalation in routing.md --- docs/routing.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) 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. + -- 2.49.1 From ad113766f71441a963a5455be63cd242a5d03454 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 18 Oct 2026 02:56:28 -0400 Subject: [PATCH 08/19] fix: replace em dashes in added lines for ASCII compliance (closes F2) --- admin/frontend/controls.html | 4 ++-- tests/test_conversation_wiring.py | 2 +- tests/test_tool_error_escalation.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/admin/frontend/controls.html b/admin/frontend/controls.html index 40be16d..fc7262e 100644 --- a/admin/frontend/controls.html +++ b/admin/frontend/controls.html @@ -765,13 +765,13 @@ const KNOB_NOTES = { // --- 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.', + 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.', + 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', }, diff --git a/tests/test_conversation_wiring.py b/tests/test_conversation_wiring.py index be7a2cf..45d5072 100644 --- a/tests/test_conversation_wiring.py +++ b/tests/test_conversation_wiring.py @@ -33,7 +33,7 @@ DEAR = "dear-model" def _clear_prefix_probe_state(): """Clear ``prefix_probe._store`` before and after our module so no test inherits stale fingerprints from a previous pytest run. - The probe stores per-session fingerprints in process memory — a POST + The probe stores per-session fingerprints in process memory -- a POST with the snapshot's payload after another module would otherwise see a prior turn and report non-NULL prefix divergence.""" import prefix_probe diff --git a/tests/test_tool_error_escalation.py b/tests/test_tool_error_escalation.py index 33c2cca..fc76d3b 100644 --- a/tests/test_tool_error_escalation.py +++ b/tests/test_tool_error_escalation.py @@ -497,7 +497,7 @@ def test_bump_only_reoute_keeps_larger_estimate(client, saved_cfg, monkeypatch): 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. + # measured (< 1k) is smaller -- the max() should pick the classifier value. monkeypatch.setattr( dispatcher, "classify", lambda task, context: Classification( -- 2.49.1 From 8055c8dc2ff54320f5deafb7479b6e241c68f61d Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 18 Oct 2026 02:58:10 -0400 Subject: [PATCH 09/19] fix: replace final em dash in test_tui_schema_drift for ASCII compliance --- tests/test_tui_schema_drift.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_tui_schema_drift.py b/tests/test_tui_schema_drift.py index 8cbfd37..e72fbb0 100644 --- a/tests/test_tui_schema_drift.py +++ b/tests/test_tui_schema_drift.py @@ -85,7 +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 + "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 -- 2.49.1 From a6656d3d759c219766b39f61227f7881878b1b4d Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 18 Oct 2026 03:38:39 -0400 Subject: [PATCH 10/19] perf: bound the tool-error bump query with the observed_at index --- src/metrics.py | 2 +- tests/test_metrics.py | 262 ++++++++++++++++++++++++++++-------------- 2 files changed, 177 insertions(+), 87 deletions(-) diff --git a/src/metrics.py b/src/metrics.py index 66b5646..05c6b66 100644 --- a/src/metrics.py +++ b/src/metrics.py @@ -1196,7 +1196,7 @@ def tool_error_bumps_by_model(conn: sqlite3.Connection) -> List[dict]: 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 julianday(d.observed_at) >= julianday('now', '-24 hours') + 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 diff --git a/tests/test_metrics.py b/tests/test_metrics.py index 6fe0f30..f0322cd 100644 --- a/tests/test_metrics.py +++ b/tests/test_metrics.py @@ -53,6 +53,7 @@ from metrics import ( scoring_coverage, selection_coverage, selection_coverage_warnings, + tool_error_bumps_by_model, top_proficiency, unroutable_models, verdict_mix, @@ -127,12 +128,12 @@ def _seed_proficiency(conn: sqlite3.Connection) -> None: def _seed_energy(conn: sqlite3.Connection) -> None: now = _now() recent_rows = [ - ("cheap", 5.0e-05, 100, 0.25), # 2 days ago - ("cheap", 3.0e-05, 200, 0.50), # 2 days ago - ("dear", 1.0e-04, 150, 0.75), # 5 days ago - ("tiny", 1.0e-05, 50, 1.00), # 10 days ago + ("cheap", 5.0e-05, 100, 0.25), # 2 days ago + ("cheap", 3.0e-05, 200, 0.50), # 2 days ago + ("dear", 1.0e-04, 150, 0.75), # 5 days ago + ("tiny", 1.0e-05, 50, 1.00), # 10 days ago ] - for (model_id, kwh, tokens, attr) in recent_rows: + for model_id, kwh, tokens, attr in recent_rows: conn.execute( """ INSERT INTO energy_observations ( @@ -484,8 +485,12 @@ def test_quota_accounts_interleaved_providers_independent(tmp_path): conn.commit() result = quota_accounts(conn, cfg) by_provider = {a["provider"]: a for a in result["accounts"]} - assert by_provider["neuralwatt"]["burn"]["burn_rate_usd_per_hour"] == pytest.approx(1.0) - assert by_provider["openrouter"]["burn"]["burn_rate_usd_per_hour"] == pytest.approx(4.0) + assert by_provider["neuralwatt"]["burn"]["burn_rate_usd_per_hour"] == pytest.approx( + 1.0 + ) + assert by_provider["openrouter"]["burn"]["burn_rate_usd_per_hour"] == pytest.approx( + 4.0 + ) assert by_provider["neuralwatt"]["shape"] == "metered_plan" assert by_provider["openrouter"]["shape"] == "prepaid_credit" @@ -584,7 +589,9 @@ def test_local_energy_summary_reset_date_is_billing_period_start(tmp_path): if today.month == 1: expected_period_start = date(today.year - 1, 12, reset_day).isoformat() else: - expected_period_start = date(today.year, today.month - 1, reset_day).isoformat() + expected_period_start = date( + today.year, today.month - 1, reset_day + ).isoformat() expected_rolling_start = (today - timedelta(days=30)).isoformat() result = local_energy_summary(conn, cfg) @@ -617,7 +624,9 @@ def test_pinch_summary_reset_date_is_billing_period_start(tmp_path): if today.month == 1: expected_period_start = date(today.year - 1, 12, reset_day).isoformat() else: - expected_period_start = date(today.year, today.month - 1, reset_day).isoformat() + expected_period_start = date( + today.year, today.month - 1, reset_day + ).isoformat() expected_rolling_start = (today - timedelta(days=30)).isoformat() result = pinch_summary(conn, cfg) @@ -977,8 +986,7 @@ def test_capability_demand_warning_incident_reproduction(tmp_path): conn, tier=1, reason=( - "context >= 242486 tokens; " - "vision-capable model (request carries image(s))" + "context >= 242486 tokens; vision-capable model (request carries image(s))" ), observed_at=ts, tokens=200000, @@ -1059,8 +1067,7 @@ def test_capability_json_mode_demand_warning(tmp_path): conn, tier=1, reason=( - "context >= 242486 tokens; json-mode-capable model " - "(json_mode requested)" + "context >= 242486 tokens; json-mode-capable model (json_mode requested)" ), observed_at=_now().isoformat(), tokens=200000, @@ -1231,10 +1238,14 @@ def test_rejection_warnings_novel_group_at_incident_volume_fires(tmp_path): _seed_models(conn) ts = _now().isoformat() for reason in ( - "tier >= 1; context >= 242486 tokens; interactive; " - "vision-capable model (request carries image(s))", - "tier >= 1; context >= 195000 tokens; interactive; " - "vision-capable model (request carries image(s))", + ( + "tier >= 1; context >= 242486 tokens; interactive; " + "vision-capable model (request carries image(s))" + ), + ( + "tier >= 1; context >= 195000 tokens; interactive; " + "vision-capable model (request carries image(s))" + ), ): _insert_rejected_decision(conn, tier=1, reason=reason, observed_at=ts) @@ -1530,7 +1541,7 @@ def test_per_model_aggregates_correctly(tmp_path): ("cheap", 0.002, 3.0e-05, 1.2e-03, 200, 0.50), ("dear", 0.010, 1.0e-04, 5.0e-03, 150, 0.75), ] - for (model_id, cost, kwh, carbon, tokens, attr) in rows: + for model_id, cost, kwh, carbon, tokens, attr in rows: conn.execute( "INSERT INTO energy_observations " "(model_id, provider, cost_usd, energy_kwh, carbon_g_co2eq, " @@ -1623,9 +1634,9 @@ def test_top_proficiency_ordered_correctly(tmp_path): results = top_proficiency(conn, "coding_general") assert len(results) == 3 - assert results[0]["model_id"] == "dear" # 0.95 - assert results[1]["model_id"] == "cheap" # 0.90 - assert results[2]["model_id"] == "tiny" # 0.70 + assert results[0]["model_id"] == "dear" # 0.95 + assert results[1]["model_id"] == "cheap" # 0.90 + assert results[2]["model_id"] == "tiny" # 0.70 def test_top_proficiency_filter_by_category(tmp_path): @@ -1774,12 +1785,20 @@ def test_pinch_summary_aggregates_correctly(tmp_path, monkeypatch): _seed_pinch_models(conn) # Two pruned cheap rows: saved tokens 50 and 30. - _insert_pinch_decision(conn, model="cheap", provider="neuralwatt", orig=100, final=50) - _insert_pinch_decision(conn, model="cheap", provider="neuralwatt", orig=80, final=50) + _insert_pinch_decision( + conn, model="cheap", provider="neuralwatt", orig=100, final=50 + ) + _insert_pinch_decision( + conn, model="cheap", provider="neuralwatt", orig=80, final=50 + ) # One non-pruned cheap row (final == orig). - _insert_pinch_decision(conn, model="cheap", provider="neuralwatt", orig=60, final=60) + _insert_pinch_decision( + conn, model="cheap", provider="neuralwatt", orig=60, final=60 + ) # One pruned dear row with NULL cost_per_1m_prompt_cached -> falls back to prompt price. - _insert_pinch_decision(conn, model="dear", provider="neuralwatt", orig=200, final=100) + _insert_pinch_decision( + conn, model="dear", provider="neuralwatt", orig=200, final=100 + ) # One rejection row with NULL selected_model -> counted in share/tokens but excluded from dollars. _insert_pinch_decision(conn, model=None, provider=None, orig=1000, final=500) @@ -1824,9 +1843,48 @@ def test_pinch_summary_disabled_returns_none(tmp_path, monkeypatch): assert pinch_summary(conn, cfg) is None +def test_tool_error_bumps_window_filtering(tmp_path): + """Bumps are correctly filtered by the 24h observed_at window. + + A bump 30h ago is excluded; a bump 2h ago is counted. + Requires a preceding decision in the same session for the JOIN. + """ + conn = _make_db(tmp_path) + now = _now() + + sess_old = "sess-old" + conn.execute( + "INSERT INTO route_decisions (observed_at, kind, session_key, selected_model, selected_provider) " + "VALUES (?, 'route', ?, 'cheap', 'neuralwatt')", + ((now - timedelta(hours=31)).isoformat(), sess_old), + ) + conn.execute( + "INSERT INTO route_decisions (observed_at, kind, session_key, escalation_reason) " + "VALUES (?, 'route', ?, 'tool_error')", + ((now - timedelta(hours=30)).isoformat(), sess_old), + ) + + sess_new = "sess-new" + conn.execute( + "INSERT INTO route_decisions (observed_at, kind, session_key, selected_model, selected_provider) " + "VALUES (?, 'route', ?, 'dear', 'neuralwatt')", + ((now - timedelta(hours=3)).isoformat(), sess_new), + ) + conn.execute( + "INSERT INTO route_decisions (observed_at, kind, session_key, escalation_reason) " + "VALUES (?, 'route', ?, 'tool_error')", + ((now - timedelta(hours=2)).isoformat(), sess_new), + ) + conn.commit() + + results = tool_error_bumps_by_model(conn) + + assert len(results) == 1 + assert results[0]["model"] == "dear" + assert results[0]["bumps"] == 1 + + # --- /health endpoint compatibility ------------------------------------------- - - def test_health_endpoint_returns_scoring_key(tmp_path, monkeypatch): """/health still returns the same SHAPE after moving functions to metrics.""" db_path = tmp_path / "test.db" @@ -2010,9 +2068,7 @@ def test_an_access_gated_row_is_not_counted_routable(tmp_path): """ conn = _make_db(tmp_path) _seed_models(conn) - conn.execute( - "UPDATE models SET access_level = 'canary' WHERE model_id = 'tiny'" - ) + conn.execute("UPDATE models SET access_level = 'canary' WHERE model_id = 'tiny'") conn.commit() coverage = selection_coverage(conn, CFG) @@ -2020,10 +2076,7 @@ def test_an_access_gated_row_is_not_counted_routable(tmp_path): assert coverage["routable_models"] == 2 assert "tiny" not in {r["model_id"] for r in coverage["never_selected"]} # The two figures in one payload must agree. - assert ( - coverage["routable_models"] - == scoring_coverage(conn, CFG)["routable_models"] - ) + assert coverage["routable_models"] == scoring_coverage(conn, CFG)["routable_models"] # ============================================================================= @@ -2100,9 +2153,7 @@ def test_cache_rate_series_counts_only_reported_rows(tmp_path): _seed_cache_rows( conn, n=5, prompt_tokens=1000, cached=None, source="details_no_count" ) - _seed_cache_rows( - conn, n=5, prompt_tokens=1000, cached=None, source="no_details" - ) + _seed_cache_rows(conn, n=5, prompt_tokens=1000, cached=None, source="no_details") series = cache_rate_series(conn, CFG) @@ -2163,10 +2214,12 @@ def test_cache_rate_series_is_bounded_by_the_trailing_window(tmp_path): def test_cache_rate_series_groups_on_provider_and_model(tmp_path): """Two providers serving the same base model are two groups, not one.""" conn = _make_db(tmp_path) - _seed_cache_rows(conn, model_id="dv4", provider="neuralwatt", n=3, - prompt_tokens=1000, cached=900) - _seed_cache_rows(conn, model_id="dv4", provider="openrouter", n=3, - prompt_tokens=1000, cached=400) + _seed_cache_rows( + conn, model_id="dv4", provider="neuralwatt", n=3, prompt_tokens=1000, cached=900 + ) + _seed_cache_rows( + conn, model_id="dv4", provider="openrouter", n=3, prompt_tokens=1000, cached=400 + ) series = cache_rate_series(conn, CFG) @@ -2249,17 +2302,27 @@ def test_cache_rate_outlier_fires_while_the_aggregate_stays_quiet(tmp_path): (provider, model) pair rather than a formatted label. """ conn = _make_db(tmp_path) - _seed_cache_rows(conn, model_id="hot", provider="neuralwatt", n=300, - prompt_tokens=1000, cached=920) - _seed_cache_rows(conn, model_id="cold", provider="openrouter", n=30, - prompt_tokens=1000, cached=400) + _seed_cache_rows( + conn, + model_id="hot", + provider="neuralwatt", + n=300, + prompt_tokens=1000, + cached=920, + ) + _seed_cache_rows( + conn, + model_id="cold", + provider="openrouter", + n=30, + prompt_tokens=1000, + cached=400, + ) series = cache_rate_series(conn, CFG) warnings = cache_rate_warnings(conn, CFG, series) - assert series["cache_rate"] == pytest.approx( - (300 * 920 + 30 * 400) / (330 * 1000) - ) + assert series["cache_rate"] == pytest.approx((300 * 920 + 30 * 400) / (330 * 1000)) assert not [w for w in warnings if w.startswith("cache rate: measured")] outliers = [w for w in warnings if w.startswith("cache rate outlier:")] assert len(outliers) == 1 @@ -2269,10 +2332,22 @@ def test_cache_rate_outlier_fires_while_the_aggregate_stays_quiet(tmp_path): def test_cache_rate_outlier_respects_the_per_group_observation_floor(tmp_path): """A four-request group that looks catastrophic is four requests.""" conn = _make_db(tmp_path) - _seed_cache_rows(conn, model_id="hot", provider="neuralwatt", n=300, - prompt_tokens=1000, cached=920) - _seed_cache_rows(conn, model_id="cold", provider="openrouter", n=4, - prompt_tokens=1000, cached=100) + _seed_cache_rows( + conn, + model_id="hot", + provider="neuralwatt", + n=300, + prompt_tokens=1000, + cached=920, + ) + _seed_cache_rows( + conn, + model_id="cold", + provider="openrouter", + n=4, + prompt_tokens=1000, + cached=100, + ) warnings = cache_rate_warnings(conn, CFG) @@ -2351,10 +2426,12 @@ def _seed_proficiency_depth_rows( def test_proficiency_depth_series_computes_average_depth(tmp_path): """The series aggregates sample depth per category and overall.""" conn = _make_db(tmp_path) - _seed_proficiency_depth_rows(conn, n=3, category="coding_general", - self_eval_samples=10, outcome_samples=5) - _seed_proficiency_depth_rows(conn, n=2, category="debugging", - self_eval_samples=20, outcome_samples=10) + _seed_proficiency_depth_rows( + conn, n=3, category="coding_general", self_eval_samples=10, outcome_samples=5 + ) + _seed_proficiency_depth_rows( + conn, n=2, category="debugging", self_eval_samples=20, outcome_samples=10 + ) series = proficiency_sample_depth_series(conn, CFG) @@ -2373,11 +2450,17 @@ def test_proficiency_depth_series_computes_average_depth(tmp_path): def test_proficiency_depth_series_identifies_thin_rows(tmp_path): """Rows below min_samples are counted as thin.""" conn = _make_db(tmp_path) - _seed_proficiency_depth_rows(conn, n=2, category="coding_general", - self_eval_samples=1, outcome_samples=1) - _seed_proficiency_depth_rows(conn, n=3, category="coding_general", - self_eval_samples=20, outcome_samples=10, - model_id="dear") + _seed_proficiency_depth_rows( + conn, n=2, category="coding_general", self_eval_samples=1, outcome_samples=1 + ) + _seed_proficiency_depth_rows( + conn, + n=3, + category="coding_general", + self_eval_samples=20, + outcome_samples=10, + model_id="dear", + ) series = proficiency_sample_depth_series(conn, CFG) @@ -2388,8 +2471,9 @@ def test_proficiency_depth_series_identifies_thin_rows(tmp_path): def test_proficiency_depth_warning_silent_below_the_observation_floor(tmp_path): """Never warns on a near-empty table (novelty-or-rate).""" conn = _make_db(tmp_path) - _seed_proficiency_depth_rows(conn, n=3, category="coding_general", - self_eval_samples=5, outcome_samples=5) + _seed_proficiency_depth_rows( + conn, n=3, category="coding_general", self_eval_samples=5, outcome_samples=5 + ) warnings = proficiency_sample_depth_warnings(conn, CFG) @@ -2399,8 +2483,9 @@ def test_proficiency_depth_warning_silent_below_the_observation_floor(tmp_path): def test_proficiency_depth_warning_silent_below_the_threshold(tmp_path): """Average sample depth below min_samples does not fire.""" conn = _make_db(tmp_path) - _seed_proficiency_depth_rows(conn, n=15, category="coding_general", - self_eval_samples=5, outcome_samples=5) + _seed_proficiency_depth_rows( + conn, n=15, category="coding_general", self_eval_samples=5, outcome_samples=5 + ) cfg = _cfg_with(proficiency_depth_warn_min_samples=50) warnings = proficiency_sample_depth_warnings(conn, cfg) @@ -2412,13 +2497,13 @@ def test_proficiency_depth_warning_fires_when_depth_exceeds_threshold(tmp_path): """Once average depth passes the configurable threshold, the premise is expired and the warning fires.""" conn = _make_db(tmp_path) - _seed_proficiency_depth_rows(conn, n=20, category="coding_general", - self_eval_samples=15, outcome_samples=10) + _seed_proficiency_depth_rows( + conn, n=20, category="coding_general", self_eval_samples=15, outcome_samples=10 + ) warnings = proficiency_sample_depth_warnings(conn, CFG) - premise = [w for w in warnings - if w.startswith("quality_tolerance premise expired")] + premise = [w for w in warnings if w.startswith("quality_tolerance premise expired")] assert len(premise) >= 1 assert "quality_tolerance" in premise[0] @@ -2426,8 +2511,9 @@ def test_proficiency_depth_warning_fires_when_depth_exceeds_threshold(tmp_path): def test_proficiency_depth_warning_respects_the_observation_floor(tmp_path): """Plenty of rows but all below the floor threshold — silent.""" conn = _make_db(tmp_path) - _seed_proficiency_depth_rows(conn, n=5, category="coding_general", - self_eval_samples=30, outcome_samples=30) + _seed_proficiency_depth_rows( + conn, n=5, category="coding_general", self_eval_samples=30, outcome_samples=30 + ) cfg = _cfg_with(proficiency_depth_warn_min_rows=10) warnings = proficiency_sample_depth_warnings(conn, cfg) @@ -2551,25 +2637,23 @@ def test_cumulative_spend_warning_fires_when_premise_expires(tmp_path): conn = _make_db(tmp_path) _seed_spend_rows(conn, n=15, cost_usd=50.0) - cfg = _cfg_with(cumulative_spend_warn_usd=10.0, - cumulative_spend_warn_min_rows=5) + cfg = _cfg_with(cumulative_spend_warn_usd=10.0, cumulative_spend_warn_min_rows=5) warnings = cumulative_spend_warnings(conn, cfg) - premise = [w for w in warnings - if w.startswith("cost-as-tiebreak premise expired")] + premise = [w for w in warnings if w.startswith("cost-as-tiebreak premise expired")] assert len(premise) >= 1 assert "cumulative spend" in premise[0] assert "$" in premise[0] - def test_scoring_coverage_carries_the_premise_expiry_series(tmp_path): """scoring_coverage includes both new premise-expiry series and warnings.""" conn = _make_db(tmp_path) _seed_models(conn) # Seed enough proficiency depth to trigger the warning - _seed_proficiency_depth_rows(conn, n=20, category="coding_general", - self_eval_samples=15, outcome_samples=10) + _seed_proficiency_depth_rows( + conn, n=20, category="coding_general", self_eval_samples=15, outcome_samples=10 + ) _seed_spend_rows(conn, n=15, cost_usd=50.0) cfg = _cfg_with( @@ -2583,12 +2667,10 @@ def test_scoring_coverage_carries_the_premise_expiry_series(tmp_path): assert "cumulative_spend" in coverage assert coverage["cumulative_spend"]["total_spend_usd"] == pytest.approx(750.0) assert any( - w.startswith("quality_tolerance premise expired") - for w in coverage["warnings"] + w.startswith("quality_tolerance premise expired") for w in coverage["warnings"] ) assert any( - w.startswith("cost-as-tiebreak premise expired") - for w in coverage["warnings"] + w.startswith("cost-as-tiebreak premise expired") for w in coverage["warnings"] ) @@ -2613,7 +2695,8 @@ def _seed_conversation_adoption_rows( "(observed_at, kind, session_key, agent, parent_key) " "VALUES (?, 'chat', ?, 'classifier', NULL)", ( - (now - timedelta(hours=1)).isoformat() if in_window + (now - timedelta(hours=1)).isoformat() + if in_window else (now - timedelta(days=30)).isoformat(), key, ), @@ -2624,7 +2707,8 @@ def _seed_conversation_adoption_rows( "(observed_at, kind, session_key, agent, parent_key) " "VALUES (?, 'chat', ?, 'classifier', NULL)", ( - (now - timedelta(hours=1)).isoformat() if in_window + (now - timedelta(hours=1)).isoformat() + if in_window else (now - timedelta(days=30)).isoformat(), f"fp-{i}", ), @@ -2762,6 +2846,7 @@ def test_ensure_tables_adds_route_decisions_columns_to_old_db(tmp_path, monkeypa # Point dispatcher at this DB and run _ensure_tables import dispatcher as d + original_path = d.cfg.database.path try: d.cfg.database.path = str(db_path) @@ -2777,8 +2862,12 @@ def test_ensure_tables_adds_route_decisions_columns_to_old_db(tmp_path, monkeypa assert "parent_key" in cols, "parent_key column should exist after migration" # Verify local_energy_observations has session_key - local_cols = {row[1] for row in check.execute("PRAGMA table_info(local_energy_observations)")} - assert "session_key" in local_cols, "session_key column should exist after migration" + local_cols = { + row[1] for row in check.execute("PRAGMA table_info(local_energy_observations)") + } + assert "session_key" in local_cols, ( + "session_key column should exist after migration" + ) # Also test that recent_decisions runs cleanly on the migrated DB rows = recent_decisions(check) @@ -2791,6 +2880,7 @@ def test_log_local_energy_persists_session_key(tmp_path): conn = sqlite3.connect(str(tmp_path / "le-test.db")) conn.row_factory = sqlite3.Row import local_energy + local_energy.ensure_local_energy_table(conn) local_energy.log_local_energy( -- 2.49.1 From 8e8e6120230980c138803152f2f6f1e0b6911825 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 18 Oct 2026 03:45:29 -0400 Subject: [PATCH 11/19] test: restore tests/test_metrics.py and move the window test 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. --- tests/test_metrics.py | 262 +++++++++------------------- tests/test_tool_error_escalation.py | 63 +++++++ 2 files changed, 149 insertions(+), 176 deletions(-) diff --git a/tests/test_metrics.py b/tests/test_metrics.py index f0322cd..6fe0f30 100644 --- a/tests/test_metrics.py +++ b/tests/test_metrics.py @@ -53,7 +53,6 @@ from metrics import ( scoring_coverage, selection_coverage, selection_coverage_warnings, - tool_error_bumps_by_model, top_proficiency, unroutable_models, verdict_mix, @@ -128,12 +127,12 @@ def _seed_proficiency(conn: sqlite3.Connection) -> None: def _seed_energy(conn: sqlite3.Connection) -> None: now = _now() recent_rows = [ - ("cheap", 5.0e-05, 100, 0.25), # 2 days ago - ("cheap", 3.0e-05, 200, 0.50), # 2 days ago - ("dear", 1.0e-04, 150, 0.75), # 5 days ago - ("tiny", 1.0e-05, 50, 1.00), # 10 days ago + ("cheap", 5.0e-05, 100, 0.25), # 2 days ago + ("cheap", 3.0e-05, 200, 0.50), # 2 days ago + ("dear", 1.0e-04, 150, 0.75), # 5 days ago + ("tiny", 1.0e-05, 50, 1.00), # 10 days ago ] - for model_id, kwh, tokens, attr in recent_rows: + for (model_id, kwh, tokens, attr) in recent_rows: conn.execute( """ INSERT INTO energy_observations ( @@ -485,12 +484,8 @@ def test_quota_accounts_interleaved_providers_independent(tmp_path): conn.commit() result = quota_accounts(conn, cfg) by_provider = {a["provider"]: a for a in result["accounts"]} - assert by_provider["neuralwatt"]["burn"]["burn_rate_usd_per_hour"] == pytest.approx( - 1.0 - ) - assert by_provider["openrouter"]["burn"]["burn_rate_usd_per_hour"] == pytest.approx( - 4.0 - ) + assert by_provider["neuralwatt"]["burn"]["burn_rate_usd_per_hour"] == pytest.approx(1.0) + assert by_provider["openrouter"]["burn"]["burn_rate_usd_per_hour"] == pytest.approx(4.0) assert by_provider["neuralwatt"]["shape"] == "metered_plan" assert by_provider["openrouter"]["shape"] == "prepaid_credit" @@ -589,9 +584,7 @@ def test_local_energy_summary_reset_date_is_billing_period_start(tmp_path): if today.month == 1: expected_period_start = date(today.year - 1, 12, reset_day).isoformat() else: - expected_period_start = date( - today.year, today.month - 1, reset_day - ).isoformat() + expected_period_start = date(today.year, today.month - 1, reset_day).isoformat() expected_rolling_start = (today - timedelta(days=30)).isoformat() result = local_energy_summary(conn, cfg) @@ -624,9 +617,7 @@ def test_pinch_summary_reset_date_is_billing_period_start(tmp_path): if today.month == 1: expected_period_start = date(today.year - 1, 12, reset_day).isoformat() else: - expected_period_start = date( - today.year, today.month - 1, reset_day - ).isoformat() + expected_period_start = date(today.year, today.month - 1, reset_day).isoformat() expected_rolling_start = (today - timedelta(days=30)).isoformat() result = pinch_summary(conn, cfg) @@ -986,7 +977,8 @@ def test_capability_demand_warning_incident_reproduction(tmp_path): conn, tier=1, reason=( - "context >= 242486 tokens; vision-capable model (request carries image(s))" + "context >= 242486 tokens; " + "vision-capable model (request carries image(s))" ), observed_at=ts, tokens=200000, @@ -1067,7 +1059,8 @@ def test_capability_json_mode_demand_warning(tmp_path): conn, tier=1, reason=( - "context >= 242486 tokens; json-mode-capable model (json_mode requested)" + "context >= 242486 tokens; json-mode-capable model " + "(json_mode requested)" ), observed_at=_now().isoformat(), tokens=200000, @@ -1238,14 +1231,10 @@ def test_rejection_warnings_novel_group_at_incident_volume_fires(tmp_path): _seed_models(conn) ts = _now().isoformat() for reason in ( - ( - "tier >= 1; context >= 242486 tokens; interactive; " - "vision-capable model (request carries image(s))" - ), - ( - "tier >= 1; context >= 195000 tokens; interactive; " - "vision-capable model (request carries image(s))" - ), + "tier >= 1; context >= 242486 tokens; interactive; " + "vision-capable model (request carries image(s))", + "tier >= 1; context >= 195000 tokens; interactive; " + "vision-capable model (request carries image(s))", ): _insert_rejected_decision(conn, tier=1, reason=reason, observed_at=ts) @@ -1541,7 +1530,7 @@ def test_per_model_aggregates_correctly(tmp_path): ("cheap", 0.002, 3.0e-05, 1.2e-03, 200, 0.50), ("dear", 0.010, 1.0e-04, 5.0e-03, 150, 0.75), ] - for model_id, cost, kwh, carbon, tokens, attr in rows: + for (model_id, cost, kwh, carbon, tokens, attr) in rows: conn.execute( "INSERT INTO energy_observations " "(model_id, provider, cost_usd, energy_kwh, carbon_g_co2eq, " @@ -1634,9 +1623,9 @@ def test_top_proficiency_ordered_correctly(tmp_path): results = top_proficiency(conn, "coding_general") assert len(results) == 3 - assert results[0]["model_id"] == "dear" # 0.95 - assert results[1]["model_id"] == "cheap" # 0.90 - assert results[2]["model_id"] == "tiny" # 0.70 + assert results[0]["model_id"] == "dear" # 0.95 + assert results[1]["model_id"] == "cheap" # 0.90 + assert results[2]["model_id"] == "tiny" # 0.70 def test_top_proficiency_filter_by_category(tmp_path): @@ -1785,20 +1774,12 @@ def test_pinch_summary_aggregates_correctly(tmp_path, monkeypatch): _seed_pinch_models(conn) # Two pruned cheap rows: saved tokens 50 and 30. - _insert_pinch_decision( - conn, model="cheap", provider="neuralwatt", orig=100, final=50 - ) - _insert_pinch_decision( - conn, model="cheap", provider="neuralwatt", orig=80, final=50 - ) + _insert_pinch_decision(conn, model="cheap", provider="neuralwatt", orig=100, final=50) + _insert_pinch_decision(conn, model="cheap", provider="neuralwatt", orig=80, final=50) # One non-pruned cheap row (final == orig). - _insert_pinch_decision( - conn, model="cheap", provider="neuralwatt", orig=60, final=60 - ) + _insert_pinch_decision(conn, model="cheap", provider="neuralwatt", orig=60, final=60) # One pruned dear row with NULL cost_per_1m_prompt_cached -> falls back to prompt price. - _insert_pinch_decision( - conn, model="dear", provider="neuralwatt", orig=200, final=100 - ) + _insert_pinch_decision(conn, model="dear", provider="neuralwatt", orig=200, final=100) # One rejection row with NULL selected_model -> counted in share/tokens but excluded from dollars. _insert_pinch_decision(conn, model=None, provider=None, orig=1000, final=500) @@ -1843,48 +1824,9 @@ def test_pinch_summary_disabled_returns_none(tmp_path, monkeypatch): assert pinch_summary(conn, cfg) is None -def test_tool_error_bumps_window_filtering(tmp_path): - """Bumps are correctly filtered by the 24h observed_at window. - - A bump 30h ago is excluded; a bump 2h ago is counted. - Requires a preceding decision in the same session for the JOIN. - """ - conn = _make_db(tmp_path) - now = _now() - - sess_old = "sess-old" - conn.execute( - "INSERT INTO route_decisions (observed_at, kind, session_key, selected_model, selected_provider) " - "VALUES (?, 'route', ?, 'cheap', 'neuralwatt')", - ((now - timedelta(hours=31)).isoformat(), sess_old), - ) - conn.execute( - "INSERT INTO route_decisions (observed_at, kind, session_key, escalation_reason) " - "VALUES (?, 'route', ?, 'tool_error')", - ((now - timedelta(hours=30)).isoformat(), sess_old), - ) - - sess_new = "sess-new" - conn.execute( - "INSERT INTO route_decisions (observed_at, kind, session_key, selected_model, selected_provider) " - "VALUES (?, 'route', ?, 'dear', 'neuralwatt')", - ((now - timedelta(hours=3)).isoformat(), sess_new), - ) - conn.execute( - "INSERT INTO route_decisions (observed_at, kind, session_key, escalation_reason) " - "VALUES (?, 'route', ?, 'tool_error')", - ((now - timedelta(hours=2)).isoformat(), sess_new), - ) - conn.commit() - - results = tool_error_bumps_by_model(conn) - - assert len(results) == 1 - assert results[0]["model"] == "dear" - assert results[0]["bumps"] == 1 - - # --- /health endpoint compatibility ------------------------------------------- + + def test_health_endpoint_returns_scoring_key(tmp_path, monkeypatch): """/health still returns the same SHAPE after moving functions to metrics.""" db_path = tmp_path / "test.db" @@ -2068,7 +2010,9 @@ def test_an_access_gated_row_is_not_counted_routable(tmp_path): """ conn = _make_db(tmp_path) _seed_models(conn) - conn.execute("UPDATE models SET access_level = 'canary' WHERE model_id = 'tiny'") + conn.execute( + "UPDATE models SET access_level = 'canary' WHERE model_id = 'tiny'" + ) conn.commit() coverage = selection_coverage(conn, CFG) @@ -2076,7 +2020,10 @@ def test_an_access_gated_row_is_not_counted_routable(tmp_path): assert coverage["routable_models"] == 2 assert "tiny" not in {r["model_id"] for r in coverage["never_selected"]} # The two figures in one payload must agree. - assert coverage["routable_models"] == scoring_coverage(conn, CFG)["routable_models"] + assert ( + coverage["routable_models"] + == scoring_coverage(conn, CFG)["routable_models"] + ) # ============================================================================= @@ -2153,7 +2100,9 @@ def test_cache_rate_series_counts_only_reported_rows(tmp_path): _seed_cache_rows( conn, n=5, prompt_tokens=1000, cached=None, source="details_no_count" ) - _seed_cache_rows(conn, n=5, prompt_tokens=1000, cached=None, source="no_details") + _seed_cache_rows( + conn, n=5, prompt_tokens=1000, cached=None, source="no_details" + ) series = cache_rate_series(conn, CFG) @@ -2214,12 +2163,10 @@ def test_cache_rate_series_is_bounded_by_the_trailing_window(tmp_path): def test_cache_rate_series_groups_on_provider_and_model(tmp_path): """Two providers serving the same base model are two groups, not one.""" conn = _make_db(tmp_path) - _seed_cache_rows( - conn, model_id="dv4", provider="neuralwatt", n=3, prompt_tokens=1000, cached=900 - ) - _seed_cache_rows( - conn, model_id="dv4", provider="openrouter", n=3, prompt_tokens=1000, cached=400 - ) + _seed_cache_rows(conn, model_id="dv4", provider="neuralwatt", n=3, + prompt_tokens=1000, cached=900) + _seed_cache_rows(conn, model_id="dv4", provider="openrouter", n=3, + prompt_tokens=1000, cached=400) series = cache_rate_series(conn, CFG) @@ -2302,27 +2249,17 @@ def test_cache_rate_outlier_fires_while_the_aggregate_stays_quiet(tmp_path): (provider, model) pair rather than a formatted label. """ conn = _make_db(tmp_path) - _seed_cache_rows( - conn, - model_id="hot", - provider="neuralwatt", - n=300, - prompt_tokens=1000, - cached=920, - ) - _seed_cache_rows( - conn, - model_id="cold", - provider="openrouter", - n=30, - prompt_tokens=1000, - cached=400, - ) + _seed_cache_rows(conn, model_id="hot", provider="neuralwatt", n=300, + prompt_tokens=1000, cached=920) + _seed_cache_rows(conn, model_id="cold", provider="openrouter", n=30, + prompt_tokens=1000, cached=400) series = cache_rate_series(conn, CFG) warnings = cache_rate_warnings(conn, CFG, series) - assert series["cache_rate"] == pytest.approx((300 * 920 + 30 * 400) / (330 * 1000)) + assert series["cache_rate"] == pytest.approx( + (300 * 920 + 30 * 400) / (330 * 1000) + ) assert not [w for w in warnings if w.startswith("cache rate: measured")] outliers = [w for w in warnings if w.startswith("cache rate outlier:")] assert len(outliers) == 1 @@ -2332,22 +2269,10 @@ def test_cache_rate_outlier_fires_while_the_aggregate_stays_quiet(tmp_path): def test_cache_rate_outlier_respects_the_per_group_observation_floor(tmp_path): """A four-request group that looks catastrophic is four requests.""" conn = _make_db(tmp_path) - _seed_cache_rows( - conn, - model_id="hot", - provider="neuralwatt", - n=300, - prompt_tokens=1000, - cached=920, - ) - _seed_cache_rows( - conn, - model_id="cold", - provider="openrouter", - n=4, - prompt_tokens=1000, - cached=100, - ) + _seed_cache_rows(conn, model_id="hot", provider="neuralwatt", n=300, + prompt_tokens=1000, cached=920) + _seed_cache_rows(conn, model_id="cold", provider="openrouter", n=4, + prompt_tokens=1000, cached=100) warnings = cache_rate_warnings(conn, CFG) @@ -2426,12 +2351,10 @@ def _seed_proficiency_depth_rows( def test_proficiency_depth_series_computes_average_depth(tmp_path): """The series aggregates sample depth per category and overall.""" conn = _make_db(tmp_path) - _seed_proficiency_depth_rows( - conn, n=3, category="coding_general", self_eval_samples=10, outcome_samples=5 - ) - _seed_proficiency_depth_rows( - conn, n=2, category="debugging", self_eval_samples=20, outcome_samples=10 - ) + _seed_proficiency_depth_rows(conn, n=3, category="coding_general", + self_eval_samples=10, outcome_samples=5) + _seed_proficiency_depth_rows(conn, n=2, category="debugging", + self_eval_samples=20, outcome_samples=10) series = proficiency_sample_depth_series(conn, CFG) @@ -2450,17 +2373,11 @@ def test_proficiency_depth_series_computes_average_depth(tmp_path): def test_proficiency_depth_series_identifies_thin_rows(tmp_path): """Rows below min_samples are counted as thin.""" conn = _make_db(tmp_path) - _seed_proficiency_depth_rows( - conn, n=2, category="coding_general", self_eval_samples=1, outcome_samples=1 - ) - _seed_proficiency_depth_rows( - conn, - n=3, - category="coding_general", - self_eval_samples=20, - outcome_samples=10, - model_id="dear", - ) + _seed_proficiency_depth_rows(conn, n=2, category="coding_general", + self_eval_samples=1, outcome_samples=1) + _seed_proficiency_depth_rows(conn, n=3, category="coding_general", + self_eval_samples=20, outcome_samples=10, + model_id="dear") series = proficiency_sample_depth_series(conn, CFG) @@ -2471,9 +2388,8 @@ def test_proficiency_depth_series_identifies_thin_rows(tmp_path): def test_proficiency_depth_warning_silent_below_the_observation_floor(tmp_path): """Never warns on a near-empty table (novelty-or-rate).""" conn = _make_db(tmp_path) - _seed_proficiency_depth_rows( - conn, n=3, category="coding_general", self_eval_samples=5, outcome_samples=5 - ) + _seed_proficiency_depth_rows(conn, n=3, category="coding_general", + self_eval_samples=5, outcome_samples=5) warnings = proficiency_sample_depth_warnings(conn, CFG) @@ -2483,9 +2399,8 @@ def test_proficiency_depth_warning_silent_below_the_observation_floor(tmp_path): def test_proficiency_depth_warning_silent_below_the_threshold(tmp_path): """Average sample depth below min_samples does not fire.""" conn = _make_db(tmp_path) - _seed_proficiency_depth_rows( - conn, n=15, category="coding_general", self_eval_samples=5, outcome_samples=5 - ) + _seed_proficiency_depth_rows(conn, n=15, category="coding_general", + self_eval_samples=5, outcome_samples=5) cfg = _cfg_with(proficiency_depth_warn_min_samples=50) warnings = proficiency_sample_depth_warnings(conn, cfg) @@ -2497,13 +2412,13 @@ def test_proficiency_depth_warning_fires_when_depth_exceeds_threshold(tmp_path): """Once average depth passes the configurable threshold, the premise is expired and the warning fires.""" conn = _make_db(tmp_path) - _seed_proficiency_depth_rows( - conn, n=20, category="coding_general", self_eval_samples=15, outcome_samples=10 - ) + _seed_proficiency_depth_rows(conn, n=20, category="coding_general", + self_eval_samples=15, outcome_samples=10) warnings = proficiency_sample_depth_warnings(conn, CFG) - premise = [w for w in warnings if w.startswith("quality_tolerance premise expired")] + premise = [w for w in warnings + if w.startswith("quality_tolerance premise expired")] assert len(premise) >= 1 assert "quality_tolerance" in premise[0] @@ -2511,9 +2426,8 @@ def test_proficiency_depth_warning_fires_when_depth_exceeds_threshold(tmp_path): def test_proficiency_depth_warning_respects_the_observation_floor(tmp_path): """Plenty of rows but all below the floor threshold — silent.""" conn = _make_db(tmp_path) - _seed_proficiency_depth_rows( - conn, n=5, category="coding_general", self_eval_samples=30, outcome_samples=30 - ) + _seed_proficiency_depth_rows(conn, n=5, category="coding_general", + self_eval_samples=30, outcome_samples=30) cfg = _cfg_with(proficiency_depth_warn_min_rows=10) warnings = proficiency_sample_depth_warnings(conn, cfg) @@ -2637,23 +2551,25 @@ def test_cumulative_spend_warning_fires_when_premise_expires(tmp_path): conn = _make_db(tmp_path) _seed_spend_rows(conn, n=15, cost_usd=50.0) - cfg = _cfg_with(cumulative_spend_warn_usd=10.0, cumulative_spend_warn_min_rows=5) + cfg = _cfg_with(cumulative_spend_warn_usd=10.0, + cumulative_spend_warn_min_rows=5) warnings = cumulative_spend_warnings(conn, cfg) - premise = [w for w in warnings if w.startswith("cost-as-tiebreak premise expired")] + premise = [w for w in warnings + if w.startswith("cost-as-tiebreak premise expired")] assert len(premise) >= 1 assert "cumulative spend" in premise[0] assert "$" in premise[0] + def test_scoring_coverage_carries_the_premise_expiry_series(tmp_path): """scoring_coverage includes both new premise-expiry series and warnings.""" conn = _make_db(tmp_path) _seed_models(conn) # Seed enough proficiency depth to trigger the warning - _seed_proficiency_depth_rows( - conn, n=20, category="coding_general", self_eval_samples=15, outcome_samples=10 - ) + _seed_proficiency_depth_rows(conn, n=20, category="coding_general", + self_eval_samples=15, outcome_samples=10) _seed_spend_rows(conn, n=15, cost_usd=50.0) cfg = _cfg_with( @@ -2667,10 +2583,12 @@ def test_scoring_coverage_carries_the_premise_expiry_series(tmp_path): assert "cumulative_spend" in coverage assert coverage["cumulative_spend"]["total_spend_usd"] == pytest.approx(750.0) assert any( - w.startswith("quality_tolerance premise expired") for w in coverage["warnings"] + w.startswith("quality_tolerance premise expired") + for w in coverage["warnings"] ) assert any( - w.startswith("cost-as-tiebreak premise expired") for w in coverage["warnings"] + w.startswith("cost-as-tiebreak premise expired") + for w in coverage["warnings"] ) @@ -2695,8 +2613,7 @@ def _seed_conversation_adoption_rows( "(observed_at, kind, session_key, agent, parent_key) " "VALUES (?, 'chat', ?, 'classifier', NULL)", ( - (now - timedelta(hours=1)).isoformat() - if in_window + (now - timedelta(hours=1)).isoformat() if in_window else (now - timedelta(days=30)).isoformat(), key, ), @@ -2707,8 +2624,7 @@ def _seed_conversation_adoption_rows( "(observed_at, kind, session_key, agent, parent_key) " "VALUES (?, 'chat', ?, 'classifier', NULL)", ( - (now - timedelta(hours=1)).isoformat() - if in_window + (now - timedelta(hours=1)).isoformat() if in_window else (now - timedelta(days=30)).isoformat(), f"fp-{i}", ), @@ -2846,7 +2762,6 @@ def test_ensure_tables_adds_route_decisions_columns_to_old_db(tmp_path, monkeypa # Point dispatcher at this DB and run _ensure_tables import dispatcher as d - original_path = d.cfg.database.path try: d.cfg.database.path = str(db_path) @@ -2862,12 +2777,8 @@ def test_ensure_tables_adds_route_decisions_columns_to_old_db(tmp_path, monkeypa assert "parent_key" in cols, "parent_key column should exist after migration" # Verify local_energy_observations has session_key - local_cols = { - row[1] for row in check.execute("PRAGMA table_info(local_energy_observations)") - } - assert "session_key" in local_cols, ( - "session_key column should exist after migration" - ) + local_cols = {row[1] for row in check.execute("PRAGMA table_info(local_energy_observations)")} + assert "session_key" in local_cols, "session_key column should exist after migration" # Also test that recent_decisions runs cleanly on the migrated DB rows = recent_decisions(check) @@ -2880,7 +2791,6 @@ def test_log_local_energy_persists_session_key(tmp_path): conn = sqlite3.connect(str(tmp_path / "le-test.db")) conn.row_factory = sqlite3.Row import local_energy - local_energy.ensure_local_energy_table(conn) local_energy.log_local_energy( diff --git a/tests/test_tool_error_escalation.py b/tests/test_tool_error_escalation.py index fc76d3b..d006ca4 100644 --- a/tests/test_tool_error_escalation.py +++ b/tests/test_tool_error_escalation.py @@ -532,3 +532,66 @@ def test_bump_only_reoute_keeps_larger_estimate(client, saved_cfg, monkeypatch): 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.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) + 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"] + -- 2.49.1 From d9f57f806cd2028ec394a594971185655d29b09f Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 18 Oct 2026 03:46:12 -0400 Subject: [PATCH 12/19] test: tool_error_bumps_by_model TTL test in escalation suite 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). --- tests/test_tool_error_escalation.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/test_tool_error_escalation.py b/tests/test_tool_error_escalation.py index d006ca4..9374849 100644 --- a/tests/test_tool_error_escalation.py +++ b/tests/test_tool_error_escalation.py @@ -543,6 +543,7 @@ def test_tool_error_bumps_by_model_ttl(client, tmp_path, monkeypatch): 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) @@ -583,6 +584,7 @@ def test_tool_error_bumps_by_model_ttl(client, tmp_path, monkeypatch): 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() -- 2.49.1 From 7ae1affadc96f269484e4bb66b07d339fc72e56c Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 18 Oct 2026 03:49:06 -0400 Subject: [PATCH 13/19] fix: tool-error bump falls back when the bumped tier has no candidates 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. --- src/dispatcher.py | 80 ++++++++++++++++--------- tests/test_tool_error_escalation.py | 93 +++++++++++++++++++++++++++++ 2 files changed, 146 insertions(+), 27 deletions(-) diff --git a/src/dispatcher.py b/src/dispatcher.py index 049fec0..decb144 100644 --- a/src/dispatcher.py +++ b/src/dispatcher.py @@ -4958,23 +4958,36 @@ def chat_completions(body: dict[str, Any], background: BackgroundTasks, request: bumped_tier, bump_reason = _apply_tool_error_bump( cached.task_tier, messages, 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=bumped_tier, - required_context_tokens=measured, - ), - profile=profile_name, - profile_obj=profile_obj, - ) + 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 @@ -5013,12 +5026,10 @@ def chat_completions(body: dict[str, Any], background: BackgroundTasks, request: bump_tier, bump_reason = _apply_tool_error_bump( decision.classification.task_tier, messages, measured ) - if ( - measured > decision.classification.required_context_tokens - or bump_reason is not None - ): - ctx_src = "measured" - decision = route( + 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 + @@ -5029,10 +5040,7 @@ 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=( - bump_tier if bump_reason is not None - else decision.classification.task_tier - ), + task_tier=tier, required_context_tokens=max( measured, decision.classification.required_context_tokens, @@ -5041,6 +5049,24 @@ def chat_completions(body: dict[str, Any], background: BackgroundTasks, request: 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 diff --git a/tests/test_tool_error_escalation.py b/tests/test_tool_error_escalation.py index 9374849..745b193 100644 --- a/tests/test_tool_error_escalation.py +++ b/tests/test_tool_error_escalation.py @@ -597,3 +597,96 @@ def test_tool_error_bumps_by_model_ttl(client, tmp_path, monkeypatch): 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]}" + -- 2.49.1 From 88d685e2adc4bd2ee414eebd2488acc943544bfd Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 18 Oct 2026 03:50:57 -0400 Subject: [PATCH 14/19] fix: restore classifier_reject comment in schema.sql 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. --- config/schema.sql | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/config/schema.sql b/config/schema.sql index d873852..3aa5f86 100644 --- a/config/schema.sql +++ b/config/schema.sql @@ -359,13 +359,13 @@ 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, - -- 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. + 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. -- 2.49.1 From cd66bc5b9a8b7744ed6303ee6ea97a32a540847e Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 18 Oct 2026 03:54:59 -0400 Subject: [PATCH 15/19] style: restore indentation in escalation_reason changes (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. --- admin/frontend/controls.html | 10 +++++----- admin/frontend/decisions.html | 6 +++--- src/dispatcher.py | 10 +++++----- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/admin/frontend/controls.html b/admin/frontend/controls.html index fc7262e..a99bb17 100644 --- a/admin/frontend/controls.html +++ b/admin/frontend/controls.html @@ -868,11 +868,11 @@ const NUMBER_BOUNDS = { // still caches and the classifier-failure cascade still replays the entry. 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 }, + 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 50bfdc6..23d9775 100644 --- a/admin/frontend/decisions.html +++ b/admin/frontend/decisions.html @@ -591,9 +591,9 @@ function matchesFilters(d, f) { if (f.tier && String(d.task_tier || '') !== f.tier) return false; if (f.search) { const haystack = [ - d.selected_model, d.selected_provider, d.session_key, - d.rejected_reason, d.escalation_reason, d.task_category, d.kind, d.profile, - ].filter(Boolean).join(' ').toLowerCase(); + d.selected_model, d.selected_provider, d.session_key, + d.rejected_reason, d.escalation_reason, d.task_category, d.kind, d.profile, + ].filter(Boolean).join(' ').toLowerCase(); if (!haystack.includes(f.search)) return false; } return true; diff --git a/src/dispatcher.py b/src/dispatcher.py index decb144..7eba923 100644 --- a/src/dispatcher.py +++ b/src/dispatcher.py @@ -2597,11 +2597,11 @@ def persist_route_decision( flex_preference, flex_swapped, flex_forced, exploration, 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, - escalation_reason - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - """, + prefix_prev_message_count, agent, parent_key, + classifier_confidence, classifier_coverage, classifier_reject, + escalation_reason + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, ( observed_at, decision_kind, -- 2.49.1 From c2aa1b4428456652b18c3fca70c05e8188deb420 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 18 Oct 2026 04:05:08 -0400 Subject: [PATCH 16/19] fix: remove extra ? from INSERT placeholder count (was 39, should be 38)\n\ntest: revert tests/test_conversation_wiring.py to origin/main\n\nThe last commit modified the _clear_prefix_probe_state fixture by\nmoving prefix_probe._store.clear() from before to after the yield.\nRevert to origin/main's version as this is outside the plan's file\nlist and modifies an existing fixture. Full test suite (2776 tests)\npasses after this revert. --- src/dispatcher.py | 2 +- tests/test_conversation_wiring.py | 13 ++++++------- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/dispatcher.py b/src/dispatcher.py index 7eba923..26124ea 100644 --- a/src/dispatcher.py +++ b/src/dispatcher.py @@ -2600,7 +2600,7 @@ def persist_route_decision( prefix_prev_message_count, agent, parent_key, classifier_confidence, classifier_coverage, classifier_reject, escalation_reason - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( observed_at, diff --git a/tests/test_conversation_wiring.py b/tests/test_conversation_wiring.py index 45d5072..4644504 100644 --- a/tests/test_conversation_wiring.py +++ b/tests/test_conversation_wiring.py @@ -31,14 +31,13 @@ DEAR = "dear-model" @pytest.fixture(autouse=True, scope="module") def _clear_prefix_probe_state(): - """Clear ``prefix_probe._store`` before and after our module so no - test inherits stale fingerprints from a previous pytest run. - The probe stores per-session fingerprints in process memory -- a POST - with the snapshot's payload after another module would otherwise see - a prior turn and report non-NULL prefix divergence.""" - import prefix_probe - prefix_probe._store.clear() + """Clean up ``prefix_probe._store`` after our module so the snapshot + test (runs alphabetically after us) sees a clean prefix-probe cache. + The probe stores per-session fingerprints in process-memory and a + POST with the snapshot's payload here would otherwise make a later + test see a prior turn and report non-NULL prefix divergence.""" yield + import prefix_probe prefix_probe._store.clear() _SYS = "You work in /home/user/proj and follow the design docs." -- 2.49.1 From da4b4aee3ef5dbb90ac379375bac36dcca613450 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 18 Oct 2026 04:06:13 -0400 Subject: [PATCH 17/19] test: pin the never-lowers guard 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. --- tests/test_tool_error_escalation.py | 66 +++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/tests/test_tool_error_escalation.py b/tests/test_tool_error_escalation.py index 745b193..3122e71 100644 --- a/tests/test_tool_error_escalation.py +++ b/tests/test_tool_error_escalation.py @@ -690,3 +690,69 @@ def test_bump_fallback_cached_branch(client, saved_cfg): 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]}" + -- 2.49.1 From fde16483930a0e41be78e0daf0476a1e7314c986 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Tue, 20 Oct 2026 17:51:07 -0400 Subject: [PATCH 18/19] revert: a6656d3 due to scope creep and missing tests --- src/metrics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/metrics.py b/src/metrics.py index 05c6b66..66b5646 100644 --- a/src/metrics.py +++ b/src/metrics.py @@ -1196,7 +1196,7 @@ def tool_error_bumps_by_model(conn: sqlite3.Connection) -> List[dict]: 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 julianday(d.observed_at) >= julianday('now', '-24 hours') AND prev.selected_model IS NOT NULL GROUP BY prev.selected_model ORDER BY bumps DESC, prev.selected_model -- 2.49.1 From e4af4cad2958657d6f995b7b8bac849d8d6111e5 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Tue, 20 Oct 2026 17:51:21 -0400 Subject: [PATCH 19/19] restore: the item B observed_at index fix reverted in error --- src/metrics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/metrics.py b/src/metrics.py index 66b5646..05c6b66 100644 --- a/src/metrics.py +++ b/src/metrics.py @@ -1196,7 +1196,7 @@ def tool_error_bumps_by_model(conn: sqlite3.Connection) -> List[dict]: 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 julianday(d.observed_at) >= julianday('now', '-24 hours') + 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 -- 2.49.1