Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(metrics): align truncation_ratio formula and tests with 80% threshold (#3840)

LearningCircuitcb38a226534d
diff --git a/src/local_deep_research/metrics/token_counter.py b/src/local_deep_research/metrics/token_counter.py
index fa582c3846..29d3f41515 100644
--- a/src/local_deep_research/metrics/token_counter.py
+++ b/src/local_deep_research/metrics/token_counter.py
@@ -251,13 +251,19 @@ class TokenCountingCallback(BaseCallbackHandler):
0,
self.original_prompt_estimate - prompt_eval_count,
)
+ if (
+ self.tokens_truncated > 0
+ and self.original_prompt_estimate > 0
+ ):
+ self.truncation_ratio = (
+ self.tokens_truncated / self.original_prompt_estimate
+ )
elif prompt_eval_count > self.context_limit:
self.tokens_truncated = prompt_eval_count - self.context_limit
-
- if self.tokens_truncated > 0 and prompt_eval_count > 0:
- self.truncation_ratio = (
- self.tokens_truncated / prompt_eval_count
- )
+ if self.tokens_truncated > 0 and prompt_eval_count > 0:
+ self.truncation_ratio = (
+ self.tokens_truncated / prompt_eval_count
+ )
logger.warning(
f"Context overflow detected [{source}]! "
diff --git a/tests/metrics/test_token_counter_extended.py b/tests/metrics/test_token_counter_extended.py
index 3ea1f2791c..ed69e35660 100644
--- a/tests/metrics/test_token_counter_extended.py
+++ b/tests/metrics/test_token_counter_extended.py
@@ -720,29 +720,29 @@ class TestResearchContextIntegration:
def test_token_warning_thresholds(self):
"""Test warning at various threshold levels"""
- # Test at 90% - should not trigger
- callback_90 = TokenCountingCallback(
+ # Test at 70% - should not trigger
+ callback_70 = TokenCountingCallback(
research_context={"context_limit": 1000}
)
- callback_90.on_llm_start(
+ callback_70.on_llm_start(
{"_type": "ChatOllama", "kwargs": {"model": "llama2"}}, ["test"]
)
- mock_gen_90 = MagicMock()
- mock_gen_90.message.response_metadata = {
- "prompt_eval_count": 900,
+ mock_gen_70 = MagicMock()
+ mock_gen_70.message.response_metadata = {
+ "prompt_eval_count": 700,
"eval_count": 10,
}
- mock_gen_90.message.usage_metadata = None
+ mock_gen_70.message.usage_metadata = None
- mock_resp_90 = MagicMock()
- mock_resp_90.llm_output = {}
- mock_resp_90.generations = [[mock_gen_90]]
+ mock_resp_70 = MagicMock()
+ mock_resp_70.llm_output = {}
+ mock_resp_70.generations = [[mock_gen_70]]
- callback_90.on_llm_end(mock_resp_90)
+ callback_70.on_llm_end(mock_resp_70)
- # 90% should not trigger (threshold is 95%)
- assert callback_90.context_truncated is False
+ # 70% should not trigger (threshold is 80%)
+ assert callback_70.context_truncated is False
# Test at 96% - should trigger
callback_96 = TokenCountingCallback(
diff --git a/tests/metrics/test_token_counter_high_value.py b/tests/metrics/test_token_counter_high_value.py
index 5d92e25809..7cc0765e32 100644
--- a/tests/metrics/test_token_counter_high_value.py
+++ b/tests/metrics/test_token_counter_high_value.py
@@ -508,7 +508,7 @@ class TestContextOverflow:
cb.on_llm_end(result)
assert cb.tokens_truncated == 1100 # 5000 - 3900
- assert abs(cb.truncation_ratio - 0.282) < 0.01 # 1100/3900
+ assert abs(cb.truncation_ratio - 0.22) < 0.01 # 1100/5000
def test_get_context_overflow_fields_when_truncated(self):
"""_get_context_overflow_fields returns values when truncated."""
diff --git a/tests/metrics/test_token_counter_llm_paths_coverage.py b/tests/metrics/test_token_counter_llm_paths_coverage.py
index e8febf65e4..d1fd504be0 100644
--- a/tests/metrics/test_token_counter_llm_paths_coverage.py
+++ b/tests/metrics/test_token_counter_llm_paths_coverage.py
@@ -4,7 +4,7 @@ Targets the specific uncovered lines:
- on_llm_start: call stack capture, model extraction from invocation_params,
Ollama _type detection
- on_llm_end: usage_metadata from generations (Ollama-specific),
- context overflow detection (prompt_eval_count >= 95% of limit),
+ context overflow detection (prompt_eval_count >= 80% of limit),
raw Ollama response_metadata metrics extraction
- on_llm_error: error status and type recorded
- _save_to_db (background thread): no username -> warning + return early;
@@ -477,7 +477,7 @@ class TestOnLlmEndUsageMetadataFromGenerations:
class TestOnLlmEndContextOverflowDetection:
- """prompt_eval_count >= 95% of context_limit sets context_truncated = True."""
+ """prompt_eval_count >= 80% of context_limit sets context_truncated = True."""
def _run_with_resp_meta(self, cb, resp_meta):
gen = _make_generation(usage_metadata=None, response_metadata=resp_meta)
@@ -513,15 +513,15 @@ class TestOnLlmEndContextOverflowDetection:
assert cb.context_truncated is True
- def test_below_95_percent_does_not_trigger_overflow(self):
+ def test_below_threshold_does_not_trigger_overflow(self):
cb = _make_callback()
cb.context_limit = 1000
- cb.original_prompt_estimate = 900
+ cb.original_prompt_estimate = 700
_setup_model_counts(cb, "phi3", "ollama")
- # 900 / 1000 = 90% — below threshold
+ # 700 / 1000 = 70% — below 80% threshold
self._run_with_resp_meta(
- cb, {"prompt_eval_count": 900, "eval_count": 50}
+ cb, {"prompt_eval_count": 700, "eval_count": 50}
)
assert cb.context_truncated is False
diff --git a/tests/metrics/test_token_counter_logic.py b/tests/metrics/test_token_counter_logic.py
index 44ceafabd4..f52def0e32 100644
--- a/tests/metrics/test_token_counter_logic.py
+++ b/tests/metrics/test_token_counter_logic.py
@@ -371,10 +371,10 @@ class TestContextOverflowDetection:
assert cb.tokens_truncated == 1200 - 960
def test_no_overflow_below_threshold(self):
- """No overflow when below 95% threshold."""
+ """No overflow when below 80% threshold."""
cb = self._trigger_overflow(
context_limit=1000,
- prompt_eval_count=940, # 94% < 95%
+ prompt_eval_count=700, # 70% < 80%
original_prompt_estimate=1200,
)
assert cb.context_truncated is False
diff --git a/tests/metrics/test_token_counter_metrics.py b/tests/metrics/test_token_counter_metrics.py
index f58e3439c1..22ac232392 100644
--- a/tests/metrics/test_token_counter_metrics.py
+++ b/tests/metrics/test_token_counter_metrics.py
@@ -247,8 +247,8 @@ class TestContextOverflowEdgeCases:
assert callback.context_truncated is True
- def test_context_overflow_at_94_percent(self):
- """Test context overflow not triggered at 94%."""
+ def test_context_overflow_below_threshold(self):
+ """Test context overflow not triggered below the 80% threshold."""
from local_deep_research.metrics.token_counter import (
TokenCountingCallback,
)
@@ -263,7 +263,7 @@ class TestContextOverflowEdgeCases:
mock_generation = MagicMock()
mock_generation.message.response_metadata = {
- "prompt_eval_count": 940, # 94% - below threshold
+ "prompt_eval_count": 700, # 70% - below 80% threshold
"eval_count": 10,
}
mock_generation.message.usage_metadata = None
diff --git a/tests/web/routes/test_context_overflow_api_http.py b/tests/web/routes/test_context_overflow_api_http.py
index 6ab7ebd47a..e75dbef0cc 100644
--- a/tests/web/routes/test_context_overflow_api_http.py
+++ b/tests/web/routes/test_context_overflow_api_http.py
@@ -70,12 +70,23 @@ def _authenticated_client(app):
_routes_mod = "local_deep_research.web.routes.context_overflow_api"
+ # SettingsManager(session) is invoked at the end of the route to read
+ # llm.local_context_window_size; with a Mock session its lazy-init code
+ # path raises. Patch the class so it returns a stub manager that yields
+ # a fixed setting value.
+ _mock_settings_manager = Mock()
+ _mock_settings_manager.get_setting.return_value = 4096
+
patches = [
patch("local_deep_research.web.auth.decorators.db_manager", mock_db),
patch(
f"{_routes_mod}.get_user_db_session",
side_effect=_fake_session,
),
+ patch(
+ f"{_routes_mod}.SettingsManager",
+ return_value=_mock_settings_manager,
+ ),
]
started = []