Skip to content

fix(platform): deliver realtime hints and bells, reclaim the outbox - #3164

Merged
larryro merged 4 commits into
mainfrom
fix/realtime-notification-delivery
Sep 3, 2026
Merged

larryro merged 4 commits into
mainfrom
fix/realtime-notification-delivery

Conversation

@larryro

@larryro larryro commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Fixes the verified review class "realtime hints and notifications don't reach the user, and the mechanism that delivers them grows without bound" — three findings, three atomic commits, each with a colocated vitest and an integration probe proven red on main and green here.

Findings

1. Bell notifications emitted user_notification, the app listens on notification — realtime bell dead (high) → fixed

writeCoalescedNotification (every mention / assignment / review / escalation bell row) and the document-review dismissal emitted hints as user_notification; app/lib/backend/engagement.ts keys every bell read (my-unread, my-page, org-unread, org-page) under notification and use-backend-hints.ts invalidates by ['backend', orgId, hint.entity]. Nothing ever matched — a mention landed silently until a reload.

  • One source of truth: lib/shared/hint-entities.ts exports NOTIFICATION_HINT_ENTITY = 'notification', imported by the collab writer, the org-notification writer, the documents dismissal and the frontend query keys — the wire name cannot drift per call site again.
  • One helper, emitBellHint, for every personal-bell write / rewrite / cancel / dismissal. It also narrows the hint to the recipient (userId) — a bell row is one person's; before, every member in the org refetched both bells on every bell write (the sibling low finding "Per-user bell writes emit org-wide realtime hints", same three lines — folded in).
  • Mark-read / mark-all-read and the server-side review-request and ask dismissals now hint the affected reader(s) too, so other tabs drop the badge without a reload.

Tests: backend/domains/collab/service.test.ts (fake db, mocked outbox) pins entity + recipient scoping for inserted / rewritten / cancelled / read-all / dismissal; app/lib/backend/engagement.test.ts pins all four bell query keys to the shared constant; integration probe personal bell hint wire — the recipient's stream receives exactly {"entity":"notification","entityId":null}, another member's stream does not, the outbox row is user-scoped, read-all hints the reader.

2. Board drag and bulk ops skip status-change notifications and platform events (high) → fixed

moveTask (/move, the board DnD) recorded activity/audit and minted reviews but never called notifyTaskStatusChanged nor emitEvent('task.status_changed'); bulkUpdateTasks did activity only and skipped notifyTaskAssigned; handTaskToInProgressForKick did activity only; the picker did everything.

  • Extracted settleTaskStatusChange — rollup transition, activity line (= the board hint), audit row (auth-carrying doors), task.status_changed platform event (human actors), subscribers' bell — and routed the picker, the drag, the bulk bar, the mention-kick hand-off, the agent door and both review-decision legs through it (the review legs pass bell: false: the resolved bell already told subscribers). settleTaskAssigneeChange does the same for the assign verb and the bulk bar's assignee branch.
  • Deliberately unchanged: the agent lane still emits no platform event. dispatchAutomationEvent has an 'automation' origin guard but nothing passes it, so an automation reacting to task.status_changed by moving the card would re-trigger itself. Turning it on needs origin plumbing from the turn shim — noted at the seam as a follow-up.
  • The board's agent kick stays outside /move on purpose: the frontend's cross-column "choreograph" verb owns it (use-task-board-dnd.ts).
  • Side effects of one path: bulk status changes now write an audit row per task (the picker always did); the picker's status bell now lands before requestTaskReview (as the agent door always did), so a reviewer auto-subscribed by the request gets the request bell, not a redundant status bell too.

Tests: backend/domains/tasks/service.test.ts drives the doors over a fake transaction — /move and /bulk produce the picker's exact bell + event + audit, a same-column drop produces nothing, the bulk assignee branch fans out like assignTask, the kick hand-off bells and fires, the agent door bells without an event; integration probe board drag + bulk bar — a transform-only automation armed on task.status_changed, a card assigned to a teammate: drag, bulk and picker each bell the assignee (coalesced row follows the truth) and start a triggered run, 3 activity lines, 3 audit rows.

