File size: 5,490 Bytes
978c21c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# ==============================================================================
# BRIDGE Modul X — Run-quality monitor (item 10, VALIDATOR-PERFORMANCE-REPORT §6)
# ==============================================================================
# A bulk run where most rows come back risky/unknown is a *systemic* failure —
# the original "64 verified · 0 good · 64 risky" bug looked exactly like this.
# This monitor computes the concerning share of a finished run and fires the
# existing signed webhook alert when it crosses a threshold.
#
# Monitoring convention (like error-rate SLO alerts): fires at >= threshold.
# `threshold=0` disables the monitor entirely.
# ==============================================================================

import time
from dataclasses import dataclass
from typing import Any, Dict, Iterable, Optional

import structlog

logger = structlog.get_logger("webhook_alerts")

try:
    from app.utils.webhook_alerts import WebhookDispatcher
except ImportError:  # pragma: no cover - standalone use without the app package
    WebhookDispatcher = None  # type: ignore[assignment]

# Statuses that mean "no decision was possible" — the concerning set. `invalid`
# is a definitive verdict (a decision *was* made) and must not count.
_CONCERNING = {"risky", "unknown", "error"}


@dataclass
class RateAlert:
    """Computed summary of one finished run, plus whether it breached."""

    total: int
    risky: int
    unknown: int
    error: int
    risky_rate: float
    threshold: float
    breached: bool


def check_risky_rate(rows: Iterable[Any], threshold: float = 0.5) -> Optional[RateAlert]:
    """Compute the risky/unknown/error share of a run's rows.

    Rows may be dicts (model_dump() output in the Celery/sync paths) or objects
    exposing ``.status`` (ValidationResult). Rows without a status are skipped.
    Returns None when the monitor is disabled (threshold <= 0), when the
    threshold is out of range (> 1), or when there is nothing to evaluate.
    """
    if threshold <= 0 or threshold > 1:
        return None

    counts = {"risky": 0, "unknown": 0, "error": 0}
    total = 0
    for row in rows:
        status = row.get("status") if isinstance(row, dict) else getattr(row, "status", None)
        if status is None:
            continue
        total += 1
        key = str(status).lower()
        if key in _CONCERNING:
            counts[key] += 1

    if total == 0:
        return None

    concerning = counts["risky"] + counts["unknown"] + counts["error"]
    rate = concerning / total
    return RateAlert(
        total=total,
        risky=counts["risky"],
        unknown=counts["unknown"],
        error=counts["error"],
        risky_rate=rate,
        threshold=threshold,
        breached=rate >= threshold,
    )


def get_system_alert_template(metric_name: str, threshold: float, current_value: float,
                              run_summary: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
    """System-alert payload for a breached run-quality threshold.

    Mirrors the shape of webhook_alerts.get_system_alert_template and adds the
    per-run breakdown so the receiver can diagnose without re-querying.
    """
    payload = {
        "sys_alert_id": f"sys_warn_{int(time.time())}",
        "severity": "WARNING",
        "system_status": "DEGRADED",
        "metric_violated": metric_name,
        "alert_conditions": {
            "threshold_limit": threshold,
            "active_value": current_value,
            "deviation_percentage": (
                round(((current_value - threshold) / threshold * 100), 1)
                if threshold > 0 else 100.0
            ),
        },
        "triggered_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
    }
    if run_summary is not None:
        payload["run_summary"] = run_summary
    return payload


async def maybe_alert_risky_rate(
    rows: Iterable[Any],
    webhook_url: Optional[str] = None,
    job_id: str = "sync",
    threshold: float = 0.5,
) -> Optional[bool]:
    """Check a finished run and fire the signed webhook when it breached.

    Returns True (dispatched), False (breached but delivery failed), None
    (healthy or monitor disabled). Never raises: an alerting failure must not
    turn a completed validation run into a failed one.
    """
    try:
        alert = check_risky_rate(rows, threshold=threshold)
    except Exception as exc:  # defensive: monitoring never breaks validation
        logger.warning("rate_check_failed", error=str(exc))
        return None

    if alert is None or not alert.breached:
        return None

    run_summary = {
        "job_id": job_id,
        "total": alert.total,
        "risky": alert.risky,
        "unknown": alert.unknown,
        "error": alert.error,
        "risky_rate": round(alert.risky_rate, 4),
        "threshold": alert.threshold,
    }
    payload = get_system_alert_template(
        "bulk_risky_rate", alert.threshold, alert.risky_rate, run_summary=run_summary
    )

    if not webhook_url or WebhookDispatcher is None:
        logger.warning(
            "bulk_risky_rate_breached_no_webhook",
            **run_summary,
        )
        return None

    try:
        ok = await WebhookDispatcher.dispatch(
            webhook_url, "SYSTEM_ALERT", payload
        )
        return bool(ok)
    except Exception as exc:
        logger.error("bulk_risky_rate_dispatch_failed", error=str(exc))
        return False