Skip to content

feat: implement reliable notification delivery with stream reclaimer - #823

Merged
pikann merged 6 commits into
masterfrom
feature/enhance-notification-feature
Nov 23, 2026
Merged

pikann merged 6 commits into
masterfrom
feature/enhance-notification-feature

Conversation

@pikann

@pikann pikann commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Makes sure a user always receives a notification. Notifications were stored reliably but delivered on a best-effort basis: the realtime announcement is fire-and-forget Pub/Sub, email was sent at most once, errors were swallowed, and a client that missed an announcement had no way to catch up. This PR closes those gaps end to end, adds Web Push and Do Not Disturb, and adds the observability to tell when delivery is not working.

A plan with the reasoning behind each decision is in docs/notification-reliability-plan.md.

Type of Change

Other: feature (backend, web, one migration).

What changed

1. The client always catches up (web)

  • After a socket reconnect, and once a minute while the tab is visible, the app re-reads everything under ["notifications"] (useNotificationCatchUp). Pub/Sub keeps nothing for a client that was away, so the database is the source of truth.
  • Errors that used to be discarded when creating or announcing a notification are now logged.

2. Stream consumers no longer lose or stall entries (worker)

  • A stream reclaimer (XAUTOCLAIM) redelivers entries left unacknowledged, including ones owned by a dead pod's consumer name, and dead-letters an entry after 5 deliveries to <stream>.dead with a reason. It runs on the assignment, plugin-event and question consumers. Delivery is now at-least-once.
  • A failed insert of a mention notification is retried, and its error is returned to the caller.

3. Delivery outbox (notification_deliveries)

  • A notification and its realtime delivery are inserted in one transaction. The creating request publishes right away and marks the delivery sent; a dispatcher (FOR UPDATE SKIP LOCKED, exponential backoff, 8 attempts, expiry after 15 minutes) retries what did not go out. Safe on several replicas.

4. Email is retried (platform/plugin, worker)

  • The core already owns paca.send_email, so it records the outcome of each send made while a plugin handles an event, with no change to the plugin ABI. A retryable failure (connection refused, timeout, SMTP 4xx) leaves the stream entry unacknowledged and the reclaimer redelivers it, running only the plugins that failed. A permanent failure (SMTP 5xx, invalid address) is parked on the dead-letter stream with its reason.

5. Coverage gaps

  • A mention in a document body or a task description now creates an in-app notification as well as the email event. Agents and service accounts have no inbox and are skipped.

6. Web Push and preferences

  • Browser push subscriptions, per-type push preferences, and a VAPID key pair generated on first use (encrypted when ENCRYPTION_KEY is set). A push delivery is queued with the notification only when the recipient has a subscription and has not switched the type off. Subscriptions the push service reports gone are deleted; sends go through the SSRF-guarded client and only to https endpoints.
  • A service worker shows the notification and opens the right page. Push is on by default for a browser: opening Account → Preferences subscribes it unless the user switched it off or notifications are blocked.
  • New dependency: github.com/SherClockHolmes/webpush-go.

7. Do Not Disturb

  • One switch per account, with an end time or "until I turn it off". Enforced in the single place every push passes through and evaluated when the push is due. It also silences the in-app chime; the inbox and the bell badge keep counting.

8. Notification popover UX (web)

  • Grouped by day with a sticky header, an All / Unread filter, mark-as-read per row, loading and error states, a settings link, Do Not Disturb awareness, and a one-line prompt to turn on push (a click, which Safari and Firefox need before they show the permission prompt). Opening a notification closes the popover.

9. Observability

  • GET /api/v1/admin/notifications/health (gated on settings:write) reports per-channel backlog, failures, delivery latency (p50/p95) and top failure reasons, plus unacknowledged and dead-letter entries per stream, and folds them into ok / degraded / failing with plain-language reasons. An admin page (Admin → Settings → Notification delivery) shows it.
  • Each dispatcher logs a summary line every 5 minutes (Warn when anything failed or expired).
  • There is no metrics system in the API, so this adds no Prometheus dependency or endpoint.

Migration

One migration, 000097_notification_reliability.sql, in three labelled parts: the delivery outbox, Web Push (subscriptions, per-type preferences, VAPID keys) and Do Not Disturb. Every statement is idempotent.

Not in this PR

Chat, calls and the meeting assistant are not on master, so pushes for direct messages, chat mentions, incoming calls and assistant proposals are not included. They were built against release/v1.0.0 and need porting once those features land.