3. Realtime hint outbox grows forever — nothing deletes it (high ×2) → fixed, lazily (no cron)

app_realtime.outbox had INSERT and SELECT only; the retention sweep and schedules.ts skip it.

Design. Reclaim rides the read path: every /events poll ticks one per-process reclaimer (createOutboxReclaimer) which, at most once a minute (every second while a sweep keeps spending its whole budget, so a backlog after an idle spell drains), runs reclaimOutbox: read the oldest 500 rows by id, delete — by explicit id, never by range — the strict id-prefix of rows with created_at older than OUTBOX_RETENTION_MS (1 hour), up to 20 rounds. Steady state is one bounded PK index read and no DELETE. No migration needed (the PK is the walk order).

Retention horizon: 1 hour. A live stream is never more than one poll (300 ms; 1 s on a DB blip; 500 rows a poll) behind the tail; a browser's EventSource reconnects within seconds. An hour is three-plus orders of magnitude above any replay a connected client can need.

Safety argument — never delete a row a live/reconnecting client still needs.

  • Live streams: their cursors sit within seconds of max(id); only rows older than an hour are ever touched.
  • Reconnecting clients (Last-Event-ID): the reclaim removes a strict prefix in id order (reclaimablePrefix stops at the first in-horizon row — so an older created_at a long transaction left above a newer row is never punched out). Therefore a row at or below the client's cursor still existing proves every row above it still exists and the replay is complete. The stream checks this once, after its first read (outboxRetainsCursor), and if the cursor row is gone it sends a resync event; the web app answers by invalidating the whole ['backend', orgId] scope (backendOrgPrefix). A client away longer than the horizon thus refetches instead of trusting a cache with a hole — the horizon is a size knob, not a correctness one.
  • Empty table / cursor from another deployment: no row ≤ cursor → resync → one extra refetch, never a missed update.

Tests: backend/realtime/outbox.test.ts pins the prefix planner (incl. the skew case and the exact-cutoff edge) and the throttle (interval, catch-up, no overlap, a failing sweep stays inside); use-backend-hints.test.tsx pins resync → org-scope invalidation; integration probe realtime outbox retention — aged prefix reclaimed (5/5), the fresh row and the aged row above it survive, a second sweep deletes 0, a resume from the reclaimed cursor gets resync and stays live, a resume from the retained cursor replays with no resync. README realtime paragraph documents the retention + resync contract.

Verification

Gate Branch Base (main 6eed31e, same tests copied in)
New/extended vitest files (6 files) 30/30 green 5/5 files red: 12 failed, 7 passed (collab + engagement fail at import — no hint-entities.ts on main)
Whole platform server vitest project 370 files / 5083 tests green —
bunx tsc --noEmit (platform) exit 0 —
bunx oxlint --type-aware (touched files) + pre-commit opengrep clean, 0 findings —
backend:integration (throwaway tale-db + MinIO) 282/282 checks passed, 0 FAIL (incl. the 3 new probes) 278/282 — the 3 new probes red exactly as the findings describe (outbox: "no reclaim seam — never pruned"; bell: user_notification→org-wide, recipient hint false; board: drag/bulk event=false bell=[], audit 2/3) + one audit chain verifies (head=false) red seen in the base run only

Cross-class discoveries (not fixed here)

  • Agent-lane status doors emit no task.status_changed platform event (loop hazard without origin plumbing — see above).
  • readHintsAfter advances past id > cursor by insertion id; a long transaction whose row commits after a higher id was already read is never delivered (classic outbox id/commit-order gap) — pre-existing, independent of retention.
  • dispatchAutomationEvent's 'automation' origin guard has no caller.

The personal bell writer (writeCoalescedNotification and the document
review dismissal) emitted realtime hints as `user_notification`, while the
web app keys every bell read — unread counts and pages of both bells —
under `notification` and invalidates by that prefix. Mentions, assignments,
review requests and status bells therefore never lit the bell live; a
reload was the only way to see them.

