"""Operations health read models and alerts (Phase 15). * ``GET /analytics/operations?days=N`` - error rates, approval latency (p50/p95), denial reasons grouped by category, quota and circuit-breaker trips, LLM cost (total, per run, per day), injection signals and recent alerts. Tenant-scoped through RLS. * ``GET /alerts`` - the tenant's alerts, newest first. * ``POST /alerts/{id}/ack`` - mark an alert acknowledged (manager or owner). """ from __future__ import annotations import uuid from datetime import UTC, datetime, timedelta from typing import Any from fastapi import APIRouter, Depends, HTTPException, Query, status from sqlalchemy import case, func, select from core.agent.runs import Run from core.api.routes.runs import services from core.approvals.models import Approval from core.auth.deps import Principal, current_principal, require_role from core.gateway.models import AuditLog from core.observability.alerts import recent_alerts from core.observability.models import Alert, SecuritySignal from core.services import Services from core.tenancy.models import Role router = APIRouter(tags=["observability"]) # Denial reason prefix -> category (the gateway's reason strings start with these). CATEGORIES = ( ("policy:", "policy"), ("quota:", "quota"), ("circuit breaker", "circuit_breaker"), ("idempotency", "idempotency"), ("invalid arguments", "validation"), ("unknown tool", "unknown_tool"), ("approval", "approval"), ("state changed", "stale_approval"), ("human", "human"), ) def category(reason: str | None) -> str: r = (reason or "").lower() for prefix, name in CATEGORIES: if r.startswith(prefix): return name if "kill switch" in r or "disabled" in r: return "kill_switch" return "other" def _alert(a: Alert) -> dict[str, Any]: return { "id": str(a.id), "kind": a.kind, "severity": a.severity, "message": a.message, "status": a.status, "detail": a.detail, "created_at": a.created_at.isoformat() if a.created_at else None, } @router.get("/analytics/operations") async def operations_health( days: int = Query(default=7, ge=1, le=90), p: Principal = Depends(current_principal), svc: Services = Depends(services), ) -> dict[str, Any]: since = datetime.now(UTC) - timedelta(days=days) async with svc.db.session(tenant_id=p.tenant_id) as s: runs = dict( ( await s.execute( select(Run.status, func.count()) .where(Run.started_at >= since) .group_by(Run.status) ) ).all() ) decisions = dict( ( await s.execute( select(AuditLog.decision, func.count()) .where(AuditLog.at >= since) .group_by(AuditLog.decision) ) ).all() ) lat = ( await s.execute( select( func.percentile_cont(0.5).within_group( func.extract("epoch", Approval.decided_at - Approval.created_at) ), func.percentile_cont(0.95).within_group( func.extract("epoch", Approval.decided_at - Approval.created_at) ), func.count(), ).where(Approval.decided_at.is_not(None), Approval.created_at >= since) ) ).one() reasons = ( await s.execute( select(AuditLog.reason, func.count()) .where( AuditLog.decision.in_(["denied", "rejected"]), AuditLog.at >= since, AuditLog.reason.is_not(None), ) .group_by(AuditLog.reason) .order_by(func.count().desc()) .limit(200) ) ).all() day = func.date_trunc("day", Run.started_at) cost_daily = ( await s.execute( select(day, func.coalesce(func.sum(Run.cost_usd), 0.0), func.count()) .where(Run.started_at >= since) .group_by(day) .order_by(day) ) ).all() aday = func.date_trunc("day", AuditLog.at) failed_calls_daily = ( await s.execute( select( aday, func.count(), func.sum(case((AuditLog.decision.in_(["failed", "denied"]), 1), else_=0)), ) .where(AuditLog.at >= since) .group_by(aday) .order_by(aday) ) ).all() injection = int( ( await s.execute( select(func.count()) .select_from(SecuritySignal) .where(SecuritySignal.kind == "injection", SecuritySignal.created_at >= since) ) ).scalar_one() ) alerts = await recent_alerts(s, since) total_runs = sum(runs.values()) total_calls = sum(decisions.values()) by_cat: dict[str, int] = {} top: list[dict[str, Any]] = [] for reason, n in reasons: by_cat[category(reason)] = by_cat.get(category(reason), 0) + n if len(top) < 10: top.append({"reason": reason, "count": n, "category": category(reason)}) total_cost = float(sum(float(c) for _, c, _ in cost_daily)) return { "days": days, "runs": {"total": total_runs, "failed": runs.get("failed", 0), "by_status": runs}, "run_error_rate": runs.get("failed", 0) / total_runs if total_runs else None, "tool_calls": { "total": total_calls, "failed": decisions.get("failed", 0), "denied": decisions.get("denied", 0), "by_decision": decisions, }, "tool_error_rate": decisions.get("failed", 0) / total_calls if total_calls else None, "approval_latency_s": { "p50": float(lat[0]) if lat[0] is not None else None, "p95": float(lat[1]) if lat[1] is not None else None, "decided": int(lat[2] or 0), }, "denials": {"by_category": by_cat, "top_reasons": top}, "quota_trips": by_cat.get("quota", 0), "circuit_breaker_trips": by_cat.get("circuit_breaker", 0), "injection_signals": injection, "cost": { "total_usd": total_cost, "per_run_usd": total_cost / total_runs if total_runs else None, "daily": [ {"date": d.date().isoformat(), "cost_usd": float(c), "runs": int(n)} for d, c, n in cost_daily ], "prices_verified": False, # see core.observability.costs }, "errors_daily": [ {"date": d.date().isoformat(), "calls": int(n), "failed_or_denied": int(f or 0)} for d, n, f in failed_calls_daily ], "alerts": [_alert(a) for a in alerts], } @router.get("/alerts") async def list_alerts( limit: int = Query(default=50, ge=1, le=200), p: Principal = Depends(current_principal), svc: Services = Depends(services), ) -> list[dict[str, Any]]: async with svc.db.session(tenant_id=p.tenant_id) as s: rows = ( await s.execute(select(Alert).order_by(Alert.created_at.desc()).limit(limit)) ).scalars() return [_alert(a) for a in rows] @router.post("/alerts/{alert_id}/ack") async def ack_alert( alert_id: uuid.UUID, p: Principal = Depends(require_role(Role.MANAGER)), svc: Services = Depends(services), ) -> dict[str, Any]: async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin(): a = await s.get(Alert, alert_id) if a is None: # also other tenants' alerts (RLS) raise HTTPException(status.HTTP_404_NOT_FOUND, "alert not found") a.status = "acknowledged" await s.flush() return _alert(a)