Spaces:
Running

File size: 8,310 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
"""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)