4 Commits
Author SHA1 Message Date
bvandeusenandClaude Opus 5.5 45aae6d585 feat(syslog): list patterns and add a ready-made one through MCP
CI / unit (push) Failing after 1m35s
CI / lint (push) Successful in 1s
CI / integration (push) Successful in 1m47s
CI / publish (push) Skipped
Patterns could only be added on the Syslog page, so an agent asked to map
them on the NASes couldn't. list_syslog_patterns gives each pattern's metric
and the ready-made ones not added; add_syslog_preset (admin, audited) adds one.
The key-picking helper moves beside the patterns for both callers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:04:34 -04:00
bvandeusenandClaude Opus 5.5 4cce3f0d12 feat(host_agent): the heat alert says which sensor set the temperature
"Host running hot" read the host's hottest sensor and didn't name it, so the
operator couldn't tell what hit 100 °C on VDNT-Util01. The alert email now
names the sensor and its reading, through the same names_behind a count uses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:04:34 -04:00
bvandeusenandClaude Opus 5.5 e51d969c43 feat(alerts): a rule can fire when a reading rises, "rose by N" (#6724)
A rule compared a reading with a fixed number, so Synology Disk 1's bad
sectors going from 3,160 to 3,392 could say nothing: a count that only grows
is soon past any line. "rose by" compares each reading with the one before it,
kept on the alert's state and only for such a rule. A fall (a replaced disk)
doesn't fire. On the rule form, through MCP, and worded in emails, the alert
sentence, history and the timeline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:03:29 -04:00
bvandeusenandClaude Opus 5.5 d83f8ffe9b fix(anomalies): a level over its usual hold opens an anomaly only past its usual peak or once held (#6723)
Rows on the live instance were mostly bursts of a few minutes: 28 of 52
peaked within the metric's own usual peak, and 42 of 52 latest occurrences
lasted 30 minutes or less, which is what a burst shorter than the 15-minute
average looks like once its span is back-dated. Nothing asked how high or how
long, as the System 182 ruling says a normal records.

A departure now also has to be past the slot's usual peak, or held: the
median of the last hour over the same line. Those spans were also keeping the
burstiest hours out of learning, lowering the usual lines further.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:01:55 -04:00
28 changed files with 364 additions and 46 deletions
+1 -1
View File
@@ -105,7 +105,7 @@ A two-minute spike raises the peak and leaves the p95 low; an hour spent at that
A metric a plugin registers with `learn_normal()` gets a normal per hour of the day, then per hour of the week once three weeks of history exist (`metric_norms`, relearned hourly by `metric_norms`; `steward/core/norms.py`).
Every minute, `metric_anomalies` averages each learned key's last 15 minutes and compares it with the normal for that hour. A level above the usual hold ×1.25, and above the metric's floor, opens an anomaly (`steward/core/anomalies.py`):
Every minute, `metric_anomalies` averages each learned key's last 15 minutes and compares it with the normal for that hour. A level above the usual hold ×1.25, and above the metric's floor, has departed. It opens an anomaly once it is also past the usual peak for that hour, or held: the median of the last hour is over the same line. A burst of a few minutes within the usual peak lifts the 15-minute average and opens nothing (`steward/core/anomalies.py`):
- `metric_anomalies` holds one row per item to review. A repeat while the row still waits joins it as another occurrence (`metric_anomaly_spans`).
- A row is `to_review` until someone marks it `normal` or `real` (Alerts → Anomalies, or MCP `review_anomaly`). An ended row nobody reviews within `anomalies.review_days` (14) becomes `lapsed`.
- Learning skips every hour an occurrence covers unless its anomaly was marked `normal`, so a new level is never learned without review.
+1
View File
@@ -73,6 +73,7 @@ Alert rules are created in the UI at `/alerts/`. Each rule requires:
- **Metric name** — the metric key (e.g. `response_time_ms`, `up`, `error_rate_5xx_pct`)
- **Operator** — `>`, `<`, `>=`, `<=`, `==`, `!=`
- **Threshold** — numeric value
- **rose by** — instead of a line to cross, fires when a reading is at least the threshold above the one before it, for a count that only grows (a disk's bad sectors). A fall doesn't fire. A reading that hasn't risen counts as OK, so the checks to clear set how long the alert stays up, and rises inside that are one alert
- **Consecutive failures required** — how many consecutive breaches before FIRING (default 1)
The form offers only what has reported, read from `plugin_metric_latest`.
+1 -1
View File
@@ -85,7 +85,7 @@ Each role includes the tools of the roles above it in this list.
| Traefik plugin | `list_routers` (each router graded as the Traefik page grades it, with the status codes behind a problem, what they mean and the swarm service behind it), `get_router` (one router's history, codes, normal and anomalies), `list_certificates` (served certificates, days left, the routers they cover), `get_traffic` (the access log's clients, countries and routers, and Traefik's own figures) |
| UniFi plugin | `get_network` (the WAN, clients, Wi-Fi networks, speed tests and devices by status), `list_devices`, `list_clients` (everyone seen, or the newest poll's top talkers), `list_network_events`, `list_alarms`, `get_network_config` (networks and VLANs, port forwards, firewall rules) |
| SNMP plugin | `list_snmp_devices` (each device's state, newest readings in their units and the readings it didn't return), `get_snmp_device` (one device's readings over a range). Never the community or v3 keys |
| Syslog plugin | `list_syslog_sources` (the devices sending syslog: added, offered or ignored, each with its rate, last heard and newest line), `search_syslog` (an added source's kept lines, or a host's, filtered by text, severity and worse, app and time, newest first) |
| Syslog plugin | `list_syslog_sources` (the devices sending syslog: added, offered or ignored, each with its rate, last heard and newest line), `search_syslog` (an added source's kept lines, or a host's, filtered by text, severity and worse, app and time, newest first), `list_syslog_patterns` (the phrases and severities counted, the metric each writes and the ready-made ones not added), `add_syslog_preset` (admin: add a ready-made one) |
| Prometheus plugin | `list_prometheus_targets` (each target's state and its newest scrape: series kept, dropped and over the cap), `get_prometheus_target` (a target's stored series by metric, with labels and newest values). Never the token, and a password in a URL is masked |
### Operator: run playbooks, change monitoring
+1 -1
View File
@@ -26,7 +26,7 @@ puts them beside Steward's other readings.
by the anomaly's host or SNMP device. Each anomaly row has "Syslog around
it". Host metrics charts and SNMP device charts mark each error with a
dashed red line.
- **MCP.** `list_syslog_sources` and `search_syslog`.
- **MCP.** `list_syslog_sources`, `search_syslog`, `list_syslog_patterns` and `add_syslog_preset`.
## Deploying
+4
View File
@@ -25,6 +25,10 @@ def setup(app: "Quart") -> None:
from steward.hosts.service import agent_stale_after_seconds
agent_heartbeat("host_agent", "seconds_since_seen", lambda: agent_stale_after_seconds(app.config))
agent_fed("host_agent", lambda resource: resource.split(":", 1)[0])
# temp_c_max stands for one of many sensors: its alert says which.
from steward.core.alerts import names_behind
from .routes import name_hottest_sensor
names_behind("host_agent", "temp_c_max", name_hottest_sensor)
# A reboot the agent announced is silence with a reason, for a while (#5756).
from datetime import datetime, timezone
from steward.core.alerts import agents_away
+21
View File
@@ -122,6 +122,27 @@ def is_thermometer(host_name: str, label: str, celsius: float) -> bool:
return label not in sensors.unwired(host_name) and counts_as_hottest(label, celsius)
def hottest_sensor(host_name: str, temps: dict[str, float]) -> list[str]:
"""Which sensor sets a host's temperature, as an alert on it says:
["Package id 0 at 86°C"], or [] with no thermometer among `temps`."""
from steward.core.formatting import metric_value
real = {label: c for label, c in temps.items() if is_thermometer(host_name, label, c)}
if not real:
return []
label = max(real, key=real.get)
return [f"{label} at {metric_value('temp_c', real[label])}"]
async def name_hottest_sensor(session, resource: str) -> list[str]:
"""The sensor behind temp_c_max on host `resource` right now."""
from steward.models.metrics import PluginMetricLatest
prefix = f"{resource}:temp:"
rows = (await session.execute(select(PluginMetricLatest.resource_name, PluginMetricLatest.value).where(
PluginMetricLatest.source_module == "host_agent", PluginMetricLatest.metric_name == "temp_c",
PluginMetricLatest.resource_name.startswith(prefix, autoescape=True)))).all()
return hottest_sensor(resource, {name[len(prefix):]: value for name, value in rows})
def split_temps(host_name: str, temps: dict) -> tuple[dict, dict]:
"""(real, unwired): a host's sensors, hottest first, apart from the ones
is_thermometer leaves out. Unwired ones map to (reading, why); they read
+52 -2
View File
@@ -8,12 +8,14 @@ from datetime import datetime
from sqlalchemy import select
from steward.core.paging import keyset
from steward.mcp.tools._audit import audit_mcp
from steward.mcp.tools._shape import age_s, clamp_limit, cut_middle, db_session, iso, lookback, now_utc, pick
from steward.models.hosts import Host
from steward.models.users import UserRole
from .models import SyslogLine, SyslogSource
from .models import SyslogLine, SyslogPattern, SyslogSource
from .parse import facility_name, severity_name
from .patterns import PRESETS, PRESETS_BY_KEY, SOURCE_MODULE, free_key, resource_of
from .service import (AROUND_LINES, AROUND_SEVERITY, LineFilter, addresses_by_name, device_address, filtered,
lines_between, place_for, rates, severity_level, shown_on, source_name, sources_for)
@@ -127,6 +129,53 @@ async def search_syslog(source: str = "", host: str = "", text: str = "", severi
return out
async def list_syslog_patterns() -> dict:
"""The phrases and severities counted in the kept syslog lines, and the
ready-made ones not added yet.
Each pattern's count of matching lines over its window is the metric
`metric` of source module `source_module`, per added source (`resources`,
empty until a source is added), written every minute with zeros included.
An alert rule on it ("> 0") fires on the first match and clears once the
window has passed. add_syslog_preset adds a ready-made one.
"""
async with db_session() as db:
patterns = list((await db.execute(select(SyslogPattern).order_by(SyslogPattern.name))).scalars())
accepted = list((await db.execute(
select(SyslogSource).where(SyslogSource.state == "accepted"))).scalars())
taken = {p.key for p in patterns}
return {"source_module": SOURCE_MODULE, "patterns": [{
"key": p.key, "name": p.name, "metric": p.metric, "phrases": p.phrases or [],
"severity_and_worse": severity_name(p.max_severity) if p.max_severity is not None else None,
"window_minutes": p.window_minutes, "enabled": p.enabled,
"resources": [resource_of(s) for s in accepted if p.source_id in (None, s.id)],
} for p in patterns], "presets_not_added": [{
"key": p.key, "name": p.name, "about": p.about,
} for p in PRESETS if p.key not in taken]}
async def add_syslog_preset(key: str) -> dict:
"""Add a ready-made pattern, counted for every added source. The same as
"Add" under Syslog → Patterns. Disk I/O errors, disk resets, NFS server
trouble, filesystem errors, degraded arrays and errors and worse:
list_syslog_patterns gives their keys. Recorded in the audit log as
"<you> via MCP".
"""
preset = PRESETS_BY_KEY.get((key or "").strip())
if preset is None:
raise ValueError(f"No preset {key!r}. Presets: {', '.join(p.key for p in PRESETS)}.")
async with db_session() as db, db.begin():
if (await db.execute(select(SyslogPattern).where(SyslogPattern.key == preset.key))).scalars().first():
raise ValueError(f"{preset.name!r} is already added.")
pattern = SyslogPattern(key=await free_key(db, preset.key), name=preset.name,
phrases=list(preset.phrases), max_severity=preset.max_severity)
db.add(pattern)
await db.flush()
added = {"pattern_id": pattern.id, "key": pattern.key, "name": pattern.name, "metric": pattern.metric}
await audit_mcp("syslog.pattern_added", "syslog_pattern", preset.name, {"preset": preset.key})
return added
def _as_events(lines: list[SyslogLine], sources: list[SyslogSource]) -> list[dict]:
from steward.mcp.tools._events import event
names = {s.id: source_name(s) for s in sources}
@@ -155,5 +204,6 @@ async def mcp_resource_events(db, source: str, resource: str, since, until) -> l
def register_tools(register) -> None:
for fn in (list_syslog_sources, search_syslog):
for fn in (list_syslog_sources, search_syslog, list_syslog_patterns):
register(fn, role=UserRole.viewer, read_only=True)
register(add_syslog_preset, role=UserRole.admin, read_only=False)
+10
View File
@@ -87,6 +87,16 @@ def key_for(name: str) -> str:
return _KEY.sub("_", name.lower()).strip("_")[:48] or "pattern"
async def free_key(db, wanted: str) -> str:
"""`wanted`, or that with a number where another pattern has it."""
taken = set((await db.execute(select(SyslogPattern.key))).scalars())
key, n = wanted, 2
while key in taken:
key = f"{wanted[:44]}_{n}"
n += 1
return key
def parse_form(form) -> dict:
"""A pattern's fields from its form, or PatternError saying what to fix."""
name = (form.get("name") or "").strip()[:100]
+3 -12
View File
@@ -21,7 +21,7 @@ from steward.models.users import UserRole
from .models import SyslogLine, SyslogPattern, SyslogSource
from .network import on_own_network
from .parse import SEVERITIES, facility_name, severity_name
from .patterns import (PRESETS, PRESETS_BY_KEY, SOURCE_MODULE, WINDOWS, PatternError, key_for, parse_form,
from .patterns import (PRESETS, PRESETS_BY_KEY, SOURCE_MODULE, WINDOWS, PatternError, free_key, key_for, parse_form,
resource_of)
from .receiver import LISTENER, MAX_SENDERS, send_to, settings
from .service import (AROUND_LINES, AROUND_SEVERITY, MARK_SEVERITY, MAX_MARKS, PANEL_LINES, PANEL_SPAN,
@@ -339,15 +339,6 @@ async def patterns_index():
any_sources=any(s.state == "accepted" for s in sources.values()))
async def _free_key(db, wanted: str) -> str:
taken = set((await db.execute(select(SyslogPattern.key))).scalars())
key, n = wanted, 2
while key in taken:
key = f"{wanted[:44]}_{n}"
n += 1
return key
async def _accepted_sources(db) -> list:
return list((await db.execute(select(SyslogSource).where(SyslogSource.state == "accepted")
.order_by(SyslogSource.name))).scalars())
@@ -368,7 +359,7 @@ async def add_preset(key: str):
abort(404)
async with current_app.db_sessionmaker() as db:
async with db.begin():
pattern = SyslogPattern(key=await _free_key(db, preset.key), name=preset.name,
pattern = SyslogPattern(key=await free_key(db, preset.key), name=preset.name,
phrases=list(preset.phrases), max_severity=preset.max_severity)
db.add(pattern)
await db.flush()
@@ -402,7 +393,7 @@ async def create_pattern():
async with db.begin():
if values["source_id"] and await db.get(SyslogSource, values["source_id"]) is None:
values["source_id"] = None
pattern = SyslogPattern(key=await _free_key(db, key_for(values["name"])), **values)
pattern = SyslogPattern(key=await free_key(db, key_for(values["name"])), **values)
db.add(pattern)
await db.flush()
pattern_id = pattern.id
+1 -1
View File
@@ -15,7 +15,7 @@ QUIET = frozenset({"inactive", "resolved"})
# The worst thing an episode went through, most severe first.
_SEVERITY = ("firing", "acknowledged", "no_data", "pending")
_WORDS = {">": "above", ">=": "at or above", "<": "below", "<=": "at or below",
"==": "at", "!=": "other than"}
"==": "at", "!=": "other than", "rose": "on a rise of"}
def fires_when(rule) -> str:
+1 -1
View File
@@ -15,7 +15,7 @@ from steward.models.users import UserRole
alerts_bp = Blueprint("alerts", __name__, url_prefix="/alerts")
_OPERATORS = [(op.value, op.value) for op in AlertOperator]
_OPERATORS = [(op.value, op.said) for op in AlertOperator]
def _form_condition(form) -> dict:
"""The operator and threshold the form asks for. An up/down metric's form
+4 -2
View File
@@ -154,7 +154,7 @@ def condition_text(metric: str, operator: AlertOperator | str, threshold: float)
if _is_breached(v, operator, threshold)]
if len(fires_on) == 1:
return f"is {fires_on[0]}"
return f"{metric_label(metric)} {operator.value} {metric_value(metric, threshold)}"
return f"{metric_label(metric)} {operator.said} {metric_value(metric, threshold)}"
def alert_sentence(rule: AlertRule, label: str, value: float | None,
@@ -175,7 +175,7 @@ def alert_sentence(rule: AlertRule, label: str, value: float | None,
# not how long ago someone acknowledged it (the page says that apart).
word = "breaching" if label == "acknowledged" else label
for_how_long = f", {word} for {held}" if held else f", {word}"
condition = f" ({rule.operator.value} {metric_value(metric, rule.threshold)})"
condition = f" ({rule.operator.said} {metric_value(metric, rule.threshold)})"
counted = count_words(metric, value)
if counted and rule.resource_name in WHOLE_RESOURCES:
# The count is the whole of it, and links where the swarm is shown.
@@ -599,6 +599,8 @@ async def rule_fields(db, *, name: str, source_module: str, resource_name: str,
threshold = float(threshold)
except (TypeError, ValueError):
raise ValueError(f"threshold must be a number, got {threshold!r}.") from None
if op == AlertOperator.rose and threshold <= 0:
raise ValueError("A rule on a rise needs how much it rises by, above 0.")
try:
consecutive = (1 if consecutive_failures_required in (None, "")
else int(consecutive_failures_required))
+15 -5
View File
@@ -81,9 +81,10 @@ def agents_away(hosts_away: Callable[[AsyncSession], Awaitable[set[str]]]) -> No
def names_behind(source_module: str, metric_name: str,
names: Callable[[AsyncSession, str], Awaitable[list[str]]]) -> None:
"""A figure that counts things: `await names(session, resource)` names
the things it counts right now ("web_app (0 of 1 running)"), so the
alert about it can say which. The plugin recording the figure registers it."""
"""A figure that counts things, or stands for one of several: `await
names(session, resource)` names them right now ("web_app (0 of 1 running)",
"Package id 0 at 86°C"), so the alert about it can say which. The plugin
recording the figure registers it."""
_NAMED[(source_module, metric_name)] = names
@@ -506,8 +507,14 @@ def _track_samples(state: AlertState, samples: list[PluginMetric], now: datetime
return note
def _is_breached(value: float, operator: AlertOperator, threshold: float) -> bool:
def _is_breached(value: float, operator: AlertOperator, threshold: float,
previous: float | None = None) -> bool:
"""Whether a reading breaks a condition. "rose" needs the reading before
it (`previous`): the first has nothing to have risen from, and a fall,
such as a replaced disk's count starting over, is no rise."""
op = operator.value
if op == "rose":
return previous is not None and value - previous >= threshold
if op == ">":
return value > threshold
if op == "<":
@@ -581,8 +588,10 @@ async def _evaluate_rule(
"""
from_state = state.state
step = next_step(from_state, state.consecutive_failure_count, state.consecutive_ok_count,
_is_breached(value, rule.operator, rule.threshold),
_is_breached(value, rule.operator, rule.threshold, state.last_value),
rule.consecutive_failures_required, rule.consecutive_ok_required)
if rule.operator == AlertOperator.rose:
state.last_value = value
state.consecutive_failure_count = step.fail_count
state.consecutive_ok_count = step.ok_count
notifications: list[tuple[str, str, str | None]] = []
@@ -627,6 +636,7 @@ async def reset_rule_state(session: AsyncSession, rule: AlertRule, note: str,
state.last_sample_at = None
state.sample_interval_s = None
state.no_data_since = None
state.last_value = None
state.state = AlertStateEnum.inactive
state.consecutive_failure_count = 0
state.consecutive_ok_count = 0
+47 -9
View File
@@ -2,8 +2,12 @@
Every minute the last WINDOW of each learned key is averaged and compared
with the normal for the slot it falls in (steward.core.norms). A level above
the slot's usual hold by DEPART times, and by at least the metric's floor,
opens an occurrence; the occurrence ends when the level comes back.
the slot's usual hold by DEPART times, and by at least the metric's floor, has
departed. That opens an occurrence once it is also outside what the normal
records in height or in time: higher than the slot's usual peak, or held, with
most of the last HELD above the line. A burst of a few minutes within the
usual peak lifts the average for a while and opens nothing. The occurrence ends
when the level comes back under the line.
What the operator ruled (System 182 "Metric Norms and Anomalies"):
- A departure is a warning, marked as a metric anomaly, and stays "to review"
@@ -28,6 +32,7 @@ from steward.timeline.record import anomaly_changed
WINDOW = timedelta(minutes=15) # the level judged is this window's average
DEPART = 1.25 # times the slot's usual hold that counts as a departure
HELD = timedelta(hours=1) # a level within the usual peak opens once the median of this is out
# An occurrence that comes back within one window of ending continues the
# same occurrence: a level wobbling around the line is one event, not ten.
REJOIN = WINDOW
@@ -118,6 +123,32 @@ async def levels_now(session, now: datetime) -> dict[tuple[str, str, str], float
return {(s, r, m): float(level) for s, r, m, level in rows}
# The median, as a burst moves an average of the same stretch but not this.
_HELD_LEVELS = text("""
SELECT k.s, k.r, k.m, v.held
FROM unnest(:sources, :resources, :metrics) AS k(s, r, m)
CROSS JOIN LATERAL (
SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY p.value) AS held FROM plugin_metrics p
WHERE p.source_module = k.s AND p.resource_name = k.r AND p.metric_name = k.m
AND p.recorded_at >= :since AND p.recorded_at <= :now
) v
WHERE v.held IS NOT NULL
""").bindparams(bindparam("sources", type_=ARRAY(String)), bindparam("resources", type_=ARRAY(String)),
bindparam("metrics", type_=ARRAY(String)))
async def held_levels(session, keys: list[tuple[str, str, str]], now: datetime) -> dict[tuple[str, str, str], float]:
"""{(source, resource, metric): the median of its last HELD}. Asked only of
keys that have departed and stayed within their usual peak, so the longer
read isn't paid for the rest."""
if not keys:
return {}
rows = await session.execute(_HELD_LEVELS, {
"sources": [k[0] for k in keys], "resources": [k[1] for k in keys], "metrics": [k[2] for k in keys],
"since": now - HELD, "now": now})
return {(s, r, m): float(held) for s, r, m, held in rows}
async def detect(session, now: datetime | None = None) -> dict:
"""One pass: open, extend and close occurrences. Runs inside the caller's
transaction. Returns {"opened", "closed"} counts."""
@@ -135,10 +166,13 @@ async def detect(session, now: datetime | None = None) -> dict:
}
opened = closed = 0
changed: list[MetricAnomaly] = [] # opened, joined or ended: their timeline entries follow
out_now = {key for key, level in levels.items()
if key in norms and departs(level, norms[key], LEARNED[(key[0], key[2])].least_departure)}
held = await held_levels(session, [key for key in out_now
if key not in open_now and levels[key] <= norms[key].usual_peak], now)
for key, level in levels.items():
norm = norms.get(key)
learned = LEARNED.get((key[0], key[2]))
out = norm is not None and learned is not None and departs(level, norm, learned.least_departure)
out = key in out_now
current = open_now.pop(key, None)
if current is not None:
span, anomaly = current
@@ -148,8 +182,11 @@ async def detect(session, now: datetime | None = None) -> dict:
_close(anomaly, span, now)
changed.append(anomaly)
closed += 1
elif out:
changed.append(await _occur(session, key, level, norm, now))
elif out and level > norm.usual_peak:
changed.append(await _occur(session, key, level, norm, now, WINDOW))
opened += 1
elif out and departs(held.get(key, 0.0), norm, LEARNED[(key[0], key[2])].least_departure):
changed.append(await _occur(session, key, level, norm, now, HELD))
opened += 1
# An open occurrence whose key stopped reporting, lost its normal or fell
# below its gate can't be judged any more: it ends now.
@@ -175,11 +212,12 @@ def _close(anomaly: MetricAnomaly, span: MetricAnomalySpan, now: datetime) -> No
anomaly.ended_at = now
async def _occur(session, key, level: float, norm: Norm, now: datetime) -> MetricAnomaly:
async def _occur(session, key, level: float, norm: Norm, now: datetime, judged_over: timedelta) -> MetricAnomaly:
"""A departure on a key with no open occurrence: join the key's anomaly
still to review, or open a new one. Returns the anomaly."""
still to review, or open a new one, starting where the stretch it was
judged over starts. Returns the anomaly."""
source, resource, metric = key
start = now - WINDOW
start = now - judged_over
anomaly = (await session.execute(
select(MetricAnomaly)
.where(MetricAnomaly.source_module == source, MetricAnomaly.resource_name == resource,
+2
View File
@@ -224,6 +224,8 @@ def alert_facts(alert: dict, tz: tzinfo, show_utc: bool = True) -> dict:
else _upper_first(f"{counted}{on} again.")
elif counted:
headline = _upper_first(f"{counted}{on}.")
elif state == "resolved" and alert.get("operator") == "rose":
headline = f"{metric_label(metric)}{on} has stopped rising" + (f", at {reading}." if reading else ".")
elif state == "resolved":
headline = f"{metric_label(metric)}{on} is back within its limit" + (
f", at {reading}." if reading else ".")
+6 -2
View File
@@ -23,7 +23,7 @@ def _condition(rule: AlertRule) -> str:
ok = rule.consecutive_ok_required or 1
tail = f" for {n} consecutive checks" if n > 1 else ""
clear = f"; clears after {ok} OK checks" if ok > 1 else ""
return f"{rule.metric_name} {rule.operator.value} {rule.threshold:g}{tail}{clear}"
return f"{rule.metric_name} {rule.operator.said} {rule.threshold:g}{tail}{clear}"
def _action(rule: AlertRule) -> dict | None:
@@ -288,7 +288,11 @@ async def create_alert_rule(name: str, source_module: str, resource: str, metric
`resource` as "". Steward then keeps one rule per host, named
"<name>: <host>", and adds one within a minute for a host that starts
reporting or joins the group. Only for host_agent.
operator: ">", "<", ">=", "<=", "==" or "!=".
operator: ">", "<", ">=", "<=", "==" or "!=", or "rose" to fire when a
reading is at least `threshold` above the one before it (for a count
that only grows). A falling reading doesn't fire, and the next reading
that hasn't risen counts as OK: clear_after_checks sets how long the
alert stays up, so repeats inside it are one alert.
consecutive_checks: how many checks in a row must breach before it fires
(default 1); higher values ride out a single blip.
clear_after_checks: how many checks in a row must be OK before a firing or
+9 -5
View File
@@ -52,7 +52,8 @@ def _row(v: anom.AnomalyView) -> dict:
async def list_anomalies(review: str = "to_review", limit: int = 50) -> dict:
"""Metric anomalies: a learned metric whose 15-minute level went well
above what is normal for it at that hour (its usual hold ×1.25, and by
more than the metric's floor).
more than the metric's floor), and either past how high it usually goes
(`usual_peak`) or held there for most of an hour.
review: "to_review" (default) — waiting for someone to mark them; "normal"
— accepted, their hours are learned; "real" — a real problem, not learned;
@@ -263,8 +264,9 @@ def slot_label(kind: str, slot: int) -> str:
def flag_above(norm_hold: float, floor: float) -> float:
"""The 15-minute level that would open an anomaly in a slot whose usual
hold is `norm_hold` (anomalies.departs)."""
"""The 15-minute level that has departed in a slot whose usual hold is
`norm_hold` (anomalies.departs). It opens an anomaly past the usual peak,
or once held."""
return max(norm_hold * anom.DEPART, norm_hold + floor)
@@ -287,8 +289,10 @@ async def get_metric_normal(source_module: str, resource: str, metric: str) -> d
(168 hours from Monday 00:00 UTC, once 21 days do). Each slot gives
`usual_hold` (the level its hours usually held: each hour's p95, at the
90th percentile across past days), `usual_peak` (how high they usually
went), `days_seen`, and `flag_above`: the 15-minute average that would
open an anomaly there (usual hold ×1.25, and at least `floor` above it).
went), `days_seen`, and `flag_above`: the 15-minute average that has
departed there (usual hold ×1.25, and at least `floor` above it). A
departure opens an anomaly once it passes `usual_peak`, or when the median
of the last hour is over `flag_above` too.
`floor` is the smallest departure worth calling an anomaly, and
`floor_setting` the Settings → Thresholds floor it comes from. Hours an
anomaly covers are learned only once someone marks it normal.
+1 -1
View File
@@ -190,7 +190,7 @@ async def get_host(host: str, parts_limit: int = 20) -> dict:
{
"rule_id": rule.id, "rule_name": rule.name, "state": alert_svc.alert_label(state),
"resource": rule.resource_name, "metric": rule.metric_name,
"condition": f"{rule.metric_name} {rule.operator.value} {rule.threshold:g}",
"condition": f"{rule.metric_name} {rule.operator.said} {rule.threshold:g}",
"since": iso(state.last_transition_at), "age_s": age_s(state.last_transition_at),
}
for state, rule in active
+1 -1
View File
@@ -127,7 +127,7 @@ def alert_findings(active, silent: dict[str, list[str]] | None = None) -> list[d
what += _also_silent(silent.get(rule.resource_name))
out.append(finding(
sev, f"alert_{s}", rule.name,
f"{rule.metric_name} {rule.operator.value} {rule.threshold:g} on "
f"{rule.metric_name} {rule.operator.said} {rule.threshold:g} on "
f"{rule.source_module}/{rule.resource_name} {what}",
since=state.no_data_since if s == "no_data" else state.last_transition_at,
ids={"rule_id": rule.id},
@@ -0,0 +1,28 @@
"""Alert rules: a condition that fires on a rise, and the reading before this one.
Revision ID: 0049_alert_on_a_rise
Revises: 0048_tickets
Create Date: 2026-10-30
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "0049_alert_on_a_rise"
down_revision: Union[str, None] = "0048_tickets"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ALTER TYPE ... ADD VALUE cannot run inside a transaction block.
with op.get_context().autocommit_block():
op.execute("ALTER TYPE alertoperator ADD VALUE IF NOT EXISTS 'rose'")
op.add_column("alert_states", sa.Column("last_value", sa.Float, nullable=True))
def downgrade() -> None:
# Postgres can't drop an enum value; 'rose' stays in the type, unused.
op.execute("DELETE FROM alert_rules WHERE operator = 'rose'")
op.drop_column("alert_states", "last_value")
+10
View File
@@ -14,6 +14,14 @@ class AlertOperator(str, enum.Enum):
lte = "<="
eq = "=="
ne = "!="
# The reading against the one before it, not against a fixed line: for a
# count that only grows, where any fixed line is soon behind it.
rose = "rose"
@property
def said(self) -> str:
"""The operator as a condition reads: "> 90", "rose by 1"."""
return "rose by" if self is AlertOperator.rose else self.value
class AlertStateEnum(str, enum.Enum):
@@ -96,6 +104,8 @@ class AlertState(Base):
last_sample_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
sample_interval_s: Mapped[float | None] = mapped_column(Float, nullable=True)
no_data_since: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
# The reading before this one, kept only for a rule that fires on a rise.
last_value: Mapped[float | None] = mapped_column(Float, nullable=True)
class MaintenanceWindow(Base):
+2 -1
View File
@@ -102,12 +102,13 @@
</div>
<div data-cond-numeric {% if binary %}hidden{% endif %} class="form-pair">
<div class="form-group">
<label>Fires when the reading is</label>
<label>Fires when the reading</label>
<select name="operator" {% if binary %}disabled{% endif %}>
{% for val, label in operators %}
<option value="{{ val }}" {% if rule and rule.operator.value == val %}selected{% endif %}>{{ label }}</option>
{% endfor %}
</select>
<p class="field-hint">"rose by" compares each reading with the one before it, for a count that only grows. A reading that hasn't risen counts as OK, so "Good checks in a row before it clears" sets how long the alert stays up.</p>
</div>
<div class="form-group">
<label>Threshold <span data-threshold-unit style="color:var(--text-muted);font-weight:normal;">{% if metric_unit(m0) %}({{ metric_unit(m0) }}){% endif %}</span></label>
+1 -1
View File
@@ -112,7 +112,7 @@ def alert_summary(type_: str, rule, value: float | None) -> str:
if metric in _BINARY:
reading = breach = f"{res} is {metric_value(metric, value)}"
else:
op = getattr(rule.operator, "value", rule.operator)
op = getattr(rule.operator, "said", rule.operator)
reading = f"{said} on {res} is {metric_value(metric, value)}"
breach = f"{reading} ({op} {metric_value(metric, rule.threshold)})"
return {
+16
View File
@@ -100,3 +100,19 @@ def test_the_verdict_counts_what_fired_and_for_how_long():
def test_an_up_or_down_rule_says_the_word():
assert fires_when(_rule(metric="is_up", op=AlertOperator.lt, threshold=0.5)) == "fires when down"
def test_a_rule_on_a_rise_reads_as_one():
rule = _rule(metric="disk_bad_sectors", op=AlertOperator.rose, threshold=1.0)
assert fires_when(rule).startswith("fires on a rise of ")
assert AlertOperator.rose.said == "rose by" and AlertOperator.gt.said == ">"
def test_a_rise_is_against_the_reading_before_it():
from steward.core.alerts import _is_breached
rose = AlertOperator.rose
assert _is_breached(3392.0, rose, 1.0, previous=3160.0)
assert not _is_breached(3392.0, rose, 1.0, previous=3392.0) # flat
assert not _is_breached(0.0, rose, 1.0, previous=3392.0) # a replaced disk starts over
assert not _is_breached(3392.0, rose, 1.0) # nothing to have risen from
assert not _is_breached(3161.0, rose, 5.0, previous=3160.0) # less than asked
+48
View File
@@ -230,3 +230,51 @@ def test_a_rule_without_state_gets_one_and_is_watched_again(app):
assert first == (1, 0) # the covering rule has no state of its own
assert second == 1 # a second pass adds nothing
assert state == AlertStateEnum.firing
def test_a_rule_on_a_rise_fires_on_the_rise_and_clears_after_its_ok_run(app):
from sqlalchemy import select
from steward.alerts import service as alert_svc
from steward.core.alerts import record_metric, record_metrics
from steward.models.alerts import AlertState, AlertStateEnum
from steward.models.metrics import PluginMetric
from steward.models.users import User, UserRole
async def _go():
tag = uuid.uuid4().hex[:8]
res = f"box-{tag}"
async with app.db_sessionmaker() as s:
async with s.begin():
user = User(username=f"rs-{tag}", email=f"rs-{tag}@test", password_hash="x",
role=UserRole.admin)
s.add(user)
await record_metrics(s, [PluginMetric(source_module="host_agent", resource_name=res,
metric_name="cpu_pct", value=100.0)])
await s.flush()
with pytest.raises(ValueError, match="above 0"):
await alert_svc.rule_fields(
s, name=f"flat {tag}", source_module="host_agent", resource_name=res,
metric_name="cpu_pct", operator="rose", threshold=0)
fields = await alert_svc.rule_fields(
s, name=f"rise {tag}", source_module="host_agent", resource_name=res,
metric_name="cpu_pct", operator="rose", threshold=1,
consecutive_failures_required=1, consecutive_ok_required=2)
rule = await alert_svc.add_rule(s, fields, created_by=user.id)
rule_id = rule.id
async def after(v):
async with app.db_sessionmaker() as s:
async with s.begin():
await record_metric(s, "host_agent", res, "cpu_pct", v)
async with app.db_sessionmaker() as s:
state = (await s.execute(select(AlertState).where(AlertState.rule_id == rule_id))).scalar_one()
return state.state
assert await after(100.0) == AlertStateEnum.inactive # the first has nothing to have risen from
assert await after(100.0) == AlertStateEnum.inactive # flat
assert await after(105.0) == AlertStateEnum.firing
assert await after(105.0) == AlertStateEnum.firing # one good check of two
assert await after(105.0) == AlertStateEnum.inactive
assert await after(40.0) == AlertStateEnum.inactive # a fall is no rise
asyncio.run(_go())
+39
View File
@@ -104,6 +104,45 @@ def test_a_level_within_its_normal_is_no_anomaly(app, src):
assert rows == []
def _hour_of(app, src: str, res: str, *, level: float, for_minutes: int, then: float = 10.0):
"""A detection pass after an hour reading `then`, with its last
`for_minutes` at `level`, against the normal that holds 10 and peaks at 20."""
from sqlalchemy import select
from steward.core.anomalies import detect
from steward.models.metrics import PluginMetric, PluginMetricLatest
from steward.models.norms import MetricAnomaly
async def _go():
async with app.db_sessionmaker() as s:
async with s.begin():
s.add_all(_norms(src, res))
s.add_all([PluginMetric(source_module=src, resource_name=res, metric_name=METRIC,
value=level if m < for_minutes else then,
recorded_at=NOW - timedelta(minutes=m)) for m in range(60)])
await s.merge(PluginMetricLatest(source_module=src, resource_name=res, metric_name=METRIC,
value=level, recorded_at=NOW))
async with s.begin():
await detect(s, NOW)
return list((await s.execute(select(MetricAnomaly).where(MetricAnomaly.resource_name == res))).scalars())
return asyncio.run(_go())
def test_a_burst_within_its_usual_peak_is_no_anomaly(app, src):
# 18 is over the line (15) and under the usual peak (20), for 15 minutes of the hour.
assert _hour_of(app, src, _res("burst"), level=18.0, for_minutes=15) == []
def test_a_burst_past_its_usual_peak_is_an_anomaly(app, src):
(a,) = _hour_of(app, src, _res("tall"), level=30.0, for_minutes=15)
assert a.started_at == NOW - timedelta(minutes=15)
def test_a_level_within_its_usual_peak_is_an_anomaly_once_held(app, src):
# The system running at its peaked rate: never past the peak, but not a burst.
(a,) = _hour_of(app, src, _res("held"), level=18.0, for_minutes=45)
assert a.started_at == NOW - timedelta(hours=1) and a.peak_level == 18.0
def test_a_step_change_stays_open_and_to_review(app, src):
from steward.core.anomalies import TO_REVIEW
res = _res("step")
+32
View File
@@ -290,6 +290,38 @@ def test_a_source_page_filters_its_lines_and_hosts_show_them(app):
asyncio.run(go())
def test_a_preset_is_added_once_through_mcp(app):
from sqlalchemy import delete
from steward.core.api_tokens import Caller
from steward.mcp import _context
from steward.models.users import UserRole
tools = _mod("mcp_tools")
SyslogPattern = _mod("models").SyslogPattern
async def go():
_context._app_ctx.set(app)
_context._caller_ctx.set(Caller(user_id=None, username="admin", role=UserRole.admin, token_id=0))
async with app.db_sessionmaker() as s:
async with s.begin():
await s.execute(delete(SyslogPattern).where(SyslogPattern.key == "nfs"))
with pytest.raises(ValueError, match="No preset"):
await tools.add_syslog_preset("no-such-preset")
added = await tools.add_syslog_preset("nfs")
assert added["metric"] == "lines_matching_nfs"
listed = await tools.list_syslog_patterns()
assert "nfs" in {p["key"] for p in listed["patterns"]}
assert "nfs" not in {p["key"] for p in listed["presets_not_added"]}
with pytest.raises(ValueError, match="already added"):
await tools.add_syslog_preset("nfs")
async with app.db_sessionmaker() as s:
async with s.begin():
await s.execute(delete(SyslogPattern).where(SyslogPattern.key == "nfs"))
asyncio.run(go())
def test_search_syslog_filters_and_pages(app):
from steward.core.api_tokens import Caller
from steward.mcp import _context
@@ -107,6 +107,13 @@ def test_stalled_mounts_are_counted_and_have_no_figures():
assert ("disk_used_pct", "d3:/nfs/media") not in idx
def test_the_heat_alert_names_the_sensor_that_set_it():
from plugins.host_agent.routes import hottest_sensor
temps = {"Package id 0": 86.0, "Composite": 40.0, "AUXTIN0": 110.0, "PCH_CHIP_CPU_MAX_TEMP": 0.0}
assert hottest_sensor("box", temps) == ["Package id 0 at 86°C"]
assert hottest_sensor("box", {"AUXTIN0": 110.0}) == []
def test_a_wired_board_input_still_counts():
"""#5759: below 100 °C a board input is a real reading."""
from plugins.host_agent.routes import counts_as_hottest