Known limits

  • Push text is rendered on the server in English (it has no per-user locale).
  • The service worker always shows a push and closes it after 4 seconds when the app is focused, because Safari revokes subscriptions whose pushes show nothing.
  • Do Not Disturb does not silence email (the SMTP plugin has its own opt-out) and has no schedule.
  • A plugin that fails before it tries to send (not configured, recipient opted out) looks like success to the host. A trap or timeout in plugin code is still not retried.

Testing

  • Go: go vet and the unit tests pass for the whole API module. New Postgres-backed tests (outbox claim and SKIP LOCKED, push repository, preferences, Do Not Disturb, delivery stats) pass against a real Postgres.
  • Web: typecheck, Biome and the full Vitest suite pass; all new strings are translated in the 9 locales.
  • E2E (new, apps/e2e/tests/realtime/notification-delivery.spec.ts, Chromium, against a stack rebuilt from this branch): a notification assigned while the browser is offline, while the announcement is lost with the socket still up (found by the 1-minute re-read), and while the realtime service is down. The last one stops the stack's realtime service, so it only runs with E2E_ALLOW_STACK_RESTART=1.
  • Not exercised: a real push service and real browsers' permission flow, and the popover has been checked in tests but not reviewed visually here.

- Introduced a stream reclaimer to handle unacknowledged entries in Redis streams, ensuring at-least-once delivery semantics.
- Enhanced PluginEventConsumer to support retry logic for failed plugin deliveries, allowing targeted retries for specific plugins.
- Added StreamInspector to monitor the health of notification streams, reporting pending and dead-letter entries.
- Created a new database migration for notification delivery outbox, web push subscriptions, and user notification settings.
- Implemented tests for PluginEventConsumer, StreamReclaimer, and StreamInspector to ensure reliability and correctness of notification delivery.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

One must-fix before merge: the push dispatcher performs outbound HTTPS inside the ClaimDue transaction, which that method's own contract forbids — details inline. The rest of the review is minor.

Approach: sound in the main — the DB outbox, XAUTOCLAIM reclaimer, per-plugin retries and client refetch catch-up are the right at-least-once pieces; only the push channel's wiring misuses the claim path.

Reviewed changes

  • Delivery outbox & dispatchers — notification_deliveries is written with the notification, the fast path marks realtime sent, and the dispatcher retries with backoff, an attempt cap, max age, pruning and periodic summary logs; the push channel reuses the same claim path.
  • Stream reclaimer & dead letters — XAUTOCLAIM every 30s over 60s idle with a 5-delivery cap, poisons copied to <stream>.dead, wired into the assignment, plugin-event and question consumers, plus a health inspector.
  • Plugin event retries — host-observed SMTP send outcomes, retryable/permanent classification, a per-entry retry set and a targeted DeliverEvent.
  • Web Push — subscription management, per-type preferences, VAPID generation/encryption, SSRF-guarded sends, 404/410 cleanup, the service worker, and Do Not Disturb enforced at send time.
  • In-app mention rows — document-content and task-description mentions now create notification rows (membership re-checked, agents skipped), with createWithRetry for transient insert failures.
  • Client catch-up & bell — reconnect/visibility/60s refetch hook, day-grouped bell with an unread filter and quick mark-read, push prompt, profile push/DND cards, DND-aware chime.
  • Admin health — gated /admin/notifications/health with channel and stream stats, status reasons and a settings page.
  • Migration, tests, i18n — 000097 tables, repository/dispatcher/reclaimer/consumer/push/handler tests, strings in all nine locales.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

Comment thread apps/web/src/lib/push-api.ts Resolved
Comment thread services/api/go.mod Resolved
… claiming

- Renamed ClaimDue to LeaseDue in NotificationRepository to better reflect its functionality of leasing deliveries.
- Updated the logic to lease pending deliveries, allowing for longer processing times without holding database locks.
- Introduced RecordOutcomes method to store outcomes of leased deliveries in a single transaction.
- Modified NotificationDeliveryDispatcher to handle leased deliveries and introduced concurrency for push notifications.
- Enhanced tests to validate the new leasing mechanism and ensure proper handling of delivery outcomes.
- Improved error handling in PluginEventConsumer and QuestionNotificationConsumer to maintain message integrity during failures.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — the leasing refactor addresses every prior thread cleanly; one minor follow-up inline.

