Skip to content

feat(realtime): make every mutation publish and reconnect backfill deltas - #33

Merged
pulkitxm merged 4 commits into
mainfrom
feat/s4-realtime
Jul 23, 2026
Merged

pulkitxm merged 4 commits into
mainfrom
feat/s4-realtime

Conversation

@pulkitxm

@pulkitxm pulkitxm commented Jul 23, 2026 •

Copy link
Copy Markdown
Member

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 SyncAction delta to Redis, reconnecting clients send a since watermark on re-subscribe, and a new /api/sync endpoint backfills all changed rows since that cursor. It also adds per-connection token-bucket rate limiting, a ConnectionBanner for offline/reconnecting state, and precise optimistic updates to the inbox view (replacing the previous router.refresh() calls).

  • Backfill infrastructure (backfill.ts, /api/sync route): parallel Promise.all loader pattern queries all 20 sync models since a cursor, sorts by syncId, slices to a configurable page limit, and marks the page truncated when any model overflows.
  • Realtime client & provider: the client now tracks maxSeenSyncId, fires onResume on reconnect, drops denied scopes from future re-subscriptions, and terminates on both UNAUTHORIZED and ORGANIZATION_FORBIDDEN close codes.
  • Inbox view: replaces router.refresh() with applyNotificationDeltas, computing read/unread badge deltas from the incoming SyncAction stream, and filters own-tab echoes via originClientId.

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

Filename Overview
apps/web/src/lib/realtime/delta-bridge.tsx Adds reconnect backfill handler and refined routeAction routing; notification model actions from backfill are silently dropped, leaving the inbox stale after reconnect while removing the old router.refresh() safety net.
packages/core/src/realtime/backfill.ts New file: parallel loaders for all 20 sync models, overflow detection, sort-and-slice to CATCHUP_LIMIT; the per-model +1 probe query correctly fixes the previous false-negative truncation issue.
apps/realtime/src/connection.ts Adds token-bucket rate limiter, per-connection watermark, and returns rejected scopes from addScopes; logic is clean and well-tested.
apps/realtime/src/server.ts Wires rate limiting and watermark-aware subscribe handling; partitionScopes now returns both accepted and denied arrays; presence TTL moved to shared package.
packages/realtime-client/src/index.ts Client tracks maxSeenSyncId, fires onResume on reconnect with the watermark, removes denied scopes from the active set, and treats both terminal close codes correctly.
packages/realtime-client/src/react.tsx Adds useResumeHandler and useObserveSyncId hooks; clears presence on status changes other than open; isFresh filtering of stale presence records.
apps/web/src/features/inbox/inbox-view.tsx Replaces router.refresh() with applyNotificationDeltas for live deltas; precise badge delta accounting; no reconnect backfill handling (notification model is silently dropped by DeltaBridge).
apps/realtime/src/auth.ts Expands issueScopeAllowed to grant admin role access to all issues in their org regardless of team membership; intentional permissions expansion.
packages/shared/src/events/sync.ts Adds issue_subscription, team_member, doc_collection, invitation to SYNC_MODELS; adds cursor/catchup Zod schemas and CATCHUP_LIMIT constant.
packages/db/src/schema/work.ts Adds syncId column to issueSubscription table with default 0; requires a schema migration on deploy.

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)
Loading

Fix All in Claude Code

Prompt To Fix All With AI
Fix the following 1 code review issue. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 1
apps/web/src/lib/realtime/delta-bridge.tsx:161-175
**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.

Reviews (3): Last reviewed commit: "fix(realtime): parallel backfill, satura..." | Re-trigger Greptile

Greptile also left 1 inline comment on this PR.

Context used:

  • Context used - CLAUDE.md (source)

pulkitxm added 2 commits July 24, 2026 00:17
…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
@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The 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.

Changes

Realtime synchronization

