Functional Weave
Code in TypeScript

monitor.alert-state

Step an alert through inactive, pending, firing and resolved, and say which notification to send.

1.0.0 · published 2026-10-03 by charlie · Anterra

Pinned by 25 tests, run in TypeScript, Python and Rust.

What it does

The lifecycle of one alert, one evaluation at a time, and the notification each step should send. The function is pure: store the returned `state` and pass it back as `previous` next time. Start from `{ phase: "inactive", since: null, lastNotifiedAt: null, clearSince: null }`. The condition itself comes from anywhere: `monitor.alert-rule`, a heartbeat, a burn-rate alert.

## Transitions

For example

  • nextAlertState(phase inactive, since —, last notified at —, clear since —, true, 1,000, for seconds 300, clear for seconds 0, renotify seconds —) → state …, notify —, changed true the condition starting on an inactive alert makes it pending
  • nextAlertState(phase inactive, since —, last notified at —, clear since —, true, 1,000, for seconds 0, clear for seconds 0, renotify seconds —) → state …, notify firing, changed true forSeconds 0 fires at once and notifies
  • nextAlertState(phase inactive, since —, last notified at —, clear since —, false, 1,000, for seconds 300, clear for seconds 0, renotify seconds —) → state …, notify —, changed false an inactive alert with the condition false stays as it is

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

export function nextAlertState(previous: AlertState, condition: boolean, now: number, policy: AlertPolicy): AlertTransition
previousAlertStatethe state this function returned last time; start from inactive with every time null
conditionboolwhether the alert condition holds at this evaluation
nowintUnix seconds of this evaluation, not before any time in previous
policyAlertPolicy
returnsAlertTransition

The types it declares, generated into your project

export type AlertPhase = "inactive" | "pending" | "firing" | "resolved";

/** Everything the next evaluation needs; store it between evaluations. */
export interface AlertState {
  readonly phase: AlertPhase;
  /** when this phase began */
  readonly since: number | null;
  /** when the last notification of any kind was sent */
  readonly lastNotifiedAt: number | null;
  /** while firing, when the condition was first seen false again */
  readonly clearSince: number | null;
}

/** How long to wait before firing and before resolving, and how often to repeat. */
export interface AlertPolicy {
  /** the condition must hold this long before firing, 0 = at once */
  readonly forSeconds: number;
  /** the condition must stay false this long before resolving, 0 = at once */
  readonly clearForSeconds: number;
  /** while firing, repeat the notification this often; null = never */
  readonly renotifySeconds: number | null;
}

export type Notification = "firing" | "repeat" | "resolved";

/** The new state, and what to tell people. */
export interface AlertTransition {
  readonly state: AlertState;
  /** null = send nothing */
  readonly notify: Notification | null;
  /** the phase changed */
  readonly changed: boolean;
}

Your code names it in one line, in the file that uses it

import { nextAlertState } from "#fune/monitor.alert-state@^1";
impl/typescript.ts · 61 lines · open · raw
import { type AlertPolicy, type AlertState, type AlertTransition } from "./monitor_alert_state_types.ts";

/**
 * One step of an alert's lifecycle. Pure: the caller stores the returned
 * state and passes it back at the next evaluation.
 *
 * Firing needs the condition to hold forSeconds (Prometheus `for`);
 * resolving needs it to stay false clearForSeconds, so a flapping check does
 * not send resolved-firing-resolved storms. lastNotifiedAt records the last
 * notification of any kind; it drives the repeat interval while firing.
 */
export function nextAlertState(previous: AlertState, condition: boolean, now: number, policy: AlertPolicy): AlertTransition {
  if (!Number.isSafeInteger(now)) throw new RangeError("now must be a whole number of seconds");
  const { forSeconds, clearForSeconds } = policy;
  const renotify = policy.renotifySeconds ?? null;
  if (forSeconds < 0) throw new RangeError(`forSeconds must not be negative, received ${forSeconds}`);
  if (clearForSeconds < 0) throw new RangeError(`clearForSeconds must not be negative, received ${clearForSeconds}`);
  if (renotify !== null && renotify < 1) throw new RangeError(`renotifySeconds must be null or at least 1, received ${renotify}`);
  const phase = previous.phase;
  if (phase !== "inactive" && phase !== "pending" && phase !== "firing" && phase !== "resolved") {
    throw new RangeError(`unknown alert phase: ${String(phase)}`);
  }
  const since = previous.since ?? null;
  const last = previous.lastNotifiedAt ?? null;
  const clearSince = previous.clearSince ?? null;
  if ((phase === "pending" || phase === "firing") && since === null) {
    throw new RangeError(`since must be set in phase ${phase}`);
  }
  const times: Array<[string, number | null]> = [["since", since], ["lastNotifiedAt", last], ["clearSince", clearSince]];
  for (const [name, t] of times) {
    if (t !== null && now < t) throw new RangeError(`now ${now} is earlier than ${name} ${t}`);
  }
  const same: AlertState = { phase, since, lastNotifiedAt: last, clearSince };

  if (phase === "inactive" || phase === "resolved") {
    if (!condition) return { state: same, notify: null, changed: false };
    if (forSeconds === 0) {
      return { state: { phase: "firing", since: now, lastNotifiedAt: now, clearSince: null }, notify: "firing", changed: true };
    }
    return { state: { phase: "pending", since: now, lastNotifiedAt: last, clearSince: null }, notify: null, changed: true };
  }
  if (phase === "pending") {
    if (!condition) return { state: { phase: "inactive", since: now, lastNotifiedAt: last, clearSince: null }, notify: null, changed: true };
    if (now - (since as number) >= forSeconds) {
      return { state: { phase: "firing", since: now, lastNotifiedAt: now, clearSince: null }, notify: "firing", changed: true };
    }
    return { state: same, notify: null, changed: false };
  }
  // firing
  if (condition) {
    if (renotify !== null && (last === null || now - last >= renotify)) {
      return { state: { phase, since, lastNotifiedAt: now, clearSince: null }, notify: "repeat", changed: false };
    }
    return { state: { phase, since, lastNotifiedAt: last, clearSince: null }, notify: null, changed: false };
  }
  const clearing = clearSince ?? now;
  if (now - clearing >= clearForSeconds) {
    return { state: { phase: "resolved", since: now, lastNotifiedAt: now, clearSince: null }, notify: "resolved", changed: true };
  }
  return { state: { phase, since, lastNotifiedAt: last, clearSince: clearing }, notify: null, changed: false };
}

