Skip to content
Source
Sign inSign up
pingdotgg/t3code

perf(orchestration): per-thread shell deltas, visit throttling, event compaction #4971

Mergedjuliusmarmingemerged 3 commits intot3code/codex-turn-mapping fromrefs/pull/4971/headmerged by juliusmarminge View on GitHub

juliusmarmingecommented

Problem

Live profiling of the Alpha build on this branch (native sample, V8 CPU profile via the inspector, and server.trace.ndjson span aggregation) showed the server pinning a full core with a sustained ~4.5 MB/s write stream. Per 88.7s trace window:

  • thread.visit command storm: ~2.4 dispatches/sec while a turn is active — ChatView re-dispatched a visit on every thread updatedAt bump. 2,572 of the last 2,590 command receipts were visits; 100,626 thread.visited events (106 MB) accumulated in the event store in about a day — the #1 v2 event type.
  • ws.orchestrationV2.projectShellItems: 221 × 196 ms avg ≈ 50% of a core. Every stored event batch ran a full getShellSnapshot(): a 12-correlated-subquery SELECT over all ~1,000 threads plus an Effect-Schema decode of every thread + latest-message payload — to then extract a single thread's delta. The archived-shell subscription did this per event with no batching window.
  • Every dispatch (including visits) also ran ensureLegacyTranscript (~80 ms avg → ~20% of a core during the storm).

The v1 shell stream on main already avoids all of this by refetching only the affected aggregate per coalesced event; the v2 rewrite regressed it.

Changes

