"""Wiring tests for tool-error tier escalation in the dispatcher. TestClient-driven: temp SQLite seeded from schema.sql, classify stubbed, provider stubbed at _provider_client boundary. Follows the pattern from tests/test_blocked_routing.py (no real network). """ from __future__ import annotations import json import sqlite3 from pathlib import Path import pytest from pydantic import ValidationError from starlette.testclient import TestClient import dispatcher from config import ToolErrorBumpConfig from dispatcher import Classification, app ROOT = Path(__file__).resolve().parent.parent SCHEMA_SQL = (ROOT / "config" / "schema.sql").read_text() # --- verbatim error strings --- ERR_OLDSTRING = ( "Could not find oldString in the file. It must match exactly, " "including whitespace, indentation, and line endings." ) ERR_ABORT = "Tool execution aborted" # --- message builders --- def _assistant_call(call_id, name): return { "role": "assistant", "tool_calls": [ { "id": call_id, "type": "function", "function": {"name": name, "arguments": "{}"}, } ], } def _tool_result(call_id, content): return { "role": "tool", "tool_call_id": call_id, "content": content, } def _messages_with_errors(n): """n consecutive edit-class errors at the tail.""" msgs = [{"role": "user", "content": "Refactor this file"}] for i in range(n): cid = f"call{i}" msgs.append(_assistant_call(cid, "edit")) msgs.append(_tool_result(cid, ERR_OLDSTRING)) msgs.append({"role": "user", "content": "Try again"}) return msgs def _messages_abort(n): """n abort results (should NOT count as errors).""" msgs = [{"role": "user", "content": "Refactor this file"}] for i in range(n): cid = f"call{i}" msgs.append(_assistant_call(cid, "edit")) msgs.append(_tool_result(cid, ERR_ABORT)) msgs.append({"role": "user", "content": "Try again"}) return msgs _FAKE_COMPLETION_BODY = { "id": "chatcmpl-test", "object": "chat.completion", "created": 1000000000, "model": "tier1-model", "choices": [ { "index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": "Done."}, } ], "usage": {"prompt_tokens": 50, "completion_tokens": 10}, } class _FakeResponse: status_code = 200 reason = "OK" text = json.dumps(_FAKE_COMPLETION_BODY) @staticmethod def json(): return _FAKE_COMPLETION_BODY def __bool__(self): return True # --- fixtures --- @pytest.fixture def client(tmp_path, monkeypatch): """Fresh DB + classify stub + provider stub.""" db_path = tmp_path / "te.db" conn = sqlite3.connect(db_path) conn.executescript(SCHEMA_SQL) models = [ ("tier1-model", 1), ("tier2-model", 2), ("tier3-model", 3), ] for model_id, tier in models: conn.execute( """ INSERT INTO models ( model_id, provider, base_model_id, tier, context_window, effective_context_window, max_output_tokens, cost_per_1m_prompt, cost_per_1m_completion, supports_vision, supports_json_mode, latency_class, reasoning_mode, context_variant, access_level, availability, last_updated ) VALUES (?, 'neuralwatt', ?, ?, 262128, 192500, 16384, 1.0, 2.0, 0, 1, 'standard', 'default', 'full', 'public', 'active', '2026-08-22T00:00:00+00:00') """, (model_id, model_id, tier), ) # Proficiency row required for candidate selection. conn.execute( """ INSERT INTO proficiency (model_id, provider, category, blended_score, source, last_updated, outcome_samples) VALUES (?, 'neuralwatt', 'coding_general', 0.5, 'leaderboard', '2026-08-22T00:00:00+00:00', 50) """, (model_id,), ) conn.commit() conn.close() monkeypatch.setattr(dispatcher.cfg.database, "path", str(db_path)) monkeypatch.setattr(dispatcher.cfg.verification, "local_llm_enabled", False) monkeypatch.setattr(dispatcher.cfg.local_vision, "enabled", False) monkeypatch.setattr(dispatcher.cfg.local_compute, "enabled", False) # Classifier always returns tier 1 (the pre-bump tier). monkeypatch.setattr( dispatcher, "classify", lambda task, context: Classification( task_category="coding_general", task_tier=1, required_context_tokens=0, confidence=0.9, ), ) monkeypatch.setattr(dispatcher.requests, "post", lambda *a, **kw: _FakeResponse()) monkeypatch.setattr(dispatcher.requests, "post", lambda *a, **kw: _FakeResponse()) return TestClient(app) @pytest.fixture def saved_cfg(): """Save and restore cfg fields around each test.""" import session_cache saved = { "escalation_enabled": dispatcher.cfg.escalation.enabled, "bump_config": { "enabled": dispatcher.cfg.escalation.tool_error_bump.enabled, "threshold": dispatcher.cfg.escalation.tool_error_bump.threshold, "max_bump": dispatcher.cfg.escalation.tool_error_bump.max_bump, }, "max_rebill": dispatcher.cfg.iteration.max_rebill_prompt_tokens, "cache_enabled": dispatcher.cfg.session_cache.enabled, "max_tier": dispatcher.cfg.escalation.max_tier, } dispatcher.cfg.session_cache.enabled = False yield dispatcher.cfg.escalation.enabled = saved["escalation_enabled"] dispatcher.cfg.escalation.tool_error_bump.enabled = saved["bump_config"]["enabled"] dispatcher.cfg.escalation.tool_error_bump.threshold = saved["bump_config"]["threshold"] dispatcher.cfg.escalation.tool_error_bump.max_bump = saved["bump_config"]["max_bump"] dispatcher.cfg.iteration.max_rebill_prompt_tokens = saved["max_rebill"] dispatcher.cfg.session_cache.enabled = saved["cache_enabled"] dispatcher.cfg.escalation.max_tier = saved["max_tier"] session_cache.clear() # --- helper: query last route_decision --- def _last_decision_row(): """Query the newest route_decisions row from the temp DB.""" db_path = dispatcher.cfg.database.path conn = sqlite3.connect(db_path) row = conn.execute( """ SELECT task_tier, task_category, classification_source, required_context_tokens FROM route_decisions WHERE kind = 'chat' ORDER BY rowid DESC LIMIT 1 """ ).fetchone() conn.close() return row # --- tests --- def test_positive_control_bumps_tier(client, saved_cfg): """Test 1: flag ON, 3 errors -> tier 2.""" dispatcher.cfg.escalation.enabled = True dispatcher.cfg.escalation.tool_error_bump.enabled = True dispatcher.cfg.escalation.tool_error_bump.threshold = 3 dispatcher.cfg.escalation.tool_error_bump.max_bump = 1 resp = client.post( "/v1/chat/completions", json={"model": "auto", "messages": _messages_with_errors(3)}, ) assert resp.status_code == 200, resp.text row = _last_decision_row() assert row is not None assert row[0] == 2, f"Expected tier 2 (bumped), got {row[0]}" def test_flag_off_no_bump(client, saved_cfg): """Test 2: flag OFF, 3 errors -> tier 1 (same as today).""" dispatcher.cfg.escalation.enabled = False resp = client.post( "/v1/chat/completions", json={"model": "auto", "messages": _messages_with_errors(3)}, ) assert resp.status_code == 200 row = _last_decision_row() assert row is not None assert row[0] == 1, f"Expected tier 1 (no bump), got {row[0]}" def test_shadow_mode_logs_scan(client, caplog, saved_cfg): """Test 3: flag OFF, 2 errors -> shadow log, no bump.""" import logging dispatcher.cfg.escalation.enabled = False caplog.set_level(logging.INFO) resp = client.post( "/v1/chat/completions", json={"model": "auto", "messages": _messages_with_errors(2)}, ) assert resp.status_code == 200 row = _last_decision_row() assert row is not None assert row[0] == 1 found = any( "tool_error_scan" in record.message and "errors=2" in record.message and "would_escalate=0" in record.message and "tier=1" in record.message for record in caplog.records ) assert found, f"No shadow scan line found. Records: {[r.message for r in caplog.records]}" def test_session_cache_unbumped_m1(client, saved_cfg): """Test 4: session cache must hold UNBUMPED tier (the M1 fix). MUTATION EVIDENCE: revert the put back to ``decision.classification.task_tier`` (one-line edit) -> MUST FAIL (cache now holds 2 instead of 1). """ dispatcher.cfg.escalation.enabled = True dispatcher.cfg.escalation.tool_error_bump.enabled = True dispatcher.cfg.escalation.tool_error_bump.threshold = 3 dispatcher.cfg.escalation.tool_error_bump.max_bump = 1 dispatcher.cfg.session_cache.enabled = True # First request: cache miss, triggers classify branch + bump -> tier 2. resp = client.post( "/v1/chat/completions", json={"model": "auto", "messages": _messages_with_errors(3)}, headers={"X-Router-Conversation": "test-session-m1"}, ) assert resp.status_code == 200 row = _last_decision_row() assert row[0] == 2, f"Persisted tier should be 2, got {row[0]}" # Second request: a follow-up with a success resets error count, # triggers cache hit path. The cache should hold tier 1. resp2 = client.post( "/v1/chat/completions", json={ "model": "auto", "messages": [ {"role": "user", "content": "previous"}, _assistant_call("c0", "edit"), _tool_result("c0", "The file has been updated."), {"role": "user", "content": "next"}, ], }, headers={"X-Router-Conversation": "test-session-m1"}, ) assert resp2.status_code == 200 # On the cached branch, tier should be 1 (from cache), NOT 2. row2 = _last_decision_row() assert row2 is not None assert row2[0] == 1, f"Expected cached tier 1, got {row2[0]}" def test_cache_write_unchanged_on_low_errors(client, saved_cfg): """Test 5: 1 error (below threshold) -> cache write is normal.""" dispatcher.cfg.escalation.enabled = True dispatcher.cfg.escalation.tool_error_bump.enabled = True dispatcher.cfg.escalation.tool_error_bump.threshold = 3 dispatcher.cfg.session_cache.enabled = True resp = client.post( "/v1/chat/completions", json={"model": "auto", "messages": _messages_with_errors(1)}, headers={"X-Router-Conversation": "test-cache-low-err"}, ) assert resp.status_code == 200 row = _last_decision_row() assert row[0] == 1, f"Expected tier 1 (below threshold), got {row[0]}" def test_global_kill_switch(client, saved_cfg): """Test 6: global escalation.enabled=False -> no bump.""" dispatcher.cfg.escalation.enabled = False dispatcher.cfg.escalation.tool_error_bump.enabled = True dispatcher.cfg.escalation.tool_error_bump.threshold = 3 resp = client.post( "/v1/chat/completions", json={"model": "auto", "messages": _messages_with_errors(3)}, ) assert resp.status_code == 200 row = _last_decision_row() assert row[0] == 1, f"Expected tier 1 (global kill switch), got {row[0]}" def test_rebill_guard(client, saved_cfg): """Test 7: max_rebill_prompt_tokens=1, prompt > 1 -> no bump.""" dispatcher.cfg.escalation.enabled = True dispatcher.cfg.escalation.tool_error_bump.enabled = True dispatcher.cfg.escalation.tool_error_bump.threshold = 3 dispatcher.cfg.iteration.max_rebill_prompt_tokens = 1 msgs = _messages_with_errors(3) msgs[-1]["content"] = "A" * 500 # pad so measured prompt > 1 resp = client.post( "/v1/chat/completions", json={"model": "auto", "messages": msgs}, ) assert resp.status_code == 200 row = _last_decision_row() assert row[0] == 1, f"Expected tier 1 (rebill guard), got {row[0]}" def test_cached_branch_bumps(client, saved_cfg): """Test 8: cache hit + 3 errors -> cached-branch bump to tier 2.""" dispatcher.cfg.escalation.enabled = True dispatcher.cfg.escalation.tool_error_bump.enabled = True dispatcher.cfg.escalation.tool_error_bump.threshold = 3 dispatcher.cfg.session_cache.enabled = True dispatcher.cfg.escalation.max_tier = 3 # Seed the session cache with tier 1. dispatcher.session_cache.put( "c:test-session-cache-branch", "coding_general", 1, ) resp = client.post( "/v1/chat/completions", json={"model": "auto", "messages": _messages_with_errors(3)}, headers={"X-Router-Conversation": "test-session-cache-branch"}, ) assert resp.status_code == 200 row = _last_decision_row() assert row[0] == 2, f"Expected tier 2 (cached bump), got {row[0]}" def test_never_lowers_tier(client, saved_cfg): """Test 9: bump never lowers tier (already at max_tier=3).""" dispatcher.cfg.escalation.enabled = True dispatcher.cfg.escalation.tool_error_bump.enabled = True dispatcher.cfg.escalation.tool_error_bump.threshold = 3 dispatcher.cfg.escalation.tool_error_bump.max_bump = 1 dispatcher.cfg.session_cache.enabled = True dispatcher.cfg.escalation.max_tier = 3 # Seed the cache with tier 3 (max). Key must include 'c:' prefix since # resolve_identity prefixes X-Router-Conversation with 'c:'. dispatcher.session_cache.put( "c:test-session-never-low", "coding_general", 3, ) resp = client.post( "/v1/chat/completions", json={"model": "auto", "messages": _messages_with_errors(3)}, headers={"X-Router-Conversation": "test-session-never-low"}, ) assert resp.status_code == 200 row = _last_decision_row() assert row[0] == 3, f"Expected tier 3 (never lowers), got {row[0]}" def test_abort_does_not_count(client, caplog, saved_cfg): """Test 11: abort results -> no bump, no escalation log.""" import logging dispatcher.cfg.escalation.enabled = True dispatcher.cfg.escalation.tool_error_bump.enabled = True dispatcher.cfg.escalation.tool_error_bump.threshold = 3 caplog.set_level(logging.INFO) resp = client.post( "/v1/chat/completions", json={"model": "auto", "messages": _messages_abort(3)}, ) assert resp.status_code == 200 row = _last_decision_row() assert row[0] == 1, f"Expected tier 1 (abort neutral), got {row[0]}" escalation_found = any( "tool_error_escalation" in record.message for record in caplog.records ) assert not escalation_found, ( "tool_error_escalation should NOT appear for abort-only" ) # --- validator tests --- def test_threshold_zero_rejected(): """Test 10: threshold=0 must be rejected.""" with pytest.raises(ValidationError) as exc: ToolErrorBumpConfig(threshold=0) assert "threshold must be >= 1" in str(exc.value) def test_max_bump_five_rejected(): """Test 12: max_bump=5 must be rejected (only 1 or 2 allowed).""" with pytest.raises(ValidationError) as exc: ToolErrorBumpConfig(max_bump=5) assert "max_bump must be in 1..2" in str(exc.value) # --- bump-only re-route context test --- def test_bump_only_reoute_keeps_larger_estimate(client, saved_cfg, monkeypatch): """Test 13: bump-only re-route uses max(measured, classifier_estimate). When only the bump triggers re-route (measured <= classifier_estimate), the decision's required_context_tokens should be the larger estimate (classifier_estimate), not just measured. """ dispatcher.cfg.escalation.enabled = True dispatcher.cfg.escalation.tool_error_bump.enabled = True dispatcher.cfg.escalation.tool_error_bump.threshold = 3 dispatcher.cfg.escalation.tool_error_bump.max_bump = 1 dispatcher.cfg.session_cache.enabled = True dispatcher.cfg.escalation.max_tier = 3 # Patch the classifier to return a LARGE required_context_tokens so that # measured (< 1k) is smaller -- the max() should pick the classifier value. monkeypatch.setattr( dispatcher, "classify", lambda task, context: Classification( task_category="coding_general", task_tier=1, required_context_tokens=50000, confidence=0.9, ), ) # Small conversation with 3 edit-class errors -> triggers bump msgs = _messages_with_errors(3) resp = client.post( "/v1/chat/completions", json={"model": "auto", "messages": msgs}, ) assert resp.status_code == 200, resp.text # The route_decision should have required_context_tokens = 50000 # (max of measured ~122 and classifier_estimate 50000) db_path = dispatcher.cfg.database.path conn = sqlite3.connect(db_path) row = conn.execute( """ SELECT required_context_tokens FROM route_decisions WHERE kind = 'chat' ORDER BY rowid DESC LIMIT 1 """ ).fetchone() conn.close() assert row is not None assert row[0] >= 50000, f"Expected >=50000, got {row[0]}" # --- ITEM 0 bump-count test (moved from test_metrics.py) --- def test_tool_error_bumps_by_model_ttl(client, tmp_path, monkeypatch): """A bump 30h old is excluded; one 2h old is counted.""" from datetime import datetime, timedelta, timezone import metrics as metrics_mod db_path = tmp_path / "bumps.db" conn = sqlite3.connect(db_path) conn.row_factory = sqlite3.Row conn.executescript(SCHEMA_SQL) now = datetime.now(timezone.utc) two_hours_ago = (now - timedelta(hours=2)).strftime("%Y-%m-%dT%H:%M:%S") thirty_hours_ago = (now - timedelta(hours=30)).strftime("%Y-%m-%dT%H:%M:%S") # Session A: previous row at 30h, bump at 30h -> excluded (outside 24h window) conn.execute( "INSERT INTO route_decisions " "(observed_at, kind, task_category, task_tier, selected_model, " "session_key) VALUES (?, 'chat', 'coding_general', 1, 'old-model', 'sess-bump-ttl')", (thirty_hours_ago,), ) conn.execute( "INSERT INTO route_decisions " "(observed_at, kind, task_category, task_tier, selected_model, " "session_key, escalation_reason) VALUES (?, 'chat', 'coding_general', 2, 'bumped-model', " "'sess-bump-ttl', 'tool_errors:3:1->2')", (thirty_hours_ago,), ) # Session B: previous row at 2h, bump at 2h -> counted conn.execute( "INSERT INTO route_decisions " "(observed_at, kind, task_category, task_tier, selected_model, " "session_key) VALUES (?, 'chat', 'coding_general', 1, 'fresh-model', 'sess-bump-ttl-b')", (two_hours_ago,), ) conn.execute( "INSERT INTO route_decisions " "(observed_at, kind, task_category, task_tier, selected_model, " "session_key, escalation_reason) VALUES (?, 'chat', 'coding_general', 2, 'bumped-model2', " "'sess-bump-ttl-b', 'tool_errors:3:1->2')", (two_hours_ago,), ) conn.commit() conn.close() fresh_conn = sqlite3.connect(db_path) fresh_conn.row_factory = sqlite3.Row result = metrics_mod.tool_error_bumps_by_model(fresh_conn) fresh_conn.close() # Only the 2h bump should appear; 30h bump excluded by 24h window expected = { "bumps": 1, } # There should be exactly one row assert len(result) == 1, f"Expected 1 row, got {len(result)}: {result}" assert result[0]["model"] == "fresh-model" assert result[0]["bumps"] == expected["bumps"] # --- ITEM A: bump falls back when bumped tier has no candidates --- def test_bump_fallback_cache_miss(client, saved_cfg): """Cache-miss: 3 edit errors bump tier 1->2, but tier-3 models don't exist, so the bump is skipped and the original tier (1) is used. Returns 200.""" import sqlite3 as sqlite3_mod import dispatcher as disp_mod disp_mod.cfg.escalation.enabled = True disp_mod.cfg.escalation.tool_error_bump.enabled = True disp_mod.cfg.escalation.tool_error_bump.threshold = 3 disp_mod.cfg.escalation.tool_error_bump.max_bump = 2 disp_mod.cfg.escalation.max_tier = 3 # Delete tier-3 models so bumping to tier 2+ has no candidates db_path = disp_mod.cfg.database.path conn = sqlite3_mod.connect(db_path) conn.execute("DELETE FROM models WHERE tier = 3") conn.execute("DELETE FROM proficiency WHERE model_id = 'tier3-model'") conn.commit() conn.close() msgs = _messages_with_errors(3) resp = client.post( "/v1/chat/completions", json={"model": "auto", "messages": msgs}, ) assert resp.status_code == 200, resp.text # The persisted tier should be the ORIGINAL (1), not bumped, and # escalation_reason should be NULL because the bump was skipped. row = _last_decision_row() assert row[0] == 1, f"Expected original tier 1, got {row[0]}" # Check escalation_reason is NULL conn = sqlite3_mod.connect(db_path) row2 = conn.execute( "SELECT escalation_reason FROM route_decisions " "WHERE kind = 'chat' ORDER BY rowid DESC LIMIT 1" ).fetchone() conn.close() assert row2[0] is None, f"Expected escalation_reason NULL, got {row2[0]}" def test_bump_fallback_cached_branch(client, saved_cfg): """Cache-hit: cached tier 1, 3 errors bump to tier 2, but no tier-3 models, so fallback to original tier 1. Returns 200.""" import sqlite3 as sqlite3_mod import dispatcher as disp_mod disp_mod.cfg.escalation.enabled = True disp_mod.cfg.escalation.tool_error_bump.enabled = True disp_mod.cfg.escalation.tool_error_bump.threshold = 3 disp_mod.cfg.escalation.tool_error_bump.max_bump = 2 disp_mod.cfg.escalation.max_tier = 3 disp_mod.cfg.session_cache.enabled = True # Delete tier-3 models db_path = disp_mod.cfg.database.path conn = sqlite3_mod.connect(db_path) conn.execute("DELETE FROM models WHERE tier = 3") conn.execute("DELETE FROM proficiency WHERE model_id = 'tier3-model'") conn.commit() conn.close() # Seed the cache with tier 1 disp_mod.session_cache.put( "c:test-session-bump-fallback", "coding_general", 1, ) msgs = _messages_with_errors(3) resp = client.post( "/v1/chat/completions", json={"model": "auto", "messages": msgs}, headers={"X-Router-Conversation": "test-session-bump-fallback"}, ) assert resp.status_code == 200, resp.text row = _last_decision_row() assert row[0] == 1, f"Expected original tier 1, got {row[0]}" conn = sqlite3_mod.connect(db_path) row2 = conn.execute( "SELECT escalation_reason FROM route_decisions " "WHERE kind = 'chat' ORDER BY rowid DESC LIMIT 1" ).fetchone() conn.close() assert row2[0] is None, f"Expected escalation_reason NULL, got {row2[0]}" # --- ITEM F: pin the never-lowers guard --- def test_never_lowers_pins_reason_null(client, saved_cfg): """With cached tier 3 and escalation.max_tier = 3, bump does not change the tier and escalation_reason is NULL. Same with max_tier = 2.""" import sqlite3 as sqlite3_mod import dispatcher as disp_mod disp_mod.cfg.escalation.enabled = True disp_mod.cfg.escalation.tool_error_bump.enabled = True disp_mod.cfg.escalation.tool_error_bump.threshold = 3 disp_mod.cfg.session_cache.enabled = True # --- Case 1: cached tier 3, max_tier = 3 --- disp_mod.cfg.escalation.max_tier = 3 disp_mod.session_cache.put( "c:test-never-lower-pin-1", "coding_general", 3, ) resp = client.post( "/v1/chat/completions", json={"model": "auto", "messages": _messages_with_errors(3)}, headers={"X-Router-Conversation": "test-never-lower-pin-1"}, ) assert resp.status_code == 200, resp.text row = _last_decision_row() assert row[0] == 3, f"Case 1: Expected tier 3, got {row[0]}" db_path = disp_mod.cfg.database.path conn = sqlite3_mod.connect(db_path) row2 = conn.execute( "SELECT escalation_reason FROM route_decisions " "WHERE kind = 'chat' ORDER BY rowid DESC LIMIT 1" ).fetchone() conn.close() assert row2[0] is None, f"Case 1: Expected NULL, got {row2[0]}" # --- Case 2: cached tier 3, max_tier = 2 --- # max_tier < cached tier: bump guard (new_tier <= tier) should keep tier 3 disp_mod.cfg.escalation.max_tier = 2 disp_mod.session_cache.put( "c:test-never-lower-pin-2", "coding_general", 3, ) resp = client.post( "/v1/chat/completions", json={"model": "auto", "messages": _messages_with_errors(3)}, headers={"X-Router-Conversation": "test-never-lower-pin-2"}, ) assert resp.status_code == 200, resp.text # The tier should stay 3 (never lowers) conn = sqlite3_mod.connect(db_path) row3 = conn.execute( "SELECT task_tier, escalation_reason FROM route_decisions " "WHERE kind = 'chat' ORDER BY rowid DESC LIMIT 1" ).fetchone() conn.close() assert row3[0] == 3, f"Case 2: Expected tier 3, got {row3[0]}" assert row3[1] is None, f"Case 2: Expected NULL, got {row3[1]}"