Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Fix notification delivery health reporting

rcourtman0b6f7ad49aee
diff --git a/docs/API.md b/docs/API.md
index c0cb443e25..a922b95ac9 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -537,6 +537,14 @@ Triggers a test alert to all configured channels.
- `GET /api/notifications/webhook-history` (admin)
- `GET /api/notifications/email-providers` (admin)
- `GET /api/notifications/health` (admin)
+ - Queue health is `degraded` whenever any retained `failed` or `dlq`
+ delivery exists, and `unavailable` when queue state cannot be read.
+ Recoverable failed attempts that returned to `pending` for retry do not
+ degrade health.
+ - `queue.attention_required` is the retained terminal-failure count.
+ `reason_codes` identifies failed and/or dead-letter state without exposing
+ notification content. Counts are retention-bounded: sent, failed, and
+ cancelled rows are retained for 7 days; dead-letter rows for 30 days.
### Audit Webhooks (Pro)
- `GET /api/admin/webhooks/audit` (admin, `settings:read`)
@@ -577,6 +585,8 @@ Common reporting error codes:
### Queue and Dead-Letter Tools
- `GET /api/notifications/queue/stats` (admin)
+ - Returns counts for all rows still retained by the queue. Status counts have
+ different retention windows and are not a delivery rate or lifetime total.
- `GET /api/notifications/dlq` (admin)
- `POST /api/notifications/dlq/retry` (admin)
- `POST /api/notifications/dlq/delete` (admin)
diff --git a/docs/PRIVACY.md b/docs/PRIVACY.md
index f45d369925..6f51285608 100644
--- a/docs/PRIVACY.md
+++ b/docs/PRIVACY.md
@@ -37,7 +37,7 @@ Every field is listed below with the reason it exists. Nothing else is included
| Field | Example | Purpose |
|-------|---------|---------|
-| Schema version | `2` | Identify the exact payload contract so old and new signals are not mixed silently |
+| Schema version | `3` | Identify the exact payload contract so old and new signals are not mixed silently |
| Sent at | `2026-07-23T08:30:00Z` | Date the individual heartbeat without sending a history of client activity |
| Install ID | `a1b2c3d4-...` | Distinguish active installations within one rotation window without tying telemetry to an account or person |
| Version | `6.0.0-rc.1` | Track the canonical release identity currently deployed |
@@ -91,9 +91,9 @@ Every field is listed below with the reason it exists. Nothing else is included
| Alerts fired 30d | `18` | Count locally retained alert-history entries in the current 30-day window without sending alert text, resource IDs, or timestamps |
| Alerts acknowledged 30d | `7` | Count acknowledgements in the current 30-day window without sending actors, reasons, alert IDs, or timestamps |
| Alerts resolved 30d | `12` | Count resolved alert records in the current 30-day window without sending resolution details, alert IDs, or resource IDs |
-| Notification attempts 7d | `14` | Count delivery attempts in the locally retained seven-day queue window without sending recipients, endpoints, titles, or message content |
+| Notification attempts 7d | `14` | Count delivery attempts, including retry attempts, in the locally retained seven-day queue window without sending recipients, endpoints, titles, or message content |
| Notification deliveries 7d | `11` | Count successfully delivered queue records in the local seven-day window without sending channel, recipient, endpoint, or content |
-| Notification failures 7d | `3` | Count failed delivery attempts in the local seven-day window without sending error text, endpoint, recipient, or message content |
+| Notification failures 7d (terminal in schema v3) | `3` | Count terminal failed or dead-lettered delivery outcomes in the local seven-day window without sending retry-attempt failures, error text, endpoint, recipient, or message content |
| Relay enabled | `true`/`false` | See whether remote-access features are being used |
| SSO enabled | `true`/`false` | See whether single-sign-on support is being used |
| Multi-tenant | `true`/`false` | See whether multi-tenant/runtime-org features are being used |
@@ -165,6 +165,13 @@ Every field is listed below with the reason it exists. Nothing else is included
| Pulse Intelligence approved action stuck executing 30d | `1` | Count approved governed actions abandoned in the executing state in the current 30-day telemetry window without sending action output, command text, resource IDs, or actors |
| Pulse Intelligence approved action last failure reason 30d | `plan_drift` | See one fixed machine reason code for the most recent approved-action failure in the current 30-day telemetry window without sending error text, action output, command text, resource IDs, or actors |
+Telemetry schema v3 corrects the meaning of `notification_failures_7d`: v2
+counted every unsuccessful queue attempt, including attempts that later
+succeeded on retry; v3 counts only terminal `failed` or dead-letter outcomes.
+The adoption report keeps those schema cohorts separate, so legacy retry noise
+is not compared with current terminal-delivery failures. This correction adds
+no notification content or identity fields.
+
#### Server-side handling and retention
- Telemetry pings are stored on the Pulse license server only for aggregate install/use analysis.
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index cd3c6b2ed9..89d1cab5df 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -119,11 +119,17 @@ first step before platform-local cleanup.
### Notifications
#### Emails not sending
+- Open **Alerts → Notifications** first. Pulse shows a delivery warning when
+ failed or dead-lettered notifications remain in the persistent queue; a
+ missing queue-health read is shown as unavailable rather than healthy.
- Check SMTP settings in **Alerts → Notifications**.
- Check logs: `docker logs pulse | grep email`.
- Ensure your SMTP provider allows the connection (e.g., Gmail App Passwords).
#### Webhooks failing
+- Check the delivery warning in **Alerts → Notifications** and use **Send test**
+ after correcting the destination. Recoverable retries do not trigger the
+ warning; retained terminal failures do.
- Verify the URL is reachable from the Pulse server.
- If targeting private IPs, allow them in **Settings → System → Network → Webhook Security**.
- Check Pulse logs for HTTP status codes and response bodies.
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 0e267cd46b..cfe9177ef2 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -2197,6 +2197,11 @@ likewise adjacent only: the webhook `signingSecret` payload field, its masked
list representation, and masked-echo preservation on update are
notifications/API-contract owned and grant no agent install, enrollment,
setup-token, or fleet command authority.
+Notification queue-health changes on that same shared boundary are also
+adjacent only. Retained failed/dead-letter counts, fail-closed unavailable
+state, and retention metadata are notifications/API-contract delivery evidence;
+they do not describe agent liveness, enrollment, install readiness, command
+transport, or fleet health.
SSO provider-detail payload changes on shared `internal/api/identity_sso_handlers.go`
are API-contract/security-settings owned. Nested OIDC/SAML edit fields,
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index d5b9ade013..e60718077f 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -1118,14 +1118,23 @@ notification destination reload and persistence orchestration.
`frontend-modern/src/features/alerts/useAlertWebhookDestinationsState.ts` now
owns webhook load/mutate/test flow,
`frontend-modern/src/features/alerts/useAlertDestinationsTabState.ts` now owns
-destination test actions plus retry orchestration around that webhook runtime,
+destination test actions, retry orchestration, and notification delivery-health
+loading around that webhook runtime,
while
`frontend-modern/src/features/alerts/tabs/DestinationsTab.tsx` stays the
destinations render shell and composes
+`frontend-modern/src/features/alerts/AlertDeliveryHealthCard.tsx`,
`frontend-modern/src/features/alerts/AlertEmailDestinationsSection.tsx`,
`frontend-modern/src/features/alerts/AlertAppriseDestinationsSection.tsx`,
`frontend-modern/src/features/alerts/AlertWebhookDestinationsSection.tsx`, and
-the dedicated load/error wrappers. Future config cleanup should extend the
+the dedicated load/error wrappers. The delivery card must warn for retained
+terminal failures, present an unavailable queue-health read as unverified
+rather than healthy, and give the operator a refresh action plus configuration
+and test guidance. Recoverable retry attempts must not produce this warning.
+`frontend-modern/src/features/alerts/AlertDeliveryHealthCard.test.tsx` and
+`frontend-modern/src/features/alerts/__tests__/useAlertDestinationsTabState.test.tsx`
+are the focused render and runtime proofs for that operator surface.
+Future config cleanup should extend the
config transport hook, the config model, the override-projection hook, or the
shared `frontend-modern/src/utils/alertDestinationsPresentation.ts` helper for
customer-facing destinations copy instead of reviving inline retry, test, and
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 87f689e288..2df817cd99 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -4497,6 +4497,12 @@ resource identifiers, alert/notification content, or clickstream events.
An install that already has monitoring data when schema v2 is first observed
must use `present_at_first_observation` instead of an invented elapsed-time
bucket.
+Telemetry schema v3 changes only the semantics of
+`notification_failures_7d`: v2 values are unsuccessful delivery attempts,
+including retries, while v3 values are terminal failed/dead-letter outcomes.
+`notification_attempts_7d` continues to include retries. Reports must cohort
+the v2 and v3 failure meanings separately rather than compare or sum them as
+one signal; the payload remains content-free and field/type compatible.
`scripts/check_telemetry_schema_parity.py` must prove that this TypeScript
preview interface, `internal/telemetry.Ping`, and the Pulse Pro receiver have
matching public fields and primitive types.
@@ -5961,6 +5967,16 @@ input aliases at ingress instead of leaving them as a live runtime contract:
Pushover `app_token` / `user_token` may be accepted only at config/API/UI input
boundaries, and API responses plus live notification runtime state must carry
only canonical `token` / `user` fields.
+`GET /api/notifications/health` must fail closed around the persistent queue.
+Its queue object reports `healthy`, `degraded`, or `unavailable`; includes
+retained status counts, `attention_required`, fixed `reason_codes`, and the
+seven-day completed/30-day dead-letter retention contract; and explicitly
+states that retry attempts do not affect health while terminal failures do.
+Any retained `failed` or `dlq` row makes both queue and overall health false.
+A queue-stats read error also makes health false and must not expose the raw
+storage error. `frontend-modern/src/api/notifications.ts` owns normalization
+of this payload and must turn malformed or missing health fields into
+`unavailable`, not a healthy fallback.
That same shared owner now also governs writable auth env target order:
setup, password-change, and auth-status flows must route `.env` writes through
the shared helper instead of open-coding config-path writes plus ad hoc
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index d9faffb726..fddcc5b572 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -4607,10 +4607,16 @@ rendering remains in
metric normalization remains in
`frontend-modern/src/components/Alerts/alertResourceTableModel.ts`.
`frontend-modern/src/features/alerts/useAlertDestinationsTabState.ts` now owns
-destination test actions plus retry orchestration while
+destination test actions, retry orchestration, and delivery-health loading while
`frontend-modern/src/features/alerts/tabs/DestinationsTab.tsx` stays the
render shell and should compose the dedicated email, Apprise, webhook, and
-load/error section owners instead of carrying those panels inline. Future
+load/error section owners plus
+`frontend-modern/src/features/alerts/AlertDeliveryHealthCard.tsx` instead of
+carrying those panels inline. That card is a route-owned danger surface, not a
+global success badge: degraded retained terminal delivery state and unavailable
+health reads remain visible, while healthy and retry-pending state add no
+banner. Its operator copy stays centralized in
+`frontend-modern/src/utils/alertDestinationsPresentation.ts`. Future
cleanup should extend the transport hook, config model, override hook, or
destinations runtime hook based on the true owner, not move config control
flow back into the top-level page shell.
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index e760601bba..38c03d77e5 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -1323,11 +1323,13 @@ targets, and active alerts. Telemetry callers may consume those coarse totals,
but they must not bypass monitoring to read provider-local identifiers or
tenant-local resource names.
That install-wide boundary also owns privacy-bounded outcome aggregation for
-telemetry schema v2. It may count alert history entries fired, acknowledged,
+telemetry schema v3. It may count alert history entries fired, acknowledged,
or resolved within the existing 30-day local history window and notification
-attempt/delivery/failure totals within the notification queue's existing
-seven-day retention window, across the provisioned tenant set. It must consume
-only content-free totals from tenant-owned managers and must not export alert
+attempt, successful-delivery, and terminal failed/dead-letter totals within the
+notification queue's existing seven-day telemetry window, across the
+provisioned tenant set. Attempts include retries; a recoverable failed attempt
+must not also become a terminal failure. It must consume only content-free
+totals from tenant-owned managers and must not export alert
IDs, resource IDs, actors, reasons, destinations, recipients, endpoints,
timestamps, error text, or message content. Notification queue state remains
delivery evidence rather than alert-lifecycle truth, and monitoring must not
diff --git a/docs/release-control/v6/internal/subsystems/notifications.md b/docs/release-control/v6/internal/subsystems/notifications.md
index 37a3f00e59..3356a2947b 100644
--- a/docs/release-control/v6/internal/subsystems/notifications.md
+++ b/docs/release-control/v6/internal/subsystems/notifications.md
@@ -258,9 +258,10 @@ remains notification truth only and cannot resolve or reopen the alert
lifecycle.
The queue owner may expose a read-only, content-free telemetry aggregate over
-its retained per-attempt audit rows: total delivery attempts plus successful
-and failed attempt counts since a caller-supplied cutoff. The aggregate must
-be computed in storage,
+its retained per-attempt audit rows: total delivery attempts, including
+retries, plus successful deliveries and terminal failed/dead-letter outcomes
+since a caller-supplied cutoff. A failed attempt that is returned to `pending`
+for retry is not a terminal delivery failure. The aggregate must be computed in storage,
must not return or copy notification IDs, alert links, destinations,
recipients, endpoint URLs, titles, bodies, error text, or timestamps, and must
not mutate queue or alert state. The install-wide monitoring owner may sum that
@@ -269,6 +270,15 @@ outcome counters. Because completed queue rows are retention-bounded, this is a
seven-day delivery signal only and must not be presented as lifetime delivery
history or as proof that an alert was resolved.
+Queue health is retention-bounded delivery truth. `GetQueueStats` counts every
+row still retained by the queue: `sent`, `failed`, and `cancelled` rows for
+seven days, dead-letter rows for 30 days, and nonterminal rows until they
+complete. The notification health API must report `degraded` when any retained
+`failed` or `dlq` row exists and `unavailable`, never healthy, when those
+counts cannot be read. Pending retries do not degrade health. The response
+must expose fixed reason codes and retention metadata rather than raw queue
+errors or notification content.
+
### Occurrence-bound delivery receipts
The notification owner records successful firing delivery by exact alert ID,
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index dab2160c47..a7c55a7364 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -2242,6 +2242,8 @@
"frontend-modern/src/features/alerts/__tests__/OverviewTab.timelineerror.test.tsx",
"frontend-modern/src/features/alerts/__tests__/OverviewTab.total24h.test.tsx",
"frontend-modern/src/features/alerts/__tests__/ThresholdsTab.test.tsx",
+ "frontend-modern/src/features/alerts/__tests__/useAlertDestinationsTabState.test.tsx",
+ "frontend-modern/src/features/alerts/AlertDeliveryHealthCard.test.tsx",
"frontend-modern/src/features/alerts/identity.test.ts",
"frontend-modern/src/features/alerts/thresholds/__tests__/helpers.test.ts",
"frontend-modern/src/features/alerts/thresholds/hooks/__tests__/truenasThresholdPersistence.test.tsx",
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 8322ebbc0f..2e44d171ef 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -977,6 +977,13 @@ recipients, endpoints, alert content, notification content, prompts, commands,
or an event-level journey/clickstream. Known install age for an upgraded
installation is therefore a lower bound beginning with its first schema-v2
observation, not a reconstructed installation date.
+Schema v3 preserves that field/type allowlist but corrects
+`notification_failures_7d` from all unsuccessful attempts to terminal
+failed/dead-letter outcomes; `notification_attempts_7d` still includes retry
+attempts. Adoption reporting must keep legacy schema-v2 failed-attempt values
+separate from schema-v3 terminal-failure values. This semantic correction
+must not add destination, recipient, endpoint, error, notification, alert, or
+identity content to either the outbound payload or central aggregate.
If monitoring is already populated at that first observation, time-to-first
resource must report a dedicated present-at-first-observation bucket rather
than inventing an under-15-minute activation duration.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 518c2f1f94..c7c645102c 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -1993,6 +1993,11 @@ Notification webhook management changes on shared `internal/api/` handlers are
likewise adjacent only: the webhook `signingSecret` payload field and its
masking semantics are notifications/API-contract owned and create no storage,
recovery-point, or backup-surface semantics.
+Persistent notification queue-health changes on that same shared boundary
+remain notifications/API-contract owned. Retained failed/dead-letter counts,
+their seven-day/30-day retention metadata, and fail-closed unavailable state
+must not be reinterpreted as storage health, backup status, recovery-point
+validity, or restore readiness.
SSO provider-detail payload changes on shared `internal/api/identity_sso_handlers.go`
are API-contract/security-settings owned. Nested OIDC/SAML edit fields,
diff --git a/frontend-modern/public/docs/PRIVACY.md b/frontend-modern/public/docs/PRIVACY.md
index f45d369925..6f51285608 100644
--- a/frontend-modern/public/docs/PRIVACY.md
+++ b/frontend-modern/public/docs/PRIVACY.md
@@ -37,7 +37,7 @@ Every field is listed below with the reason it exists. Nothing else is included
| Field | Example | Purpose |
|-------|---------|---------|
-| Schema version | `2` | Identify the exact payload contract so old and new signals are not mixed silently |
+| Schema version | `3` | Identify the exact payload contract so old and new signals are not mixed silently |
| Sent at | `2026-07-23T08:30:00Z` | Date the individual heartbeat without sending a history of client activity |
| Install ID | `a1b2c3d4-...` | Distinguish active installations within one rotation window without tying telemetry to an account or person |
| Version | `6.0.0-rc.1` | Track the canonical release identity currently deployed |
@@ -91,9 +91,9 @@ Every field is listed below with the reason it exists. Nothing else is included
| Alerts fired 30d | `18` | Count locally retained alert-history entries in the current 30-day window without sending alert text, resource IDs, or timestamps |
| Alerts acknowledged 30d | `7` | Count acknowledgements in the current 30-day window without sending actors, reasons, alert IDs, or timestamps |
| Alerts resolved 30d | `12` | Count resolved alert records in the current 30-day window without sending resolution details, alert IDs, or resource IDs |
-| Notification attempts 7d | `14` | Count delivery attempts in the locally retained seven-day queue window without sending recipients, endpoints, titles, or message content |
+| Notification attempts 7d | `14` | Count delivery attempts, including retry attempts, in the locally retained seven-day queue window without sending recipients, endpoints, titles, or message content |
| Notification deliveries 7d | `11` | Count successfully delivered queue records in the local seven-day window without sending channel, recipient, endpoint, or content |
-| Notification failures 7d | `3` | Count failed delivery attempts in the local seven-day window without sending error text, endpoint, recipient, or message content |
+| Notification failures 7d (terminal in schema v3) | `3` | Count terminal failed or dead-lettered delivery outcomes in the local seven-day window without sending retry-attempt failures, error text, endpoint, recipient, or message content |
| Relay enabled | `true`/`false` | See whether remote-access features are being used |
| SSO enabled | `true`/`false` | See whether single-sign-on support is being used |
| Multi-tenant | `true`/`false` | See whether multi-tenant/runtime-org features are being used |
@@ -165,6 +165,13 @@ Every field is listed below with the reason it exists. Nothing else is included
| Pulse Intelligence approved action stuck executing 30d | `1` | Count approved governed actions abandoned in the executing state in the current 30-day telemetry window without sending action output, command text, resource IDs, or actors |
| Pulse Intelligence approved action last failure reason 30d | `plan_drift` | See one fixed machine reason code for the most recent approved-action failure in the current 30-day telemetry window without sending error text, action output, command text, resource IDs, or actors |
+Telemetry schema v3 corrects the meaning of `notification_failures_7d`: v2
+counted every unsuccessful queue attempt, including attempts that later
+succeeded on retry; v3 counts only terminal `failed` or dead-letter outcomes.
+The adoption report keeps those schema cohorts separate, so legacy retry noise
+is not compared with current terminal-delivery failures. This correction adds
+no notification content or identity fields.
+
#### Server-side handling and retention
- Telemetry pings are stored on the Pulse license server only for aggregate install/use analysis.
diff --git a/frontend-modern/src/api/__tests__/notifications.test.ts b/frontend-modern/src/api/__tests__/notifications.test.ts
index b01315805d..162b02fe33 100644
--- a/frontend-modern/src/api/__tests__/notifications.test.ts
+++ b/frontend-modern/src/api/__tests__/notifications.test.ts
@@ -88,6 +88,112 @@ describe('NotificationsAPI', () => {
expect(result).toEqual([]);
});
+ it('normalizes retained terminal delivery health from the API', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({
+ overall_healthy: false,
+ queue: {
+ pending: 2,
+ sending: 1,
+ sent: 8,
+ failed: 1,
+ dlq: 3,
+ healthy: false,
+ status: 'degraded',
+ attention_required: 4,
+ reason_codes: ['retained_failed_deliveries', 'retained_dead_letter_deliveries'],
+ completed_retention_days: 7,
+ dead_letter_retention_days: 30,
+ counts_are_retention_bounded: true,
+ retry_attempts_affect_health: false,
+ terminal_failures_affect_health: true,
+ },
+ } as any);
+
+ const health = await NotificationsAPI.getHealth();
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/notifications/health');
+ expect(health).toEqual({
+ overallHealthy: false,
+ queue: {
+ pending: 2,
+ sending: 1,
+ sent: 8,
+ failed: 1,
+ deadLetter: 3,
+ healthy: false,
+ status: 'degraded',
+ attentionRequired: 4,
+ reasonCodes: ['retained_failed_deliveries', 'retained_dead_letter_deliveries'],
+ completedRetentionDays: 7,
+ deadLetterRetentionDays: 30,
+ countsAreRetentionBounded: true,
+ retryAttemptsAffectHealth: false,
+ terminalFailuresAffectHealth: true,
+ },
+ });
+ });
+
+ it('fails closed when notification health fields are malformed', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({
+ overall_healthy: 'yes',
+ queue: {
+ failed: '4',
+ dlq: null,
+ healthy: 'yes',
+ status: 'unknown',
+ reason_codes: ['queue_stats_unavailable', 42],
+ terminal_failures_affect_health: 'yes',
+ },
+ } as any);
+
+ const health = await NotificationsAPI.getHealth();
+
+ expect(health.overallHealthy).toBe(false);
+ expect(health.queue).toEqual(
+ expect.objectContaining({
+ failed: 0,
+ deadLetter: 0,
+ healthy: false,
+ status: 'unavailable',
+ reasonCodes: ['queue_stats_unavailable'],
+ terminalFailuresAffectHealth: true,
+ }),
+ );
+ });
+
+ it('fails closed when nominal health contradicts retained terminal counts', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({
+ overall_healthy: true,
+ queue: {
+ pending: 0,
+ sending: 0,
+ sent: 8,
+ failed: 1,
+ dlq: 0,
+ healthy: true,
+ status: 'healthy',
+ attention_required: 0,
+ reason_codes: [],
+ completed_retention_days: 7,
+ dead_letter_retention_days: 30,
+ counts_are_retention_bounded: true,
+ retry_attempts_affect_health: false,
+ terminal_failures_affect_health: true,
+ },
+ } as any);
+
+ const health = await NotificationsAPI.getHealth();
+
+ expect(health.queue).toEqual(
+ expect.objectContaining({
+ healthy: false,
+ status: 'unavailable',
+ failed: 1,
+ }),
+ );
+ expect(health.overallHealthy).toBe(false);
+ });
+
it('surfaces webhook template labels from the API', async () => {
apiFetchJSONMock.mockResolvedValueOnce([
{
diff --git a/frontend-modern/src/api/__tests__/settings.test.ts b/frontend-modern/src/api/__tests__/settings.test.ts
index d42ce63deb..c0354208a3 100644
--- a/frontend-modern/src/api/__tests__/settings.test.ts
+++ b/frontend-modern/src/api/__tests__/settings.test.ts
@@ -7,7 +7,7 @@ vi.mock('@/utils/apiClient', () => ({
}));
const mockTelemetryPreviewPayload = {
- schema_version: 2,
+ schema_version: 3,
sent_at: '2026-07-23T08:30:00Z',
install_id: 'preview-install-id',
version: '6.0.0',
diff --git a/frontend-modern/src/api/notifications.ts b/frontend-modern/src/api/notifications.ts
index f1786d6105..4c5f7ecf6a 100644
--- a/frontend-modern/src/api/notifications.ts
+++ b/frontend-modern/src/api/notifications.ts
@@ -88,6 +88,45 @@ export interface NotificationTestRequest {
webhookId?: string;
}
+export type NotificationQueueHealthStatus = 'healthy' | 'degraded' | 'unavailable';
+
+export interface NotificationQueueHealth {
+ pending: number;
+ sending: number;
+ sent: number;
+ failed: number;
+ deadLetter: number;
+ healthy: boolean;
+ status: NotificationQueueHealthStatus;
+ attentionRequired: number;
+ reasonCodes: string[];
+ completedRetentionDays: number;
+ deadLetterRetentionDays: number;
+ countsAreRetentionBounded: boolean;
+ retryAttemptsAffectHealth: boolean;
+ terminalFailuresAffectHealth: boolean;
+}
+
+export interface NotificationHealth {
+ overallHealthy: boolean;
+ queue: NotificationQueueHealth;
+}
+
+function apiRecord(value: unknown): Record<string, unknown> {
+ return value && typeof value === 'object' ? (value as Record<string, unknown>) : {};
+}
+
+function normalizeQueueHealthStatus(value: unknown): NotificationQueueHealthStatus {
+ return value === 'healthy' || value === 'degraded' ? value : 'unavailable';
+}
+
+function nonNegativeCount(value: unknown): number | undefined {
+ const normalized = finiteNumberOrUndefined(value);
+ return normalized !== undefined && Number.isInteger(normalized) && normalized >= 0
+ ? normalized
+ : undefined;
+}
+
export class NotificationsAPI {
private static baseUrl = '/api/notifications';
@@ -95,6 +134,75 @@ export class NotificationsAPI {
return apiFetchJSON(`${this.baseUrl}/apprise`);
}
+ static async getHealth(): Promise<NotificationHealth> {
+ const payload = await apiFetchJSON<Record<string, unknown>>(`${this.baseUrl}/health`);
+ const queue = apiRecord(payload.queue);
+ const pending = nonNegativeCount(queue.pending);
+ const sending = nonNegativeCount(queue.sending);
+ const sent = nonNegativeCount(queue.sent);
+ const failed = nonNegativeCount(queue.failed);
+ const deadLetter = nonNegativeCount(queue.dlq);
+ const attentionRequired = nonNegativeCount(queue.attention_required);
+ const completedRetentionDays = nonNegativeCount(queue.completed_retention_days);
+ const deadLetterRetentionDays = nonNegativeCount(queue.dead_letter_retention_days);
+ const reasonCodesAreValid =
+ Array.isArray(queue.reason_codes) &&
+ queue.reason_codes.every((reasonCode) => typeof reasonCode === 'string');
+ const semanticsAreValid =
+ queue.counts_are_retention_bounded === true &&
+ queue.retry_attempts_affect_health === false &&
+ queue.terminal_failures_affect_health === true;
+ const availableFieldsAreValid =
+ pending !== undefined &&
+ sending !== undefined &&
+ sent !== undefined &&
+ attentionRequired !== undefined &&
+ completedRetentionDays !== undefined &&
+ completedRetentionDays > 0 &&
+ deadLetterRetentionDays !== undefined &&
+ deadLetterRetentionDays > 0 &&
+ reasonCodesAreValid &&
+ semanticsAreValid;
+ const rawStatus = normalizeQueueHealthStatus(queue.status);
+ const rawHealthy = typeof queue.healthy === 'boolean' ? queue.healthy : undefined;
+ const terminalFailureCount =
+ failed !== undefined && deadLetter !== undefined ? failed + deadLetter : undefined;
+ const statusIsConsistent =
+ rawStatus === 'unavailable' ||
+ (rawStatus === 'healthy' &&
+ availableFieldsAreValid &&
+ rawHealthy === true &&
+ terminalFailureCount === 0 &&
+ attentionRequired === 0) ||
+ (rawStatus === 'degraded' &&
+ availableFieldsAreValid &&
+ rawHealthy === false &&
+ terminalFailureCount !== undefined &&
+ terminalFailureCount > 0 &&
+ attentionRequired === terminalFailureCount);
+ const status = statusIsConsistent ? rawStatus : 'unavailable';
+
+ return {
+ overallHealthy: status === 'healthy' && strictBoolean(payload.overall_healthy),
+ queue: {
+ pending: pending ?? 0,
+ sending: sending ?? 0,
+ sent: sent ?? 0,
+ failed: failed ?? 0,
+ deadLetter: deadLetter ?? 0,
+ healthy: status === 'healthy',
+ status,
+ attentionRequired: attentionRequired ?? 0,
+ reasonCodes: stringArray(queue.reason_codes),
+ completedRetentionDays: completedRetentionDays ?? 7,
+ deadLetterRetentionDays: deadLetterRetentionDays ?? 30,
+ countsAreRetentionBounded: strictBoolean(queue.counts_are_retention_bounded),
+ retryAttemptsAffectHealth: strictBoolean(queue.retry_attempts_affect_health),
+ terminalFailuresAffectHealth: strictBoolean(queue.terminal_failures_affect_health, true),
+ },
+ };
+ }
+
static async updateAppriseConfig(config: AppriseConfig): Promise<AppriseConfig> {
return apiFetchJSON(`${this.baseUrl}/apprise`, {
method: 'PUT',
diff --git a/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts b/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts
index 9b960f404c..1138bd9046 100644
--- a/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts
@@ -13,7 +13,7 @@ const flushAsync = async () => {
const buildTelemetryPreviewPayload = (
overrides: Partial<TelemetryPingPreview> = {},
): TelemetryPingPreview => ({
- schema_version: 2,
+ schema_version: 3,
sent_at: '2026-07-23T08:30:00Z',
install_id: 'preview-install-id',
version: '6.0.0',
diff --git a/frontend-modern/src/features/alerts/AlertDeliveryHealthCard.test.tsx b/frontend-modern/src/features/alerts/AlertDeliveryHealthCard.test.tsx
new file mode 100644
index 0000000000..fc3d597d01
--- /dev/null
+++ b/frontend-modern/src/features/alerts/AlertDeliveryHealthCard.test.tsx
@@ -0,0 +1,63 @@
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type { NotificationQueueHealth } from '@/api/notifications';
+
+import { AlertDeliveryHealthCard } from './AlertDeliveryHealthCard';
+
+const degradedHealth: NotificationQueueHealth = {
+ pending: 2,
+ sending: 0,
+ sent: 12,
+ failed: 1,
+ deadLetter: 2,
+ healthy: false,
+ status: 'degraded',
+ attentionRequired: 3,
+ reasonCodes: ['retained_failed_deliveries', 'retained_dead_letter_deliveries'],
+ completedRetentionDays: 7,
+ deadLetterRetentionDays: 30,
+ countsAreRetentionBounded: true,
+ retryAttemptsAffectHealth: false,
+ terminalFailuresAffectHealth: true,
+};
+
+describe('AlertDeliveryHealthCard', () => {
+ afterEach(() => cleanup());
+
+ it('tells operators that retained terminal deliveries were not delivered', () => {
+ const onRefresh = vi.fn();
+ render(() => (
+ <AlertDeliveryHealthCard
+ health={degradedHealth}
+ unavailable={false}
+ refreshing={false}
+ onRefresh={onRefresh}
+ />
+ ));
+
+ expect(screen.getByRole('alert')).toHaveTextContent('Notification delivery needs attention');
+ expect(screen.getByRole('alert')).toHaveTextContent('1 failed delivery retained for 7 days');
+ expect(screen.getByRole('alert')).toHaveTextContent(
+ '2 dead-lettered deliveries retained for 30 days',
+ );
+ expect(screen.getByRole('alert')).toHaveTextContent(
+ 'recoverable retry attempts do not trigger this warning',
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh delivery status' }));
+ expect(onRefresh).toHaveBeenCalledTimes(1);
+ });
+
+ it('fails closed when queue health cannot be verified', () => {
+ render(() => (
+ <AlertDeliveryHealthCard health={null} unavailable refreshing onRefresh={vi.fn()} />
+ ));
+
+ expect(screen.getByRole('alert')).toHaveTextContent(
+ 'Notification delivery status is unavailable',
+ );
+ expect(screen.getByRole('alert')).toHaveTextContent('send a test before relying on delivery');
+ expect(screen.getByRole('button', { name: 'Refresh delivery status' })).toBeDisabled();
+ });
+});
diff --git a/frontend-modern/src/features/alerts/AlertDeliveryHealthCard.tsx b/frontend-modern/src/features/alerts/AlertDeliveryHealthCard.tsx
new file mode 100644
index 0000000000..1731c788d0
--- /dev/null
+++ b/frontend-modern/src/features/alerts/AlertDeliveryHealthCard.tsx
@@ -0,0 +1,59 @@
+import AlertTriangleIcon from 'lucide-solid/icons/alert-triangle';
+import RefreshCwIcon from 'lucide-solid/icons/refresh-cw';
+
+import type { NotificationQueueHealth } from '@/api/notifications';
+import { Card } from '@/components/shared/Card';
+import {
+ getAlertDestinationsDeliveryHealthDescription,
+ getAlertDestinationsDeliveryHealthTitle,
+ getAlertDestinationsDeliveryRefreshLabel,
+} from '@/utils/alertDestinationsPresentation';
+
+interface AlertDeliveryHealthCardProps {
+ health: NotificationQueueHealth | null;
+ unavailable: boolean;
+ refreshing: boolean;
+ onRefresh: () => void;
+}
+
+export function AlertDeliveryHealthCard(props: AlertDeliveryHealthCardProps) {
+ const status = (): 'degraded' | 'unavailable' =>
+ props.unavailable || props.health?.status === 'unavailable' ? 'unavailable' : 'degraded';
+ const failed = () => props.health?.failed ?? 0;
+ const deadLetter = () => props.health?.deadLetter ?? 0;
+ const completedRetentionDays = () => props.health?.completedRetentionDays ?? 7;
+ const deadLetterRetentionDays = () => props.health?.deadLetterRetentionDays ?? 30;
+
+ return (
+ <Card tone="danger" padding="sm" class="border-red-200 dark:border-red-800 sm:p-4" role="alert">
+ <div class="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
+ <div class="flex min-w-0 items-start gap-3">
+ <AlertTriangleIcon class="mt-0.5 h-4 w-4 flex-shrink-0 text-red-700 dark:text-red-300" />
+ <div class="min-w-0">
+ <h3 class="text-sm font-semibold text-red-900 dark:text-red-100">
+ {getAlertDestinationsDeliveryHealthTitle(status())}
+ </h3>
+ <p class="mt-1 text-sm leading-6 text-red-800 dark:text-red-200">
+ {getAlertDestinationsDeliveryHealthDescription({
+ status: status(),
+ failed: failed(),
+ deadLetter: deadLetter(),
+ completedRetentionDays: completedRetentionDays(),
+ deadLetterRetentionDays: deadLetterRetentionDays(),
+ })}
+ </p>
+ </div>
+ </div>
+ <button
+ type="button"
+ class="inline-flex flex-shrink-0 items-center justify-center gap-2 rounded-md border border-red-300 bg-transparent px-3 py-1.5 text-sm font-medium text-red-800 transition hover:bg-red-100 disabled:cursor-not-allowed disabled:opacity-50 dark:border-red-700 dark:text-red-200 dark:hover:bg-red-900/30"
+ disabled={props.refreshing}
+ onClick={props.onRefresh}
+ >
+ <RefreshCwIcon class={`h-4 w-4 ${props.refreshing ? 'animate-spin' : ''}`} />
+ {getAlertDestinationsDeliveryRefreshLabel()}
+ </button>
+ </div>
+ </Card>
+ );
+}
diff --git a/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsTabState.test.tsx b/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsTabState.test.tsx
index bd4329c0c4..22c8806bde 100644
--- a/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsTabState.test.tsx
+++ b/frontend-modern/src/features/alerts/__tests__/useAlertDestinationsTabState.test.tsx
@@ -13,6 +13,7 @@ vi.mock('@/api/notifications', () => ({
NotificationsAPI: {
createWebhook: vi.fn(),
deleteWebhook: vi.fn(),
+ getHealth: vi.fn(),
getWebhooks: vi.fn(),
testNotification: vi.fn(),
testWebhook: vi.fn(),
@@ -71,6 +72,7 @@ describe('useAlertDestinationsTabState', () => {
beforeEach(() => {
vi.mocked(NotificationsAPI.createWebhook).mockReset();
vi.mocked(NotificationsAPI.deleteWebhook).mockReset();
+ vi.mocked(NotificationsAPI.getHealth).mockReset();
vi.mocked(NotificationsAPI.getWebhooks).mockReset();
vi.mocked(NotificationsAPI.testNotification).mockReset();
vi.mocked(NotificationsAPI.testWebhook).mockReset();
@@ -98,6 +100,25 @@ describe('useAlertDestinationsTabState', () => {
url: 'https://hooks.example.test/ops',
},
] as never);
+ vi.mocked(NotificationsAPI.getHealth).mockResolvedValue({
+ overallHealthy: true,
+ queue: {
+ pending: 0,
+ sending: 0,
+ sent: 0,
+ failed: 0,
+ deadLetter: 0,
+ healthy: true,
+ status: 'healthy',
+ attentionRequired: 0,
+ reasonCodes: [],
+ completedRetentionDays: 7,
+ deadLetterRetentionDays: 30,
+ countsAreRetentionBounded: true,
+ retryAttemptsAffectHealth: false,
+ terminalFailuresAffectHealth: true,
+ },
+ });
vi.mocked(NotificationsAPI.testNotification).mockResolvedValue({ success: true } as never);
vi.mocked(NotificationsAPI.testWebhook).mockResolvedValue({ success: true } as never);
@@ -114,6 +135,8 @@ describe('useAlertDestinationsTabState', () => {
);
await waitFor(() => expect(NotificationsAPI.getWebhooks).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(NotificationsAPI.getHealth).toHaveBeenCalledTimes(1));
+ expect(result.deliveryHealth()?.queue.status).toBe('healthy');
expect(result.webhooks()).toEqual([
expect.objectContaining({ id: 'hook-1', service: 'generic' }),
]);
@@ -146,6 +169,7 @@ describe('useAlertDestinationsTabState', () => {
result.handleRetry();
expect(onRetryLoad).toHaveBeenCalledTimes(1);
await waitFor(() => expect(NotificationsAPI.getWebhooks).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(NotificationsAPI.getHealth).toHaveBeenCalledTimes(2));
expect(notificationStore.success).toHaveBeenCalledTimes(2);
expect(showErrorWithDetail).not.toHaveBeenCalled();
});
diff --git a/frontend-modern/src/features/alerts/tabs/DestinationsTab.tsx b/frontend-modern/src/features/alerts/tabs/DestinationsTab.tsx
index 54ffac80a6..0f5507caa7 100644
--- a/frontend-modern/src/features/alerts/tabs/DestinationsTab.tsx
+++ b/frontend-modern/src/features/alerts/tabs/DestinationsTab.tsx
@@ -3,6 +3,7 @@ import { hasFeature } from '@/stores/license';
import { getUpgradeActionDestination } from '@/stores/licenseCommercial';
import { presentationPolicyHidesUpgradePrompts } from '@/stores/sessionPresentationPolicy';
import { AlertAppriseDestinationsSection } from '../AlertAppriseDestinationsSection';
+import { AlertDeliveryHealthCard } from '../AlertDeliveryHealthCard';
import { AlertDestinationsLoadErrorCard } from '../AlertDestinationsLoadErrorCard';
import { AlertDestinationsLoadingState } from '../AlertDestinationsLoadingState';
import { AlertEmailDestinationsSection } from '../AlertEmailDestinationsSection';
@@ -25,6 +26,19 @@ export function DestinationsTab(props: DestinationsTabProps) {
return (
<div class="flex w-full max-w-full flex-col gap-6 md:gap-8">
<Show when={!state.isLoading()} fallback={<AlertDestinationsLoadingState />}>
+ <Show
+ when={
+ state.deliveryHealthUnavailable() || state.deliveryHealth()?.queue.status === 'degraded'
+ }
+ >
+ <AlertDeliveryHealthCard
+ health={state.deliveryHealth()?.queue ?? null}
+ unavailable={state.deliveryHealthUnavailable()}
+ refreshing={state.refreshingDeliveryHealth()}
+ onRefresh={() => void state.loadDeliveryHealth()}
+ />
+ </Show>
+
<Show when={state.hasLoadError()}>
<AlertDestinationsLoadErrorCard
error={props.configLoadError() || state.webhookLoadError() || ''}
diff --git a/frontend-modern/src/features/alerts/useAlertDestinationsTabState.ts b/frontend-modern/src/features/alerts/useAlertDestinationsTabState.ts
index e50b3159f2..f5c03f7fd3 100644
--- a/frontend-modern/src/features/alerts/useAlertDestinationsTabState.ts
+++ b/frontend-modern/src/features/alerts/useAlertDestinationsTabState.ts
@@ -1,6 +1,6 @@
-import { createMemo, createSignal, type Accessor } from 'solid-js';
+import { createMemo, createSignal, onMount, type Accessor } from 'solid-js';
-import { NotificationsAPI, type AppriseConfig } from '@/api/notifications';
+import { NotificationsAPI, type AppriseConfig, type NotificationHealth } from '@/api/notifications';
import { notificationStore } from '@/stores/notifications';
import { logger } from '@/utils/logger';
import { showErrorWithDetail } from '@/utils/toast';
@@ -29,6 +29,9 @@ export interface AlertDestinationsTabStateProps {
export function useAlertDestinationsTabState(props: AlertDestinationsTabStateProps) {
const [testingEmail, setTestingEmail] = createSignal(false);
const [testingApprise, setTestingApprise] = createSignal(false);
+ const [deliveryHealth, setDeliveryHealth] = createSignal<NotificationHealth | null>(null);
+ const [deliveryHealthUnavailable, setDeliveryHealthUnavailable] = createSignal(false);
+ const [refreshingDeliveryHealth, setRefreshingDeliveryHealth] = createSignal(false);
const webhookState = useAlertWebhookDestinationsState();
const isLoading = createMemo(
@@ -41,6 +44,21 @@ export function useAlertDestinationsTabState(props: AlertDestinationsTabStatePro
props.setAppriseConfig({ ...props.appriseConfig(), ...partial });
};
+ const loadDeliveryHealth = async () => {
+ setRefreshingDeliveryHealth(true);
+ try {
+ const health = await NotificationsAPI.getHealth();
+ setDeliveryHealth(health);
+ setDeliveryHealthUnavailable(health.queue.status === 'unavailable');
+ } catch (error) {
+ logger.error('Failed to load notification delivery health', error);
+ setDeliveryHealth(null);
+ setDeliveryHealthUnavailable(true);
+ } finally {
+ setRefreshingDeliveryHealth(false);
+ }
+ };
+
const buildAppriseRequestConfig = (): AppriseConfig => {
const config = appriseState();
const serverUrl = (config.serverUrl || '').trim();
@@ -114,13 +132,22 @@ export function useAlertDestinationsTabState(props: AlertDestinationsTabStatePro
const handleRetry = () => {
props.onRetryLoad();
void webhookState.loadWebhooks();
+ void loadDeliveryHealth();
};
+ onMount(() => {
+ void loadDeliveryHealth();
+ });
+
return {
appriseState,
+ deliveryHealth,
+ deliveryHealthUnavailable,
handleRetry,
hasLoadError,
isLoading,
+ loadDeliveryHealth,
+ refreshingDeliveryHealth,
testApprise,
testEmailConfig,
testingApprise,
diff --git a/frontend-modern/src/utils/__tests__/alertDestinationsPresentation.test.ts b/frontend-modern/src/utils/__tests__/alertDestinationsPresentation.test.ts
index 54b66044f7..4e902b71bc 100644
--- a/frontend-modern/src/utils/__tests__/alertDestinationsPresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/alertDestinationsPresentation.test.ts
@@ -30,6 +30,9 @@ import {
getAlertDestinationsAppriseTestSuccess,
getAlertDestinationsAppriseValidationError,
getAlertDestinationsConfigLoadError,
+ getAlertDestinationsDeliveryHealthDescription,
+ getAlertDestinationsDeliveryHealthTitle,
+ getAlertDestinationsDeliveryRefreshLabel,
getAlertDestinationsEmailTestFailure,
getAlertDestinationsEmailTestSuccess,
getAlertDestinationsLoadErrorBanner,
@@ -115,4 +118,34 @@ describe('alertDestinationsPresentation', () => {
expect(ALERT_DESTINATIONS_PUSH_GATE_MESSAGE).toContain('no port forwarding or VPN');
expect(ALERT_DESTINATIONS_PUSH_GATE_MESSAGE).toContain('Available with Relay and Pro plans');
});
+
+ it('distinguishes retained terminal failures from recoverable retry attempts', () => {
+ expect(getAlertDestinationsDeliveryHealthTitle('degraded')).toBe(
+ 'Notification delivery needs attention',
+ );
+ expect(getAlertDestinationsDeliveryHealthTitle('unavailable')).toBe(
+ 'Notification delivery status is unavailable',
+ );
+ expect(
+ getAlertDestinationsDeliveryHealthDescription({
+ status: 'degraded',
+ failed: 1,
+ deadLetter: 2,
+ completedRetentionDays: 7,
+ deadLetterRetentionDays: 30,
+ }),
+ ).toBe(
+ '1 failed delivery retained for 7 days and 2 dead-lettered deliveries retained for 30 days. These notifications were not delivered. Check each enabled destination and send a test; recoverable retry attempts do not trigger this warning.',
+ );
+ expect(
+ getAlertDestinationsDeliveryHealthDescription({
+ status: 'unavailable',
+ failed: 0,
+ deadLetter: 0,
+ completedRetentionDays: 7,
+ deadLetterRetentionDays: 30,
+ }),
+ ).toContain('could not verify the notification queue');
+ expect(getAlertDestinationsDeliveryRefreshLabel()).toBe('Refresh delivery status');
+ });
});
diff --git a/frontend-modern/src/utils/alertDestinationsPresentation.ts b/frontend-modern/src/utils/alertDestinationsPresentation.ts
index 588b2d49e8..fd758ddbd9 100644
--- a/frontend-modern/src/utils/alertDestinationsPresentation.ts
+++ b/frontend-modern/src/utils/alertDestinationsPresentation.ts
@@ -74,6 +74,10 @@ export const ALERT_DESTINATIONS_PUSH_GATE_MESSAGE =
'Pair the Pulse Mobile app to receive alert push notifications and check on your systems from anywhere — no port forwarding or VPN required. Available with Relay and Pro plans.';
export const ALERT_DESTINATIONS_APPRISE_TEST_SUCCESS = 'Test Apprise notification sent.';
export const ALERT_DESTINATIONS_APPRISE_TEST_FAILURE = 'Unable to send the test notification.';
+export const ALERT_DESTINATIONS_DELIVERY_DEGRADED_TITLE = 'Notification delivery needs attention';
+export const ALERT_DESTINATIONS_DELIVERY_UNAVAILABLE_TITLE =
+ 'Notification delivery status is unavailable';
+export const ALERT_DESTINATIONS_DELIVERY_REFRESH_LABEL = 'Refresh delivery status';
export function getAlertDestinationsConfigLoadError() {
return ALERT_DESTINATIONS_CONFIG_LOAD_ERROR;
@@ -137,3 +141,39 @@ export function getAlertDestinationsAppriseTestSuccess() {
export function getAlertDestinationsAppriseTestFailure() {
return ALERT_DESTINATIONS_APPRISE_TEST_FAILURE;
}
+
+export function getAlertDestinationsDeliveryHealthTitle(status: 'degraded' | 'unavailable') {
+ return status === 'degraded'
+ ? ALERT_DESTINATIONS_DELIVERY_DEGRADED_TITLE
+ : ALERT_DESTINATIONS_DELIVERY_UNAVAILABLE_TITLE;
+}
+
+export function getAlertDestinationsDeliveryHealthDescription(input: {
+ status: 'degraded' | 'unavailable';
+ failed: number;
+ deadLetter: number;
+ completedRetentionDays: number;
+ deadLetterRetentionDays: number;
+}) {
+ if (input.status === 'unavailable') {
+ return 'Pulse could not verify the notification queue. Review the destination settings below and send a test before relying on delivery.';
+ }
+
+ const outcomes: string[] = [];
+ if (input.failed > 0) {
+ outcomes.push(
+ `${input.failed} failed ${input.failed === 1 ? 'delivery' : 'deliveries'} retained for ${input.completedRetentionDays} days`,
+ );
+ }
+ if (input.deadLetter > 0) {
+ outcomes.push(
+ `${input.deadLetter} dead-lettered ${input.deadLetter === 1 ? 'delivery' : 'deliveries'} retained for ${input.deadLetterRetentionDays} days`,
+ );
+ }
+ const summary = outcomes.join(' and ') || 'A retained terminal delivery failure';
+ return `${summary}. These notifications were not delivered. Check each enabled destination and send a test; recoverable retry attempts do not trigger this warning.`;
+}
+
+export function getAlertDestinationsDeliveryRefreshLabel() {
+ return ALERT_DESTINATIONS_DELIVERY_REFRESH_LABEL;
+}
diff --git a/internal/api/notifications.go b/internal/api/notifications.go
index edb154db64..761f6deb96 100644
--- a/internal/api/notifications.go
+++ b/internal/api/notifications.go
@@ -21,6 +21,8 @@ import (
const (
notificationTestRequestBodyLimit = 64 * 1024
webhookTestRequestBodyLimit = 64 * 1024
+ completedQueueRetentionDays = 7
+ deadLetterQueueRetentionDays = 30
)
// NotificationManager defines the interface for notification management operations.
@@ -845,28 +847,51 @@ func (h *NotificationHandlers) TestWebhook(w http.ResponseWriter, r *http.Reques
// GetNotificationHealth returns health status of notification system
func (h *NotificationHandlers) GetNotificationHealth(w http.ResponseWriter, r *http.Request) {
- // Get queue stats
+ monitor := h.getMonitor(r.Context())
+ manager := monitor.GetNotificationManager()
+
queueStats := make(map[string]interface{})
- stats, err := h.getMonitor(r.Context()).GetNotificationManager().GetQueueStats()
+ stats, err := manager.GetQueueStats()
if err != nil {
log.Warn().Err(err).Msg("Failed to get queue stats for health check")
- queueStats["error"] = err.Error()
- queueStats["healthy"] = false
+ queueStats = map[string]interface{}{
+ "healthy": false,
+ "status": "unavailable",
+ "attention_required": 0,
+ "reason_codes": []string{"queue_stats_unavailable"},
+ "completed_retention_days": completedQueueRetentionDays,
+ "dead_letter_retention_days": deadLetterQueueRetentionDays,
+ "counts_are_retention_bounded": true,
+ "retry_attempts_affect_health": false,
+ "terminal_failures_affect_health": true,
+ }
} else {
+ healthy, attentionRequired, reasonCodes := classifyNotificationQueueHealth(stats)
+ status := "healthy"
+ if !healthy {
+ status = "degraded"
+ }
queueStats = map[string]interface{}{
- "pending": stats["pending"],
- "sending": stats["sending"],
- "sent": stats["sent"],
- "failed": stats["failed"],
- "dlq": stats["dlq"],
- "healthy": true,
+ "pending": stats["pending"],
+ "sending": stats["sending"],
+ "sent": stats["sent"],
+ "failed": stats["failed"],
+ "dlq": stats["dlq"],
+ "healthy": healthy,
+ "status": status,
+ "attention_required": attentionRequired,
+ "reason_codes": reasonCodes,
+ "completed_retention_days": completedQueueRetentionDays,
+ "dead_letter_retention_days": deadLetterQueueRetentionDays,
+ "counts_are_retention_bounded": true,
+ "retry_attempts_affect_health": false,
+ "terminal_failures_affect_health": true,
}
}
// Get config status
- nm := h.getMonitor(r.Context()).GetNotificationManager()
- emailCfg := nm.GetEmailConfig()
- webhooks := nm.GetWebhooks()
+ emailCfg := manager.GetEmailConfig()
+ webhooks := manager.GetWebhooks()
health := map[string]interface{}{
"queue": queueStats,
@@ -879,7 +904,7 @@ func (h *NotificationHandlers) GetNotificationHealth(w http.ResponseWriter, r *h
"enabled": countEnabledWebhooks(webhooks),
},
"encryption": map[string]interface{}{
- "enabled": h.getMonitor(r.Context()).GetConfigPersistence().IsEncryptionEnabled(),
+ "enabled": monitor.GetConfigPersistence().IsEncryptionEnabled(),
},
"overall_healthy": queueStats["healthy"] == true,
}
@@ -888,6 +913,20 @@ func (h *NotificationHandlers) GetNotificationHealth(w http.ResponseWriter, r *h
json.NewEncoder(w).Encode(health)
}
+func classifyNotificationQueueHealth(stats map[string]int) (bool, int, []string) {
+ failed := stats[string(notifications.QueueStatusFailed)]
+ deadLetter := stats[string(notifications.QueueStatusDLQ)]
+ reasonCodes := make([]string, 0, 2)
+ if failed > 0 {
+ reasonCodes = append(reasonCodes, "retained_failed_deliveries")
+ }
+ if deadLetter > 0 {
+ reasonCodes = append(reasonCodes, "retained_dead_letter_deliveries")
+ }
+ attentionRequired := failed + deadLetter
+ return attentionRequired == 0, attentionRequired, reasonCodes
+}
+
func countEnabledWebhooks(webhooks []notifications.WebhookConfig) int {
count := 0
for _, wh := range webhooks {
diff --git a/internal/api/notifications_health_test.go b/internal/api/notifications_health_test.go
new file mode 100644
index 0000000000..3aed5a90a7
--- /dev/null
+++ b/internal/api/notifications_health_test.go
@@ -0,0 +1,128 @@
+package api
+
+import (
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/notifications"
+)
+
+func TestGetNotificationHealthReportsRetainedTerminalFailures(t *testing.T) {
+ mockMonitor := new(MockNotificationMonitor)
+ mockManager := new(MockNotificationManager)
+ mockPersistence := new(MockNotificationConfigPersistence)
+ mockMonitor.On("GetNotificationManager").Return(mockManager)
+ mockMonitor.On("GetConfigPersistence").Return(mockPersistence)
+ mockManager.On("GetQueueStats").Return(map[string]int{
+ "pending": 4,
+ "sending": 1,
+ "sent": 9,
+ "failed": 2,
+ "dlq": 3,
+ }, nil).Once()
+ mockManager.On("GetEmailConfig").Return(notifications.EmailConfig{}).Once()
+ mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{}).Once()
+ mockPersistence.On("IsEncryptionEnabled").Return(true).Once()
+
+ rec := httptest.NewRecorder()
+ NewNotificationHandlers(nil, mockMonitor).GetNotificationHealth(
+ rec,
+ httptest.NewRequest(http.MethodGet, "/api/notifications/health", nil),
+ )
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
+ }
+ var response struct {
+ OverallHealthy bool `json:"overall_healthy"`
+ Queue struct {
+ Healthy bool `json:"healthy"`
+ Status string `json:"status"`
+ AttentionRequired int `json:"attention_required"`
+ ReasonCodes []string `json:"reason_codes"`
+ CompletedRetentionDays int `json:"completed_retention_days"`
+ DeadLetterRetentionDays int `json:"dead_letter_retention_days"`
+ CountsAreRetentionBounded bool `json:"counts_are_retention_bounded"`
+ RetryAttemptsAffectHealth bool `json:"retry_attempts_affect_health"`
+ TerminalFailuresAffectHealth bool `json:"terminal_failures_affect_health"`
+ } `json:"queue"`
+ }
+ if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
+ t.Fatalf("decode health response: %v", err)
+ }
+ if response.OverallHealthy || response.Queue.Healthy || response.Queue.Status != "degraded" {
+ t.Fatalf("health response = %#v, want degraded and unhealthy", response)
+ }
+ if response.Queue.AttentionRequired != 5 {
+ t.Fatalf("attention_required = %d, want 5", response.Queue.AttentionRequired)
+ }
+ if len(response.Queue.ReasonCodes) != 2 ||
+ response.Queue.ReasonCodes[0] != "retained_failed_deliveries" ||
+ response.Queue.ReasonCodes[1] != "retained_dead_letter_deliveries" {
+ t.Fatalf("reason_codes = %#v", response.Queue.ReasonCodes)
+ }
+ if response.Queue.CompletedRetentionDays != 7 ||
+ response.Queue.DeadLetterRetentionDays != 30 ||
+ !response.Queue.CountsAreRetentionBounded ||
+ response.Queue.RetryAttemptsAffectHealth ||
+ !response.Queue.TerminalFailuresAffectHealth {
+ t.Fatalf("queue semantics = %#v", response.Queue)
+ }
+}
+
+func TestGetNotificationHealthFailsClosedWhenQueueStatsAreUnavailable(t *testing.T) {
+ mockMonitor := new(MockNotificationMonitor)
+ mockManager := new(MockNotificationManager)
+ mockPersistence := new(MockNotificationConfigPersistence)
+ mockMonitor.On("GetNotificationManager").Return(mockManager)
+ mockMonitor.On("GetConfigPersistence").Return(mockPersistence)
+ mockManager.On("GetQueueStats").Return(nil, errors.New("database path /secret unavailable")).Once()
+ mockManager.On("GetEmailConfig").Return(notifications.EmailConfig{}).Once()
+ mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{}).Once()
+ mockPersistence.On("IsEncryptionEnabled").Return(false).Once()
+
+ rec := httptest.NewRecorder()
+ NewNotificationHandlers(nil, mockMonitor).GetNotificationHealth(
+ rec,
+ httptest.NewRequest(http.MethodGet, "/api/notifications/health", nil),
+ )
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
+ }
+ var response struct {
+ OverallHealthy bool `json:"overall_healthy"`
+ Queue struct {
+ Healthy bool `json:"healthy"`
+ Status string `json:"status"`
+ ReasonCodes []string `json:"reason_codes"`
+ } `json:"queue"`
+ }
+ if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
+ t.Fatalf("decode health response: %v", err)
+ }
+ if response.OverallHealthy || response.Queue.Healthy || response.Queue.Status != "unavailable" {
+ t.Fatalf("health response = %#v, want unavailable and unhealthy", response)
+ }
+ if len(response.Queue.ReasonCodes) != 1 ||
+ response.Queue.ReasonCodes[0] != "queue_stats_unavailable" {
+ t.Fatalf("reason_codes = %#v", response.Queue.ReasonCodes)
+ }
+ if body := rec.Body.String(); body == "" ||
+ containsAny(body, "database path", "/secret") {
+ t.Fatalf("health response exposed internal queue error: %s", body)
+ }
+}
+
+func containsAny(value string, needles ...string) bool {
+ for _, needle := range needles {
+ if needle != "" && strings.Contains(value, needle) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/notifications/queue.go b/internal/notifications/queue.go
index 8034eaa212..455462732c 100644
--- a/internal/notifications/queue.go
+++ b/internal/notifications/queue.go
@@ -1204,7 +1204,11 @@ func (nq *NotificationQueue) RecordAudit(notif *QueuedNotification, success bool
return err
}
-// GetQueueStats returns statistics about the notification queue
+// GetQueueStats returns counts for the rows currently retained by the queue.
+// Sent, failed, and cancelled rows are retained for seven days; dead-letter
+// rows are retained for 30 days; pending and sending rows remain until they
+// reach a terminal state. Callers must not present these mixed retention
+// windows as a rate or as lifetime delivery history.
func (nq *NotificationQueue) GetQueueStats() (map[string]int, error) {
nq.mu.RLock()
defer nq.mu.RUnlock()
@@ -1212,14 +1216,10 @@ func (nq *NotificationQueue) GetQueueStats() (map[string]int, error) {
query := `
SELECT status, COUNT(*) as count
FROM notification_queue
- WHERE completed_at IS NULL OR completed_at > ?
GROUP BY status
`
- // Include last 24 hours of completed
- since := time.Now().Add(-24 * time.Hour).Unix()
-
- rows, err := nq.db.Query(query, since)
+ rows, err := nq.db.Query(query)
if err != nil {
return nil, err
}
@@ -1230,11 +1230,14 @@ func (nq *NotificationQueue) GetQueueStats() (map[string]int, error) {
var status string
var count int
if err := rows.Scan(&status, &count); err != nil {
- continue
+ return nil, fmt.Errorf("scan notification queue statistics: %w", err)
}
stats[status] = count
}
+ if err := rows.Err(); err != nil {
+ return nil, fmt.Errorf("iterate notification queue statistics: %w", err)
+ }
return stats, nil
}
@@ -1243,12 +1246,17 @@ func (nq *NotificationQueue) GetQueueStats() (map[string]int, error) {
type TelemetryStats struct {
Attempts int
Deliveries int
- Failures int
+ // Failures counts terminal delivery failures only. Recoverable failed
+ // attempts that returned to pending for retry are included in Attempts but
+ // not in Failures.
+ Failures int
}
-// GetTelemetryStats returns aggregate delivery outcomes from locally retained
-// per-attempt audit rows recorded on or after since. Callers must not interpret
-// a window longer than the queue's completed-row retention as complete.
+// GetTelemetryStats returns aggregate delivery activity from locally retained
+// per-attempt audit rows recorded on or after since. Attempts includes retries;
+// Deliveries counts successful terminal sends; Failures counts only failed or
+// dead-letter terminal outcomes. Callers must not interpret a window longer
+// than the queue's completed-row retention as complete.
func (nq *NotificationQueue) GetTelemetryStats(since time.Time) (TelemetryStats, error) {
if nq == nil {
return TelemetryStats{}, nil
@@ -1265,7 +1273,10 @@ func (nq *NotificationQueue) GetTelemetryStats(since time.Time) (TelemetryStats,
SELECT
COUNT(*),
COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END), 0),
- COALESCE(SUM(CASE WHEN success = 0 THEN 1 ELSE 0 END), 0)
+ COALESCE(SUM(CASE
+ WHEN success = 0 AND status IN ('failed', 'dlq') THEN 1
+ ELSE 0
+ END), 0)
FROM notification_audit
WHERE timestamp >= ?
`, since.UTC().Unix()).Scan(&stats.Attempts, &stats.Deliveries, &stats.Failures)
diff --git a/internal/notifications/queue_queryplan_test.go b/internal/notifications/queue_queryplan_test.go
index 175a776877..15f34db7af 100644
--- a/internal/notifications/queue_queryplan_test.go
+++ b/internal/notifications/queue_queryplan_test.go
@@ -25,6 +25,7 @@ func TestNotificationQueueQueryPlansUseIndexes(t *testing.T) {
query string
args []any
wantTableIndexes map[string]string
+ wantTableIndexScans map[string]string
allowOrderTempBTree bool
}{
{
@@ -45,6 +46,13 @@ func TestNotificationQueueQueryPlansUseIndexes(t *testing.T) {
},
allowOrderTempBTree: true,
},
+ {
+ name: "get retained queue stats uses covering status index",
+ query: `SELECT status, COUNT(*) FROM notification_queue GROUP BY status`,
+ wantTableIndexScans: map[string]string{
+ "notification_queue": "idx_status",
+ },
+ },
{
name: "get dlq uses status completed index",
query: `
@@ -104,6 +112,11 @@ func TestNotificationQueueQueryPlansUseIndexes(t *testing.T) {
t.Fatalf("expected SEARCH on %s using index %q\nPlan:\n%s", tableName, indexName, plan)
}
}
+ for tableName, indexName := range tt.wantTableIndexScans {
+ if !containsNotificationScanWithIndex(plan, tableName, indexName) {
+ t.Fatalf("expected SCAN on %s using index %q\nPlan:\n%s", tableName, indexName, plan)
+ }
+ }
if strings.Contains(plan, "USE TEMP B-TREE FOR ORDER BY") && !tt.allowOrderTempBTree {
t.Fatalf("unexpected temp B-tree order spill\nPlan:\n%s", plan)
}
@@ -271,6 +284,17 @@ func containsNotificationSearchWithIndex(plan, tableName, indexName string) bool
return false
}
+func containsNotificationScanWithIndex(plan, tableName, indexName string) bool {
+ for _, line := range strings.Split(plan, "\n") {
+ if strings.Contains(line, "SCAN") &&
+ notificationLineRefersToTable(line, tableName) &&
+ strings.Contains(line, indexName) {
+ return true
+ }
+ }
+ return false
+}
+
func containsNotificationFullTableScan(plan string) bool {
for _, line := range strings.Split(plan, "\n") {
if !strings.Contains(line, "SCAN") {
diff --git a/internal/notifications/queue_test.go b/internal/notifications/queue_test.go
index 309aa94084..500708dea3 100644
--- a/internal/notifications/queue_test.go
+++ b/internal/notifications/queue_test.go
@@ -1339,6 +1339,47 @@ func TestGetQueueStats(t *testing.T) {
}
})
+ t.Run("includes terminal rows for their full retention window", func(t *testing.T) {
+ tempDir := t.TempDir()
+ nq, err := NewNotificationQueue(tempDir)
+ if err != nil {
+ t.Fatalf("Failed to create notification queue: %v", err)
+ }
+ defer func() { _ = nq.Stop() }()
+
+ for _, notif := range []*QueuedNotification{
+ {ID: "failed-retained", Type: "email", Status: QueueStatusPending, MaxAttempts: 3, Config: []byte(`{}`)},
+ {ID: "dlq-retained", Type: "webhook", Status: QueueStatusPending, MaxAttempts: 3, Config: []byte(`{}`)},
+ } {
+ if err := nq.Enqueue(notif); err != nil {
+ t.Fatalf("Failed to enqueue %s: %v", notif.ID, err)
+ }
+ }
+ if err := nq.UpdateStatus("failed-retained", QueueStatusFailed, "terminal"); err != nil {
+ t.Fatalf("mark failed: %v", err)
+ }
+ if err := nq.UpdateStatus("dlq-retained", QueueStatusDLQ, "terminal"); err != nil {
+ t.Fatalf("mark dlq: %v", err)
+ }
+ retainedAt := time.Now().Add(-48 * time.Hour).Unix()
+ if _, err := nq.db.Exec(
+ `UPDATE notification_queue SET completed_at = ? WHERE id IN (?, ?)`,
+ retainedAt,
+ "failed-retained",
+ "dlq-retained",
+ ); err != nil {
+ t.Fatalf("age retained terminal rows: %v", err)
+ }
+
+ stats, err := nq.GetQueueStats()
+ if err != nil {
+ t.Fatalf("GetQueueStats failed: %v", err)
+ }
+ if stats["failed"] != 1 || stats["dlq"] != 1 {
+ t.Fatalf("retained terminal stats = %#v, want failed=1 dlq=1", stats)
+ }
+ })
+
t.Run("UpdateStatus returns error for non-existent notification", func(t *testing.T) {
tempDir := t.TempDir()
nq, err := NewNotificationQueue(tempDir)
@@ -1383,7 +1424,7 @@ func TestGetTelemetryStatsReturnsOnlyWindowedOutcomeCounts(t *testing.T) {
t.Fatalf("record sent delivery: %v", err)
}
entries[1].Attempts = 1
- entries[1].Status = QueueStatusFailed
+ entries[1].Status = QueueStatusDLQ
if err := nq.RecordAudit(entries[1], false, "final attempt failed"); err != nil {
t.Fatalf("record failed delivery: %v", err)
}
@@ -1404,7 +1445,7 @@ func TestGetTelemetryStatsReturnsOnlyWindowedOutcomeCounts(t *testing.T) {
if err != nil {
t.Fatalf("GetTelemetryStats: %v", err)
}
- if stats != (TelemetryStats{Attempts: 3, Deliveries: 1, Failures: 2}) {
+ if stats != (TelemetryStats{Attempts: 3, Deliveries: 1, Failures: 1}) {
t.Fatalf("telemetry stats = %#v", stats)
}
}
diff --git a/internal/telemetry/telemetry.go b/internal/telemetry/telemetry.go
index 58cacd132f..d131d6fc16 100644
--- a/internal/telemetry/telemetry.go
+++ b/internal/telemetry/telemetry.go
@@ -132,8 +132,9 @@ const (
PulseIntelligenceTelemetryWindow = installIDRotationWindow
// TelemetrySchemaVersion identifies the exact outbound payload contract.
- // Increment this when fields or their semantics change.
- TelemetrySchemaVersion = 2
+ // Schema v3 makes notification_failures_7d a terminal-delivery count;
+ // schema v2 counted every unsuccessful retry attempt.
+ TelemetrySchemaVersion = 3
)
type installIDRecord struct {
@@ -228,7 +229,9 @@ type Ping struct {
AlertsResolved30d int `json:"alerts_resolved_30d"`
NotificationAttempts7d int `json:"notification_attempts_7d"`
NotificationDeliveries7d int `json:"notification_deliveries_7d"`
- NotificationFailures7d int `json:"notification_failures_7d"`
+ // NotificationFailures7d counts only terminal failed/dead-letter outcomes.
+ // Retry-attempt failures remain represented in NotificationAttempts7d.
+ NotificationFailures7d int `json:"notification_failures_7d"`
// Pulse Intelligence usage (30-day counts/booleans — no prompts, commands, outputs, resource IDs, or token values)
PulseIntelligenceLoopConfigured bool `json:"pulse_intelligence_loop_configured"`
diff --git a/scripts/telemetry_adoption_report.py b/scripts/telemetry_adoption_report.py
index 89d089a422..e5e8416d88 100644
--- a/scripts/telemetry_adoption_report.py
+++ b/scripts/telemetry_adoption_report.py
@@ -84,9 +84,18 @@ USER_BASE_COUNT_FIELDS = (
("alerts_fired_30d", "Alerts fired (30d)"),
("alerts_acknowledged_30d", "Alerts acknowledged (30d)"),
("alerts_resolved_30d", "Alerts resolved (30d)"),
- ("notification_attempts_7d", "Notification attempts (7d)"),
+ ("notification_attempts_7d", "Notification attempts, including retries (7d)"),
("notification_deliveries_7d", "Notification deliveries (7d)"),
- ("notification_failures_7d", "Notification failures (7d)"),
+)
+NOTIFICATION_FAILURE_COUNT_SIGNALS = (
+ (
+ "notification_attempt_failures_7d_schema_v2",
+ "Notification failed attempts (7d, legacy schema v2)",
+ ),
+ (
+ "notification_terminal_failures_7d_schema_v3",
+ "Notification terminal failures (7d, schema v3+)",
+ ),
)
PULSE_INTELLIGENCE_ASSISTANT_LOOP_BOOL_FIELDS = (
"pulse_intelligence_assistant_operations_loop_30d",
@@ -1816,7 +1825,7 @@ def summarize_user_base_signals(
}
count_signals = {
field: {"field": field, "label": label, "installs": 0, "total": 0}
- for field, label in USER_BASE_COUNT_FIELDS
+ for field, label in USER_BASE_COUNT_FIELDS + NOTIFICATION_FAILURE_COUNT_SIGNALS
}
for row in active_rows:
@@ -1833,6 +1842,15 @@ def summarize_user_base_signals(
if value > 0:
count_signals[field]["installs"] += 1
count_signals[field]["total"] += value
+ failure_value = parse_optional_nonnegative_int(row.get("notification_failures_7d"))
+ if failure_value > 0:
+ failure_field = (
+ "notification_terminal_failures_7d_schema_v3"
+ if schema_version >= 3
+ else "notification_attempt_failures_7d_schema_v2"
+ )
+ count_signals[failure_field]["installs"] += 1
+ count_signals[failure_field]["total"] += failure_value
return {
"window": "7d",
@@ -2121,6 +2139,10 @@ def format_text(summary: dict[str, Any], repo: str, since_days: int) -> str:
"- interpretation: known install age begins when schema v2 lifecycle tracking is first initialized; "
"older upgraded installs are therefore lower bounds"
)
+ lines.append(
+ "- notification failure semantics: schema v2 counted unsuccessful retry attempts; "
+ "schema v3+ counts only terminal failed or dead-letter outcomes"
+ )
pulse_loop = summary.get("pulse_intelligence_value_loop_7d")
if pulse_loop:
diff --git a/scripts/tests/test_telemetry_adoption_report.py b/scripts/tests/test_telemetry_adoption_report.py
index a7b039eaf0..07f6f6ceed 100644
--- a/scripts/tests/test_telemetry_adoption_report.py
+++ b/scripts/tests/test_telemetry_adoption_report.py
@@ -1391,6 +1391,48 @@ class TelemetryAdoptionReportTest(unittest.TestCase):
"total": 3,
})
+ def test_summarize_user_base_signals_keeps_notification_failure_semantics_separate(self) -> None:
+ now = datetime(2026, 7, 23, 12, tzinfo=timezone.utc)
+ summary = report.summarize_user_base_signals(
+ {
+ "legacy-attempt-failures": {
+ "received_at": "2026-07-23 10:00:00",
+ "schema_version": 2,
+ "notification_attempts_7d": 5,
+ "notification_deliveries_7d": 1,
+ "notification_failures_7d": 4,
+ },
+ "terminal-failures": {
+ "received_at": "2026-07-23 11:00:00",
+ "schema_version": 3,
+ "notification_attempts_7d": 4,
+ "notification_deliveries_7d": 2,
+ "notification_failures_7d": 1,
+ },
+ },
+ now=now,
+ )
+
+ signals = {item["field"]: item for item in summary["count_signals"]}
+ self.assertEqual(
+ signals["notification_attempt_failures_7d_schema_v2"],
+ {
+ "field": "notification_attempt_failures_7d_schema_v2",
+ "label": "Notification failed attempts (7d, legacy schema v2)",
+ "installs": 1,
+ "total": 4,
+ },
+ )
+ self.assertEqual(
+ signals["notification_terminal_failures_7d_schema_v3"],
+ {
+ "field": "notification_terminal_failures_7d_schema_v3",
+ "label": "Notification terminal failures (7d, schema v3+)",
+ "installs": 1,
+ "total": 1,
+ },
+ )
+
def test_format_text_includes_user_base_privacy_bounded_signals(self) -> None:
rendered = report.format_text(
{