Spaces:
Running

File size: 13,245 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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
"""Alerts (Phase 15): periodic checks per tenant, deduplicated rows, pluggable sinks.



Checks (each over ``WP_ALERTS_WINDOW_MINUTES`` unless noted):



* ``circuit_breaker`` - gateway denials "circuit breaker: ..." >= threshold;

* ``quota``           - gateway denials "quota: ..." >= threshold;

* ``audit_chain``     - ``core.gateway.audit.verify_chain`` fails (critical; tampering or

                        a bug - the hash chain of the tenant's audit log is broken);

* ``injection_spike`` - heuristic injection signals on inbound text >= threshold

                        (``core.observability.injection``; a signal, not a control);

* ``cost_anomaly``    - LLM cost in the last 24 h > factor x the daily mean of the 7 days

                        before, and above a floor.



An alert is a row in ``alerts`` (RLS; unique per tenant + dedupe key, so the same condition

in the same window alerts once) and is then sent to every sink: the log (always), a webhook

(``WP_ALERTS_WEBHOOK_URL``; JSON body signed with HMAC-SHA256 in ``X-WorkPilot-Signature``

when ``WP_ALERTS_WEBHOOK_SECRET`` is set) and the tenant's dashboard (the row itself, shown by

``GET /analytics/operations``). Alert payloads carry counts and ids, never message text.



``AlertMonitor.sweep`` runs as the DBOS cron workflow ``wp.alert_sweep``

(``core.observability.jobs``), fired by exactly one worker.

"""

from __future__ import annotations

import hashlib
import hmac
import json
import logging
import uuid
from collections.abc import Iterable, Sequence
from dataclasses import asdict, dataclass, field
from datetime import UTC, datetime, timedelta
from typing import Any, Protocol

import httpx
from sqlalchemy import func, or_, select
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession

from core.config import Settings, get_settings
from core.db.session import Database
from core.gateway.audit import verify_chain
from core.gateway.models import AuditLog
from core.observability.models import Alert, SecuritySignal

log = logging.getLogger(__name__)


@dataclass(frozen=True)
class AlertCandidate:
    tenant_id: uuid.UUID
    kind: str
    severity: str  # info | warning | critical
    message: str
    dedupe_key: str
    detail: dict[str, Any] = field(default_factory=dict)

    def payload(self) -> dict[str, Any]:
        d = asdict(self)
        d["tenant_id"] = str(self.tenant_id)
        return d


class AlertSink(Protocol):
    name: str

    async def send(self, alert: AlertCandidate) -> None: ...


class LogSink:
    name = "log"

    async def send(self, alert: AlertCandidate) -> None:
        level = logging.CRITICAL if alert.severity == "critical" else logging.WARNING
        log.log(level, "ALERT %s tenant=%s %s", alert.kind, alert.tenant_id, alert.message)


class WebhookSink:
    name = "webhook"

    def __init__(

        self,

        url: str,

        secret: str | None = None,

        *,

        transport: httpx.AsyncBaseTransport | None = None,

        timeout_s: float = 5.0,

    ) -> None:
        self.url = url
        self.secret = secret
        self.transport = transport
        self.timeout_s = timeout_s

    async def send(self, alert: AlertCandidate) -> None:
        body = json.dumps(alert.payload(), sort_keys=True).encode()
        headers = {"Content-Type": "application/json"}
        if self.secret:
            sig = hmac.new(self.secret.encode(), body, hashlib.sha256).hexdigest()
            headers["X-WorkPilot-Signature"] = f"sha256={sig}"
        async with httpx.AsyncClient(transport=self.transport, timeout=self.timeout_s) as c:
            r = await c.post(self.url, content=body, headers=headers)
            r.raise_for_status()


def sinks_from_settings(settings: Settings | None = None) -> list[AlertSink]:
    s = settings or get_settings()
    sinks: list[AlertSink] = [LogSink()]
    if s.alerts_webhook_url:
        secret = s.alerts_webhook_secret.get_secret_value() if s.alerts_webhook_secret else None
        sinks.append(WebhookSink(s.alerts_webhook_url, secret))
    return sinks


