Skip to content

Commit e88d5b1

Browse files
brownjuly2003-codeJuliaEdomclaude
authored
feat(serving): alert history + alert-rule repository behind ControlPlaneStore (ADR 0010 slice 2) (#132)
* feat(serving): alert history + alert-rule repository behind ControlPlaneStore (ADR 0010 slice 2) Second rollout slice of ADR 0010: alert delivery history and the alert-rule repository (including mutable runtime state — state, fired_at, last_escalation_level, flap window, cooldown) move behind the ControlPlaneStore port. Pure extraction — table DDL, the YAML file format, and the dispatcher/router behavior are byte-compatible; no behavior change on the embedded (default) profile. - ControlPlaneStore gains log_alert_delivery / get_alert_delivery_history (mirrors the webhook attempt-log shape) and load_alert_rules / save_alert_rules (JSON-shaped records — the port doesn't import the AlertRule pydantic model, avoiding a cycle with alerts.dispatcher, which imports get_control_plane_store to resolve the store). - EmbeddedControlPlaneStore gains ensure_alert_history_table (moved verbatim from alerts/history.py, same catalog_ddl_lock discipline as its webhook siblings) and alert_rules_path_provider (mirrors conn_provider — resolved per call so app.state.alert_config_path swaps in tests keep working). - alerts/escalation.py and routers/alerts.py no longer reach query_engine._conn (structural ratchet test extended); create_alert / list_alerts / get_alert / update_alert / deactivate_alert now take the FastAPI app (resolving the store internally) instead of a bare Path. - src/serving/api/alerts/history.py removed; its DB-plumbing backwards-compat re-exports (get_alert_history, ensure_alert_history_table) retired from the alert_dispatcher.py shim — internal plumbing, not public SDK surface. Tests: tests/unit/test_control_plane_store.py gains alert history log + YAML rule-repository round-trip coverage; test_catalog_ddl_concurrency, test_alert_dispatcher_backcompat, test_alerts_router_unit, test_blocking_routes_offloaded and integration test_alert_dedup rewired to the new module/signatures. Verified: full unit+property 1561 passed, mypy strict clean, ruff clean, integration (docker/live excluded) 206 passed/19 skipped. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * style: ruff format tests/unit/test_control_plane_store.py --------- Co-authored-by: JuliaEdom <uedomskikh@gmail.com> Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
1 parent 55ec2fd commit e88d5b1

16 files changed

Lines changed: 460 additions & 255 deletions

‎CHANGELOG.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,30 @@ All notable changes to AgentFlow are documented in this file.
44

55
## [Unreleased]
66

7+
### Added — Alert history + alert-rule repository behind the ControlPlaneStore port (ADR 0010 slice 2, 2026-07-02)
8+
9+
- **Alert delivery history** (`alert_history`) moved behind `ControlPlaneStore`
10+
(`log_alert_delivery` / `get_alert_delivery_history`) — `alerts/escalation.py`
11+
and `routers/alerts.py` no longer reach `query_engine._conn`; the DDL
12+
(`ensure_alert_history_table`) moved to `control_plane/embedded.py` next to
13+
its webhook sibling, same catalog-DDL-lock discipline.
14+
- **Alert-rule repository** (`config/alerts.yaml`, including mutable runtime
15+
state — `state`, `fired_at`, `last_escalation_level`, flap window, cooldown)
16+
moved behind the port (`load_alert_rules` / `save_alert_rules`); the
17+
embedded adapter keeps the exact YAML file format, so `config/alerts.yaml`
18+
is unchanged on disk. `create_alert` / `list_alerts` / `get_alert` /
19+
`update_alert` / `deactivate_alert` now take the FastAPI `app` (resolving
20+
the store internally) instead of a bare config `Path`.
21+
- `src/serving/api/alerts/history.py` removed — its logic split between the
22+
store port (history log) and `alerts/dispatcher.py` (rule repository
23+
callers); the `get_alert_history` / `ensure_alert_history_table` backwards-
24+
compatible re-exports on `alert_dispatcher.py` are retired with it (both
25+
were internal DB-plumbing, not public SDK surface).
26+
- Structural ratchet test extended to `alerts/dispatcher.py`,
27+
`alerts/escalation.py` and `routers/alerts.py` — none may reach
28+
`query_engine._conn` directly. New `tests/unit/test_control_plane_store.py`
29+
coverage for the alert history log and the YAML rule-repository round-trip.
30+
731
### Added — ControlPlaneStore port + embedded adapter: webhook queue/log behind it (ADR 0010 slice 1, 2026-07-02)
832

933
- **New `src/serving/control_plane/`** — the `ControlPlaneStore` port and its

‎src/serving/api/alert_dispatcher.py‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@
22
33
Historical import path ``src.serving.api.alert_dispatcher`` kept for
44
``main.py``/routers. The clock, logger, and HTTP client live in their
5-
defining modules (``alerts.dispatcher``/``alerts.escalation``/``alerts.history``)
6-
and are patched there in tests — this module no longer tunnels them.
5+
defining modules (``alerts.dispatcher``/``alerts.escalation``) and are
6+
patched there in tests — this module no longer tunnels them. Alert-history
7+
persistence and the alert-rule repository moved behind ``ControlPlaneStore``
8+
in ADR 0010 slice 2 — resolve them via
9+
``src.serving.control_plane.get_control_plane_store``, not through this shim.
710
"""
811

912
from __future__ import annotations
@@ -18,10 +21,8 @@
1821
create_alert,
1922
deactivate_alert,
2023
ensure_alert_dispatcher,
21-
ensure_alert_history_table,
2224
get_alert,
2325
get_alert_config_path,
24-
get_alert_history,
2526
list_alerts,
2627
load_alerts,
2728
save_alerts,
@@ -38,10 +39,8 @@
3839
"create_alert",
3940
"deactivate_alert",
4041
"ensure_alert_dispatcher",
41-
"ensure_alert_history_table",
4242
"get_alert",
4343
"get_alert_config_path",
44-
"get_alert_history",
4544
"list_alerts",
4645
"load_alerts",
4746
"save_alerts",

‎src/serving/api/alerts/__init__.py‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
save_alerts,
1616
update_alert,
1717
)
18-
from .history import ensure_alert_history_table, get_alert_history
1918

2019
__all__ = [
2120
"DEFAULT_ALERTS_CONFIG_PATH",
@@ -27,10 +26,8 @@
2726
"create_alert",
2827
"deactivate_alert",
2928
"ensure_alert_dispatcher",
30-
"ensure_alert_history_table",
3129
"get_alert",
3230
"get_alert_config_path",
33-
"get_alert_history",
3431
"list_alerts",
3532
"load_alerts",
3633
"save_alerts",

‎src/serving/api/alerts/dispatcher.py‎

Lines changed: 24 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
from __future__ import annotations
22

33
import asyncio
4-
import json
54
import os
65
import secrets
76
import uuid
@@ -12,10 +11,7 @@
1211
import structlog
1312
from pydantic import BaseModel, Field, model_validator
1413

15-
try:
16-
import yaml
17-
except ImportError: # pragma: no cover
18-
yaml = None # type: ignore[assignment]
14+
from src.serving.control_plane import get_control_plane_store
1915

2016
if TYPE_CHECKING:
2117
from fastapi import FastAPI
@@ -92,30 +88,18 @@ def get_alert_config_path(app: FastAPI) -> Path:
9288
return Path(configured) if configured else DEFAULT_ALERTS_CONFIG_PATH
9389

9490

95-
def load_alerts(path: Path) -> list[AlertRule]:
96-
if not path.exists():
97-
return []
98-
raw = path.read_text(encoding="utf-8")
99-
if not raw.strip():
100-
return []
101-
data = yaml.safe_load(raw) if yaml is not None else json.loads(raw)
102-
config = AlertConfig.model_validate(data or {})
103-
return config.alerts
104-
105-
106-
def save_alerts(path: Path, alerts: list[AlertRule]) -> None:
107-
path.parent.mkdir(parents=True, exist_ok=True)
108-
payload = AlertConfig(alerts=alerts).model_dump(mode="json")
109-
content = (
110-
yaml.safe_dump(payload, sort_keys=False)
111-
if yaml is not None
112-
else json.dumps(payload, indent=2)
113-
)
114-
path.write_text(content, encoding="utf-8", newline="\n")
91+
def load_alerts(app: FastAPI) -> list[AlertRule]:
92+
store = get_control_plane_store(app)
93+
return [AlertRule.model_validate(record) for record in store.load_alert_rules()]
94+
95+
96+
def save_alerts(app: FastAPI, alerts: list[AlertRule]) -> None:
97+
store = get_control_plane_store(app)
98+
store.save_alert_rules([alert.model_dump(mode="json") for alert in alerts])
11599

116100

117101
def create_alert(
118-
path: Path,
102+
app: FastAPI,
119103
*,
120104
name: str,
121105
tenant: str,
@@ -126,7 +110,7 @@ def create_alert(
126110
webhook_url: str,
127111
cooldown_minutes: int,
128112
) -> AlertRule:
129-
alerts = load_alerts(path)
113+
alerts = load_alerts(app)
130114
now = datetime.now(UTC)
131115
rule = AlertRule(
132116
id=str(uuid.uuid4()),
@@ -143,23 +127,23 @@ def create_alert(
143127
updated_at=now,
144128
)
145129
alerts.append(rule)
146-
save_alerts(path, alerts)
130+
save_alerts(app, alerts)
147131
return rule
148132

149133

150-
def list_alerts(path: Path, tenant: str) -> list[AlertRule]:
151-
return [alert for alert in load_alerts(path) if alert.tenant == tenant and alert.active]
134+
def list_alerts(app: FastAPI, tenant: str) -> list[AlertRule]:
135+
return [alert for alert in load_alerts(app) if alert.tenant == tenant and alert.active]
152136

153137

154-
def get_alert(path: Path, alert_id: str, tenant: str) -> AlertRule | None:
155-
for alert in load_alerts(path):
138+
def get_alert(app: FastAPI, alert_id: str, tenant: str) -> AlertRule | None:
139+
for alert in load_alerts(app):
156140
if alert.id == alert_id and alert.tenant == tenant and alert.active:
157141
return alert
158142
return None
159143

160144

161-
def update_alert(path: Path, alert_id: str, tenant: str, updates: dict) -> AlertRule | None:
162-
alerts = load_alerts(path)
145+
def update_alert(app: FastAPI, alert_id: str, tenant: str, updates: dict) -> AlertRule | None:
146+
alerts = load_alerts(app)
163147
for index, alert in enumerate(alerts):
164148
if alert.id != alert_id or alert.tenant != tenant or not alert.active:
165149
continue
@@ -168,13 +152,13 @@ def update_alert(path: Path, alert_id: str, tenant: str, updates: dict) -> Alert
168152
payload["updated_at"] = datetime.now(UTC)
169153
updated = AlertRule.model_validate(payload)
170154
alerts[index] = updated
171-
save_alerts(path, alerts)
155+
save_alerts(app, alerts)
172156
return updated
173157
return None
174158

175159

176-
def deactivate_alert(path: Path, alert_id: str, tenant: str) -> bool:
177-
alerts = load_alerts(path)
160+
def deactivate_alert(app: FastAPI, alert_id: str, tenant: str) -> bool:
161+
alerts = load_alerts(app)
178162
changed = False
179163
for index, alert in enumerate(alerts):
180164
if alert.id != alert_id or alert.tenant != tenant or not alert.active:
@@ -186,7 +170,7 @@ def deactivate_alert(path: Path, alert_id: str, tenant: str) -> bool:
186170
changed = True
187171
break
188172
if changed:
189-
save_alerts(path, alerts)
173+
save_alerts(app, alerts)
190174
return changed
191175

192176

@@ -266,8 +250,7 @@ async def run(self) -> None:
266250
async def dispatch_alerts(self) -> int:
267251
from .escalation import dispatch_alert
268252

269-
path = get_alert_config_path(self.app)
270-
alerts = load_alerts(path)
253+
alerts = load_alerts(self.app)
271254
now = datetime.now(UTC)
272255
triggered = 0
273256
changed = False
@@ -279,7 +262,7 @@ async def dispatch_alerts(self) -> int:
279262
triggered += alert_triggered
280263
changed = changed or alert_changed
281264
if changed:
282-
save_alerts(path, alerts)
265+
save_alerts(self.app, alerts)
283266
return triggered
284267

285268
async def send_test_alert(self, alert: AlertRule) -> dict:

‎src/serving/api/alerts/escalation.py‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@
1010

1111
from src.serving.api.egress_guard import UnsafeEgressURLError, validate_public_url
1212
from src.serving.api.webhook_dispatcher import _event_body, _signature
13+
from src.serving.control_plane import get_control_plane_store
1314

1415
from .evaluator import evaluate_rule
15-
from .history import ensure_alert_history_table, log_alert_history
1616

1717
if TYPE_CHECKING:
1818
from .dispatcher import AlertDispatcher, AlertRule
@@ -248,8 +248,7 @@ async def deliver(
248248
change_pct: float | None = None,
249249
webhook_url: str | None = None,
250250
) -> dict:
251-
conn = dispatcher.app.state.query_engine._conn
252-
ensure_alert_history_table(conn)
251+
store = get_control_plane_store(dispatcher.app)
253252
delivery_id = str(uuid.uuid4())
254253
body = _event_body(payload)
255254
headers = {
@@ -270,10 +269,11 @@ async def deliver(
270269
await asyncio.to_thread(validate_public_url, target_url)
271270
except UnsafeEgressURLError as exc:
272271
error = f"unsafe egress URL: {exc}"
273-
log_alert_history(
274-
conn,
272+
store.log_alert_delivery(
275273
delivery_id=delivery_id,
276-
alert=alert,
274+
alert_id=alert.id,
275+
alert_name=alert.name,
276+
tenant=alert.tenant,
277277
metric=alert.metric,
278278
current_value=current_value,
279279
previous_value=previous_value,
@@ -322,10 +322,11 @@ async def deliver(
322322
]
323323
await asyncio.sleep(delay)
324324

325-
log_alert_history(
326-
conn,
325+
store.log_alert_delivery(
327326
delivery_id=delivery_id,
328-
alert=alert,
327+
alert_id=alert.id,
328+
alert_name=alert.name,
329+
tenant=alert.tenant,
329330
metric=alert.metric,
330331
current_value=current_value,
331332
previous_value=previous_value,

0 commit comments

Comments
 (0)