Spaces:
Running
Running
Download core/observability/alerts.py from Aynkhn/WorkPilot-AI: direct link, hf CLI and curl.
- Browser
- Download file 13.2 kB
-
https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/observability/alerts.py
- Command line
-
hf download hf://spaces/Aynkhn/WorkPilot-AI/core/observability/alerts.py
-
curl -L -o alerts.py https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/observability/alerts.py
13.2 kB
| """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__) | |
| 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 | |
| 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 | |