def _bucket(now: datetime, minutes: int) -> str:
    return str(int(now.timestamp() // (max(minutes, 1) * 60)))


async def _denials(s: AsyncSession, prefix: str, since: datetime) -> int:
    return int(
        (
            await s.execute(
                select(func.count())
                .select_from(AuditLog)
                .where(
                    AuditLog.decision == "denied",
                    AuditLog.at >= since,
                    AuditLog.reason.like(f"{prefix}%"),
                )
            )
        ).scalar_one()
    )


async def check_tenant(

    s: AsyncSession, tenant_id: uuid.UUID, settings: Settings, now: datetime

) -> list[AlertCandidate]:
    """All alert conditions for one tenant (the session is bound to it under RLS)."""
    from core.agent.runs import Run

    out: list[AlertCandidate] = []
    window = settings.alerts_window_minutes
    since = now - timedelta(minutes=window)
    bucket = _bucket(now, window)

    trips = await _denials(s, "circuit breaker", since)
    if trips >= settings.alerts_circuit_breaker_threshold:
        out.append(
            AlertCandidate(
                tenant_id,
                "circuit_breaker",
                "warning",
                f"{trips} circuit-breaker trips in the last {window} min",
                f"circuit_breaker:{bucket}",
                {"count": trips, "window_minutes": window},
            )
        )
    quota = await _denials(s, "quota", since)
    if quota >= settings.alerts_quota_threshold:
        out.append(
            AlertCandidate(
                tenant_id,
                "quota",
                "warning",
                f"{quota} quota denials in the last {window} min",
                f"quota:{bucket}",
                {"count": quota, "window_minutes": window},
            )
        )
    try:  # retention purges anchor the chain (Phase 18); verify from the anchor if present
        from core.ops.retention import verify_chain_anchored as verify
    except ImportError:
        verify = verify_chain
    chain = await verify(s, tenant_id)
    if not chain.ok:
        out.append(
            AlertCandidate(
                tenant_id,
                "audit_chain",
                "critical",
                f"audit chain verification failed at seq {chain.broken_at_seq}",
                f"audit_chain:{chain.broken_at_seq}",
                {"broken_at_seq": chain.broken_at_seq, "checked": chain.checked},
            )
        )
    signals = int(
        (
            await s.execute(
                select(func.count())
                .select_from(SecuritySignal)
                .where(SecuritySignal.kind == "injection", SecuritySignal.created_at >= since)
            )
        ).scalar_one()
    )
    if signals >= settings.alerts_injection_threshold:
        out.append(
            AlertCandidate(
                tenant_id,
                "injection_spike",
                "warning",
                f"{signals} inbound messages flagged as possible prompt injection in the last "
                f"{window} min",
                f"injection_spike:{bucket}",
                {"count": signals, "window_minutes": window},
            )
        )
    day = now - timedelta(days=1)
    week = day - timedelta(days=7)
    last = float(
        (
            await s.execute(
                select(func.coalesce(func.sum(Run.cost_usd), 0.0)).where(Run.started_at >= day)
            )
        ).scalar_one()
        or 0.0
    )
    before = float(
        (
            await s.execute(
                select(func.coalesce(func.sum(Run.cost_usd), 0.0)).where(
                    Run.started_at >= week, Run.started_at < day
                )
            )
        ).scalar_one()
        or 0.0
    )
    mean = before / 7
    if last >= settings.alerts_cost_min_usd and last > settings.alerts_cost_anomaly_factor * mean:
        out.append(
            AlertCandidate(
                tenant_id,
                "cost_anomaly",
                "warning",
                f"LLM cost ${last:.2f} in the last 24 h vs ${mean:.2f}/day over the prior week",
                f"cost_anomaly:{now.date().isoformat()}",
                {"last_24h_usd": round(last, 4), "daily_mean_usd": round(mean, 4)},
            )
        )
    return out


async def record(s: AsyncSession, candidates: Iterable[AlertCandidate]) -> list[AlertCandidate]:
    """Insert alerts; return only the ones that are new (not deduplicated)."""
    new: list[AlertCandidate] = []
    for c in candidates:
        inserted = (
            await s.execute(
                insert(Alert)
                .values(
                    id=uuid.uuid4(),
                    tenant_id=c.tenant_id,
                    kind=c.kind,
                    severity=c.severity,
                    message=c.message,
                    detail=c.detail,
                    dedupe_key=c.dedupe_key,
                    status="open",
                    delivered={},
                )
                .on_conflict_do_nothing(constraint="uq_alerts_tenant_dedupe")
                .returning(Alert.id)
            )
        ).scalar_one_or_none()
        if inserted is not None:
            new.append(c)
    return new


@dataclass
class SweepReport:
    tenants: int = 0
    raised: list[dict[str, Any]] = field(default_factory=list)
    errors: list[str] = field(default_factory=list)


class AlertMonitor:
    def __init__(

        self,

        db: Database,

        owner_db: Database | None = None,

        *,

        settings: Settings | None = None,

        sinks: Sequence[AlertSink] | None = None,

    ) -> None:
        self.db = db
        self.owner_db = owner_db
        self.settings = settings or get_settings()
        self.sinks = list(sinks) if sinks is not None else sinks_from_settings(self.settings)

    async def active_tenants(self, now: datetime) -> list[uuid.UUID]:
        """Tenants with gateway or run activity in the last 8 days (owner role, cross-tenant)."""
        if self.owner_db is None:
            return []
        from core.agent.runs import Run

        since = now - timedelta(days=8)
        async with self.owner_db.session() as s:
            a = select(AuditLog.tenant_id).where(AuditLog.at >= since)
            r = select(Run.tenant_id).where(Run.started_at >= since)
            sig = select(SecuritySignal.tenant_id).where(SecuritySignal.created_at >= since)
            rows = await s.execute(a.union(r, sig))
            return sorted({row[0] for row in rows})

    async def sweep(

        self, tenant_ids: Iterable[uuid.UUID] | None = None, now: datetime | None = None

    ) -> SweepReport:
        now = now or datetime.now(UTC)
        report = SweepReport()
        ids = list(tenant_ids) if tenant_ids is not None else await self.active_tenants(now)
        for tid in ids:
            report.tenants += 1
            try:
                async with self.db.session(tenant_id=tid) as s, s.begin():
                    new = await record(s, await check_tenant(s, tid, self.settings, now))
            except Exception as exc:  # one tenant must not stop the sweep
                log.exception("alert checks failed for tenant %s", tid)
                report.errors.append(f"{tid}: {type(exc).__name__}")
                continue
            for c in new:
                report.raised.append(c.payload())
                await self._deliver(c)
        return report

    async def _deliver(self, c: AlertCandidate) -> None:
        delivered: dict[str, Any] = {}
        for sink in self.sinks:
            try:
                await sink.send(c)
                delivered[sink.name] = "ok"
            except Exception as exc:
                delivered[sink.name] = f"error: {type(exc).__name__}"
                log.warning("alert sink %s failed: %s", sink.name, type(exc).__name__)
        async with self.db.session(tenant_id=c.tenant_id) as s, s.begin():
            row = (
                await s.execute(select(Alert).where(Alert.dedupe_key == c.dedupe_key))
            ).scalar_one_or_none()
            if row is not None:
                row.delivered = delivered


async def recent_alerts(s: AsyncSession, since: datetime, limit: int = 20) -> list[Alert]:
    return list(
        (
            await s.execute(
                select(Alert)
                .where(or_(Alert.created_at >= since, Alert.status == "open"))
                .order_by(Alert.created_at.desc())
                .limit(limit)
            )
        ).scalars()
    )


# Process binding for the DBOS cron job (like core.channels.delivery.bind).
_monitor: AlertMonitor | None = None


def bind(monitor: AlertMonitor | None) -> None:
    global _monitor
    _monitor = monitor


def current() -> AlertMonitor | None:
    return _monitor