Skip to content

perf(renderer): keep remote snapshot batches linear - #13676

Merged
nwparker merged 2 commits into
mainfrom
nwparker/perf-remote-snapshot-reconciliation
Aug 11, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/perf-remote-snapshot-reconciliation

Conversation

@nwparker

@nwparker nwparker commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

The one-sentence version

When a remote host sends updates for 1,200 workspaces at once, Orca used to photocopy the entire filing cabinet 1,200 times — once per workspace. Now it photocopies it once, writes all 1,200 updates into that copy, and files it. 52× faster at 1,200 workspaces.


Start here: what is actually happening

A remote Orca host tells your client about its workspaces through session.tabs snapshots — one per workspace, describing that workspace's terminals, browser pages, editors, and agent panes.

On reconnect or replay, the host does not send these one at a time. It sends a batch: every workspace at once.

The renderer stores these in maps keyed by workspace. Those maps are immutable — the standard React/Zustand rule that you never edit state in place, you make a modified copy. Reconciling one snapshot means copying the map, changing one entry, and swapping the copy in.

That rule is correct. Applying it once per workspace inside a batch is what was expensive.

flowchart TB
    subgraph BEFORE["Before — one full copy per workspace"]
        direction TB
        B1["Snapshot 1 arrives"] --> B2["Copy ALL maps (1,200 entries)"] --> B3["Edit entry 1"] --> B4["Swap in"]
        B4 --> B5["Snapshot 2 arrives"] --> B6["Copy ALL maps again"] --> B7["Edit entry 2"] --> B8["Swap in"]
        B8 --> B9["... ×1,200"]
    end

    subgraph AFTER["After — one copy for the whole batch"]
        direction TB
        A1["Batch of 1,200 arrives"] --> A2["Copy ALL maps ONCE (a draft)"]
        A2 --> A3["Edit entry 1 in the draft"] --> A4["Edit entry 2 in the draft"] --> A5["... edit entry 1,200"]
        A5 --> A6["Swap the finished draft in ONCE"]
    end
Loading

The cost of the old shape is quadratic: copying an N-entry map N times is N² work. That is why the numbers get dramatically worse as workspace count grows rather than just proportionally worse.

Measured

Synthetic reconnect fixture, one ready remote terminal and one working agent per workspace, prior sequential reducer vs. the batch path on the same machine:

Workspaces Before After Speedup
400 86.5 ms 6.8 ms 12.8×
800 338.5 ms 10.6 ms 31.8×
1,200 811.1 ms 15.5 ms 52.5×

Note the shape: workspaces triple, old cost grows ~9×, new cost grows ~2×. Quadratic became linear.

811 ms is a visibly frozen window. That is a single reconnect to one busy host.

The second change is related: looking up "which agent panes belong to this tab?" used to scan every agent pane in the app, once per workspace. Those are now indexed by owner, so an agent-heavy batch stops re-scanning globally.

Where this runs in production

  • The initial session.tabs.listAll when you connect to a remote host.
  • The batched snapshots stream event — i.e. every remote reconnect and replay, for every paired runtime environment.

Reconnects are exactly when a user is already waiting.


The behavior change you should actually review

Everything above is a pure speedup. This part is not, and it deserves a decision.

updateHostSessionTabIdMappings runs on every snapshot apply. It clears the local→host tab id mappings belonging to a worktree. Previously it did that by string prefix match:

delete every key starting with `${environmentId}:${worktreeId}:`

Worktree ids are built as ${repoId}::${absolutePath} (src/shared/pty-session-id-format.ts:15). On POSIX, absolute paths may legally contain a colon.

So consider two sibling worktrees:

Worktree Its id Its mapping keys
A repo::/w env:repo::/w:<tabId>
B repo::/w:2 env:repo::/w:2:<tabId>

Every key belonging to B also starts with the prefix computed for A. So whenever worktree A published a snapshot, it silently wiped worktree B's tab mappings.

What that looked like to a user: a wiped mapping makes tab close fall back to toHostSessionTabId(terminalTabId). The comment already in terminal-tab-actions.ts:136 describes the symptom — close "silently fell back to a local-only prune and the host's next snapshot re-added the tab." In other words: you close a tab, and it comes back. Reordering and moving tabs hit the same fallback (web-runtime-session.ts:768).

This PR replaces the prefix scan with an exact (environmentId, worktreeId) index, so only the worktree that actually published gets cleared.

This is a bug fix, not a regression — but it is a real behavior change and it should be merged as one, not waved through as "pure perf." Less reachable on Windows, where colons are not legal inside path components.

Compatibility

  • Renderer-only. Two files, both under src/renderer/src/runtime/.
  • No wire involvement whatsoever: no RPC, no stream opcode, no protocol version, no persisted schema. hostSessionTabIdByLocalKey is purely client-side bookkeeping.
  • Old and new remote hosts are unaffected. They send byte-identical snapshots either way; only how the client indexes them locally changed. A client on this build talking to a host on any older build behaves exactly as a client without it, minus the sibling-wipe bug.

Correctness argument for the batch rewrite

The risk in a copy-on-write draft is a read seeing a value that a later write in the same batch was supposed to produce, or vice versa. This was checked explicitly:

  • Every read of the 20 draft-owned record fields happens before that record's first write within a snapshot pass.
  • writableWebSessionTabsRecord(state, k, undefined) returns {...(state[k] ?? {})} — identical to the inline spreads it replaces, so the single-snapshot path is provably unchanged.
  • The agentPaneKeysByTabId index is built before the first mutation of agentStatusByPaneKey, and is kept in sync on every add and delete.
  • Key insertion order of the resulting records is unchanged.
  • Per-snapshot reducer order, scalar/array semantics, and focus/close/handoff side effects are preserved.

