"""Soft confidence band tests for the local decision path. The soft band [soft_confidence_min, confidence_min) is a range where the classifier *answered* but with low confidence. Verdicts in this band are accepted as ``source="classifier_soft"`` and MUST reach ``classify()`` so ``_record_success_cooldown()`` runs; they MUST NOT trigger ``_record_failure()``. """ from __future__ import annotations from unittest.mock import MagicMock, patch import pytest from classifier_rejection import ClassifierRejected from src.dispatcher import _classify_via_local_decision # --------------------------------------------------------------------------- # Helper - build a mocked cfg # --------------------------------------------------------------------------- def _mock_cfg(**overrides) -> MagicMock: """Build a ``MagicMock`` in the shape of ``dispatcher.cfg``. Use with ``patch("src.dispatcher.cfg", mock_cfg)`` in the test body. """ kwargs = { "confidence_min": 0.6, "soft_confidence_min": 0.4, "tier_enabled": True, "base_url": "http://test:11434/v1", "model": "test-model", "num_ctx": 4096, "timeout_s": 30, "coverage_min": 0.0, "fallback_tier": 2, "local_energy_enabled": False, } kwargs.update(overrides) decision = MagicMock( confidence_min=kwargs["confidence_min"], soft_confidence_min=kwargs["soft_confidence_min"], tier_enabled=kwargs["tier_enabled"], base_url=kwargs["base_url"], model=kwargs["model"], num_ctx=kwargs["num_ctx"], timeout_s=kwargs["timeout_s"], coverage_min=kwargs["coverage_min"], ) classifier = MagicMock( decision=decision, fallback_tier=kwargs["fallback_tier"], mode="local_decision", # These static attrs are needed by the classify() path through # _classify_via_configured_mode. candidate_categories=[], system_prompt="", context_framing=False, max_input_chars=10000, ) cfg = MagicMock( classifier=classifier, local_energy=MagicMock(enabled=kwargs["local_energy_enabled"]), local_energy_call_sites={}, ) return cfg # --------------------------------------------------------------------------- # Fixtures # --------------------------------------------------------------------------- @pytest.fixture def mock_cat(): with patch("local_decision.classify_category") as m: yield m @pytest.fixture def mock_tier(): with patch("src.dispatcher._classify_tier_via_local_decision") as m: yield m # --------------------------------------------------------------------------- # Soft band acceptance # --------------------------------------------------------------------------- class TestSoftBandAccepted: """Confidence in [soft_confidence_min, confidence_min) -> source=classifier_soft.""" def test_accepted(self, mock_cat, mock_tier): mock_cat.return_value = ("coding_refactor", 0.55, 0.8) mock_tier.return_value = 2 with patch("src.dispatcher.cfg", _mock_cfg()): result = _classify_via_local_decision("system", "user content") assert result.task_category == "coding_refactor" assert result.task_tier == 2 assert result.confidence == 0.55 assert result.source == "classifier_soft" assert result.attempt is not None assert result.attempt.confidence == 0.55 assert result.attempt.coverage == 0.8 def test_accepted_no_tier(self, mock_cat, mock_tier): mock_cat.return_value = ("coding_refactor", 0.55, 0.8) with patch("src.dispatcher.cfg", _mock_cfg(tier_enabled=False, fallback_tier=1)): result = _classify_via_local_decision("system", "user content") assert result.source == "classifier_soft" assert result.confidence == 0.55 def test_accepted_metered(self, mock_cat, mock_tier): mock_cat.return_value = ("coding_refactor", 0.55, 0.8) mock_tier.return_value = 2 with patch("src.dispatcher.cfg", _mock_cfg(local_energy_enabled=True)): result = _classify_via_local_decision("system", "user content") assert result.source == "classifier_soft" assert result.confidence == 0.55 def test_accepted_metered_no_tier(self, mock_cat, mock_tier): mock_cat.return_value = ("coding_refactor", 0.55, 0.8) with patch( "src.dispatcher.cfg", _mock_cfg(tier_enabled=False, fallback_tier=1, local_energy_enabled=True), ): result = _classify_via_local_decision("system", "user content") assert result.source == "classifier_soft" assert result.confidence == 0.55 def test_at_lower_boundary(self, mock_cat, mock_tier): """Confidence exactly equal to soft_confidence_min is accepted (inclusive).""" mock_cat.return_value = ("coding_refactor", 0.4, 0.8) mock_tier.return_value = 2 with patch("src.dispatcher.cfg", _mock_cfg()): result = _classify_via_local_decision("system", "user content") assert result.source == "classifier_soft" assert result.confidence == 0.4 # --------------------------------------------------------------------------- # Above confidence_min - normal acceptance, source="classifier" # --------------------------------------------------------------------------- class TestAboveConfidenceMin: """Confidence >= confidence_min -> source=classifier (unchanged).""" def test_above_confidence_min(self, mock_cat, mock_tier): mock_cat.return_value = ("coding_refactor", 0.9, 0.8) mock_tier.return_value = 2 with patch("src.dispatcher.cfg", _mock_cfg()): result = _classify_via_local_decision("system", "user content") assert result.source == "classifier" assert result.confidence == 0.9 def test_at_confidence_min(self, mock_cat, mock_tier): """Confidence exactly equal to confidence_min is accepted (inclusive).""" mock_cat.return_value = ("coding_refactor", 0.6, 0.8) mock_tier.return_value = 2 with patch("src.dispatcher.cfg", _mock_cfg()): result = _classify_via_local_decision("system", "user content") assert result.source == "classifier" assert result.confidence == 0.6 # --------------------------------------------------------------------------- # Below soft_confidence_min - still rejected (unchanged from W0) # --------------------------------------------------------------------------- class TestBelowSoftConfidenceMin: """Confidence < soft_confidence_min -> ClassifierRejected (unchanged).""" def test_below_soft_confidence_min(self, mock_cat, mock_tier): mock_cat.return_value = ("coding_refactor", 0.3, 0.8) mock_tier.return_value = 2 with patch("src.dispatcher.cfg", _mock_cfg()), \ pytest.raises(ClassifierRejected) as excinfo: _classify_via_local_decision("system", "user content") assert excinfo.value.confidence == 0.3 def test_below_soft_confidence_min_no_tier(self, mock_cat, mock_tier): mock_cat.return_value = ("coding_refactor", 0.3, 0.8) with patch("src.dispatcher.cfg", _mock_cfg(tier_enabled=False)), \ pytest.raises(ClassifierRejected) as excinfo: _classify_via_local_decision("system", "user content") assert excinfo.value.confidence == 0.3 # --------------------------------------------------------------------------- # No soft band configured (soft_confidence_min is None) - unchanged behavior # --------------------------------------------------------------------------- class TestNoSoftBand: """When soft_confidence_min is None, the soft band does not exist.""" def test_below_confidence_min_raises(self, mock_cat, mock_tier): mock_cat.return_value = ("coding_refactor", 0.5, 0.8) mock_tier.return_value = 2 with patch("src.dispatcher.cfg", _mock_cfg(soft_confidence_min=None)), \ pytest.raises(ClassifierRejected) as excinfo: _classify_via_local_decision("system", "user content") assert excinfo.value.confidence == 0.5 def test_above_confidence_min_normal(self, mock_cat, mock_tier): mock_cat.return_value = ("coding_refactor", 0.9, 0.8) mock_tier.return_value = 2 with patch("src.dispatcher.cfg", _mock_cfg(soft_confidence_min=None)): result = _classify_via_local_decision("system", "user content") assert result.source == "classifier" assert result.confidence == 0.9 # --------------------------------------------------------------------------- # Logging # --------------------------------------------------------------------------- class TestSoftBandLogging: """Soft band verdicts must log classify_soft with the right fields.""" def test_logs_classify_soft(self, mock_cat, mock_tier, caplog): import logging caplog.set_level(logging.INFO) mock_cat.return_value = ("coding_refactor", 0.55, 0.8) mock_tier.return_value = 2 with patch("src.dispatcher.cfg", _mock_cfg()): _classify_via_local_decision("system", "user content") records = [r for r in caplog.records if r.name == "llm_router"] soft_records = [r for r in records if "classify_soft" in r.getMessage()] assert len(soft_records) == 1 msg = soft_records[0] text = msg.getMessage() assert "local_decision" in text assert "coding_refactor" in text assert "0.55" in text assert "0.4" in text def test_above_confidence_min_does_not_log_soft(self, mock_cat, mock_tier, caplog): import logging caplog.set_level(logging.INFO) mock_cat.return_value = ("coding_refactor", 0.9, 0.8) mock_tier.return_value = 2 with patch("src.dispatcher.cfg", _mock_cfg()): _classify_via_local_decision("system", "user content") records = [r for r in caplog.records if r.name == "llm_router"] soft_records = [r for r in records if "classify_soft" in r.getMessage()] assert len(soft_records) == 0 # --------------------------------------------------------------------------- # Failure recording - soft band MUST NOT call _record_failure # --------------------------------------------------------------------------- class TestSoftBandNoFailureRecorded: """Soft band verdicts must NOT trigger _record_failure.""" def test_no_failure_recorded(self, mock_cat, mock_tier): mock_cat.return_value = ("coding_refactor", 0.55, 0.8) mock_tier.return_value = 2 with patch("src.dispatcher.cfg", _mock_cfg()), \ patch("src.dispatcher._record_failure") as mock_rec: result = _classify_via_local_decision("system", "user content") assert result.source == "classifier_soft" mock_rec.assert_not_called() def test_no_failure_recorded_metered(self, mock_cat, mock_tier): mock_cat.return_value = ("coding_refactor", 0.55, 0.8) mock_tier.return_value = 2 with patch("src.dispatcher.cfg", _mock_cfg(local_energy_enabled=True)), \ patch("src.dispatcher._record_failure") as mock_rec: result = _classify_via_local_decision("system", "user content") assert result.source == "classifier_soft" mock_rec.assert_not_called() # --------------------------------------------------------------------------- # Soft band still reaches classify() # --------------------------------------------------------------------------- class TestSoftBandReachesClassify: """Soft band verdicts must reach classify() so _record_success_cooldown runs.""" def test_success_cooldown_is_called(self, mock_cat, mock_tier): """Verify _record_success_cooldown is called when classify() gets a soft verdict.""" from src.dispatcher import classify mock_cat.return_value = ("coding_refactor", 0.55, 0.8) mock_tier.return_value = 2 with patch("src.dispatcher.cfg", _mock_cfg()), \ patch("src.dispatcher._record_success_cooldown") as mock_cooldown: result = classify("test task", None) assert result.source == "classifier_soft" mock_cooldown.assert_called_once() # --------------------------------------------------------------------------- # Reject reason - both soft band and normal paths # --------------------------------------------------------------------------- class TestRejectReason: """A soft-band result carries reject_reason == "below_confidence_min"; an accepted (>= confidence_min) result carries reject_reason is None.""" def test_soft_band_carries_below_confidence_min(self, mock_cat, mock_tier): mock_cat.return_value = ("coding_refactor", 0.55, 0.8) mock_tier.return_value = 2 with patch("src.dispatcher.cfg", _mock_cfg()): result = _classify_via_local_decision("system", "user content") assert result.source == "classifier_soft" assert result.attempt is not None assert result.attempt.reject_reason == "below_confidence_min" def test_soft_band_metered_carries_below_confidence_min(self, mock_cat, mock_tier): mock_cat.return_value = ("coding_refactor", 0.55, 0.8) mock_tier.return_value = 2 with patch("src.dispatcher.cfg", _mock_cfg(local_energy_enabled=True)): result = _classify_via_local_decision("system", "user content") assert result.source == "classifier_soft" assert result.attempt is not None assert result.attempt.reject_reason == "below_confidence_min" def test_normal_acceptance_has_no_reject_reason(self, mock_cat, mock_tier): mock_cat.return_value = ("coding_refactor", 0.9, 0.8) mock_tier.return_value = 2 with patch("src.dispatcher.cfg", _mock_cfg()): result = _classify_via_local_decision("system", "user content") assert result.source == "classifier" assert result.attempt is not None assert result.attempt.reject_reason is None def test_normal_acceptance_no_tier_has_no_reject_reason(self, mock_cat, mock_tier): mock_cat.return_value = ("coding_refactor", 0.9, 0.8) with patch( "src.dispatcher.cfg", _mock_cfg(tier_enabled=False, fallback_tier=1) ): result = _classify_via_local_decision("system", "user content") assert result.source == "classifier" assert result.attempt is not None assert result.attempt.reject_reason is None