File size: 7,538 Bytes
81e3338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
CloudPulse — Weekly Intelligence Pass

Aggregates classified incidents over a date range and produces a natural-language
intelligence report. Powers the `POST /weekly` endpoint.

Two input modes:
  1. JSON list of classified incidents (provided by the caller)
  2. SQL query against Mădălina's TimescaleDB (when DATABASE_URL is set)

Mode 2 is preferred in production. Mode 1 is the contract Mădălina's pipeline
uses today: she batches a week's worth of classifications and posts them.

The aggregation logic is pure Python; only the natural-language summary uses
Claude Haiku. Hotspot detection and trend deltas are deterministic.
"""
from __future__ import annotations

import json
import os
from collections import Counter, defaultdict
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Any

from anthropic import Anthropic

CLAUDE_MODEL = "claude-haiku-4-5-20251001"

SUMMARY_SYSTEM_PROMPT = """You are an SRE intelligence analyst writing a weekly
incident summary for engineering leadership.

You will receive aggregated incident statistics. Produce a concise report with
these sections:

1. **Executive summary** — 2-3 sentences on the week's overall reliability picture.
2. **Top hotspots** — which providers and services drove the most severe incidents.
3. **Trend** — how this week compares to the previous week (volume, severity).
4. **What to watch next week** — 2-3 specific things engineering should monitor.

Be concrete. Reference numbers from the data. No hedging language. No generic
SRE advice. Write as if briefing a CTO."""


@dataclass
class WeeklyAggregation:
    """Pure Python aggregation result. No LLM in here."""
    period_start  : str
    period_end    : str
    total_incidents: int
    severity_counts: dict
    provider_severity_matrix: dict   # provider -> severity -> count
    service_severity_matrix : dict   # service  -> severity -> count
    top_hotspots_provider   : list   # [{"provider": ..., "severe_count": ...}]
    top_hotspots_service    : list
    severity_trend          : dict   # week-on-week deltas (if previous week given)
    notable_incidents       : list   # critical + high incidents, full descriptions

    def to_dict(self) -> dict:
        return {
            "period_start"            : self.period_start,
            "period_end"              : self.period_end,
            "total_incidents"         : self.total_incidents,
            "severity_counts"         : self.severity_counts,
            "provider_severity_matrix": self.provider_severity_matrix,
            "service_severity_matrix" : self.service_severity_matrix,
            "top_hotspots_provider"   : self.top_hotspots_provider,
            "top_hotspots_service"    : self.top_hotspots_service,
            "severity_trend"          : self.severity_trend,
            "notable_incidents"       : self.notable_incidents,
        }


def aggregate(
    incidents     : list[dict],
    period_start  : str,
    period_end    : str,
    previous_week : list[dict] | None = None,
    top_n         : int = 5,
) -> WeeklyAggregation:
    """Build the aggregation. Pure Python, deterministic, fast."""
    severity_counts = Counter(inc["final_severity"] for inc in incidents)

    provider_matrix = defaultdict(lambda: defaultdict(int))
    service_matrix  = defaultdict(lambda: defaultdict(int))
    for inc in incidents:
        sev = inc["final_severity"]
        provider_matrix[inc.get("provider", "unknown")][sev] += 1
        service_matrix[inc.get("service",  "unknown")][sev] += 1

    # Hotspots: providers/services with most critical+high incidents
    def severe_score(matrix_row):
        return matrix_row.get("critical", 0) * 2 + matrix_row.get("high", 0)

    top_providers = sorted(
        [(p, severe_score(s), dict(s)) for p, s in provider_matrix.items()],
        key=lambda t: -t[1],
    )[:top_n]
    top_services = sorted(
        [(s, severe_score(sv), dict(sv)) for s, sv in service_matrix.items()],
        key=lambda t: -t[1],
    )[:top_n]

    top_hotspots_provider = [
        {"provider": p, "severe_score": score, "severity_breakdown": breakdown}
        for p, score, breakdown in top_providers
    ]
    top_hotspots_service = [
        {"service": s, "severe_score": score, "severity_breakdown": breakdown}
        for s, score, breakdown in top_services
    ]

    severity_trend: dict = {}
    if previous_week:
        prev_counts = Counter(inc["final_severity"] for inc in previous_week)
        for sev in ["critical", "high", "medium", "low"]:
            curr = severity_counts.get(sev, 0)
            prev = prev_counts.get(sev, 0)
            severity_trend[sev] = {
                "this_week": curr,
                "last_week": prev,
                "delta"    : curr - prev,
                "delta_pct": ((curr - prev) / prev * 100) if prev > 0 else None,
            }

    # Notable incidents: critical and high, capped at 10 to keep prompt size bounded
    notable_incidents = [
        {
            "incident_id"   : inc.get("incident_id"),
            "provider"      : inc.get("provider"),
            "service"       : inc.get("service"),
            "final_severity": inc.get("final_severity"),
            "description"   : (inc.get("description") or "")[:300],
        }
        for inc in incidents
        if inc.get("final_severity") in {"critical", "high"}
    ][:10]

    return WeeklyAggregation(
        period_start=period_start,
        period_end=period_end,
        total_incidents=len(incidents),
        severity_counts=dict(severity_counts),
        provider_severity_matrix={p: dict(s) for p, s in provider_matrix.items()},
        service_severity_matrix={s: dict(sv) for s, sv in service_matrix.items()},
        top_hotspots_provider=top_hotspots_provider,
        top_hotspots_service=top_hotspots_service,
        severity_trend=severity_trend,
        notable_incidents=notable_incidents,
    )


def generate_summary(aggregation: WeeklyAggregation, anthropic_client: Anthropic) -> str:
    """Pass the aggregation to Claude Haiku and ask for a natural-language report."""
    payload = json.dumps(aggregation.to_dict(), indent=2)

    response = anthropic_client.messages.create(
        model=CLAUDE_MODEL,
        max_tokens=1500,
        system=SUMMARY_SYSTEM_PROMPT,
        messages=[{
            "role": "user",
            "content": f"Aggregated incident data for the period {aggregation.period_start} to {aggregation.period_end}:\n\n{payload}\n\nWrite the weekly intelligence report.",
        }],
    )
    return response.content[0].text.strip()


def build_weekly_report(
    incidents     : list[dict],
    period_start  : str,
    period_end    : str,
    anthropic_client: Anthropic,
    previous_week : list[dict] | None = None,
) -> dict:
    """Top-level entry point used by the FastAPI endpoint."""
    if not incidents:
        return {
            "period_start"   : period_start,
            "period_end"     : period_end,
            "total_incidents": 0,
            "summary"        : "No incidents in the requested period.",
            "aggregation"    : None,
        }

    agg = aggregate(incidents, period_start, period_end, previous_week=previous_week)
    summary = generate_summary(agg, anthropic_client)
    return {
        "period_start"   : period_start,
        "period_end"     : period_end,
        "total_incidents": agg.total_incidents,
        "summary"        : summary,
        "aggregation"    : agg.to_dict(),
    }