Repository navigation
fix(platform): deliver realtime hints and bells, reclaim the outbox - #3164
Merged
Merged
Conversation
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
marked this pull request as ready for review
September 3, 2026 07:01
This was referenced Sep 3, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
mainand green here.Findings
1. Bell notifications emitted
user_notification, the app listens onnotification— realtime bell dead (high) → fixedwriteCoalescedNotification(every mention / assignment / review / escalation bell row) and the document-review dismissal emitted hints asuser_notification;app/lib/backend/engagement.tskeys every bell read (my-unread,my-page,org-unread,org-page) undernotificationanduse-backend-hints.tsinvalidates by['backend', orgId, hint.entity]. Nothing ever matched — a mention landed silently until a reload.lib/shared/hint-entities.tsexportsNOTIFICATION_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.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).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.tspins 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 callednotifyTaskStatusChangednoremitEvent('task.status_changed');bulkUpdateTasksdid activity only and skippednotifyTaskAssigned;handTaskToInProgressForKickdid activity only; the picker did everything.settleTaskStatusChange— rollup transition, activity line (= the board hint), audit row (auth-carrying doors),task.status_changedplatform 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 passbell: false: the resolved bell already told subscribers).settleTaskAssigneeChangedoes the same for the assign verb and the bulk bar's assignee branch.dispatchAutomationEventhas an'automation'origin guard but nothing passes it, so an automation reacting totask.status_changedby 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./moveon purpose: the frontend's cross-column "choreograph" verb owns it (use-task-board-dnd.ts).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.tsdrives the doors over a fake transaction —/moveand/bulkproduce the picker's exact bell + event + audit, a same-column drop produces nothing, the bulk assignee branch fans out likeassignTask, 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 ontask.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.outboxhad INSERT and SELECT only; the retention sweep andschedules.tsskip it.Design. Reclaim rides the read path: every
/eventspoll 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), runsreclaimOutbox: read the oldest500rows by id, delete — by explicit id, never by range — the strict id-prefix of rows withcreated_atolder thanOUTBOX_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
EventSourcereconnects 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.
max(id); only rows older than an hour are ever touched.Last-Event-ID): the reclaim removes a strict prefix in id order (reclaimablePrefixstops at the first in-horizon row — so an oldercreated_ata 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 aresyncevent; 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.Tests:
backend/realtime/outbox.test.tspins 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.tsxpinsresync→ 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 getsresyncand stays live, a resume from the retained cursor replays with no resync. README realtime paragraph documents the retention + resync contract.Verification
main6eed31e, same tests copied in)hint-entities.tson main)servervitest projectbunx tsc --noEmit(platform)bunx oxlint --type-aware(touched files) + pre-commit opengrepbackend:integration(throwaway tale-db + MinIO)user_notification→org-wide, recipient hint false; board: drag/bulk event=false bell=[], audit 2/3) + oneaudit chain verifies(head=false) red seen in the base run onlyCross-class discoveries (not fixed here)
task.status_changedplatform event (loop hazard without origin plumbing — see above).readHintsAfteradvances pastid > cursorby 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.