feat(alerts): an acknowledgement is on the record, with who made it (#5463)
#5463 "Acknowledgements on record: an event and who did it", step 1 of milestone 499 "Alerts you can trust". The live walk in #5461 found that acknowledging changed only the alert's current state: once it resolved, nothing said who had acknowledged it or when. - alert_events.actor_id (migration 0040): the person behind a transition. - Acknowledging writes a firing → acknowledged event by the acknowledger. - A rule edit, disable or enable that resets an alert carries its actor (web and MCP alike). - The history page notes "acknowledged by X" and "rule disabled by X"; MCP get_alert_history returns `by`. - One usernames() helper in alerts.service, used by the active list, the history page and the MCP tools. - docs/core/alerting.md: the state diagram no longer shows an acknowledged alert re-firing, and says what an event records. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -144,8 +144,9 @@ async def active_fragment():
|
||||
rules_off=sum(1 for r in rules if not r.enabled))
|
||||
|
||||
|
||||
def _history_row(event, rule) -> dict:
|
||||
"""One transition as the history page shows it."""
|
||||
def _history_row(event, rule, names: dict | None = None) -> dict:
|
||||
"""One transition as the history page shows it. `names` maps user ids to
|
||||
usernames: a transition a person made says who (#5463)."""
|
||||
from steward.core.alerts import MUTED, RELEASED
|
||||
from steward.core.formatting import metric_label, metric_value
|
||||
notes, muted_by, released = [], None, False
|
||||
@@ -156,6 +157,12 @@ def _history_row(event, rule) -> dict:
|
||||
released = True
|
||||
elif part:
|
||||
notes.append(part)
|
||||
actor = getattr(event, "actor_id", None)
|
||||
by = (names or {}).get(actor) or ("a deleted user" if actor else None)
|
||||
if event.to_state == "acknowledged":
|
||||
notes.insert(0, f"acknowledged by {by}" if by else "acknowledged")
|
||||
elif by and notes:
|
||||
notes[0] = f"{notes[0]} by {by}"
|
||||
metric = rule.metric_name
|
||||
if event.metric_value is None:
|
||||
value = f"No {metric_label(metric)} reading"
|
||||
@@ -193,14 +200,15 @@ async def alert_history():
|
||||
rule_id = chosen.id if chosen else None
|
||||
rows = await alert_svc.history(db, since, rule_id, PAGE_SIZE, before)
|
||||
show_notified, show_action = await alert_svc.history_columns(db, since, rule_id)
|
||||
names = await alert_svc.usernames(db, (e.actor_id for e, _ in rows))
|
||||
verdict = None
|
||||
if chosen and not before:
|
||||
every = await alert_svc.history(db, since, rule_id, HISTORY_SUMMARY_ROWS)
|
||||
verdict = summary(episodes([_history_row(e, r) for e, r in every], newest_page=True,
|
||||
now=now, since=since))
|
||||
rows, after = next_page(rows, lambda row: (row[0].transitioned_at, row[0].id))
|
||||
ctx = {"episodes": episodes([_history_row(e, r) for e, r in rows], newest_page=not before,
|
||||
now=now, since=since),
|
||||
ctx = {"episodes": episodes([_history_row(e, r, names) for e, r in rows],
|
||||
newest_page=not before, now=now, since=since),
|
||||
"after": after, "rules": rules, "chosen": chosen, "current_range": range_key,
|
||||
"show_notified": show_notified, "show_action": show_action, "verdict": verdict}
|
||||
if before:
|
||||
@@ -327,7 +335,7 @@ async def update_rule(rule_id: str):
|
||||
fields = await alert_svc.rule_fields(db, **_rule_form(form))
|
||||
except ValueError as exc:
|
||||
return str(exc), 400
|
||||
await alert_svc.apply_rule_change(db, rule, fields)
|
||||
await alert_svc.apply_rule_change(db, rule, fields, actor_id=session.get("user_id"))
|
||||
if apply_action:
|
||||
rule.ansible_action = ansible_action
|
||||
await log_audit(current_app, session.get("user_id"), session.get("username", ""),
|
||||
@@ -344,7 +352,8 @@ async def toggle_rule(rule_id: str):
|
||||
rule = result.scalar_one_or_none()
|
||||
if rule is None:
|
||||
return "Not found", 404
|
||||
await alert_svc.apply_rule_change(db, rule, {}, enabled=not rule.enabled)
|
||||
await alert_svc.apply_rule_change(db, rule, {}, enabled=not rule.enabled,
|
||||
actor_id=session.get("user_id"))
|
||||
action = "alert_rule.enabled" if rule.enabled else "alert_rule.disabled"
|
||||
await log_audit(current_app, session.get("user_id"), session.get("username", ""),
|
||||
action, entity_type="alert_rule", entity_id=rule.name)
|
||||
|
||||
+23
-11
@@ -203,18 +203,24 @@ async def breach_started(db, rule_ids) -> dict[str, datetime]:
|
||||
)).all())
|
||||
|
||||
|
||||
async def usernames(db, ids) -> dict[str, str]:
|
||||
"""{user id: username} for the given ids (None and repeats ignored)."""
|
||||
from steward.models.users import User
|
||||
ids = {i for i in ids if i}
|
||||
if not ids:
|
||||
return {}
|
||||
return dict((await db.execute(select(User.id, User.username).where(User.id.in_(ids)))).all())
|
||||
|
||||
|
||||
async def active_rows(db, now: datetime) -> list[dict]:
|
||||
"""The alerts page's active list, firing first, then no data, then
|
||||
acknowledged, then pending; within each the longest-running first. Each
|
||||
row: its state, rule, label, sentence, the link to what it watches, when
|
||||
the breach began, and who acknowledged it."""
|
||||
from steward.models.users import User
|
||||
alerts = await active_alerts(db)
|
||||
started = await breach_started(db, {rule.id for state, rule in alerts
|
||||
if state.state.value in _BREACHING})
|
||||
ackers = {s.acknowledged_by for s, _ in alerts if s.acknowledged_by}
|
||||
names = dict((await db.execute(
|
||||
select(User.id, User.username).where(User.id.in_(ackers)))).all()) if ackers else {}
|
||||
names = await usernames(db, (s.acknowledged_by for s, _ in alerts))
|
||||
rows = []
|
||||
for state, rule in alerts:
|
||||
label = alert_label(state)
|
||||
@@ -430,11 +436,12 @@ async def rule_fields(db, *, name: str, source_module: str, resource_name: str,
|
||||
WATCHED_FIELDS = ("source_module", "resource_name", "metric_name", "operator", "threshold")
|
||||
|
||||
|
||||
async def apply_rule_change(db, rule: AlertRule, fields: dict, *, enabled: bool | None = None) -> None:
|
||||
async def apply_rule_change(db, rule: AlertRule, fields: dict, *, enabled: bool | None = None,
|
||||
actor_id: str | None = None) -> None:
|
||||
"""Apply validated fields (and optionally enabled) to a rule, in the
|
||||
caller's transaction. A change to what it watches, or disabling or
|
||||
re-enabling it, puts its alert back to inactive and starts its silence
|
||||
watch over (core.alerts.reset_rule_state)."""
|
||||
watch over (core.alerts.reset_rule_state); the event says who did it."""
|
||||
from steward.core.alerts import reset_rule_state
|
||||
changed = [k for k in WATCHED_FIELDS if k in fields and getattr(rule, k) != fields[k]]
|
||||
for k, v in fields.items():
|
||||
@@ -444,11 +451,11 @@ async def apply_rule_change(db, rule: AlertRule, fields: dict, *, enabled: bool
|
||||
if enabled is not None:
|
||||
rule.enabled = bool(enabled)
|
||||
if disabling:
|
||||
await reset_rule_state(db, rule, "rule disabled")
|
||||
await reset_rule_state(db, rule, "rule disabled", actor_id)
|
||||
elif enabling:
|
||||
await reset_rule_state(db, rule, "rule enabled")
|
||||
await reset_rule_state(db, rule, "rule enabled", actor_id)
|
||||
elif changed:
|
||||
await reset_rule_state(db, rule, "rule changed: " + ", ".join(changed))
|
||||
await reset_rule_state(db, rule, "rule changed: " + ", ".join(changed), actor_id)
|
||||
|
||||
|
||||
async def add_rule(db, fields: dict, *, created_by: str, enabled: bool = True,
|
||||
@@ -462,11 +469,14 @@ async def add_rule(db, fields: dict, *, created_by: str, enabled: bool = True,
|
||||
return rule
|
||||
|
||||
|
||||
async def acknowledge(db, rule_id: str, user_id: str) -> AlertState:
|
||||
"""Acknowledge a firing alert, in the caller's transaction.
|
||||
async def acknowledge(db, rule_id: str, user_id: str | None) -> AlertState:
|
||||
"""Acknowledge a firing alert, in the caller's transaction, and record it
|
||||
in the alert's history as a firing → acknowledged event by `user_id`, so
|
||||
who saw it outlives the alert (#5463).
|
||||
|
||||
LookupError when the rule has no state; ValueError when it is not firing.
|
||||
"""
|
||||
from steward.core.alerts import _add_event
|
||||
state = (await db.execute(
|
||||
select(AlertState).where(AlertState.rule_id == rule_id))).scalar_one_or_none()
|
||||
if state is None:
|
||||
@@ -479,6 +489,8 @@ async def acknowledge(db, rule_id: str, user_id: str) -> AlertState:
|
||||
state.acknowledged_by = user_id
|
||||
state.acknowledged_at = now
|
||||
state.last_transition_at = now
|
||||
_add_event(db, rule_id, AlertStateEnum.firing.value, AlertStateEnum.acknowledged.value,
|
||||
None, now, actor_id=user_id)
|
||||
return state
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user