Iaroslav Kozlov Русский

Observability Anomaly detection with AI

Anomaly detection with AI

A service that checks the metrics of databases by catalogs of signals: it confirms a breach of a threshold, finds what has become unusual for a series against its own past and where it is heading, follows each finding as an episode, and reports to a chat, where a language model may add a hypothesis of the cause.

My work

I am rolling out anomaly detection on the metrics of databases: each series is checked against its own past, findings are followed as episodes, and a language model suggests a likely cause.

How it is built

The layout of my project as it is built, from its own description; how it runs in its environment is not shown. The database engines it watches, the metrics store, the model and the chat are not named. Its numbers are those of its description; where it says so, they are defaults.

data control

While no fresh metrics come

  • The healthcheck says UNKNOWN: there are no metrics, or they are stale.
  • The detector marks each series that stopped arriving no_data and skips its other checks: missing data is not taken for normal.
  • An anomaly found before is not counted as resolved because the collection broke.

Components

Press a component to read what it does.

Catalogs signals, YAML

YAML catalogs of signals: for each, the query to the metrics store, its unit, which direction is bad, a rise or a fall, the warn and crit thresholds where it has them, and the labels that name the object of the check, such as a cluster or a node.

Metrics the store

The store of the metrics, outside the project: the queries of the catalogs go to it.

Service each series

Runs the checks on a schedule or on a command, in one of two modes, and evaluates every series on its own.

Healthcheck three points

The first mode: is a set threshold broken now, and the breach confirmed? It checks that the data is fresh and that the breach holds.

Detector four checks

The second mode: what has become unusual for the series against its own past, and where is it heading? Four checks in order: missing data, usual behaviour, an absolute threshold, a trend to a limit.

Episodes state

The history of anomalies, kept between runs: an episode is named by its signal, the labels of its object and the type of anomaly, and has a state.

Model a hypothesis

A language model: it may group related findings and suggest a hypothesis of their cause.

Chat report, thread

Where the report goes, one for each system, with the details in a thread; commands to the service come from it too.

  1. Signals

    The catalogs say what to watch: a query, a unit, the bad direction, thresholds if any, and the labels of the object. The checks run on a schedule or on a command.

    My part I am rolling out this detection on the metrics of several database engines.

    In detail

    A signal in a YAML catalog holds the query to the metrics store, the unit, which direction is bad, a rise or a fall, the warn and crit thresholds if it has them, and the labels that define the object of the check: a cluster, a node. The service evaluates every series on its own, in one of two modes: the healthcheck asks whether a set threshold is broken now and the breach confirmed; the anomaly mode also asks what has become unusual against the series’ own past, and where the metric is heading.

    Where it breaks Each series is evaluated on its own, so a rise of latency on two clusters is two separate events; grouping related findings is left to the model, after the verdicts.

  2. Healthcheck

    The healthcheck wants fresh data and a breach that holds: by default three points in a row over the threshold, usually five minutes apart. A gap in the data breaks the run.

    In detail

    From the first point to the third, ten minutes. With a latency threshold of 0.5 s: 0.6 → 0.7 → 0.8 is FAIL; 0.2 → 0.3 → 0.8 is not yet a sustained breach, only a warning to watch; 0.6 → 0.7 → 0.8 → 0.2 is PASS now, as the breach is over; no metrics, or stale ones, is UNKNOWN. The verdict needs no language model. 2

    Where it breaks A required duration can make alerts more precise, but at a cost in recall and detection time, the SRE workbook warns: it does not scale with how bad the breach is, and a metric that keeps coming back under the threshold resets it and may never alert.

  3. Usual behaviour

    The detector first checks that the series still arrives: missing data is not normal. Then it compares the series with what is typical for it on the same weekday at the same hour.

    In detail

    A series that has stopped arriving, or whose window is covered too thinly, is no_data, and its other checks are skipped. Otherwise, by default, the last day at a five-minute step is set against four weeks of history at a thirty-minute step. The norm is the median, and the spread is the MAD, the median absolute deviation, which is robust to outliers. A deviation counts once it passes a robust z-score of 3.5 and holds three points in a row; further filters drop changes too small to matter and the artefacts of counter resets. A short rise is a spike, a fall a drop, and a deviation one way that covers the last three hours a level_shift. The method is a general one: Iglewicz and Hoaglin recommend a modified z-score over the median and the MAD, and labelling as potential outliers the values whose modified z-score is greater than 3.5 in absolute value. 1

    Where it breaks With little history the baseline is coarser: the detector first merges the weekdays, then uses one common band of the norm, and says so in its result.

  4. Limits

    An absolute threshold catches a dangerous value even when it has become usual for the series. A separate check forecasts a steady trend toward a limit, such as a disk filling up.

    In detail

    threshold_breach catches a dangerous value even when it has become usual for this series. trend_saturation looks for a steady trend toward a limit; a forecast may reach up to 30 days ahead, and is given only after checks of its quality and of the stability of its slope.

    Where it breaks A chance rise is not a trend: without the checks of quality and of the slope it would become a forecast that the disk is about to run out.

  5. Episodes

    In the anomaly mode each finding is an episode, named by its signal, its object’s labels and its type. Between runs it is new, ongoing, worsening, or resolved once no longer found.

    In detail

    The history of episodes is kept between runs, under an identifier built from the signal, the labels of the object and the type of anomaly; resolved means it is no longer found. The priority of a behavioural anomaly depends on the size of the change and on how long it lasts, not on the z-score alone, so that a small wobble of a quiet metric does not outrank a serious fall of load.

    Where it breaks If the collection of metrics breaks, an anomaly found before is not counted as resolved: data that does not come is no recovery.

  6. Hypothesis

    After the detector, a language model may group related findings and suggest a hypothesis of their cause. The verdicts are computed before it: the model adds an explanation, not a decision.

    In detail

    For example, a rise of latency, of IOPS and of the queue of requests together may point to a limit of the disks. It stays a hypothesis, and a failure of the model does not change a computed verdict; in the healthcheck mode the model is not needed for the verdict at all. 3

    Where it breaks Findings that move together are a correlation, not a proof of cause: a variable may be useful for forecasting another without causing it, the forecasting textbook reminds. So the model’s answer stays a hypothesis.

  7. Report

    A report goes to the chat for each system, with the details in a thread. Commands come from the chat too, and the checks also run on a schedule.

    In detail

    The report is formed after the detector, one for each system, with the details in a thread. The service takes commands and runs the checks on a schedule; the bot itself runs only the permitted checks of metrics.

    Where it breaks The bot looks and does not touch: it is built to run no commands on servers and to change nothing in the databases it watches; a command in the chat has no way to make it do either.

