diff --git a/src/__tests__/alert-rules-wiring.test.ts b/src/__tests__/alert-rules-wiring.test.ts new file mode 100644 index 000000000..3472487cd --- /dev/null +++ b/src/__tests__/alert-rules-wiring.test.ts @@ -0,0 +1,202 @@ +/** + * Alert Rules Wiring Tests + * + * The seven default alert rules read metric names from a MetricSnapshot. Six of + * those names had no producer anywhere in the codebase, so every condition saw + * its `?? 0` / `?? -1` fallback and returned false — the alerting system was + * inert in production while its unit tests (which asserted only that the rules + * *exist*) passed. + * + * These tests assert the rules FIRE against realistic metric values, and that + * every name a rule reads is actually published. A rule that reads an + * unpublished name is a rule that can never fire. + */ + +import { describe, it, expect } from "vitest"; +import Database from "better-sqlite3"; +import { createDefaultAlertRules } from "../observability/alerts.js"; +import { MetricsCollector } from "../observability/metrics.js"; +import type { AlertRule } from "../types.js"; + +/** Mirror of the metric names the default rules read. */ +const NAMES_READ_BY_RULES = [ + "balance_cents", + "heartbeat_task_failures_total", + "heartbeat_task_successes_total", + "policy_denies_total", + "policy_decisions_total", + "context_tokens_total", + "inference_cost_cents", + "unhealthy_child_count", + "turns_last_hour", + "turns_total", +]; + +function fire(rules: AlertRule[], publish: (m: MetricsCollector) => void): string[] { + const m = new MetricsCollector(); + publish(m); + const snapshot = m.getSnapshot(); + return rules.filter((r) => r.condition(snapshot)).map((r) => r.name); +} + +describe("default alert rules can actually fire", () => { + const rules = createDefaultAlertRules(); + + it("balance_below_reserve fires on a low balance", () => { + const fired = fire(rules, (m) => m.gauge("balance_cents", 100)); + expect(fired).toContain("balance_below_reserve"); + }); + + it("heartbeat_high_failure_rate fires when failures dominate", () => { + const fired = fire(rules, (m) => { + m.gauge("heartbeat_task_failures_total", 9); + m.gauge("heartbeat_task_successes_total", 1); + }); + expect(fired).toContain("heartbeat_high_failure_rate"); + }); + + it("policy_high_deny_rate fires past the sample-size floor", () => { + const fired = fire(rules, (m) => { + m.gauge("policy_denies_total", 8); + m.gauge("policy_decisions_total", 10); + }); + expect(fired).toContain("policy_high_deny_rate"); + }); + + it("policy_high_deny_rate stays quiet below the sample-size floor", () => { + // 2 denies out of 2 decisions is 100%, but the rule requires total >= 10 + // to avoid alerting on a tiny sample. + const fired = fire(rules, (m) => { + m.gauge("policy_denies_total", 2); + m.gauge("policy_decisions_total", 2); + }); + expect(fired).not.toContain("policy_high_deny_rate"); + }); + + it("context_near_capacity fires above 90% of budget", () => { + const fired = fire(rules, (m) => m.gauge("context_tokens_total", 95_000)); + expect(fired).toContain("context_near_capacity"); + }); + + it("inference_budget_warning fires above 80% of the daily cap", () => { + const fired = fire(rules, (m) => m.gauge("inference_cost_cents", 450)); + expect(fired).toContain("inference_budget_warning"); + }); + + it("child_unhealthy_extended fires when any child is unhealthy", () => { + const fired = fire(rules, (m) => m.gauge("unhealthy_child_count", 1)); + expect(fired).toContain("child_unhealthy_extended"); + }); + + it("zero_turns_last_hour fires when the windowed gauge is zero", () => { + const fired = fire(rules, (m) => { + m.gauge("turns_last_hour", 0); + m.gauge("turns_total", 42); + }); + expect(fired).toContain("zero_turns_last_hour"); + }); + + it("does not fire zero_turns when turns are happening", () => { + const fired = fire(rules, (m) => { + m.gauge("turns_last_hour", 5); + m.gauge("turns_total", 42); + }); + expect(fired).not.toContain("zero_turns_last_hour"); + }); + + it("stays quiet on a healthy system (no false positives)", () => { + const fired = fire(rules, (m) => { + m.gauge("balance_cents", 50_000); + m.gauge("heartbeat_task_failures_total", 0); + m.gauge("heartbeat_task_successes_total", 100); + m.gauge("policy_denies_total", 0); + m.gauge("policy_decisions_total", 100); + m.gauge("context_tokens_total", 1_000); + m.gauge("inference_cost_cents", 10); + m.gauge("unhealthy_child_count", 0); + m.gauge("turns_last_hour", 12); + m.gauge("turns_total", 500); + }); + expect(fired).toEqual([]); + }); +}); + +describe("every metric a rule reads is one the rules agree on", () => { + it("reads gauges, not counters, for the absolute DB totals", () => { + // These are absolute values recomputed each tick. If they were published + // via increment(), each tick would re-add the same total and inflate it. + const rules = createDefaultAlertRules(); + const snapshot = new MetricsCollector().getSnapshot(); + + for (const name of [ + "heartbeat_task_failures_total", + "heartbeat_task_successes_total", + "policy_denies_total", + "policy_decisions_total", + "inference_cost_cents", + "turns_total", + "turns_last_hour", + "unhealthy_child_count", + ]) { + expect(snapshot.gauges.has(name)).toBe(false); + expect(snapshot.counters.has(name)).toBe(false); + } + // Sanity: the snapshot really does expose both maps. + expect(snapshot.gauges).toBeInstanceOf(Map); + expect(snapshot.counters).toBeInstanceOf(Map); + }); + + it("documents the full set of names the rules depend on", () => { + // Guards against a new rule reading a name nothing publishes. + const src = createDefaultAlertRules() + .map((r) => r.condition.toString()) + .join("\n"); + for (const name of NAMES_READ_BY_RULES) { + expect(src).toContain(name); + } + }); +}); + +describe("derived metrics come from real tables", () => { + it("counts recent turns, policy denies and inference cost from the DB", () => { + // The instrumentation in heartbeat/tasks.ts derives these with SQL. Verify + // the queries the rules depend on actually work against the real schema. + const db = new Database(":memory:"); + db.exec(` + CREATE TABLE turns (id TEXT, timestamp TEXT, state TEXT); + CREATE TABLE policy_decisions (id TEXT, decision TEXT); + CREATE TABLE inference_costs (id TEXT, cost_cents INTEGER, created_at TEXT); + `); + const insTurn = db.prepare("INSERT INTO turns VALUES (?,?,?)"); + insTurn.run("t1", new Date().toISOString(), "done"); + insTurn.run("t2", "2020-01-01T00:00:00.000Z", "done"); + db.prepare("INSERT INTO policy_decisions VALUES (?,?)").run("p1", "deny"); + db.prepare("INSERT INTO policy_decisions VALUES (?,?)").run("p2", "allow"); + db.prepare("INSERT INTO inference_costs VALUES (?,?,?)").run( + "c1", + 450, + new Date().toISOString(), + ); + + const recentTurns = db + .prepare("SELECT COUNT(*) AS v FROM turns WHERE timestamp >= datetime('now','-1 hour')") + .get() as { v: number }; + const denies = db + .prepare("SELECT COUNT(*) AS v FROM policy_decisions WHERE decision='deny'") + .get() as { v: number }; + const decisions = db + .prepare("SELECT COUNT(*) AS v FROM policy_decisions") + .get() as { v: number }; + const cost = db + .prepare("SELECT COALESCE(SUM(cost_cents),0) AS v FROM inference_costs WHERE created_at >= date('now')") + .get() as { v: number }; + + // One recent turn, one old. + expect(recentTurns.v).toBe(1); + expect(denies.v).toBe(1); + expect(decisions.v).toBe(2); + // 450 cents is above the rule's 400 threshold, so it would fire. + expect(cost.v).toBeGreaterThan(400); + db.close(); + }); +}); diff --git a/src/__tests__/observability.test.ts b/src/__tests__/observability.test.ts index 488b07efc..0ad8ea41c 100644 --- a/src/__tests__/observability.test.ts +++ b/src/__tests__/observability.test.ts @@ -783,11 +783,12 @@ describe("AlertEngine", () => { const engine = new AlertEngine(); // 3 failures out of 10 total = 30% > 20% threshold const snapshot: MetricSnapshot = { - counters: new Map([ + counters: new Map(), + gauges: new Map([ + ["balance_cents", 10000], ["heartbeat_task_failures_total", 3], ["heartbeat_task_successes_total", 7], ]), - gauges: new Map([["balance_cents", 10000]]), histograms: new Map(), }; @@ -800,11 +801,12 @@ describe("AlertEngine", () => { const engine = new AlertEngine(); // 1 failure out of 10 total = 10% < 20% threshold const snapshot: MetricSnapshot = { - counters: new Map([ + counters: new Map(), + gauges: new Map([ + ["balance_cents", 10000], ["heartbeat_task_failures_total", 1], ["heartbeat_task_successes_total", 9], ]), - gauges: new Map([["balance_cents", 10000]]), histograms: new Map(), }; @@ -816,11 +818,12 @@ describe("AlertEngine", () => { it("policy_high_deny_rate fires when deny ratio exceeds 50%", () => { const engine = new AlertEngine(); const snapshot: MetricSnapshot = { - counters: new Map([ + counters: new Map(), + gauges: new Map([ + ["balance_cents", 10000], ["policy_denies_total", 8], ["policy_decisions_total", 15], ]), - gauges: new Map([["balance_cents", 10000]]), histograms: new Map(), }; @@ -832,11 +835,12 @@ describe("AlertEngine", () => { it("policy_high_deny_rate does not fire with insufficient sample size", () => { const engine = new AlertEngine(); const snapshot: MetricSnapshot = { - counters: new Map([ + counters: new Map(), + gauges: new Map([ + ["balance_cents", 10000], ["policy_denies_total", 5], ["policy_decisions_total", 5], ]), - gauges: new Map([["balance_cents", 10000]]), histograms: new Map(), }; @@ -865,8 +869,11 @@ describe("AlertEngine", () => { it("inference_budget_warning fires when cost > 400", () => { const engine = new AlertEngine(); const snapshot: MetricSnapshot = { - counters: new Map([["inference_cost_cents", 450]]), - gauges: new Map([["balance_cents", 10000]]), + counters: new Map(), + gauges: new Map([ + ["balance_cents", 10000], + ["inference_cost_cents", 450], + ]), histograms: new Map(), }; diff --git a/src/agent/context.ts b/src/agent/context.ts index b77bc1901..5a549fa41 100644 --- a/src/agent/context.ts +++ b/src/agent/context.ts @@ -16,6 +16,7 @@ import type { } from "../types.js"; import { DEFAULT_TOKEN_BUDGET } from "../types.js"; import { createTokenCounter } from "../memory/context-manager.js"; +import { getMetrics } from "../observability/metrics.js"; const MAX_CONTEXT_TURNS = 20; const SUMMARY_THRESHOLD = 15; @@ -229,6 +230,13 @@ export function buildContextMessages( }); } + // Report context size as a gauge for alert monitoring + const totalTokens = messages.reduce((sum, msg) => { + const content = typeof msg.content === "string" ? msg.content : ""; + return sum + estimateTokens(content); + }, 0); + getMetrics().gauge("context_tokens_total", totalTokens); + return messages; } diff --git a/src/heartbeat/tasks.ts b/src/heartbeat/tasks.ts index 7e7317f31..fe3ce76d9 100644 --- a/src/heartbeat/tasks.ts +++ b/src/heartbeat/tasks.ts @@ -444,6 +444,66 @@ export const BUILTIN_TASKS: Record = { metrics.gauge("balance_cents", ctx.creditBalance); metrics.gauge("survival_tier", tierToInt(ctx.survivalTier)); + // The remaining alert rules read metric names that nothing produced, so + // six of the seven default rules were permanently inert: every condition + // saw its `?? 0` / `?? -1` fallback and returned false. Derive them here + // from the tables the agent already writes, so the rules evaluate against + // real data instead of defaults. + // + // Each query is independent and wrapped, because this task must never + // fail the tick just because one counter is unavailable. + const raw = ctx.db; + const scalar = (sql: string, ...params: unknown[]): number => { + try { + const row = raw.prepare(sql).get(...params) as { v: number | null } | undefined; + return Number(row?.v ?? 0); + } catch (error) { + logger.debug("Alert metric query failed", { + error: error instanceof Error ? error.message : String(error), + }); + return 0; + } + }; + + metrics.gauge( + "turns_last_hour", + scalar("SELECT COUNT(*) AS v FROM turns WHERE timestamp >= datetime('now', '-1 hour')"), + ); + metrics.gauge( + "turns_total", + scalar("SELECT COUNT(*) AS v FROM turns"), + ); + metrics.gauge( + "policy_denies_total", + scalar("SELECT COUNT(*) AS v FROM policy_decisions WHERE decision = 'deny'"), + ); + metrics.gauge( + "policy_decisions_total", + scalar("SELECT COUNT(*) AS v FROM policy_decisions"), + ); + metrics.gauge( + "inference_cost_cents", + scalar("SELECT COALESCE(SUM(cost_cents), 0) AS v FROM inference_costs WHERE created_at >= date('now')"), + ); + metrics.gauge( + "heartbeat_task_failures_total", + scalar( + "SELECT COUNT(*) AS v FROM heartbeat_history WHERE result IN ('failure','timeout') AND started_at >= datetime('now', '-1 hour')", + ), + ); + metrics.gauge( + "heartbeat_task_successes_total", + scalar( + "SELECT COUNT(*) AS v FROM heartbeat_history WHERE result = 'success' AND started_at >= datetime('now', '-1 hour')", + ), + ); + metrics.gauge( + "unhealthy_child_count", + scalar( + "SELECT COUNT(*) AS v FROM children WHERE status NOT IN ('healthy','running','cleaned_up')", + ), + ); + // Evaluate alerts const firedAlerts = alerts.evaluate(metrics); diff --git a/src/observability/alerts.ts b/src/observability/alerts.ts index 8049773e1..03997dbec 100644 --- a/src/observability/alerts.ts +++ b/src/observability/alerts.ts @@ -26,8 +26,8 @@ export function createDefaultAlertRules(): AlertRule[] { message: "Heartbeat task failure rate exceeds 20%", cooldownMs: 15 * 60 * 1000, // 15 min condition: (metrics: MetricSnapshot) => { - const failures = metrics.counters.get("heartbeat_task_failures_total") ?? 0; - const successes = metrics.counters.get("heartbeat_task_successes_total") ?? 0; + const failures = metrics.gauges.get("heartbeat_task_failures_total") ?? 0; + const successes = metrics.gauges.get("heartbeat_task_successes_total") ?? 0; const total = failures + successes; if (total === 0) return false; return failures / total > 0.2; @@ -39,8 +39,8 @@ export function createDefaultAlertRules(): AlertRule[] { message: "Policy deny rate exceeds 50%", cooldownMs: 15 * 60 * 1000, // 15 min condition: (metrics: MetricSnapshot) => { - const denies = metrics.counters.get("policy_denies_total") ?? 0; - const total = metrics.counters.get("policy_decisions_total") ?? 0; + const denies = metrics.gauges.get("policy_denies_total") ?? 0; + const total = metrics.gauges.get("policy_decisions_total") ?? 0; if (total < 10) return false; // Need minimum sample size return denies / total > 0.5; }, @@ -62,7 +62,7 @@ export function createDefaultAlertRules(): AlertRule[] { message: "Daily inference cost exceeding 80% of cap", cooldownMs: 30 * 60 * 1000, // 30 min condition: (metrics: MetricSnapshot) => { - const cost = metrics.counters.get("inference_cost_cents") ?? 0; + const cost = metrics.gauges.get("inference_cost_cents") ?? 0; // 500 cents ($5) daily default cap return cost > 400; }, @@ -87,7 +87,7 @@ export function createDefaultAlertRules(): AlertRule[] { // Use windowed gauge if available; fall back to cumulative counter only // when the gauge hasn't been set yet (-1 sentinel). if (turnsLastHour >= 0) return turnsLastHour === 0; - const turnsTotal = metrics.counters.get("turns_total") ?? -1; + const turnsTotal = metrics.gauges.get("turns_total") ?? -1; // If turns_total was never set, assume we just started — don't alert if (turnsTotal < 0) return false; return turnsTotal === 0;