Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(api): honest dashboard metrics from the live case table
Alexandru Mateescub889baa79ec9
diff --git a/services/api/app/api/v1/endpoints/insights.py b/services/api/app/api/v1/endpoints/insights.pyindex b5a1e2ef9..410dea158 100644--- a/services/api/app/api/v1/endpoints/insights.py+++ b/services/api/app/api/v1/endpoints/insights.py@@ -48,6 +48,11 @@ from __future__ import annotationsimport loggingimport uuid++def _tid(t):+ """Bind a native UUID for raw SQL on uuid-typed columns (asyncpg)."""+ return t if isinstance(t, uuid.UUID) else uuid.UUID(str(t))+from datetime import UTC, datetime, timedeltafrom typing import Literal@@ -301,15 +306,16 @@ async def _case_sparkline("""24 evenly-spaced buckets of case-open volume across [start, end)."""total_seconds = max((end - start).total_seconds(), 1.0)bucket_seconds = total_seconds / _SPARKLINE_BUCKETS+ # Raw SQL on aisoc_cases — the ORM Case model reads the empty legacy+ # `cases` table, so the sparkline was flat zero for live tenants.rows = (await db.execute(- select(Case.created_at).where(- and_(- Case.tenant_id == tenant_id,- Case.created_at >= start,- Case.created_at < end,- )- )+ text(+ "SELECT created_at FROM aisoc_cases "+ "WHERE tenant_id = :tenant_id "+ "AND created_at >= :start AND created_at < :end"+ ),+ {"tenant_id": _tid(tenant_id), "start": start, "end": end},)).all()buckets = [0.0] * _SPARKLINE_BUCKETSdiff --git a/services/api/app/api/v1/endpoints/metrics.py b/services/api/app/api/v1/endpoints/metrics.pyindex 281734efb..e3d5e4925 100644--- a/services/api/app/api/v1/endpoints/metrics.py+++ b/services/api/app/api/v1/endpoints/metrics.py@@ -107,6 +107,8 @@ class DashboardMetrics(BaseModel):topMitre: list[MitreTactic]alertsTrend: list[TrendPoint]threatsBySource: list[SourceThreat]+ #: Echo of the selected window so the console can confirm what it fetched.+ period: str = "24h"# ───────────────────────────── v1.5 Funnel models ─────────────────────────────@@ -445,12 +447,14 @@ async def get_dashboard_metrics(MitreTactic(tactic=tactic, count=count) for tactic, count in sorted(tactic_counts.items(), key=lambda x: x[1], reverse=True)[:10]]- # ── 24-hour trend (hourly buckets) ────────────────────────────────────────- trend_start = now - timedelta(hours=24)+ # ── trend over the selected period ────────────────────────────────────────+ # Bucket by hour inside a day-scale window; `1h` still buckets by hour.+ trend_start = now - window+ bucket_fn = "minute" if period == "1h" else "hour"trend_rows = (await db.execute(select(- func.date_trunc("hour", Alert.created_at).label("bucket"),+ func.date_trunc(bucket_fn, Alert.created_at).label("bucket"),Alert.severity,func.count().label("cnt"),)@@ -484,6 +488,7 @@ async def get_dashboard_metrics(topMitre=top_mitre,alertsTrend=alerts_trend,threatsBySource=threats_by_source,+ period=period,)diff --git a/services/api/app/services/resolution_time.py b/services/api/app/services/resolution_time.pyindex 32204cf61..002aa375b 100644--- a/services/api/app/services/resolution_time.py+++ b/services/api/app/services/resolution_time.py@@ -34,6 +34,7 @@ asserts they report the same number for the same rows.from __future__ import annotations+import uuidfrom datetime import UTC, datetime, timedeltafrom sqlalchemy import text@@ -44,6 +45,11 @@ from sqlalchemy.ext.asyncio import AsyncSession# the account is being run now rather than a year ago.MTTR_WINDOW = timedelta(days=30)+def _tid(t):+ """Bind a native UUID for raw SQL on uuid-typed columns (asyncpg)."""+ return t if isinstance(t, uuid.UUID) else uuid.UUID(str(t))++# What "this case is finished" means. `closed_at` is written by the transition# into the terminal state, so its presence is the fact; `status` is a label# that has had several spellings. The `closed_at >= created_at` guard drops@@ -74,7 +80,7 @@ async def tenant_case_mttr_minutes(db: AsyncSession, tenant_id) -> float | None:AND closed_at >= :since"""),- {"tenant_id": str(tenant_id), "since": datetime.now(UTC) - MTTR_WINDOW},+ {"tenant_id": _tid(tenant_id), "since": datetime.now(UTC) - MTTR_WINDOW},)return float(value) if value is not None else None@@ -95,6 +101,6 @@ async def tenant_cases_closed(db: AsyncSession, tenant_id, since: datetime) -> iAND closed_at >= :since"""),- {"tenant_id": str(tenant_id), "since": since},+ {"tenant_id": _tid(tenant_id), "since": since},)return int(value or 0)diff --git a/services/api/tests/test_funnel_and_pipeline.py b/services/api/tests/test_funnel_and_pipeline.pyindex dbccb8fb4..aae01c14c 100644--- a/services/api/tests/test_funnel_and_pipeline.py+++ b/services/api/tests/test_funnel_and_pipeline.py@@ -96,16 +96,18 @@ class TestPctDelta:"""Period-over-period percentage helper.Tiny and pure — the contract is exactly two lines: zero-base- returns 0.0 (never ``inf``), otherwise round to two decimals.+ returns ``None`` ("no baseline" — a fake 0.0 became a fake +0%+ pill, and 1-from-16 unrounded scaled twice in the UI became the+ -9375% tile), otherwise round to two decimals as PERCENT."""- def test_zero_previous_returns_zero(self) -> None:+ def test_zero_previous_returns_none(self) -> None:from app.api.v1.endpoints.metrics import _pct_delta- # The dashboard cannot render ``inf`` or ``NaN`` — we'd- # rather show "no change" than a useless ∞ pill.- assert _pct_delta(10.0, 0.0) == 0.0- assert _pct_delta(0.0, 0.0) == 0.0+ # No baseline exists when the previous window was empty;+ # the UI renders None as "no baseline".+ assert _pct_delta(10.0, 0.0) is None+ assert _pct_delta(0.0, 0.0) is Nonedef test_positive_change(self) -> None:from app.api.v1.endpoints.metrics import _pct_deltadiff --git a/services/api/tests/test_resolution_time_parity.py b/services/api/tests/test_resolution_time_parity.pyindex 6444abaff..2ce1142e9 100644--- a/services/api/tests/test_resolution_time_parity.py+++ b/services/api/tests/test_resolution_time_parity.py@@ -98,12 +98,12 @@ async def _teardown(session) -> None:await session.rollback()await session.execute(text("DELETE FROM aisoc_cases WHERE tenant_id = ANY(:ids)"),- {"ids": [str(t) for t in _ALL_TENANTS]},+ {"ids": list(_ALL_TENANTS)},)await session.execute(text("DELETE FROM organizations WHERE id = :id"), {"id": str(ORG)})await session.execute(text("DELETE FROM tenants WHERE id = ANY(:ids)"),- {"ids": [str(t) for t in _ALL_TENANTS]},+ {"ids": list(_ALL_TENANTS)},)await session.commit()@@ -120,8 +120,8 @@ async def _case(session, *, tenant, number, opened_minutes_ago, duration_minutes"""),{- "id": str(uuid.uuid4()),- "tenant": str(tenant),+ "id": uuid.uuid4(),+ "tenant": tenant,"number": number,"title": f"parity fixture {number}","status": status,