The whole diagram

Anomaly detection with AI

Every component and step of the figure, drawn at once; the page lists them in text.

data control

Code: an example

The detector in Python

Written for this page to show the mechanism in code: it is not the project’s code. Plain Python 3.10 or later, no dependencies; the tests run with python -m unittest. The numbers the project’s description gives are its defaults; those it does not give are marked as this example’s own.

detector.py The four checks, in the order of the stops. 213 lines

Lines 1–42 The constants come in two groups: STEP, RECENT, Z_LIMIT, HOLD, SHIFT_SPAN and HORIZON are the description’s defaults, while MIN_COVERAGE to Z_CAP are this example’s own, as the description gives no numbers for them.

"""A detector of anomalies in one metric series, as the story on this page draws it.

Written for the page to show the mechanism; it is not the project's code. Plain Python 3.10+,
no dependencies. A series is a list of (timestamp, value) points, oldest first.

The checks run in the story's order:
  1. no_data          - the series stopped arriving, or the window is covered too thinly
  2. spike, drop,     - the series left what is usual for it on the same weekday and hour
     level_shift
  3. threshold_breach - an absolute threshold is crossed, however usual the value has become
  4. trend_saturation - a steady trend runs into a limit, such as a full disk
Only no_data stops the others: a series with no fresh data cannot be judged. A series with too
little history is not judged against its past, but its thresholds and its trend still are.
"""

from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime, timedelta
from statistics import median
from typing import Literal, Sequence

Point = tuple[datetime, float]
Kind = Literal["no_data", "spike", "drop", "level_shift", "threshold_breach", "trend_saturation"]

# The defaults the story gives.
STEP = timedelta(minutes=5)  # the step of the recent window
RECENT = timedelta(days=1)  # the recent window: the last day
Z_LIMIT = 3.5  # robust z-score, in absolute value: past it, not at it
HOLD = 3  # points in a row before a deviation counts
SHIFT_SPAN = timedelta(hours=3)  # a deviation this long, one way, is a level shift
HORIZON = timedelta(days=30)  # the furthest a forecast may reach

