diff --git a/pm-stack/aggregator/README.md b/pm-stack/aggregator/README.md index 3738b05dfc..1069cdebf7 100644 --- a/pm-stack/aggregator/README.md +++ b/pm-stack/aggregator/README.md @@ -348,6 +348,13 @@ alerts-intake-token`, resolved by name at runtime `notification_sends` row per attempt. An unacked critical older than `ALERT_ACK_WINDOW_MIN` (default 15) escalates with exactly one more push (`escalated_at`). Warnings never push in v1. +- **Measurement**: `/notifications` (#3319) is the read-only weekly + sent-vs-acted-on roll-up over `notification_sends`: per class and + rolling week, only `outcome = sent` rows count as sends, and a send + counts as acted-on when its `acted_on_at` (stamped by Ack) falls + within 24 hours. A class under 10% acted-on over the rolling + four-week window renders as a default-off *proposal* — display + only; the page never changes a preference or a default. - **Ack surface**: `/alerts` lists open incidents with Ack/Close. Ack is exactly-once: only the open→acked transition writes an event (and stamps the sends' `acted_on_at`); a repeat ack returns diff --git a/pm-stack/aggregator/src/alerts.ts b/pm-stack/aggregator/src/alerts.ts index 00c741b81c..daf66ce175 100644 --- a/pm-stack/aggregator/src/alerts.ts +++ b/pm-stack/aggregator/src/alerts.ts @@ -70,6 +70,21 @@ export interface PushSubscriptionRow { gone_count: number; } +/** One alerts.notification_sends ledger row (#3319): one per send + * attempt, written by logSend; acted_on_at is stamped by the + * exactly-once Ack transition. The insert names no timestamp column, + * so the send time is the row's defaulted created_at; sent_at is + * read first when a row carries one. */ +export interface NotificationSendRow { + class: string; + object_ref: string; + incident_id: string | null; + outcome: string; + sent_at?: string | null; + created_at?: string | null; + acted_on_at: string | null; +} + export interface QuietPrefs { start: string; end: string; @@ -528,6 +543,13 @@ export class AlertsStore { }, ${sqlStr(entry.outcome)})`, ); } + + /** Every send-ledger row (#3319 roll-up input). The ledger is one + * row per attempt, so a full read stays small; the rolling window + * is applied by the pure roll-up in src/notifications.ts. */ + async listSends(): Promise { + return this.db.query(`select * from alerts.notification_sends`); + } } /** The test alert (#3676 follow-up, Drew 2026-11-01): the /alerts diff --git a/pm-stack/aggregator/src/notifications.ts b/pm-stack/aggregator/src/notifications.ts new file mode 100644 index 0000000000..90eb44815c --- /dev/null +++ b/pm-stack/aggregator/src/notifications.ts @@ -0,0 +1,130 @@ +// Notification measurement (#3319, slice (e) of the #1254 design): +// the weekly sent-vs-acted-on roll-up over the alert throat's send +// ledger (alerts.notification_sends, written by AlertsStore.logSend). +// +// The roll-up is a pure derivation over ledger rows so it can be +// pinned by fixture tests without a database; the /notifications page +// and its /api twin render exactly this shape. +// +// Counting rules (the page states them in plain words too): +// - Only outcome = "sent" rows are sends. suppressed-quiet, +// suppressed-dedupe, gone, and error rows are attempts that never +// reached a device; they never enter the denominator, and a send +// is never inferred from delivered/escalated incident events. +// - A send counts as acted-on when its acted_on_at (stamped by the +// exactly-once Ack transition in AlertsStore.ackIncident) falls +// within 24 hours of the send. Ack is the durable v1 acted-on +// signal; acting through any other surface is not attributable +// to a specific send (see the page's attribution note). +// - Weeks are rolling 7-day buckets ending at `now`, four of them: +// the window is the last 28 days, not calendar weeks. +// - A class whose rolling-window acted-on ratio is under 10% (with +// at least one send) is flagged as a default-off PROPOSAL. The +// flag is display-only: nothing here mutates a preference or a +// default; default changes are Drew's call (design Q1). +import type { NotificationSendRow } from "./alerts.ts"; + +export const ACTED_WINDOW_MS = 24 * 60 * 60 * 1000; +export const ROLLING_WEEKS = 4; +export const WEEK_MS = 7 * 24 * 60 * 60 * 1000; +export const PROPOSAL_THRESHOLD = 0.1; + +/** The send's timestamp: the ledger's insert-time column. Rows the + * store writes carry no explicit timestamp, so the row's defaulted + * created_at is the send time; sent_at wins when a row carries one. */ +export function sendTimestamp(row: NotificationSendRow): string | null { + return row.sent_at ?? row.created_at ?? null; +} + +export interface NotificationWeekRollup { + /** Inclusive bucket start (ISO); the bucket is [start, start + 7d). */ + start: string; + sent: number; + acted: number; + /** acted / sent, or null when nothing was sent that week. */ + ratio: number | null; +} + +export interface NotificationClassRollup { + class: string; + /** Oldest week first; always ROLLING_WEEKS entries. */ + weeks: NotificationWeekRollup[]; + sent: number; + acted: number; + /** acted / sent over the whole rolling window; null when sent = 0. */ + ratio: number | null; + /** Display-only default-off proposal (ratio under the threshold). */ + proposal: boolean; +} + +export interface NotificationRollup { + /** The instant the rolling window ends (ISO). */ + asOf: string; + /** Inclusive window start (ISO): asOf - ROLLING_WEEKS weeks. */ + windowStart: string; + classes: NotificationClassRollup[]; + /** Ledger rows skipped because they carry no usable send timestamp. */ + undated: number; +} + +export function rollupNotificationSends( + rows: NotificationSendRow[], + now: Date, + weeks: number = ROLLING_WEEKS, +): NotificationRollup { + const asOfMs = now.getTime(); + const windowStartMs = asOfMs - weeks * WEEK_MS; + const byClass = new Map(); + let undated = 0; + for (const row of rows) { + if (row.outcome !== "sent") continue; + const tsRaw = sendTimestamp(row); + const ts = tsRaw ? Date.parse(tsRaw) : Number.NaN; + if (!Number.isFinite(ts)) { + undated += 1; + continue; + } + if (ts < windowStartMs || ts > asOfMs) continue; + // Bucket 0 is the oldest week in the window. + const bucket = Math.min(weeks - 1, Math.floor((ts - windowStartMs) / WEEK_MS)); + let entry = byClass.get(row.class); + if (!entry) { + entry = { sent: new Array(weeks).fill(0), acted: new Array(weeks).fill(0) }; + byClass.set(row.class, entry); + } + entry.sent[bucket] += 1; + if (row.acted_on_at) { + const actedMs = Date.parse(row.acted_on_at); + if (Number.isFinite(actedMs) && actedMs >= ts && actedMs - ts <= ACTED_WINDOW_MS) { + entry.acted[bucket] += 1; + } + } + } + const classes: NotificationClassRollup[] = [...byClass.entries()] + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([cls, entry]) => { + const weekRollups: NotificationWeekRollup[] = entry.sent.map((sent, i) => ({ + start: new Date(windowStartMs + i * WEEK_MS).toISOString(), + sent, + acted: entry.acted[i], + ratio: sent > 0 ? entry.acted[i] / sent : null, + })); + const sent = entry.sent.reduce((a, b) => a + b, 0); + const acted = entry.acted.reduce((a, b) => a + b, 0); + const ratio = sent > 0 ? acted / sent : null; + return { + class: cls, + weeks: weekRollups, + sent, + acted, + ratio, + proposal: ratio !== null && ratio < PROPOSAL_THRESHOLD, + }; + }); + return { + asOf: now.toISOString(), + windowStart: new Date(windowStartMs).toISOString(), + classes, + undated, + }; +} diff --git a/pm-stack/aggregator/src/pages.ts b/pm-stack/aggregator/src/pages.ts index 68c8265dfc..af5bd6acb1 100644 --- a/pm-stack/aggregator/src/pages.ts +++ b/pm-stack/aggregator/src/pages.ts @@ -216,6 +216,16 @@ export const PAGES: PageDef[] = [ // post-#1497 dropdown placement recorded in curation-1497.test). nav: "primary", }, + { + id: "notifications", + title: "Notifications", + route: "/notifications", + api: "/api/notifications.json", + blurb: + "Notification measurement (#3319): the weekly sent-vs-acted-on roll-up over the alert throat's send ledger, with display-only default-off proposals under 10%.", + group: "ops", + nav: "dropdown", + }, { id: "pages", title: "All pages", diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index 91b45a2f7b..0edf220823 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -53,6 +53,7 @@ import { import { summarizeDns } from "./dns.ts"; import type { NeedsDrewCensus } from "./needs-drew.ts"; import type { Incident, IncidentEvent, PushSubscriptionRow } from "./alerts.ts"; +import type { NotificationRollup } from "./notifications.ts"; import { ageMsText, feedAgeText } from "./feed.ts"; import type { QueueView, QueueRow } from "./queue-view.ts"; import type { HealthView, PageHealth } from "./health.ts"; @@ -7053,3 +7054,59 @@ document.getElementById("push-test").addEventListener("click", async () => { `; return layout("Alerts", body, provenance, "/alerts", script); } + +// --- Notifications page (#3319, notification measurement) ------------------- + +export interface NotificationsPageView { + available: boolean; + rollup: NotificationRollup | null; +} + +function pct(ratio: number | null): string { + return ratio === null ? "—" : `${Math.round(ratio * 100)}%`; +} + +export function renderNotifications(view: NotificationsPageView, provenance: Provenance): string { + if (!view.available || !view.rollup) { + return layout( + "Notifications", + `

Notifications

The notification send ledger (Supabase alerts.notification_sends) is unreachable from this process right now — the roll-up is paused with it. The rest of the dashboard is unaffected.

`, + provenance, + "/notifications", + ); + } + const rollup = view.rollup; + const proposals = rollup.classes.filter((c) => c.proposal); + const rows = rollup.classes + .map((c) => { + const cells = c.weeks + .map((w) => `${w.sent} sent · ${w.acted} acted (${pct(w.ratio)})`) + .join(""); + return `${esc(c.class)}${cells}${c.sent} sent · ${c.acted} acted (${pct(c.ratio)})`; + }) + .join(""); + const weekHeads = rollup.classes[0] + ? rollup.classes[0].weeks.map((w) => `week of ${esc(fmtDate(w.start))}`).join("") + : ""; + const proposalHtml = proposals.length + ? `

Default-off proposals

${proposals + .map( + (c) => + `
Proposal: default class ${esc(c.class)} off — acted-on ratio ${pct(c.ratio)} over the rolling window (${c.acted} of ${c.sent} sends acted on within 24h), under the 10% threshold.
Proposal only — this page never changes a preference or a default. Turning a class off by default is Drew's call, made on the Alerts page's subscription preferences.
`, + ) + .join("")}` + : `

Default-off proposals

No class is under the 10% acted-on threshold over the rolling window.

`; + const body = `

Notifications

+

Weekly sent-vs-acted-on roll-up over the alert throat's send ledger (alerts.notification_sends), rolling four weeks ending ${esc(fmtDate(rollup.asOf))}. Read-only: this page measures; it never changes a notification preference or default. Machine-first: /api/notifications.json.

+

How acted-on is counted (attribution)

+

A send counts as acted-on when the incident's Ack lands within 24 hours of the send: Ack is the exactly-once transition that stamps the send's acted_on_at, so it is the durable acted-on signal. Only ledger rows with outcome sent count as sends — suppressed (quiet hours / dedupe), gone, and error attempts never reached a device and never enter the denominator, and no send is inferred from delivered/escalated incident events. What this cannot attribute: reading a notification without acking, acting on the incident through another surface (GitHub, chat, a later dashboard visit that does not ack), and sends to subscriptions that were later removed — those count as sent-but-not-acted even when a human did see them. Test sends (class test) are real ledger rows and are reported as their own class.

+${rollup.undated ? `

${rollup.undated} ledger row(s) carried no usable send timestamp and were excluded from the roll-up.

` : ""} +

Per class, per week

+${ + rollup.classes.length + ? `
${weekHeads}${rows}
Sent vs acted-on by class and rolling week
classrolling 4 weeks
` + : `

No sends in the rolling four-week window.

` +} +${proposalHtml}`; + return layout("Notifications", body, provenance, "/notifications"); +} diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 5f8c651610..675b7fe33a 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -111,7 +111,8 @@ import { import { recordSwProbe, swProbeSummary, VAPID_PUBLIC_KEY } from "./push.ts"; import { resolveBwsSecret } from "./secrets.ts"; import { SW_SOURCE } from "./sw-source.ts"; -import { renderAlerts, esc } from "./render.ts"; +import { renderAlerts, renderNotifications, esc } from "./render.ts"; +import { rollupNotificationSends } from "./notifications.ts"; import { readJsonBody } from "./request-body.ts"; import { parseRegistryQuery, queryRegistry } from "./registry-view.ts"; import { searchWork } from "./search-view.ts"; @@ -1784,6 +1785,27 @@ async function handler(req: Request): Promise { : json({ error: "alerts store unavailable" }, 503); } } + if (path === "/notifications" || path === "/api/notifications.json") { + // #3319: the weekly sent-vs-acted roll-up over the send ledger. + // Same reachability as every dashboard page (the tailnet origin); + // the only alerts write surface stays the bearer-gated intake. + const store = await getAlertsStore(); + if (!store) { + return path === "/notifications" + ? html(renderNotifications({ available: false, rollup: null }, prov())) + : json({ error: "alerts store unavailable" }, 503); + } + try { + const sends = await store.listSends(); + const rollup = rollupNotificationSends(sends, new Date()); + if (path === "/api/notifications.json") return json(rollup); + return html(renderNotifications({ available: true, rollup }, prov())); + } catch { + return path === "/notifications" + ? html(renderNotifications({ available: false, rollup: null }, prov())) + : json({ error: "alerts store unavailable" }, 503); + } + } if (path === "/api/health") { // #1267: prime first — health's answer must not depend on // request order. `sections` carries the structured diagnosis diff --git a/pm-stack/aggregator/test/curation-1497.test.ts b/pm-stack/aggregator/test/curation-1497.test.ts index 4b679f03a4..e92aa90da1 100644 --- a/pm-stack/aggregator/test/curation-1497.test.ts +++ b/pm-stack/aggregator/test/curation-1497.test.ts @@ -53,6 +53,10 @@ const DECISIONS: Record = { // Post-#1497 addition (#1282, 2026-11-03): the source-conflict inbox // enters at dropdown tier — a triage queue, not a primary surface. conflicts: "dropdown", + // Post-#1497 addition (#3319, 2026-11-03): the notifications + // measurement page enters at dropdown tier — no curation ruling + // promotes it, and new pages do not take primary slots without one. + notifications: "dropdown", }; describe("the #1497 decision table is applied to the manifest", () => { diff --git a/pm-stack/aggregator/test/notifications.test.ts b/pm-stack/aggregator/test/notifications.test.ts new file mode 100644 index 0000000000..366eb1b58d --- /dev/null +++ b/pm-stack/aggregator/test/notifications.test.ts @@ -0,0 +1,179 @@ +// Notification measurement (#3319): the sent-vs-acted-on roll-up over +// the notification_sends ledger. The roll-up is pure, so the counting +// rules are pinned here with a hand-checked fixture; the store read +// is pinned against a fake Supabase client. +import { describe, expect, test } from "bun:test"; +import { AlertsStore, type NotificationSendRow } from "../src/alerts.ts"; +import { rollupNotificationSends, sendTimestamp } from "../src/notifications.ts"; +import { renderNotifications } from "../src/render.ts"; +import type { Provenance } from "../src/model.ts"; +import type { SupabaseClient } from "../src/supabase.ts"; + +const NOW = new Date("2026-11-03T12:00:00Z"); +// Rolling window: [2026-10-06T12:00Z, 2026-11-03T12:00Z], buckets of +// 7 days starting Oct 6, Oct 13, Oct 20, Oct 27. + +const PROV: Provenance = { + board: "x", + roadmap: "x", + items: "x", + comments: "x", + quota: "x", + usage: "x", + attention: "x", + orchestration: "x", + dns: "x", + registry: "x", + aa: "x", +}; + +function send(partial: Partial): NotificationSendRow { + return { + class: "incident", + object_ref: "incident:x", + incident_id: "inc-1", + outcome: "sent", + created_at: "2026-11-01T00:00:00Z", + acted_on_at: null, + ...partial, + }; +} + +describe("rollupNotificationSends", () => { + test("hand-checked fixture week: per-class, per-week sent/acted/ratio", () => { + const rows: NotificationSendRow[] = []; + // Week of Oct 27 (newest bucket): 10 incident sends, 3 acked in 24h. + for (let i = 0; i < 10; i++) { + rows.push( + send({ + created_at: "2026-10-28T08:00:00Z", + acted_on_at: i < 3 ? "2026-10-28T20:00:00Z" : null, + }), + ); + } + // Week of Oct 6 (oldest bucket): 2 incident sends, 1 acked. + rows.push(send({ created_at: "2026-10-07T08:00:00Z", acted_on_at: "2026-10-07T09:00:00Z" })); + rows.push(send({ created_at: "2026-10-07T10:00:00Z" })); + const rollup = rollupNotificationSends(rows, NOW); + expect(rollup.windowStart).toBe("2026-10-06T12:00:00.000Z"); + expect(rollup.classes).toHaveLength(1); + const incident = rollup.classes[0]; + expect(incident.class).toBe("incident"); + expect(incident.weeks.map((w) => w.sent)).toEqual([2, 0, 0, 10]); + expect(incident.weeks.map((w) => w.acted)).toEqual([1, 0, 0, 3]); + expect(incident.weeks[0].start).toBe("2026-10-06T12:00:00.000Z"); + expect(incident.weeks[3].start).toBe("2026-10-27T12:00:00.000Z"); + expect(incident.sent).toBe(12); + expect(incident.acted).toBe(4); + expect(incident.ratio).toBeCloseTo(4 / 12); + expect(incident.proposal).toBe(false); + }); + + test("only outcome=sent counts; suppressed/gone/error never enter the denominator", () => { + const rows = [ + send({ outcome: "suppressed-quiet", created_at: "2026-11-01T00:00:00Z" }), + send({ outcome: "suppressed-dedupe", created_at: "2026-11-01T00:00:00Z" }), + send({ outcome: "gone", created_at: "2026-11-01T00:00:00Z" }), + send({ outcome: "error", created_at: "2026-11-01T00:00:00Z" }), + send({ outcome: "sent", created_at: "2026-11-01T00:00:00Z", acted_on_at: "2026-11-01T01:00:00Z" }), + ]; + const rollup = rollupNotificationSends(rows, NOW); + expect(rollup.classes).toHaveLength(1); + expect(rollup.classes[0].sent).toBe(1); + expect(rollup.classes[0].acted).toBe(1); + expect(rollup.classes[0].ratio).toBe(1); + }); + + test("the 24-hour acted window is inclusive at exactly 24h and closed after it", () => { + const at = "2026-11-01T00:00:00Z"; + const rows = [ + send({ created_at: at, acted_on_at: "2026-11-02T00:00:00Z" }), // exactly 24h — counts + send({ created_at: at, acted_on_at: "2026-11-02T00:00:01Z" }), // 24h + 1s — does not + send({ created_at: at, acted_on_at: "2026-10-31T23:59:59Z" }), // before the send — does not + send({ created_at: at, acted_on_at: null }), // never acked — does not + ]; + const rollup = rollupNotificationSends(rows, NOW); + expect(rollup.classes[0].sent).toBe(4); + expect(rollup.classes[0].acted).toBe(1); + }); + + test("the rolling four-week window excludes older sends and future sends", () => { + const rows = [ + send({ created_at: "2026-10-06T11:59:59Z", acted_on_at: "2026-10-06T12:30:00Z" }), // just before the window + send({ created_at: "2026-10-06T12:00:00Z" }), // window start — included, oldest bucket + send({ created_at: "2026-11-03T12:00:01Z" }), // after `now` — excluded + ]; + const rollup = rollupNotificationSends(rows, NOW); + expect(rollup.classes[0].sent).toBe(1); + expect(rollup.classes[0].weeks[0].sent).toBe(1); + }); + + test("classes group separately; an undated sent row is counted as excluded, not as a send", () => { + const rows = [ + send({ class: "test", object_ref: "test:push", incident_id: null, created_at: "2026-11-02T00:00:00Z" }), + send({ class: "incident", created_at: null, sent_at: null }), + ]; + const rollup = rollupNotificationSends(rows, NOW); + expect(rollup.classes.map((c) => c.class)).toEqual(["test"]); + expect(rollup.undated).toBe(1); + }); + + test("proposal: under 10% over the window proposes; exactly 10% and zero sends do not", () => { + const rows: NotificationSendRow[] = []; + for (let i = 0; i < 20; i++) { + rows.push(send({ class: "digest", created_at: "2026-11-01T00:00:00Z", acted_on_at: i === 0 ? "2026-11-01T01:00:00Z" : null })); + } + for (let i = 0; i < 10; i++) { + rows.push(send({ class: "edge", created_at: "2026-11-01T00:00:00Z", acted_on_at: i === 0 ? "2026-11-01T01:00:00Z" : null })); + } + const rollup = rollupNotificationSends(rows, NOW); + const digest = rollup.classes.find((c) => c.class === "digest")!; + const edge = rollup.classes.find((c) => c.class === "edge")!; + expect(digest.ratio).toBeCloseTo(0.05); + expect(digest.proposal).toBe(true); + expect(edge.ratio).toBeCloseTo(0.1); + expect(edge.proposal).toBe(false); + }); + + test("sent_at wins over created_at when a row carries both", () => { + const row = send({ sent_at: "2026-10-07T00:00:00Z", created_at: "2026-11-02T00:00:00Z" }); + expect(sendTimestamp(row)).toBe("2026-10-07T00:00:00Z"); + const rollup = rollupNotificationSends([row], NOW); + expect(rollup.classes[0].weeks[0].sent).toBe(1); + }); +}); + +describe("AlertsStore.listSends", () => { + test("reads the notification_sends ledger", async () => { + const rows = [send({})]; + const db: SupabaseClient = { + ref: "test", + async query(sql: string): Promise { + expect(sql).toContain("alerts.notification_sends"); + return rows as T[]; + }, + }; + const store = new AlertsStore(db); + expect(await store.listSends()).toEqual(rows); + }); +}); + +describe("renderNotifications", () => { + test("renders the roll-up, the attribution note, and a display-only proposal", () => { + const rows: NotificationSendRow[] = []; + for (let i = 0; i < 20; i++) { + rows.push(send({ class: "digest", created_at: "2026-11-01T00:00:00Z", acted_on_at: i === 0 ? "2026-11-01T01:00:00Z" : null })); + } + const html = renderNotifications({ available: true, rollup: rollupNotificationSends(rows, NOW) }, PROV); + expect(html).toContain("digest"); + expect(html).toContain("Proposal: default class"); + expect(html).toContain("never changes a preference or a default"); + expect(html).toContain("acted_on_at"); + expect(html).toContain("/api/notifications.json"); + }); + + test("unavailable renders the paused message, not an empty roll-up", () => { + const html = renderNotifications({ available: false, rollup: null }, PROV); + expect(html).toContain("unreachable"); + }); +});