Skip to content
Source
Sign inSign up
pingdotgg/t3code

perf: make streaming projection and activity appends incremental #6608

Closedx1xhlol(GitHub profile, opens in a new tab)wants to merge 4 commits intomain fromrefs/pull/6608/headopened View on GitHub

What Changed

Server (ProjectionPipeline):

  • thread.message-sent no longer triggers a full refreshThreadShellSummary; it updates the projection row directly, bumping updatedAt and advancing latestUserMessageAt only for newer user messages.
  • thread.activity-appended also updates the row directly and only refreshes the shell summary for lifecycle activity kinds that can change it (user-input.requested/resolved, approval.requested/resolved, and their provider failure events). Ordinary streaming activities (commands, deltas, logs) skip the recomputation entirely.
  • Proposed-plan and explicit approval/user-input response events keep the full refresh. Every event that mutates latestTurnId, proposed plans, or pending-approval rows still refreshes, so the gated kinds are exactly the ones the summary derives from.

Client (threadReducer):

  • Appending an activity takes a fast path (plain append + updatedAt bump) only when the current array is known to be reducer-produced and therefore activityOrder-sorted, the event is in order relative to the tail, and its id is unseen. A WeakMap-backed id set keyed by array identity provides both the sortedness proof and O(1) dedup; it moves forward with each append.
  • Everything else — snapshot-loaded arrays (DB order), out-of-order arrivals, re-deliveries, resolvable context-window supersession — falls back to the previous filter + re-sort, which repairs ordering once and seeds the index so subsequent in-order appends are O(1).

Tests:

  • ProjectionPipeline: streaming messages/activities preserve latestUserMessageAt and pending counters; user-input.requested and approval lifecycle kinds still update the pending counts.
  • threadReducer: out-of-order insertion, re-delivered activity replacement (including right after fast-path appends), and snapshot-order repair (null-sequence rows in DB order get re-sorted before the fast path engages).

Why

Streaming a turn generates a high-frequency stream of thread.activity-appended and thread.message-sent events. Each one previously:

  • recomputed the full thread shell summary on the server (queries across messages/activities per event), and
  • re-filtered and re-sorted the whole activity array on the client per delta (O(n log n) per event, so O(n² log n) across a long turn).

Both costs grow with thread length and are hottest exactly when the app needs to stay responsive: during active streaming and during reconnect/sync, when the client replays buffered events after resuming a subscription. Making the projection update incremental and the common append O(1) amortized cuts redundant work on both ends without changing any observable state — the regression tests pin the fields the summary refresh used to recompute and the ordering invariant the fast path relies on.

Verification

  • vp test run apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts: 23 tests pass
  • vp test run packages/client-runtime/src/state/threadReducer.test.ts: 31 tests pass
  • Typecheck passes in apps/server and packages/client-runtime
  • Targeted lint on all four touched files passes

Checklist

  • This PR is small and focused
  • I explained what changed and why
  • I included before/after screenshots for any UI changes (no UI changes)
  • I included a video for animation/interaction changes (not applicable)

Note

Medium Risk Changes derived projection fields and client activity ordering invariants; regressions could show wrong pending counts or duplicate/misordered activities, but behavior is heavily regression-tested.

Overview Cuts hot-path work during streaming by making server projections and client activity updates incremental instead of recomputing on every delta.

Server (ProjectionPipeline): thread.message-sent now patches the thread row directly—updatedAt always advances; latestUserMessageAt only moves forward on newer user messages—instead of calling refreshThreadShellSummary. thread.activity-appended always bumps updatedAt; full shell refresh runs only when activityAffectsShellSummary matches approval/user-input lifecycle kinds (requested, resolved, provider failures). High-frequency tool/progress activities skip the cross-table re-read.

Client (threadReducer): In-order thread.activity-appended events on reducer-owned, sorted activity arrays take a fast path: append + WeakMap-backed id set for O(1) dedup. Out-of-order delivery, snapshot-loaded ordering, context-window supersession, and redeliveries still use filter + sort and rebuild the index.