Layer / File(s) Summary
Sync contracts and presence freshness
packages/shared/src/events/*
Adds catch-up schemas, sync cursors, new sync models, denied scopes, and shared presence freshness handling.
Sync IDs and catch-up loaders
packages/db/src/schema/work.ts, packages/core/src/realtime/*, packages/core/src/org/*, packages/core/src/content/*, packages/core/src/work/*, apps/web/src/app/api/sync/route.ts
Persists sync IDs across synchronized records and exposes authorized, ordered catch-up actions through a new API route.
Server authorization, watermarking, and throttling
apps/realtime/src/*
Adds organization-based issue authorization, subscription overflow reporting, monotonic watermarks, token-bucket message limiting, and presence TTL behavior.
Client resume and presence lifecycle
packages/realtime-client/src/*
Tracks observed sync IDs, resumes subscriptions after reconnects, removes denied scopes, and filters stale presence messages.
Web delta routing and local state
apps/web/src/features/inbox/*, apps/web/src/lib/realtime/*, apps/web/src/lib/api/client.ts
Routes realtime actions through cache patching and invalidation, updates inbox state locally, adds origin-client headers, and renders connection status.
Mutation publishing and notification synchronization
apps/web/src/app/api/account/profile/route.ts, apps/web/src/app/api/notifications/*, packages/services/src/notifications/index.ts
Publishes profile and notification mutations with sync metadata and transport-normalized notification actions.

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
Loading
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
Loading

Possibly related PRs

  • Noveum/orbit#12: Adds the origin client ID mechanism used to suppress same-tab realtime echoes.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: publishing mutations and replaying missed realtime deltas on reconnect.
Description check ✅ Passed The description is directly aligned with the changeset, describing mutation publishing and cursor-based backfill.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/s4-realtime

Comment @coderabbitai help to get the list of available commands.

Comment thread packages/core/src/realtime/backfill.ts Resolved
Comment thread packages/core/src/realtime/backfill.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (2)
packages/core/src/org/invite-service.ts (1)

332-371: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

acceptInvite creates team_member rows but publishes no team_member delta.

addTeamMember emits a team_member sync action, but here the inserted team memberships only surface through the member action's team scopes; clients tracking the team_member model won't get a live insert and must wait for catch-up. Consider emitting a team_member insert action per created row for parity with addTeamMember, 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 lift

Deletes cannot be replayed by state-based catch-up.

Because loaders read only current rows, a client that misses a delete delta (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 by syncId; 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

📥 Commits

Reviewing files that changed from the base of the PR and between e5473ef and 6112d1b.

📒 Files selected for processing (33)
  • apps/realtime/src/auth.ts
  • apps/realtime/src/connection.test.ts
  • apps/realtime/src/connection.ts
  • apps/realtime/src/server.test.ts
  • apps/realtime/src/server.ts
  • apps/web/src/app/api/account/profile/route.ts
  • apps/web/src/app/api/notifications/[id]/route.ts
  • apps/web/src/app/api/notifications/deltas.ts
  • apps/web/src/app/api/notifications/read/route.ts
  • apps/web/src/app/api/sync/route.ts
  • apps/web/src/features/inbox/inbox-deltas.test.ts
  • apps/web/src/features/inbox/inbox-view.tsx
  • apps/web/src/lib/api/client.ts
  • apps/web/src/lib/realtime/connection-banner.tsx
  • apps/web/src/lib/realtime/delta-bridge.test.tsx
  • apps/web/src/lib/realtime/delta-bridge.tsx
  • apps/web/src/lib/realtime/provider.tsx
  • packages/core/src/content/doc-service.ts
  • packages/core/src/index.ts
  • packages/core/src/org/invite-service.ts
  • packages/core/src/org/team-service.ts
  • packages/core/src/realtime/backfill.test.ts
  • packages/core/src/realtime/backfill.ts
  • packages/core/src/work/issue-service.ts
  • packages/db/src/schema/work.ts
  • packages/realtime-client/src/index.test.ts
  • packages/realtime-client/src/index.ts
  • packages/realtime-client/src/react.tsx
  • packages/services/src/notifications/index.ts
  • packages/shared/src/events/index.test.ts
  • packages/shared/src/events/message.ts
  • packages/shared/src/events/presence.ts
  • packages/shared/src/events/sync.ts

Comment thread apps/realtime/src/auth.ts Resolved
Comment thread packages/core/src/realtime/backfill.ts Resolved
Comment thread packages/realtime-client/src/react.tsx Resolved
…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.
Comment on lines 161 to +175
@@ -102,23 +171,51 @@ export interface DeltaBridgeProps {

export function DeltaBridge({ organizationId, teamIds }: DeltaBridgeProps) {
const client = useQueryClient();
const currentUserId = useCurrentUserId();
const observeSyncId = useObserveSyncId();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 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.

Fix in Claude Code

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