Skip to content

fix(workspace-space): bound traversal memory and serialize local disk scans - #11026

Merged
AmethystLiang merged 2 commits into
mainfrom
storage-scanning-crash-computer
Jul 28, 2026
Merged

AmethystLiang merged 2 commits into
mainfrom
storage-scanning-crash-computer

Conversation

@AmethystLiang

Copy link
Copy Markdown
Contributor

Problem

Resource Manager scans worktrees to calculate workspace disk usage. The July 27 incident with 298 Orca worktrees demonstrated two independent resource failures:

  • macOS/Linux: Up to six concurrent du processes competed for local storage, saturating disk I/O and stalling unrelated applications.
  • Windows/fallback: The portable recursive scanner allocated promises and result nodes without limits, allowing large worktrees to exhaust heap (desktop or relay).

Solution

Local disk serialization

Introduce a scan-wide limiter that reduces maximum concurrent local traversals from six to one. This preserves host responsiveness while scanning hundreds of worktrees.

Fixed-worker portable traversal

Replace recursive promise fanout with iterative DirectoryFrame stack and fixed-worker concurrency. Use shared scanWorkspaceSpaceEntryTree for desktop local fallback, desktop remote-provider fallback, and relay fallback scans.

Capacity admission

Every portable entry is admitted through WorkspaceSpaceScanBudget before retention:

  • Maximum entries held at once per worktree: 100,000
  • Maximum estimated live state per worktree: 64 MiB

Budget measures what the traversal holds right now, not cumulative tree size. Directory listings are charged on admission and released once all entries are dispatched, bounding the widest concurrent frontier rather than total tree size. This distinction preserves success for ordinary large worktrees (76,788-entry Orca worktree peaks between 4–8 MiB live state).

Failure mode

Capacity errors become unavailable rows rather than crashes, since the workspace is intact and readable, just too large to size safely.

Testing

  • Focused capacity and concurrency regression tests added across desktop, relay, and shared traversal modules.
  • TypeScript and production build validation passed.
  • 36 tests across analysis, IPC, relay, and budget modules.
  • Existing desktop coverage (local results, symlinks, progress, cancellation, WSL routing, SSH bulk scans, du timeout fallback) preserved.

Platform parity

  • macOS/Linux: One local du at a time; bounded Node fallback on failure.
  • Windows: One local bounded Node traversal at a time.
  • WSL: Retains getLocalProjectWorktreeGitOptions distro selection; same admission and capacity bounds.
  • SSH: Relay and request-by-request fallback use shared capacity model.
  • Folder workspaces: Synthetic main worktree passes through same limiter and scanner.

Prevent resource exhaustion during large workspace scans by limiting
local disk access to one concurrent `du` call and capping portable
traversal memory to 100k entries or 64 MiB per worktree. Fixes July 27
incident with 298 worktrees causing host stalls and renderer OOM.

Portable traversals now use fixed-worker iterative frames instead of
recursive promises. Capacity failures become unavailable rows. Behavior
below limits is unchanged.
@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Workspace space scanning now uses shared bounded directory traversal with live entry and retained-byte accounting. Directory listings are released as traversal progresses, while capacity failures are surfaced or used for relay fallback according to scan path. Local worktree scans are serialized across repositories, and desktop and relay implementations use shared traversal and concurrency helpers. New tests cover capacity failures, listing release and refund behavior, deep trees, relay fallback, and single-concurrent local du traversal.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the change and testing, but it does not follow the required template or include Screenshots, AI Review Report, Security Audit, or Notes. Rewrite the PR description to match the template with Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes sections.
Docstring Coverage ⚠️ Warning Docstring coverage is 13.33% 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 is concise and accurately summarizes the main change: bounding workspace traversal memory and serializing local scans.
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
📝 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.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/main/workspace-space-analysis.ts (1)

828-831: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Name the repo-scan concurrency literal.

Every other concurrency bound in this module is a named constant (WORKTREE_SCAN_CONCURRENCY, LOCAL_WORKTREE_SCAN_CONCURRENCY, ...); the bare 2 here is the odd one out.

♻️ Proposed tweak
-  const repoResults = await mapWithConcurrency(reposToScan, 2, (repo) =>
+  const repoResults = await mapWithConcurrency(reposToScan, REPO_SCAN_CONCURRENCY, (repo) =>
     scanRepo(repo, scannedAt, store, localWorktreeLimit, progress, options)
   )

Add alongside the other constants:

const REPO_SCAN_CONCURRENCY = 2
src/relay/workspace-space-scan.test.ts (1)

9-12: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Capacity rethrow on the DU path stays uncovered.

Forcing platform to win32 routes straight to scanDirectoryWithNode, so the new WorkspaceSpaceScanCapacityError rethrow in scanWorkspaceSpaceDirectory (the non-win32 DU branch) is never exercised — the very branch that decides whether an oversized workspace falls back or fails closed. Consider a second case that leaves platform as-is (or mocks it to linux) with execFile stubbed.

Also applies to: 42-51


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c58a71df-9124-443b-9c69-9775b0e1505a

📥 Commits

Reviewing files that changed from the base of the PR and between edc6cc0 and 3f62a11.

📒 Files selected for processing (11)
  • docs/workspace-space-scan-resource-bounds.md
  • src/main/workspace-space-analysis-capacity.test.ts
  • src/main/workspace-space-analysis-du-timeout.test.ts
  • src/main/workspace-space-analysis.ts
  • src/relay/workspace-space-scan.test.ts
  • src/relay/workspace-space-scan.ts
  • src/shared/workspace-space-directory-frame.ts
  • src/shared/workspace-space-entry-traversal.test.ts
  • src/shared/workspace-space-entry-traversal.ts
  • src/shared/workspace-space-scan-budget.test.ts
  • src/shared/workspace-space-scan-budget.ts

Desktop-side SSH fallback traversals run in the main process with independent admission
budgets. Without limiting, up to six concurrent traversals could stack six 64 MiB budgets.
Cap remote fallback traversals to 2 concurrent, keeping aggregate admission at 2 × 64 MiB.

Also make capacity error messages reflect configured limits instead of hardcoded defaults.
@AmethystLiang
AmethystLiang merged commit 9a8e21a into main Jul 28, 2026
22 checks passed

@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/relay/workspace-space-scan-du-capacity.test.ts (1)

74-76: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert the configured capacity limit, not only the error class.

The test forces maxEntries: 2, but only checks WorkspaceSpaceScanCapacityError. A regression that formats the error with default limits would still pass.

Suggested assertion
-    await expect(scanWorkspaceSpaceDirectory(rootPath, context)).rejects.toBeInstanceOf(
+    const scan = scanWorkspaceSpaceDirectory(rootPath, context)
+    await expect(scan).rejects.toBeInstanceOf(
       WorkspaceSpaceScanCapacityError
     )
+    await expect(scan).rejects.toThrow('2 entries')

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: cc5b95ae-fa46-4277-b885-cf80daabaf5d

📥 Commits

Reviewing files that changed from the base of the PR and between 3f62a11 and 2fefdd3.

📒 Files selected for processing (6)
  • docs/workspace-space-scan-resource-bounds.md
  • src/main/workspace-space-analysis.test.ts
  • src/main/workspace-space-analysis.ts
  • src/relay/workspace-space-scan-du-capacity.test.ts
  • src/shared/workspace-space-scan-budget.test.ts
  • src/shared/workspace-space-scan-budget.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/shared/workspace-space-scan-budget.test.ts
  • src/shared/workspace-space-scan-budget.ts
  • docs/workspace-space-scan-resource-bounds.md
  • src/main/workspace-space-analysis.ts

nwparker added a commit to nwparker/orca that referenced this pull request Jul 28, 2026
Traversal capacity cap no longer scales with worker concurrency
(stablyai#11026). retainWorkspaceSpaceScanEntry charged a traversal-wide entry
counter, so N workers each holding a listing multiplied the live charge.
At concurrency 48 a 48x2,100 tree (100,848 entries) hit the 100,000 cap
while 100x1,500 (150,100 entries, 50% more) passed, and scanLocalWorktree
treats the capacity error as terminal, reporting an intact worktree as
"Unavailable" with sizeBytes 0. The cap is now per directory listing --
the only quantity fixed by directory shape -- restoring the invariant
docs/workspace-space-scan-resource-bounds.md already states. Aggregate
live retention stays bounded by the unchanged 64 MiB byte cap.

Note: releasing each entry's charge at dispatch (the originally suggested
fix) was measured and does not help; the peak is set at admission, before
any entry is dispatched.

Repo image icons are no longer fully base64-decoded on every snapshot
publish (stablyai#11012). sanitizeRepoIcon reached decodeBase64Prefix, which
sized its buffer to the whole payload to read a 24-byte header, running
synchronously inside ipcMain.handle at a 250 ms throttle. Validation is
now memoized on source+src in a BoundedMap. Measured for 10 icons x
256 KB: 37.34 ms -> 0.67 ms per publish.

One over-long card label no longer discards the entire snapshot (stablyai#11012).
isDashboardSnapshot was all-or-nothing and dashboard-popout returned
early with no log while replaying lastSnapshot, so `orca terminal rename
--title "<1025+ chars>"` froze the pop-out board on its last good paint
with nothing surfaced. Labels are truncated at the producer, the
validator drops only the offending card, and both the rejection and the
drop are logged. The bound now lives in the shared snapshot contract so
producer and validator cannot drift.

Co-authored-by: Orca <[email protected]>
nwparker added a commit that referenced this pull request Jul 29, 2026
* fix(perf): correct three 07-27 perf regressions

Traversal capacity cap no longer scales with worker concurrency
(#11026). retainWorkspaceSpaceScanEntry charged a traversal-wide entry
counter, so N workers each holding a listing multiplied the live charge.
At concurrency 48 a 48x2,100 tree (100,848 entries) hit the 100,000 cap
while 100x1,500 (150,100 entries, 50% more) passed, and scanLocalWorktree
treats the capacity error as terminal, reporting an intact worktree as
"Unavailable" with sizeBytes 0. The cap is now per directory listing --
the only quantity fixed by directory shape -- restoring the invariant
docs/workspace-space-scan-resource-bounds.md already states. Aggregate
live retention stays bounded by the unchanged 64 MiB byte cap.

Note: releasing each entry's charge at dispatch (the originally suggested
fix) was measured and does not help; the peak is set at admission, before
any entry is dispatched.

Repo image icons are no longer fully base64-decoded on every snapshot
publish (#11012). sanitizeRepoIcon reached decodeBase64Prefix, which
sized its buffer to the whole payload to read a 24-byte header, running
synchronously inside ipcMain.handle at a 250 ms throttle. Validation is
now memoized on source+src in a BoundedMap. Measured for 10 icons x
256 KB: 37.34 ms -> 0.67 ms per publish.

One over-long card label no longer discards the entire snapshot (#11012).
isDashboardSnapshot was all-or-nothing and dashboard-popout returned
early with no log while replaying lastSnapshot, so `orca terminal rename
--title "<1025+ chars>"` froze the pop-out board on its last good paint
with nothing surfaced. Labels are truncated at the producer, the
validator drops only the offending card, and both the rejection and the
drop are logged. The bound now lives in the shared snapshot contract so
producer and validator cannot drift.

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

* fix(perf): charge a scan listing's parent path once, not per entry

The 4.1 fix made the entry cap per-listing but left the 64 MiB byte cap
charging parentPath.length for every entry in a listing. Because a
listing's entries all share one parent-path string, that multiplied the
path by the directory's width, so the byte cap measured checkout depth
rather than live heap.

The reported symptom therefore still reproduced at the production default
limits: 48 x 2,100 @ concurrency 48 raised a capacity error once the
worktree path passed ~58 characters, while the same layout at concurrency
1 succeeded. The shipped regression test could not see this because it
passes maxRetainedBytes: Number.MAX_SAFE_INTEGER, disabling the only cap
still in play. Measured at a real 65-char worktree root, 3 of the report's
4 documented layouts still failed.

The parent path is now charged once per listing, with its first entry, so
an empty listing strands no charge. Per-entry overhead is unchanged at
512 B + name, which still dominates the estimate, so the OOM protection
the original PR added is preserved.

Adds a production-default-limits case covering the report's layouts under
a deep root, plus an assertion that a short and a deep root reach the same
verdict -- the path independence docs/workspace-space-scan-resource-bounds.md
requires and which no existing test enforced.

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

* fix(perf): prove the icon cache by decode count, not wall clock

The caching test asserted a per-publish millisecond budget, which failed
on CI at 5.64 ms against a 5 ms ceiling. Any threshold flakes on a loaded
box, so count real sanitizeRepoIcon entries instead: 10 repos x 20
publishes is 200 icon checks against exactly 1 decode. Added cases pin
the cache key (payload and source both re-decode; a cached image verdict
never answers for an emoji) and that a rejection is cached too.

Also drops budget.entries, which the per-listing cap left as a
traversal-wide counter no check reads -- exactly the shape a future
guard could reintroduce the concurrency bug from.

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

* fix(dashboard): bound the project filter label the whole board rides on

#11042 added snapshot-level filterOptions whose project labels are
repo.displayName -- the same unbounded source this PR already bounds for
card.repoName, but one level up where dropping a card cannot recover it.
An over-long project name would fail isDashboardFilterOptions and take
the entire snapshot with it, which is the exact frozen-board failure the
per-card drop was added to end. Workspace-status labels are already
capped at 32 by workspace-statuses.ts, so only projects needed this.

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

* fix(dashboard): disambiguate the repo icon cache key

The memoization key joined `source` and `src` with a space, but the
sanitizer's base64 pattern admits whitespace inside a valid `src`. A
rejected icon can therefore split the same concatenation differently and
inherit an accepted icon's cached verdict, reaching the pop-out's
`<img src>` without ever being sanitized. Length-prefix the source.

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

---------

Co-authored-by: Orca <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… scans (stablyai#11026)

* fix(workspace-space): serialize local disk and cap traversal memory

Prevent resource exhaustion during large workspace scans by limiting
local disk access to one concurrent `du` call and capping portable
traversal memory to 100k entries or 64 MiB per worktree. Fixes July 27
incident with 298 worktrees causing host stalls and renderer OOM.

Portable traversals now use fixed-worker iterative frames instead of
recursive promises. Capacity failures become unavailable rows. Behavior
below limits is unchanged.

* fix(workspace-space): bound concurrent SSH fallback traversals

Desktop-side SSH fallback traversals run in the main process with independent admission
budgets. Without limiting, up to six concurrent traversals could stack six 64 MiB budgets.
Cap remote fallback traversals to 2 concurrent, keeping aggregate admission at 2 × 64 MiB.

Also make capacity error messages reflect configured limits instead of hardcoded defaults.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* fix(perf): correct three 07-27 perf regressions

Traversal capacity cap no longer scales with worker concurrency
(stablyai#11026). retainWorkspaceSpaceScanEntry charged a traversal-wide entry
counter, so N workers each holding a listing multiplied the live charge.
At concurrency 48 a 48x2,100 tree (100,848 entries) hit the 100,000 cap
while 100x1,500 (150,100 entries, 50% more) passed, and scanLocalWorktree
treats the capacity error as terminal, reporting an intact worktree as
"Unavailable" with sizeBytes 0. The cap is now per directory listing --
the only quantity fixed by directory shape -- restoring the invariant
docs/workspace-space-scan-resource-bounds.md already states. Aggregate
live retention stays bounded by the unchanged 64 MiB byte cap.

Note: releasing each entry's charge at dispatch (the originally suggested
fix) was measured and does not help; the peak is set at admission, before
any entry is dispatched.

Repo image icons are no longer fully base64-decoded on every snapshot
publish (stablyai#11012). sanitizeRepoIcon reached decodeBase64Prefix, which
sized its buffer to the whole payload to read a 24-byte header, running
synchronously inside ipcMain.handle at a 250 ms throttle. Validation is
now memoized on source+src in a BoundedMap. Measured for 10 icons x
256 KB: 37.34 ms -> 0.67 ms per publish.

One over-long card label no longer discards the entire snapshot (stablyai#11012).
isDashboardSnapshot was all-or-nothing and dashboard-popout returned
early with no log while replaying lastSnapshot, so `orca terminal rename
--title "<1025+ chars>"` froze the pop-out board on its last good paint
with nothing surfaced. Labels are truncated at the producer, the
validator drops only the offending card, and both the rejection and the
drop are logged. The bound now lives in the shared snapshot contract so
producer and validator cannot drift.

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

* fix(perf): charge a scan listing's parent path once, not per entry

The 4.1 fix made the entry cap per-listing but left the 64 MiB byte cap
charging parentPath.length for every entry in a listing. Because a
listing's entries all share one parent-path string, that multiplied the
path by the directory's width, so the byte cap measured checkout depth
rather than live heap.

The reported symptom therefore still reproduced at the production default
limits: 48 x 2,100 @ concurrency 48 raised a capacity error once the
worktree path passed ~58 characters, while the same layout at concurrency
1 succeeded. The shipped regression test could not see this because it
passes maxRetainedBytes: Number.MAX_SAFE_INTEGER, disabling the only cap
still in play. Measured at a real 65-char worktree root, 3 of the report's
4 documented layouts still failed.

The parent path is now charged once per listing, with its first entry, so
an empty listing strands no charge. Per-entry overhead is unchanged at
512 B + name, which still dominates the estimate, so the OOM protection
the original PR added is preserved.

Adds a production-default-limits case covering the report's layouts under
a deep root, plus an assertion that a short and a deep root reach the same
verdict -- the path independence docs/workspace-space-scan-resource-bounds.md
requires and which no existing test enforced.

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

* fix(perf): prove the icon cache by decode count, not wall clock

The caching test asserted a per-publish millisecond budget, which failed
on CI at 5.64 ms against a 5 ms ceiling. Any threshold flakes on a loaded
box, so count real sanitizeRepoIcon entries instead: 10 repos x 20
publishes is 200 icon checks against exactly 1 decode. Added cases pin
the cache key (payload and source both re-decode; a cached image verdict
never answers for an emoji) and that a rejection is cached too.

Also drops budget.entries, which the per-listing cap left as a
traversal-wide counter no check reads -- exactly the shape a future
guard could reintroduce the concurrency bug from.

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

* fix(dashboard): bound the project filter label the whole board rides on

stablyai#11042 added snapshot-level filterOptions whose project labels are
repo.displayName -- the same unbounded source this PR already bounds for
card.repoName, but one level up where dropping a card cannot recover it.
An over-long project name would fail isDashboardFilterOptions and take
the entire snapshot with it, which is the exact frozen-board failure the
per-card drop was added to end. Workspace-status labels are already
capped at 32 by workspace-statuses.ts, so only projects needed this.

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

* fix(dashboard): disambiguate the repo icon cache key

The memoization key joined `source` and `src` with a space, but the
sanitizer's base64 pattern admits whitespace inside a valid `src`. A
rejected icon can therefore split the same concatenation differently and
inherit an accepted icon's cached verdict, reaching the pop-out's
`<img src>` without ever being sanitized. Length-prefix the source.

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