# Values of this example only: the story names these checks but not their numbers.
MIN_COVERAGE = 0.8  # share of the window's five-minute slots that must hold a point
STALE = 3 * STEP  # no point for this long: the series has stopped arriving
MIN_CHANGE = 0.05  # a deviation smaller than 5% of the norm is not worth a finding
MIN_SAME_SLOT = 3  # values the same weekday and hour need before they are a baseline
MIN_FIT = 0.8  # R squared a trend must reach before it is forecast
Z_CAP = 100.0  # past this, a z-score says only "very far": it keeps severities comparable


Lines 43–62 Signal holds the bad direction, an optional crit threshold and limit capacity, and a counter flag; each check reads only the fields it needs. Finding.baseline stays empty unless behaviour names the norm it used.

@dataclass(frozen=True)
class Signal:
    """One entry of a catalog: what is watched, and which way is bad."""

    name: str
    unit: str
    bad: Literal["rise", "fall"]
    crit: float | None = None  # an absolute threshold, where the signal has one
    limit: float | None = None  # a capacity a trend can run into, such as a disk's size
    counter: bool = False  # a cumulative counter, which may restart from zero


@dataclass(frozen=True)
class Finding:
    kind: Kind
    severity: float  # how bad, comparable within a kind across runs: higher is worse
    detail: str
    baseline: str = ""  # which norm was used: "weekday+hour", "hour" or "band"


Lines 63–91 robust_z returns 0.6745 × (x − norm) / mad, clipped to ±Z_CAP; when mad is 0, any departure scores ±Z_CAP. baseline takes the first of weekday+hour, hour and band with at least MIN_SAME_SLOT values and says which.

def robust_z(x: float, norm: float, mad: float) -> float:
    """The modified z-score: the distance from the median in units of the MAD.

    0.6745 makes it comparable with a standard z-score on normal data (Iglewicz and Hoaglin).
    """
    if mad == 0:
        return 0.0 if x == norm else Z_CAP if x > norm else -Z_CAP
    return max(-Z_CAP, min(Z_CAP, 0.6745 * (x - norm) / mad))


def baseline(history: Sequence[Point], at: datetime) -> tuple[float, float, str] | None:
    """The norm and spread of the series for the moment `at`, from its own past, or None.

    The same weekday and hour first; with too little of that, the same hour on any day (the
    weekdays merged); with too little of that too, one band for the whole history. The result
    says which, so a coarser norm is never mistaken for a finer one.
    """
    for name, same in (
        ("weekday+hour", lambda t: t.weekday() == at.weekday() and t.hour == at.hour),
        ("hour", lambda t: t.hour == at.hour),
        ("band", lambda t: True),
    ):
        values = [v for t, v in history if same(t)]
        if len(values) >= MIN_SAME_SLOT:
            norm = median(values)
            return norm, median(abs(v - norm) for v in values), name
    return None


Lines 92–106 no_data reports a series whose last point is older than STALE, or whose last day fills fewer than MIN_COVERAGE of its five-minute slots; _slots keys points by slot, so one timestamp repeated counts once.

def _slots(points: Sequence[Point], since: datetime) -> dict[int, Point]:
    """The points after `since`, one per five-minute slot: a duplicate timestamp counts once."""
    return {int((t - since) / STEP): (t, v) for t, v in points if t > since}


def no_data(recent: Sequence[Point], now: datetime) -> Finding | None:
    """Missing data is not normal: a stale or thinly covered window is reported, not judged."""
    if not recent or now - recent[-1][0] > STALE:
        return Finding("no_data", 0.0, "the series stopped arriving")
    covered = len(_slots(recent, now - RECENT)) / (RECENT / STEP)
    if covered < MIN_COVERAGE:
        return Finding("no_data", 0.0, f"only {covered:.0%} of the window holds a point")
    return None


Lines 107–151 A deviation counts only if every point’s z lies past Z_LIMIT one way with no gap: the last HOLD steps for a spike or drop, the last SHIFT_SPAN for a level_shift. MIN_CHANGE and _counter_reset can still veto it.

