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): show recording failures on the dashboard (#7330)

LearningCircuit6f57340d3580
diff --git a/changelog.d/4600.bugfix.md b/changelog.d/4600.bugfix.md
new file mode 100644
index 0000000000..81be38b16d
--- /dev/null
+++ b/changelog.d/4600.bugfix.md
@@ -0,0 +1 @@
+Show a per-user metrics-dashboard warning when token, search, or rate-limit updates cannot be recorded, using bounded in-memory counts without storing exception details.
diff --git a/docs/metrics-dashboard.md b/docs/metrics-dashboard.md
index 1ed41b836f..e48ab25956 100644
--- a/docs/metrics-dashboard.md
+++ b/docs/metrics-dashboard.md
@@ -39,6 +39,26 @@ The main metrics page shows:
| Total Cost | Estimated LLM API costs |
| Average Duration | Mean research completion time |
+### Incomplete Metrics Warning
+
+If token, search, or rate-limit updates cannot be recorded, the main metrics
+page shows a warning for the signed-in user. It counts final write failures
+after retries, missing database credentials, and search or token updates skipped to
+preserve pending caller work or when no matching owner session is available. Research can continue while recording
+is unavailable. Refresh the page to see the latest count and reason categories;
+the server logs provide the existing diagnostic details.
+
+The count describes failed or skipped recording attempts, not a verified number
+of missing rows: an error during session cleanup can occur after a write.
+
+These counters are held in memory by the current server process, separately
+for each user. They reset on restart and retain at most 512 recent writers;
+older entries can be evicted. Counts are therefore lower bounds, not a durable
+audit or a count restricted to the dashboard's selected date range. An absent
+warning does not prove historical metrics are complete. Calls without an
+identified user and intentional programmatic mode do not create a user's
+warning. The counter stores no passwords, queries, or exception messages.
+
### Per-Research Metrics
Click on any research to see detailed metrics:
diff --git a/src/local_deep_research/metrics/search_tracker.py b/src/local_deep_research/metrics/search_tracker.py
index a742f70711..9c08a9bb41 100644
--- a/src/local_deep_research/metrics/search_tracker.py
+++ b/src/local_deep_research/metrics/search_tracker.py
@@ -9,6 +9,10 @@ from loguru import logger
from sqlalchemy import case, func
from ..utilities.thread_context import get_search_context
+from ..utilities.metric_write_health import (
+ MetricWriteReason,
+ record_metric_write_drop,
+)
from ..database.models import SearchCall
from .database import MetricsDatabase
from .query_utils import get_research_mode_condition, get_time_filter_condition
@@ -100,6 +104,8 @@ class SearchTracker:
)
# Record search call in database - only from background threads
+ username = None
+ dropped_reason: MetricWriteReason | None = None
try:
# Get username from context for thread-safe database
username = context.get("username")
@@ -113,6 +119,7 @@ class SearchTracker:
# Get password from context
password = context.get("user_password")
if not password:
+ dropped_reason = "missing_credentials"
logger.warning(
"Cannot save search metrics - no password in research "
f"context. Search engine: {engine_name}, "
@@ -184,6 +191,7 @@ class SearchTracker:
username
)
if session is None:
+ dropped_reason = "database_unavailable"
# Unlike rollback-coupled loss, an owner mismatch is
# an anomaly worth surfacing (as rate telemetry does).
logger.warning(
@@ -192,6 +200,7 @@ class SearchTracker:
)
return
if _session_has_pending_orm_state(session):
+ dropped_reason = "pending_transaction"
logger.debug(
"Skipping in-scope search metrics write; "
"caller session has pending ORM state "
@@ -210,6 +219,7 @@ class SearchTracker:
with metrics_writer.get_session(username) as session:
_write_search(session)
except Exception as e:
+ dropped_reason = "write_error"
# Deferred import to avoid potential circular imports during module initialization
from ..security.log_sanitizer import scrub_error
@@ -217,11 +227,17 @@ class SearchTracker:
logger.warning(f"Failed to write search metrics: {safe_msg}")
except Exception as e:
+ dropped_reason = "write_error"
# Deferred import to avoid potential circular imports during module initialization
from ..security.log_sanitizer import scrub_error
safe_msg = scrub_error(e, password)
logger.warning(f"Failed to record search call: {safe_msg}")
+ finally:
+ # A write and its context-manager cleanup can both fail. Count
+ # this recording attempt once after all nested handlers finish.
+ if dropped_reason is not None:
+ record_metric_write_drop(username, "search", dropped_reason)
def get_search_metrics(
self,
diff --git a/src/local_deep_research/metrics/token_counter.py b/src/local_deep_research/metrics/token_counter.py
index dc5596ea9a..83ef29ec4f 100644
--- a/src/local_deep_research/metrics/token_counter.py
+++ b/src/local_deep_research/metrics/token_counter.py
@@ -15,6 +15,7 @@ from loguru import logger
from sqlalchemy import func, text
from ..database.models import ModelUsage, TokenUsage
+from ..utilities.metric_write_health import record_metric_write_drop
from .query_utils import (
get_period_cutoff,
get_research_mode_condition,
@@ -870,6 +871,9 @@ class TokenCountingCallback(BaseCallbackHandler):
# Get password from research context
password = self.research_context.get("user_password")
if not password and not in_scope:
+ record_metric_write_drop(
+ username, "tokens", "missing_credentials"
+ )
logger.warning(
f"Cannot save token metrics - no password in research context. "
f"Username: {username}, Token usage: prompt={prompt_tokens}, completion={completion_tokens}"
@@ -892,6 +896,9 @@ class TokenCountingCallback(BaseCallbackHandler):
username
)
if session is None:
+ record_metric_write_drop(
+ username, "tokens", "database_unavailable"
+ )
# Unlike rollback-coupled loss, an owner mismatch is
# an anomaly worth surfacing (as rate telemetry does).
logger.warning(
@@ -900,6 +907,9 @@ class TokenCountingCallback(BaseCallbackHandler):
)
return
if session.new or session.dirty or session.deleted:
+ record_metric_write_drop(
+ username, "tokens", "pending_transaction"
+ )
# begin_nested() flushes pending ORM work BEFORE the
# SAVEPOINT. A failed flush can invalidate the caller
# transaction, so best-effort telemetry must skip.
@@ -938,6 +948,7 @@ class TokenCountingCallback(BaseCallbackHandler):
retry_on_db_lock(_write_metrics)
except Exception as e:
+ record_metric_write_drop(username, "tokens", "write_error")
# Deferred import to avoid potential circular imports during module initialization
from ..security.log_sanitizer import scrub_error
@@ -948,6 +959,7 @@ class TokenCountingCallback(BaseCallbackHandler):
return
# In MainThread, save directly
+ username = None
try:
from ..database.session_context import get_user_db_session
@@ -1057,6 +1069,7 @@ class TokenCountingCallback(BaseCallbackHandler):
session.commit()
except Exception as e:
+ record_metric_write_drop(username, "tokens", "write_error")
# Deferred import to avoid potential circular imports during module initialization
from ..security.log_sanitizer import scrub_error
diff --git a/src/local_deep_research/utilities/metric_write_health.py b/src/local_deep_research/utilities/metric_write_health.py
new file mode 100644
index 0000000000..f4275a3ada
--- /dev/null
+++ b/src/local_deep_research/utilities/metric_write_health.py
@@ -0,0 +1,97 @@
+"""Bounded, per-user diagnostics for best-effort metric writes.
+
+Only fixed source/reason categories and counts are retained. This module stays
+independent of database and metrics imports so optional/programmatic callers
+can report a failure without initializing either subsystem.
+"""
+
+from collections import Counter, OrderedDict
+from threading import Lock
+from typing import Literal, TypedDict
+
+MetricWriteSource = Literal["tokens", "search", "rate_limits"]
+MetricWriteReason = Literal[
+ "write_error",
+ "missing_credentials",
+ "pending_transaction",
+ "database_unavailable",
+]
+
+_SOURCES: tuple[MetricWriteSource, ...] = ("tokens", "search", "rate_limits")
+METRIC_WRITE_REASON_LABELS: dict[MetricWriteReason, str] = {
+ "write_error": "Database write failures",
+ "missing_credentials": "Missing database credentials",
+ "pending_transaction": "Updates skipped while another write was pending",
+ "database_unavailable": "Metrics storage unavailable",
+}
+MAX_TRACKED_USERS = 512
+
+
+class MetricWriteSnapshot(TypedDict):
+ dropped_writes: int
+ by_source: dict[MetricWriteSource, int]
+ by_reason: dict[MetricWriteReason, int]
+
+
+class MetricWriteHealth:
+ """Count dropped updates for at most ``max_users`` recent writers.
+
+ Counts are process-local lower bounds, reset by restart or eviction. Reads
+ never allocate an entry or expose another user's counts.
+ """
+
+ def __init__(self, max_users: int = MAX_TRACKED_USERS) -> None:
+ if max_users < 1:
+ raise ValueError("max_users must be positive")
+ self._max_users = max_users
+ self._lock = Lock()
+ self._users: OrderedDict[
+ str, Counter[tuple[MetricWriteSource, MetricWriteReason]]
+ ] = OrderedDict()
+
+ def record(
+ self,
+ username: str | None,
+ source: MetricWriteSource,
+ reason: MetricWriteReason,
+ ) -> None:
+ if not isinstance(username, str) or not username:
+ return
+ if source not in _SOURCES or reason not in METRIC_WRITE_REASON_LABELS:
+ return
+ with self._lock:
+ counts = self._users.setdefault(username, Counter())
+ counts[(source, reason)] += 1
+ self._users.move_to_end(username)
+ if len(self._users) > self._max_users:
+ self._users.popitem(last=False)
+
+ def snapshot(self, username: str | None) -> MetricWriteSnapshot:
+ counts: Counter[tuple[MetricWriteSource, MetricWriteReason]] = Counter()
+ with self._lock:
+ if isinstance(username, str):
+ counts = self._users.get(username, counts).copy()
+ return {
+ "dropped_writes": sum(counts.values()),
+ "by_source": {
+ source: sum(n for (s, _), n in counts.items() if s == source)
+ for source in _SOURCES
+ },
+ "by_reason": {
+ reason: sum(n for (_, r), n in counts.items() if r == reason)
+ for reason in METRIC_WRITE_REASON_LABELS
+ },
+ }
+
+
+_health = MetricWriteHealth()
+
+
+def record_metric_write_drop(
+ username: str | None, source: MetricWriteSource, reason: MetricWriteReason
+) -> None:
+ _health.record(username, source, reason)
+
+
+def get_metric_write_health(username: str) -> MetricWriteSnapshot:
+ return _health.snapshot(username)
diff --git a/src/local_deep_research/web/routers/metrics.py b/src/local_deep_research/web/routers/metrics.py
index 9f0fac72d2..923c231ef8 100644
--- a/src/local_deep_research/web/routers/metrics.py
+++ b/src/local_deep_research/web/routers/metrics.py
@@ -39,6 +39,10 @@ from ...metrics.query_utils import (
get_time_filter_condition,
)
from ...metrics.search_tracker import get_search_tracker
+from ...utilities.metric_write_health import (
+ METRIC_WRITE_REASON_LABELS,
+ get_metric_write_health,
+)
from ...security import redact_url_for_log, url_authority_without_userinfo
from ..dependencies.json_body import json_body_error, read_json_dict
from .notes import _log_value_preview
@@ -787,7 +791,13 @@ def metrics_dashboard(
):
"""Render the metrics dashboard page."""
return templates.TemplateResponse(
- request=request, name="pages/metrics.html", context={"request": request}
+ request=request,
+ name="pages/metrics.html",
+ context={
+ "request": request,
+ "metric_write_health": get_metric_write_health(username),
+ "metric_write_reason_labels": METRIC_WRITE_REASON_LABELS,
+ },
)
diff --git a/src/local_deep_research/web/templates/pages/metrics.html b/src/local_deep_research/web/templates/pages/metrics.html
index 9d750d700f..91342287f4 100644
--- a/src/local_deep_research/web/templates/pages/metrics.html
+++ b/src/local_deep_research/web/templates/pages/metrics.html
@@ -45,6 +45,20 @@
</div>
</div>
</div>
+ {% if metric_write_health and metric_write_health.dropped_writes %}
+ <div id="metric-write-warning" class="ldr-alert ldr-alert-warning" role="status">
+ <strong>Metrics may be incomplete.</strong>
+ Recording problems since the server started: at least
+ {{ metric_write_health.dropped_writes }}. Check the server logs for details.
+ <ul>
+ {% for reason, count in metric_write_health.by_reason.items() %}
+ {% if count %}
+ <li>{{ metric_write_reason_labels[reason] }}: {{ count }}</li>
+ {% endif %}
+ {% endfor %}
+ </ul>
+ </div>
+ {% endif %}
<!-- Understanding Metrics Help Panel -->
{% call help_panel('metrics-how', 'Understanding Metrics', icon='tachometer-alt', collapsed=true, dismissible=true) %}
<div class="ldr-help-steps">
diff --git a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
index bc1a4d04cb..036c55b7e0 100644
--- a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
+++ b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
@@ -29,6 +29,7 @@ from ...config.thread_settings import (
)
from ...settings.env_registry import is_ci_environment
from ...utilities.thread_context import get_search_context
+from ...utilities.metric_write_health import record_metric_write_drop
# Lazy imports to avoid database initialization in programmatic mode
_db_imports = None
@@ -672,6 +673,9 @@ class AdaptiveRateLimitTracker:
else None
)
if not RateLimitEstimate:
+ record_metric_write_drop(
+ username, "rate_limits", "database_unavailable"
+ )
return
session_inner: "Session"
@@ -724,6 +728,9 @@ class AdaptiveRateLimitTracker:
# instead of silently failing.
retry_on_db_lock(_persist_estimate)
except Exception as exc:
+ record_metric_write_drop(
+ username, "rate_limits", "write_error"
+ )
# Class only, never message/traceback: the DB
# password is a live local in the session frames
# below, and rendering them would leak it
@@ -735,6 +742,10 @@ class AdaptiveRateLimitTracker:
f"(exc_class={type(exc).__name__})"
)
else:
+ if username:
+ record_metric_write_drop(
+ username, "rate_limits", "missing_credentials"
+ )
logger.debug(
"Skipping rate limit estimate save - no user context"
)
diff --git a/tests/metrics/test_metric_write_health.py b/tests/metrics/test_metric_write_health.py
new file mode 100644
index 0000000000..f1c2a1b5cf
--- /dev/null
+++ b/tests/metrics/test_metric_write_health.py
@@ -0,0 +1,467 @@
+"""Dropped-write reporting through real metric writers and the dashboard."""
+
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import contextmanager
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+from sqlalchemy.exc import OperationalError
+
+from local_deep_research.utilities import metric_write_health as health_module
+
+
+def health(monkeypatch):
+ state = health_module.MetricWriteHealth()
+ monkeypatch.setattr(health_module, "_health", state)
+ return state
+
+
+def test_counts_are_isolated_copied_and_bounded():
+ health = health_module.MetricWriteHealth(max_users=2)
+ health.record("alice", "tokens", "write_error")
+ health.record("bob", "search", "missing_credentials")
+ health.record("alice", "search", "pending_transaction")
+ snapshot = health.snapshot("alice")
+ assert snapshot["dropped_writes"] == 2
+ assert snapshot["by_source"] == {"tokens": 1, "search": 1, "rate_limits": 0}
+ assert snapshot["by_reason"]["write_error"] == 1
+ assert snapshot["by_reason"]["missing_credentials"] == 0
+ snapshot["by_reason"]["write_error"] = 500
+ assert health.snapshot("alice")["by_reason"]["write_error"] == 1
+
+ # Reads neither evict writers nor make an older writer recent again.
+ for username in ("bob", "unknown", None):
+ health.snapshot(username)
+ health.record("carol", "rate_limits", "database_unavailable")
+ assert health.snapshot("bob")["dropped_writes"] == 0
+ assert health.snapshot("alice")["dropped_writes"] == 2
+ assert health.snapshot("carol")["dropped_writes"] == 1
+
+
+def test_concurrent_writers_do_not_lose_counts(health):
+ def record_batch(_):
+ for _ in range(100):
+ health_module.record_metric_write_drop(
+ "alice", "tokens", "write_error"
+ )
+
+ with ThreadPoolExecutor(max_workers=8) as pool:
+ list(pool.map(record_batch, range(16)))
+ assert (
+ health_module.get_metric_write_health("alice")["dropped_writes"] == 1600
+ )
+ assert health.snapshot("bob")["dropped_writes"] == 0
+
+
+def test_only_known_categories_and_identified_users_are_retained(health):
+ for username in (None, ""):
+ health.record(username, "tokens", "write_error")
+ health.record("alice", "private query", "write_error")
+ health.record("alice", "tokens", "private exception message")
+ assert health.snapshot("alice")["dropped_writes"] == 0
+ assert health.snapshot(None)["dropped_writes"] == 0
+ with pytest.raises(ValueError, match="positive"):
+ health_module.MetricWriteHealth(max_users=0)
+
+
+def _context(password=True):
+ return {
+ "username": "alice",
+ "user_password": "test-password" if password else None,
+ "research_id": "health-research",
+ }
+
+
[email protected]("fail", [False, True])
[email protected]("explicit_owner", [False, True])
+def test_main_thread_token_commit_result(
+ health, monkeypatch, fail, explicit_owner
+):
+ from local_deep_research.database import session_context
+ from local_deep_research.metrics import token_counter
+
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.first.return_value = None
+ if fail:
+ session.commit.side_effect = RuntimeError("private write error")
+
+ opened_sessions = []
+
+ @contextmanager
+ def get_session(username, password=None):
+ opened_sessions.append((username, password))
+ yield session
+
+ monkeypatch.setattr(session_context, "get_user_db_session", get_session)
+ monkeypatch.setattr(
+ token_counter,
+ "get_current_username",
+ lambda: "bob" if explicit_owner else "alice",
+ )
+ # pytest invokes this on MainThread, so exercise the real synchronous path.
+ callback = token_counter.TokenCountingCallback(
+ research_id="health-research",
+ research_context=_context() if explicit_owner else None,
+ )
+ callback._save_to_db(10, 5)
+ assert opened_sessions == [
+ ("alice", "test-password" if explicit_owner else None)
+ ]
+ assert session.commit.call_count == 1
+ assert health.snapshot("alice")["dropped_writes"] == int(fail)
+ assert health.snapshot("alice")["by_source"]["tokens"] == int(fail)
+ assert health.snapshot("bob")["dropped_writes"] == 0
+
+
[email protected]("failures, expected", [(0, 0), (2, 0), (3, 1)])
+def test_background_tokens_count_only_exhausted_retries(
+ health, monkeypatch, failures, expected
+):
+ import threading
+
+ from local_deep_research.database import sqlcipher_utils, thread_metrics
+ from local_deep_research.metrics.token_counter import TokenCountingCallback
+
+ writer = MagicMock()
+ locked = OperationalError("INSERT", {}, Exception("database is locked"))
+ writer.write_token_metrics.side_effect = [locked] * failures + [None]
+ monkeypatch.setattr(thread_metrics, "metrics_writer", writer)
+ monkeypatch.setattr(sqlcipher_utils.time, "sleep", lambda _: None)
+ monkeypatch.setattr(
+ threading, "current_thread", lambda: SimpleNamespace(name="worker")
+ )
+ callback = TokenCountingCallback(research_context=_context())
+ callback._save_to_db(10, 5)
+ assert writer.write_token_metrics.call_count == min(failures + 1, 3)
+ assert health.snapshot("alice")["by_source"]["tokens"] == expected
+ assert health.snapshot("alice")["by_reason"]["write_error"] == expected
+
+
+def test_background_tokens_missing_credentials(health, monkeypatch):
+ import threading
+
+ from local_deep_research.database import thread_metrics
+ from local_deep_research.metrics.token_counter import TokenCountingCallback
+
+ writer = MagicMock()
+ monkeypatch.setattr(thread_metrics, "metrics_writer", writer)
+ monkeypatch.setattr(
+ threading, "current_thread", lambda: SimpleNamespace(name="worker")
+ )
+ TokenCountingCallback(
+ research_context=_context(password=False)
+ )._save_to_db(10, 5)
+ assert health.snapshot("alice")["by_reason"]["missing_credentials"] == 1
+ writer.write_token_metrics.assert_not_called()
+
+
+ "mode, expected_reason",
+ [
+ ("success", None),
+ ("owned_failure", "write_error"),
+ ("nested_failure", "write_error"),
+ ("double_failure", "write_error"),
+ ("nested_success", None),
+ ("owner_mismatch", "database_unavailable"),
+ ("pending", "pending_transaction"),
+ ("missing_password", "missing_credentials"),
+ ("no_context", None),
+ ],
+)
+def test_search_failures_count_once_without_touching_caller_transaction(
+ health, monkeypatch, mode, expected_reason
+):
+ from local_deep_research.database import (
+ session_context,
+ thread_local_session,
+ thread_metrics,
+ )
+ from local_deep_research.metrics import search_tracker
+
+ session = MagicMock()
+ session.new = [object()] if mode == "pending" else []
+ session.dirty = session.deleted = []
+ if mode in ("owned_failure", "nested_failure", "double_failure"):
+ session.add.side_effect = RuntimeError("private query and password")
+ if mode == "double_failure":
+ session.begin_nested.return_value.__exit__.side_effect = RuntimeError(
+ "private cleanup error"
+ )
+
+ @contextmanager
+ def get_session(*args):
+ try:
+ yield session
+ finally:
+ if mode == "double_failure":
+ raise RuntimeError("private cleanup error")
+
+ writer = MagicMock()
+ writer.get_session.side_effect = get_session
+ monkeypatch.setattr(thread_metrics, "metrics_writer", writer)
+ monkeypatch.setattr(session_context, "get_user_db_session", get_session)
+ monkeypatch.setattr(
+ thread_local_session.thread_session_manager,
+ "in_scope",
+ lambda: (
+ mode
+ in (
+ "nested_failure",
+ "double_failure",
+ "nested_success",
+ "owner_mismatch",
+ "pending",
+ )
+ ),
+ )
+ borrow = MagicMock(
+ return_value=None if mode == "owner_mismatch" else session
+ )
+ monkeypatch.setattr(
+ thread_local_session.thread_session_manager,
+ "get_scoped_session",
+ borrow,
+ )
+ monkeypatch.setattr(
+ search_tracker,
+ "get_search_context",
+ lambda: (
+ None
+ if mode == "no_context"
+ else _context(mode != "missing_password")
+ ),
+ )
+ search_tracker.SearchTracker.record_search("test-engine", "private query")
+ snapshot = health.snapshot("alice")
+ assert snapshot["dropped_writes"] == int(expected_reason is not None)
+ if expected_reason:
+ assert snapshot["by_reason"][expected_reason] == 1
+ if mode in ("pending", "owner_mismatch"):
+ session.add.assert_not_called()
+ session.begin_nested.assert_not_called()
+ elif mode in ("success", "nested_success"):
+ session.add.assert_called_once()
+ if mode in (
+ "nested_failure",
+ "double_failure",
+ "nested_success",
+ "owner_mismatch",
+ "pending",
+ ):
+ borrow.assert_called_once_with("alice")
+ writer.get_session.assert_not_called()
+ session.commit.assert_not_called()
+ session.rollback.assert_not_called()
+ session.flush.assert_not_called()
+ assert "private" not in str(snapshot)
+
+
[email protected]("worker", [False, True])
+ "mode, reason",
+ [
+ ("success", None),
+ ("no_password", None),
+ ("write_error", "write_error"),
+ ("pending", "pending_transaction"),
+ ("owner_mismatch", "database_unavailable"),
+ ],
+)
+def test_scoped_tokens_report_skips_without_changing_the_transaction(
+ health, monkeypatch, worker, mode, reason
+):
+ import threading
+
+ from local_deep_research.database import (
+ thread_local_session,
+ thread_metrics,
+ )
+ from local_deep_research.metrics import token_counter
+
+ session = MagicMock()
+ session.new = [object()] if mode == "pending" else []
+ session.dirty = session.deleted = []
+ writer = MagicMock()
+ if mode == "write_error":
+ writer.add_token_metrics_to_session.side_effect = RuntimeError(
+ "private write error"
+ )
+ monkeypatch.setattr(thread_metrics, "metrics_writer", writer)
+ monkeypatch.setattr(
+ threading,
+ "current_thread",
+ lambda: SimpleNamespace(name="worker" if worker else "MainThread"),
+ )
+ manager = thread_local_session.thread_session_manager
+ monkeypatch.setattr(manager, "in_scope", lambda: True)
+ borrow = MagicMock(
+ return_value=None if mode == "owner_mismatch" else session
+ )
+ monkeypatch.setattr(manager, "get_scoped_session", borrow)
+ monkeypatch.setattr(token_counter, "get_current_username", lambda: "bob")
+ callback = token_counter.TokenCountingCallback(
+ research_context=_context(password=mode != "no_password")
+ )
+ callback._save_to_db(10, 5)
+
+ borrow.assert_called_once_with("alice")
+ snapshot = health.snapshot("alice")
+ assert snapshot["dropped_writes"] == int(reason is not None)
+ if reason:
+ assert snapshot["by_reason"][reason] == 1
+ assert health.snapshot("bob")["dropped_writes"] == 0
+ assert "private" not in str(snapshot)
+ assert writer.add_token_metrics_to_session.call_count == int(
+ mode not in ("pending", "owner_mismatch")
+ )
+ writer.write_token_metrics.assert_not_called()
+ writer.set_user_password.assert_not_called()
+ session.commit.assert_not_called()
+ session.rollback.assert_not_called()
+ session.flush.assert_not_called()
+ if mode in ("pending", "owner_mismatch"):
+ session.begin_nested.assert_not_called()
+
+
+ "mode, failures, reason",
+ [
+ ("normal", 0, None),
+ ("normal", 2, None),
+ ("normal", 3, "write_error"),
+ ("missing_password", 0, "missing_credentials"),
+ ("unavailable", 0, "database_unavailable"),
+ ("programmatic", 0, None),
+ ("no_context", 0, None),
+ ],
+)
+def test_rate_estimate_final_outcome(
+ health, monkeypatch, mode, failures, reason
+):
+ from local_deep_research.database import sqlcipher_utils
+ from local_deep_research.web_search_engines.rate_limiting import (
+ tracker as rate_module,
+ )
+
+ tracker = rate_module.AdaptiveRateLimitTracker(programmatic_mode=True)
+ tracker.programmatic_mode = mode == "programmatic"
+ tracker.recent_attempts["test-engine"] = [
+ {"wait_time": wait, "success": True} for wait in (1, 2, 3)
+ ]
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.first.return_value = None
+ calls = 0
+
+ @contextmanager
+ def get_session(*args):
+ nonlocal calls
+ calls += 1
+ if calls <= failures:
+ raise OperationalError(
+ "INSERT", {}, Exception("database is locked")
+ )
+ yield session
+
+ imports = MagicMock(
+ return_value={}
+ if mode == "unavailable"
+ else {"RateLimitEstimate": MagicMock()}
+ )
+ monkeypatch.setattr(rate_module, "_get_db_imports", imports)
+ monkeypatch.setattr(
+ rate_module,
+ "get_search_context",
+ lambda: (
+ None
+ if mode == "no_context"
+ else _context(mode != "missing_password")
+ ),
+ )
+ monkeypatch.setattr(tracker, "_resolve_session", get_session)
+ monkeypatch.setattr(sqlcipher_utils.time, "sleep", lambda _: None)
+ tracker._update_estimate("test-engine")
+ snapshot = health.snapshot("alice")
+ assert snapshot["dropped_writes"] == int(reason is not None)
+ if reason:
+ assert snapshot["by_reason"][reason] == 1
+ if mode == "normal":
+ assert calls == min(failures + 1, 3)
+ assert session.add.call_count == int(failures < 3)
+ else:
+ assert calls == 0
+ if mode in ("programmatic", "no_context"):
+ imports.assert_not_called()
+ # The adaptive calculation still completes even if persistence fails.
+ assert tracker.current_estimates["test-engine"]["base"] == 2
+
+
+def dashboard(monkeypatch):
+ from fastapi import FastAPI
+ from fastapi.templating import Jinja2Templates
+ from fastapi.testclient import TestClient
+ from jinja2 import ChoiceLoader, DictLoader
+ from starlette.middleware.sessions import SessionMiddleware
+
+ from local_deep_research.web.routers import metrics
+
+ # Render the actual page and help macros; omit only the unrelated site shell.
+ env = metrics.templates.env.overlay(
+ loader=ChoiceLoader(
+ [
+ DictLoader({"base.html": "{% block content %}{% endblock %}"}),
+ metrics.templates.env.loader,
+ ]
+ )
+ )
+ env.globals = {**env.globals, "url_for": lambda *a, **kw: "/navigation"}
+ monkeypatch.setattr(metrics, "templates", Jinja2Templates(env=env))
+ app = FastAPI()
+ app.add_middleware(SessionMiddleware, secret_key="test-session-secret")
+ app.include_router(metrics.router)
+ with TestClient(app) as client:
+ yield app, client, metrics.require_auth
+
+
+def test_dashboard_uses_authenticated_owner_and_fixed_reason_labels(
+ health, dashboard
+):
+ app, client, require_auth = dashboard
+ health.record("alice", "search", "missing_credentials")
+ health.record("bob", "tokens", "write_error")
+ health.record("bob", "tokens", "write_error")
+ app.dependency_overrides[require_auth] = lambda: "alice"
+ response = client.get("/metrics/?username=bob")
+ assert response.status_code == 200
+ assert 'id="metric-write-warning"' in response.text
+ assert "Missing database credentials: 1" in response.text
+ assert "Database write failures" not in response.text
+ assert (
+ "Recording problems since the server started: at least 1."
+ in " ".join(response.text.split())
+ )
+
+ app.dependency_overrides[require_auth] = lambda: "bob"
+ response = client.get("/metrics/")
+ assert "Database write failures: 2" in response.text
+ assert "Missing database credentials" not in response.text
+
+
+def test_dashboard_omits_warning_when_no_drops_recorded(health, dashboard):
+ app, client, require_auth = dashboard
+ health.record("alice", "tokens", "write_error")
+ app.dependency_overrides[require_auth] = lambda: "carol"
+ response = client.get("/metrics/")
+ assert response.status_code == 200
+ assert 'id="metric-write-warning"' not in response.text
+
+
+def test_anonymous_dashboard_does_not_expose_counts(health, dashboard):
+ _, client, _ = dashboard
+ health.record("alice", "tokens", "write_error")
+ response = client.get("/metrics/?username=alice")
+ assert response.status_code == 401
+ assert "metric-write-warning" not in response.text
diff --git a/tests/theme_tests/test_accent_ink_contrast.py b/tests/theme_tests/test_accent_ink_contrast.py
index 479bccbdd1..15e7996bb3 100644
--- a/tests/theme_tests/test_accent_ink_contrast.py
+++ b/tests/theme_tests/test_accent_ink_contrast.py
@@ -1025,8 +1025,10 @@ DYNAMIC_INLINE_STYLES = {
),
None,
),
- # metrics.html L975: an inline ternary of two literals.
- ("templates/pages/metrics.html", 975, "color"): (
+ # metrics.html L989: an inline ternary of two literals. Keyed at L975
+ # until PR 7330 inserted a 14-line metric-write-health warning block
+ # above it; the expression itself is unchanged.
+ ("templates/pages/metrics.html", 989, "color"): (
"item.success_status === 'success' ? 'green' : 'red'",
("green", "red"),
None,
@@ -1281,7 +1283,7 @@ def test_inline_style_scan_finds_the_known_expressions():
("templates/pages/journal_quality.html", 831, "background"),
("static/js/components/context-overflow.js", 577, "background"),
("static/js/components/details.js", 712, "color"),
- ("templates/pages/metrics.html", 975, "color"),
+ ("templates/pages/metrics.html", 989, "color"),
} <= set(found), sorted(found)
expanded = {
_allow_key(name, selector)