From 98d196c11daefe8f9703a44b97e6ec9cf2757e87 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 20:18:46 -0600 Subject: [PATCH] cloudflare-export: alert on Workers AI neurons/day over threshold (#2287) The workers-ai-neurons metric is a per-day cycle average, which diluted the Oct 24-25 2026 burn (4.11M neurons, ~$45) to invisibility. Add a grouped per-day/per-model aiInference query (dimensions date + modelId, verified against the live GraphQL schema), a threshold rule (env CLOUDFLARE_AI_NEURONS_DAY_ALERT_THRESHOLD, default 50000, honest fallback on invalid values), and an alerts array on the success document present only when firing, with top-3 model attribution and lower-bound saturation flagging. The aggregator appends firing alerts loudly to the Cloudflare card sourceNote; documents without alerts render exactly as before. The average metric is unchanged. --- pm-stack/aggregator/src/saas-extract.ts | 42 +++++- .../aggregator/test/cloudflare-export.test.ts | 35 +++++ pm-stack/cloudflare-export/README.md | 44 ++++++ .../cloudflare-quota-export.mjs | 104 +++++++++++++- .../cloudflare-quota-export.test.mjs | 136 ++++++++++++++++++ 5 files changed, 357 insertions(+), 4 deletions(-) diff --git a/pm-stack/aggregator/src/saas-extract.ts b/pm-stack/aggregator/src/saas-extract.ts index c647280d1c..eff8d0f746 100644 --- a/pm-stack/aggregator/src/saas-extract.ts +++ b/pm-stack/aggregator/src/saas-extract.ts @@ -760,6 +760,19 @@ export interface CloudflareExportMetric { lowerBound?: boolean; } +/** One Workers AI neurons/day alert from the export document (#2287): + * a UTC day in the cycle-to-date whose grouped per-day total exceeded + * the exporter's threshold. Present only when firing. */ +export interface CloudflareExportAlert { + kind?: string; + date?: string; + totalNeurons?: number; + threshold?: number; + topModels?: { model?: string; neurons?: number }[]; + /** Day total is a lower bound (grouped query hit its limit). */ + lowerBound?: boolean; +} + /** The file-export document written by pm-stack/cloudflare-export. */ export interface CloudflareExportDoc { service?: string; @@ -769,6 +782,7 @@ export interface CloudflareExportDoc { cycleStart?: string; billing?: { status?: string }; metrics?: CloudflareExportMetric[]; + alerts?: CloudflareExportAlert[]; } /** Freshness bound for preferring export values: the #1151 tick is @@ -830,10 +844,36 @@ export function applyCloudflareExport( doc.billing?.status === "invoice-only" ? "; billing invoice-only (subscriptions/billing 403 with the day-to-day token)" : "" - }`; + }${cloudflareAlertsNote(doc.alerts)}`; return services; } +/** Render the export document's Workers AI neurons/day alerts (#2287) + * loudly onto the card's sourceNote. Absent/empty/malformed alerts + * render nothing — a document without alerts renders exactly as + * before. Only called for a fresh ok document (the caller's gates). */ +function cloudflareAlertsNote(alerts: CloudflareExportAlert[] | undefined): string { + if (!Array.isArray(alerts)) return ""; + const parts: string[] = []; + for (const a of alerts) { + if (!a || a.kind !== "workers-ai-neurons-day") continue; + const top = Array.isArray(a.topModels) + ? a.topModels + .filter((m) => m && typeof m.model === "string") + .map((m) => `${m.model} ${typeof m.neurons === "number" ? m.neurons : "?"}`) + .join(", ") + : ""; + parts.push( + `⚠ ALERT workers-ai-neurons-day: ${typeof a.date === "string" ? a.date : "unknown date"} burned ${ + typeof a.totalNeurons === "number" ? a.totalNeurons : "?" + } neurons, over the ${typeof a.threshold === "number" ? a.threshold : "?"} threshold${ + a.lowerBound ? " (total is a lower bound)" : "" + }${top ? `; top models: ${top}` : ""}`, + ); + } + return parts.length ? `; ${parts.join("; ")}` : ""; +} + // --- Supabase live export overlay (#1050) ----------------------------------- /** One metric row of a supabase-quota-export document. */ diff --git a/pm-stack/aggregator/test/cloudflare-export.test.ts b/pm-stack/aggregator/test/cloudflare-export.test.ts index c717157d2e..d86391d76a 100644 --- a/pm-stack/aggregator/test/cloudflare-export.test.ts +++ b/pm-stack/aggregator/test/cloudflare-export.test.ts @@ -83,6 +83,41 @@ describe("applyCloudflareExport", () => { expect(cf.sourceClass).toBe("manual"); }); + test("alerts in a fresh export render loudly on the sourceNote (#2287)", () => { + const doc = freshDoc(); + doc.alerts = [ + { + kind: "workers-ai-neurons-day", + date: "2026-10-24", + totalNeurons: 3090000, + threshold: 50000, + topModels: [ + { model: "@cf/deepseek-ai/deepseek-v4-pro-0813", neurons: 2990000 }, + { model: "@cf/meta/llama-3.1-8b-instruct", neurons: 100000 }, + ], + }, + ]; + const services = applyCloudflareExport(extractSaasServices(VIEW), doc, NOW); + const cf = services.find((s) => s.id === "cloudflare")!; + expect(cf.sourceNote).toContain("⚠ ALERT workers-ai-neurons-day"); + expect(cf.sourceNote).toContain("2026-10-24"); + expect(cf.sourceNote).toContain("3090000"); + expect(cf.sourceNote).toContain("@cf/deepseek-ai/deepseek-v4-pro-0813"); + // The pre-alert rendering is untouched apart from the appended alert. + expect(cf.sourceNote).toContain("invoice-only"); + }); + + test("a document without alerts renders the sourceNote exactly as before (#2287)", () => { + const withEmpty = freshDoc(); + withEmpty.alerts = []; + for (const doc of [freshDoc(), withEmpty]) { + const services = applyCloudflareExport(extractSaasServices(VIEW), doc, NOW); + const cf = services.find((s) => s.id === "cloudflare")!; + expect(cf.sourceNote).not.toContain("ALERT"); + expect(cf.sourceNote).toContain("invoice-only"); + } + }); + test("a lower-bound metric carries the marker onto the card", () => { const doc = freshDoc(); doc.metrics = doc.metrics!.map((m) => (m.id === "r2-storage" ? { ...m, lowerBound: true } : m)); diff --git a/pm-stack/cloudflare-export/README.md b/pm-stack/cloudflare-export/README.md index c20691f8db..a66d4a7ad9 100644 --- a/pm-stack/cloudflare-export/README.md +++ b/pm-stack/cloudflare-export/README.md @@ -28,12 +28,56 @@ One GraphQL analytics POST (`/client/v4/graphql`) plus REST probes: | `r2-class-a`, `r2-class-b` | `r2OperationsAdaptiveGroups` by actionType, classified per Cloudflare's published pricing classes (deletes free; unknown actions reported in `r2UnclassifiedActions`, never guessed) | | `r2-storage` | `r2StorageAdaptiveGroups` max payloadSize → GB; bucket names enumerated directly via `GET /accounts/{id}/r2/buckets` | | `workers-ai-neurons` | `aiInferenceAdaptiveGroups` sum totalNeurons, as a per-day average over the cycle to date (cycle total in the metric's `detail`) | +| neurons/day alert | `aiInferenceAdaptiveGroups` grouped by `date` + `modelId` (limit 10000, sized for cycle-days × models) — see the alert section below | Metric ids match the aggregator's Cloudflare card (`pm-stack/aggregator/src/saas-extract.ts`), which prefers a fresh (< 30 min) export for the card's `used` values and falls back to tracker prose when the export is missing or stale. +## Workers AI neurons/day alert (code#2287) + +The `workers-ai-neurons` metric is a per-day **average** over the +cycle, which dilutes a one-day burn past visibility — the Oct 24–25 +2026 burn (4.11M neurons, ~$45 PAYG) averaged to ~145k/day and was +invisible for days. The exporter therefore also runs the grouped +per-day/per-model query and evaluates a threshold rule on every tick +(the 15-minute cadence surfaces a crossing the same day): + +- **Rule:** any UTC day in the cycle-to-date whose total neurons + **exceed** the threshold fires an alert. +- **Threshold:** env `CLOUDFLARE_AI_NEURONS_DAY_ALERT_THRESHOLD`, + default **50000** (5× the 10k free daily allowance). Unset, empty, + non-numeric, or negative values fall back to the default, so a typo + never silently disables the alert. Retune via the env — no code + change. +- **Surfacing:** the success document gains an `alerts` array, + present **only** when at least one day is firing: + + ```json + "alerts": [{ + "kind": "workers-ai-neurons-day", + "date": "2026-10-24", + "totalNeurons": 3090000, + "threshold": 50000, + "topModels": [{ "model": "@cf/deepseek-ai/deepseek-v4-pro-0813", "neurons": 2990000 }] + }] + ``` + + The aggregator (`pm-stack/aggregator/src/saas-extract.ts`, + `applyCloudflareExport`) appends each alert loudly to the + Cloudflare card's `sourceNote`. `history.jsonl` already persists + every tick's document, so firings are auditable after the fact. A + document without `alerts` renders exactly as before. +- **Saturation:** the grouped query's limit is 10000 (cycle-days × + models). If a result ever hits it, day totals are lower bounds: + alerts carry `lowerBound: true` and the document carries + `aiNeuronsByDaySaturated: true` — flagged, never silently truncated + (the same discipline as `r2-storage`). + +The average metric is unchanged (card compatibility); the alert is +additive. The prevention side (config guard) is code#2288, separate. + ## Billing: invoice-only (settled) Probed live 2026-10-29: `GET /accounts/{id}/billing/profile` and diff --git a/pm-stack/cloudflare-export/cloudflare-quota-export.mjs b/pm-stack/cloudflare-export/cloudflare-quota-export.mjs index 400a56930c..1b6cc37325 100755 --- a/pm-stack/cloudflare-export/cloudflare-quota-export.mjs +++ b/pm-stack/cloudflare-export/cloudflare-quota-export.mjs @@ -24,6 +24,9 @@ * metrics: [ { id, used, unit, source } ] } * Metric ids match the aggregator's saas-extract cloudflare card, so * the aggregator can prefer these live values over tracker prose. + * When a UTC day's Workers AI neurons exceed the alert threshold + * (#2287), the document also carries an `alerts` array (present only + * when firing) which the aggregator surfaces on the card's sourceNote. * * Billing: the subscriptions/billing endpoints return 403 with the * day-to-day token (probed live 2026-10-29, #1048) — the issue's own @@ -57,6 +60,31 @@ export const SOURCE = "file-export/cloudflare"; */ export const API_REQUEST_TIMEOUT_MS = 30_000; export const API_BASE = "https://api.cloudflare.com/client/v4"; +/** + * Workers AI neurons/day alert (#2287). The per-day-average + * workers-ai-neurons metric dilutes a single-day burn across the whole + * cycle (the Oct 24–25 2026 burn: 4.11M neurons, ~$45, invisible for + * days), so the exporter also runs a grouped per-day/per-model + * aiInference query and fires an alert for any UTC day whose total + * exceeds the threshold. The limit sizes for cycle-days × models + * (31 days × every model id in the catalogue, with headroom); a result + * at the limit is flagged as a lower bound, never silently truncated — + * the r2-storage discipline. + */ +export const AI_NEURONS_DAY_GROUP_LIMIT = 10000; +/** Default alert threshold: 5× the 10k free daily neurons allowance. */ +export const AI_NEURONS_DAY_ALERT_THRESHOLD_DEFAULT = 50000; + +/** Threshold from the environment: CLOUDFLARE_AI_NEURONS_DAY_ALERT_THRESHOLD, + * retunable without a code change. Unset, empty, non-numeric, or + * negative values fall back to the default — a typo must never + * silently disable (or zero) the alert. */ +export function aiNeuronsDayAlertThreshold(env = process.env) { + const raw = env?.CLOUDFLARE_AI_NEURONS_DAY_ALERT_THRESHOLD; + if (raw == null || String(raw).trim() === "") return AI_NEURONS_DAY_ALERT_THRESHOLD_DEFAULT; + const n = Number(raw); + return Number.isFinite(n) && n >= 0 ? n : AI_NEURONS_DAY_ALERT_THRESHOLD_DEFAULT; +} /** The analytics scopes the day-to-day token needs for this collector. */ export const ANALYTICS_SCOPES = [ "Account Analytics Read (GraphQL analytics: workersInvocationsAdaptive, kvOperationsAdaptiveGroups, d1AnalyticsAdaptiveGroups, queueMessageOperationsAdaptiveGroups, r2OperationsAdaptiveGroups, r2StorageAdaptiveGroups, aiInferenceAdaptiveGroups)", @@ -179,10 +207,69 @@ const firstSum = (groups, field, label, { integerString = true } = {}) => { return total; }; +const AI_DAY_DATE = /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/; + +/** Fold the grouped per-day/per-model aiInference rows into threshold + * alerts (#2287). Dimension field names verified against the live + * GraphQL schema at implementation time (2026-11-01): `date` and + * `modelId` are the aiInferenceAdaptiveGroups dimensions (`modelName` + * and `model` are unknown fields). Fail-closed like the rest of the + * parser: a missing groups field or a drifted dimension is shape + * drift, not zero usage. Returns the alerts (only days whose total + * strictly exceeds the threshold) plus whether the grouped result hit + * the query limit — in which case day totals are lower bounds and the + * alerts say so. */ +export function aiNeuronsDayAlerts(groups, threshold) { + if (!Array.isArray(groups)) { + throw new ExportError("unparseable", 6, "graphql: aiInferenceAdaptiveGroupsByDay groups missing"); + } + const byDay = new Map(); + for (const g of groups) { + const date = g?.dimensions?.date; + const model = g?.dimensions?.modelId; + if (typeof date !== "string" || !AI_DAY_DATE.test(date)) { + throw new ExportError("unparseable", 6, `graphql: ai dimensions.date not a YYYY-MM-DD date: ${String(date)}`); + } + if (typeof model !== "string" || model === "") { + throw new ExportError("unparseable", 6, "graphql: ai dimensions.modelId missing"); + } + const neurons = num(g?.sum?.totalNeurons, `ai.${date}.${model}.totalNeurons`, { integerString: false }); + let day = byDay.get(date); + if (!day) { + day = { total: 0, models: new Map() }; + byDay.set(date, day); + } + day.total += neurons; + day.models.set(model, (day.models.get(model) ?? 0) + neurons); + } + const saturated = groups.length >= AI_NEURONS_DAY_GROUP_LIMIT; + const alerts = []; + for (const date of [...byDay.keys()].sort()) { + const day = byDay.get(date); + if (day.total <= threshold) continue; + const topModels = [...day.models.entries()] + .map(([model, neurons]) => ({ model, neurons: Math.round(neurons) })) + .sort((a, b) => b.neurons - a.neurons) + .slice(0, 3); + alerts.push({ + kind: "workers-ai-neurons-day", + date, + totalNeurons: Math.round(day.total), + threshold, + topModels, + ...(saturated ? { lowerBound: true } : {}), + }); + } + return { alerts, saturated }; +} + /** Parse one combined GraphQL analytics payload into export metrics. * Fail-closed: any recognised-shape violation throws; GraphQL-level * errors are handled by the caller (they arrive out-of-band). */ -export function parseGraphqlUsage(account, { now = new Date(), cycleStart } = {}) { +export function parseGraphqlUsage( + account, + { now = new Date(), cycleStart, aiThreshold = AI_NEURONS_DAY_ALERT_THRESHOLD_DEFAULT } = {}, +) { const src = "cloudflare-graphql-analytics"; const metrics = []; const push = (id, used, unit, extra = {}) => @@ -242,7 +329,12 @@ export function parseGraphqlUsage(account, { now = new Date(), cycleStart } = {} detail: `per-day average over the cycle to date; cycle total ${Math.round(neuronsTotal)} neurons`, }); - return { metrics, r2Unclassified: r2.unclassified }; + // The average above stays for card compatibility; the per-day alert + // (#2287) is computed from the grouped query so a one-day burn is + // not diluted by the cycle length. + const aiNeurons = aiNeuronsDayAlerts(account?.aiInferenceAdaptiveGroupsByDay, aiThreshold); + + return { metrics, r2Unclassified: r2.unclassified, aiNeurons }; } /** Classify the billing probe pair (billing/profile + subscriptions). @@ -280,6 +372,11 @@ export function successDocument({ measuredAt, cycleStart, accountId, billing, pa billing, r2Buckets, ...(parsed.r2Unclassified?.length ? { r2UnclassifiedActions: parsed.r2Unclassified } : {}), + // #2287: the alerts array is present ONLY when a day is firing, so + // consumers can key on its presence; saturation of the grouped + // query is flagged on the document even when no day crossed. + ...(parsed.aiNeurons?.alerts?.length ? { alerts: parsed.aiNeurons.alerts } : {}), + ...(parsed.aiNeurons?.saturated ? { aiNeuronsByDaySaturated: true } : {}), metrics: parsed.metrics, }; } @@ -343,6 +440,7 @@ const GRAPHQL_QUERY = `query($a: string!, $s: Time!, $e: Time!) { r2OperationsAdaptiveGroups(limit: 1000, filter: { datetime_geq: $s, datetime_leq: $e }) { dimensions { actionType responseStatusCode } sum { requests } } r2StorageAdaptiveGroups(limit: 10000, filter: { datetime_geq: $s, datetime_leq: $e }) { dimensions { bucketName } max { payloadSize } } aiInferenceAdaptiveGroups(limit: 100, filter: { datetime_geq: $s, datetime_leq: $e }) { sum { totalNeurons } } + aiInferenceAdaptiveGroupsByDay: aiInferenceAdaptiveGroups(limit: 10000, filter: { datetime_geq: $s, datetime_leq: $e }) { dimensions { date modelId } sum { totalNeurons } } } } }`; @@ -435,7 +533,7 @@ export async function run({ token, accountId, now = new Date() } = {}) { } const account = gql.body?.data?.viewer?.accounts?.[0]; if (!account) throw new ExportError("unparseable", 6, "POST /graphql: no account node in data"); - const parsed = parseGraphqlUsage(account, { now, cycleStart: start }); + const parsed = parseGraphqlUsage(account, { now, cycleStart: start, aiThreshold: aiNeuronsDayAlertThreshold() }); return successDocument({ measuredAt: now.toISOString(), cycleStart: start, diff --git a/pm-stack/cloudflare-export/cloudflare-quota-export.test.mjs b/pm-stack/cloudflare-export/cloudflare-quota-export.test.mjs index 8c5816c1e2..5c55b3f085 100755 --- a/pm-stack/cloudflare-export/cloudflare-quota-export.test.mjs +++ b/pm-stack/cloudflare-export/cloudflare-quota-export.test.mjs @@ -3,6 +3,10 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { + aiNeuronsDayAlerts, + aiNeuronsDayAlertThreshold, + AI_NEURONS_DAY_ALERT_THRESHOLD_DEFAULT, + AI_NEURONS_DAY_GROUP_LIMIT, classifyBilling, classifyR2, cycleStartUtc, @@ -35,6 +39,14 @@ const ACCOUNT = { ], r2StorageAdaptiveGroups: [{ max: { payloadSize: 25139205306 } }], aiInferenceAdaptiveGroups: [{ sum: { totalNeurons: 4114515.31 } }], + // Grouped rows sum to the same 4,114,515.31 cycle total: the + // Oct 24–25 2026 burn shape from #2287 (Oct 24 alone ~2.99M on the + // deepseek model via the gateway). + aiInferenceAdaptiveGroupsByDay: [ + { dimensions: { date: "2026-10-24", modelId: "@cf/deepseek-ai/deepseek-v4-pro-0813" }, sum: { totalNeurons: 2990000 } }, + { dimensions: { date: "2026-10-24", modelId: "@cf/meta/llama-3.1-8b-instruct" }, sum: { totalNeurons: 100000 } }, + { dimensions: { date: "2026-10-25", modelId: "@cf/deepseek-ai/deepseek-v4-pro-0813" }, sum: { totalNeurons: 1024515.31 } }, + ], }; const NOW = new Date("2026-10-29T10:00:00Z"); const START = cycleStartUtc(NOW); @@ -291,6 +303,130 @@ test("run: GraphQL errors controls unchanged (#2608)", async () => { assert.equal(doc.metrics.length, 11); }); +test("aiNeuronsDayAlerts: an Oct 24-shaped day fires with top-model attribution (#2287)", () => { + const { alerts, saturated } = aiNeuronsDayAlerts(ACCOUNT.aiInferenceAdaptiveGroupsByDay, 50000); + assert.equal(saturated, false); + assert.equal(alerts.length, 2); // both burn days exceed 50k + assert.deepEqual(alerts[0], { + kind: "workers-ai-neurons-day", + date: "2026-10-24", + totalNeurons: 3090000, + threshold: 50000, + topModels: [ + { model: "@cf/deepseek-ai/deepseek-v4-pro-0813", neurons: 2990000 }, + { model: "@cf/meta/llama-3.1-8b-instruct", neurons: 100000 }, + ], + }); + assert.equal(alerts[1].date, "2026-10-25"); + assert.equal(alerts[1].totalNeurons, 1024515); // fractional day total rounds for display +}); + +test("aiNeuronsDayAlerts: days at or under the threshold stay silent (#2287)", () => { + const quiet = [ + { dimensions: { date: "2026-10-24", modelId: "@cf/meta/llama-3.1-8b-instruct" }, sum: { totalNeurons: 10000 } }, + { dimensions: { date: "2026-10-25", modelId: "@cf/meta/llama-3.1-8b-instruct" }, sum: { totalNeurons: 9999 } }, + ]; + assert.deepEqual(aiNeuronsDayAlerts(quiet, 50000), { alerts: [], saturated: false }); + // Exactly at the threshold does not fire (the rule is exceeds). + assert.deepEqual(aiNeuronsDayAlerts(quiet, 10000).alerts, []); + // No usage at all (empty groups) is a legitimate silent zero. + assert.deepEqual(aiNeuronsDayAlerts([], 50000), { alerts: [], saturated: false }); +}); + +test("aiNeuronsDayAlerts: top models are capped at 3, ordered by neurons (#2287)", () => { + const groups = ["m1", "m2", "m3", "m4"].map((modelId, i) => ({ + dimensions: { date: "2026-10-24", modelId }, + sum: { totalNeurons: (4 - i) * 100000 }, + })); + const { alerts } = aiNeuronsDayAlerts(groups, 50000); + assert.equal(alerts.length, 1); + assert.deepEqual(alerts[0].topModels.map((m) => m.model), ["m1", "m2", "m3"]); +}); + +test("aiNeuronsDayAlerts: a missing or drifted grouped field fails closed (#2287)", () => { + assert.throws(() => aiNeuronsDayAlerts(undefined, 50000), /aiInferenceAdaptiveGroupsByDay groups missing/); + assert.throws( + () => aiNeuronsDayAlerts([{ dimensions: { date: "24 Oct", modelId: "m" }, sum: { totalNeurons: 1 } }], 50000), + /dimensions\.date/, + ); + assert.throws( + () => aiNeuronsDayAlerts([{ dimensions: { date: "2026-10-24" }, sum: { totalNeurons: 1 } }], 50000), + /dimensions\.modelId/, + ); + const missing = structuredClone(ACCOUNT); + delete missing.aiInferenceAdaptiveGroupsByDay; + assert.throws(() => parseGraphqlUsage(missing, { now: NOW, cycleStart: START }), /aiInferenceAdaptiveGroupsByDay/); +}); + +test("aiNeuronsDayAlerts: saturation is flagged, never silently truncated (#2287)", () => { + const groups = Array.from({ length: AI_NEURONS_DAY_GROUP_LIMIT }, (_, i) => ({ + dimensions: { date: "2026-10-24", modelId: `m${i}` }, + sum: { totalNeurons: 100 }, + })); + const { alerts, saturated } = aiNeuronsDayAlerts(groups, 50000); + assert.equal(saturated, true); + assert.equal(alerts.length, 1); + assert.equal(alerts[0].lowerBound, true); + // The document carries the saturation flag even when nothing fires. + const parsed = parseGraphqlUsage( + { ...structuredClone(ACCOUNT), aiInferenceAdaptiveGroupsByDay: groups }, + { now: NOW, cycleStart: START, aiThreshold: Number.MAX_SAFE_INTEGER }, + ); + const doc = successDocument({ + measuredAt: NOW.toISOString(), + cycleStart: START, + accountId: "acct", + billing: { status: "invoice-only" }, + parsed, + r2Buckets: [], + }); + assert.equal(doc.aiNeuronsByDaySaturated, true); + assert.equal("alerts" in doc, false); +}); + +test("aiNeuronsDayAlertThreshold: env override with honest fallback (#2287)", () => { + assert.equal(AI_NEURONS_DAY_ALERT_THRESHOLD_DEFAULT, 50000); + assert.equal(aiNeuronsDayAlertThreshold({}), 50000); + assert.equal(aiNeuronsDayAlertThreshold({ CLOUDFLARE_AI_NEURONS_DAY_ALERT_THRESHOLD: "12345" }), 12345); + assert.equal(aiNeuronsDayAlertThreshold({ CLOUDFLARE_AI_NEURONS_DAY_ALERT_THRESHOLD: "" }), 50000); + assert.equal(aiNeuronsDayAlertThreshold({ CLOUDFLARE_AI_NEURONS_DAY_ALERT_THRESHOLD: "abc" }), 50000); + assert.equal(aiNeuronsDayAlertThreshold({ CLOUDFLARE_AI_NEURONS_DAY_ALERT_THRESHOLD: "-5" }), 50000); + // A custom threshold actually gates the alert through parseGraphqlUsage. + const parsed = parseGraphqlUsage(ACCOUNT, { now: NOW, cycleStart: START, aiThreshold: 4000000 }); + assert.deepEqual(parsed.aiNeurons.alerts, []); +}); + +test("documents: alerts array present only when a day is firing (#2287)", () => { + const billing = classifyBilling([ + { endpoint: "a", status: 403 }, + { endpoint: "b", status: 403 }, + ]); + const firing = successDocument({ + measuredAt: NOW.toISOString(), + cycleStart: START, + accountId: "acct", + billing, + parsed: parseGraphqlUsage(ACCOUNT, { now: NOW, cycleStart: START }), + r2Buckets: [], + }); + assert.equal(firing.alerts.length, 2); + assert.equal(firing.alerts[0].kind, "workers-ai-neurons-day"); + + const quietAccount = structuredClone(ACCOUNT); + quietAccount.aiInferenceAdaptiveGroupsByDay = [ + { dimensions: { date: "2026-10-24", modelId: "@cf/meta/llama-3.1-8b-instruct" }, sum: { totalNeurons: 5000 } }, + ]; + const quiet = successDocument({ + measuredAt: NOW.toISOString(), + cycleStart: START, + accountId: "acct", + billing, + parsed: parseGraphqlUsage(quietAccount, { now: NOW, cycleStart: START }), + r2Buckets: [], + }); + assert.equal("alerts" in quiet, false); +}); + test("measurement strings use plain decimals; request counts remain integers (#2791)", () => { const invalid = ["", " ", " 12 ", "0x10", "1e2", "1.5"]; for (const value of invalid) {