Repository navigation
feat(realtime): make every mutation publish and reconnect backfill deltas - #33
Conversation
…ltas Audited every mutating route and core service. The ones that did not publish a SyncAction now do, so the whole product moves in realtime rather than most of it. The client applies each delta by patching the cache in place and never refetches a list the viewer is looking at. On reconnect the client sends its last seen sync id and the server replays only what was missed, instead of the client refetching everything. Presence shows who is viewing an issue. A delta never crosses an organization or a team boundary, covered by tests for two tabs of one user and two users in different orgs.
# Conflicts: # packages/core/src/org/invite-service.ts # packages/core/src/org/team-service.ts # packages/shared/src/events/index.ts
📝 WalkthroughWalkthroughThe PR adds resumable realtime synchronization with catch-up APIs, sync cursors, scoped action backfill, connection throttling, denied-scope reporting, notification delta publishing, local inbox updates, presence expiry, and connection-status UI. ChangesRealtime synchronization
Estimated code review effort: 5 (Critical) | ~120 minutes Sequence Diagram(s)sequenceDiagram
participant RealtimeClient
participant RealtimeServer
participant SyncRoute
participant Database
RealtimeClient->>RealtimeServer: subscribe with since cursor
RealtimeServer-->>RealtimeClient: subscribed scopes and denied scopes
RealtimeClient->>SyncRoute: request catch-up from since
SyncRoute->>Database: load newer authorized rows
Database-->>SyncRoute: scoped rows
SyncRoute-->>RealtimeClient: ordered sync actions
sequenceDiagram
participant InboxView
participant NotificationAPI
participant Publish
participant DeltaBridge
InboxView->>NotificationAPI: update notification
NotificationAPI->>Publish: build and publish notification delta
Publish-->>DeltaBridge: realtime action
DeltaBridge-->>InboxView: apply local row and unread changes
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (2)
packages/core/src/org/invite-service.ts (1)
332-371: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win
acceptInvitecreatesteam_memberrows but publishes noteam_memberdelta.
addTeamMemberemits ateam_membersync action, but here the inserted team memberships only surface through thememberaction's team scopes; clients tracking theteam_membermodel won't get a live insert and must wait for catch-up. Consider emitting ateam_memberinsert action per created row for parity withaddTeamMember, so realtime and backfill agree on how memberships appear.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/core/src/org/invite-service.ts` around lines 332 - 371, The acceptInvite flow must publish team_member insert actions for each newly created team membership. Update the action construction near the teamMember insertion and existing member action to emit one team_member insert via the same builder and payload conventions used by addTeamMember, while preserving the existing member and invitation actions.packages/core/src/realtime/backfill.ts (1)
472-498: 🗄️ Data Integrity & Integration | 🔵 Trivial | 🏗️ Heavy liftDeletes cannot be replayed by state-based catch-up.
Because loaders read only current rows, a client that misses a
deletedelta (e.g.unsubscribe, notification delete) will never learn to remove that entity on resume — catch-up emits only'update'for rows that still exist. If tombstone-accurate resume matters, consider a deletions/tombstone log keyed bysyncId; otherwise document that resume is convergent only for live rows.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/core/src/realtime/backfill.ts` around lines 472 - 498, Update the catch-up flow around SYNC_CATCHUP_MODELS and LOADERS to include deletion tombstones keyed by syncId, not only currently live rows. Convert tombstones into delete SyncActions through buildSyncAction, merge them with update actions before sorting and applying the limit, and preserve the highest-syncId and truncated calculations so missed deletes replay on resume.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/realtime/src/auth.ts`:
- Around line 119-126: Update issueScopeAllowed to enforce the same
teamScope(issue) membership required by loadIssue, rather than allowing any
principal matching the issue’s organizationId. Preserve the issue lookup and
ensure issue:<id> subscriptions are granted only to members of the issue’s team.
In `@packages/core/src/realtime/backfill.test.ts`:
- Around line 120-128: Make the test “only returns notifications addressed to
the caller” create notifications for both workspace.admin and teammate before
calling catchUp. Assert that the returned notification actions include only the
caller’s notification and exclude the teammate’s, ensuring the test exercises
the userId scoping filter.
In `@packages/core/src/realtime/backfill.ts`:
- Around line 466-499: The catchUp function must apply authorizeScope filtering
to loaded sync actions before returning them, matching realtime delivery
authorization. Filter each built action using the principal and its scopes, then
sort and slice only the authorized actions while preserving the existing syncId
and truncated calculations.
In `@packages/realtime-client/src/react.tsx`:
- Around line 205-210: Update the presence hook around the useMemo that derives
others so expiry is reevaluated as PRESENCE_TTL_MS elapses, even when stored
remains unchanged. Add a small interval or equivalent expiry-driven state tick,
include it in the memoization flow, and ensure stale entries are removed without
requiring a new presence update.
---
Nitpick comments:
In `@packages/core/src/org/invite-service.ts`:
- Around line 332-371: The acceptInvite flow must publish team_member insert
actions for each newly created team membership. Update the action construction
near the teamMember insertion and existing member action to emit one team_member
insert via the same builder and payload conventions used by addTeamMember, while
preserving the existing member and invitation actions.
In `@packages/core/src/realtime/backfill.ts`:
- Around line 472-498: Update the catch-up flow around SYNC_CATCHUP_MODELS and
LOADERS to include deletion tombstones keyed by syncId, not only currently live
rows. Convert tombstones into delete SyncActions through buildSyncAction, merge
them with update actions before sorting and applying the limit, and preserve the
highest-syncId and truncated calculations so missed deletes replay on resume.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 10adaf10-4aa2-4e21-a286-e05e310fb970
📒 Files selected for processing (33)
apps/realtime/src/auth.tsapps/realtime/src/connection.test.tsapps/realtime/src/connection.tsapps/realtime/src/server.test.tsapps/realtime/src/server.tsapps/web/src/app/api/account/profile/route.tsapps/web/src/app/api/notifications/[id]/route.tsapps/web/src/app/api/notifications/deltas.tsapps/web/src/app/api/notifications/read/route.tsapps/web/src/app/api/sync/route.tsapps/web/src/features/inbox/inbox-deltas.test.tsapps/web/src/features/inbox/inbox-view.tsxapps/web/src/lib/api/client.tsapps/web/src/lib/realtime/connection-banner.tsxapps/web/src/lib/realtime/delta-bridge.test.tsxapps/web/src/lib/realtime/delta-bridge.tsxapps/web/src/lib/realtime/provider.tsxpackages/core/src/content/doc-service.tspackages/core/src/index.tspackages/core/src/org/invite-service.tspackages/core/src/org/team-service.tspackages/core/src/realtime/backfill.test.tspackages/core/src/realtime/backfill.tspackages/core/src/work/issue-service.tspackages/db/src/schema/work.tspackages/realtime-client/src/index.test.tspackages/realtime-client/src/index.tspackages/realtime-client/src/react.tsxpackages/services/src/notifications/index.tspackages/shared/src/events/index.test.tspackages/shared/src/events/message.tspackages/shared/src/events/presence.tspackages/shared/src/events/sync.ts
…subscriptions Load catchup models concurrently and flag truncation when any single model saturates its per-model cap, gate an issue subscription on team visibility to match the read path, drop a redundant delta-handler wrapper, and make the notification-scoping backfill test create real rows.
| @@ -102,23 +171,51 @@ export interface DeltaBridgeProps { | |||
|
|
|||
| export function DeltaBridge({ organizationId, teamIds }: DeltaBridgeProps) { | |||
| const client = useQueryClient(); | |||
| const currentUserId = useCurrentUserId(); | |||
| const observeSyncId = useObserveSyncId(); | |||
There was a problem hiding this comment.
Notification backfill actions are silently dropped on reconnect
routeAction has no branch for model === 'notification', so every notification action in the backfill payload falls through all conditions and is discarded. The inbox view registers its own useDeltaHandler, but applyActions is called directly from the resume callback — it does not broadcast through the registered handler set — so InboxView's handler never sees the backfill actions.
Before this PR, InboxView called router.refresh() on every live notification delta, which acted as an implicit catch-up: the first notification that arrived after a reconnect would refresh the full inbox. This PR removes router.refresh() without providing an equivalent for the reconnect path. A user whose tab disconnects while another tab marks notifications as read will see a stale badge and stale read-state after reconnecting, and it will never self-correct (subsequent live notifications apply precisely, they do not reset the view to server state).
The simplest fix is to add a useResumeHandler in InboxView that invalidates or refetches inbox data, or to make the resume path broadcast through all registered delta handlers.
Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/web/src/lib/realtime/delta-bridge.tsx
Line: 161-175
Comment:
**Notification backfill actions are silently dropped on reconnect**
`routeAction` has no branch for `model === 'notification'`, so every notification action in the backfill payload falls through all conditions and is discarded. The inbox view registers its own `useDeltaHandler`, but `applyActions` is called *directly* from the resume callback — it does not broadcast through the registered handler set — so `InboxView`'s handler never sees the backfill actions.
Before this PR, `InboxView` called `router.refresh()` on every live notification delta, which acted as an implicit catch-up: the first notification that arrived after a reconnect would refresh the full inbox. This PR removes `router.refresh()` without providing an equivalent for the reconnect path. A user whose tab disconnects while another tab marks notifications as read will see a stale badge and stale read-state after reconnecting, and it will never self-correct (subsequent live notifications apply precisely, they do not reset the view to server state).
The simplest fix is to add a `useResumeHandler` in `InboxView` that invalidates or refetches inbox data, or to make the resume path broadcast through all registered delta handlers.
How can I resolve this? If you propose a fix, please make it concise.
Publish a sync delta for every mutation and let a reconnecting client backfill everything it missed from a cursor.
Greptile Summary
This PR adds a full realtime sync pipeline: every mutation now publishes a
SyncActiondelta to Redis, reconnecting clients send asincewatermark on re-subscribe, and a new/api/syncendpoint backfills all changed rows since that cursor. It also adds per-connection token-bucket rate limiting, aConnectionBannerfor offline/reconnecting state, and precise optimistic updates to the inbox view (replacing the previousrouter.refresh()calls).backfill.ts,/api/syncroute): parallelPromise.allloader pattern queries all 20 sync models since a cursor, sorts bysyncId, slices to a configurable page limit, and marks the pagetruncatedwhen any model overflows.maxSeenSyncId, firesonResumeon reconnect, drops denied scopes from future re-subscriptions, and terminates on bothUNAUTHORIZEDandORGANIZATION_FORBIDDENclose codes.router.refresh()withapplyNotificationDeltas, computing read/unread badge deltas from the incomingSyncActionstream, and filters own-tab echoes viaoriginClientId.Confidence Score: 4/5
Safe to merge with one functional gap: the inbox does not update on reconnect backfill for notifications.
The backfill, rate limiting, watermark deduplication, and delta routing logic are solid and well-tested. The one concrete defect is in delta-bridge.tsx: notification actions returned by /api/sync are silently discarded by routeAction, and the old router.refresh() safety net that would have caught up the inbox on the next live delta is removed. A user who disconnects while another tab changes notification read-state will see a stale inbox badge after reconnecting with no self-correction path.
apps/web/src/lib/realtime/delta-bridge.tsx — routeAction has no handler for the notification model, so notification backfill actions are dropped on reconnect.
Important Files Changed
Sequence Diagram
sequenceDiagram participant Client as Browser tab participant WS as Realtime server (WS) participant Redis as Redis pub/sub participant Web as Web server (REST) participant DB as Postgres Note over Client,DB: Normal mutation flow (every model) Client->>Web: PATCH /api/issues/:id Web->>DB: "UPDATE issue SET sync_id = nextval()" Web->>Redis: PUBLISH delta channel (SyncAction) Redis-->>WS: fan-out to subscribed connections WS-->>Client: "{type:delta, actions:[...]}" Note over Client,DB: Reconnect backfill flow Client->>WS: "{type:subscribe, scopes:[...], since:70}" WS->>WS: advanceWatermark(70) WS-->>Client: "{type:subscribed, scopes:[...], denied:[...]}" Client->>Web: "GET /api/sync?since=70" Web->>DB: "SELECT rows WHERE sync_id > 70" Web-->>Client: "{syncId:85, actions:[...], truncated:false}" Client->>Client: DeltaBridge.applyActions(catchup.actions) Client->>Client: observeSyncId(85)Prompt To Fix All With AI
Reviews (3): Last reviewed commit: "fix(realtime): parallel backfill, satura..." | Re-trigger Greptile
Context used: