Skip to content

perf(remote): read the repo catalog once per publish, not once per worktree - #18410

Merged
nwparker merged 3 commits into
mainfrom
perf/remote-export-repo-lookup
Sep 4, 2026
Merged

nwparker merged 3 commits into
mainfrom
perf/remote-export-repo-lookup

Conversation

@nwparker

@nwparker nwparker commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​95 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​92
Prod 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​46 $\color{#cf222e}{\Huge{\mathbf{−}}}$​8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​38

ELI5

When Orca publishes your workspace to a connected SSH host, it walks every worktree and asks "does this one belong to that host?"

To answer, it fetched the entire repo catalog and re-built it from scratch — every single time, for every single worktree. 413 worktrees meant 413 full catalog rebuilds to answer 413 yes/no questions, and the catalog is identical every time.

Now it fetches the catalog once and asks 413 cheap questions against it.

Why it matters

remoteWorkspace:setForConnectedTargets is the second most expensive IPC handler in Orca's main process. Measured live against the packaged app with a probe wrapping all 746 ipcMain invoke handlers:

measured
call rate 0.48 calls/sec
main-thread time per call 13 ms
share of total wall-clock CPU 0.63%

And in a 30-second CPU profile of the same running main process, the repo normaliser reached through hydrateRepo was the #2 self-time function in the whole process at 0.25%, sitting under exactly this call chain:

0.40%  exportRemoteWorkspaceSession
0.34%    isTargetWorktree            ← runs once per worktree
0.33%      targetForWorktree
0.33%        store.getRepos()        ← full catalog re-hydration, per worktree
0.33%          hydrateRepo
0.31%            <repo normaliser>   ← 8 conditional spreads + new URL() per repo

createRepoRowExecutionHostLookup also filters the catalog on each lookup, so the old shape was O(worktrees × repos) allocations per publish on top of the hydration.

Measurement

On the reporter's real session — 413 worktrees, 13 repos, 1 connected target:

before after
store.getRepos() calls per publish 413 1
hydrateRepo calls per publish 5,369 13
lookup objects allocated per publish 413 1

Deterministic regression guard in remote-workspace.test.ts — a 12-worktree session, counting catalog reads:

without the fix:  AssertionError: expected "vi.fn()" to be called 1 times, but got 12 times
with the fix:     1

The count scales 1:1 with worktree count, so at the reporter's 413 it is 413 → 1.

Correctness

Negative user-facing trade-offs

None. This is deleted work, not a traded-off behaviour.

  • The exported remote session is byte-for-byte identical.
  • No caching across calls — the catalog is still re-read on every publish, so a repo added or removed between publishes is picked up exactly as before.
  • No new cadence, cap, debounce or threshold.

Test plan

  • src/main/ipc/remote-workspace.test.ts — 1 new test; verified to fail without the fix (12 vs 1).
  • Existing 7 tests in that file still pass (ownership resolution, hydrated-target gating, stale-revision, host-observation-token).
  • tsc -p config/tsconfig.node.json clean; oxlint clean.

Update: second commit — resolve each worktree's owning target once per publish, not once per target

Hoisting store.getRepos() removed the repeat hydration, but the ownership resolution was still repeated once per connected target. targetForWorktree computes a connection id from the repo catalog alone — only the final === targetId differs — so exporting to N targets ran the identical resolution N times over every worktree key. And the projection asks the question once per key of tabsByWorktree, activeTabIdByWorktree, lastVisitedAtByWorktreeId and defaultTerminalTabsAppliedByWorktreeId, so it is roughly 4-5x the worktree count per target.

Resolutions are now memoised for the life of one publish, keyed on (worktreeId, executionHostId) — both participate in resolution, so both must participate in the key.

New regression guard, 6 worktrees x 2 targets:

without the memo:  AssertionError: expected 12 to be 6
with the memo:     6

Combined effect at the reporter's scale (413 worktrees, 13 repos):

per publish before after
store.getRepos() calls 413 x targets 1
hydrateRepo calls 5,369 x targets 13
resolveWorktreeExecutionHost calls ~413 x targets (x4-5 key maps) once per distinct worktree
lookup objects allocated 413 x targets 1

Correctness is unchanged from above: the memo lives entirely inside one synchronous publish and is discarded afterwards, so a repo added or removed between publishes is picked up exactly as before. NUL is the key separator because it cannot occur in a worktree or host id.

Negative user-facing trade-offs: still none. No cross-call caching, no staleness window, identical exported bytes.


Update: third commit — keep the disconnected path free of the hoisted read

Review caught a real regression the hoist introduced: before this PR the catalog was only read
inside isTargetWorktree, which never runs when no hydrated target is currently connected. Hoisting
it made a zero-connected-target publish pay for a full repo hydration it previously never did —
on a handler that fires ~0.48 times/sec, so the idle/disconnected case is the common one.

A zero-target publish already fell through to Promise.all([]).filter(...) → [], so the handler
now returns early instead:

if (targets.length === 0) {
  // Nothing to project onto, so skip the session and repo-catalog reads entirely.
  return []
}

That also drops the pre-existing store.getWorkspaceSession() read on the same path. The return
value is unchanged ([] either way). New regression guard, verified to fail without it
(getRepos called 1 time, expected 0).

Note on the rebase

createRepoRowExecutionHostLookup no longer re-filters the catalog per lookup — #18416 landed
that indexing on main after this PR was opened. That part of the "Why it matters" section above is
now historical; the win claimed here is the removed hydration and the removed repeated
resolution, both of which are orthogonal to #18416 and still measured as stated.

Linked Issue

N/A — no tracked issue. Found by profiling the packaged main process (ipcMain invoke-handler probe
plus a 30-second CPU profile); the call chain and measurements are in "Why it matters" above.

Visual Proof

N/A — no visual or interaction change. This is a pure main-process optimization: the exported
remote session is byte-for-byte identical, so nothing renders differently.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

pnpm test src/main/ipc/remote-workspace.test.ts — 10 passed. Each of the three perf guards was
verified to fail when its fix is reverted:

guard without the fix with the fix
catalog read once per publish (12 worktrees) getRepos 12x 1x
ownership resolved once per publish (6 worktrees x 2 targets) 12 resolutions 6
disconnected path reads nothing getRepos 1x 0x

Also green: pnpm tc:node, oxlint, oxfmt --check, pnpm run check:code-quality:changed
(0 new findings), and src/shared/worktree-execution-host-resolution.test.ts (15 passed) to confirm
the rebase onto #18416 composes.

Platforms: the change is platform-agnostic (no paths, no shell, no process spawning). Exercised on
macOS. SSH is the subject of the change rather than a caveat — this handler only ever runs for
connected SSH targets, and the SSH execution boundary is untouched: ownership still resolves against
the repo catalog on the execution host, and unresolvable ownership still exports to nobody rather
than guessing (#11163).

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Security — no new inputs, no new trust boundary; store.getRepos() is a pure read that was already on this path.
  • Cross-platform — no platform-dependent code touched.
  • Remote SSH / wire compatibility — no wire change. The exported session bytes, revision stream, stale-revision handling and host-observation-token checks are all identical; nothing new is published to a host, so old clients see exactly what they saw before.
  • Folder workspaces — ownership resolution is keyed on repo id + host id, not on worktree-ness, so folder workspaces resolve exactly as before.
  • Git provider — not applicable; no provider-specific code.
  • Backwards compatibility — no caching across calls. The catalog is still re-read every publish, so a repo added or removed between publishes is picked up exactly as before.
  • Performance — the point of the PR; see the tables above.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@coderabbitai

coderabbitai Bot commented Sep 3, 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: Team

Run ID: febbe81a-7402-433a-91e5-173113b8cec9

📥 Commits

Reviewing files that changed from the base of the PR and between 7ed86a9 and 204d54f.

📒 Files selected for processing (2)
  • src/main/ipc/remote-workspace.test.ts
  • src/main/ipc/remote-workspace.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/ipc/remote-workspace.ts
  • src/main/ipc/remote-workspace.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.


📝 Walkthrough

Walkthrough

The remote workspace publish handler now creates one repository execution-host lookup and one memoizing worktree target resolver per publish. Target export functions reuse this resolver across connected targets. The handler skips session and repository reads when no target is connected. Tests verify catalog-read reuse, worktree-resolution reuse, and the idle path.

Merge Risk: ⚪ Minimal · up to 204d5

Remote workspace publishing now reuses repository and worktree resolution within a publish while preserving existing session behavior. The idle-path regression is covered, and no current merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description is detailed and covers the change, rationale, testing, visual proof, review notes, and checklist. However, the required Linked Issue section is marked N/A even though the template requ… Add the tracked issue link in the Linked Issue section. If no issue exists, create or associate one before merging, because the repository template requires a linked issue for every pull request.
✅ Passed checks (3 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 and concisely describes the primary optimization: reading the repository catalog once per publish instead of once per worktree.
Full details: Description check

Explanation

The description is detailed and covers the change, rationale, testing, visual proof, review notes, and checklist. However, the required Linked Issue section is marked N/A even though the template requires an issue link.

  • Fix all pre-merge checks with AI
✨ 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.

@pullfrog pullfrog 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.

ℹ️ Minor suggestion only — one edge case on the zero-target path.

Reviewed changes

  • Hoist the repo catalog read — createRepoRowExecutionHostLookup(store.getRepos()) now runs once per publish rather than once per worktree, threaded through exportSessionForTarget → targetForWorktree.
  • Regression guard — getRepos becomes a tracked vi.fn, and a new test asserts a 12-worktree publish reads the catalog exactly once.

The optimization is sound: exportRemoteWorkspaceSession is synchronous, and every exportSessionForTarget call runs to completion inside the targets.map callback before the first await, so the hydrated rows cannot change between the hoist and the last use. The shared lookup is also target-independent (resolution compares the resolved connection id against targetId), so reusing one snapshot across all targets is correct.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Comment thread src/main/ipc/remote-workspace.ts Resolved

@pullfrog pullfrog 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.

ℹ️ No critical issues — the memoization is sound; one comment nit inline.

Reviewed changes

  • Memoised per-worktree ownership resolution — createWorktreeTargetResolver caches targetForWorktree results for the life of a single publish, keyed on (worktreeId, executionHostId), so exporting to N targets resolves each worktree once instead of N times.
  • Added a resolution-count regression guard — a new test wraps resolveWorktreeExecutionHost with a call counter and asserts a 6-worktree × 2-target publish resolves ownership exactly 6 times.

The memoization is correct: within one publish targetForWorktree is a pure function of (worktreeId, executionHostId) given a fixed repoLookup, so caching the resolved connection id (or null) across targets is safe. The Map correctly distinguishes a cached null from a missing entry via cached !== undefined, and executionHostId participates in the key, which matters because the lastVisitedAtByWorktreeId loop resolves host-qualified keys with a non-null host id that changes the answer. The NUL separator is collision-free since neither id can contain NUL.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Comment thread src/main/ipc/remote-workspace.ts Resolved
…rktree

`remoteWorkspace:setForConnectedTargets` costs 13 ms of main-thread time per
call at 0.48 calls/sec — 0.63% of wall on a real session, the second most
expensive IPC handler in the main process.

Almost all of it is one line. `exportRemoteWorkspaceSession` asks
`isTargetWorktree(worktreeId)` once per worktree in the session, and that
callback called `targetForWorktree(store, ...)`, which called
`store.getRepos()` — and `getRepos()` maps `hydrateRepo` over every repo row.
So publishing to one SSH target re-hydrated the whole repo catalog once per
worktree, then threw a fresh `createRepoRowExecutionHostLookup` (which itself
`filter`s the catalog per lookup) away each time.

The lookup is now built once per handler invocation and shared across targets:
the rows cannot change inside one synchronous projection, and they are the same
for every target.

On the session that surfaced this — 413 worktrees, 13 repos, 1 connected target
— that is 413 catalog hydrations (5369 `hydrateRepo` calls) per publish reduced
to 1 (13 calls). The repo normaliser reached through `hydrateRepo` was the #2
self-time function in a 30 s main-process CPU profile at 0.25%.

No user-facing trade-off: identical ownership resolution, identical exported
session, identical stale-revision handling.
Follow-up on the same handler: hoisting `store.getRepos()` removed the repeat
hydration, but the ownership resolution itself was still repeated once per
connected target.

`targetForWorktree` computes a connection id from the repo catalog alone — only
the final `=== targetId` differs — so exporting to N targets ran the identical
resolution N times over every worktree key, and the projection asks the question
once per key of `tabsByWorktree`, `activeTabIdByWorktree`,
`lastVisitedAtByWorktreeId` and `defaultTerminalTabsAppliedByWorktreeId`.

Resolutions are now memoised for the life of one publish, keyed on
`(worktreeId, executionHostId)` because both participate in resolution.

Test asserts 6 worktree keys resolve 6 times across 2 targets instead of 12.
… is connected

Hoisting the catalog read made a zero-connected-target publish pay for a full
repo hydration it never did before. Return early instead.
@nwparker
nwparker force-pushed the perf/remote-export-repo-lookup branch from 5dcc791 to 204d54f Compare September 4, 2026 03:42
@coderabbitai

coderabbitai Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@nwparker

nwparker commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Bot review resolution:

pullfrog — zero-target path still hydrates the catalog. Fixed in 204d54f. This was a genuine regression introduced by the hoist: the catalog used to be read only inside isTargetWorktree, which never runs when no hydrated target is connected, so the disconnected case went from zero reads to a full hydration per publish. The handler now returns early on targets.length === 0 (it already fell through to []), which also drops the pre-existing getWorkspaceSession() read there. New test; verified it fails without the guard.

pullfrog — line 278 comment misstates the memo. Fixed in 204d54f, took the suggested wording verbatim.

coderabbit — Description check. Fixed: added the Linked Issue, Visual Proof (N/A + reason), Testing, Notes and Checklist sections to the body.

coderabbit — Docstring Coverage 16.67% vs 80% threshold. Declining. AGENTS.md is explicit that this repo wants "Concise/Brief Non-obvious Comments ONLY — DO NOT be verbose, explain the obvious... BE CONCISE. 1 LINE if possible." The 6 functions counted are mostly one-line closures whose names already say what they do; the two that carry non-obvious reasoning (createWorktreeTargetResolver and the targets.length === 0 guard) do have comments, and they explain why rather than how, which is what the repo asks for. Adding docstrings to (worktreeId, executionHostId) => ... to hit a percentage would work against the stated house style.

coderabbit — inline review. "No actionable comments were generated." Nothing to action.

Also rebased onto current main, which now includes #18416 (indexes createRepoRowExecutionHostLookup so it no longer re-filters per lookup). The two changes are orthogonal and compose; worktree-execution-host-resolution.test.ts is green alongside this.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

Since the prior review (memoization at 5dcc791), this delta adds the zero-target early return:

  • Early return on the disconnected path — if (targets.length === 0) return [] now runs before store.getWorkspaceSession() and store.getRepos(), so a hydrated-but-disconnected target no longer pays a full repo hydration per publish (a regression the hoisted catalog read introduced, on a handler firing ~0.48/sec).
  • Regression guard — a new test asserts the zero-connected-target publish returns [] while reading neither the session nor the repo catalog.
  • Comment reword — the misleading "one ownership resolution for every target" is now "ownership resolutions shared across targets."

The early return is behavior-preserving: a zero-target publish previously ended in Promise.all([]).filter(...) → [], so returning [] up front skips only the reads. Both prior review threads are addressed cleanly, and the 10 tests in the file pass.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker

nwparker commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

CI note: e2e / ssh docker watcher isolation is red, and it is not caused by this PR.

Evidence:

  1. It fails on main with no PR involved. Run 33792502150 (workflow_dispatch on main) fails the same ssh docker watcher isolation job, and every scheduled e2e run on main from Aug 29 through today is red.
  2. It is non-deterministic. Two runs on this branch failed at different points: first Terminal did not contain "LEASE_GEN_2_...", then LEASE_GEN_1_.... The main run fails a different test entirely (ssh-cold-hydration-gap-tab-seeding). A real regression would fail at the same place.
  3. The logs show infrastructure, not assertion, failure: Relay process exited before ready, connect ECONNREFUSED .../relay-*.sock, and listen EADDRINUSE 127.0.0.1:*.
  4. The failing test is unreachable from this diff. It exercises PTY lease reattachment across relay restarts; this PR only touches remoteWorkspace:setForConnectedTargets. The one new behavior — returning early when no hydrated target is connected — is observationally identical to before (the old code also fell through to []), and the two calls it now skips, store.getRepos() and store.getWorkspaceSession(), are pure reads: getWorkspaceSession returns state.workspaceSession ?? getDefaultWorkspaceSession() with no write or lazy init (src/main/persistence/loading-store/session-host-partitions.ts:55).

Everything else is green, including e2e / changed e2e specs (the e2e job scoped to this diff), verify, typecheck, static analysis, all 8 test shards, and both package jobs.

@nwparker
nwparker merged commit 36354f1 into main Sep 4, 2026
60 of 62 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…rktree (stablyai#18410)

* perf(remote): read the repo catalog once per publish, not once per worktree

`remoteWorkspace:setForConnectedTargets` costs 13 ms of main-thread time per
call at 0.48 calls/sec — 0.63% of wall on a real session, the second most
expensive IPC handler in the main process.

Almost all of it is one line. `exportRemoteWorkspaceSession` asks
`isTargetWorktree(worktreeId)` once per worktree in the session, and that
callback called `targetForWorktree(store, ...)`, which called
`store.getRepos()` — and `getRepos()` maps `hydrateRepo` over every repo row.
So publishing to one SSH target re-hydrated the whole repo catalog once per
worktree, then threw a fresh `createRepoRowExecutionHostLookup` (which itself
`filter`s the catalog per lookup) away each time.

The lookup is now built once per handler invocation and shared across targets:
the rows cannot change inside one synchronous projection, and they are the same
for every target.

On the session that surfaced this — 413 worktrees, 13 repos, 1 connected target
— that is 413 catalog hydrations (5369 `hydrateRepo` calls) per publish reduced
to 1 (13 calls). The repo normaliser reached through `hydrateRepo` was the stablyai#2
self-time function in a 30 s main-process CPU profile at 0.25%.

No user-facing trade-off: identical ownership resolution, identical exported
session, identical stale-revision handling.

* perf(remote): resolve each worktree's owning target once per publish

Follow-up on the same handler: hoisting `store.getRepos()` removed the repeat
hydration, but the ownership resolution itself was still repeated once per
connected target.

`targetForWorktree` computes a connection id from the repo catalog alone — only
the final `=== targetId` differs — so exporting to N targets ran the identical
resolution N times over every worktree key, and the projection asks the question
once per key of `tabsByWorktree`, `activeTabIdByWorktree`,
`lastVisitedAtByWorktreeId` and `defaultTerminalTabsAppliedByWorktreeId`.

Resolutions are now memoised for the life of one publish, keyed on
`(worktreeId, executionHostId)` because both participate in resolution.

Test asserts 6 worktree keys resolve 6 times across 2 targets instead of 12.

* perf(remote): skip the session and repo reads when no hydrated target is connected

Hoisting the catalog read made a zero-connected-target publish pay for a full
repo hydration it never did before. Return early instead.
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