T0: absorb shared/ into backend — cot_logger→src/core, CotJsonFormatter→src/core/cot_formatter.py, _llm_http/_llm_health/ssl→src/core/utils; imports rewritten (26 prod + tests, patch targets); run.sh/backend.Dockerfile/requirements/.axiom source_dirs/semantic_health/AGENTS/INSTALL cleaned; ADR-0022 supersedes ADR-0015; fixed latent CI defects (ss_tools ImportError, record.message in logger tests, same-name test-module collision). ADR-0021 wire enrichment (additive): contract_id/claim/error_code/loc fields; _contract_id ContextVar + resolve_contract_id (explicit > belief_scope > declared-src mirror, derived src never mirrors); EXPLORE auto-loc via single frame walk; facade error auto-fill; 2KB payload cap with payload_truncated/payload_bytes markers; migrated 85 error="CODE" sites to error_code= (12 files); pilot editor/load.py; superset preview payload-bomb inlined bodies removed. Analytics SSOT src/core/log_stats.py (bond transition matrix, orphan-EXPLORE ratio, REFLECT pairing, intent families, coverage, insufficient-sample flag); pretty_cot.py --stats/--digest/--trajectory/--story over one engine; log_gap_service three-tier ground-truth triangulation (FAILED w/o EXPLORE etc.) + GET /api/reports/log-stats|task-log-gaps (polling-suppressed); scripts/cot_audit.py CLI; enriched fields persisted into task_logs.payload for tier queries. Frontend: ReportsAnalyticsModel + AnalyticsStatsPanel (Logs tab) + TaskGapPanel and per-row T1/T2/T3 gap badges (Tasks tab); cot-logger.ts ADR-0021 opts; i18n en/ru. Scheduler console spam fixed: apscheduler logger demoted to WARNING via LoggingConfig.scheduler_log_level. .axiom belief patterns -> $OBJ.* (alias undercount). molecular-cot-logging skill updated (fields, decision rules, tie-break, CLI) and synced. Reviewed orthogonally: F1 cot_span contract pollution, F2 cap boundary accounting, F3 digest over-dedup, F4 trace-state bound, F5 tier metadata — fixed with regression tests. Validation: backend 11287 passed + ruff + compileall; frontend 3446 passed + lint + build; CLI smoke on live app.log.
135 lines
5.5 KiB
Python
135 lines
5.5 KiB
Python
# #region Test.Api.AgentStatusRoutes [C:2] [TYPE Module] [SEMANTICS test,agent,llm,status,health]
|
|
# @BRIEF Unit tests for Agent LLM provider health status endpoint.
|
|
# @RELATION BINDS_TO -> [Api.Agent.Status]
|
|
|
|
import os
|
|
|
|
os.environ.setdefault("DATABASE_URL", "sqlite:///:memory:")
|
|
os.environ.setdefault("AUTH_DATABASE_URL", "sqlite:///:memory:")
|
|
os.environ.setdefault("SECRET_KEY", "test-secret-key-for-tests")
|
|
os.environ.setdefault("DEV_MODE", "true")
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
import pytest
|
|
from fastapi import FastAPI
|
|
from fastapi.testclient import TestClient
|
|
|
|
# Ensure backend/src is importable for src.api / src.core modules
|
|
_src = str(Path(__file__).resolve().parent.parent.parent / "src")
|
|
if _src not in sys.path:
|
|
sys.path.insert(0, _src)
|
|
|
|
|
|
def _make_client() -> TestClient:
|
|
"""Build a TestClient with the agent status router."""
|
|
from src.api.routes.agent_status import router
|
|
|
|
app = FastAPI()
|
|
app.include_router(router)
|
|
return TestClient(app)
|
|
|
|
|
|
class TestGetLlmStatus:
|
|
"""GET /api/agent/llm-status"""
|
|
|
|
@patch("src.core.utils.llm_health._check_llm_provider_health", AsyncMock(return_value="ok"))
|
|
@patch("src.core.utils.llm_health._llm_status", {"status": "ok", "last_error": ""})
|
|
def test_status_ok(self):
|
|
"""Returns ok when LLM provider is healthy."""
|
|
client = _make_client()
|
|
resp = client.get("/api/agent/llm-status")
|
|
|
|
assert resp.status_code == 200
|
|
data = resp.json()
|
|
assert data["status"] == "ok"
|
|
assert data["last_error"] == ""
|
|
assert data["retry_after_s"] == 0
|
|
|
|
@patch("src.core.utils.llm_health._check_llm_provider_health", AsyncMock(return_value="unavailable"))
|
|
@patch("src.core.utils.llm_health._llm_status", {"status": "unavailable", "last_error": "Provider unreachable"})
|
|
def test_status_unavailable(self):
|
|
"""Returns unavailable with retry_after_s > 0."""
|
|
client = _make_client()
|
|
resp = client.get("/api/agent/llm-status")
|
|
|
|
assert resp.status_code == 200
|
|
data = resp.json()
|
|
assert data["status"] == "unavailable"
|
|
assert data["last_error"] == "Provider unreachable"
|
|
assert data["retry_after_s"] == 30
|
|
|
|
@patch("src.core.utils.llm_health._check_llm_provider_health", AsyncMock(return_value="timeout"))
|
|
@patch("src.core.utils.llm_health._llm_status", {"status": "timeout", "last_error": "Request timed out"})
|
|
def test_status_timeout(self):
|
|
"""Returns timeout status."""
|
|
client = _make_client()
|
|
resp = client.get("/api/agent/llm-status")
|
|
|
|
assert resp.status_code == 200
|
|
assert resp.json()["status"] == "timeout"
|
|
|
|
@patch("src.core.utils.llm_health._check_llm_provider_health", AsyncMock(return_value="auth_error"))
|
|
@patch("src.core.utils.llm_health._llm_status", {"status": "auth_error", "last_error": "Invalid API key"})
|
|
def test_status_auth_error(self):
|
|
"""Returns auth_error status."""
|
|
client = _make_client()
|
|
resp = client.get("/api/agent/llm-status")
|
|
|
|
assert resp.status_code == 200
|
|
assert resp.json()["status"] == "auth_error"
|
|
assert resp.json()["last_error"] == "Invalid API key"
|
|
|
|
@patch("src.core.utils.llm_health._check_llm_provider_health", AsyncMock(return_value="ok"))
|
|
@patch("src.core.utils.llm_health._llm_status", {"status": "ok", "last_error": ""})
|
|
def test_no_auth_required(self):
|
|
"""Status endpoint does not require authentication."""
|
|
client = _make_client()
|
|
# No auth token — should still work since no Depends on get_current_user
|
|
resp = client.get("/api/agent/llm-status")
|
|
assert resp.status_code == 200
|
|
|
|
def test_check_health_called(self):
|
|
"""_check_llm_provider_health is called on each request."""
|
|
mock_check = AsyncMock(return_value="ok")
|
|
with (
|
|
patch("src.core.utils.llm_health._check_llm_provider_health", mock_check),
|
|
patch("src.core.utils.llm_health._llm_status", {"status": "ok", "last_error": ""}),
|
|
):
|
|
client = _make_client()
|
|
resp = client.get("/api/agent/llm-status")
|
|
|
|
assert resp.status_code == 200
|
|
mock_check.assert_called_once()
|
|
|
|
def test_force_param_bypasses_cache(self):
|
|
"""?force=true must reach _check_llm_provider_health(force=True) so the
|
|
"Retry now" button gets a fresh probe instead of the 30s cached status."""
|
|
mock_check = AsyncMock(return_value="unavailable")
|
|
with (
|
|
patch("src.core.utils.llm_health._check_llm_provider_health", mock_check),
|
|
patch("src.core.utils.llm_health._llm_status", {"status": "unavailable", "last_error": "Provider unreachable"}),
|
|
):
|
|
client = _make_client()
|
|
resp = client.get("/api/agent/llm-status?force=true")
|
|
|
|
assert resp.status_code == 200
|
|
assert resp.json()["status"] == "unavailable"
|
|
mock_check.assert_called_once_with(force=True)
|
|
|
|
def test_force_false_default_passes_no_force(self):
|
|
"""Without the force param the health check is called with force=False (cached)."""
|
|
mock_check = AsyncMock(return_value="ok")
|
|
with (
|
|
patch("src.core.utils.llm_health._check_llm_provider_health", mock_check),
|
|
patch("src.core.utils.llm_health._llm_status", {"status": "ok", "last_error": ""}),
|
|
):
|
|
client = _make_client()
|
|
resp = client.get("/api/agent/llm-status")
|
|
|
|
assert resp.status_code == 200
|
|
mock_check.assert_called_once_with(force=False)
|
|
# #endregion Test.Api.AgentStatusRoutes
|