Install

fune build

With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the TypeScript package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:

fune add monitor.alert-state
Download for TypeScript monitor.alert-state-1.0.0-typescript.fune · 20,288 bytes sha256 182c96738dd64f692b56bce06f917f19eb074a88c00b4740002244efebd22fb2

The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./monitor.alert-state-1.0.0-typescript.fune, or fetch it from a terminal with fune pull monitor.alert-state@1.0.0:typescript.

The whole function, every language, is one file too: monitor.alert-state-1.0.0.fune, 30,077 bytes, sha256 9f53e4ae117c8e8b7e9613f83b621d77b32fb2d1ac4450004a95b8d77e1eaa2b. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

// fune: before monitor.alert-state

after — your function gets the result and the arguments, and returns the final result.

// fune: after monitor.alert-state

replace — it requires no other capability, so there is no dependency to replace.

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show monitor.alert-state --steps.

// fune: step monitor.alert-state after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
the condition starting on an inactive alert makes it pending phase inactive, since —, last notified at —, clear since —, true, 1,000, for seconds 300, clear for seconds 0, renotify seconds — → state …, notify —, changed true
forSeconds 0 fires at once and notifies phase inactive, since —, last notified at —, clear since —, true, 1,000, for seconds 0, clear for seconds 0, renotify seconds — → state …, notify firing, changed true
an inactive alert with the condition false stays as it is phase inactive, since —, last notified at —, clear since —, false, 1,000, for seconds 300, clear for seconds 0, renotify seconds — → state …, notify —, changed false
pending one second short of forSeconds stays pending phase pending, since 1,000, last notified at —, clear since —, true, 1,299, for seconds 300, clear for seconds 0, renotify seconds — → state …, notify —, changed false
pending for exactly forSeconds fires and notifies phase pending, since 1,000, last notified at —, clear since —, true, 1,300, for seconds 300, clear for seconds 0, renotify seconds — → state …, notify firing, changed true
the condition ending while pending goes back to inactive without a notification phase pending, since 1,000, last notified at —, clear since —, false, 1,100, for seconds 300, clear for seconds 0, renotify seconds — → state …, notify —, changed true
firing and still true, with no repeat interval, sends nothing phase firing, since 1,300, last notified at 1,300, clear since —, true, 1,500, for seconds 300, clear for seconds 0, renotify seconds — → state …, notify —, changed false
firing and still true for exactly the repeat interval sends a repeat phase firing, since 1,300, last notified at 1,300, clear since —, true, 4,900, for seconds 300, clear for seconds 0, renotify seconds 3,600 → state …, notify repeat, changed false
one second short of the repeat interval sends nothing phase firing, since 1,300, last notified at 1,300, clear since —, true, 4,899, for seconds 300, clear for seconds 0, renotify seconds 3,600 → state …, notify —, changed false
firing then false with clearForSeconds 0 resolves at once phase firing, since 1,300, last notified at 1,300, clear since —, false, 2,000, for seconds 300, clear for seconds 0, renotify seconds — → state …, notify resolved, changed true
Show the other 15 tests
CaseArgumentsExpected
firing then false with a clear delay starts the clear clock and keeps firing phase firing, since 1,300, last notified at 1,300, clear since —, false, 2,000, for seconds 300, clear for seconds 600, renotify seconds — → state …, notify —, changed false
false for the whole clear delay resolves phase firing, since 1,300, last notified at 1,300, clear since 2,000, false, 2,600, for seconds 300, clear for seconds 600, renotify seconds — → state …, notify resolved, changed true
false one second short of the clear delay keeps firing phase firing, since 1,300, last notified at 1,300, clear since 2,000, false, 2,599, for seconds 300, clear for seconds 600, renotify seconds — → state …, notify —, changed false
a flap back to true during the clear delay cancels it, no resolved sent phase firing, since 1,300, last notified at 1,300, clear since 2,000, true, 2,300, for seconds 300, clear for seconds 600, renotify seconds — → state …, notify —, changed false
a resolved alert with the condition false stays resolved phase resolved, since 2,000, last notified at 2,000, clear since —, false, 3,000, for seconds 300, clear for seconds 0, renotify seconds — → state …, notify —, changed false
a resolved alert whose condition returns goes pending, keeping the last notification time phase resolved, since 2,000, last notified at 2,000, clear since —, true, 3,000, for seconds 300, clear for seconds 0, renotify seconds — → state …, notify —, changed true
now before the state's since is an error phase pending, since 1,000, last notified at —, clear since —, true, 900, for seconds 300, clear for seconds 0, renotify seconds — → error: now 900 is earlier than since 1000
now before the last notification is an error phase firing, since 1,300, last notified at 1,500, clear since —, true, 1,400, for seconds 300, clear for seconds 0, renotify seconds — → error: now 1400 is earlier than lastNotifiedAt 1500
now before clearSince is an error phase firing, since 1,300, last notified at 1,300, clear since 2,000, false, 1,900, for seconds 300, clear for seconds 0, renotify seconds — → error: now 1900 is earlier than clearSince 2000
an unknown phase is an error phase acknowledged, since 1,000, last notified at —, clear since —, true, 1,000, for seconds 300, clear for seconds 0, renotify seconds — → error: unknown alert phase: acknowledged
a pending state without since is an error phase pending, since —, last notified at —, clear since —, true, 1,000, for seconds 300, clear for seconds 0, renotify seconds — → error: since must be set in phase pending
a negative forSeconds is an error phase inactive, since —, last notified at —, clear since —, true, 1,000, for seconds -1, clear for seconds 0, renotify seconds — → error: forSeconds must not be negative
a negative clearForSeconds is an error phase inactive, since —, last notified at —, clear since —, true, 1,000, for seconds 300, clear for seconds -1, renotify seconds — → error: clearForSeconds must not be negative
a zero repeat interval is an error phase inactive, since —, last notified at —, clear since —, true, 1,000, for seconds 300, clear for seconds 0, renotify seconds 0 → error: renotifySeconds must be null or at least 1
a fractional now is an error phase inactive, since —, last notified at —, clear since —, true, 1,000.5, for seconds 300, clear for seconds 0, renotify seconds — → error: now must be a whole number of seconds