One invariant is load-bearing and worth naming: writableWebSessionTabsRecord mutates its state argument when a batch context is present. That is safe only because applyWebSessionTabsSnapshots hands it a shallow copy { ...state } and every read precedes its write. If someone later passes the real store state, this breaks quietly. A guard test for that invariant would be a reasonable follow-up.

activeGroupIdByWorktree now routes through a value-equality gate, so a patch that changed identity but not value is no longer emitted. Content is the same; one redundant notification disappears.

Testing

  • pnpm lint
  • pnpm typecheck
  • ORCA_CROSS_VERSION_BASELINE_REF=v1.4.177 pnpm test — 4,603 files passed, 15 skipped; 49,334 tests passed, 97 skipped
  • pnpm build
  • Renderer runtime suite — 67 files, 634 tests passed

The regression test compares the final batch result against repeated immutable single-snapshot reconciliation across terminal, agent-status, browser, editor, removal/replacement, and provisional-handoff cases — i.e. it asserts the fast path and the slow path agree, rather than asserting the fast path's own output. Also covered: input immutability, empty-batch identity, and selective same-environment mapping teardown.

The baseline ref is pinned because an unrelated repository tag named v799 currently outranks the intended release tag during automatic baseline selection.

The temporary benchmark harness used for the table above was removed from the diff.

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 416ed98f-705b-4176-9268-35b19bcf6da6

📥 Commits

Reviewing files that changed from the base of the PR and between 4c176ea and 9095681.

📒 Files selected for processing (2)
  • src/renderer/src/runtime/web-session-tabs-sync.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/renderer/src/runtime/web-session-tabs-sync.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync.ts

📝 Walkthrough

Walkthrough

Session-tab snapshot reconciliation now supports shared state mutation across snapshot batches. Host session-tab mappings use environment and worktree indexes for targeted cleanup. Agent-pane indexes and cloned records are reused during batch updates. Single-snapshot behavior remains available through the public wrapper. Tests cover empty batches, mixed and duplicate-worktree snapshots, sequential equivalence, immutability, and per-worktree cleanup.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the change and testing in detail, but it omits the required Screenshots, AI Review Report, Security Audit, and Notes sections. Add all required template sections, including explicit no-visual-change text, AI review findings, security audit coverage, and platform-specific notes.
Docstring Coverage ⚠️ Warning Docstring coverage is 9.52% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: improving renderer performance for remote snapshot batch reconciliation.
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.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/renderer/src/runtime/web-session-tabs-sync.ts (1)

1630-1650: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Bind withWorktreeEntry to the record key type.

recordKey is typed as the full WebSessionTabsBatchRecordKey union while T is inferred only from value. The two as Record<string, T> casts then erase the relation between the key and the record's element type. A mismatched pair, for example 'tabBarOrderByWorktree' with a TabGroup[] value, compiles. In batch mode the helper mutates the shared working state, so such a mismatch would write a wrong value into renderer state instead of failing type checking.

Make the helper generic over the key so the compiler enforces the pairing.

♻️ Proposed typing change
-function withWorktreeEntry<T>(
-  state: WebSessionTabsSyncState,
-  recordKey: WebSessionTabsBatchRecordKey,
-  key: string,
-  value: T | null,
-  equal: (a: T | undefined, b: T | null) => boolean,
-  batchContext?: WebSessionTabsBatchContext,
-  deleteNull = true
-): Record<string, T> {
-  const record = (state[recordKey] ?? {}) as Record<string, T>
+function withWorktreeEntry<
+  K extends WebSessionTabsBatchRecordKey,
+  T = NonNullable<WebSessionTabsSyncState[K]>[string]
+>(
+  state: WebSessionTabsSyncState,
+  recordKey: K,
+  key: string,
+  value: T | null,
+  equal: (a: T | undefined, b: T | null) => boolean,
+  batchContext?: WebSessionTabsBatchContext,
+  deleteNull = true
+): Record<string, T> {
+  const record = (state[recordKey] ?? {}) as Record<string, T>

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d23096bf-48b1-4f0f-9025-06e29faea710

📥 Commits

Reviewing files that changed from the base of the PR and between fe0ab30 and 4c176ea.

📒 Files selected for processing (2)
  • src/renderer/src/runtime/web-session-tabs-sync.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync.ts

The sibling-mapping test used a worktree id that shares no prefix with WT,
so it passed against the prefix-scan it was meant to pin. Use an id prefixed
by WT's and drain the new mapping index in the leak counters.

Co-authored-by: Orca <[email protected]>
@nwparker
nwparker merged commit a65e0c5 into main Aug 11, 2026
44 checks passed
@nwparker
nwparker deleted the nwparker/perf-remote-snapshot-reconciliation branch August 11, 2026 03:55
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* perf(renderer): keep remote snapshot batches linear

* test(renderer): cover the prefix-colliding sibling worktree

The sibling-mapping test used a worktree id that shares no prefix with WT,
so it passed against the prefix-scan it was meant to pin. Use an id prefixed
by WT's and drain the new mapping index in the leak counters.

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Orca <[email protected]>
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