Approach: sound — the outbox now leases rows in a short transaction and does the slow work outside it, so a slow push service no longer pins a connection or a row lock, and a sender that dies only delays its rows until the lease runs out.

Reviewed changes

  • Replaced the in-transaction ClaimDue with LeaseDue + RecordOutcomes, sending leased deliveries outside any transaction from a bounded pool, and made shutdown cancel in-flight sends without spending an attempt.
  • Hardened the plugin-event consumer: a dead-letter write that fails keeps the entry pending, and the retry set is deleted only after the ack succeeded.
  • Stopped acking a question notification whose NotifyQuestion failed, so the reclaimer repairs it.
  • Made StreamHealth surface Valkey failures instead of reading them as an empty stream.
  • Handled VAPID key rotation on both sides: the client resubscribes when the stored key differs, and the server forgets a subscription the push service rejects with 403.
  • Added tests for the lease semantics (no pinned transaction, expired lease re-leased), pooled push sends, shutdown abandonment, dead-letter/ack failure paths and the question consumer, and fixed the webpush-go // indirect drift.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — the re-registration fix works for the single-browser case; one minor gap remains inline.

Reviewed changes — reviewed the delta since the prior review (88f0844..aa1949d), a web-only change to the push preferences card.

  • Held-subscription re-registration — the auto-subscribe effect now also fires when the browser holds a subscription and the server reports subscription_count === 0, so a 403 key-mismatch delete self-heals on the next preferences visit; added a test for the dropped-subscription case and set subscription_count: 1 in the already-subscribed test.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes — reviewed the delta since the prior review (aa1949d..2deefcc), a web-only change to how the push preferences card re-registers a browser's subscription.

  • Re-registration no longer depends on the account-wide count — the subscription_count === 0 gate is gone, so a browser that already holds a subscription calls enablePush on each Preferences visit; the endpoint-unique server upsert restores a row the server dropped after a 403 key mismatch or a VAPID rotation, even while the user's other browsers stay registered.
  • Stale endpoint forgotten on key mismatch — enablePush now also posts /users/me/push/subscriptions/delete for the endpoint it replaces (best effort, scoped to the caller's account), so subscription_count stops counting a row that can never be signed again.
  • Tests updated to the new behaviour — the re-registration case now runs with subscription_count: 2, a new case pins that an opted-out browser is not re-registered, and the push-api test asserts the delete call alongside the fresh subscription.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes — reviewed the delta since the prior pullfrog review (2deefcc..79de131): five files in the push service, the delivery dispatcher, the stream reclaimer, and the plan doc.

  • Per-account subscription cap — Subscribe now evicts the account's oldest rows when it already holds maxSubscriptionsPerAccount (20) endpoints; refreshing an endpoint that is already registered evicts nothing, and the eviction arithmetic leaves exactly room for the incoming row.
  • Concurrent push fan-out — Send posts to a notification's subscriptions four at a time, collects per-index outcomes, and aggregates them after Wait, so one slow endpoint no longer serialises the rest; the loop variable is per-iteration on Go 1.26, and each goroutine gets its own webpush.Options.
  • Placeholder VAPID contact — New records that the mailto:[email protected] placeholder is in use, and a 403 under it is logged rather than deleting the subscription, since the push service may be rejecting the placeholder rather than a stale key.
  • VAPID key load failures surface — a stored raw 32-byte base64url key is used as-is; anything else must decrypt, so a rotated or missing ENCRYPTION_KEY now returns an error instead of signing with ciphertext. The heuristic cannot misclassify an encryptor output (StdEncoding, ≥40 chars).
  • Reclaimer local delivery count — when XPENDING errors or returns no row, a per-entry local claim count keeps the dead-letter cap effective instead of resetting to zero; the count is cleared on a successful read and before a dead-letter copy.
  • Idempotent dispatcher shutdown — Stop closes its channel through a sync.Once, so a second call no longer panics.
  • Tests and plan doc — added coverage for the cap, the placeholder 403, and the undecryptable key, and recorded the decisions in the plan doc's "Review follow-ups".

Verified locally at 79de131: go vet and go test -race pass for ./internal/service/push and ./internal/worker, and gofmt -l is clean on both.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

@pikann
pikann merged commit cd045af into master Nov 23, 2026
8 checks passed
@pikann
pikann deleted the feature/enhance-notification-feature branch November 23, 2026 16:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant