From 06b5d77e826f323ab76920f94ae75dc3e60728ee Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Fri, 9 Oct 2026 23:33:59 -0400 Subject: [PATCH 01/33] test: add characterization tests for local decision Pin current behavior of _classify_via_local_decision for accepted turn, below-confidence turn, tier call failing, and tier_enabled=False. --- tests/test_local_decision_characterization.py | 88 +++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 tests/test_local_decision_characterization.py diff --git a/tests/test_local_decision_characterization.py b/tests/test_local_decision_characterization.py new file mode 100644 index 0000000..0ee7ffb --- /dev/null +++ b/tests/test_local_decision_characterization.py @@ -0,0 +1,88 @@ +import pytest +from unittest.mock import patch +from src.dispatcher import _classify_via_local_decision +from classifier_rejection import ClassifierRejected + + +@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 -- 2.49.1 From ea88c1f09b9ef8c63ee349e47ac15403219dbf48 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Fri, 9 Oct 2026 23:36:04 -0400 Subject: [PATCH 02/33] test: add characterization tests for local decision --- tests/test_local_decision_characterization.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_local_decision_characterization.py b/tests/test_local_decision_characterization.py index 0ee7ffb..8a039ac 100644 --- a/tests/test_local_decision_characterization.py +++ b/tests/test_local_decision_characterization.py @@ -1,7 +1,7 @@ import pytest from unittest.mock import patch -from src.dispatcher import _classify_via_local_decision from classifier_rejection import ClassifierRejected +from src.dispatcher import _classify_via_local_decision @pytest.fixture -- 2.49.1 From def5ff45ca8b6f55e23dc401764bc2541a5a6e23 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Fri, 9 Oct 2026 23:36:04 -0400 Subject: [PATCH 03/33] refactor: extract local decision verdict helper --- src/dispatcher.py | 161 ++++++++++++++++++---------------------------- 1 file changed, 64 insertions(+), 97 deletions(-) diff --git a/src/dispatcher.py b/src/dispatcher.py index 9e4eb5f..a150ce7 100644 --- a/src/dispatcher.py +++ b/src/dispatcher.py @@ -1165,6 +1165,68 @@ def _classify_via_local_encoder(task: str) -> Classification: ) +def _get_local_decision_verdict( + user_content: str, +) -> tuple[str, float, float, int]: + """Classify category (and optionally tier) via local_decision. + + Returns ``(category, confidence, coverage, tier)``. + Raises ``ClassifierRejected`` when confidence is below the threshold + (``_below_confidence``), exactly as the two call sites in + ``_classify_via_local_decision`` did before extraction. + """ + dec = cfg.classifier.decision + 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) + return category, confidence, coverage, tier + + def _classify_via_local_decision( system_prompt: str, user_content: str ) -> Classification: @@ -1199,55 +1261,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 = _get_local_decision_verdict(user_content) _log_local_energy( model_id=dec.model, @@ -1279,54 +1293,7 @@ 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 = _get_local_decision_verdict(user_content) return Classification( task_category=category, task_tier=tier, -- 2.49.1 From 9c429388cbb149e820534a17b0f3a367f0604fa0 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Fri, 9 Oct 2026 23:45:03 -0400 Subject: [PATCH 04/33] feat: add soft_confidence_min knob to LocalDecisionConfig --- src/config.py | 18 +++++++++++++++ tests/test_admin_knob_coverage.py | 7 ++++++ tests/test_classifier_modes_config.py | 32 +++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) diff --git a/src/config.py b/src/config.py index c00e3e6..5e26210 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 diff --git a/tests/test_admin_knob_coverage.py b/tests/test_admin_knob_coverage.py index 8f74b4a..20018ea 100644 --- a/tests/test_admin_knob_coverage.py +++ b/tests/test_admin_knob_coverage.py @@ -384,6 +384,13 @@ DELIBERATELY_NOT_IN_ADMIN: dict[str, str] = { "for a future feature that is not implemented anywhere outside " "config.py -- no admin control because it would control nothing real." ), + "classifier.decision.soft_confidence_min": ( + "Wave-1 config knob for the soft confidence band: shipped OFF (None) " + "and inert, read by nothing until a later wave wires the band into " + "the local decision verdict. An admin toggle would control nothing " + "real until then; it gets a control with the wave that wires it " + "(same logic as classifier.encoder.tier_from_features above)." + ), # --- deployment wiring: set in config, never in admin -------------------- "watchdog.dashboard_base_url": ( "deployment wiring, set in config, not admin" 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" -- 2.49.1 From 52429158bf49d952c60241ee97c561bf98aaae7d Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Fri, 9 Oct 2026 23:57:47 -0400 Subject: [PATCH 05/33] feat: implement soft confidence band logic --- src/dispatcher.py | 69 +++++++-- tests/test_soft_band.py | 336 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 395 insertions(+), 10 deletions(-) create mode 100644 tests/test_soft_band.py diff --git a/src/dispatcher.py b/src/dispatcher.py index a150ce7..069dacb 100644 --- a/src/dispatcher.py +++ b/src/dispatcher.py @@ -291,6 +291,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 @@ -1171,11 +1174,20 @@ def _get_local_decision_verdict( """Classify category (and optionally tier) via local_decision. Returns ``(category, confidence, coverage, tier)``. - Raises ``ClassifierRejected`` when confidence is below the threshold - (``_below_confidence``), exactly as the two call sites in - ``_classify_via_local_decision`` did before extraction. + 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 (MagicMock auto-creates + # attributes, returning a MagicMock which is not a number). + _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 @@ -1194,12 +1206,12 @@ def _get_local_decision_verdict( _classify_tier_via_local_decision, user_content ) category, confidence, coverage = cat_future.result() - if confidence < dec.confidence_min: + if confidence < _floor: raise _below_confidence( "local_decision", "decision", confidence, - dec.confidence_min, + _floor, coverage, ) try: @@ -1215,12 +1227,12 @@ def _get_local_decision_verdict( timeout_s=dec.timeout_s, coverage_min=dec.coverage_min, ) - if confidence < dec.confidence_min: + if confidence < _floor: raise _below_confidence( "local_decision", "decision", confidence, - dec.confidence_min, + _floor, coverage, ) tier = _classify_tier_via_local_decision(user_content) @@ -1263,6 +1275,25 @@ def _classify_via_local_decision( ) as measurement: category, confidence, coverage, tier = _get_local_decision_verdict(user_content) + # Detect soft band: classifier answered but confidence landed + # in [soft_confidence_min, confidence_min). + _soft_raw = getattr(dec, "soft_confidence_min", None) + _soft_min = _soft_raw if isinstance(_soft_raw, (int, float)) else None + _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=dec.confidence_min, + ) + _source = "classifier_soft" + _log_local_energy( model_id=dec.model, call_type="classify", @@ -1273,7 +1304,7 @@ def _classify_via_local_decision( task_tier=tier, required_context_tokens=0, confidence=confidence, - source="classifier", + source=_source, attempt=ClassifierAttempt( confidence=confidence, coverage=coverage ), @@ -1294,12 +1325,30 @@ def _classify_via_local_decision( # cooldown_seconds on healthy traffic. try: category, confidence, coverage, tier = _get_local_decision_verdict(user_content) + # Detect soft band: classifier answered but confidence landed + # in [soft_confidence_min, confidence_min). + _soft_raw = getattr(dec, "soft_confidence_min", None) + _soft_min = _soft_raw if isinstance(_soft_raw, (int, float)) else None + _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=dec.confidence_min, + ) + _source = "classifier_soft" return Classification( task_category=category, task_tier=tier, required_context_tokens=0, confidence=confidence, - source="classifier", + source=_source, attempt=ClassifierAttempt( confidence=confidence, coverage=coverage ), @@ -3204,7 +3253,7 @@ def _most_recent_if_unambiguous(conn: sqlite3.Connection): # not a measurement of this request. Outcomes on these decisions are recorded # but must not move proficiency. DEGRADED_CLASSIFICATION_SOURCES: Final = frozenset( - {"fallback", "session_stale", "session_history"} + {"fallback", "session_stale", "session_history", "classifier_soft"} ) diff --git a/tests/test_soft_band.py b/tests/test_soft_band.py new file mode 100644 index 0000000..e3ef07c --- /dev/null +++ b/tests/test_soft_band.py @@ -0,0 +1,336 @@ +"""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.6" 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() \ No newline at end of file -- 2.49.1 From 87f7905b2a1a4354ced8f28c787a4f8c7324dc06 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 10 Oct 2026 00:08:11 -0400 Subject: [PATCH 06/33] fix: isolate classifier_soft from teaching and replaying - _outcome_is_attributable docstring: add classifier_soft to non-attributable list - Session cache write gate: comment that classifier_soft is deliberately excluded - metrics.py degraded-share SQL: add classifier_soft alongside classifier_cloud - DEGRADED_CLASSIFICATION_SOURCES: comment explaining classifier_cloud intentional absence - test_outcome_attribution.py: add classifier_soft to degraded parametrize - test_route_decisions.py: pin test that _session_history_lookup filters out classifier_soft --- src/dispatcher.py | 11 +++++- src/metrics.py | 12 +++---- tests/test_outcome_attribution.py | 5 ++- tests/test_route_decisions.py | 60 +++++++++++++++++++++++++++++++ 4 files changed, 80 insertions(+), 8 deletions(-) diff --git a/src/dispatcher.py b/src/dispatcher.py index 069dacb..f46dba1 100644 --- a/src/dispatcher.py +++ b/src/dispatcher.py @@ -3252,6 +3252,12 @@ 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 out-of-band measurement — the design treats a cloud classifier +# as degraded for the *operator-share* warning, but retains attribution. DEGRADED_CLASSIFICATION_SOURCES: Final = frozenset( {"fallback", "session_stale", "session_history", "classifier_soft"} ) @@ -3272,7 +3278,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 @@ -4848,6 +4856,7 @@ 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 diff --git a/src/metrics.py b/src/metrics.py index 114525e..9ae4a92 100644 --- a/src/metrics.py +++ b/src/metrics.py @@ -1754,9 +1754,9 @@ def classifier_degradation_warning(conn: sqlite3.Connection, cfg: Any) -> list[s SELECT COUNT(*) AS total, SUM( - CASE WHEN classification_source IN - ('fallback', 'session_stale', 'session_history', - 'classifier_cloud') + CASE WHEN classification_source IN + ('fallback', 'session_stale', 'session_history', + 'classifier_soft', 'classifier_cloud') THEN 1 ELSE 0 END ) AS degraded FROM route_decisions @@ -1798,9 +1798,9 @@ def _declined_for(conn: sqlite3.Connection) -> str: SELECT classifier_reject AS reason, COUNT(*) AS n FROM route_decisions WHERE classifier_reject IS NOT NULL - AND classification_source IN - ('fallback', 'session_stale', 'session_history', - 'classifier_cloud') + AND classification_source IN + ('fallback', 'session_stale', 'session_history', + '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_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..ad60a0c 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 -- 2.49.1 From 8cf3e4806d55602ba416110e192106d3cc0fdb90 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 10 Oct 2026 00:14:27 -0400 Subject: [PATCH 07/33] feat: add soft_confidence_min admin control --- admin/frontend/controls.html | 13 +++++++++++++ src/admin.py | 1 + tests/test_admin_knob_coverage.py | 7 ------- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/admin/frontend/controls.html b/admin/frontend/controls.html index 2acf44e..f86e683 100644 --- a/admin/frontend/controls.html +++ b/admin/frontend/controls.html @@ -1480,6 +1480,17 @@ function classifierModeFieldsHtml(mode, data) { value="${dec.coverage_min != null ? dec.coverage_min : ''}"> +
+
+ + +
Blank = off. Start near 0.30.
+
+
Date: Sat, 10 Oct 2026 00:16:36 -0400 Subject: [PATCH 08/33] docs: add classifier_soft source code --- docs/data-model.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 | -- 2.49.1 From 472367dbff8c195282cdefcab3f42548147b7ef0 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 10 Oct 2026 20:21:39 -0400 Subject: [PATCH 09/33] fix: soft attempt carries below_confidence_min reject reason --- src/dispatcher.py | 79 +++++++++++++++++++---------------------------- 1 file changed, 31 insertions(+), 48 deletions(-) diff --git a/src/dispatcher.py b/src/dispatcher.py index f46dba1..9184ac1 100644 --- a/src/dispatcher.py +++ b/src/dispatcher.py @@ -1170,10 +1170,10 @@ def _classify_via_local_encoder(task: str) -> Classification: def _get_local_decision_verdict( user_content: str, -) -> tuple[str, float, float, int]: +) -> tuple[str, float, float, int, str]: """Classify category (and optionally tier) via local_decision. - Returns ``(category, confidence, coverage, tier)``. + 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 @@ -1183,8 +1183,7 @@ def _get_local_decision_verdict( # 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 (MagicMock auto-creates - # attributes, returning a MagicMock which is not a number). + # 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 @@ -1236,7 +1235,24 @@ def _get_local_decision_verdict( coverage, ) tier = _classify_tier_via_local_decision(user_content) - return category, confidence, coverage, tier + + # 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=dec.confidence_min, + ) + _source = "classifier_soft" + + return category, confidence, coverage, tier, _source def _classify_via_local_decision( @@ -1273,26 +1289,7 @@ def _classify_via_local_decision( sample_interval_seconds=cfg.local_energy.sample_interval_seconds, sampler=local_energy.sample_nvidia_smi, ) as measurement: - category, confidence, coverage, tier = _get_local_decision_verdict(user_content) - - # Detect soft band: classifier answered but confidence landed - # in [soft_confidence_min, confidence_min). - _soft_raw = getattr(dec, "soft_confidence_min", None) - _soft_min = _soft_raw if isinstance(_soft_raw, (int, float)) else None - _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=dec.confidence_min, - ) - _source = "classifier_soft" + category, confidence, coverage, tier, source = _get_local_decision_verdict(user_content) _log_local_energy( model_id=dec.model, @@ -1304,9 +1301,11 @@ def _classify_via_local_decision( task_tier=tier, required_context_tokens=0, confidence=confidence, - source=_source, + 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 @@ -1324,33 +1323,17 @@ def _classify_via_local_decision( # circuit on every unsure classification would skip the classifier for # cooldown_seconds on healthy traffic. try: - category, confidence, coverage, tier = _get_local_decision_verdict(user_content) - # Detect soft band: classifier answered but confidence landed - # in [soft_confidence_min, confidence_min). - _soft_raw = getattr(dec, "soft_confidence_min", None) - _soft_min = _soft_raw if isinstance(_soft_raw, (int, float)) else None - _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=dec.confidence_min, - ) - _source = "classifier_soft" + 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=_source, + 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 -- 2.49.1 From df09f27838320bbd86b65ded688b31f931751edf Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 10 Oct 2026 20:30:00 -0400 Subject: [PATCH 10/33] fix: classify_soft log floor carries soft band floor --- src/dispatcher.py | 2 +- tests/test_soft_band.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/dispatcher.py b/src/dispatcher.py index 9184ac1..3f5ad9f 100644 --- a/src/dispatcher.py +++ b/src/dispatcher.py @@ -1248,7 +1248,7 @@ def _get_local_decision_verdict( category=category, tier=tier, confidence=confidence, - floor=dec.confidence_min, + floor=_soft_min, ) _source = "classifier_soft" diff --git a/tests/test_soft_band.py b/tests/test_soft_band.py index e3ef07c..ae71370 100644 --- a/tests/test_soft_band.py +++ b/tests/test_soft_band.py @@ -265,7 +265,7 @@ class TestSoftBandLogging: assert "local_decision" in text assert "coding_refactor" in text assert "0.55" in text - assert "0.6" in text + assert "0.4" in text def test_above_confidence_min_does_not_log_soft(self, mock_cat, mock_tier, caplog): import logging -- 2.49.1 From c1a614ea0f67b6ea8c55f09a073ffc61312969b7 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 10 Oct 2026 20:42:25 -0400 Subject: [PATCH 11/33] test: pin soft band reject reason, persistence, metrics, cache, admin round trip --- admin/frontend/controls.html | 104 +++++++++++++------------- tests/test_admin_classifier_config.py | 66 ++++++++++++++++ tests/test_admin_js_units.py | 45 ++++++++++- tests/test_classifier_attempt.py | 68 +++++++++++++++++ tests/test_classifier_cascade.py | 87 +++++++++++++++++++++ tests/test_soft_band.py | 57 +++++++++++++- 6 files changed, 374 insertions(+), 53 deletions(-) diff --git a/admin/frontend/controls.html b/admin/frontend/controls.html index f86e683..d2266b8 100644 --- a/admin/frontend/controls.html +++ b/admin/frontend/controls.html @@ -1616,61 +1616,63 @@ async function loadClassifierConfig() { } } +/* COLLECT_CLASSIFIER_BODY:BEGIN */ function collectClassifierConfigBody() { - const mode = document.getElementById('classifier-mode-select').value; - const body = { mode }; - if (mode === 'cloud_llm') { - const auto = document.getElementById('classifier-cloud-auto').checked; - body.cloud_primary_auto = auto; - if (!auto) { - const baseUrl = document.getElementById('classifier-cloud-base-url').value.trim(); - const model = document.getElementById('classifier-cloud-model').value.trim(); - // Send null, not {base_url: "", model: ""}, when either is blank -- - // an object with keys is truthy, so the backend's own "cloud_primary - // is required" check would not catch an empty-but-present block. - body.cloud_primary = (baseUrl && model) ? { base_url: baseUrl, model } : null; - if (body.cloud_primary) { - const apiKeyEnv = document.getElementById('classifier-cloud-api-key-env').value.trim(); - if (apiKeyEnv) body.cloud_primary.api_key_env = apiKeyEnv; - const timeout = document.getElementById('classifier-cloud-timeout').value; - if (timeout !== '') body.cloud_primary.timeout_seconds = parseInt(timeout, 10); + const mode = document.getElementById('classifier-mode-select').value; + const body = { mode }; + if (mode === 'cloud_llm') { + const auto = document.getElementById('classifier-cloud-auto').checked; + body.cloud_primary_auto = auto; + if (!auto) { + const baseUrl = document.getElementById('classifier-cloud-base-url').value.trim(); + const model = document.getElementById('classifier-cloud-model').value.trim(); + // Send null, not {base_url: "", model: ""}, when either is blank -- + // an object with keys is truthy, so the backend's own "cloud_primary + // is required" check would not catch an empty-but-present block. + body.cloud_primary = (baseUrl && model) ? { base_url: baseUrl, model } : null; + if (body.cloud_primary) { + const apiKeyEnv = document.getElementById('classifier-cloud-api-key-env').value.trim(); + if (apiKeyEnv) body.cloud_primary.api_key_env = apiKeyEnv; + const timeout = document.getElementById('classifier-cloud-timeout').value; + if (timeout !== '') body.cloud_primary.timeout_seconds = parseInt(timeout, 10); + } } + } else if (mode === 'local_encoder') { + const encoder = {}; + const model = document.getElementById('classifier-encoder-model').value.trim(); + if (model) encoder.model = model; + encoder.device = document.getElementById('classifier-encoder-device').value; + const thresholdPct = document.getElementById('classifier-encoder-threshold').value; + // The field is 0-100 for a human to type ("80" meaning 80%); the backend + // wants the 0.0-1.0 probability classify_zero_shot actually returns. + if (thresholdPct !== '') encoder.confidence_min = parseFloat(thresholdPct) / 100; + body.encoder = encoder; + } else if (mode === 'local_decision') { + // A blank field is left OUT so the server default applies and keeps floating + // with the repo. Never `value || default`: that rewrites a deliberate 0 + // (confidence_min 0 means "accept every verdict") into the default. + const decision = {}; + const text = (id) => document.getElementById(id).value.trim(); + const baseUrl = text('classifier-decision-base-url'); + if (baseUrl !== '') decision.base_url = baseUrl; + const model = text('classifier-decision-model'); + if (model !== '') decision.model = model; + const numCtx = text('classifier-decision-num-ctx'); + if (numCtx !== '') decision.num_ctx = parseInt(numCtx, 10); + const timeoutS = text('classifier-decision-timeout-s'); + if (timeoutS !== '') decision.timeout_s = parseInt(timeoutS, 10); + const confidenceMin = text('classifier-decision-confidence-min'); + if (confidenceMin !== '') decision.confidence_min = parseFloat(confidenceMin); + const softConfidenceMin = text('classifier-decision-soft-confidence-min'); + if (softConfidenceMin !== '') decision.soft_confidence_min = parseFloat(softConfidenceMin); + const coverageMin = text('classifier-decision-coverage-min'); + if (coverageMin !== '') decision.coverage_min = parseFloat(coverageMin); + decision.tier_enabled = document.getElementById('classifier-decision-tier-enabled').checked; + body.decision = decision; } - } else if (mode === 'local_encoder') { - const encoder = {}; - const model = document.getElementById('classifier-encoder-model').value.trim(); - if (model) encoder.model = model; - encoder.device = document.getElementById('classifier-encoder-device').value; - const thresholdPct = document.getElementById('classifier-encoder-threshold').value; - // The field is 0-100 for a human to type ("80" meaning 80%); the backend - // wants the 0.0-1.0 probability classify_zero_shot actually returns. - if (thresholdPct !== '') encoder.confidence_min = parseFloat(thresholdPct) / 100; - body.encoder = encoder; - } else if (mode === 'local_decision') { - // A blank field is left OUT so the server default applies and keeps floating - // with the repo. Never `value || default`: that rewrites a deliberate 0 - // (confidence_min 0 means "accept every verdict") into the default. - const decision = {}; - const text = (id) => document.getElementById(id).value.trim(); - const baseUrl = text('classifier-decision-base-url'); - if (baseUrl !== '') decision.base_url = baseUrl; - const model = text('classifier-decision-model'); - if (model !== '') decision.model = model; - const numCtx = text('classifier-decision-num-ctx'); - if (numCtx !== '') decision.num_ctx = parseInt(numCtx, 10); - const timeoutS = text('classifier-decision-timeout-s'); - if (timeoutS !== '') decision.timeout_s = parseInt(timeoutS, 10); - const confidenceMin = text('classifier-decision-confidence-min'); - if (confidenceMin !== '') decision.confidence_min = parseFloat(confidenceMin); - const softConfidenceMin = text('classifier-decision-soft-confidence-min'); - if (softConfidenceMin !== '') decision.soft_confidence_min = parseFloat(softConfidenceMin); - const coverageMin = text('classifier-decision-coverage-min'); - if (coverageMin !== '') decision.coverage_min = parseFloat(coverageMin); - decision.tier_enabled = document.getElementById('classifier-decision-tier-enabled').checked; - body.decision = decision; - } - return body; + return body; } +/* COLLECT_CLASSIFIER_BODY:END */ async function saveClassifierConfig() { showClassifierConfigError(''); diff --git a/tests/test_admin_classifier_config.py b/tests/test_admin_classifier_config.py index 7244e1e..e7c332c 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..36967c8 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..62e7a18 100644 --- a/tests/test_classifier_cascade.py +++ b/tests/test_classifier_cascade.py @@ -10,10 +10,12 @@ import sqlite3 from datetime import datetime, time, timedelta, timezone from pathlib import Path from types import SimpleNamespace +from unittest.mock import MagicMock import pytest import dispatcher +import local_decision import session_cache ROOT = Path(__file__).resolve().parent.parent @@ -392,3 +394,88 @@ 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_classifier_soft_not_written_to_session_cache(monkeypatch): + """classifier_soft is deliberately excluded from the session cache gate + (the tuple ``("classifier", "classifier_cloud")`` check). + + A soft-band verdict must not renew the staleness clock of any previous + classification -- it is a low-confidence guess that should not become the + session's incumbent category on a subsequent turn. + """ + mock_cat = MagicMock(return_value=("coding_refactor", 0.55, 0.8)) + mock_tier = MagicMock(return_value=2) + monkeypatch.setattr(local_decision, "classify_category", mock_cat) + monkeypatch.setattr(dispatcher, "_classify_tier_via_local_decision", mock_tier) + monkeypatch.setattr(dispatcher.cfg.session_cache, "enabled", True) + monkeypatch.setattr(dispatcher.cfg.local_energy, "enabled", False) + monkeypatch.setattr(dispatcher.cfg.local_compute, "enabled", True) + + # Set a session key so the gate path is exercised (not None). + token = dispatcher._current_session_key.set("sess-test") + try: + dispatcher.classify("test task", None) + finally: + dispatcher._current_session_key.reset(token) + + # The cache must NOT have been written by the soft-band classification. + got = session_cache.get("sess-test", staleness_seconds=60) + assert got is None + diff --git a/tests/test_soft_band.py b/tests/test_soft_band.py index ae71370..7fd856b 100644 --- a/tests/test_soft_band.py +++ b/tests/test_soft_band.py @@ -333,4 +333,59 @@ class TestSoftBandReachesClassify: result = classify("test task", None) assert result.source == "classifier_soft" - mock_cooldown.assert_called_once() \ No newline at end of file + 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 -- 2.49.1 From 81fdca906ef64a530882004121ad5a053176fd43 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 10 Oct 2026 21:02:59 -0400 Subject: [PATCH 12/33] fix: ASCII-only, metrics indentation, DEGRADED_CLASSIFICATION_SOURCES comment, import order --- src/dispatcher.py | 3 +-- src/metrics.py | 22 ++++++++++--------- tests/test_admin_classifier_config.py | 10 ++++----- tests/test_local_decision_characterization.py | 4 +++- tests/test_soft_band.py | 18 +++++++-------- 5 files changed, 30 insertions(+), 27 deletions(-) diff --git a/src/dispatcher.py b/src/dispatcher.py index 3f5ad9f..3d28459 100644 --- a/src/dispatcher.py +++ b/src/dispatcher.py @@ -3239,8 +3239,7 @@ def _most_recent_if_unambiguous(conn: sqlite3.Connection): # 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 out-of-band measurement — the design treats a cloud classifier -# as degraded for the *operator-share* warning, but retains attribution. +# it is an operator signal, not an attribution one. DEGRADED_CLASSIFICATION_SOURCES: Final = frozenset( {"fallback", "session_stale", "session_history", "classifier_soft"} ) diff --git a/src/metrics.py b/src/metrics.py index 9ae4a92..4bc3ce4 100644 --- a/src/metrics.py +++ b/src/metrics.py @@ -1754,12 +1754,13 @@ def classifier_degradation_warning(conn: sqlite3.Connection, cfg: Any) -> list[s SELECT COUNT(*) AS total, SUM( - CASE WHEN classification_source IN - ('fallback', 'session_stale', 'session_history', - 'classifier_soft', 'classifier_cloud') - THEN 1 ELSE 0 END + CASE WHEN classification_source IN + ('fallback', 'session_stale', 'session_history', + 'classifier_soft', 'classifier_cloud') + THEN 1 ELSE 0 END ) AS degraded FROM route_decisions + WHERE classification_source IS NOT NULL AND julianday(observed_at) >= julianday('now', '-24 hours') """ @@ -1798,12 +1799,13 @@ def _declined_for(conn: sqlite3.Connection) -> str: SELECT classifier_reject AS reason, COUNT(*) AS n FROM route_decisions WHERE classifier_reject IS NOT NULL - AND classification_source IN - ('fallback', 'session_stale', 'session_history', - 'classifier_soft', 'classifier_cloud') - AND julianday(observed_at) >= julianday('now', '-24 hours') - GROUP BY classifier_reject - ORDER BY n DESC, classifier_reject + AND classification_source IN + ('fallback', 'session_stale', 'session_history', + 'classifier_soft', 'classifier_cloud') + AND julianday(observed_at) >= julianday('now', '-24 hours') + GROUP BY classifier_reject + ORDER BY n DESC, classifier_reject + """ ).fetchall() if not rows: diff --git a/tests/test_admin_classifier_config.py b/tests/test_admin_classifier_config.py index e7c332c..2ae490e 100644 --- a/tests/test_admin_classifier_config.py +++ b/tests/test_admin_classifier_config.py @@ -393,14 +393,14 @@ def test_post_invalid_mode_returns_422(tmp_path): # --------------------------------------------------------------------------- -# soft_confidence_min admin round-trip (POST → GET → omit → GET → validation) +# 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.""" + """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 @@ -422,7 +422,7 @@ def test_admin_round_trip_soft_confidence_min(tmp_path): 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 + # 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", diff --git a/tests/test_local_decision_characterization.py b/tests/test_local_decision_characterization.py index 8a039ac..b324848 100644 --- a/tests/test_local_decision_characterization.py +++ b/tests/test_local_decision_characterization.py @@ -1,5 +1,7 @@ -import pytest from unittest.mock import patch + +import pytest + from classifier_rejection import ClassifierRejected from src.dispatcher import _classify_via_local_decision diff --git a/tests/test_soft_band.py b/tests/test_soft_band.py index 7fd856b..4ed7f56 100644 --- a/tests/test_soft_band.py +++ b/tests/test_soft_band.py @@ -16,7 +16,7 @@ from classifier_rejection import ClassifierRejected from src.dispatcher import _classify_via_local_decision # --------------------------------------------------------------------------- -# Helper — build a mocked cfg +# Helper - build a mocked cfg # --------------------------------------------------------------------------- @@ -91,7 +91,7 @@ def mock_tier(): class TestSoftBandAccepted: - """Confidence in [soft_confidence_min, confidence_min) → source=classifier_soft.""" + """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) @@ -152,12 +152,12 @@ class TestSoftBandAccepted: # --------------------------------------------------------------------------- -# Above confidence_min — normal acceptance, source="classifier" +# Above confidence_min - normal acceptance, source="classifier" # --------------------------------------------------------------------------- class TestAboveConfidenceMin: - """Confidence >= confidence_min → source=classifier (unchanged).""" + """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) @@ -182,12 +182,12 @@ class TestAboveConfidenceMin: # --------------------------------------------------------------------------- -# Below soft_confidence_min — still rejected (unchanged from W0) +# Below soft_confidence_min - still rejected (unchanged from W0) # --------------------------------------------------------------------------- class TestBelowSoftConfidenceMin: - """Confidence < soft_confidence_min → ClassifierRejected (unchanged).""" + """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) @@ -210,7 +210,7 @@ class TestBelowSoftConfidenceMin: # --------------------------------------------------------------------------- -# No soft band configured (soft_confidence_min is None) — unchanged behavior +# No soft band configured (soft_confidence_min is None) - unchanged behavior # --------------------------------------------------------------------------- @@ -283,7 +283,7 @@ class TestSoftBandLogging: # --------------------------------------------------------------------------- -# Failure recording — soft band MUST NOT call _record_failure +# Failure recording - soft band MUST NOT call _record_failure # --------------------------------------------------------------------------- @@ -337,7 +337,7 @@ class TestSoftBandReachesClassify: # --------------------------------------------------------------------------- -# Reject reason — both soft band and normal paths +# Reject reason - both soft band and normal paths # --------------------------------------------------------------------------- -- 2.49.1 From 3c4d24407eb9d52c766a2439d88134023146cd36 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 10 Oct 2026 21:08:23 -0400 Subject: [PATCH 13/33] fix: remove all remaining non-ASCII characters from diff --- src/config.py | 2 +- src/dispatcher.py | 2 +- tests/test_admin_classifier_config.py | 2 +- tests/test_admin_js_units.py | 2 +- tests/test_route_decisions.py | 4 ++-- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/config.py b/src/config.py index 5e26210..031bea6 100644 --- a/src/config.py +++ b/src/config.py @@ -1139,7 +1139,7 @@ class LocalDecisionConfig(StrictModel): 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 + # 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 diff --git a/src/dispatcher.py b/src/dispatcher.py index 3d28459..6f61703 100644 --- a/src/dispatcher.py +++ b/src/dispatcher.py @@ -3261,7 +3261,7 @@ def _outcome_is_attributable(conn, request_id: Optional[str]) -> bool: 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), classifier_soft (a low-confidence self - classification — good enough to route one visibly-flagged request, but not + 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 diff --git a/tests/test_admin_classifier_config.py b/tests/test_admin_classifier_config.py index 2ae490e..dabab19 100644 --- a/tests/test_admin_classifier_config.py +++ b/tests/test_admin_classifier_config.py @@ -440,7 +440,7 @@ def test_admin_round_trip_soft_confidence_min(tmp_path): assert body["mode"] == "local_decision" assert body["decision"].get("soft_confidence_min") is None - # 4. POST soft_confidence_min > confidence_min → 422 + # 4. POST soft_confidence_min > confidence_min -> 422 resp = client.post( "/admin/api/classifier-config", json={ diff --git a/tests/test_admin_js_units.py b/tests/test_admin_js_units.py index 36967c8..c6f2ed5 100644 --- a/tests/test_admin_js_units.py +++ b/tests/test_admin_js_units.py @@ -698,7 +698,7 @@ 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. + 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 diff --git a/tests/test_route_decisions.py b/tests/test_route_decisions.py index ad60a0c..f735c96 100644 --- a/tests/test_route_decisions.py +++ b/tests/test_route_decisions.py @@ -1466,7 +1466,7 @@ def test_exploration_runners_up_coherent_after_flex_swap(decision_router, monkey # --------------------------------------------------------------------------- -# _session_history_lookup — degraded-source filter pin +# _session_history_lookup - degraded-source filter pin # --------------------------------------------------------------------------- @@ -1484,7 +1484,7 @@ def test_session_history_lookup_excludes_classifier_soft(_session_db): The query filters to ``classification_source IN ('classifier','cached','override')``. - classifier_soft is a low-confidence self-classification — good enough to + 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. """ -- 2.49.1 From a78a2b60e25f032b22ada95271271c26220450ea Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 10 Oct 2026 21:40:22 -0400 Subject: [PATCH 14/33] test: add _session_cache_admits function and unit test --- src/dispatcher.py | 14 +++++++++- tests/test_classifier_cascade.py | 44 ++++++++++++++------------------ 2 files changed, 32 insertions(+), 26 deletions(-) diff --git a/src/dispatcher.py b/src/dispatcher.py index 6f61703..f1ee05b 100644 --- a/src/dispatcher.py +++ b/src/dispatcher.py @@ -3244,6 +3244,18 @@ DEGRADED_CLASSIFICATION_SOURCES: Final = frozenset( {"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. @@ -4842,7 +4854,7 @@ def chat_completions(body: dict[str, Any], background: BackgroundTasks, request: 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, diff --git a/tests/test_classifier_cascade.py b/tests/test_classifier_cascade.py index 62e7a18..4119628 100644 --- a/tests/test_classifier_cascade.py +++ b/tests/test_classifier_cascade.py @@ -10,12 +10,10 @@ import sqlite3 from datetime import datetime, time, timedelta, timezone from pathlib import Path from types import SimpleNamespace -from unittest.mock import MagicMock import pytest import dispatcher -import local_decision import session_cache ROOT = Path(__file__).resolve().parent.parent @@ -452,30 +450,26 @@ def test_declined_for_includes_classifier_soft_reason(db): assert "below_confidence_min" in warning -def test_classifier_soft_not_written_to_session_cache(monkeypatch): - """classifier_soft is deliberately excluded from the session cache gate - (the tuple ``("classifier", "classifier_cloud")`` check). - - A soft-band verdict must not renew the staleness clock of any previous - classification -- it is a low-confidence guess that should not become the - session's incumbent category on a subsequent turn. +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. """ - mock_cat = MagicMock(return_value=("coding_refactor", 0.55, 0.8)) - mock_tier = MagicMock(return_value=2) - monkeypatch.setattr(local_decision, "classify_category", mock_cat) - monkeypatch.setattr(dispatcher, "_classify_tier_via_local_decision", mock_tier) - monkeypatch.setattr(dispatcher.cfg.session_cache, "enabled", True) - monkeypatch.setattr(dispatcher.cfg.local_energy, "enabled", False) - monkeypatch.setattr(dispatcher.cfg.local_compute, "enabled", True) + from dispatcher import _session_cache_admits - # Set a session key so the gate path is exercised (not None). - token = dispatcher._current_session_key.set("sess-test") - try: - dispatcher.classify("test task", None) - finally: - dispatcher._current_session_key.reset(token) + 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 - # The cache must NOT have been written by the soft-band classification. - got = session_cache.get("sess-test", staleness_seconds=60) - assert got is None + +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 -- 2.49.1 From 08ef1bbfbe619eb51d551d81c2d392dd7d4db4cc Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 10 Oct 2026 21:46:29 -0400 Subject: [PATCH 15/33] fix: restore original whitespace in src/metrics.py SQL blocks --- src/metrics.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/metrics.py b/src/metrics.py index 4bc3ce4..23ebd74 100644 --- a/src/metrics.py +++ b/src/metrics.py @@ -1757,10 +1757,9 @@ def classifier_degradation_warning(conn: sqlite3.Connection, cfg: Any) -> list[s CASE WHEN classification_source IN ('fallback', 'session_stale', 'session_history', 'classifier_soft', 'classifier_cloud') - THEN 1 ELSE 0 END + THEN 1 ELSE 0 END ) AS degraded FROM route_decisions - WHERE classification_source IS NOT NULL AND julianday(observed_at) >= julianday('now', '-24 hours') """ @@ -1802,10 +1801,9 @@ def _declined_for(conn: sqlite3.Connection) -> str: AND classification_source IN ('fallback', 'session_stale', 'session_history', 'classifier_soft', 'classifier_cloud') - AND julianday(observed_at) >= julianday('now', '-24 hours') - GROUP BY classifier_reject - ORDER BY n DESC, classifier_reject - + AND julianday(observed_at) >= julianday('now', '-24 hours') + GROUP BY classifier_reject + ORDER BY n DESC, classifier_reject """ ).fetchall() if not rows: -- 2.49.1 From 316231eab4bae665e93a96eba5b5ebd4f5a4e9c4 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 10 Oct 2026 21:58:34 -0400 Subject: [PATCH 16/33] fix: restore 2-space indentation in collectClassifierConfigBody() in controls.html --- admin/frontend/controls.html | 102 +++++++++++++++++------------------ 1 file changed, 51 insertions(+), 51 deletions(-) diff --git a/admin/frontend/controls.html b/admin/frontend/controls.html index d2266b8..9ba10a1 100644 --- a/admin/frontend/controls.html +++ b/admin/frontend/controls.html @@ -1618,59 +1618,59 @@ async function loadClassifierConfig() { /* COLLECT_CLASSIFIER_BODY:BEGIN */ function collectClassifierConfigBody() { - const mode = document.getElementById('classifier-mode-select').value; - const body = { mode }; - if (mode === 'cloud_llm') { - const auto = document.getElementById('classifier-cloud-auto').checked; - body.cloud_primary_auto = auto; - if (!auto) { - const baseUrl = document.getElementById('classifier-cloud-base-url').value.trim(); - const model = document.getElementById('classifier-cloud-model').value.trim(); - // Send null, not {base_url: "", model: ""}, when either is blank -- - // an object with keys is truthy, so the backend's own "cloud_primary - // is required" check would not catch an empty-but-present block. - body.cloud_primary = (baseUrl && model) ? { base_url: baseUrl, model } : null; - if (body.cloud_primary) { - const apiKeyEnv = document.getElementById('classifier-cloud-api-key-env').value.trim(); - if (apiKeyEnv) body.cloud_primary.api_key_env = apiKeyEnv; - const timeout = document.getElementById('classifier-cloud-timeout').value; - if (timeout !== '') body.cloud_primary.timeout_seconds = parseInt(timeout, 10); - } + const mode = document.getElementById('classifier-mode-select').value; + const body = { mode }; + if (mode === 'cloud_llm') { + const auto = document.getElementById('classifier-cloud-auto').checked; + body.cloud_primary_auto = auto; + if (!auto) { + const baseUrl = document.getElementById('classifier-cloud-base-url').value.trim(); + const model = document.getElementById('classifier-cloud-model').value.trim(); + // Send null, not {base_url: "", model: ""}, when either is blank -- + // an object with keys is truthy, so the backend's own "cloud_primary + // is required" check would not catch an empty-but-present block. + body.cloud_primary = (baseUrl && model) ? { base_url: baseUrl, model } : null; + if (body.cloud_primary) { + const apiKeyEnv = document.getElementById('classifier-cloud-api-key-env').value.trim(); + if (apiKeyEnv) body.cloud_primary.api_key_env = apiKeyEnv; + const timeout = document.getElementById('classifier-cloud-timeout').value; + if (timeout !== '') body.cloud_primary.timeout_seconds = parseInt(timeout, 10); } - } else if (mode === 'local_encoder') { - const encoder = {}; - const model = document.getElementById('classifier-encoder-model').value.trim(); - if (model) encoder.model = model; - encoder.device = document.getElementById('classifier-encoder-device').value; - const thresholdPct = document.getElementById('classifier-encoder-threshold').value; - // The field is 0-100 for a human to type ("80" meaning 80%); the backend - // wants the 0.0-1.0 probability classify_zero_shot actually returns. - if (thresholdPct !== '') encoder.confidence_min = parseFloat(thresholdPct) / 100; - body.encoder = encoder; - } else if (mode === 'local_decision') { - // A blank field is left OUT so the server default applies and keeps floating - // with the repo. Never `value || default`: that rewrites a deliberate 0 - // (confidence_min 0 means "accept every verdict") into the default. - const decision = {}; - const text = (id) => document.getElementById(id).value.trim(); - const baseUrl = text('classifier-decision-base-url'); - if (baseUrl !== '') decision.base_url = baseUrl; - const model = text('classifier-decision-model'); - if (model !== '') decision.model = model; - const numCtx = text('classifier-decision-num-ctx'); - if (numCtx !== '') decision.num_ctx = parseInt(numCtx, 10); - const timeoutS = text('classifier-decision-timeout-s'); - if (timeoutS !== '') decision.timeout_s = parseInt(timeoutS, 10); - const confidenceMin = text('classifier-decision-confidence-min'); - if (confidenceMin !== '') decision.confidence_min = parseFloat(confidenceMin); - const softConfidenceMin = text('classifier-decision-soft-confidence-min'); - if (softConfidenceMin !== '') decision.soft_confidence_min = parseFloat(softConfidenceMin); - const coverageMin = text('classifier-decision-coverage-min'); - if (coverageMin !== '') decision.coverage_min = parseFloat(coverageMin); - decision.tier_enabled = document.getElementById('classifier-decision-tier-enabled').checked; - body.decision = decision; } - return body; + } else if (mode === 'local_encoder') { + const encoder = {}; + const model = document.getElementById('classifier-encoder-model').value.trim(); + if (model) encoder.model = model; + encoder.device = document.getElementById('classifier-encoder-device').value; + const thresholdPct = document.getElementById('classifier-encoder-threshold').value; + // The field is 0-100 for a human to type ("80" meaning 80%); the backend + // wants the 0.0-1.0 probability classify_zero_shot actually returns. + if (thresholdPct !== '') encoder.confidence_min = parseFloat(thresholdPct) / 100; + body.encoder = encoder; + } else if (mode === 'local_decision') { + // A blank field is left OUT so the server default applies and keeps floating + // with the repo. Never `value || default`: that rewrites a deliberate 0 + // (confidence_min 0 means "accept every verdict") into the default. + const decision = {}; + const text = (id) => document.getElementById(id).value.trim(); + const baseUrl = text('classifier-decision-base-url'); + if (baseUrl !== '') decision.base_url = baseUrl; + const model = text('classifier-decision-model'); + if (model !== '') decision.model = model; + const numCtx = text('classifier-decision-num-ctx'); + if (numCtx !== '') decision.num_ctx = parseInt(numCtx, 10); + const timeoutS = text('classifier-decision-timeout-s'); + if (timeoutS !== '') decision.timeout_s = parseInt(timeoutS, 10); + const confidenceMin = text('classifier-decision-confidence-min'); + if (confidenceMin !== '') decision.confidence_min = parseFloat(confidenceMin); + const coverageMin = text('classifier-decision-coverage-min'); + if (coverageMin !== '') decision.coverage_min = parseFloat(coverageMin); + const softConfidenceMin = text('classifier-decision-soft-confidence-min'); + if (softConfidenceMin !== '') decision.soft_confidence_min = parseFloat(softConfidenceMin); + decision.tier_enabled = document.getElementById('classifier-decision-tier-enabled').checked; + body.decision = decision; + } + return body; } /* COLLECT_CLASSIFIER_BODY:END */ -- 2.49.1 From 14cfc9408da6a798af4fea37afa6418bbe1bfec0 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 10 Oct 2026 22:06:02 -0400 Subject: [PATCH 17/33] fix: replace em dash with ASCII in _SESSION_CACHE_SOURCES comment --- src/dispatcher.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/dispatcher.py b/src/dispatcher.py index f1ee05b..eccacf1 100644 --- a/src/dispatcher.py +++ b/src/dispatcher.py @@ -3245,7 +3245,7 @@ DEGRADED_CLASSIFICATION_SOURCES: Final = frozenset( ) # 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 +# 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. -- 2.49.1 From a6f5159f6c6fe87884a6f42f78ac7d128406fea6 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 17 Oct 2026 13:36:21 -0400 Subject: [PATCH 18/33] feat: add shadow_encoder knob to ClassifierConfig and config.yaml --- config/config.yaml | 2 ++ src/config.py | 10 ++++++++++ 2 files changed, 12 insertions(+) diff --git a/config/config.yaml b/config/config.yaml index b6db076..ca79b3b 100644 --- a/config/config.yaml +++ b/config/config.yaml @@ -857,6 +857,8 @@ classifier: # " 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/src/config.py b/src/config.py index 031bea6..6c6bd5c 100644 --- a/src/config.py +++ b/src/config.py @@ -1215,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 @@ -1331,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. -- 2.49.1 From 68338fd5484fc0170b47a631b25962be23be553f Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 17 Oct 2026 13:43:01 -0400 Subject: [PATCH 19/33] feat: add classifier_shadow table and ensure_classifier_shadow --- config/schema.sql | 17 +++++++++++++++++ src/dispatcher.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/config/schema.sql b/config/schema.sql index dbdfdb0..179d6c3 100644 --- a/config/schema.sql +++ b/config/schema.sql @@ -386,6 +386,23 @@ 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 table for classifier reliability experiments. +-- Stores labels from a separate 'labeler' (e.g. a stronger model) for the same +-- task as a route_decision, enabling direct confidence-vs-ground-truth analysis. +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/src/dispatcher.py b/src/dispatcher.py index eccacf1..56d7a07 100644 --- a/src/dispatcher.py +++ b/src/dispatcher.py @@ -548,6 +548,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. -- 2.49.1 From 413bed433887b7edc3be093706502677b157e522 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 17 Oct 2026 13:50:33 -0400 Subject: [PATCH 20/33] feat: add run_shadow_encoder, _SHADOW_LOCK, and _write_shadow_row --- src/dispatcher.py | 94 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/src/dispatcher.py b/src/dispatcher.py index 56d7a07..584ea6d 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. @@ -2924,6 +2929,95 @@ 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: + 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)) + _SHADOW_LOCK.release() + 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)) + _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, -- 2.49.1 From 60d280b5476146a08bbfda55417605db707cf9de Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 17 Oct 2026 13:52:42 -0400 Subject: [PATCH 21/33] feat: wire shadow_encoder into chat_completions --- src/dispatcher.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/dispatcher.py b/src/dispatcher.py index 584ea6d..f430d46 100644 --- a/src/dispatcher.py +++ b/src/dispatcher.py @@ -5086,6 +5086,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 -- 2.49.1 From ec4ce2ce6c456ecf19a4c00a70db22bfb2143587 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 17 Oct 2026 13:54:36 -0400 Subject: [PATCH 22/33] feat: register classifier_shadow_encoder in admin portal --- admin/frontend/controls.html | 12 ++++++++++++ src/admin.py | 9 ++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/admin/frontend/controls.html b/admin/frontend/controls.html index 9ba10a1..be8e12d 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: 'use a second encoder for validation', + title: 'If enabled, the router runs a shadow encoder to cross-verify the primary encoder\'s confidence.', + cls: 'bg-info', + glyph: 'info', + }, + 'classifier.shadow_encoder': { + text: 'use a second encoder for validation', + title: 'If enabled, the router runs a shadow encoder to cross-verify the primary encoder\'s confidence.', + cls: 'bg-info', + glyph: 'info', + }, }; function noteBadge(key) { diff --git a/src/admin.py b/src/admin.py index 9cff51a..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}, @@ -630,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"), @@ -663,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", @@ -1128,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] ), -- 2.49.1 From 62a66c863a0903cd73e943e8951409c96bf8b78a Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 17 Oct 2026 13:59:09 -0400 Subject: [PATCH 23/33] feat: add read-only shadow classifier report script --- scripts/shadow_report.py | 271 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 271 insertions(+) create mode 100644 scripts/shadow_report.py diff --git a/scripts/shadow_report.py b/scripts/shadow_report.py new file mode 100644 index 0000000..1476e17 --- /dev/null +++ b/scripts/shadow_report.py @@ -0,0 +1,271 @@ +import argparse +import sqlite3 +import sys +from datetime import datetime, timezone +from typing import Any, 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 + where_clause = "WHERE observed_at >= julianday('now') - ? / 86400.0" + params = (days,) + + # Empty table guard + try: + has_rows = conn.execute( + f"SELECT 1 FROM classifier_shadow {where_clause} 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 = conn.execute( + "SELECT MIN(observed_at) as first FROM classifier_shadow" + ).fetchone()["first"] + + shadow_count = conn.execute( + f"SELECT COUNT(*) as n FROM classifier_shadow {where_clause}", 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 s.observed_at >= julianday('now') - ? / 86400.0 + """, params + ).fetchone()["n"] + + chat_since_first = conn.execute( + f""" + SELECT COUNT(*) as n + FROM route_decisions + WHERE kind = 'chat' AND observed_at >= {first_shadow} + """, + ).fetchone()["n"] if first_shadow else 0 + + 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 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 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 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(f"SELECT confidence FROM classifier_shadow {where_clause}", 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 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( + f"SELECT session_key, COUNT(*) as n FROM classifier_shadow {where_clause} 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) -- 2.49.1 From 32aee61c26f705e22ef0313f1d47d9bf0d453bd8 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 17 Oct 2026 14:00:52 -0400 Subject: [PATCH 24/33] fix: cleanup unused imports and dict access in shadow_report.py --- scripts/shadow_report.py | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/scripts/shadow_report.py b/scripts/shadow_report.py index 1476e17..b1c377b 100644 --- a/scripts/shadow_report.py +++ b/scripts/shadow_report.py @@ -1,8 +1,7 @@ import argparse import sqlite3 import sys -from datetime import datetime, timezone -from typing import Any, Optional +from typing import Optional def get_percentile(data: list[float], p: float) -> Optional[float]: if not data: @@ -43,9 +42,10 @@ def run_report(db_path: str, days: int): # 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 = conn.execute( + first_shadow_row = conn.execute( "SELECT MIN(observed_at) as first FROM classifier_shadow" - ).fetchone()["first"] + ).fetchone() + first_shadow = first_shadow_row["first"] if first_shadow_row else None shadow_count = conn.execute( f"SELECT COUNT(*) as n FROM classifier_shadow {where_clause}", params @@ -60,13 +60,16 @@ def run_report(db_path: str, days: int): """, params ).fetchone()["n"] - chat_since_first = conn.execute( - f""" - SELECT COUNT(*) as n - FROM route_decisions - WHERE kind = 'chat' AND observed_at >= {first_shadow} - """, - ).fetchone()["n"] if first_shadow else 0 + 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}") -- 2.49.1 From 4e369bc907efc60516a30fd7f15def078447ff8d Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 17 Oct 2026 14:27:51 -0400 Subject: [PATCH 25/33] feat: add shadow report fixes and full shadow encoder test suite --- scripts/shadow_report.py | 36 +- tests/test_shadow_encoder.py | 654 +++++++++++++++++++++++++++++++++++ 2 files changed, 679 insertions(+), 11 deletions(-) create mode 100644 tests/test_shadow_encoder.py diff --git a/scripts/shadow_report.py b/scripts/shadow_report.py index b1c377b..869ef2a 100644 --- a/scripts/shadow_report.py +++ b/scripts/shadow_report.py @@ -18,14 +18,16 @@ def run_report(db_path: str, days: int): print(f"Error connecting to database: {e}") sys.exit(1) - # Window filter - where_clause = "WHERE observed_at >= julianday('now') - ? / 86400.0" + # 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( - f"SELECT 1 FROM classifier_shadow {where_clause} LIMIT 1", params + "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(): @@ -48,7 +50,9 @@ def run_report(db_path: str, days: int): first_shadow = first_shadow_row["first"] if first_shadow_row else None shadow_count = conn.execute( - f"SELECT COUNT(*) as n FROM classifier_shadow {where_clause}", params + "SELECT COUNT(*) as n FROM classifier_shadow " + "WHERE julianday(observed_at) >= julianday('now') - ? / 86400.0", + params, ).fetchone()["n"] chat_with_shadow = conn.execute( @@ -56,7 +60,7 @@ def run_report(db_path: str, days: int): 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 s.observed_at >= julianday('now') - ? / 86400.0 + WHERE d.kind = 'chat' AND julianday(s.observed_at) >= julianday('now') - ? / 86400.0 """, params ).fetchone()["n"] @@ -126,7 +130,7 @@ def run_report(db_path: str, days: int): JOIN route_decisions d ON s.decision_id = d.id WHERE s.abstained = 0 AND d.classification_source = 'classifier' - AND s.observed_at >= julianday('now') - ? / 86400.0 + AND julianday(s.observed_at) >= julianday('now') - ? / 86400.0 """, params ).fetchall() @@ -158,7 +162,7 @@ def run_report(db_path: str, days: int): FROM classifier_shadow s JOIN route_decisions d ON s.decision_id = d.id WHERE d.classification_source IN ('session_history', 'fallback') - AND s.observed_at >= julianday('now') - ? / 86400.0 + AND julianday(s.observed_at) >= julianday('now') - ? / 86400.0 """, params ).fetchall() @@ -190,7 +194,7 @@ def run_report(db_path: str, days: int): 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 s.observed_at >= julianday('now') - ? / 86400.0 + AND julianday(s.observed_at) >= julianday('now') - ? / 86400.0 """, params ).fetchall() @@ -223,7 +227,15 @@ def run_report(db_path: str, days: int): print("Addenda:") # Raw confidence distribution - confs = [r["confidence"] for r in conn.execute(f"SELECT confidence FROM classifier_shadow {where_clause}", params) if r["confidence"] is not None] + 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}") @@ -244,7 +256,7 @@ def run_report(db_path: str, days: int): 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 s.observed_at >= julianday('now') - ? / 86400.0 + WHERE s.abstained = 0 AND {cond} AND julianday(s.observed_at) >= julianday('now') - ? / 86400.0 """, params ).fetchone() if res and res["total"] > 0: @@ -254,7 +266,9 @@ def run_report(db_path: str, days: int): # Sessions stats sess_data = conn.execute( - f"SELECT session_key, COUNT(*) as n FROM classifier_shadow {where_clause} GROUP BY session_key", params + "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) diff --git a/tests/test_shadow_encoder.py b/tests/test_shadow_encoder.py new file mode 100644 index 0000000..85cdd3d --- /dev/null +++ b/tests/test_shadow_encoder.py @@ -0,0 +1,654 @@ +"""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 copy +import json +import sqlite3 +import sys +import threading +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. + dispatcher._SHADOW_LOCK.acquire() + 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) + 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 io + import contextlib + + 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 io + import contextlib + + 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 -- 2.49.1 From 3911651e08b92650e6f490196c771146b5a906df Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 17 Oct 2026 14:44:18 -0400 Subject: [PATCH 26/33] test: fix unused imports in test_shadow_encoder.py --- tests/test_shadow_encoder.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/test_shadow_encoder.py b/tests/test_shadow_encoder.py index 85cdd3d..edbc594 100644 --- a/tests/test_shadow_encoder.py +++ b/tests/test_shadow_encoder.py @@ -13,11 +13,9 @@ patched, never called for real, and the DB lives in ``tmp_path``. from __future__ import annotations -import copy import json import sqlite3 import sys -import threading from datetime import datetime, timezone from pathlib import Path -- 2.49.1 From be0fb03ecf97917e38372aefe80e1040482551c8 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 17 Oct 2026 14:45:59 -0400 Subject: [PATCH 27/33] test: fix import sort order in test_shadow_encoder.py --- tests/test_shadow_encoder.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_shadow_encoder.py b/tests/test_shadow_encoder.py index edbc594..62932fc 100644 --- a/tests/test_shadow_encoder.py +++ b/tests/test_shadow_encoder.py @@ -519,9 +519,9 @@ def test_config_validation_no_encoder(): def test_report_empty(db_path): - """Test 11a: empty table → 'No classifier_shadow rows found'.""" - import io + """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. @@ -563,8 +563,8 @@ def test_report_populated(db_path): conn.commit() conn.close() - import io import contextlib + import io f = io.StringIO() with contextlib.redirect_stdout(f): -- 2.49.1 From 095f6a4ffd017e667f867974e9f1223a02db787f Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 17 Oct 2026 15:35:48 -0400 Subject: [PATCH 28/33] style: ASCII only in shadow encoder files --- scripts/shadow_report.py | 2 +- tests/test_shadow_encoder.py | 60 ++++++++++++++++++------------------ 2 files changed, 31 insertions(+), 31 deletions(-) diff --git a/scripts/shadow_report.py b/scripts/shadow_report.py index 869ef2a..85dcbe1 100644 --- a/scripts/shadow_report.py +++ b/scripts/shadow_report.py @@ -18,7 +18,7 @@ def run_report(db_path: str, days: int): print(f"Error connecting to database: {e}") sys.exit(1) - # Window filter — use AND so it can be appended after an existing WHERE + # 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,) diff --git a/tests/test_shadow_encoder.py b/tests/test_shadow_encoder.py index 62932fc..94a28ac 100644 --- a/tests/test_shadow_encoder.py +++ b/tests/test_shadow_encoder.py @@ -1,11 +1,11 @@ """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 +- ``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``. @@ -80,7 +80,7 @@ def cfg_patch(db_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - encoder = {model, device, confidence_min} - local_compute.enabled = True - logging.log_route_decisions = True - - database.path → tmp_path / shadow.db + - database.path -> tmp_path / shadow.db """ monkeypatch.setattr( dispatcher.cfg.database, "path", str(db_path) @@ -140,12 +140,12 @@ def _rows(conn: sqlite3.Connection) -> list[sqlite3.Row]: # --------------------------------------------------------------------------- -# 1. flag off — shadow_encoder=False → zero rows, encoder never called +# 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.""" + """Test 1: shadow_encoder=False -> no rows, encoder never called.""" monkeypatch.setattr( dispatcher.cfg.classifier, "shadow_encoder", False ) @@ -157,14 +157,14 @@ def test_flag_off_no_rows(encoder_ok, db_path, monkeypatch): # --------------------------------------------------------------------------- -# 2. flag on, above threshold → one row, abstained=0 +# 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.""" + """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 @@ -183,14 +183,14 @@ def test_flag_on_above_threshold( # --------------------------------------------------------------------------- -# 3. flag on, below threshold → abstained=1, reject_reason='below_confidence_min' +# 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.""" + """Test 3: encoder returns below confidence_min -> abstained=1.""" monkeypatch.setattr( local_encoder, "classify_zero_shot", @@ -207,14 +207,14 @@ def test_flag_on_below_threshold( # --------------------------------------------------------------------------- -# 4. encoder raises → no exception escapes, reject_reason='error:RuntimeError' +# 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.""" + """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 @@ -226,12 +226,12 @@ def test_encoder_raises( # --------------------------------------------------------------------------- -# 5. local_compute.enabled=false → zero calls, zero rows +# 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.""" + """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)) @@ -241,12 +241,12 @@ def test_local_compute_disabled(cfg_patch, encoder_ok, db_path, monkeypatch): # --------------------------------------------------------------------------- -# 6. lock held → second call writes abstained=1, reject_reason='busy' +# 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.""" + """Test 6: lock held by caller -> second call gets busy row.""" # Manually hold the lock so the second call finds it busy. dispatcher._SHADOW_LOCK.acquire() try: @@ -353,7 +353,7 @@ def test_routing_unchanged(tmp_path, monkeypatch): messages = [{"role": "user", "content": "Refactor this Django view"}] client = TestClient(dispatcher.app) - # Call 1 — shadow on. + # Call 1 - shadow on. resp1 = client.post( "/v1/chat/completions", json={"model": "auto", "messages": messages}, @@ -361,7 +361,7 @@ def test_routing_unchanged(tmp_path, monkeypatch): assert resp1.status_code == 200 model1 = resp1.json()["choices"][0]["message"]["content"] - # Call 2 — shadow off. + # Call 2 - shadow off. monkeypatch.setattr( dispatcher.cfg.classifier, "shadow_encoder", False ) @@ -376,7 +376,7 @@ def test_routing_unchanged(tmp_path, monkeypatch): # --------------------------------------------------------------------------- -# 8. table schema — exactly the columns from the spec +# 8. table schema - exactly the columns from the spec # --------------------------------------------------------------------------- @@ -497,7 +497,7 @@ def test_streaming_schedules_shadow(tmp_path, monkeypatch): # --------------------------------------------------------------------------- -# 10. config validation — shadow_encoder=true without encoder block raises +# 10. config validation - shadow_encoder=true without encoder block raises # --------------------------------------------------------------------------- @@ -513,8 +513,8 @@ def test_config_validation_no_encoder(): # --------------------------------------------------------------------------- -# 11. report script — empty table → "no rows" -# populated fixture → all sections present +# 11. report script - empty table -> "no rows" +# populated fixture -> all sections present # --------------------------------------------------------------------------- @@ -535,7 +535,7 @@ def test_report_empty(db_path): def test_report_populated(db_path): - """Test 11b: populated fixture → all five sections appear.""" + """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() @@ -584,7 +584,7 @@ def test_report_populated(db_path): # --------------------------------------------------------------------------- -# 12. decision_id is None → writes nothing, does not raise +# 12. decision_id is None -> writes nothing, does not raise # --------------------------------------------------------------------------- @@ -598,12 +598,12 @@ def test_decision_id_none(cfg_patch, encoder_ok, db_path): # --------------------------------------------------------------------------- -# 13. log_route_decisions=false → shadow writes nothing +# 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.""" + """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)) @@ -613,12 +613,12 @@ def test_log_route_decisions_off(cfg_patch, encoder_ok, db_path, monkeypatch): # --------------------------------------------------------------------------- -# 14. DB write failure → no exception escapes, logs.warning emitted +# 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. + """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 -- 2.49.1 From 03920bb300e3883cca4d3e4c82e6cd2c9c6c4d84 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 17 Oct 2026 15:44:25 -0400 Subject: [PATCH 29/33] fix: release _SHADOW_LOCK in a finally and pin it --- src/dispatcher.py | 37 +++++++++++++++++------------------- tests/test_shadow_encoder.py | 34 +++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 20 deletions(-) diff --git a/src/dispatcher.py b/src/dispatcher.py index f430d46..a27e362 100644 --- a/src/dispatcher.py +++ b/src/dispatcher.py @@ -2956,27 +2956,24 @@ def run_shadow_encoder(decision_id: int, session_key: str, task: str) -> None: started = time.perf_counter() 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)) + 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() - 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)) - _SHADOW_LOCK.release() def _write_shadow_row( diff --git a/tests/test_shadow_encoder.py b/tests/test_shadow_encoder.py index 94a28ac..d40eec5 100644 --- a/tests/test_shadow_encoder.py +++ b/tests/test_shadow_encoder.py @@ -650,3 +650,37 @@ def test_db_write_failure(cfg_patch, encoder_ok, db_path): 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() -- 2.49.1 From bd65777896a9f67d920efaf10d2cee8e233febcb Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 17 Oct 2026 15:58:29 -0400 Subject: [PATCH 30/33] test: pin that chat_completions schedules the shadow task only when the flag is on --- tests/test_shadow_encoder.py | 116 +++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) diff --git a/tests/test_shadow_encoder.py b/tests/test_shadow_encoder.py index d40eec5..366ebdd 100644 --- a/tests/test_shadow_encoder.py +++ b/tests/test_shadow_encoder.py @@ -429,6 +429,9 @@ def test_streaming_schedules_shadow(tmp_path, monkeypatch): 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( @@ -684,3 +687,116 @@ def test_lock_released_after_compare_error(cfg_patch, db_path, monkeypatch): 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) -- 2.49.1 From d4b43e7bf31a5be60836de40d3b633cb18afb81d Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 17 Oct 2026 16:00:23 -0400 Subject: [PATCH 31/33] docs: update shadow-encoder description in admin portal and schema comments --- admin/frontend/controls.html | 24 ++++++++++++------------ config/schema.sql | 5 ++--- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/admin/frontend/controls.html b/admin/frontend/controls.html index be8e12d..8f4c5be 100644 --- a/admin/frontend/controls.html +++ b/admin/frontend/controls.html @@ -750,18 +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: 'use a second encoder for validation', - title: 'If enabled, the router runs a shadow encoder to cross-verify the primary encoder\'s confidence.', - cls: 'bg-info', - glyph: 'info', - }, - 'classifier.shadow_encoder': { - text: 'use a second encoder for validation', - title: 'If enabled, the router runs a shadow encoder to cross-verify the primary encoder\'s confidence.', - 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', + }, + '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) { diff --git a/config/schema.sql b/config/schema.sql index 179d6c3..94e9bda 100644 --- a/config/schema.sql +++ b/config/schema.sql @@ -386,9 +386,8 @@ 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 table for classifier reliability experiments. --- Stores labels from a separate 'labeler' (e.g. a stronger model) for the same --- task as a route_decision, enabling direct confidence-vs-ground-truth analysis. +-- 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, -- 2.49.1 From 90b8e26700d2236be7a00da0726f45ddc18c084f Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 17 Oct 2026 16:03:26 -0400 Subject: [PATCH 32/33] style: restore 2-space indentation of the shadow_encoder KNOB_NOTES entries Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01XtPLeRkmHJk4VeiTEUfhVR --- admin/frontend/controls.html | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/admin/frontend/controls.html b/admin/frontend/controls.html index 8f4c5be..033d9fb 100644 --- a/admin/frontend/controls.html +++ b/admin/frontend/controls.html @@ -750,18 +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', - }, + 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) { -- 2.49.1 From 6ac57127cec300c9c808ec17ee5a5b271feafed1 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 17 Oct 2026 16:05:47 -0400 Subject: [PATCH 33/33] test: fail test_lock_busy fast when the shadow lock leaks instead of hanging Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01XtPLeRkmHJk4VeiTEUfhVR --- tests/test_shadow_encoder.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_shadow_encoder.py b/tests/test_shadow_encoder.py index 366ebdd..61a0552 100644 --- a/tests/test_shadow_encoder.py +++ b/tests/test_shadow_encoder.py @@ -248,7 +248,8 @@ def test_local_compute_disabled(cfg_patch, encoder_ok, db_path, monkeypatch): 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. - dispatcher._SHADOW_LOCK.acquire() + # 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)) -- 2.49.1