Server

  • ProjectionStore.getThreadShell(threadId): materializes one thread's shell (plus its fork-source chain for visibleItemCount) instead of every thread. getShellSnapshot now shares the same query/decoder helpers, so the two paths cannot drift.
  • ws.ts: both the live and archived shell subscriptions map each coalesced event to a per-thread shell read (restoring main's v1 design); the archived stream gains the 512/50 ms coalescing window it was missing. The wire protocol already spoke per-thread deltas — no contract or client changes.
  • ThreadManagementService: thread.visit / thread.mark-unread skip legacy-transcript hydration (they only rewrite the read-state watermark). LegacyV1ThreadImporter memoizes threads whose transcript import is already confirmed (transcript_imported_at is never reset).
  • ProjectionMaintenance.compactEventStore: full event-store compaction, forked after startup. Projections are the working state (startup verifies, never replays), so events only serve afterSequence catch-up and disaster-recovery rebuild — for full-payload state events, everything but the newest per entity is dead weight in both. Passes: superseded thread-state events (visit/unread/archive/settle/snooze/metadata/…, keeping the newest per thread plus thread.created, which verify anchors on); superseded message.updated/node.updated per entity id (turn-item.updated deliberately untouched — rebuild derives turn_item_positions from it with first-write-wins semantics); and legacy v1 thread events plus pre-migration command receipts for threads whose v2 import completed. Deletes run in paced 2k-row batches with yields so the synchronous sqlite driver never pins the event loop. VACUUM is not auto-run (it would block the connection for minutes); reclaimable free-page bytes are reported and startup logs a hint. Dry-run against the real 8.2 GB state.sqlite: ~2.1M rows pruned — 113k superseded thread-state events, 1.02M v1 events (~3 GB), 1.01M legacy receipts (~400 MB with indexes). Covered by a test asserting per-pass retention and that verify/rebuild stay valid across the deletion gaps.

Web

  • ChatView: server-side visit dispatch is throttled to one per 10 s with a trailing timer (the trailing dispatch carries the newest watermark). Unread prominence only flips on run completions (hasUnseenCompletion), so an unseen completion bypasses the throttle and publishes immediately — only mid-turn activity bumps, which carry no unread signal, are throttled. resolveThreadLastVisitedAt stays server-authoritative (a mark-unread rewind cannot be masked by a stale browser-local watermark), and the per-watermark dispatch dedupe keeps a mark-unread on the open thread sticky until new activity lands.

Expected effect

During an active turn with a thread open: shell work per event drops from O(all threads) (~196 ms) to O(1 thread), visit commands drop from ~2.4/s to ≤0.1/s, and the event store stops accumulating ~100k read-state events/day. Idle-with-open-thread sessions should dispatch zero commands.

Testing

  • apps/server: typecheck clean (except the pre-existing ProviderEventIngestor.test.ts DateTime error at the base commit, deliberately not absorbed here — it has a pending fix in a separate working tree). Orchestration-v2 test files (43 tests) and FoundationPersistence (23 tests, incl. new compaction test) pass; runtimeLayer lifecycle test now asserts getThreadShell parity with the full snapshot end-to-end.
  • apps/web: typecheck clean; full suite (1,679 tests) passes, incl. new resolveThreadLastVisitedAt cases.

Inherited base-branch breaks fixed here

The base branch's CI was already red; this PR absorbs the small fixes so its own CI can go green:

  • sendToThread now tolerates the missing user turn item for queued sends — the base branch intentionally stopped emitting it at dispatch time (it materializes when the queued turn starts), but sendToThread still demanded it, failing the ThreadLaunchService queued-follow-up test.
  • ProviderEventIngestor.test narrows the nullable retry startedAt before DateTime.toEpochMillis (the typecheck break).

Still failing on the base branch (pre-existing, out of scope here): the 5 queued_turn/* replay fixtures (await_thread_idle leaves run 1 waiting / run 2 queued — the in-flight queued-turn promotion work; fails at least as far back as the merge-main commit 33e9559b92) and the flaky OrchestratorMcpToolkit cross-provider delegation test (fails identically at the base tip).

Deliberately out of scope (follow-ups)

  • Pruning the v1 projection tables (projection_thread_activities ≈ 2.9 GB) — the v1 event rows are handled by compactEventStore above, but the v1 projection tables may still serve legacy protocol paths and the importer needs them until the last threads finish importing.
  • A VACUUM story to shrink the file on disk (needs to run offline or via VACUUM INTO + swap; not safe on the live synchronous connection).
  • The VCS remote-status broadcaster (git fetch every ~10 s) and terminal subprocess polling — pre-existing on main, not regressions from this branch.

🤖 Generated with Claude Code


Note

Medium Risk Touches live shell projection reads, event-store deletion for thread.visited, and cross-device read-state semantics; compaction is guarded by verify/rebuild tests but first-run backlog deletion is still a one-time data mutation.

Overview Cuts orchestration v2 shell-stream and thread.visit load by computing WebSocket deltas from per-thread shells instead of reloading every thread on each stored event, throttling client visit commands, and pruning redundant thread.visited rows.

Server — shell streaming: Adds getThreadShell on the projection store (target thread plus fork-source chain for visibleItemCount) and wires live and archived shell subscriptions in ws.ts to coalesce events per thread and map them through shellStreamItemFromThreadShell / archivedShellStreamItemFromThreadShell (archived stream now uses the same batching window as the live stream).

Server — visits and imports: thread.visit and thread.mark-unread no longer require legacy transcript hydration before dispatch; confirmed transcript imports are memoized in-process to skip repeated DB work on hot read paths.

Server — compaction: ProjectionMaintenance.compactReadStateEvents deletes superseded thread.visited events (keeps the newest per thread); forked after startup with logging on failure.

Web: ChatView throttles server visit dispatches to about one per 10s (trailing timer for mid-turn bumps) but dispatches immediately when there is an unseen run completion. resolveThreadLastVisitedAt treats server-tracked watermarks as authoritative (including explicit null from mark-unread) so local state does not mask rewinds.

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

Note

Add per-thread shell deltas, visit throttling, and event store compaction to orchestration

  • Adds getThreadShell to the projection store, orchestrator, and thread management service, enabling per-thread shell retrieval instead of full snapshot reads for WebSocket shell stream updates in ws.ts.
  • Implements compactEventStore in ProjectionMaintenance.ts, which deletes superseded thread-state, message/node update, and imported legacy v1 events in batched transactions; runs in the background at server startup.
  • Adds coalesceStoredThreadEvents in ShellStream.ts to deduplicate per-thread events within a batch before shell conversion.
  • Throttles thread.visit command dispatch in ChatView.tsx to at most once per 10s during active turns, with an immediate dispatch on completion.
  • Skips transcript hydration for thread.visit and thread.mark-unread commands in ThreadManagementService.ts.
📊 Macroscope summarized c43eec4. 2 files reviewed, 0 issues evaluated, 0 issues filtered, 0 comments posted

🗂️ Filtered Issues

No issues evaluated.

    1. 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: 75de4261-8fcb-4d99-be8e-9ed4a0745091

      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

      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    3. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Needs human review

      1 blocking correctness issue found. This PR introduces event compaction (deleting superseded events at startup), changes shell streaming architecture to per-thread reads, and adds client-side visit throttling. An unresolved review comment flags that compacted events may leave orphaned command receipts, potentially breaking retry semantics. These runtime behavior changes and the open correctness concern warrant human review.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    4. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Fix All in Cursor Bugbot Autofix is [ON](https://www.cursor.com/dashboard/bugbot), but a cloud agent failed to start. Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 9952f0a19e52af0369abc9c6ab07c3cbf4f07ad8. Configure [here](https://www.cursor.com/dashboard/bugbot).
    5. @@ -212,0 +325,21 @@
      325+ WHERE application_event_version = 2
      326+ AND event_type = ${eventType}
      327+ GROUP BY stream_id, json_extract(payload_json, '$.id')
      328+ )
      329+ `;
      330+ const supersededMessageRows = yield* supersededEntityRows("message.updated");
      331+ const supersededNodeRows = yield* supersededEntityRows("node.updated");
      332+
      333+ const importedLegacyEventRows = yield* sql<{ readonly sequence: number }>`
      334+ SELECT sequence
      335+ FROM orchestration_events
      336+ WHERE application_event_version = 1
      337+ AND aggregate_kind = 'thread'
      338+ AND stream_id IN (
      339+ SELECT thread_id
      340+ FROM orchestration_v2_legacy_imports
      341+ WHERE transcript_imported_at IS NOT NULL
      342+ )
      343+ `;
      344+
      345+ const deletedEventCount = yield* deleteRowsBatched({
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProjectionMaintenance.ts:345

      compactEventStore deletes superseded v2 events (e.g. duplicate thread.visited, message.updated) without deleting the corresponding orchestration_command_receipts rows. When a client retries a command using the same commandId, the receipt is still found and the command is reported as accepted, but readByCommandId now returns an empty or partial storedEvents array because the events it would have read were compacted away. This breaks the retry contract — callers and tests expect storedEvents to be retained so retrying clients can recover identifiers and event details. Consider deleting receipts for compacted v2 events alongside the events themselves, or excluding events that still have active receipts from compaction.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/ProjectionMaintenance.ts around line 345:
      
      `compactEventStore` deletes superseded v2 events (e.g. duplicate `thread.visited`, `message.updated`) without deleting the corresponding `orchestration_command_receipts` rows. When a client retries a command using the same `commandId`, the receipt is still found and the command is reported as accepted, but `readByCommandId` now returns an empty or partial `storedEvents` array because the events it would have read were compacted away. This breaks the retry contract — callers and tests expect `storedEvents` to be retained so retrying clients can recover identifiers and event details. Consider deleting receipts for compacted v2 events alongside the events themselves, or excluding events that still have active receipts from compaction.
    6. juliusmarminge merged thisa22a61d

    7. juliusmarminge closed this

Sign in to join this conversation.