Tests lock shell summary fields under streaming messages/activities and activity ordering, dedup, and snapshot repair.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 5e23afae421eac3247da67e645fb358d31239116. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Make streaming projection and activity appends incremental in thread reducer and projection pipeline

  • In ProjectionPipeline.ts, splits thread.message-sent and thread.activity-appended into dedicated projection cases: user messages advance latestUserMessageAt monotonically, streaming deltas only bump updatedAt, and activities only refresh the shell summary when their kind relates to user-input or approval lifecycle events.
  • In threadReducer.ts, adds a WeakMap-backed id index on activity arrays to enable a fast-path append for in-order activities, skipping full re-sort and dedup scans when the new activity is already sorted at the tail and unseen.
  • Out-of-order or duplicate activities still fall back to the full filter/sort path, and the id index is rebuilt after sorting.
  • Behavioral Change: streaming assistant deltas no longer trigger shell summary refreshes, reducing server-side work during active streams.
Macroscope summarized 5e23afa.
    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    2. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 3bcc83ab-8871-4ec8-872b-97592ad05587

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands.
    3. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot). Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 5b48607de1d3e40735ef96d9750449696d198068. Configure [here](https://www.cursor.com/dashboard/bugbot).
    4. Approvability

      Verdict: Needs human review

      This PR changes core projection and reducer logic from full refresh to incremental updates for streaming events. While the intent is performance optimization, the change introduces new logic paths and caching mechanisms that alter how thread state is computed - warranting human review of the correctness invariants.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    5. mInrOz(GitHub profile, opens in a new tab)commented

      Data from a self-hosted instance. Context: t3 0.0.32, Node 24, Linux LXC, measured on 2026-08-15. Our agent threads run for tens of hours.

      Symptom. The server slows down as a thread grows. The projection loop is serialized, so one large thread delays every thread on the instance.

      Measured on the live instance:

      • One thread holds 4,655 activity rows with 413 MB of payload_json in projection_thread_activities. A second thread holds 4,507 rows with 359 MB.
      • One stream produced 67,066 thread.activity-appended events for ~8,000 distinct activity ids. Task-progress ticks account for the difference.
      • Only ~30 of the 79,000 activity rows on the instance are user-input lifecycle kinds. This matches the design of this PR: ordinary streaming activities can skip the recomputation.
      • Retained server traces show refreshThreadShellSummary spans up to ~8.0 s.
      • With the default V8 heap limit, the server died with a heap OOM (SIGABRT) after 11 h to 125 h. Restart=on-failure hid the crashes. We raised --max-old-space-size to 32 GB. The crashes stopped, but GC thrash replaced them: the crash log shows average mutator utilization 0.245 and major GC pauses of 930–990 ms. The cgroup memory peaked at 42.7 GB.

      Modeled, not measured directly:

      • We replayed the exact listByThreadId query and the JSON decode against a copy of the production database. The replay costs 6.3–10.9 s per event on the large threads.
      • A cumulative model of the 413 MB thread gives ~846 GB of re-reads over its lifetime. This is a prefix-sum model, not a counter we read.

      This PR removes the dominant cost we measured: ordinary activities get a single-row upsert instead of a full refresh. The reducer fix in client-runtime also helps us — long threads lag in the UI today.

      One related point. Event volume stays quadratic for chatty tools even with this fix. Each tool.updated payload carries the full accumulated data.rawOutput. The 180-char truncation applies only to detail.

    6. Agent comment posted on behalf of @t3dotgg by Claude Fable 5.1.

      Thanks for this. Main moved under the branch (#8150 added a shell summary gate, #9032 changed streaming message projection), so I rebased the work and carried it forward in #9152. Your three commits are cherry-picked there with your authorship intact, and the squash merge will carry a Co-authored-by trailer for you. I will close this PR once #9152 merges.

    7. Agent comment posted on behalf of @t3dotgg by Claude Fable 5.1.

      Merged via #9152 as c2283ce14628127ef1758974ddab4f5b1f89d47a with a Co-authored-by trailer for you. Thanks again for the work.

Sign in to join this conversation.