Declare the name once in lib/shared/hint-entities.ts and import it from
both ends (the collab and org-notification writers, the engagement query
keys), so the wire contract cannot drift per call site. Route every
personal-bell write, rewrite, cancel and dismissal through one
`emitBellHint` helper that also narrows the hint to the recipient — a bell
row is one person's, so no other member refetches their bell for it — and
hint the reader on mark-read / mark-all-read and the server-side review and
ask dismissals, so other tabs drop the badge without a reload.

Tests: collab/service.test.ts pins the entity and recipient scoping over a
fake db; engagement.test.ts pins the bell query keys to the shared
constant; the integration check gains a wire probe (recipient stream gets
exactly `{"entity":"notification"}`, another member's does not, the outbox
row is user-scoped, read-all hints the reader).
The board drag (`/move`) recorded activity and audit and minted reviews but
never belled the subscribers nor fired the `task.status_changed` platform
event; the bulk bar recorded activity only and skipped the assignment
fan-out; the mention-kick hand-off recorded activity only. The sheet's
picker did everything. Moving a card — the board's primary gesture — landed
silently for the assignee and never started the org's event automations.

Extract the post-write step into `settleTaskStatusChange` (rollup, activity
+ board hint, audit for the auth-carrying doors, platform event for human
actors, subscribers' bell) and route the picker, the drag, the bulk bar,
the kick hand-off, the agent door and both review-decision legs through
it; `settleTaskAssigneeChange` does the same for the assign verb and the
bulk bar's assignee branch. The agent lane deliberately keeps emitting no
platform event: nothing passes dispatch its 'automation' origin yet, so an
automation reacting to the event by moving the card would re-trigger
itself — that plumbing is the precondition, noted at the seam.

Tests: tasks/service.test.ts drives the doors over a fake transaction and
pins that `/move` and `/bulk` produce the picker's exact bell + event +
audit, that the kick hand-off bells and fires, and that the agent door
bells without an event; the integration check gains a board probe (drag,
bulk and picker each bell the assignee and start a `task.status_changed`
event automation, one activity line and one audit row apiece).
Every mutation in every org inserts an `app_realtime.outbox` row and
nothing ever deleted one — no DELETE anywhere, the retention sweep and the
cron table both skip it. The table only serves the SSE tail (a poll behind)
and `Last-Event-ID` replays (seconds), yet it grew without bound.

Reclaim lazily from the read path instead of adding a job: every `/events`
poll ticks one per-process reclaimer that, at most once a minute (sooner
while it keeps spending its whole budget, so a backlog drains), deletes
rows older than `OUTBOX_RETENTION_MS` (1h) in bounded batches by explicit
id — always as a strict id-PREFIX (`reclaimablePrefix` stops at the first
row inside the horizon, so an older stamp a long transaction left above a
newer row is never punched out). Steady state is one bounded index read.

Safety: a client resuming from a cursor whose row the reclaim took cannot
know what it missed, so the stream checks once, after its first read, that
a row at or below the cursor still exists (the prefix rule makes that proof
exact) and otherwise sends a `resync` event; the web app answers by
invalidating the whole `['backend', orgId]` scope. The horizon is thereby a
size knob, never a correctness one.

Tests: outbox.test.ts pins the prefix planner (skew case included) and the
throttle (interval, catch-up, no overlap, a failing sweep stays inside);
use-backend-hints.test.tsx pins the resync → org-scope refetch; the
integration check gains a retention probe (aged prefix reclaimed, the fresh
row and the skewed row above it survive, a second sweep is a no-op, a
resume from the reclaimed cursor gets `resync` and stays live, a resume
from the retained cursor replays with no resync).
…tion-delivery

# Conflicts:
#	services/platform/backend/domains/tasks/reviews.ts
#	services/platform/backend/domains/tasks/service.test.ts
#	services/platform/backend/realtime/sse.ts
@larryro
larryro marked this pull request as ready for review September 3, 2026 07:01
@larryro
larryro merged commit 0f5f024 into main Sep 3, 2026
30 of 31 checks passed
@larryro
larryro deleted the fix/realtime-notification-delivery branch September 3, 2026 07:01
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