Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions frontend/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }[]
Expand Down
5 changes: 5 additions & 0 deletions frontend/src/pages/AdminPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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."
/>
<ServiceCard
name="Home Stats"
status={s.public_stats}
description="Home-page /stats/public cache refresh (every 4 min, off the request path). Stale if not refreshed for 15 min — catches a stalled refresh even when Beat itself is alive."
/>
<ServiceCard
name="Entity Index"
status={s.entity_index}
Expand Down
10 changes: 8 additions & 2 deletions frontend/src/pages/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { SearchResult, Ontology, api } from '../lib/api'
import SourceBadge from '../components/SourceBadge'
import { MOSQuery } from '../components/MOSQuery'
import { ResultList, TypeBadge } from '../components/ResultList'
import { useIsMobile } from '../hooks/useIsMobile'

// Re-exported for existing importers (Home.mos.test.tsx).
export { normalizeMos, isNamedClassQuery } from '../components/MOSQuery'
Expand Down Expand Up @@ -404,6 +405,7 @@ function KeywordSearch({ typeFilters, onTypeFiltersChange }: {
export default function Home() {
const [mode, setMode] = useState<Mode>('ontology')
const [typeFilters, setTypeFilters] = useState<EntityTypeFilter[]>([])
const isMobile = useIsMobile()

const { data: publicStats } = useQuery({
queryKey: ['public-stats'],
Expand All @@ -412,7 +414,7 @@ export default function Home() {
})

return (
<div style={{ maxWidth: 700, margin: '0 auto', padding: '5rem 1.5rem 3rem' }}>
<div style={{ maxWidth: 700, margin: '0 auto', padding: isMobile ? '2rem 1rem 2.5rem' : '5rem 1.5rem 3rem' }}>
<h1 style={{ color: 'var(--text)', fontSize: 28, fontWeight: 700, marginBottom: '0.5rem', textAlign: 'center' }}>
OntoExplorer
</h1>
Expand All @@ -421,7 +423,11 @@ export default function Home() {
</p>

{publicStats && (
<div style={{ display: 'flex', gap: 12, marginBottom: '2rem', flexWrap: 'wrap' }}>
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))',
gap: 12, marginBottom: '2rem',
}}>
<StatCard label="Ontologies" value={publicStats.total_ontologies} to="/ontologies" />
<StatCard label="Classes" value={publicStats.total_classes}
subtitle={publicStats.unique_classes != null ? `${publicStats.unique_classes.toLocaleString()} unique` : undefined}
Expand Down
4 changes: 3 additions & 1 deletion frontend/src/pages/Reuse.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,8 @@ export function Reuse() {
</div>
)}

<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11 }}>
<div style={{ overflowX: 'auto' }}>
<table style={{ width: '100%', minWidth: 520, borderCollapse: 'collapse', fontSize: 11 }}>
<thead>
<tr>
<Th onClick={() => clickHeader('name')}
Expand Down Expand Up @@ -164,6 +165,7 @@ export function Reuse() {
))}
</tbody>
</table>
</div>
</div>
)
}
4 changes: 3 additions & 1 deletion frontend/src/pages/Submissions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ export default function Submissions() {
No submissions yet.
</p>
) : (
<table style={{ width: '100%', borderCollapse: 'collapse', border: '1px solid var(--border)', borderRadius: 'var(--radius)', overflow: 'hidden' }}>
<div style={{ overflowX: 'auto' }}>
<table style={{ width: '100%', minWidth: 440, borderCollapse: 'collapse', border: '1px solid var(--border)', borderRadius: 'var(--radius)', overflow: 'hidden' }}>
<thead>
<tr style={{ textAlign: 'left', color: 'var(--text-dim)', fontSize: 'var(--font-size-sm)' }}>
<th style={{ padding: '0.5rem 0.75rem' }}>Submitted</th>
Expand Down Expand Up @@ -112,6 +113,7 @@ export default function Submissions() {
})}
</tbody>
</table>
</div>
)}
</div>
)
Expand Down
25 changes: 25 additions & 0 deletions ontoexplorer/api/admin/health.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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),
Expand All @@ -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
Expand Down Expand Up @@ -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"],
Expand Down
15 changes: 14 additions & 1 deletion ontoexplorer/modules/stats/public_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down
29 changes: 29 additions & 0 deletions tests/integration/test_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 9 additions & 4 deletions tests/unit/test_public_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down