diff --git a/pm-stack/aggregator/src/alerts.ts b/pm-stack/aggregator/src/alerts.ts index 4caf9e86b..1dc3248a5 100644 --- a/pm-stack/aggregator/src/alerts.ts +++ b/pm-stack/aggregator/src/alerts.ts @@ -86,9 +86,10 @@ export interface PushSubscriptionRow { /** 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. */ + * exactly-once Ack transition. #14419: logSend stamps sent_at + * explicitly in ISO-8601 UTC; legacy rows written before that carry + * only a defaulted created_at, which the reader normalizes (see + * normalizeSendTimestamp / repairLegacySendRow in notifications.ts). */ export interface NotificationSendRow { class: string; object_ref: string; @@ -667,12 +668,19 @@ export class AlertsStore { objectRef: string; incidentId?: string; outcome: "sent" | "suppressed-quiet" | "suppressed-dedupe" | "gone" | "error"; + /** #14419: injectable for tests; defaults to now. */ + sentAt?: string; }): Promise { + // #14419: stamp sent_at explicitly in ISO-8601 UTC on every row. + // Relying on the created_at column default left live rows in a + // format the reader could not parse, so every send was excluded + // from the measurement roll-up. + const sentAt = entry.sentAt ?? new Date().toISOString(); await this.db.query( - `insert into alerts.notification_sends (class, object_ref, incident_id, outcome) + `insert into alerts.notification_sends (class, object_ref, incident_id, outcome, sent_at) values (${sqlStr(entry.class)}, ${sqlStr(entry.objectRef)}, ${ entry.incidentId ? sqlStr(entry.incidentId) : "null" - }, ${sqlStr(entry.outcome)})`, + }, ${sqlStr(entry.outcome)}, ${sqlStr(sentAt)})`, ); } diff --git a/pm-stack/aggregator/src/notifications.ts b/pm-stack/aggregator/src/notifications.ts index c92d1bdeb..cd5cdb9fc 100644 --- a/pm-stack/aggregator/src/notifications.ts +++ b/pm-stack/aggregator/src/notifications.ts @@ -722,11 +722,49 @@ 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. */ +/** #14419: normalize a ledger timestamp to ISO-8601 UTC, or null. + * Legacy rows carry the column-default format the live stores emit — + * `YYYY-MM-DD HH:MM:SS[.fff]` (space separator, no zone) from + * SQLite/Turso defaults, and Postgres-style `+00` offsets — which + * Date.parse does not reliably parse. Those are UTC by construction + * (the defaults are UTC), so normalize them explicitly instead of + * excluding the rows. Oracle: Date.parse on the normalized string. */ +export function normalizeSendTimestamp(raw: string | null | undefined): string | null { + if (!raw) return null; + const value = raw.trim(); + if (!value) return null; + const direct = Date.parse(value); + if (Number.isFinite(direct) && (value.includes("T") || value.endsWith("Z") || /[+-]\d{2}:?\d{2}$/.test(value))) { + return new Date(direct).toISOString(); + } + const m = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2}(?:\.\d+)?)\s*(Z|[+-]\d{2}(?::?\d{2})?)?$/.exec(value); + if (m) { + const zone = m[3] ? (m[3] === "Z" ? "Z" : m[3]) : "Z"; + const parsed = Date.parse(`${m[1]}T${m[2]}${zone}`); + return Number.isFinite(parsed) ? new Date(parsed).toISOString() : null; + } + const dateOnly = /^\d{4}-\d{2}-\d{2}$/.exec(value); + if (dateOnly) { + const parsed = Date.parse(`${value}T00:00:00Z`); + return Number.isFinite(parsed) ? new Date(parsed).toISOString() : null; + } + return Number.isFinite(direct) ? new Date(direct).toISOString() : null; +} + +/** The send's timestamp (#14419): sent_at (stamped explicitly by + * logSend in ISO-8601 UTC) wins; a legacy row's defaulted created_at + * is repaired by normalization when sent_at is absent/unusable. */ export function sendTimestamp(row: NotificationSendRow): string | null { - return row.sent_at ?? row.created_at ?? null; + return normalizeSendTimestamp(row.sent_at) ?? normalizeSendTimestamp(row.created_at); +} + +/** #14419: backfill sent_at for a recoverable legacy row (its + * created_at normalizes); unrecoverable rows are returned unchanged + * and are counted as undated/excluded by the roll-up. */ +export function repairLegacySendRow(row: NotificationSendRow): NotificationSendRow { + if (normalizeSendTimestamp(row.sent_at)) return row; + const repaired = normalizeSendTimestamp(row.created_at); + return repaired ? { ...row, sent_at: repaired } : row; } export interface NotificationWeekRollup { @@ -758,6 +796,12 @@ export interface NotificationRollup { classes: NotificationClassRollup[]; /** Ledger rows skipped because they carry no usable send timestamp. */ undated: number; + /** Total outcome=sent ledger rows considered (dated + undated). */ + total: number; + /** #14419 alarm: true when every sent row was excluded as undated + * (excluded == total and total > 0) — the measurement page would + * otherwise silently report no sends at all. */ + alarm: boolean; } export function rollupNotificationSends( @@ -769,8 +813,10 @@ export function rollupNotificationSends( const windowStartMs = asOfMs - weeks * WEEK_MS; const byClass = new Map(); let undated = 0; + let total = 0; for (const row of rows) { if (row.outcome !== "sent") continue; + total += 1; const tsRaw = sendTimestamp(row); const ts = tsRaw ? Date.parse(tsRaw) : Number.NaN; if (!Number.isFinite(ts)) { @@ -819,5 +865,7 @@ export function rollupNotificationSends( windowStart: new Date(windowStartMs).toISOString(), classes, undated, + total, + alarm: total > 0 && undated === total, }; } diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index 1bfd89aa0..faf9e0208 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -8625,7 +8625,7 @@ export function renderNotifications(view: NotificationsPageView, provenance: Pro

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.

` : ""} +${rollup.alarm ? `

ALARM: all ${rollup.total} send ledger row(s) were excluded for missing/unusable timestamps — the roll-up below reports no sends because the ledger timestamps are unreadable, not because nothing was sent (#14419).

` : 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 diff --git a/pm-stack/aggregator/test/notifications.test.ts b/pm-stack/aggregator/test/notifications.test.ts index ba1f247ab..7171849d5 100644 --- a/pm-stack/aggregator/test/notifications.test.ts +++ b/pm-stack/aggregator/test/notifications.test.ts @@ -8,6 +8,8 @@ import { deriveSoleDoorPoolIds, nextNotificationDigestAt, NOTIFICATION_CLASS_DEFAULTS, + normalizeSendTimestamp, + repairLegacySendRow, rollupNotificationSends, sendTimestamp, type NotificationCandidate, @@ -408,6 +410,73 @@ describe("rollupNotificationSends", () => { }); }); +describe("#14419 send ledger sent_at stamping and legacy repair", () => { + test("logSend stamps sent_at explicitly in ISO-8601 UTC and sendTimestamp reads it back", async () => { + const queries: string[] = []; + const db: SqlClient = { + ref: "test", + async query(sql: string): Promise { + queries.push(sql); + return [] as T[]; + }, + }; + const store = new AlertsStore(db); + await store.logSend({ + class: "incident", + objectRef: "incident:x", + outcome: "sent", + sentAt: "2026-11-01T08:00:00.000Z", + }); + expect(queries).toHaveLength(1); + expect(queries[0]).toContain("sent_at"); + expect(queries[0]).toContain("'2026-11-01T08:00:00.000Z'"); + // Read back: a row carrying exactly what the writer stamped. + const row = send({ sent_at: "2026-11-01T08:00:00.000Z", created_at: null }); + expect(sendTimestamp(row)).toBe("2026-11-01T08:00:00.000Z"); + const rollup = rollupNotificationSends([row], NOW); + expect(rollup.classes[0].sent).toBe(1); + expect(rollup.undated).toBe(0); + expect(rollup.alarm).toBe(false); + }); + + test("logSend's default stamp is ISO-8601 UTC", async () => { + let sql = ""; + const db: SqlClient = { + ref: "test", + async query(q: string): Promise { + sql = q; + return [] as T[]; + }, + }; + await new AlertsStore(db).logSend({ class: "test", objectRef: "test:push", outcome: "sent" }); + const stamped = /'(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)'/.exec(sql); + expect(stamped).not.toBeNull(); + }); + + test("legacy space-format created_at is normalized and repairLegacySendRow backfills sent_at", () => { + expect(normalizeSendTimestamp("2026-11-01 08:00:00")).toBe("2026-11-01T08:00:00.000Z"); + expect(normalizeSendTimestamp("2026-11-01 08:00:00.123")).toBe("2026-11-01T08:00:00.123Z"); + expect(normalizeSendTimestamp("not-a-date")).toBeNull(); + const legacy = send({ sent_at: null, created_at: "2026-11-01 08:00:00" }); + expect(sendTimestamp(legacy)).toBe("2026-11-01T08:00:00.000Z"); + expect(repairLegacySendRow(legacy).sent_at).toBe("2026-11-01T08:00:00.000Z"); + const rollup = rollupNotificationSends([legacy], NOW); + expect(rollup.classes[0].sent).toBe(1); + expect(rollup.undated).toBe(0); + }); + + test("an all-undated ledger triggers the alarm (excluded == total)", () => { + const rows = [send({ created_at: null, sent_at: null }), send({ created_at: "garbage", sent_at: null })]; + const rollup = rollupNotificationSends(rows, NOW); + expect(rollup.total).toBe(2); + expect(rollup.undated).toBe(2); + expect(rollup.alarm).toBe(true); + const mixed = rollupNotificationSends([...rows, send({})], NOW); + expect(mixed.alarm).toBe(false); + expect(rollupNotificationSends([], NOW).alarm).toBe(false); + }); +}); + describe("AlertsStore.listSends", () => { test("reads the notification_sends ledger", async () => { const rows = [send({})];