More from the author

| previous | condition | result | | --- | --- | --- | | inactive or resolved | false | unchanged | | inactive or resolved | true | `pending` since now; or, when `forSeconds` is 0, `firing` since now and notify `firing` | | pending | true | `firing` since now and notify `firing` once `now - since >= forSeconds`, else unchanged | | pending | false | `inactive` since now, no notification (it never fired, so there is nothing to resolve) | | firing | true | stays firing, `clearSince` reset to null; notify `repeat` when `renotifySeconds` is set and `now - lastNotifiedAt >= renotifySeconds` | | firing | false | `clearSince` is set to now if it was null; once `now - clearSince >= clearForSeconds` it becomes `resolved` since now and notifies `resolved` |

- `lastNotifiedAt` is the time of the last notification of any kind, and is carried through the other phases; entering `firing` sets it, so the repeat interval counts from the first notification. - `changed` says whether the **phase** changed, so a caller knows when to write an alert history row. Store the returned state every time anyway: `clearSince` and `lastNotifiedAt` can change without the phase changing. - `since` of a firing alert is when it started firing, not when it became pending.

## Why this shape

`forSeconds` is Prometheus's `for`: "wait for a certain duration between first encountering a new expression output vector element and counting an alert as firing"; until then the alert is pending, and a pending alert whose condition goes away is simply dropped. `clearForSeconds` is the other direction, what Prometheus calls `keep_firing_for` ("keep this alert firing for the specified duration after the firing condition was last met"): a check that flaps true/false/true sends one firing and one resolved, not a storm. Here the condition must stay false for the whole delay; one true evaluation during it cancels the resolve. `renotifySeconds` matches Alertmanager's `repeat_interval`: a reminder while an alert keeps firing.

## Errors

- `now 900 is earlier than since 1000` (also for `lastNotifiedAt` and `clearSince`): time never goes backwards between evaluations. - `unknown alert phase: X` - `since must be set in phase pending` (or `firing`) - `forSeconds must not be negative`, `clearForSeconds must not be negative` - `renotifySeconds must be null or at least 1` - `now must be a whole number of seconds`

## Sources

- Prometheus, "Alerting rules", https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/ (`for`, pending and firing, `keep_firing_for`). - Prometheus Alertmanager, "Configuration", https://prometheus.io/docs/alerting/latest/configuration/ (`repeat_interval`).

Files

PathBytes
README.md3,115
impl/python.py3,748
impl/rust.rs5,658
impl/typescript.ts3,541
vectors.json8,666