Condition Monitor
Finishing a task is often only half the story. Sometimes you need an outcome to keep holding for the next two weeks, or you are waiting for one external milestone to finally happen. Left in your head, that turns into opening dashboards every morning — and the week you get busy, silence looks identical to "everything is fine."
Condition Monitor moves recurring verification off the requester's calendar
and into the hub. You state in one sentence what should stay true (a
condition monitor) or what single milestone you are waiting for (an
event monitor); the hub runs fresh checks on a schedule until a firm end
date, tells you only when the state actually changes, and uses an independent supervisor
timer so a missing check shows up as unknown instead of
hiding behind quiet skies.
Monitor, Monitor check
Why manual habits — and silent scheduled jobs — both fail
After a billing fix ships, a vendor contract goes out for signature, or an operational policy takes effect, a requester naturally says "I'll keep an eye on that." Whether you check manually every morning or set up a quick cron script that emails you when something breaks, both approaches share the same blind spot: no news looks identical whether the check passed or nobody checked at all.
Skip two busy mornings and a regression sits unnoticed until a customer complains. Let an API token expire on a naive alert script and the script quietly crashes every hour while your inbox stays reassuringly empty.
Condition Monitor turns "I'll check on that later" into durable hub state governed by three structural rules:
-
Store the check, cadence, grace window, and end date. Every monitor is
either a
condition(must keep holding) or anevent(waits for one milestone), with a mandatoryends_atdeadline so checks never burn budget forever. -
Separate the check timer from the supervisor timer. One timer launches
fresh checkers when
next_check_atarrives; an independent supervisor comparesnext_check_at + grace_secondsagainst the clock and records amissedcheck if no result arrives in time. -
Keep
ok,triggered,error, andmissedapart — and notify only on transitions. A failed or missed check moves the monitor tounknownand alerts its assignee to repair it, rather than faking healthy status or triggering a false alarm.
Why must the supervisor run on its own timer? If the code that detects
missing checks asks the same job queue that launches checkers, a stalled scheduler or
dropped queue job blinds both at once. Reading durable
next_check_at timestamps directly against wall-clock time
catches every failure mode from scheduler outages to crashed checkers.
missed checks routed for repair.
Architecture and participants
The requester states what to watch in one plain sentence. The lead agent turns that
sentence into a Monitor record with a repeatable
check_spec, cadence, grace window, and end date — and
normally serves as the monitor's durable assignee_id so it
can repair broken checks. The hub runs two independent timers, appends one
Monitor check per due time, and computes the requester's
status board directly from those two tables.
grace_seconds, the supervisor
writes a missed check and alerts the assignee while the
derived status board reflects the exact gap.
check_spec, cadence, and end date, confirms the
wording back to the requester, and repairs the monitor whenever checks error or are
missed.
Monitor and
Monitor check rows in one transaction per evaluation.
Its Check timer starts due checks; its independent
Supervisor timer records overdue checks as
missed.
monitors and
monitor_checks showing what is watched, how it stands,
since when, and when it was last successfully checked.
Execution flow
Toggle between the normal condition flow — where steady passing checks stay quiet and the
requester hears once on a break and once on recovery — and the missed-check path — where a
checker fails silently, the supervisor timer flips status to
unknown, and the lead agent repairs access while the board
records the exact unchecked window.
The first passing check moves a new monitor from unknown
to ok silently (notify: false).
The hub notifies the requester once when the condition breaks and once when it holds
again.
Begins after steady ok checks: the 5:00 PM checker
cannot authenticate and exits without reporting.
Once the 10-minute grace period passes, the supervisor records a
missed check with
alert_assignee: true, sets status to
unknown, and alerts the lead agent to repair access.
Calling mark_repaired schedules an immediate
replacement check on a fresh due_at slot while keeping
next_check_at on the regular hourly cadence, any late
report for the already-missed slot is rejected with
duplicate_due_at, and the board explicitly shows the
unchecked gap.
Interrupt vs. check-in: Setting notify: true
marks that the requester must be told. Whether that notice interrupts immediately or
waits for the next scheduled check-in is governed by
Question Inbox interrupt rules.
Concrete examples
Condition Monitor supports two flavors using the exact same tables: an
event monitor waiting for a single milestone before a
deadline, and a condition monitor guarding a rule that
must keep holding after work closes.
Example 1 — External security sign-off deadline
No code · Event monitor- Statement
- "Let me know when the security team approves the release, or on Friday if they haven't."
- Monitor setup
-
The lead agent registers an
eventmonitor checking the shared approval tracker every 2 hours (grace_seconds: 600,ends_at: Friday 17:00). While approval is still pending, each check recordsoksilently. - Resolution
-
If the security team approves on Thursday at 2:00 PM, the check records
triggered, notifies the requester once, and ends the monitor immediately (ended_atset,next_check_atcleared). If Friday at 5:00 PM arrives with no approval, the final check setsnotify: trueso the requester still gets a definitive closing update.
Example 2 — Duplicate invoices stay at zero
Simple ops/engineering · Condition monitor- Statement
- "After the billing fix ships, duplicate invoices stay at zero through December 1."
- Monitor setup
-
The lead agent creates a
conditionmonitor running every 60 minutes (interval_seconds: 3600,grace_seconds: 600,ends_at: Dec 1) with the lead agent asassignee_id. - Trigger & gap
-
Steady zero counts remain quiet on the board. When database credentials expire on
Wednesday at 5:00 PM and the checker exits silently, the supervisor writes a
missedcheck at 5:10 PM, flips status tounknown, and alerts the lead agent to renew access. When four duplicates appear Thursday at 9:00 AM, status flips totriggeredand notifies the requester once — and once again on Friday when a second fix restores the count to zero.
What this pattern is NOT — Job waits or worker liveness checks
Negative example- Situation
- Pausing a worker job until CI passes so that same job restarts automatically, watching whether an active worker is hung mid-task, or creating a monitor whose only action is "please open this dashboard and look."
- Why skip it
- A condition that restarts a paused job belongs to Resumable Wait; liveness tracking of active workers belongs to Progress Heartbeat. And a check that still needs the requester's own eyes removes no cognitive load at all.
When to use and when to skip
Use Condition Monitor when
- The requester says "I'll keep checking on that later," or a guarantee must keep holding after its original job closes.
- The hub or an agent can evaluate the check autonomously from data it is authorized to read.
- The check is deterministic enough that two runs over the same data produce the same outcome.
- Knowing when the check last succeeded matters just as much as knowing when it failed.
Skip it when
- The event should automatically restart a paused job (use Resumable Wait instead).
- You are monitoring whether an active worker is still making progress (use Progress Heartbeat).
- The check requires human judgment or eyeballs every time ("please look at this chart").
- No bounded end date makes sense and the rule belongs in permanent infrastructure monitoring rather than a requester-scoped watch.
Data model and hub invariants
Condition Monitor defines two durable tables — monitors
and monitor_checks — referencing
parties and requests
from Orchestrator-Workers. Storing each
evaluation in monitor_checks alongside the current state
on monitors lets the hub update both in one database
transaction while preserving a complete audit trail of every due slot, including missed
ones.
Monitor names one requester, one durable assignee,
and an optional Request, and owns one
Monitor check per scheduled due time. Cardinalities
follow the catalog convention (1,
1?, n).
Table: monitors
| Column | Postgres type | Nullability | Notes |
|---|---|---|---|
| id | uuid | NOT NULL, PK | Unique monitor identifier. |
| requester_id | uuid | NOT NULL, FK | References parties(id); recipient of status-change notices. |
| request_id | uuid | NULLABLE, FK | References requests(id); null for standalone watches. |
| assignee_id | uuid | NOT NULL, FK | References parties(id); durable owner (lead agent or hub) that repairs missed/errored checks. |
| kind | text | NOT NULL | CHECK (kind IN ('condition', 'event')). |
| statement | text | NOT NULL | Requester's plain-English sentence (e.g., "After the fix, duplicate invoices stay at zero."). |
| check_spec | jsonb | NOT NULL | Deterministic query, threshold, or checker instructions. |
| interval_seconds | integer | NOT NULL | Cadence between due times (CHECK (interval_seconds > 0)). |
| grace_seconds | integer | NOT NULL | Allowed delay past due_at before supervisor records missed (CHECK (grace_seconds >= 0)). |
| status | text | NOT NULL | CHECK (status IN ('ok', 'triggered', 'unknown')); starts as unknown. |
| status_since | timestamptz | NOT NULL | Starts as created_at; updates only when status changes. |
| next_check_at | timestamptz | NULLABLE | Next scheduled due time; null if and only if ended_at IS NOT NULL. |
| ends_at | timestamptz | NOT NULL | Required deadline after which no further checks are scheduled. |
| ended_at | timestamptz | NULLABLE | Timestamp when the monitor ended; null while active. |
| created_at | timestamptz | NOT NULL | Creation timestamp; defaults to now(). |
Table: monitor_checks
| Column | Postgres type | Nullability | Notes |
|---|---|---|---|
| id | uuid | NOT NULL, PK | Unique check evaluation identifier. |
| monitor_id | uuid | NOT NULL, FK | References monitors(id). |
| due_at | timestamptz | NOT NULL | Scheduled slot; UNIQUE (monitor_id, due_at). |
| ran_at | timestamptz | NULLABLE | Actual execution time; null if and only if outcome = 'missed'. |
| ran_by_id | uuid | NULLABLE, FK | References parties(id); checker or hub; null if and only if outcome = 'missed'. |
| outcome | text | NOT NULL | CHECK (outcome IN ('ok', 'triggered', 'error', 'missed')). |
| observed | jsonb | NULLABLE | Structured measurement (e.g., {"duplicates": 4, "customers": 1}); null when missed. |
| summary | text | NOT NULL | One plain sentence shown to the requester on the status board. |
| notify | boolean | NOT NULL | True when this check requires notifying the requester. |
| alert_assignee | boolean | NOT NULL | True on every error or missed check so the assignee is alerted to repair — even when a brand-new monitor fails on its very first run. |
| notified_at | timestamptz | NULLABLE | When the requester notice was delivered; stays null when notify = false. |
Eight hub invariants
-
01One requester and one durable assignee per monitor Database constraint
requester_idandassignee_idareNOT NULLforeign keys toparties(id). The assignee outlives any single checker session (always the lead agent or hub, never an ephemeral checker). -
02At most one check per scheduled due time Database constraint
UNIQUE (monitor_id, due_at)ensures every scheduled slot has a single authoritative outcome. If a sluggish checker reports after the supervisor already recorded that slot asmissed, the hub rejects the late write withduplicate_due_at. -
03Status derives strictly from the newest check outcome Hub guard
okmaps took,triggeredmaps totriggered, and botherrorandmissedmap tounknown. A new monitor startsunknownwithstatus_since = created_at. -
04
status_sinceadvances only when status changes Hub guardRepeated
okchecks keep the original timestamp, while recovering fromunknownresetsstatus_sinceto the recovery check — so a monitor never falsely claims a condition held across an unchecked gap. -
05Runner fields match missed vs. executed outcomes Database constraint
A
CHECKconstraint (mirrored by hub guardsrunner_requiredandmissed_must_not_have_runner) ensuresran_atandran_by_idare present if and only ifoutcome != 'missed'. Only the supervisor writesmissedchecks, and only oncenow > due_at + grace_seconds. -
06Notify only on meaningful transitions or final check Hub guard
notifyis settrueon any status transition or when the monitor ends, except the very first transition of a new monitor fromunknowntook(detected viastatus_since == created_at), which confirms baseline health without disturbing the requester. -
07Ended monitors schedule no further checks Hub guard
An
eventmonitor ends on its firsttriggeredcheck, and every monitor ends oncedue_at + interval_seconds > ends_at. Ending setsended_atand clearsnext_check_at; further reports or repairs are rejected withmonitor_ended. -
08Error and missed checks always alert the assignee; only the assignee may schedule a repair re-check Hub guard
record_checksetsalert_assignee = truewheneveroutcomeiserrorormissed, regardless of whetherstatuschanged — so a brand-new monitor that fails on its very first run (unknown→unknown) alerts its assignee immediately instead of staying silent untilends_at. Once fixed, onlyassignee_idmay callmark_repaired(elseonly_assignee_may_repair), and only whilestatus == 'unknown'(elsemonitor_not_unknown), returning an immediate replacementdue_at(nowwhen beforenext_check_at, otherwise the already-duenext_check_at) so the out-of-band check runs right away without shifting the regularnext_check_atgrid.
Reference implementation
The same minimal monitor state machine, independent supervisor sweep, and assignee repair command in Lean, TypeScript, Python, and Elixir. Notice how cleanly the first-ok suppression, assignee repair alert, immediate re-check, and end-of-life rules fit into three pure transitions.
-- Hub guards, supervisor sweep & assignee repair for Condition Monitor (timestamps in epoch seconds)
import Std.Data.HashMap
import Std.Data.HashSet
open Std
inductive MonitorKind where
| condition | event
deriving Repr, BEq
inductive MonitorStatus where
| ok | triggered | unknown
deriving Repr, BEq, DecidableEq
inductive CheckOutcome where
| ok | triggered | error | missed
deriving Repr, BEq
structure Monitor where
id : String
requesterId : String
assigneeId : String
kind : MonitorKind
statement : String
intervalSeconds : Nat
graceSeconds : Nat
status : MonitorStatus := .unknown
statusSince : Nat
nextCheckAt : Option Nat
endsAt : Nat
endedAt : Option Nat := none
createdAt : Nat
deriving Repr
structure MonitorCheck where
id : String
monitorId : String
dueAt : Nat
ranAt : Option Nat := none
ranById : Option String := none
outcome : CheckOutcome
summary : String
notify : Bool := false
alertAssignee : Bool := false
deriving Repr
inductive HubError where
| unknownMonitor | monitorEnded | duplicateDueAt | missedMustNotHaveRunner
| runnerRequired | onlyAssigneeMayRepair | monitorNotUnknown
deriving Repr, BEq
structure MonitorHub where
monitors : HashMap String Monitor := {}
recordedSlots : HashSet (String × Nat) := {} -- (monitorId, dueAt)
namespace MonitorHub
def statusAfter : CheckOutcome → MonitorStatus
| .ok => .ok
| .triggered => .triggered
| .error | .missed => .unknown
def getMonitor (hub : MonitorHub) (monitorId : String) : Except HubError Monitor :=
match hub.monitors[monitorId]? with
| some m => pure m
| none => throw .unknownMonitor
def recordCheck (hub : MonitorHub) (monitorId : String) (check : MonitorCheck) (now : Nat) :
Except HubError (Monitor × MonitorCheck × MonitorHub) := do
let m ← hub.getMonitor monitorId
if m.endedAt.isSome then throw .monitorEnded
let slot := (monitorId, check.dueAt)
if hub.recordedSlots.contains slot then throw .duplicateDueAt
if check.outcome == .missed then
if check.ranAt.isSome || check.ranById.isSome then throw .missedMustNotHaveRunner
else
if check.ranAt.isNone || check.ranById.isNone then throw .runnerRequired
let nextStatus := statusAfter check.outcome
let changed := nextStatus != m.status
-- A new monitor's first passing check confirms baseline health without alerting.
let firstOk := nextStatus == .ok && m.status == .unknown && m.statusSince == m.createdAt
-- An out-of-band repair check before nextCheckAt keeps the regular schedule grid intact.
let nextDue := match m.nextCheckAt with
| some next => if check.dueAt < next then next else check.dueAt + m.intervalSeconds
| none => check.dueAt + m.intervalSeconds
let ended := (m.kind == .event && nextStatus == .triggered) || nextDue > m.endsAt
let monitor := { m with
status := nextStatus
statusSince := if changed then now else m.statusSince
nextCheckAt := if ended then none else some nextDue
endedAt := if ended then some now else none }
let check := { check with
notify := (changed && !firstOk) || ended
-- Always alert the assignee on error/missed, even when a new monitor fails on its first run.
alertAssignee := check.outcome == .error || check.outcome == .missed }
let hub := { hub with
monitors := hub.monitors.insert monitorId monitor
recordedSlots := hub.recordedSlots.insert slot }
pure (monitor, check, hub)
-- Assignee triggers an immediate replacement check while keeping nextCheckAt on the regular grid.
def markRepaired (hub : MonitorHub) (monitorId actorId : String) (now : Nat) :
Except HubError (Monitor × Nat) := do
let m ← hub.getMonitor monitorId
if m.endedAt.isSome || now > m.endsAt then throw .monitorEnded
if m.assigneeId != actorId then throw .onlyAssigneeMayRepair
if m.status != .unknown then throw .monitorNotUnknown
let immediateDueAt := match m.nextCheckAt with
| some next => if now < next then now else next
| none => now
pure (m, immediateDueAt)
-- Independent supervisor timer: sweeps overdue monitors directly by nextCheckAt + graceSeconds.
-- `newId` stands in for a UUID generator; it is given a running count of missed checks.
def sweepOverdue (hub : MonitorHub) (now : Nat) (newId : Nat → String) :
Except HubError (List MonitorCheck × MonitorHub) :=
hub.monitors.values.foldlM (init := ([], hub)) fun (missed, hub) m => do
match m.endedAt, m.nextCheckAt with
-- Nat subtraction stops at 0, so a check that isn't due yet is never overdue
| none, some next =>
if now - next > m.graceSeconds then
let chk : MonitorCheck := {
id := newId missed.length, monitorId := m.id, dueAt := next, outcome := .missed
summary := "The scheduled check did not report within its grace period." }
let (_, saved, hub) ← hub.recordCheck m.id chk now
pure (missed ++ [saved], hub)
else
pure (missed, hub)
| _, _ => pure (missed, hub)
-- An error or missed check always leaves the monitor's status unknown.
theorem statusAfter_failure (o : CheckOutcome) (h : o = .error ∨ o = .missed) :
statusAfter o = .unknown := by
cases h <;> simp_all [statusAfter]
end MonitorHub
// Hub guards, supervisor sweep & assignee repair for Condition Monitor (timestamps in epoch seconds)
type MonitorKind = "condition" | "event";
type MonitorStatus = "ok" | "triggered" | "unknown";
type CheckOutcome = "ok" | "triggered" | "error" | "missed";
interface Monitor {
id: string;
requesterId: string;
assigneeId: string;
kind: MonitorKind;
statement: string;
intervalSeconds: number;
graceSeconds: number;
status: MonitorStatus;
statusSince: number;
nextCheckAt: number | null;
endsAt: number;
endedAt: number | null;
createdAt: number;
}
interface MonitorCheck {
id: string;
monitorId: string;
dueAt: number;
ranAt: number | null;
ranById: string | null;
outcome: CheckOutcome;
summary: string;
notify: boolean;
alertAssignee: boolean;
}
class MonitorHub {
private monitors = new Map<string, Monitor>();
private recordedSlots = new Set<string>(); // "monitorId:dueAt"
recordCheck(monitorId: string, check: MonitorCheck, now: number): { monitor: Monitor; check: MonitorCheck } {
const m = this.monitors.get(monitorId);
if (!m) throw new Error("unknown_monitor");
if (m.endedAt !== null) throw new Error("monitor_ended");
const slot = `${monitorId}:${check.dueAt}`;
if (this.recordedSlots.has(slot)) throw new Error("duplicate_due_at");
if (check.outcome === "missed") {
if (check.ranAt !== null || check.ranById !== null) throw new Error("missed_must_not_have_runner");
} else {
if (check.ranAt === null || check.ranById === null) throw new Error("runner_required");
}
const nextStatus = this.statusAfter(check.outcome);
const changed = nextStatus !== m.status;
// A new monitor's first passing check confirms baseline health without alerting.
const firstOk = nextStatus === "ok" && m.status === "unknown" && m.statusSince === m.createdAt;
// An out-of-band repair check before nextCheckAt keeps the regular schedule grid intact.
const nextDue =
m.nextCheckAt !== null && check.dueAt < m.nextCheckAt
? m.nextCheckAt
: check.dueAt + m.intervalSeconds;
const ended = (m.kind === "event" && nextStatus === "triggered") || nextDue > m.endsAt;
m.status = nextStatus;
if (changed) m.statusSince = now;
m.nextCheckAt = ended ? null : nextDue;
m.endedAt = ended ? now : null;
check.notify = (changed && !firstOk) || ended;
// Always alert the assignee on error/missed, even when a new monitor fails on its very first run.
check.alertAssignee = check.outcome === "error" || check.outcome === "missed";
this.recordedSlots.add(slot);
return { monitor: m, check };
}
// Assignee triggers an immediate replacement check while keeping nextCheckAt on the regular grid.
markRepaired(monitorId: string, actorId: string, now: number): { monitor: Monitor; immediateDueAt: number } {
const m = this.monitors.get(monitorId);
if (!m) throw new Error("unknown_monitor");
if (m.endedAt !== null || now > m.endsAt) throw new Error("monitor_ended");
if (m.assigneeId !== actorId) throw new Error("only_assignee_may_repair");
if (m.status !== "unknown") throw new Error("monitor_not_unknown");
const immediateDueAt = m.nextCheckAt !== null && now < m.nextCheckAt ? now : (m.nextCheckAt ?? now);
return { monitor: m, immediateDueAt };
}
// Independent supervisor timer: sweeps overdue monitors directly by nextCheckAt + graceSeconds.
sweepOverdue(now: number, newId: () => string): MonitorCheck[] {
const missed: MonitorCheck[] = [];
for (const m of this.monitors.values()) {
if (m.endedAt === null && m.nextCheckAt !== null && now - m.nextCheckAt > m.graceSeconds) {
const chk: MonitorCheck = {
id: newId(), monitorId: m.id, dueAt: m.nextCheckAt,
ranAt: null, ranById: null, outcome: "missed",
summary: "The scheduled check did not report within its grace period.",
notify: false, alertAssignee: false
};
missed.push(this.recordCheck(m.id, chk, now).check);
}
}
return missed;
}
private statusAfter(outcome: CheckOutcome): MonitorStatus {
if (outcome === "ok") return "ok";
if (outcome === "triggered") return "triggered";
return "unknown";
}
}
# Hub guards, supervisor sweep & assignee repair for Condition Monitor (timestamps in epoch seconds)
from dataclasses import dataclass
from typing import Callable, Literal, Optional
@dataclass
class Monitor:
id: str
requester_id: str
assignee_id: str
kind: Literal["condition", "event"]
statement: str
interval_seconds: int
grace_seconds: int
status_since: int
next_check_at: Optional[int]
ends_at: int
created_at: int
status: Literal["ok", "triggered", "unknown"] = "unknown"
ended_at: Optional[int] = None
@dataclass
class MonitorCheck:
id: str
monitor_id: str
due_at: int
outcome: Literal["ok", "triggered", "error", "missed"]
summary: str
ran_at: Optional[int] = None
ran_by_id: Optional[str] = None
notify: bool = False
alert_assignee: bool = False
class HubError(Exception):
pass
class MonitorHub:
def __init__(self) -> None:
self.monitors: dict[str, Monitor] = {}
self.recorded_slots: set[tuple[str, int]] = set()
def record_check(
self, monitor_id: str, check: MonitorCheck, now: int
) -> tuple[Monitor, MonitorCheck]:
m = self.monitors.get(monitor_id)
if m is None:
raise HubError("unknown_monitor")
if m.ended_at is not None:
raise HubError("monitor_ended")
slot = (monitor_id, check.due_at)
if slot in self.recorded_slots:
raise HubError("duplicate_due_at")
if check.outcome == "missed":
if check.ran_at is not None or check.ran_by_id is not None:
raise HubError("missed_must_not_have_runner")
elif check.ran_at is None or check.ran_by_id is None:
raise HubError("runner_required")
next_status = self._status_after(check.outcome)
changed = next_status != m.status
first_ok = next_status == "ok" and m.status == "unknown" and m.status_since == m.created_at
# An out-of-band repair check before next_check_at keeps the regular schedule grid intact.
next_due = (
m.next_check_at
if m.next_check_at is not None and check.due_at < m.next_check_at
else check.due_at + m.interval_seconds
)
ended = (m.kind == "event" and next_status == "triggered") or next_due > m.ends_at
m.status = next_status
if changed:
m.status_since = now
m.next_check_at = None if ended else next_due
m.ended_at = now if ended else None
check.notify = (changed and not first_ok) or ended
# Always alert the assignee on error/missed, even when a new monitor fails on its very first run.
check.alert_assignee = check.outcome in ("error", "missed")
self.recorded_slots.add(slot)
return m, check
def mark_repaired(self, monitor_id: str, actor_id: str, now: int) -> tuple[Monitor, int]:
m = self.monitors.get(monitor_id)
if m is None:
raise HubError("unknown_monitor")
if m.ended_at is not None or now > m.ends_at:
raise HubError("monitor_ended")
if m.assignee_id != actor_id:
raise HubError("only_assignee_may_repair")
if m.status != "unknown":
raise HubError("monitor_not_unknown")
immediate_due_at = now if m.next_check_at is not None and now < m.next_check_at else (m.next_check_at or now)
return m, immediate_due_at
def sweep_overdue(self, now: int, new_id: Callable[[], str]) -> list[MonitorCheck]:
missed: list[MonitorCheck] = []
for m in self.monitors.values():
if m.ended_at is None and m.next_check_at is not None and now - m.next_check_at > m.grace_seconds:
chk = MonitorCheck(
id=new_id(),
monitor_id=m.id,
due_at=m.next_check_at,
outcome="missed",
summary="The scheduled check did not report within its grace period.",
)
_, saved = self.record_check(m.id, chk, now)
missed.append(saved)
return missed
def _status_after(self, outcome: str) -> Literal["ok", "triggered", "unknown"]:
if outcome == "ok":
return "ok"
if outcome == "triggered":
return "triggered"
return "unknown"
# Hub guards, supervisor sweep & assignee repair for Condition Monitor (pure functional core)
defmodule Monitor do
@enforce_keys [
:id, :requester_id, :assignee_id, :kind, :statement,
:interval_seconds, :grace_seconds, :status_since, :ends_at, :created_at
]
defstruct [
:id, :requester_id, :request_id, :assignee_id, :kind, :statement, :check_spec,
:interval_seconds, :grace_seconds, :status_since, :next_check_at,
:ends_at, :ended_at, :created_at,
status: :unknown
]
end
defmodule MonitorCheck do
@enforce_keys [:id, :monitor_id, :due_at, :outcome, :summary]
defstruct [
:id, :monitor_id, :due_at, :ran_at, :ran_by_id, :outcome, :observed, :summary, :notified_at,
notify: false, alert_assignee: false
]
end
defmodule Monitors do
def record_check(%Monitor{ended_at: ended_at}, _check, _slots, _now) when not is_nil(ended_at),
do: {:error, :monitor_ended}
def record_check(%Monitor{} = m, %MonitorCheck{} = check, recorded_slots, now) do
slot = {m.id, check.due_at}
with :ok <- ensure_unique_slot(recorded_slots, slot),
:ok <- validate_runner(check) do
status = status_after(check.outcome)
changed? = status != m.status
first_ok? = status == :ok and m.status == :unknown and DateTime.compare(m.status_since, m.created_at) == :eq
next_due = next_scheduled_due(m, check)
ended? = (m.kind == :event and status == :triggered) or DateTime.compare(next_due, m.ends_at) == :gt
updated_monitor = %{
m
| status: status,
status_since: if(changed?, do: now, else: m.status_since),
next_check_at: if(ended?, do: nil, else: next_due),
ended_at: if(ended?, do: now, else: nil)
}
updated_check = %{
check
| notify: (changed? and not first_ok?) or ended?,
alert_assignee: check.outcome in [:error, :missed]
}
{:ok, updated_monitor, updated_check, MapSet.put(recorded_slots, slot)}
end
end
# Assignee triggers an immediate replacement check while keeping next_check_at on the regular grid.
def mark_repaired(%Monitor{} = m, actor_id, now) do
cond do
not is_nil(m.ended_at) or DateTime.compare(now, m.ends_at) == :gt -> {:error, :monitor_ended}
m.assignee_id != actor_id -> {:error, :only_assignee_may_repair}
m.status != :unknown -> {:error, :monitor_not_unknown}
true ->
immediate_due =
if not is_nil(m.next_check_at) and DateTime.compare(now, m.next_check_at) == :lt,
do: now,
else: m.next_check_at || now
{:ok, m, immediate_due}
end
end
defp next_scheduled_due(%Monitor{next_check_at: next_at} = m, %MonitorCheck{due_at: due_at}) do
if not is_nil(next_at) and DateTime.compare(due_at, next_at) == :lt,
do: next_at,
else: DateTime.add(due_at, m.interval_seconds, :second)
end
# Independent supervisor timer sweep: flags monitors past next_check_at + grace_seconds.
def sweep_overdue(monitors, now, new_id) do
for m <- monitors, is_nil(m.ended_at), overdue?(m, now) do
%MonitorCheck{
id: new_id.(),
monitor_id: m.id,
due_at: m.next_check_at,
outcome: :missed,
summary: "The scheduled check did not report within its grace period."
}
end
end
defp ensure_unique_slot(slots, slot),
do: if(MapSet.member?(slots, slot), do: {:error, :duplicate_due_at}, else: :ok)
defp validate_runner(%MonitorCheck{outcome: :missed, ran_at: nil, ran_by_id: nil}), do: :ok
defp validate_runner(%MonitorCheck{outcome: :missed}), do: {:error, :missed_must_not_have_runner}
defp validate_runner(%MonitorCheck{ran_at: nil}), do: {:error, :runner_required}
defp validate_runner(%MonitorCheck{ran_by_id: nil}), do: {:error, :runner_required}
defp validate_runner(_check), do: :ok
defp status_after(:ok), do: :ok
defp status_after(:triggered), do: :triggered
defp status_after(outcome) when outcome in [:error, :missed], do: :unknown
defp overdue?(%Monitor{next_check_at: nil}, _now), do: false
defp overdue?(m, now), do: DateTime.diff(now, m.next_check_at, :second) > m.grace_seconds
end
Trigger, missed check, repair, and late-report trace
Walking Example 2 (duplicate invoices stay at zero) through these guards
shows quiet initial health, a supervisor-recorded missed
check setting alert_assignee: true after the 10-minute
grace window, rejection of a late report with
duplicate_due_at, an immediate
mark_repaired replacement check, and transition-only
requester notifications:
1. hub.recordCheck(mon_dup_inv, chk_tue_1600: { dueAt: 16:00, outcome: "ok", ranBy: checker_1 })
-> ok (status: unknown -> ok; first_ok suppresses alert: notify = false, alertAssignee = false; next = 17:00)
2. # Wed 17:00 checker fails auth and exits without reporting
hub.sweepOverdue(now: Wed 17:10:01) # 10m grace_seconds elapsed
-> missed check recorded (status: ok -> unknown; notify = true, alertAssignee = true -> lead_1 alerted)
3. hub.recordCheck(mon_dup_inv, chk_wed_1700_late: { dueAt: Wed 17:00, outcome: "ok", ranBy: checker_2 })
-> error: duplicate_due_at (slot Wed 17:00 is already finalized as missed)
4. hub.markRepaired(mon_dup_inv, actor: lead_1, now: Wed 17:40)
-> immediateDueAt: Wed 17:40 (next_check_at stays on hourly grid: Wed 18:00)
hub.recordCheck(mon_dup_inv, chk_wed_1740: { dueAt: Wed 17:40, outcome: "ok", ranBy: checker_3 })
-> status: ok (next_check_at stays Wed 18:00; board records unchecked gap 16:00-17:40)
5. hub.recordCheck(mon_dup_inv, chk_thu_0900: { dueAt: Thu 09:00, outcome: "triggered",
observed: { duplicates: 4, customers: 1 }, ranBy: checker_4 })
-> status: triggered (status_since = Thu 09:00:21; notify = true -> requester told once)
6. hub.recordCheck(mon_dup_inv, chk_fri_1100: { dueAt: Fri 11:00, outcome: "ok",
observed: { duplicates: 0 }, ranBy: checker_5 })
-> status: ok (status_since = Fri 11:00:15; notify = true -> recovery notice sent once)
Tradeoffs and practical guidance
Condition Monitor frees the requester from manual polling while keeping blind spots honest. Weigh three practical costs before registering a monitor:
-
Ongoing check cost until
ends_at: every scheduled run that launches an agent costs compute and tokens. Prefer lightweight deterministic queries where possible and always set a realistic end date. -
Checking the wrong thing with high confidence: if the lead agent
translates a requester's sentence into a buggy query or wrong table, the monitor will
cheerfully report
okwhile the real problem grows. - Who watches the supervisor? An independent supervisor timer catches stalled checkers and dropped jobs, but if the hub itself goes down, external uptime monitoring must still watch the hub.
Practical implementation notes
- Restate the monitor in plain English before activating: have the lead agent echo back its exact interpretation ("I will count duplicate invoices every 60 minutes until December 1 and tell you if the count exceeds zero") so misread criteria are caught before run one.
-
Debounce noisy thresholds: if a metric hovers near a threshold, require
it to breach across consecutive checks or a minimum window (like Prometheus's
forclause) before emittingtriggered. -
Query durable due times, never the job queue: the supervisor timer
should sweep
monitorsdirectly whereended_at IS NULL AND next_check_at + grace_seconds < now(), because a lost queue entry is the exact failure it exists to expose. -
Never merge
triggered,error, andmissed: treating a database timeout astriggeredpages the requester about an infrastructure hiccup as if customer invoices broke; treating it asokhides a real outage.
Known uses and related patterns
-
Prometheus alerting rules: evaluates conditions on a cadence and uses a
forduration so transient spikes do not flap alerts before Alertmanager routes a notification. -
Grafana Alerting: explicitly distinguishes
NoDataandErrorevaluation states from threshold breaches so a broken data source is not mistaken for a healthy check. - Healthchecks.io: implements the classic dead man's switch with per-check intervals and grace periods, alerting whenever an expected heartbeat fails to arrive on time.
- LangSmith Agent Server cron jobs: invokes an agent on a schedule with fixed input, though condition state transitions and missed-run tracking must be added by the surrounding application.
- Volgenic: combines scheduled agent runs with dedicated threshold alarms for infrastructure health; Condition Monitor unifies those capabilities under one requester-facing state machine with explicit missed-check visibility.
- Martin Fowler's HeartBeat pattern: in Patterns of Distributed Systems, a missing periodic signal triggers supervisor investigation; Condition Monitor applies that same principle to recurring business and engineering checks.
Related patterns
- Derived Status Board — renders one computed status row per monitor so missed checks and unchecked gaps become immediately visible.
- Question Inbox — decides whether a monitor's
notify: truecheck waits for the next check-in or interrupts immediately via an interrupt rule. - Resumable Wait — most easily confused with Condition Monitor: a wait belongs to a job and resumes that job, whereas a monitor belongs to the requester and reports status changes.
- Progress Heartbeat — watches every active worker automatically for execution progress, rather than watching a requester-defined condition.
- Delegation Policy — lets the lead agent automatically reopen a fix when a monitor triggers, without waiting for human approval.
- Orchestrator-Workers — defines the
PartyandRequestrecords referenced by every monitor.