diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 2e4243f0..56bdb84b 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -1074,6 +1074,7 @@ export interface AdminServiceStatus { oxigraph: string workers: string beat: string + public_stats: string entity_index: string entity_index_rows: number entity_index_drift: { version_id: string; redis: number; pg: number }[] diff --git a/frontend/src/pages/AdminPage.tsx b/frontend/src/pages/AdminPage.tsx index 831e7677..097cc152 100644 --- a/frontend/src/pages/AdminPage.tsx +++ b/frontend/src/pages/AdminPage.tsx @@ -344,6 +344,11 @@ export default function AdminPage() { status={s.beat} description="Celery Beat — scheduler for periodic tasks (hourly upstream-update poll, 15-min stale-diff refresh). Stale if no heartbeat for 120s." /> + ('ontology') const [typeFilters, setTypeFilters] = useState([]) + const isMobile = useIsMobile() const { data: publicStats } = useQuery({ queryKey: ['public-stats'], @@ -412,7 +414,7 @@ export default function Home() { }) return ( -
+

OntoExplorer

@@ -421,7 +423,11 @@ export default function Home() {

{publicStats && ( -
+
)} - +
+
clickHeader('name')} @@ -164,6 +165,7 @@ export function Reuse() { ))}
+
) } diff --git a/frontend/src/pages/Submissions.tsx b/frontend/src/pages/Submissions.tsx index 89702e8b..b489c57d 100644 --- a/frontend/src/pages/Submissions.tsx +++ b/frontend/src/pages/Submissions.tsx @@ -70,7 +70,8 @@ export default function Submissions() { No submissions yet.

) : ( - +
+
@@ -112,6 +113,7 @@ export default function Submissions() { })}
Submitted
+
)}
) diff --git a/ontoexplorer/api/admin/health.py b/ontoexplorer/api/admin/health.py index e9672813..a463de6f 100644 --- a/ontoexplorer/api/admin/health.py +++ b/ontoexplorer/api/admin/health.py @@ -97,6 +97,28 @@ def _check_beat() -> str: return f"error: {exc}" +def _check_public_stats() -> str: + """Return 'ok' if the home-page stats cache was refreshed recently, else 'error: …'. + + Catches a stalled `refresh_public_stats` beat task specifically — the task could + be erroring (or beat dead) while the generic 60s beat heartbeat still looks fine. + Threshold is well above the 4-min refresh cadence so normal jitter never trips it. + A missing marker right after a Redis wipe self-heals on the next refresh.""" + from datetime import UTC, datetime + from ontoexplorer.modules.stats.public_stats import PUBLIC_STATS_REFRESHED_AT_KEY + try: + r = redis_sync.from_url(get_settings().redis_url, decode_responses=True) + raw = r.get(PUBLIC_STATS_REFRESHED_AT_KEY) + if not raw: + return "error: no refresh recorded" + age = (datetime.now(UTC) - datetime.fromisoformat(raw)).total_seconds() + if age > 900: # 15 min — ~4x the beat cadence + return f"error: stale ({int(age)}s)" + return "ok" + except Exception as exc: + return f"error: {exc}" + + _WORKERS_CACHE_KEY = "admin:health:workers" _WORKERS_CACHE_TTL = 15 # seconds; overview polls every 10s from each api replica @@ -196,6 +218,7 @@ async def admin_overview( oxigraph_status, workers_status, beat_status, + public_stats_status, entity_index_result, ) = await asyncio.gather( _check_postgres(db), @@ -206,6 +229,7 @@ async def admin_overview( asyncio.to_thread(_check_oxigraph), asyncio.to_thread(_check_workers), asyncio.to_thread(_check_beat), + asyncio.to_thread(_check_public_stats), _check_entity_index(db), ) entity_index_status, entity_index_stats = entity_index_result @@ -407,6 +431,7 @@ def _fmt(dt) -> str | None: "oxigraph": oxigraph_status, "workers": workers_status, "beat": beat_status, + "public_stats": public_stats_status, "entity_index": entity_index_status, "entity_index_rows": entity_index_stats["total_rows"], "entity_index_drift": entity_index_stats["drift"], diff --git a/ontoexplorer/modules/stats/public_stats.py b/ontoexplorer/modules/stats/public_stats.py index 46a58bc9..9ccc712d 100644 --- a/ontoexplorer/modules/stats/public_stats.py +++ b/ontoexplorer/modules/stats/public_stats.py @@ -37,6 +37,13 @@ _RECOMPUTE_LOCK_KEY = "stats:public:recomputing" _RECOMPUTE_LOCK_TTL = 300 +# Marker stamped on every successful refresh, so the admin health check can tell a +# stalled stats refresh (beat dead, or the task erroring) from a healthy one even +# while the generic beat heartbeat is fine. Age-based: a long TTL (it's the age +# that matters, not existence) and the check trips well above the 4-min cadence. +PUBLIC_STATS_REFRESHED_AT_KEY = "stats:public:refreshed_at" +_REFRESHED_AT_TTL = 86400 + def _empty() -> dict: return { @@ -205,8 +212,14 @@ async def refresh_public_stats_cache(db: AsyncSession) -> dict: result = await compute_public_stats(db) try: + from datetime import datetime, timezone + r = _get_redis() + await asyncio.to_thread( + r.set, PUBLIC_STATS_CACHE_KEY, json.dumps(result), ex=PUBLIC_STATS_TTL + ) await asyncio.to_thread( - _get_redis().set, PUBLIC_STATS_CACHE_KEY, json.dumps(result), ex=PUBLIC_STATS_TTL + r.set, PUBLIC_STATS_REFRESHED_AT_KEY, + datetime.now(timezone.utc).isoformat(), ex=_REFRESHED_AT_TTL ) except Exception: pass diff --git a/tests/integration/test_admin.py b/tests/integration/test_admin.py index 45daaa30..29a81e64 100644 --- a/tests/integration/test_admin.py +++ b/tests/integration/test_admin.py @@ -52,6 +52,35 @@ async def test_admin_overview_returns_shape(client, user_and_key, monkeypatch): assert "jobs" in body assert "postgres" in body["services"] assert "celery_queue_depth" in body["services"] + assert "public_stats" in body["services"] + + +def _fake_redis_with(value): + fake = MagicMock() + fake.get.return_value = value + return fake + + +def test_check_public_stats_fresh_ok(monkeypatch): + from datetime import datetime, timezone + from ontoexplorer.api.admin import health + monkeypatch.setattr(health.redis_sync, "from_url", + lambda *a, **k: _fake_redis_with(datetime.now(timezone.utc).isoformat())) + assert health._check_public_stats() == "ok" + + +def test_check_public_stats_stale_errors(monkeypatch): + from datetime import datetime, timedelta, timezone + from ontoexplorer.api.admin import health + old = (datetime.now(timezone.utc) - timedelta(seconds=1200)).isoformat() + monkeypatch.setattr(health.redis_sync, "from_url", lambda *a, **k: _fake_redis_with(old)) + assert health._check_public_stats().startswith("error: stale") + + +def test_check_public_stats_missing_errors(monkeypatch): + from ontoexplorer.api.admin import health + monkeypatch.setattr(health.redis_sync, "from_url", lambda *a, **k: _fake_redis_with(None)) + assert health._check_public_stats() == "error: no refresh recorded" @pytest.mark.anyio diff --git a/tests/unit/test_public_stats.py b/tests/unit/test_public_stats.py index 3f813de4..7759da53 100644 --- a/tests/unit/test_public_stats.py +++ b/tests/unit/test_public_stats.py @@ -39,10 +39,15 @@ async def test_refresh_writes_cache_with_ttl(monkeypatch): result = await ps.refresh_public_stats_cache(db=MagicMock()) assert result == {"total_ontologies": 3} - key, payload = mock_r.set.call_args[0][0], mock_r.set.call_args[0][1] - assert key == ps.PUBLIC_STATS_CACHE_KEY - assert json.loads(payload) == {"total_ontologies": 3} - assert mock_r.set.call_args[1]["ex"] == ps.PUBLIC_STATS_TTL + # refresh writes two keys (the cache blob + the freshness marker); find the + # cache-blob write specifically rather than assuming call order. + cache_calls = [c for c in mock_r.set.call_args_list if c[0][0] == ps.PUBLIC_STATS_CACHE_KEY] + assert len(cache_calls) == 1 + assert json.loads(cache_calls[0][0][1]) == {"total_ontologies": 3} + assert cache_calls[0][1]["ex"] == ps.PUBLIC_STATS_TTL + # the freshness marker (for the admin beat-stall check) is written too + marker_calls = [c for c in mock_r.set.call_args_list if c[0][0] == ps.PUBLIC_STATS_REFRESHED_AT_KEY] + assert len(marker_calls) == 1 @pytest.mark.parametrize(