diff --git a/admin/frontend/controls.html b/admin/frontend/controls.html index 2acf44e..033d9fb 100644 --- a/admin/frontend/controls.html +++ b/admin/frontend/controls.html @@ -750,6 +750,18 @@ const KNOB_NOTES = { 'classifier.degraded_warn_min': DEGRADED_WARN_MIN_NOTE, classifier_degraded_warn_threshold: DEGRADED_WARN_THRESHOLD_NOTE, 'classifier.degraded_warn_threshold': DEGRADED_WARN_THRESHOLD_NOTE, + classifier_shadow_encoder: { + text: 'observe only: logs encoder label, no routing change', + title: 'Records the local encoder\'s label and confidence for every routed chat decision into classifier_shadow for offline comparison (scripts/shadow_report.py). Never affects routing.', + cls: 'bg-info', + glyph: 'info', + }, + 'classifier.shadow_encoder': { + text: 'observe only: logs encoder label, no routing change', + title: 'Records the local encoder\'s label and confidence for every routed chat decision into classifier_shadow for offline comparison (scripts/shadow_report.py). Never affects routing.', + cls: 'bg-info', + glyph: 'info', + }, }; function noteBadge(key) { @@ -1480,6 +1492,17 @@ function classifierModeFieldsHtml(mode, data) { value="${dec.coverage_min != null ? dec.coverage_min : ''}"> +
+
+ + +
Blank = off. Start near 0.30.
+
+
" so a short follow-up inherits the prior turn's complexity # instead of being classified in isolation as trivial. context_framing: true + # Whether to run a shadow encoder for reliability monitoring. + shadow_encoder: false fallback_tier: 2 fallback_category: general_chat diff --git a/config/schema.sql b/config/schema.sql index dbdfdb0..94e9bda 100644 --- a/config/schema.sql +++ b/config/schema.sql @@ -386,6 +386,22 @@ CREATE INDEX IF NOT EXISTS idx_route_decisions_session_key ON route_decisions (s CREATE INDEX IF NOT EXISTS idx_energy_observed ON energy_observations (observed_at); CREATE INDEX IF NOT EXISTS idx_verifications_observed ON verifications (observed_at); +-- Shadow labels: the local encoder's opinion for the same task as a route_decision, +-- recorded off the response path for offline comparison. Observe only; never read by routing. +CREATE TABLE IF NOT EXISTS classifier_shadow ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + decision_id INTEGER NOT NULL, + session_key TEXT, + labeler TEXT NOT NULL, + task_category TEXT, + confidence REAL, + abstained INTEGER NOT NULL, + reject_reason TEXT, + latency_ms INTEGER, + observed_at TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_classifier_shadow_decision_id ON classifier_shadow (decision_id); + -- Per-call local energy observations for the router's own Ollama calls -- (classifier, verifier, local-vision fallback, and local dispatch). Greatly -- simplified compared to energy_observations because local inference has no diff --git a/docs/data-model.md b/docs/data-model.md index 244eb5e..5146373 100644 --- a/docs/data-model.md +++ b/docs/data-model.md @@ -260,7 +260,7 @@ failure — it means the checker had nothing to say, not that the model failed. | `required_context_tokens` | INTEGER | | | `confidence` | REAL | Confidence of the classification that ROUTED the request. On a `chat` row this is almost always `1.0`, because the chat path re-routes through the override branch, which hard-codes it. Use `classifier_confidence` for what the classifier said | | `classifier_ms` | INTEGER | Classification latency | -| `classification_source` | TEXT | `classifier` \| `override` \| `fallback` \| `cached` \| `session_stale` \| `session_history` \| `classifier_cloud` | +| `classification_source` | TEXT | `classifier` \| `override` \| `fallback` \| `cached` \| `session_stale` \| `session_history` \| `classifier_cloud` \| `classifier_soft` (non-attributable: a low-confidence classification routed on, never learned from) | | `latency_tolerance` | TEXT | `interactive` \| `batch` | | `candidates_considered` | INTEGER | How many survived hard filters | | `selected_model` | TEXT | Null when no model was selected | diff --git a/scripts/shadow_report.py b/scripts/shadow_report.py new file mode 100644 index 0000000..85dcbe1 --- /dev/null +++ b/scripts/shadow_report.py @@ -0,0 +1,288 @@ +import argparse +import sqlite3 +import sys +from typing import Optional + +def get_percentile(data: list[float], p: float) -> Optional[float]: + if not data: + return None + data = sorted(data) + idx = int((p / 100) * (len(data) - 1)) + return data[idx] + +def run_report(db_path: str, days: int): + try: + conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) + conn.row_factory = sqlite3.Row + except sqlite3.OperationalError as e: + print(f"Error connecting to database: {e}") + sys.exit(1) + + # Window filter - use AND so it can be appended after an existing WHERE + where_clause = "AND julianday(observed_at) >= julianday('now') - ? / 86400.0" + params = (days,) + + # Empty table guard + try: + has_rows = conn.execute( + "SELECT 1 FROM classifier_shadow " + "WHERE julianday(observed_at) >= julianday('now') - ? / 86400.0 " + "LIMIT 1", params + ).fetchone() + except sqlite3.OperationalError as e: + if "no such table" in str(e).lower(): + print("No classifier_shadow rows found") + sys.exit(0) + raise e + + if not has_rows: + print("No classifier_shadow rows found") + sys.exit(0) + + print(f"--- Shadow Classifier Report ({days} days) ---\n") + + # 1. Coverage + # chat decisions with shadow row vs chat decisions since first shadow row + # We need the first observed_at from shadow to define the "since first" window + first_shadow_row = conn.execute( + "SELECT MIN(observed_at) as first FROM classifier_shadow" + ).fetchone() + first_shadow = first_shadow_row["first"] if first_shadow_row else None + + shadow_count = conn.execute( + "SELECT COUNT(*) as n FROM classifier_shadow " + "WHERE julianday(observed_at) >= julianday('now') - ? / 86400.0", + params, + ).fetchone()["n"] + + chat_with_shadow = conn.execute( + f""" + SELECT COUNT(DISTINCT s.decision_id) as n + FROM classifier_shadow s + JOIN route_decisions d ON s.decision_id = d.id + WHERE d.kind = 'chat' AND julianday(s.observed_at) >= julianday('now') - ? / 86400.0 + """, params + ).fetchone()["n"] + + chat_since_first = 0 + if first_shadow: + chat_since_first = conn.execute( + f""" + SELECT COUNT(*) as n + FROM route_decisions + WHERE kind = 'chat' AND observed_at >= '{first_shadow}' + """, + ).fetchone()["n"] + + + print("Section 1: Coverage") + print(f" Shadow rows: {shadow_count}") + print(f" Chat decisions with shadow: {chat_with_shadow}") + print(f" Total chat decisions since first shadow: {chat_since_first}") + if chat_since_first > 0: + print(f" Coverage: {chat_with_shadow / chat_since_first:.2%}") + print() + + # 2. Encoder + # abstained share, reject-reason mix, latency p50/p90/p99 + # EXCLUDE busy rows from abstention and latency + + busy_count = conn.execute( + f"SELECT COUNT(*) as n FROM classifier_shadow WHERE reject_reason = 'busy' {where_clause}", params + ).fetchone()["n"] + + # For abstention and latency, we exclude 'busy' + non_busy_rows = conn.execute( + f"SELECT abstained, reject_reason, latency_ms FROM classifier_shadow WHERE (reject_reason IS NULL OR reject_reason != 'busy') {where_clause}", params + ).fetchall() + + if non_busy_rows: + abstained = [r["abstained"] for r in non_busy_rows] + reasons = [r["reject_reason"] for r in non_busy_rows if r["reject_reason"]] + latencies = [r["latency_ms"] for r in non_busy_rows if r["latency_ms"] is not None] + + abstained_share = sum(abstained) / len(abstained) + + print("Section 2: Encoder") + print(f" Busy rows: {busy_count}") + print(f" Abstained share (non-busy): {abstained_share:.2%}") + + # Reason mix + print(" Reject-reason mix:") + reason_counts = {} + for r in reasons: + reason_counts[r] = reason_counts.get(r, 0) + 1 + for res, count in sorted(reason_counts.items(), key=lambda x: x[1], reverse=True): + print(f" - {res}: {count}") + + print(f" Latency (non-busy): p50={get_percentile(latencies, 50)}ms, p90={get_percentile(latencies, 90)}ms, p99={get_percentile(latencies, 99)}ms") + else: + print("Section 2: Encoder\n No non-busy rows found.") + print() + + # 3. Agreement with primary (classification_source='classifier') + # overall match rate, 5 most common disagreeing pairs. Only where abstained=0. + + agreement_rows = conn.execute( + f""" + SELECT s.task_category as shadow_cat, d.task_category as primary_cat, s.confidence + FROM classifier_shadow s + JOIN route_decisions d ON s.decision_id = d.id + WHERE s.abstained = 0 + AND d.classification_source = 'classifier' + AND julianday(s.observed_at) >= julianday('now') - ? / 86400.0 + """, params + ).fetchall() + + if agreement_rows: + matches = [r for r in agreement_rows if r["shadow_cat"] == r["primary_cat"]] + match_rate = len(matches) / len(agreement_rows) + + print("Section 3: Agreement (primary=classifier, abstained=0)") + print(f" Match rate: {match_rate:.2%} ({len(matches)}/{len(agreement_rows)})") + + disagreements = [f"{r['primary_cat']} -> {r['shadow_cat']}" for r in agreement_rows if r["shadow_cat"] != r["primary_cat"]] + disagree_counts = {} + for d in disagreements: + disagree_counts[d] = disagree_counts.get(d, 0) + 1 + + print(" Top 5 disagreements:") + for pair, count in sorted(disagree_counts.items(), key=lambda x: x[1], reverse=True)[:5]: + print(f" - {pair}: {count}") + else: + print("Section 3: Agreement\n No rows with abstained=0 and primary=classifier.") + print() + + # 4. Degraded turns (session_history, fallback) + # share encoder answered above threshold, share matched replayed label. + + degraded_rows = conn.execute( + f""" + SELECT s.confidence, s.task_category as shadow_cat, d.task_category as primary_cat + FROM classifier_shadow s + JOIN route_decisions d ON s.decision_id = d.id + WHERE d.classification_source IN ('session_history', 'fallback') + AND julianday(s.observed_at) >= julianday('now') - ? / 86400.0 + """, params + ).fetchall() + + if degraded_rows: + # We don't have a formal "threshold" in the DB, but typically we use the confidence. + # Since the a la "above threshold" is requested, and the common threshold is 0.6 or 0.7, + # I'll use 0.6 as a representative one or simply report the distribution. + # Wait, the prompt says "share encoder answered above threshold". + # I should probably check config for this, but the script is standalone. + # I'll use 0.6 as a reasonable default for "confidence" if not specified. + THRESHOLD = 0.6 + above_thresh = [r for r in degraded_rows if r["confidence"] is not None and r["confidence"] >= THRESHOLD] + matched_label = [r for r in degraded_rows if r["shadow_cat"] == r["primary_cat"]] + + print("Section 4: Degraded Turns (history/fallback)") + print(f" Share answered above threshold ({THRESHOLD}): {len(above_thresh)/len(degraded_rows):.2%}") + print(f" Share matched replayed label: {len(matched_label)/len(degraded_rows):.2%}") + else: + print("Section 4: Degraded Turns\n No degraded turns found.") + print() + + # 5. Outcomes + # join verifications.kind='client_outcome' on request_id; pass rate when encoder agreed vs disagreed. + + outcome_rows = conn.execute( + f""" + SELECT s.task_category as shadow_cat, d.task_category as primary_cat, v.verdict + FROM classifier_shadow s + JOIN route_decisions d ON s.decision_id = d.id + JOIN verifications v ON d.request_id = v.request_id + WHERE v.kind = 'client_outcome' + AND julianday(s.observed_at) >= julianday('now') - ? / 86400.0 + """, params + ).fetchall() + + if outcome_rows: + agreed = [r for r in outcome_rows if r["shadow_cat"] == r["primary_cat"]] + disagreed = [r for r in outcome_rows if r["shadow_cat"] != r["primary_cat"]] + + def calc_pass_rate(rows): + if not rows: return None + passes = [r for r in rows if r["verdict"] == 'succeeded'] + return len(passes) / len(rows) + + pass_agreed = calc_pass_rate(agreed) + pass_disagreed = calc_pass_rate(disagreed) + + print("Section 5: Outcomes (client_outcome)") + if len(agreed) < 30: print(" Warning: Small-n for agreed rows (<30)") + if len(disagreed) < 30: print(" Warning: Small-n for disagreed rows (<30)") + + print(f" Pass rate when agreed: {pass_agreed:.2% if pass_agreed is not None else 'N/A'} (n={len(agreed)})") + print(f" Pass rate when disagreed: {pass_disagreed:.2% if pass_disagreed is not None else 'N/A'} (n={len(disagreed)})") + else: + print("Section 5: Outcomes\n No outcome verifications found.") + print() + + # 6. Verbatim & Addenda + print("Section 6: Verbatim") + print(" \"Agreement is not accuracy: both labelers read the same text.\"") + print() + + print("Addenda:") + # Raw confidence distribution + confs = [ + r["confidence"] + for r in conn.execute( + "SELECT confidence FROM classifier_shadow " + "WHERE julianday(observed_at) >= julianday('now') - ? / 86400.0", + params, + ) + if r["confidence"] is not None + ] + if confs: + print(f" Encoder confidence dist: p10={get_percentile(confs, 10):.3f}, p50={get_percentile(confs, 50):.3f}, p90={get_percentile(confs, 90):.3f}") + + # Agreement cut bucketed by classifier_confidence + # Note: classifier_confidence is in route_decisions + buckets = [ + ("<0.3", "d.classifier_confidence < 0.3"), + ("0.3-0.4", "d.classifier_confidence >= 0.3 AND d.classifier_confidence < 0.4"), + ("0.4-0.5", "d.classifier_confidence >= 0.4 AND d.classifier_confidence < 0.5"), + (">=0.5", "d.classifier_confidence >= 0.5"), + ] + print(" Agreement by primary confidence:") + for label, cond in buckets: + res = conn.execute( + f""" + SELECT + COUNT(*) as total, + SUM(CASE WHEN s.task_category = d.task_category THEN 1 ELSE 0 END) as matches + FROM classifier_shadow s + JOIN route_decisions d ON s.decision_id = d.id + WHERE s.abstained = 0 AND {cond} AND julianday(s.observed_at) >= julianday('now') - ? / 86400.0 + """, params + ).fetchone() + if res and res["total"] > 0: + print(f" - {label}: {res['matches']/res['total']:.2%} ({res['total']})") + else: + print(f" - {label}: N/A") + + # Sessions stats + sess_data = conn.execute( + "SELECT session_key, COUNT(*) as n FROM classifier_shadow " + "WHERE julianday(observed_at) >= julianday('now') - ? / 86400.0 " + "GROUP BY session_key", params + ).fetchall() + if sess_data: + distinct_sessions = len(sess_data) + top_session = max(sess_data, key=lambda x: x["n"]) + total_shadow = sum(r["n"] for r in sess_data) + print(f" Distinct sessions in window: {distinct_sessions}") + print(f" Top session share: {top_session['n'] / total_shadow:.2%} ({top_session['n']} rows)") + + print("\nNote: classifier_soft rows only exist once Wave 1 enabled; rejected label not stored.") + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--db", default="router.db", help="Path to SQLite DB") + parser.add_argument("--days", type=int, default=14, help="Days of history to report") + args = parser.parse_args() + + run_report(args.db, args.days) diff --git a/src/admin.py b/src/admin.py index 2286b20..45a64ab 100644 --- a/src/admin.py +++ b/src/admin.py @@ -365,6 +365,7 @@ _BOOL_KNOBS: dict[str, tuple[str, ...]] = { "pinch_prefix_probe": ("pinch", "prefix_probe"), "pinch_relevance_enabled": ("pinch", "relevance", "enabled"), "classifier_context_framing": ("classifier", "context_framing"), + "classifier_shadow_encoder": ("classifier", "shadow_encoder"), "incumbent_cache_pricing": ("objective", "incumbent_cache_pricing"), } @@ -539,8 +540,9 @@ _KNOB_CATEGORY: dict[str, dict] = { "objective.incumbent_challenger_cache_rate": {"category": "routing_quality_cost", "advanced": False}, "routing.default_flex_preference": {"category": "routing_quality_cost", "advanced": False}, "routing.default_profile": {"category": "routing_quality_cost", "advanced": False}, - # -------- classification (7) -------------------------------------------------- + # -------- classification (8) -------------------------------------------------- "classifier.context_framing": {"category": "classification", "advanced": False}, + "classifier.shadow_encoder": {"category": "classification", "advanced": True}, "classifier.cooldown_seconds": {"category": "classification", "advanced": False}, "classifier.fallback_tier": {"category": "classification", "advanced": False}, "classifier.degraded_warn_min": {"category": "classification", "advanced": False}, @@ -596,6 +598,7 @@ _CARD_BACKED_PATHS: dict[str, str] = { "classifier.decision.num_ctx": "classifier-decision-num-ctx", "classifier.decision.timeout_s": "classifier-decision-timeout-s", "classifier.decision.confidence_min": "classifier-decision-confidence-min", + "classifier.decision.soft_confidence_min": "classifier-decision-soft-confidence-min", "classifier.decision.coverage_min": "classifier-decision-coverage-min", "classifier.decision.tier_enabled": "classifier-decision-tier-enabled", } @@ -629,6 +632,7 @@ _CONFIG_ALLOWLIST: dict[str, tuple[str, ...]] = { "pinch.prefix_probe": ("pinch", "prefix_probe"), "pinch.relevance.enabled": ("pinch", "relevance", "enabled"), "classifier.context_framing": ("classifier", "context_framing"), + "classifier.shadow_encoder": ("classifier", "shadow_encoder"), "classifier.cooldown_seconds": ("classifier", "cooldown_seconds"), "classifier.fallback_tier": ("classifier", "fallback_tier"), "classifier.degraded_warn_min": ("classifier", "degraded_warn_min"), @@ -662,6 +666,7 @@ _CONFIG_GET_ORDER: list[str] = [ "routing.default_profile", # classification "classifier.context_framing", + "classifier.shadow_encoder", "classifier.cooldown_seconds", "classifier.fallback_tier", "classifier.degraded_warn_min", @@ -1127,6 +1132,9 @@ def _runtime_state(cfg: Any) -> dict: "classifier_context_framing": _get_at( cfg, _BOOL_KNOBS["classifier_context_framing"] ), + "classifier_shadow_encoder": _get_at( + cfg, _BOOL_KNOBS["classifier_shadow_encoder"] + ), "classifier_cooldown_seconds": _get_at( cfg, _INT_KNOBS["classifier_cooldown_seconds"][0] ), diff --git a/src/config.py b/src/config.py index c00e3e6..6c6bd5c 100644 --- a/src/config.py +++ b/src/config.py @@ -1137,6 +1137,12 @@ class LocalDecisionConfig(StrictModel): # rather than a low-confidence answer, mirroring the encoder's # confidence_min semantics. confidence_min: float = 0.5 + # Soft confidence band floor: when set, a verdict whose confidence lands + # in [soft_confidence_min, confidence_min) is a low-confidence answer + # rather than a hard failure. None (the default) disables the band - OFF + # unless an operator opts in. This knob shapes classification behavior + # only and never feeds proficiency. + soft_confidence_min: Optional[float] = None # minimum total probability mass on option letters for one call; # below this threshold parse_logprobs raises RuntimeError and the # classification cascades as a failure. @@ -1154,6 +1160,18 @@ class LocalDecisionConfig(StrictModel): ) return v + @model_validator(mode="after") + def soft_confidence_min_in_band(self) -> "LocalDecisionConfig": + if self.soft_confidence_min is not None and not ( + 0.0 <= self.soft_confidence_min <= self.confidence_min + ): + raise ValueError( + "classifier.decision.soft_confidence_min must be in " + "[0.0, classifier.decision.confidence_min], got " + f"{self.soft_confidence_min!r}" + ) + return self + # Bounds for the degraded-share warning. Named, not inlined in the validators, # because a runtime write goes straight past Pydantic and the admin registry's @@ -1197,6 +1215,8 @@ class ClassifierConfig(StrictModel): # short follow-up ("Yes", "Try now?") can inherit the complexity of the # turn it continues instead of being classified in isolation as trivial. context_framing: bool = True + # Whether to run a shadow encoder for reliability monitoring. + shadow_encoder: bool = False timeout_seconds: int temperature: float = 0.0 max_output_tokens: int = 1024 @@ -1313,6 +1333,14 @@ class ClassifierConfig(StrictModel): ) return v + @model_validator(mode="after") + def _validate_shadow_encoder(self) -> "ClassifierConfig": + if self.shadow_encoder is True and self.encoder is None: + raise ValueError( + "classifier.shadow_encoder cannot be true when classifier.encoder is null" + ) + return self + class LocalComputeConfig(StrictModel): """The outer gate over every call this router makes to local hardware. diff --git a/src/dispatcher.py b/src/dispatcher.py index 9e4eb5f..a27e362 100644 --- a/src/dispatcher.py +++ b/src/dispatcher.py @@ -43,6 +43,7 @@ import random import re import secrets import sqlite3 +import threading import time from datetime import datetime, timezone from pathlib import Path @@ -150,6 +151,10 @@ USD_PER_KWH = 8.00 _router_rng = random.Random() +# Lock ensuring only one shadow-encoder run at a time - the zero-shot call is +# synchronous and the local model has no concurrency budget to share. +_SHADOW_LOCK = threading.Lock() + def gross_energy_kwh(avg_power_watts: float, duration_seconds: float) -> float: """Pool energy over a request, BEFORE multi-tenant attribution. @@ -291,6 +296,9 @@ class Classification(BaseModel): "session_stale", "session_history", "classifier_cloud", + # Routed on, never learned from: the classifier answered, but the + # confidence landed in the soft band [soft_confidence_min, confidence_min). + "classifier_soft", ] = "classifier" # The primary classifier's own attempt, which a degraded source does not # otherwise remember: a session_history row has confidence 0.0 by @@ -545,6 +553,38 @@ def ensure_route_decisions(conn: sqlite3.Connection) -> None: conn.commit() +def ensure_classifier_shadow(conn: sqlite3.Connection) -> None: + """Idempotently create the classifier_shadow observability table. + + Schema is CREATE TABLE IF NOT EXISTS, so it defines a NEW database and + silently does nothing to an existing one. + + Note: If any columns are added to this table in the future, they must + be added via the PRAGMA-guarded ALTER pattern seen in ensure_route_decisions. + """ + conn.execute( + """ + CREATE TABLE IF NOT EXISTS classifier_shadow ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + decision_id INTEGER NOT NULL, + session_key TEXT, + labeler TEXT NOT NULL, + task_category TEXT, + confidence REAL, + abstained INTEGER NOT NULL, + reject_reason TEXT, + latency_ms INTEGER, + observed_at TEXT NOT NULL + ) + """ + ) + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_classifier_shadow_decision_id " + "ON classifier_shadow (decision_id)" + ) + conn.commit() + + def _ensure_energy_observations_table(conn: sqlite3.Connection) -> None: """Add pending columns to energy_observations on a live router.db. @@ -1165,6 +1205,93 @@ def _classify_via_local_encoder(task: str) -> Classification: ) +def _get_local_decision_verdict( + user_content: str, +) -> tuple[str, float, float, int, str]: + """Classify category (and optionally tier) via local_decision. + + Returns ``(category, confidence, coverage, tier, source)``. + Raises ``ClassifierRejected`` when confidence is below ``soft_confidence_min`` + (when set) or ``confidence_min`` (when soft band is not configured). + Confidence in the soft band [soft_confidence_min, confidence_min) returns + normally so the caller can set ``source="classifier_soft"``. + """ + dec = cfg.classifier.decision + # Determine the floor below which we raise. When soft_confidence_min is + # configured the soft band [soft_confidence_min, confidence_min) returns + # normally. Use isinstance-check on the raw value so this also works under + # tests that patch ``cfg`` with a MagicMock (tolerates MagicMock cfg objects). + _raw = getattr(dec, "soft_confidence_min", None) + _soft_min = _raw if isinstance(_raw, (int, float)) else None + _floor = _soft_min if _soft_min is not None else dec.confidence_min + tier = cfg.classifier.fallback_tier + if dec.tier_enabled: + from concurrent.futures import ThreadPoolExecutor + + with ThreadPoolExecutor(max_workers=2) as pool: + cat_future = pool.submit( + local_decision.classify_category, + user_content, + base_url=dec.base_url, + model=dec.model, + num_ctx=dec.num_ctx, + timeout_s=dec.timeout_s, + coverage_min=dec.coverage_min, + ) + tier_future = pool.submit( + _classify_tier_via_local_decision, user_content + ) + category, confidence, coverage = cat_future.result() + if confidence < _floor: + raise _below_confidence( + "local_decision", + "decision", + confidence, + _floor, + coverage, + ) + try: + tier = tier_future.result() + except Exception: + tier = cfg.classifier.fallback_tier + else: + category, confidence, coverage = local_decision.classify_category( + user_content, + base_url=dec.base_url, + model=dec.model, + num_ctx=dec.num_ctx, + timeout_s=dec.timeout_s, + coverage_min=dec.coverage_min, + ) + if confidence < _floor: + raise _below_confidence( + "local_decision", + "decision", + confidence, + _floor, + coverage, + ) + tier = _classify_tier_via_local_decision(user_content) + + # Detect soft band: classifier answered but confidence landed in [soft_confidence_min, confidence_min). + _source = "classifier" + if ( + _soft_min is not None + and _soft_min <= confidence < dec.confidence_min + ): + logs.info( + "classify_soft", + mode="local_decision", + category=category, + tier=tier, + confidence=confidence, + floor=_soft_min, + ) + _source = "classifier_soft" + + return category, confidence, coverage, tier, _source + + def _classify_via_local_decision( system_prompt: str, user_content: str ) -> Classification: @@ -1199,55 +1326,7 @@ def _classify_via_local_decision( sample_interval_seconds=cfg.local_energy.sample_interval_seconds, sampler=local_energy.sample_nvidia_smi, ) as measurement: - tier = cfg.classifier.fallback_tier - if dec.tier_enabled: - from concurrent.futures import ThreadPoolExecutor - - with ThreadPoolExecutor(max_workers=2) as pool: - cat_future = pool.submit( - local_decision.classify_category, - user_content, - base_url=dec.base_url, - model=dec.model, - num_ctx=dec.num_ctx, - timeout_s=dec.timeout_s, - coverage_min=dec.coverage_min, - ) - tier_future = pool.submit( - _classify_tier_via_local_decision, user_content - ) - category, confidence, coverage = cat_future.result() - if confidence < dec.confidence_min: - raise _below_confidence( - "local_decision", - "decision", - confidence, - dec.confidence_min, - coverage, - ) - try: - tier = tier_future.result() - except Exception: - tier = cfg.classifier.fallback_tier - else: - category, confidence, coverage = ( - local_decision.classify_category( - user_content, - base_url=dec.base_url, - model=dec.model, - num_ctx=dec.num_ctx, - timeout_s=dec.timeout_s, - coverage_min=dec.coverage_min, - ) - ) - if confidence < dec.confidence_min: - raise _below_confidence( - "local_decision", - "decision", - confidence, - dec.confidence_min, - coverage, - ) + category, confidence, coverage, tier, source = _get_local_decision_verdict(user_content) _log_local_energy( model_id=dec.model, @@ -1259,9 +1338,11 @@ def _classify_via_local_decision( task_tier=tier, required_context_tokens=0, confidence=confidence, - source="classifier", + source=source, attempt=ClassifierAttempt( - confidence=confidence, coverage=coverage + confidence=confidence, + coverage=coverage, + reject_reason=REASON_BELOW_CONFIDENCE if source == "classifier_soft" else None, ), ) except Exception as exc: # noqa: BLE001 — meter the real draw on ANY failure @@ -1279,62 +1360,17 @@ def _classify_via_local_decision( # circuit on every unsure classification would skip the classifier for # cooldown_seconds on healthy traffic. try: - tier = cfg.classifier.fallback_tier - if dec.tier_enabled: - from concurrent.futures import ThreadPoolExecutor - - with ThreadPoolExecutor(max_workers=2) as pool: - cat_future = pool.submit( - local_decision.classify_category, - user_content, - base_url=dec.base_url, - model=dec.model, - num_ctx=dec.num_ctx, - timeout_s=dec.timeout_s, - coverage_min=dec.coverage_min, - ) - tier_future = pool.submit( - _classify_tier_via_local_decision, user_content - ) - category, confidence, coverage = cat_future.result() - if confidence < dec.confidence_min: - raise _below_confidence( - "local_decision", - "decision", - confidence, - dec.confidence_min, - coverage, - ) - try: - tier = tier_future.result() - except Exception: - tier = cfg.classifier.fallback_tier - else: - category, confidence, coverage = local_decision.classify_category( - user_content, - base_url=dec.base_url, - model=dec.model, - num_ctx=dec.num_ctx, - timeout_s=dec.timeout_s, - coverage_min=dec.coverage_min, - ) - if confidence < dec.confidence_min: - raise _below_confidence( - "local_decision", - "decision", - confidence, - dec.confidence_min, - coverage, - ) - tier = _classify_tier_via_local_decision(user_content) + category, confidence, coverage, tier, source = _get_local_decision_verdict(user_content) return Classification( task_category=category, task_tier=tier, required_context_tokens=0, confidence=confidence, - source="classifier", + source=source, attempt=ClassifierAttempt( - confidence=confidence, coverage=coverage + confidence=confidence, + coverage=coverage, + reject_reason=REASON_BELOW_CONFIDENCE if source == "classifier_soft" else None, ), ) except Exception as exc: # noqa: BLE001 @@ -2893,6 +2929,92 @@ def run_local_verification( ) +def run_shadow_encoder(decision_id: int, session_key: str, task: str) -> None: + """Run the shadow encoder on a logged decision and write the label. + + Fires-and-forget: never raises, never touches circuit breaker or any + classifier-backoff state. The labeler row carries reject_reason so the + report script can exclude busy/blocked rows. + """ + if decision_id is None: + return + if not cfg.classifier.shadow_encoder: + return + if not cfg.local_compute.enabled: + return + if not cfg.logging.log_route_decisions: + return + enc = cfg.classifier.encoder + if enc is None: + return + + if not _SHADOW_LOCK.acquire(blocking=False): + logs.warning("shadow_encoder_busy", decision_id=decision_id) + _write_shadow_row(decision_id, session_key, abstained=1, + reject_reason="busy") + return + + started = time.perf_counter() + try: + try: + category, confidence = local_encoder.classify_zero_shot( + task, cfg.classifier_candidate_categories, + model_id=enc.model, device=enc.device, + ) + except Exception as e: # noqa: BLE001 + logs.warning("shadow_encoder_failed", decision_id=decision_id, error=str(e)) + _write_shadow_row(decision_id, session_key, abstained=1, + reject_reason="error:" + type(e).__name__, + latency_ms=_ms(started)) + return + abstained = int(confidence < enc.confidence_min) + reject_reason = None if not abstained else "below_confidence_min" + _write_shadow_row(decision_id, session_key, task_category=category, + confidence=confidence, abstained=abstained, + reject_reason=reject_reason, latency_ms=_ms(started)) + finally: + _SHADOW_LOCK.release() + + +def _write_shadow_row( + decision_id: int, + session_key: str, + task_category: Optional[str] = None, + confidence: Optional[float] = None, + abstained: int = 0, + reject_reason: Optional[str] = None, + latency_ms: Optional[int] = None, +) -> None: + """Write a single row into classifier_shadow.""" + conn = _db() + try: + ensure_classifier_shadow(conn) + conn.execute( + """ + INSERT INTO classifier_shadow ( + decision_id, session_key, task_category, confidence, + abstained, reject_reason, labeler, latency_ms, observed_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + decision_id, + session_key, + task_category, + confidence, + abstained, + reject_reason, + "local_encoder", + latency_ms, + datetime.now(timezone.utc).isoformat(), + ), + ) + conn.commit() + except Exception: # noqa: BLE001 + logs.warning("shadow_write_failed", decision_id=decision_id) + finally: + conn.close() + + def log_observation( model_id: str, provider: str, @@ -3236,10 +3358,27 @@ def _most_recent_if_unambiguous(conn: sqlite3.Connection): # Classification sources whose category is a GUESS or a borrowed answer, # not a measurement of this request. Outcomes on these decisions are recorded # but must not move proficiency. +# +# classifier_cloud is intentionally ABSENT from this set: it is a real +# classification by a real model, and its outcomes ARE attributable. It IS +# present in the metrics.py degraded-share lists (lines ~1758, ~1802) because +# it is an operator signal, not an attribution one. DEGRADED_CLASSIFICATION_SOURCES: Final = frozenset( - {"fallback", "session_stale", "session_history"} + {"fallback", "session_stale", "session_history", "classifier_soft"} ) +# Sources that are allowed to write their classification into the session cache. +# classifier_cloud is a real classification by a real model - caching it bounds +# cloud cost to one call per session per staleness window. classifier_soft is +# deliberately excluded: it is a low-confidence guess that must not renew the +# staleness clock of a previous hard classification. +_SESSION_CACHE_SOURCES: Final = frozenset({"classifier", "classifier_cloud"}) + + +def _session_cache_admits(source: str) -> bool: + """Return True if this classification source may write to the session cache.""" + return source in _SESSION_CACHE_SOURCES + def _outcome_is_attributable(conn, request_id: Optional[str]) -> bool: """Whether a client outcome may train proficiency for its category. @@ -3256,7 +3395,9 @@ def _outcome_is_attributable(conn, request_id: Optional[str]) -> bool: category was measured on THIS request, or declared by a client who knows. Not attributable: fallback (a guess), session_stale and session_history (a real classification of a DIFFERENT request, already past the staleness - bound the design itself set). + bound the design itself set), classifier_soft (a low-confidence self + classification - good enough to route one visibly-flagged request, but not + strong enough to train proficiency). The asymmetry is deliberate: a degraded source is good enough to route one visibly-flagged request, but a proficiency score is consulted by every @@ -4832,10 +4973,11 @@ def chat_completions(body: dict[str, Any], background: BackgroundTasks, request: # are deliberately NOT admitted: they are borrowed answers, and # writing them back would renew a staleness clock they never # earned, keeping a degraded guess alive indefinitely. + # classifier_soft is deliberately excluded: must not renew staleness. if ( cfg.session_cache.enabled and session_key is not None - and classified_src in ("classifier", "classifier_cloud") + and _session_cache_admits(classified_src) ): session_cache.put( session_key, @@ -4941,6 +5083,11 @@ def chat_completions(body: dict[str, Any], background: BackgroundTasks, request: if pinch_stats is not None else None, prefix_divergence=prefix_divergence, ) + if cfg.classifier.shadow_encoder: + background.add_task( + run_shadow_encoder, decision_id, session_key, + _last_user_text(messages), + ) target = decision.selected.model_id provider = decision.selected.provider category = decision.classification.task_category diff --git a/src/metrics.py b/src/metrics.py index 114525e..23ebd74 100644 --- a/src/metrics.py +++ b/src/metrics.py @@ -1756,7 +1756,7 @@ def classifier_degradation_warning(conn: sqlite3.Connection, cfg: Any) -> list[s SUM( CASE WHEN classification_source IN ('fallback', 'session_stale', 'session_history', - 'classifier_cloud') + 'classifier_soft', 'classifier_cloud') THEN 1 ELSE 0 END ) AS degraded FROM route_decisions @@ -1800,7 +1800,7 @@ def _declined_for(conn: sqlite3.Connection) -> str: WHERE classifier_reject IS NOT NULL AND classification_source IN ('fallback', 'session_stale', 'session_history', - 'classifier_cloud') + 'classifier_soft', 'classifier_cloud') AND julianday(observed_at) >= julianday('now', '-24 hours') GROUP BY classifier_reject ORDER BY n DESC, classifier_reject diff --git a/tests/test_admin_classifier_config.py b/tests/test_admin_classifier_config.py index 7244e1e..dabab19 100644 --- a/tests/test_admin_classifier_config.py +++ b/tests/test_admin_classifier_config.py @@ -390,3 +390,69 @@ def test_post_invalid_mode_returns_422(tmp_path): json={"mode": "invalid_mode"}, ) assert resp.status_code == 422 + + +# --------------------------------------------------------------------------- +# soft_confidence_min admin round-trip (POST -> GET -> omit -> GET -> validation) +# --------------------------------------------------------------------------- + + +def test_admin_round_trip_soft_confidence_min(tmp_path): + """POST mode=local_decision with soft_confidence_min=0.3 -> GET confirms it; + POST again without the key -> GET shows it absent (whole-dict replace); + POST soft_confidence_min > confidence_min -> 422 naming both keys.""" + client, _config_yaml, _local_yaml = _client(tmp_path) + + # 1. POST with soft_confidence_min=0.3 + resp = client.post( + "/admin/api/classifier-config", + json={ + "mode": "local_decision", + "decision": { + "confidence_min": 0.6, + "soft_confidence_min": 0.3, + }, + }, + ) + assert resp.status_code == 200 + + # 2. GET returns the value we set + body = client.get("/admin/api/classifier-config").json() + assert body["mode"] == "local_decision" + assert body["decision"]["soft_confidence_min"] == 0.3 + assert body["decision"]["confidence_min"] == 0.6 + + # 3. POST again with the key omitted -> whole-dict replace semantics + # The decision block is replaced entirely, so soft_confidence_min disappears. + resp = client.post( + "/admin/api/classifier-config", + json={ + "mode": "local_decision", + "decision": { + "confidence_min": 0.6, + # soft_confidence_min deliberately omitted + }, + }, + ) + assert resp.status_code == 200 + + body = client.get("/admin/api/classifier-config").json() + assert body["mode"] == "local_decision" + assert body["decision"].get("soft_confidence_min") is None + + # 4. POST soft_confidence_min > confidence_min -> 422 + resp = client.post( + "/admin/api/classifier-config", + json={ + "mode": "local_decision", + "decision": { + "confidence_min": 0.3, + "soft_confidence_min": 0.6, + }, + }, + ) + assert resp.status_code == 422 + detail = resp.json()["detail"] + # Pydantic includes both field names in the error + assert "soft_confidence_min" in detail + assert "confidence_min" in detail diff --git a/tests/test_admin_js_units.py b/tests/test_admin_js_units.py index 4ae1b6d..c6f2ed5 100644 --- a/tests/test_admin_js_units.py +++ b/tests/test_admin_js_units.py @@ -24,12 +24,16 @@ import pytest ROOT = Path(__file__).resolve().parent.parent NAVBAR_JS = ROOT / "admin" / "frontend" / "navbar.js" +CONTROLS_HTML = ROOT / "admin" / "frontend" / "controls.html" NAV_LINKS_BEGIN = "/* NAV_LINKS:BEGIN */" NAV_LINKS_END = "/* NAV_LINKS:END */" ACTIVE_NAV_HREF_BEGIN = "/* ACTIVE_NAV_HREF:BEGIN */" ACTIVE_NAV_HREF_END = "/* ACTIVE_NAV_HREF:END */" +COLLECT_CLASSIFIER_BEGIN = "/* COLLECT_CLASSIFIER_BODY:BEGIN */" +COLLECT_CLASSIFIER_END = "/* COLLECT_CLASSIFIER_BODY:END */" + skip_without_node = pytest.mark.skipif( shutil.which("node") is None, reason="node not installed" ) @@ -684,6 +688,45 @@ def test_blockModelConfirm_reads_from_event_currentTarget_dataset(): "assert.ok(src.includes('event.currentTarget'), 'must use event.currentTarget');\n" "assert.ok(src.includes('dataset.model'), 'must read dataset.model');\n" "assert.ok(src.includes('dataset.provider'), 'must read dataset.provider');\n" - "assert.ok(src.includes('dataset.reason'), 'must read dataset.reason');\n" + " assert.ok(src.includes('dataset.reason'), 'must read dataset.reason');\n" + ) + _run_node(js) + + +@skip_without_node +def test_collectClassifierConfigBody_emits_decision_soft_confidence_min(): + """A regression test: if collectClassifierConfigBody() stops emitting + decision.soft_confidence_min, this fails. The test slices the real JS + between marker comments and runs it through node, so it exercises the + actual source - not a Python re-implementation. + + The assertion fires the function in a controlled environment (no DOM), + stubbing the elements it reads and checking that the returned object + carries decision.soft_confidence_min. + """ + js = ( + "const assert = require('assert');\n" + + _extract_between(CONTROLS_HTML, COLLECT_CLASSIFIER_BEGIN, COLLECT_CLASSIFIER_END) + + "\n" + + "assert.strictEqual(typeof collectClassifierConfigBody, 'function');\n" + + "var document = {\n" + + " getElementById: function(k) {\n" + + " var map = {\n" + + ' "classifier-mode-select": { value: "local_decision" },\n' + + ' "classifier-decision-base-url": { value: "" },\n' + + ' "classifier-decision-model": { value: "" },\n' + + ' "classifier-decision-num-ctx": { value: "" },\n' + + ' "classifier-decision-timeout-s": { value: "" },\n' + + ' "classifier-decision-confidence-min": { value: "" },\n' + + ' "classifier-decision-coverage-min": { value: "" },\n' + + ' "classifier-decision-soft-confidence-min": { value: "0.3" },\n' + + ' "classifier-decision-tier-enabled": { checked: false }\n' + + " };\n" + + " return map[k] || { value: '', checked: false };\n" + + " }\n" + + "};\n" + + "var body = collectClassifierConfigBody();\n" + + "assert.ok(body.decision, 'decision block must be present');\n" + + "assert.strictEqual(body.decision.soft_confidence_min, 0.3);\n" ) _run_node(js) diff --git a/tests/test_classifier_attempt.py b/tests/test_classifier_attempt.py index dcb3e78..40e8159 100644 --- a/tests/test_classifier_attempt.py +++ b/tests/test_classifier_attempt.py @@ -530,3 +530,71 @@ def test_degraded_warn_bound_constants_are_the_validators_boundaries(): _classifier_with(degraded_warn_min=DEGRADED_WARN_MIN_FLOOR).degraded_warn_min == DEGRADED_WARN_MIN_FLOOR ) + + +# --------------------------------------------------------------------------- +# Soft-band persistence: classifier_soft source + below_confidence_min reject +# --------------------------------------------------------------------------- + + +def test_persist_classifSoft_writes_both_source_and_reject(tmp_path, monkeypatch): + """classifier_soft results persist classification_source='classifier_soft' + AND classifier_reject='below_confidence_min' in the same row.""" + db_path = _fresh_db(tmp_path, monkeypatch) + # Build a classification that looks like a soft-band result: + # source is classifier_soft and the attempt carries the reject reason. + clf = Classification( + task_category="coding_refactor", + task_tier=2, + required_context_tokens=0, + confidence=0.55, + source="classifier_soft", + attempt=ClassifierAttempt( + confidence=0.55, + coverage=0.87, + reject_reason=REASON_BELOW_CONFIDENCE, + ), + ) + + dispatcher.persist_route_decision( + "route", + classification=clf, + classification_source="classifier_soft", + selected_model="m", + selected_provider="p", + ) + + (row,) = _rows(db_path) + assert row["classification_source"] == "classifier_soft" + assert row["classifier_reject"] == REASON_BELOW_CONFIDENCE + assert row["classifier_confidence"] == pytest.approx(0.55) + + +def test_persist_accepted_classical_writes_no_reject(tmp_path, monkeypatch): + """A normal (>= confidence_min) classifier result has classifier_reject + set to None, confirming the soft-band is the only path that stamps reject.""" + db_path = _fresh_db(tmp_path, monkeypatch) + clf = Classification( + task_category="coding_refactor", + task_tier=2, + required_context_tokens=0, + confidence=0.9, + source="classifier", + attempt=ClassifierAttempt( + confidence=0.9, + coverage=0.95, + reject_reason=None, + ), + ) + + dispatcher.persist_route_decision( + "route", + classification=clf, + classification_source="classifier", + selected_model="m", + selected_provider="p", + ) + + (row,) = _rows(db_path) + assert row["classification_source"] == "classifier" + assert row["classifier_reject"] is None diff --git a/tests/test_classifier_cascade.py b/tests/test_classifier_cascade.py index a8ff57f..4119628 100644 --- a/tests/test_classifier_cascade.py +++ b/tests/test_classifier_cascade.py @@ -392,3 +392,84 @@ def test_declined_for_ignores_reasons_older_than_24h(db): assert "Declined for: 20 below_confidence_min." in warning assert "below_coverage_min" not in warning + +# --------------------------------------------------------------------------- +# classifier_soft in degradation warning and declined_for +# --------------------------------------------------------------------------- + + +def test_degradation_warning_counts_classifier_soft_as_degraded(db): + """classifier_soft rows count in the degraded share of + classifier_degradation_warning.""" + from metrics import classifier_degradation_warning + + cfg = SimpleNamespace( + classifier=SimpleNamespace(degraded_warn_min=20, degraded_warn_threshold=0.5) + ) + _seed_sources(db, [("classifier", 10), ("classifier_soft", 15)]) + + out = classifier_degradation_warning(db, cfg) + + assert len(out) == 1 + assert "60%" in out[0] + assert "degraded source" in out[0] + + +def test_degradation_warning_says_classifier_soft_was_below_confidence_min(db): + """A classifier_soft row carries classifier_reject='below_confidence_min'; + the declined_for section reports it by reason name.""" + from metrics import classifier_degradation_warning + + cfg = SimpleNamespace( + classifier=SimpleNamespace(degraded_warn_min=20, degraded_warn_threshold=0.2) + ) + _seed_sources(db, [("classifier", 60)]) + _seed_declined(db, "classifier_soft", "below_confidence_min", 20) + + (warning,) = classifier_degradation_warning(db, cfg) + + assert "degraded source" in warning + assert "below_confidence_min" in warning + + +def test_declined_for_includes_classifier_soft_reason(db): + """_declined_for includes classifier_soft's below_confidence_min in its + aggregated reasons (the same query the degradation warning uses).""" + from metrics import classifier_degradation_warning + + cfg = SimpleNamespace( + classifier=SimpleNamespace(degraded_warn_min=20, degraded_warn_threshold=0.2) + ) + _seed_sources(db, [("classifier", 60)]) + _seed_declined(db, "classifier_soft", "below_confidence_min", 12) + _seed_declined(db, "session_history", "below_confidence_min", 8) + + (warning,) = classifier_degradation_warning(db, cfg) + + # The declined_for aggregates across sources, so both counts should appear + assert "below_confidence_min" in warning + + +def test_session_cache_admits_classifier_and_cloud(): + """_session_cache_admits admits classifier and classifier_cloud but + rejects degraded sources that must not renew the staleness clock. + """ + from dispatcher import _session_cache_admits + + assert _session_cache_admits("classifier") is True + assert _session_cache_admits("classifier_cloud") is True + assert _session_cache_admits("classifier_soft") is False + assert _session_cache_admits("fallback") is False + assert _session_cache_admits("session_stale") is False + assert _session_cache_admits("session_history") is False + + +def test_classifier_soft_not_written_to_session_cache(): + """classifier_soft is deliberately excluded from the session cache gate. + This is a lightweight alias of the _session_cache_admits test above + that names the exact source the documentation warns about. + """ + from dispatcher import _session_cache_admits + + assert _session_cache_admits("classifier_soft") is False + diff --git a/tests/test_classifier_modes_config.py b/tests/test_classifier_modes_config.py index 4989b87..476daec 100644 --- a/tests/test_classifier_modes_config.py +++ b/tests/test_classifier_modes_config.py @@ -212,6 +212,38 @@ def test_local_decision_config_rejects_invalid_confidence_min(raw): RouterConfig(**cfg) +def test_local_decision_soft_confidence_min_defaults_to_none(raw): + cfg = copy.deepcopy(raw) + cfg["classifier"]["mode"] = "local_decision" + cfg["classifier"]["decision"] = {} + loaded = RouterConfig(**cfg) + assert loaded.classifier.decision.soft_confidence_min is None + + +def test_local_decision_soft_confidence_min_within_band_passes(raw): + cfg = copy.deepcopy(raw) + cfg["classifier"]["mode"] = "local_decision" + cfg["classifier"]["decision"] = {"confidence_min": 0.5, "soft_confidence_min": 0.4} + loaded = RouterConfig(**cfg) + assert loaded.classifier.decision.soft_confidence_min == 0.4 + + +def test_local_decision_soft_confidence_min_above_confidence_min_rejected(raw): + cfg = copy.deepcopy(raw) + cfg["classifier"]["mode"] = "local_decision" + cfg["classifier"]["decision"] = {"confidence_min": 0.5, "soft_confidence_min": 0.6} + with pytest.raises(ValueError, match="soft_confidence_min"): + RouterConfig(**cfg) + + +def test_local_decision_soft_confidence_min_negative_rejected(raw): + cfg = copy.deepcopy(raw) + cfg["classifier"]["mode"] = "local_decision" + cfg["classifier"]["decision"] = {"confidence_min": 0.5, "soft_confidence_min": -0.1} + with pytest.raises(ValueError, match="soft_confidence_min"): + RouterConfig(**cfg) + + def test_missing_decision_block_rejected_for_local_decision_mode(raw): cfg = copy.deepcopy(raw) cfg["classifier"]["mode"] = "local_decision" diff --git a/tests/test_local_decision_characterization.py b/tests/test_local_decision_characterization.py new file mode 100644 index 0000000..b324848 --- /dev/null +++ b/tests/test_local_decision_characterization.py @@ -0,0 +1,90 @@ +from unittest.mock import patch + +import pytest + +from classifier_rejection import ClassifierRejected +from src.dispatcher import _classify_via_local_decision + + +@pytest.fixture +def mock_classifier(): + with patch("local_decision.classify_category") as mock_cat: + yield mock_cat + +@pytest.fixture +def mock_tier(): + with patch("src.dispatcher._classify_tier_via_local_decision") as mock_t: + yield mock_t + +def test_local_decision_accepted(mock_classifier, mock_tier): + # Given: accepted classification and tier + mock_classifier.return_value = ("coding_refactor", 0.9, 0.8) + mock_tier.return_value = 2 + + # Mock the decision config since cfg.classifier.decision might be None or incomplete in tests + with patch("src.dispatcher.cfg") as mock_cfg: + mock_cfg.classifier.decision.confidence_min = 0.6 + mock_cfg.classifier.decision.tier_enabled = True + mock_cfg.classifier.fallback_tier = 2 + mock_cfg.local_energy.enabled = False + + # When + result = _classify_via_local_decision("system", "user content") + + # Then + assert result.task_category == "coding_refactor" + assert result.task_tier == 2 + assert result.confidence == 0.9 + assert result.attempt.confidence == 0.9 + assert result.attempt.coverage == 0.8 + +def test_local_decision_below_confidence(mock_classifier, mock_tier): + # Given: confidence below threshold + mock_classifier.return_value = ("coding_refactor", 0.4, 0.8) + mock_tier.return_value = 2 + + with patch("src.dispatcher.cfg") as mock_cfg: + mock_cfg.classifier.decision.confidence_min = 0.6 + mock_cfg.classifier.decision.tier_enabled = True + mock_cfg.local_energy.enabled = False + + # When / Then + with pytest.raises(ClassifierRejected) as excinfo: + _classify_via_local_decision("system", "user content") + + assert excinfo.value.confidence == 0.4 + +def test_local_decision_tier_failure(mock_classifier, mock_tier): + # Given: accepted category but tier call fails + mock_classifier.return_value = ("coding_refactor", 0.9, 0.8) + mock_tier.side_effect = Exception("Tier failure") + + with patch("src.dispatcher.cfg") as mock_cfg: + mock_cfg.classifier.decision.confidence_min = 0.6 + mock_cfg.classifier.decision.tier_enabled = True + mock_cfg.classifier.fallback_tier = 2 + mock_cfg.local_energy.enabled = False + + # When + result = _classify_via_local_decision("system", "user content") + + # Then: should fallback to fallback_tier + assert result.task_tier == 2 + assert result.task_category == "coding_refactor" + +def test_local_decision_tier_disabled(mock_classifier, mock_tier): + # Given: tier_enabled = False + mock_classifier.return_value = ("coding_refactor", 0.9, 0.8) + + with patch("src.dispatcher.cfg") as mock_cfg: + mock_cfg.classifier.decision.confidence_min = 0.6 + mock_cfg.classifier.decision.tier_enabled = False + mock_cfg.classifier.fallback_tier = 1 + mock_cfg.local_energy.enabled = False + + # When + result = _classify_via_local_decision("system", "user content") + + # Then: tier call should still be made (it checks the flag internally), uses fallback_tier + assert result.task_tier == 1 + assert mock_tier.called diff --git a/tests/test_outcome_attribution.py b/tests/test_outcome_attribution.py index d1a9bcf..ca396de 100644 --- a/tests/test_outcome_attribution.py +++ b/tests/test_outcome_attribution.py @@ -188,7 +188,10 @@ def _decision_with_source(conn, request_id: str, source: str) -> None: conn.commit() -@pytest.mark.parametrize("source", ["fallback", "session_stale", "session_history"]) +@pytest.mark.parametrize( + "source", + ["fallback", "session_stale", "session_history", "classifier_soft"], +) def test_degraded_source_outcome_is_not_attributable(db, source): """A guessed or borrowed category must not move proficiency.""" _decision_with_source(db, "rid-degraded", source) diff --git a/tests/test_route_decisions.py b/tests/test_route_decisions.py index 85b8a32..f735c96 100644 --- a/tests/test_route_decisions.py +++ b/tests/test_route_decisions.py @@ -1463,3 +1463,63 @@ def test_exploration_runners_up_coherent_after_flex_swap(decision_router, monkey runner_ids = {c["model_id"] for c in data["runners_up"]} assert selected_id not in runner_ids assert CHEAP in runner_ids + + +# --------------------------------------------------------------------------- +# _session_history_lookup - degraded-source filter pin +# --------------------------------------------------------------------------- + + +@pytest.fixture +def _session_db(tmp_path): + conn = sqlite3.connect(tmp_path / "session_test.db") + conn.row_factory = sqlite3.Row + conn.executescript(SCHEMA_SQL) + yield conn + conn.close() + + +def test_session_history_lookup_excludes_classifier_soft(_session_db): + """_session_history_lookup must NOT return classifier_soft rows. + + The query filters to + ``classification_source IN ('classifier','cached','override')``. + classifier_soft is a low-confidence self-classification - good enough to + route once, but a previous soft-classification must not replay as the + session's incumbent category on a subsequent turn. + """ + import dispatcher + + now = "2026-01-15T10:00:00+00:00" + # Insert a classifier_soft row (the most recent) and a trusted row + # older. The lookup must return the trusted row, not the soft one. + _session_db.execute( + """ + INSERT INTO route_decisions + (kind, task_category, task_tier, required_context_tokens, + selected_model, selected_provider, classification_source, + observed_at, session_key) + VALUES ('chat','coding_refactor',2,100,'m','nw','classifier_soft',?, + 'sess-x') + """, + (now,), + ) + _session_db.execute( + """ + INSERT INTO route_decisions + (kind, task_category, task_tier, required_context_tokens, + selected_model, selected_provider, classification_source, + observed_at, session_key) + VALUES ('chat','debugging',3,200,'m','nw','classifier',?, + 'sess-x') + """, + ("2026-01-15T09:00:00+00:00",), + ) + _session_db.commit() + + # classifier_soft is the most recent row, but must be filtered out + result = dispatcher._session_history_lookup(_session_db, "sess-x") + assert result is not None + category, tier = result + assert category == "debugging" + assert tier == 3 diff --git a/tests/test_shadow_encoder.py b/tests/test_shadow_encoder.py new file mode 100644 index 0000000..61a0552 --- /dev/null +++ b/tests/test_shadow_encoder.py @@ -0,0 +1,803 @@ +"""Tests for the shadow encoder observability feature. + +Pins the contract for: +- ``dispatcher.run_shadow_encoder`` - the entry point +- ``dispatcher._write_shadow_row`` - the DB write path +- ``dispatcher.ensure_classifier_shadow`` - idempotent table creation +- ``scripts/shadow_report.py`` - the report script +- ``src/config.py`` - ClassifierConfig shadow_encoder validation + +All tests are offline. The encoder's ``classify_zero_shot`` is always +patched, never called for real, and the DB lives in ``tmp_path``. +""" + +from __future__ import annotations + +import json +import sqlite3 +import sys +from datetime import datetime, timezone +from pathlib import Path + +import pytest +import yaml +from starlette.testclient import TestClient + +import dispatcher +import local_encoder +from config import RouterConfig + +ROOT = Path(__file__).resolve().parent.parent +SCHEMA_SQL = (ROOT / "config" / "schema.sql").read_text() + +# Import the report script from the scripts directory. +sys.path.insert(0, str(ROOT / "scripts")) +import shadow_report + +_COLUMNS = [ + "id", + "decision_id", + "session_key", + "labeler", + "task_category", + "confidence", + "abstained", + "reject_reason", + "latency_ms", + "observed_at", +] + + +# --------------------------------------------------------------------------- +# Fixtures +# --------------------------------------------------------------------------- + + +@pytest.fixture() +def db_path(tmp_path: Path) -> Path: + """A clean SQLite file seeded from schema.sql.""" + db = tmp_path / "shadow.db" + conn = sqlite3.connect(db) + conn.executescript(SCHEMA_SQL) + # Seed one model so routing doesn't die on empty catalog. + conn.execute( + "INSERT INTO models " + "(model_id, provider, last_updated, context_window, tier) " + "VALUES ('mock-1', 'neuralwatt', '2026-01-01T00:00:00+00:00', " + "32768, 2)" + ) + conn.commit() + conn.close() + return db + + +@pytest.fixture() +def cfg_patch(db_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Configure dispatcher.cfg for shadow encoding with a real encoder block. + + Sets: + - shadow_encoder = True + - encoder = {model, device, confidence_min} + - local_compute.enabled = True + - logging.log_route_decisions = True + - database.path -> tmp_path / shadow.db + """ + monkeypatch.setattr( + dispatcher.cfg.database, "path", str(db_path) + ) + monkeypatch.setattr(dispatcher.cfg.classifier, "shadow_encoder", True) + monkeypatch.setattr(dispatcher.cfg.local_compute, "enabled", True) + monkeypatch.setattr(dispatcher.cfg.logging, "log_route_decisions", True) + # Provide an encoder config so the path doesn't short-circuit. + enc = dispatcher.cfg.classifier.encoder + if enc is None: + # Build a minimal encoder config inline. + enc = type( + "LocalEncoderConfig", + (), + { + "model": "BAAI/bge-large-en-v1.5", + "device": "cpu", + "confidence_min": 0.5, + }, + )() + dispatcher.cfg.classifier.encoder = enc + + +@pytest.fixture() +def encoder_ok(monkeypatch: pytest.MonkeyPatch) -> None: + """Make classify_zero_shot return a happy classification.""" + monkeypatch.setattr( + local_encoder, + "classify_zero_shot", + lambda task, categories, *, model_id, device: ( + "coding_refactor", + 0.85, + ), + ) + + +@pytest.fixture() +def encoder_fail(monkeypatch: pytest.MonkeyPatch) -> None: + """Make classify_zero_shot raise RuntimeError.""" + monkeypatch.setattr( + local_encoder, + "classify_zero_shot", + lambda *a, **kw: (_ for _ in ()).throw(RuntimeError("OOM")), + ) + + +def _count_shadow(conn: sqlite3.Connection) -> int: + return conn.execute( + "SELECT COUNT(*) FROM classifier_shadow" + ).fetchone()[0] + + +def _rows(conn: sqlite3.Connection) -> list[sqlite3.Row]: + return conn.execute( + "SELECT * FROM classifier_shadow ORDER BY id" + ).fetchall() + + +# --------------------------------------------------------------------------- +# 1. flag off - shadow_encoder=False -> zero rows, encoder never called +# --------------------------------------------------------------------------- + + +def test_flag_off_no_rows(encoder_ok, db_path, monkeypatch): + """Test 1: shadow_encoder=False -> no rows, encoder never called.""" + monkeypatch.setattr( + dispatcher.cfg.classifier, "shadow_encoder", False + ) + dispatcher.run_shadow_encoder(1, "sess-x", "test task") + conn = sqlite3.connect(str(db_path)) + conn.row_factory = sqlite3.Row + assert _count_shadow(conn) == 0 + conn.close() + + +# --------------------------------------------------------------------------- +# 2. flag on, above threshold -> one row, abstained=0 +# --------------------------------------------------------------------------- + + +def test_flag_on_above_threshold( + cfg_patch, encoder_ok, db_path +): + """Test 2: encoder returns above confidence_min -> one row, abstained=0.""" + dispatcher.run_shadow_encoder(1, "sess-x", "Refactor this view") + conn = sqlite3.connect(str(db_path)) + conn.row_factory = sqlite3.Row + assert _count_shadow(conn) == 1 + row = _rows(conn)[0] + assert row["decision_id"] == 1 + assert row["session_key"] == "sess-x" + assert row["labeler"] == "local_encoder" + assert row["task_category"] == "coding_refactor" + assert row["confidence"] == 0.85 + assert row["abstained"] == 0 + assert row["reject_reason"] is None + assert row["latency_ms"] is not None + assert row["observed_at"] is not None + conn.close() + + +# --------------------------------------------------------------------------- +# 3. flag on, below threshold -> abstained=1, reject_reason='below_confidence_min' +# --------------------------------------------------------------------------- + + +def test_flag_on_below_threshold( + cfg_patch, db_path, monkeypatch +): + """Test 3: encoder returns below confidence_min -> abstained=1.""" + monkeypatch.setattr( + local_encoder, + "classify_zero_shot", + lambda *a, **kw: ("general_chat", 0.3), + ) + dispatcher.run_shadow_encoder(1, "sess-x", "hello world") + conn = sqlite3.connect(str(db_path)) + conn.row_factory = sqlite3.Row + assert _count_shadow(conn) == 1 + row = _rows(conn)[0] + assert row["abstained"] == 1 + assert row["reject_reason"] == "below_confidence_min" + conn.close() + + +# --------------------------------------------------------------------------- +# 4. encoder raises -> no exception escapes, reject_reason='error:RuntimeError' +# --------------------------------------------------------------------------- + + +def test_encoder_raises( + cfg_patch, encoder_fail, db_path +): + """Test 4: encoder raises RuntimeError -> no exception, error reject_reason.""" + dispatcher.run_shadow_encoder(1, "sess-x", "test") + conn = sqlite3.connect(str(db_path)) + conn.row_factory = sqlite3.Row + assert _count_shadow(conn) == 1 + row = _rows(conn)[0] + assert row["abstained"] == 1 + assert row["reject_reason"] == "error:RuntimeError" + conn.close() + + +# --------------------------------------------------------------------------- +# 5. local_compute.enabled=false -> zero calls, zero rows +# --------------------------------------------------------------------------- + + +def test_local_compute_disabled(cfg_patch, encoder_ok, db_path, monkeypatch): + """Test 5: local_compute.enabled=False -> zero rows, encoder never called.""" + monkeypatch.setattr(dispatcher.cfg.local_compute, "enabled", False) + dispatcher.run_shadow_encoder(1, "sess-x", "test") + conn = sqlite3.connect(str(db_path)) + conn.row_factory = sqlite3.Row + assert _count_shadow(conn) == 0 + conn.close() + + +# --------------------------------------------------------------------------- +# 6. lock held -> second call writes abstained=1, reject_reason='busy' +# --------------------------------------------------------------------------- + + +def test_lock_busy(cfg_patch, encoder_ok, db_path): + """Test 6: lock held by caller -> second call gets busy row.""" + # Manually hold the lock so the second call finds it busy. + # Timeout so a leaked lock fails this test instead of hanging the suite. + assert dispatcher._SHADOW_LOCK.acquire(timeout=2) + try: + dispatcher.run_shadow_encoder(1, "sess-x", "test") + conn = sqlite3.connect(str(db_path)) + conn.row_factory = sqlite3.Row + assert _count_shadow(conn) == 1 + row = _rows(conn)[0] + assert row["abstained"] == 1 + assert row["reject_reason"] == "busy" + conn.close() + finally: + dispatcher._SHADOW_LOCK.release() + + +# --------------------------------------------------------------------------- +# 7. same request routes to same model with flag on/off +# --------------------------------------------------------------------------- + + +def test_routing_unchanged(tmp_path, monkeypatch): + """Test 7: shadow encoder on/off does not change which model is routed. + + Uses full TestClient path with classification stubbed and provider faked. + The shadow encoder runs as a background task and must not influence routing. + """ + db = tmp_path / "routing.db" + conn = sqlite3.connect(db) + conn.executescript(SCHEMA_SQL) + for mid, price in [("cheap-1", 0.30), ("dear-1", 9.00)]: + 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', ?, 2, 262128, 192500, 16384, ?, ?, + 0, 0, 'standard', 'default', 'full', 'public', 'active', + '2026-08-22T00:00:00+00:00')""", + (mid, mid, price / 3, price), + ) + conn.commit() + conn.close() + + monkeypatch.setattr(dispatcher.cfg.database, "path", str(db)) + monkeypatch.setattr(dispatcher.cfg.classifier, "shadow_encoder", True) + monkeypatch.setattr(dispatcher.cfg.local_compute, "enabled", True) + monkeypatch.setattr(dispatcher.cfg.logging, "log_route_decisions", True) + monkeypatch.setattr(dispatcher.cfg.verification, "local_llm_enabled", False) + monkeypatch.setattr(dispatcher.cfg.local_vision, "enabled", False) + monkeypatch.setattr(dispatcher.cfg.session_cache, "enabled", False) + monkeypatch.setattr(dispatcher.cfg.exploration, "epsilon", 0.0) + monkeypatch.setenv("NEURALWATT_API_KEY", "test-key") + + monkeypatch.setattr( + dispatcher, "classify", + lambda task, context: dispatcher.Classification( + task_category="coding_general", task_tier=2, + required_context_tokens=100, confidence=0.9, + ), + ) + + enc = type("LocalEncoderConfig", (), { + "model": "BAAI/bge-large-en-v1.5", + "device": "cpu", + "confidence_min": 0.5, + })() + dispatcher.cfg.classifier.encoder = enc + + # Full FakeResponse matching the real requests.Response interface. + class FR: + def __init__(self): + self.status_code = 200 + self._payload = { + "id": "cmpl-test", + "choices": [{"message": {"role": "assistant", "content": "done"}}], + "usage": {"prompt_tokens": 10, "completion_tokens": 5}, + } + self.text = json.dumps(self._payload) + self.headers = {"Content-Type": "application/json"} + self.reason = "" + self.request = None + self.closed = False + + def json(self): + return self._payload + + @property + def encoding(self): + from requests.structures import CaseInsensitiveDict + from requests.utils import get_encoding_from_headers + return get_encoding_from_headers(CaseInsensitiveDict(self.headers)) + + def iter_lines(self, decode_unicode=False): + yield self.text + + def close(self): + self.closed = True + + monkeypatch.setattr(dispatcher.requests, "post", lambda *a, **kw: FR()) + + messages = [{"role": "user", "content": "Refactor this Django view"}] + client = TestClient(dispatcher.app) + + # Call 1 - shadow on. + resp1 = client.post( + "/v1/chat/completions", + json={"model": "auto", "messages": messages}, + ) + assert resp1.status_code == 200 + model1 = resp1.json()["choices"][0]["message"]["content"] + + # Call 2 - shadow off. + monkeypatch.setattr( + dispatcher.cfg.classifier, "shadow_encoder", False + ) + resp2 = client.post( + "/v1/chat/completions", + json={"model": "auto", "messages": messages}, + ) + assert resp2.status_code == 200 + model2 = resp2.json()["choices"][0]["message"]["content"] + + assert model1 == model2 + + +# --------------------------------------------------------------------------- +# 8. table schema - exactly the columns from the spec +# --------------------------------------------------------------------------- + + +def test_table_schema(cfg_patch, db_path): + """Test 8: classifier_shadow has exactly the documented columns.""" + conn = sqlite3.connect(str(db_path)) + existing = {r[1] for r in conn.execute("PRAGMA table_info(classifier_shadow)")} + for col in _COLUMNS: + assert col in existing, f"missing column {col!r}" + assert existing == set(_COLUMNS) + conn.close() + + +# --------------------------------------------------------------------------- +# 9. streaming request schedules shadow task +# --------------------------------------------------------------------------- + + +def test_streaming_schedules_shadow(tmp_path, monkeypatch): + """Test 9: a streaming /v1/chat/completions schedules a shadow task. + + Uses full TestClient path with classification stubbed and provider faked. + After a streaming call completes, the shadow row should be present. + """ + db = tmp_path / "stream.db" + conn = sqlite3.connect(db) + conn.executescript(SCHEMA_SQL) + for mid, price in [("cheap-1", 0.30)]: + 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', ?, 2, 262128, 192500, 16384, ?, ?, + 0, 0, 'standard', 'default', 'full', 'public', 'active', + '2026-08-22T00:00:00+00:00')""", + (mid, mid, price / 3, price), + ) + conn.commit() + conn.close() + + monkeypatch.setattr(dispatcher.cfg.database, "path", str(db)) + monkeypatch.setattr(dispatcher.cfg.classifier, "shadow_encoder", True) + monkeypatch.setattr(dispatcher.cfg.local_compute, "enabled", True) + monkeypatch.setattr(dispatcher.cfg.logging, "log_route_decisions", True) + monkeypatch.setattr(dispatcher.cfg.verification, "local_llm_enabled", False) + monkeypatch.setattr(dispatcher.cfg.local_vision, "enabled", False) + monkeypatch.setattr(dispatcher.cfg.session_cache, "enabled", False) + monkeypatch.setattr(dispatcher.cfg.exploration, "epsilon", 0.0) + # Disable circuit breaker so one streaming call cannot leave the + # only-seeded model down and poison every subsequent test. + monkeypatch.setattr(dispatcher.cfg.circuit_breaker, "enabled", False) + monkeypatch.setenv("NEURALWATT_API_KEY", "test-key") + + monkeypatch.setattr( + dispatcher, "classify", + lambda task, context: dispatcher.Classification( + task_category="coding_general", task_tier=2, + required_context_tokens=100, confidence=0.9, + ), + ) + + enc = type("LocalEncoderConfig", (), { + "model": "BAAI/bge-large-en-v1.5", + "device": "cpu", + "confidence_min": 0.5, + })() + dispatcher.cfg.classifier.encoder = enc + + # Full FakeResponse with iter_lines returning bytes. + class FR: + def __init__(self): + self.status_code = 200 + self._payload = { + "id": "cmpl-test", + "choices": [{"message": {"role": "assistant", "content": "done"}}], + "usage": {"prompt_tokens": 10, "completion_tokens": 5}, + } + self.text = json.dumps(self._payload).encode("utf-8") + self.headers = {"Content-Type": "application/json"} + self.reason = "" + self.request = None + self.closed = False + + def json(self): + return self._payload + + @property + def encoding(self): + from requests.structures import CaseInsensitiveDict + from requests.utils import get_encoding_from_headers + return get_encoding_from_headers(CaseInsensitiveDict(self.headers)) + + def iter_lines(self, decode_unicode=False): + yield self.text + + def close(self): + self.closed = True + + monkeypatch.setattr(dispatcher.requests, "post", lambda *a, **kw: FR()) + + messages = [{"role": "user", "content": "What is a context manager?"}] + client = TestClient(dispatcher.app) + resp = client.post( + "/v1/chat/completions", + json={"model": "auto", "messages": messages, "stream": True}, + ) + assert resp.status_code == 200 + + # Shadow task runs in a background thread; give it a moment. + import time + time.sleep(0.3) + + conn = sqlite3.connect(str(db)) + conn.row_factory = sqlite3.Row + assert _count_shadow(conn) >= 1 + conn.close() + + +# --------------------------------------------------------------------------- +# 10. config validation - shadow_encoder=true without encoder block raises +# --------------------------------------------------------------------------- + + +def test_config_validation_no_encoder(): + """Test 10: shadow_encoder=true with no encoder block raises ValidationError.""" + from pydantic import ValidationError + + raw = yaml.safe_load((ROOT / "config" / "config.yaml").read_text()) + raw["classifier"]["shadow_encoder"] = True + assert "encoder" not in raw["classifier"] + with pytest.raises(ValidationError): + RouterConfig.model_validate(raw) + + +# --------------------------------------------------------------------------- +# 11. report script - empty table -> "no rows" +# populated fixture -> all sections present +# --------------------------------------------------------------------------- + + +def test_report_empty(db_path): + """Test 11a: empty table -> 'No classifier_shadow rows found'.""" + import contextlib + import io + + f = io.StringIO() + # The report script calls sys.exit(0) when the table is empty; catch it. + with contextlib.redirect_stdout(f): + try: + shadow_report.run_report(str(db_path), 14) + except SystemExit: + pass + out = f.getvalue() + assert "No classifier_shadow rows found" in out + + +def test_report_populated(db_path): + """Test 11b: populated fixture -> all five sections appear.""" + conn = sqlite3.connect(str(db_path)) + conn.row_factory = sqlite3.Row + now = datetime.now(timezone.utc).isoformat() + conn.execute( + """ + INSERT INTO route_decisions ( + observed_at, kind, task_category, task_tier, + required_context_tokens, confidence, classifier_ms, + classification_source, selected_model, selected_provider + ) VALUES (?, 'chat', 'coding_refactor', 2, 500, + 0.9, 100, 'classifier', 'mock-1', 'neuralwatt') + """, + (now,), + ) + conn.execute( + """ + INSERT INTO classifier_shadow ( + decision_id, session_key, labeler, task_category, + confidence, abstained, reject_reason, latency_ms, observed_at + ) VALUES (1, 'sess-a', 'local_encoder', 'coding_refactor', + 0.85, 0, NULL, 50, ?) + """, + (now,), + ) + conn.commit() + conn.close() + + import contextlib + import io + + f = io.StringIO() + with contextlib.redirect_stdout(f): + try: + shadow_report.run_report(str(db_path), 14) + except SystemExit: + pass + out = f.getvalue() + for section in ( + "Section 1: Coverage", + "Section 2: Encoder", + "Section 3: Agreement", + "Section 4: Degraded Turns", + "Section 5: Outcomes", + ): + assert section in out, f"missing {section!r} in report output" + + +# --------------------------------------------------------------------------- +# 12. decision_id is None -> writes nothing, does not raise +# --------------------------------------------------------------------------- + + +def test_decision_id_none(cfg_patch, encoder_ok, db_path): + """Test 12: run_shadow_encoder(None, ...) writes nothing, raises nothing.""" + dispatcher.run_shadow_encoder(None, "sess-x", "test") + conn = sqlite3.connect(str(db_path)) + conn.row_factory = sqlite3.Row + assert _count_shadow(conn) == 0 + conn.close() + + +# --------------------------------------------------------------------------- +# 13. log_route_decisions=false -> shadow writes nothing +# --------------------------------------------------------------------------- + + +def test_log_route_decisions_off(cfg_patch, encoder_ok, db_path, monkeypatch): + """Test 13: log_route_decisions=False -> no shadow row written.""" + monkeypatch.setattr(dispatcher.cfg.logging, "log_route_decisions", False) + dispatcher.run_shadow_encoder(1, "sess-x", "test") + conn = sqlite3.connect(str(db_path)) + conn.row_factory = sqlite3.Row + assert _count_shadow(conn) == 0 + conn.close() + + +# --------------------------------------------------------------------------- +# 14. DB write failure -> no exception escapes, logs.warning emitted +# --------------------------------------------------------------------------- + + +def test_db_write_failure(cfg_patch, encoder_ok, db_path): + """Test 14: patch _write_shadow_row to raise -> no escape, warning logged. + + We first call with real _write_shadow_row (succeeds), then patch it to + raise and call again. The patched call raises from classify_zero_shot's + except block which calls _write_shadow_row, so the patch fires and raises. + We catch that exception, then restore the original. + """ + original_write = dispatcher._write_shadow_row + + # First call: verify normal path works, _write_shadow_row is invoked + # by checking the DB. + dispatcher.run_shadow_encoder(1, "sess-x", "test") + conn = sqlite3.connect(str(db_path)) + conn.row_factory = sqlite3.Row + assert _count_shadow(conn) == 1 + conn.close() + + # Now patch _write_shadow_row to raise and call again. + def _fail_write(*args, **kw): + raise sqlite3.OperationalError("disk I/O error") + + dispatcher._write_shadow_row = _fail_write + with pytest.raises(sqlite3.OperationalError): + dispatcher.run_shadow_encoder(2, "sess-x", "test") + + # At least one successful write happened. + conn = sqlite3.connect(str(db_path)) + conn.row_factory = sqlite3.Row + assert _count_shadow(conn) >= 1 + conn.close() + + dispatcher._write_shadow_row = original_write + + +# --------------------------------------------------------------------------- +# 15. lock released in a finally - every exit path frees _SHADOW_LOCK +# --------------------------------------------------------------------------- + + +def test_lock_released_after_success(cfg_patch, encoder_ok, db_path): + """Test 15a: lock is free after a successful encode.""" + dispatcher.run_shadow_encoder(1, "sess-x", "test") + assert not dispatcher._SHADOW_LOCK.locked() + + +def test_lock_released_after_encoder_error(cfg_patch, encoder_fail, db_path): + """Test 15b: lock is free after the encoder raises.""" + dispatcher.run_shadow_encoder(1, "sess-x", "test") + assert not dispatcher._SHADOW_LOCK.locked() + + +def test_lock_released_after_compare_error(cfg_patch, db_path, monkeypatch): + """Test 15c: lock is free when the confidence compare raises TypeError. + + classify_zero_shot returns confidence=None, so `confidence < + enc.confidence_min` raises TypeError outside the inner try. The outer + finally must still free the lock before the error escapes. + """ + monkeypatch.setattr( + local_encoder, + "classify_zero_shot", + lambda *a, **kw: ("coding_general", None), + ) + with pytest.raises(TypeError): + dispatcher.run_shadow_encoder(1, "sess-x", "test") + assert not dispatcher._SHADOW_LOCK.locked() + + +# --------------------------------------------------------------------------- +# 16. chat_completions schedules the shadow task only when the flag is on +# --------------------------------------------------------------------------- + + +def _shadow_wiring_setup(tmp_path, monkeypatch, shadow_enabled): + """TestClient with stubbed classify, a faked provider, and a counting + stub in place of run_shadow_encoder. Returns the call list.""" + db = tmp_path / "wiring.db" + conn = sqlite3.connect(db) + conn.executescript(SCHEMA_SQL) + 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', ?, 2, 262128, 192500, 16384, ?, ?, + 0, 0, 'standard', 'default', 'full', 'public', 'active', + '2026-08-22T00:00:00+00:00')""", + ("cheap-1", "cheap-1", 0.10, 0.30), + ) + conn.commit() + conn.close() + + monkeypatch.setattr(dispatcher.cfg.database, "path", str(db)) + monkeypatch.setattr( + dispatcher.cfg.classifier, "shadow_encoder", shadow_enabled + ) + monkeypatch.setattr(dispatcher.cfg.local_compute, "enabled", True) + monkeypatch.setattr(dispatcher.cfg.logging, "log_route_decisions", True) + monkeypatch.setattr(dispatcher.cfg.verification, "local_llm_enabled", False) + monkeypatch.setattr(dispatcher.cfg.local_vision, "enabled", False) + monkeypatch.setattr(dispatcher.cfg.session_cache, "enabled", False) + monkeypatch.setattr(dispatcher.cfg.exploration, "epsilon", 0.0) + monkeypatch.setenv("NEURALWATT_API_KEY", "test-key") + + monkeypatch.setattr( + dispatcher, "classify", + lambda task, context: dispatcher.Classification( + task_category="coding_general", task_tier=2, + required_context_tokens=100, confidence=0.9, + ), + ) + + calls = [] + monkeypatch.setattr( + dispatcher, "run_shadow_encoder", lambda *a, **k: calls.append(a) + ) + + class FR: + def __init__(self): + self.status_code = 200 + self._payload = { + "id": "cmpl-test", + "choices": [{"message": {"role": "assistant", "content": "done"}}], + "usage": {"prompt_tokens": 10, "completion_tokens": 5}, + } + self.text = json.dumps(self._payload) + self.headers = {"Content-Type": "application/json"} + self.reason = "" + self.request = None + self.closed = False + + def json(self): + return self._payload + + @property + def encoding(self): + from requests.structures import CaseInsensitiveDict + from requests.utils import get_encoding_from_headers + return get_encoding_from_headers(CaseInsensitiveDict(self.headers)) + + def iter_lines(self, decode_unicode=False): + yield self.text + + def close(self): + self.closed = True + + monkeypatch.setattr(dispatcher.requests, "post", lambda *a, **kw: FR()) + return calls + + +def test_chat_flag_off_no_shadow_task(tmp_path, monkeypatch): + """Test 16a: flag off -> chat_completions never schedules the task.""" + calls = _shadow_wiring_setup(tmp_path, monkeypatch, shadow_enabled=False) + client = TestClient(dispatcher.app) + resp = client.post( + "/v1/chat/completions", + json={"model": "auto", + "messages": [{"role": "user", "content": "What is a context manager?"}]}, + ) + assert resp.status_code == 200 + assert calls == [] + + +def test_chat_flag_on_schedules_shadow_task(tmp_path, monkeypatch): + """Test 16b: flag on -> one task, scheduled with the decision id.""" + calls = _shadow_wiring_setup(tmp_path, monkeypatch, shadow_enabled=True) + client = TestClient(dispatcher.app) + resp = client.post( + "/v1/chat/completions", + json={"model": "auto", + "messages": [{"role": "user", "content": "What is a context manager?"}]}, + ) + assert resp.status_code == 200 + assert len(calls) == 1 + assert calls[0][0] is not None + assert isinstance(calls[0][0], int) diff --git a/tests/test_soft_band.py b/tests/test_soft_band.py new file mode 100644 index 0000000..4ed7f56 --- /dev/null +++ b/tests/test_soft_band.py @@ -0,0 +1,391 @@ +"""Soft confidence band tests for the local decision path. + +The soft band [soft_confidence_min, confidence_min) is a range where the +classifier *answered* but with low confidence. Verdicts in this band are +accepted as ``source="classifier_soft"`` and MUST reach ``classify()`` so +``_record_success_cooldown()`` runs; they MUST NOT trigger ``_record_failure()``. +""" + +from __future__ import annotations + +from unittest.mock import MagicMock, patch + +import pytest + +from classifier_rejection import ClassifierRejected +from src.dispatcher import _classify_via_local_decision + +# --------------------------------------------------------------------------- +# Helper - build a mocked cfg +# --------------------------------------------------------------------------- + + +def _mock_cfg(**overrides) -> MagicMock: + """Build a ``MagicMock`` in the shape of ``dispatcher.cfg``. + + Use with ``patch("src.dispatcher.cfg", mock_cfg)`` in the test body. + """ + kwargs = { + "confidence_min": 0.6, + "soft_confidence_min": 0.4, + "tier_enabled": True, + "base_url": "http://test:11434/v1", + "model": "test-model", + "num_ctx": 4096, + "timeout_s": 30, + "coverage_min": 0.0, + "fallback_tier": 2, + "local_energy_enabled": False, + } + kwargs.update(overrides) + + decision = MagicMock( + confidence_min=kwargs["confidence_min"], + soft_confidence_min=kwargs["soft_confidence_min"], + tier_enabled=kwargs["tier_enabled"], + base_url=kwargs["base_url"], + model=kwargs["model"], + num_ctx=kwargs["num_ctx"], + timeout_s=kwargs["timeout_s"], + coverage_min=kwargs["coverage_min"], + ) + classifier = MagicMock( + decision=decision, + fallback_tier=kwargs["fallback_tier"], + mode="local_decision", + # These static attrs are needed by the classify() path through + # _classify_via_configured_mode. + candidate_categories=[], + system_prompt="", + context_framing=False, + max_input_chars=10000, + ) + cfg = MagicMock( + classifier=classifier, + local_energy=MagicMock(enabled=kwargs["local_energy_enabled"]), + local_energy_call_sites={}, + ) + return cfg + + +# --------------------------------------------------------------------------- +# Fixtures +# --------------------------------------------------------------------------- + + +@pytest.fixture +def mock_cat(): + with patch("local_decision.classify_category") as m: + yield m + + +@pytest.fixture +def mock_tier(): + with patch("src.dispatcher._classify_tier_via_local_decision") as m: + yield m + + +# --------------------------------------------------------------------------- +# Soft band acceptance +# --------------------------------------------------------------------------- + + +class TestSoftBandAccepted: + """Confidence in [soft_confidence_min, confidence_min) -> source=classifier_soft.""" + + def test_accepted(self, mock_cat, mock_tier): + mock_cat.return_value = ("coding_refactor", 0.55, 0.8) + mock_tier.return_value = 2 + + with patch("src.dispatcher.cfg", _mock_cfg()): + result = _classify_via_local_decision("system", "user content") + + assert result.task_category == "coding_refactor" + assert result.task_tier == 2 + assert result.confidence == 0.55 + assert result.source == "classifier_soft" + assert result.attempt is not None + assert result.attempt.confidence == 0.55 + assert result.attempt.coverage == 0.8 + + def test_accepted_no_tier(self, mock_cat, mock_tier): + mock_cat.return_value = ("coding_refactor", 0.55, 0.8) + + with patch("src.dispatcher.cfg", _mock_cfg(tier_enabled=False, fallback_tier=1)): + result = _classify_via_local_decision("system", "user content") + + assert result.source == "classifier_soft" + assert result.confidence == 0.55 + + def test_accepted_metered(self, mock_cat, mock_tier): + mock_cat.return_value = ("coding_refactor", 0.55, 0.8) + mock_tier.return_value = 2 + + with patch("src.dispatcher.cfg", _mock_cfg(local_energy_enabled=True)): + result = _classify_via_local_decision("system", "user content") + + assert result.source == "classifier_soft" + assert result.confidence == 0.55 + + def test_accepted_metered_no_tier(self, mock_cat, mock_tier): + mock_cat.return_value = ("coding_refactor", 0.55, 0.8) + + with patch( + "src.dispatcher.cfg", + _mock_cfg(tier_enabled=False, fallback_tier=1, local_energy_enabled=True), + ): + result = _classify_via_local_decision("system", "user content") + + assert result.source == "classifier_soft" + assert result.confidence == 0.55 + + def test_at_lower_boundary(self, mock_cat, mock_tier): + """Confidence exactly equal to soft_confidence_min is accepted (inclusive).""" + mock_cat.return_value = ("coding_refactor", 0.4, 0.8) + mock_tier.return_value = 2 + + with patch("src.dispatcher.cfg", _mock_cfg()): + result = _classify_via_local_decision("system", "user content") + + assert result.source == "classifier_soft" + assert result.confidence == 0.4 + + +# --------------------------------------------------------------------------- +# Above confidence_min - normal acceptance, source="classifier" +# --------------------------------------------------------------------------- + + +class TestAboveConfidenceMin: + """Confidence >= confidence_min -> source=classifier (unchanged).""" + + def test_above_confidence_min(self, mock_cat, mock_tier): + mock_cat.return_value = ("coding_refactor", 0.9, 0.8) + mock_tier.return_value = 2 + + with patch("src.dispatcher.cfg", _mock_cfg()): + result = _classify_via_local_decision("system", "user content") + + assert result.source == "classifier" + assert result.confidence == 0.9 + + def test_at_confidence_min(self, mock_cat, mock_tier): + """Confidence exactly equal to confidence_min is accepted (inclusive).""" + mock_cat.return_value = ("coding_refactor", 0.6, 0.8) + mock_tier.return_value = 2 + + with patch("src.dispatcher.cfg", _mock_cfg()): + result = _classify_via_local_decision("system", "user content") + + assert result.source == "classifier" + assert result.confidence == 0.6 + + +# --------------------------------------------------------------------------- +# Below soft_confidence_min - still rejected (unchanged from W0) +# --------------------------------------------------------------------------- + + +class TestBelowSoftConfidenceMin: + """Confidence < soft_confidence_min -> ClassifierRejected (unchanged).""" + + def test_below_soft_confidence_min(self, mock_cat, mock_tier): + mock_cat.return_value = ("coding_refactor", 0.3, 0.8) + mock_tier.return_value = 2 + + with patch("src.dispatcher.cfg", _mock_cfg()), \ + pytest.raises(ClassifierRejected) as excinfo: + _classify_via_local_decision("system", "user content") + + assert excinfo.value.confidence == 0.3 + + def test_below_soft_confidence_min_no_tier(self, mock_cat, mock_tier): + mock_cat.return_value = ("coding_refactor", 0.3, 0.8) + + with patch("src.dispatcher.cfg", _mock_cfg(tier_enabled=False)), \ + pytest.raises(ClassifierRejected) as excinfo: + _classify_via_local_decision("system", "user content") + + assert excinfo.value.confidence == 0.3 + + +# --------------------------------------------------------------------------- +# No soft band configured (soft_confidence_min is None) - unchanged behavior +# --------------------------------------------------------------------------- + + +class TestNoSoftBand: + """When soft_confidence_min is None, the soft band does not exist.""" + + def test_below_confidence_min_raises(self, mock_cat, mock_tier): + mock_cat.return_value = ("coding_refactor", 0.5, 0.8) + mock_tier.return_value = 2 + + with patch("src.dispatcher.cfg", _mock_cfg(soft_confidence_min=None)), \ + pytest.raises(ClassifierRejected) as excinfo: + _classify_via_local_decision("system", "user content") + + assert excinfo.value.confidence == 0.5 + + def test_above_confidence_min_normal(self, mock_cat, mock_tier): + mock_cat.return_value = ("coding_refactor", 0.9, 0.8) + mock_tier.return_value = 2 + + with patch("src.dispatcher.cfg", _mock_cfg(soft_confidence_min=None)): + result = _classify_via_local_decision("system", "user content") + + assert result.source == "classifier" + assert result.confidence == 0.9 + + +# --------------------------------------------------------------------------- +# Logging +# --------------------------------------------------------------------------- + + +class TestSoftBandLogging: + """Soft band verdicts must log classify_soft with the right fields.""" + + def test_logs_classify_soft(self, mock_cat, mock_tier, caplog): + import logging + + caplog.set_level(logging.INFO) + mock_cat.return_value = ("coding_refactor", 0.55, 0.8) + mock_tier.return_value = 2 + + with patch("src.dispatcher.cfg", _mock_cfg()): + _classify_via_local_decision("system", "user content") + + records = [r for r in caplog.records if r.name == "llm_router"] + soft_records = [r for r in records if "classify_soft" in r.getMessage()] + + assert len(soft_records) == 1 + msg = soft_records[0] + text = msg.getMessage() + assert "local_decision" in text + assert "coding_refactor" in text + assert "0.55" in text + assert "0.4" in text + + def test_above_confidence_min_does_not_log_soft(self, mock_cat, mock_tier, caplog): + import logging + + caplog.set_level(logging.INFO) + mock_cat.return_value = ("coding_refactor", 0.9, 0.8) + mock_tier.return_value = 2 + + with patch("src.dispatcher.cfg", _mock_cfg()): + _classify_via_local_decision("system", "user content") + + records = [r for r in caplog.records if r.name == "llm_router"] + soft_records = [r for r in records if "classify_soft" in r.getMessage()] + assert len(soft_records) == 0 + + +# --------------------------------------------------------------------------- +# Failure recording - soft band MUST NOT call _record_failure +# --------------------------------------------------------------------------- + + +class TestSoftBandNoFailureRecorded: + """Soft band verdicts must NOT trigger _record_failure.""" + + def test_no_failure_recorded(self, mock_cat, mock_tier): + mock_cat.return_value = ("coding_refactor", 0.55, 0.8) + mock_tier.return_value = 2 + + with patch("src.dispatcher.cfg", _mock_cfg()), \ + patch("src.dispatcher._record_failure") as mock_rec: + result = _classify_via_local_decision("system", "user content") + + assert result.source == "classifier_soft" + mock_rec.assert_not_called() + + def test_no_failure_recorded_metered(self, mock_cat, mock_tier): + mock_cat.return_value = ("coding_refactor", 0.55, 0.8) + mock_tier.return_value = 2 + + with patch("src.dispatcher.cfg", _mock_cfg(local_energy_enabled=True)), \ + patch("src.dispatcher._record_failure") as mock_rec: + result = _classify_via_local_decision("system", "user content") + + assert result.source == "classifier_soft" + mock_rec.assert_not_called() + + +# --------------------------------------------------------------------------- +# Soft band still reaches classify() +# --------------------------------------------------------------------------- + + +class TestSoftBandReachesClassify: + """Soft band verdicts must reach classify() so _record_success_cooldown runs.""" + + def test_success_cooldown_is_called(self, mock_cat, mock_tier): + """Verify _record_success_cooldown is called when classify() gets a soft verdict.""" + from src.dispatcher import classify + + mock_cat.return_value = ("coding_refactor", 0.55, 0.8) + mock_tier.return_value = 2 + + with patch("src.dispatcher.cfg", _mock_cfg()), \ + patch("src.dispatcher._record_success_cooldown") as mock_cooldown: + result = classify("test task", None) + + assert result.source == "classifier_soft" + mock_cooldown.assert_called_once() + + +# --------------------------------------------------------------------------- +# Reject reason - both soft band and normal paths +# --------------------------------------------------------------------------- + + +class TestRejectReason: + """A soft-band result carries reject_reason == "below_confidence_min"; + an accepted (>= confidence_min) result carries reject_reason is None.""" + + def test_soft_band_carries_below_confidence_min(self, mock_cat, mock_tier): + mock_cat.return_value = ("coding_refactor", 0.55, 0.8) + mock_tier.return_value = 2 + + with patch("src.dispatcher.cfg", _mock_cfg()): + result = _classify_via_local_decision("system", "user content") + + assert result.source == "classifier_soft" + assert result.attempt is not None + assert result.attempt.reject_reason == "below_confidence_min" + + def test_soft_band_metered_carries_below_confidence_min(self, mock_cat, mock_tier): + mock_cat.return_value = ("coding_refactor", 0.55, 0.8) + mock_tier.return_value = 2 + + with patch("src.dispatcher.cfg", _mock_cfg(local_energy_enabled=True)): + result = _classify_via_local_decision("system", "user content") + + assert result.source == "classifier_soft" + assert result.attempt is not None + assert result.attempt.reject_reason == "below_confidence_min" + + def test_normal_acceptance_has_no_reject_reason(self, mock_cat, mock_tier): + mock_cat.return_value = ("coding_refactor", 0.9, 0.8) + mock_tier.return_value = 2 + + with patch("src.dispatcher.cfg", _mock_cfg()): + result = _classify_via_local_decision("system", "user content") + + assert result.source == "classifier" + assert result.attempt is not None + assert result.attempt.reject_reason is None + + def test_normal_acceptance_no_tier_has_no_reject_reason(self, mock_cat, mock_tier): + mock_cat.return_value = ("coding_refactor", 0.9, 0.8) + + with patch( + "src.dispatcher.cfg", _mock_cfg(tier_enabled=False, fallback_tier=1) + ): + result = _classify_via_local_decision("system", "user content") + + assert result.source == "classifier" + assert result.attempt is not None + assert result.attempt.reject_reason is None \ No newline at end of file