def _run(scored: list[tuple[datetime, float, float, float, str]], span: timedelta) -> list | None:
    """The scored points of the last `span`, if they fill it slot by slot with no gap."""
    end = scored[-1][0]
    run = [s for s in scored if s[0] > end - span]
    slots = {int((s[0] - (end - span)) / STEP) for s in run}
    return run if len(slots) >= span / STEP else None


def behaviour(signal: Signal, recent: Sequence[Point], history: Sequence[Point]) -> Finding | None:
    """A deviation from the series' own past that holds: a spike, a drop or a level shift."""
    scored = []
    for t, v in recent:
        base = baseline(history, t)
        if base is None:
            return None  # too little history to know what is usual: not judged this way
        norm, mad, used = base
        scored.append((t, v, robust_z(v, norm, mad), norm, used))

    # A level shift fills the last three hours, slot by slot; a spike or a drop, the last HOLD steps.
    for kind, span in (("level_shift", SHIFT_SPAN), ("", HOLD * STEP)):
        run = _run(scored, span)
        if run is None:
            continue
        up, down = all(z > Z_LIMIT for *_, z, _, _ in run), all(z < -Z_LIMIT for *_, z, _, _ in run)
        if not (up or down):
            continue
        t, v, z, norm, used = run[-1]
        if abs(v - norm) < MIN_CHANGE * abs(norm):
            return None  # too small a change to matter, however rare
        if down and signal.counter and _counter_reset(recent):
            return None  # a counter that restarted from zero, not a fall of the thing it counts
        found = kind or ("spike" if up else "drop")
        return Finding(found, abs(z), f"{v:g} against a norm of {norm:g}", used)
    return None


def _counter_reset(recent: Sequence[Point]) -> bool:
    """A cumulative counter fell to near zero and has been growing again since."""
    values = [v for _, v in recent]
    lowest = min(range(len(values)), key=values.__getitem__)
    before, after = values[:lowest], values[lowest:]
    rising = len(after) > 1 and after == sorted(after) and after[-1] > after[0]
    return bool(before) and values[lowest] <= 0.01 * max(before) and rising


Lines 152–166 threshold_breach checks only the latest point against crit in the direction bad names and reads no history, so a new series is watched too; severity is the distance past crit relative to |crit|.

def threshold_breach(signal: Signal, recent: Sequence[Point]) -> Finding | None:
    """An absolute threshold crossed the bad way, even where the value has become usual.

    This example takes the latest point; the healthcheck is the mode that asks for three.
    """
    if signal.crit is None or not recent:
        return None
    v = recent[-1][1]
    crossed = v > signal.crit if signal.bad == "rise" else v < signal.crit
    if not crossed:
        return None
    severity = abs(v - signal.crit) / max(abs(signal.crit), 1e-9)  # how far past, relatively
    return Finding("threshold_breach", severity, f"{v:g} {signal.unit} past {signal.crit:g}")


Lines 167–203 trend_saturation reports a trend toward limit only if _line gives R² ≥ MIN_FIT, the two halves’ slopes agree in sign within a factor of two, and the limit falls within HORIZON; severity is HORIZON.days / days left.

def trend_saturation(signal: Signal, series: Sequence[Point]) -> Finding | None:
    """A steady trend toward the limit, forecast no further than HORIZON.

    A trend is forecast only if a straight line fits it well and the slopes of its two halves
    agree: a chance rise must not turn into "the disk will soon be full".
    """
    if signal.limit is None or len(series) < 4:
        return None
    slope, fit = _line(series)
    first, _ = _line(series[: len(series) // 2])
    second, _ = _line(series[len(series) // 2 :])
    toward = slope > 0 if signal.bad == "rise" else slope < 0
    if not toward or fit < MIN_FIT or first * second <= 0 or not 0.5 <= first / second <= 2:
        return None
    left = (signal.limit - series[-1][1]) / slope  # seconds until the line meets the limit
    if not 0 < left <= HORIZON.total_seconds():
        return None
    days = left / 86400
    # Fewer days left is worse: the severity grows as the limit comes nearer.
    return Finding("trend_saturation", HORIZON.days / days, f"the limit in {days:.1f} days")


def _line(series: Sequence[Point]) -> tuple[float, float]:
    """Least squares over (seconds, value): the slope per second, and R squared."""
    t0 = series[0][0]
    xs = [(t - t0).total_seconds() for t, _ in series]
    ys = [v for _, v in series]
    mx, my = sum(xs) / len(xs), sum(ys) / len(ys)
    sxx = sum((x - mx) ** 2 for x in xs)
    sxy = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
    syy = sum((y - my) ** 2 for y in ys)
    if sxx == 0 or syy == 0:
        return 0.0, 0.0
    slope = sxy / sxx
    return slope, (sxy * sxy) / (sxx * syy)


Lines 204–213 detect returns a no_data finding alone; otherwise the three checks run independently, trend_saturation on history and recent joined so its line covers the whole past, and those that find nothing drop out.

def detect(
    signal: Signal, recent: Sequence[Point], history: Sequence[Point], now: datetime
) -> list[Finding]:
    """All the findings for one series, in the story's order."""
    missing = no_data(recent, now)
    if missing:
        return [missing]
    found = [behaviour(signal, recent, history), threshold_breach(signal, recent)]
    found.append(trend_saturation(signal, [*history, *recent]))
    return [f for f in found if f is not None]
episodes.py Episodes from run to run, and their priority. 77 lines

Lines 1–22 State lists the four states advance assigns. WORSE = 1.2 is this example’s own number, since the story gives none: a severity must pass 1.2 times the last one to count as worsening.

"""Episodes: what the detector found, followed from run to run.

Written for the page to show the mechanism; it is not the project's code. An episode is named by
the series (the signal and the labels of its object) and the kind of anomaly, so the same event keeps
its name between runs, and a rise of latency on two clusters stays two episodes.
"""

from __future__ import annotations

import json
from dataclasses import dataclass, replace
from datetime import datetime
from typing import Literal

from detector import Finding

State = Literal["new", "ongoing", "worsening", "resolved"]

# A value of this example only: the story says "worsening", not by how much.
WORSE = 1.2  # a severity more than this many times the last one is worse


Lines 23–36 Episode keeps first_seen and last_seen so priority can tell how long it has lasted; key joins series and kind, so a spike and a level_shift on one series stay separate episodes.

@dataclass(frozen=True)
class Episode:
    series: str
    kind: str
    state: State
    severity: float
    first_seen: datetime
    last_seen: datetime

    @property
    def key(self) -> str:
        return f"{self.series}:{self.kind}"


Lines 37–41 series_key appends the labels as JSON with sorted keys: label order cannot change the name, and quoting keeps a value such as “a,node=2” from passing for a second label.

def series_key(signal: str, labels: dict[str, str]) -> str:
    """The signal and its object's labels, written so that no two objects can share a name."""
    return signal + json.dumps(labels, sort_keys=True, separators=(",", ":"))


Lines 42–69 An open episode found again keeps first_seen and turns ongoing or worsening; one not found resolves only if its series was judged, else stays as it was. A resolved episode restarts as new if found, else drops out.

def advance(
    previous: dict[str, Episode],
    found: dict[str, tuple[str, Finding]],
    now: datetime,
    judged: set[str],
) -> dict[str, Episode]:
    """The episodes after this run.

    `found` maps an episode's key to its series and finding. `judged` holds the series this run
    had data for. An episode not found again is resolved only if its series was judged: a series
    whose metrics did not come is no recovery, whatever the other series did.
    """
    out: dict[str, Episode] = {}
    for key, (series, finding) in found.items():
        was = previous.get(key)
        if was is None or was.state == "resolved":
            out[key] = Episode(series, finding.kind, "new", finding.severity, now, now)
        else:
            worse = was.severity > 0 and finding.severity > WORSE * was.severity
            state: State = "worsening" if worse else "ongoing"
            out[key] = replace(was, state=state, severity=finding.severity, last_seen=now)
    for key, was in previous.items():
        if key in out or was.state == "resolved":
            continue
        out[key] = replace(was, state="resolved") if was.series in judged else was
    return out


Lines 70–77 priority leaves out severity, which holds the z, to keep the example short (the project weighs the z as well): it multiplies the caller’s relative change by the square root of 1 + hours lasted, so a long episode gains urgency, but ever more slowly.

def priority(episode: Episode, change: float) -> float:
    """How urgent a behavioural anomaly is: the size of the change and how long it has lasted.

    Not the z-score alone: on a quiet metric a small wobble has a huge z, and it must not outrank
    a serious fall of load. `change` is the relative size of the change, |value - norm| / norm.
    """
    hours = (episode.last_seen - episode.first_seen).total_seconds() / 3600
    return abs(change) * (1 + hours) ** 0.5
test_detector.py Made-up series on which each check is seen at work. 124 lines

Lines 1–16 NOW is a fixed moment, so no test depends on the clock. LATENCY has crit 0.5 and DISK a 1000 GB limit; LOAD and COUNTER count a fall as bad, and only COUNTER sets counter=True.

"""The detector and the episodes on series made up for the test: python -m unittest test_detector"""

import math
import unittest
from datetime import datetime, timedelta

from detector import STEP, Finding, Signal, detect
from episodes import advance, priority, series_key

NOW = datetime(2026, 11, 26, 12, 0)
LATENCY = Signal("query_latency", "s", bad="rise", crit=0.5)
DISK = Signal("disk_used", "GB", bad="rise", limit=1000.0)
LOAD = Signal("queries_per_second", "1/s", bad="fall")
COUNTER = Signal("queries_total", "1", bad="fall", counter=True)


Lines 17–36 daily gives latency a 24-hour sine plus a small jitter from the minute. As in the story, day() is the last 24 hours at STEP up to NOW, and HISTORY the four weeks before at 30-minute steps.

def daily(t: datetime) -> float:
    """A latency with a day's rhythm: higher in the working hours."""
    return 0.1 + 0.05 * math.sin((t.hour + t.minute / 60) / 24 * 2 * math.pi) + 0.002 * (t.minute % 7)


def series(start: datetime, end: datetime, step: timedelta, value) -> list:
    points, t = [], start
    while t < end:
        points.append((t, value(t)))
        t += step
    return points


def day(value) -> list:
    return series(NOW - timedelta(days=1) + STEP, NOW + STEP, STEP, value)


HISTORY = series(NOW - timedelta(days=29), NOW - timedelta(days=1), timedelta(minutes=30), daily)


Lines 37–58 A quiet day gives nothing; 0.3 added to the last three points is a spike, to the last two not yet, which pins HOLD at three. A series that stopped two hours ago, or 288 points at one timestamp, is no_data.

class Detector(unittest.TestCase):
    def test_a_quiet_day_has_no_finding(self):
        self.assertEqual(detect(LATENCY, day(daily), HISTORY, NOW), [])

    def test_three_points_up_are_a_spike(self):
        recent = day(daily)
        recent[-3:] = [(t, v + 0.3) for t, v in recent[-3:]]
        self.assertEqual([f.kind for f in detect(LATENCY, recent, HISTORY, NOW)], ["spike"])

    def test_two_points_up_are_not_yet(self):
        recent = day(daily)
        recent[-2:] = [(t, v + 0.3) for t, v in recent[-2:]]
        self.assertEqual(detect(LATENCY, recent, HISTORY, NOW), [])

    def test_missing_data_is_not_normal(self):
        recent = series(NOW - timedelta(days=1), NOW - timedelta(hours=2), STEP, daily)
        self.assertEqual([f.kind for f in detect(LATENCY, recent, HISTORY, NOW)], ["no_data"])

    def test_one_moment_repeated_is_not_a_covered_window(self):
        recent = [(NOW, 0.1)] * 288
        self.assertEqual([f.kind for f in detect(LATENCY, recent, HISTORY, NOW)], ["no_data"])

Lines 59–71 Latency at 0.7 for four weeks is usual, yet breaches crit 0.5, and so does 0.7 with no history at all. A flat load of 100 moving to 101 hits Z_CAP against a MAD of 0 but stays under MIN_CHANGE.

    def test_a_breach_is_caught_even_when_usual(self):
        high = lambda t: 0.7 + 0.001 * (t.minute % 5)  # noqa: E731 - always above 0.5
        history = series(NOW - timedelta(days=29), NOW - timedelta(days=1), timedelta(minutes=30), high)
        self.assertEqual([f.kind for f in detect(LATENCY, day(high), history, NOW)], ["threshold_breach"])

    def test_with_no_history_the_threshold_is_still_watched(self):
        high = lambda t: 0.7  # noqa: E731
        self.assertEqual([f.kind for f in detect(LATENCY, day(high), [], NOW)], ["threshold_breach"])

    def test_a_small_shift_is_not_worth_a_finding(self):
        flat = series(NOW - timedelta(days=29), NOW - timedelta(days=1), timedelta(minutes=30), lambda t: 100.0)
        self.assertEqual(detect(LOAD, day(lambda t: 101.0), flat, NOW), [])

Lines 72–88 Against a flat 100, three zeros are a drop on LOAD; on COUNTER, a zero then 0.5 and 1.0 read as a restart and give nothing. A disk at 890 GB growing 10 GB a day gets one trend_saturation finding: the limit in 11.0 days.

    def test_a_gauge_at_zero_is_a_drop_and_a_counter_restarting_is_not(self):
        history = series(NOW - timedelta(days=29), NOW - timedelta(days=1), timedelta(minutes=30), lambda t: 100.0 + t.minute % 3)
        fallen = day(lambda t: 100.0 + t.minute % 3)
        fallen[-3:] = [(t, 0.0) for t, _ in fallen[-3:]]
        self.assertEqual([f.kind for f in detect(LOAD, fallen, history, NOW)], ["drop"])
        restarted = day(lambda t: 100.0 + t.minute % 3)
        restarted[-3:] = [(t, v) for (t, _), v in zip(restarted[-3:], (0.0, 0.5, 1.0))]
        self.assertEqual(detect(COUNTER, restarted, history, NOW), [])

    def test_a_disk_filling_up_is_forecast(self):
        filling = lambda t: 600 + (t - (NOW - timedelta(days=29))).total_seconds() / 86400 * 10  # noqa: E731
        history = series(NOW - timedelta(days=29), NOW - timedelta(days=1), timedelta(minutes=30), filling)
        found = [f for f in detect(DISK, day(filling), history, NOW) if f.kind == "trend_saturation"]
        self.assertEqual(len(found), 1)
        self.assertIn("in 11.0 days", found[0].detail)  # 890 GB now, 10 GB a day, 1000 GB


Lines 89–96 A and B name the same signal on two clusters. The tricky key puts “a,node=2” inside one cluster value: key=value pairs joined by commas would read it as A.

class Episodes(unittest.TestCase):
    A = series_key("query_latency", {"cluster": "a", "node": "2"})
    B = series_key("query_latency", {"cluster": "b", "node": "2"})

    def test_two_objects_never_share_a_name(self):
        tricky = series_key("query_latency", {"cluster": "a,node=2"})
        self.assertNotEqual(self.A, tricky)

Lines 97–109 One spike key walks through every state: new on first sight, ongoing at the same 6.0, worsening at 9.0, above WORSE times 6.0, and resolved once a run judges A and finds nothing.

    def test_states_from_run_to_run(self):
        spike = Finding("spike", 6.0, "made up")
        key = f"{self.A}:spike"
        first = advance({}, {key: (self.A, spike)}, NOW, judged={self.A})
        self.assertEqual(first[key].state, "new")
        later = NOW + STEP
        again = advance(first, {key: (self.A, spike)}, later, judged={self.A})
        self.assertEqual(again[key].state, "ongoing")
        worse = advance(again, {key: (self.A, Finding("spike", 9.0, "made up"))}, later, judged={self.A})
        self.assertEqual(worse[key].state, "worsening")
        gone = advance(again, {}, later, judged={self.A})
        self.assertEqual(gone[key].state, "resolved")

Lines 110–124 If the next run judges only B, as A’s metrics did not come, A keeps its state and B resolves. priority ranks change 0.6 above 0.02 on one episode, so the test cannot show that z is ignored.

    def test_a_series_with_no_data_keeps_its_episode_while_another_resolves(self):
        a, b = f"{self.A}:spike", f"{self.B}:spike"
        spike = Finding("spike", 6.0, "made up")
        both = advance({}, {a: (self.A, spike), b: (self.B, spike)}, NOW, judged={self.A, self.B})
        after = advance(both, {}, NOW + STEP, judged={self.B})  # A's metrics did not come
        self.assertEqual(after[a].state, "new")
        self.assertEqual(after[b].state, "resolved")

    def test_priority_weighs_the_change_not_the_z(self):
        quiet = advance({}, {"q": ("quiet{}", Finding("spike", 100.0, "made up"))}, NOW, judged=set())["q"]
        self.assertLess(priority(quiet, change=0.02), priority(quiet, change=0.6))


if __name__ == "__main__":
    unittest.main()

Next story

Automated alert triage

Monitoring of databases: metrics are collected and stored, rules turn them into alerts, Alertmanager groups and routes the alerts, and a triage service gathers what the engineer on call looks for first.

How the triage works Observability