Skip to content

perf(windows): drop the unread Memory flag and share one process-table projection per snapshot - #18151

Merged
nwparker merged 1 commit into
mainfrom
perf/windows-process-table-flags-and-index
Sep 2, 2026
Merged

nwparker merged 1 commit into
mainfrom
perf/windows-process-table-flags-and-index

Conversation

@nwparker

@nwparker nwparker commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​169 $\color{#cf222e}{\Huge{\mathbf{−}}}$​10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​159
Prod 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​177 $\color{#cf222e}{\Huge{\mathbf{−}}}$​117 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​60

ELI5

On Windows, twice a second Orca asks the operating system for a memory reading on every single running program — about 1,050 of them — and then throws every one of those readings away without looking at it. Nothing in the app reads that field.

And separately: those 1,050 processes get looked up once per open terminal. With 11 terminals open, Orca builds the same index of the same 1,050 processes 11 times over, a fraction of a second apart, instead of building it once and sharing it. The snapshot itself was already shared; only the work done on top of it was not.

This PR stops asking for the memory field, and shares the index.


What was wrong, and what I found when I checked

Three fixes. I verified each against the code and the vendored addon source rather than taking the brief at face value; two details in the brief were wrong and are corrected below.

Fix 1 — the snapshot requested a Memory field with zero consumers

src/main/windows/windows-process-table.ts set ProcessDataFlag.Memory | CommandLine | CreationTime and surfaced the result as WindowsProcessRow.memoryBytes.

A full rg memoryBytes src/ finds no reader. The only other hits are an unrelated local variable in src/main/memory/collector.ts / memory-snapshot-buckets.ts (the Resource Manager's own CIM sweep, which needs PageFileUsage and CPU counters in one pass and cannot use this table), plus the module's own test and a comment in windows-process-table-cim-scan.ts saying the CIM fallback deliberately leaves it undefined. Nothing consumed it, so memoryBytes is removed along with the flag.

Cost, read out of the vendored addon source (@vscode/[email protected], as patched by config/patches/):

// src/process.cc:47-63  -- GetProcessMemoryUsage, called per row when MEMORY is set
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid);
if (GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc))) { ... }

So Memory costs one OpenProcess plus one GetProcessMemoryInfo per process, per snapshot, and the handle it takes carries PROCESS_VM_READ.

Correction to the brief. The brief said "process.cc:52 and :84 each do OpenProcess(...) plus GetProcessMemoryInfo per process." Line 52 is right. Line 84 is GetCpuUsage, which calls GetProcessTimes, not GetProcessMemoryInfo — and Orca never calls it (getProcessCpuUsage is explicitly rejected in windows-process-enumeration.md for its blocking Sleep(1000)). So the Memory flag costs one extra handle per process, not two. The "roughly 2100 OpenProcess/sec, of which the Memory half is dead work" figure still holds: it was 2 handles per process (Memory + CommandLine) and is now 1.

Fix 2 — every pane re-projected and re-indexed the whole snapshot

src/main/providers/windows-foreground-process-rows.ts, per inspection:

  • native.map(toProcessRow) — a fresh ~1050-object array;
  • rows.some(row => row.pid === rootPid) — linear scan;
  • collectDescendants(rows, rootPid) — a whole-table Map plus ~1050 child arrays, rebuilt from scratch;
  • rows.find(row => row.pid === anchorPid) — a second linear scan.

POSIX already had the fix: getProcessTableIndex() in src/shared/process-table-snapshot.ts memoizes byPid / childrenByPpid per snapshot identity in a WeakMap. The brief's diagnosis here is exactly right, including the subtle part — the .map() defeated any such memo by construction, because it returns a new array identity on every call, so even wiring getProcessTableIndex in directly would have missed every time.

Now: a WeakMap caches the toProcessRow projection keyed by the native rows array, and the projected array (now stable) feeds the existing getProcessTableIndex. Both lookups become byPid hits and the descendant walk reads the shared childrenByPpid.

Rather than adding a parallel Windows index, buildProcessTableIndex / getProcessTableIndex / lookupProcessTableIndex are now generic over the row shape (ProcessIdentityRow = { pid; ppid }), and the descendant walk moved into a shared collectDescendantsFromIndex. ProcessTableIndex stays as an alias, so no POSIX caller changed shape.

The "related and smaller" item was clean, so it is included: src/main/providers/agent-foreground-process.ts had a byte-identical duplicate collectDescendants with the same per-call Map rebuild on POSIX. It now uses the shared index too — getFreshProcessTableSnapshot()/getProcessTableSnapshot() already return a per-capture-memoized array, so the identity the memo needs is there.

Fix 3 — docs/reference/windows-edr-posture.md was wrong in three places

I checked all three against the vendored source. All three claims were false at the base commit.

Claim in the doc Reality
(a) "Memory is retired" It was not. windows-process-table.ts set it on every snapshot. It is retired now — by this PR.
(b) "one cache per flag set… 6.3 ms p50 / 12.3 ms p50 at 492 processes" There is no flag-set split and never was. One TTL cache serves everyone, deliberately (the code comment says a split "would restore exactly the fan-out it exists to prevent"). Those two p50 figures describe no code path in the tree.
(c) "the command line now comes from the kernel through NtQueryInformationProcess's ProcessCommandLineInformation… ReadProcessMemory is absent from the compiled addon, asserted against the binary's import table" False. process_commandline.cc:32 opens PROCESS_QUERY_INFORMATION | PROCESS_VM_READ; :38 queries ProcessBasicInformation (to find the PEB, not the command line); :41, :43, :47 are three ReadProcessMemory calls walking PEB → RTL_USER_PROCESS_PARAMETERS → command-line buffer. No import-table assertion exists anywhere in the repo, and none would pass.

(c) is the one that mattered beyond tidiness: the doc told future contributors that the MDE "suspicious memory activity" signal — the thing Incident D fired on — had been removed. It had not. Both docs are now rewritten to describe what the code actually does, and to state precisely what this PR changed (Memory's second handle: gone) versus what remains (one PROCESS_VM_READ handle and a PEB read per process, from CommandLine). Moving to ProcessCommandLineInformation would genuinely retire the remote read; the doc now labels that as unwritten work rather than shipped.


Measurements

Measured here — unit-level counters (src/main/providers/windows-foreground-process-inspection-cost.test.ts)

Simulated 1,050-process table, 11 panes inspecting inside one 500 ms TTL window. Counters are Map.prototype.set calls (scoped patch, restored in finally) and distinct projected-row object identities. Fail-first confirmed by reverting src/ and re-running.

Counter, per 11-pane sweep on one snapshot Before After
Snapshot projections (native.map(toProcessRow) passes) 11 1
Row objects allocated by projection (11 × 1050 vs 1 × 1050) 11,550 1,050
Map insertions during the sweep 11,550 0
Map insertions, one-time index build (amortised over all 11 panes) — 2,100
Whole-table linear scans (.some + .find) 22 0
Flag bitfield sent to the addon 7 (Memory|CommandLine|CreationTime) 6 (CommandLine|CreationTime)
OpenProcess calls the addon makes per snapshot 2 × N 1 × N

Net per snapshot window: 11,550 → 2,100 Map insertions and 11,550 → 1,050 row objects, and the index cost is now paid once no matter how many panes share the window (it stops scaling with pane count entirely).

The after-numbers are exact, not bounded: 0 Map insertions across the sweep, 1 distinct projection. The committed assertions are the tight ones (=== 1, < TABLE_SIZE).

Not measured here — the module's published figures

The flag-cost claim rests on @vscode/windows-process-tree's own published numbers, reproduced in docs/reference/windows-process-enumeration.md, measured on Windows 11 at 1,050 processes:

  • pid + ppid + name: 15.9 ms p50 / 17.5 ms p95
  • + memory + command line: 30.6 ms p50 / 33.7 ms p95
  • Get-CimInstance via PowerShell: 706 ms p50

Those are the module's figures for both extra fields together. This PR removes one of the two. I have not measured where CommandLine alone lands between 15.9 and 30.6 ms and I am not claiming a number — the doc now says so explicitly instead of implying a split.

Needs a real Windows box — with the exact command

Nothing here was run on Windows; all profiling of this app to date was on macOS. What would settle it:

Question Command
Handle churn from the flag change Get-Counter '\Process(Orca)\Handle Count' -SampleInterval 1 -MaxSamples 60, with 11 panes inspecting, before vs after
Snapshot wall time for CommandLine-only vs both flags Measure-Command around a loop calling getProcessList at each bitfield, on a ≥1000-process host
Main-process CPU attributable to inspection Get-Counter '\Process(Orca)\% Processor Time' -SampleInterval 1 -MaxSamples 120 at 11 panes, idle
Whether MDE stops scoring "suspicious memory activity" It will not — CommandLine still does the PEB read. Only an addon patch to ProcessCommandLineInformation would test that.

Negative user-facing trade-offs

None. Specifically:

  • Detection results are unchanged. Same rows in, same rows out. byPid is built first-wins on duplicate pids, which is exactly rows.find() semantics; childrenByPpid is built in capture order and the walk pops last-pushed-first, so collectDescendantsFromIndex emits descendants in the identical order to the old per-call walk, and the subsequent .sort() is stable in V8. Agent foreground-process detection and has-children answers are byte-identical — asserted by a dedicated case in the new test file, and the pre-existing windows-agent-foreground-process-scan-volume.test.ts, windows-foreground-process-rows.test.ts, agent-foreground-process*.test.ts and structured-tui-process-identity.test.ts all pass unchanged.
  • Removing Memory has no reader. Full-repo grep above; the only other memoryBytes identifiers belong to the Resource Manager's independent CIM sweep. If a future caller wants a working set off this table it should not use this field anyway: process.cc:59 stores pmc.WorkingSetSize into a DWORD, so anything above 4 GB wraps — already documented, and now cross-referenced from the flag comment.
  • Rows are shared, not copied. The projected array is handed to multiple readers, so queryWindowsProcessRowsFresh now returns readonly WindowsProcessRow[]. I checked both callers (windows-pty-root-identity.ts, structured-tui-process-identity.ts) — one reads, one .map()s; neither mutates. Descendant candidates are still { ...row, depth } copies, and anchorRow is read-only at every use site.
  • Caches are correctly bounded. Both memos are WeakMaps keyed by the snapshot array identity, so an entry dies with its snapshot — no new retention, no cross-snapshot staleness, and resetWindowsProcessTableForTests() still invalidates everything by producing a new array.
  • No EDR posture regression. Strictly fewer handles opened per process, no new interpreter hop, no PowerShell, no child_process. Enumeration still goes solely through windows-process-table.ts.

Verification

  • pnpm tc — clean (run once, at the end)
  • npx oxlint <changed files> — clean; npx oxfmt --check — clean
  • npx vitest run --config config/vitest.config.ts src/main/windows src/main/providers src/shared — 690 files / 7,457 tests pass. The 11 failures are all *.node-pty.test.ts real-PTY tests, which need node-pty built from source; they fail identically on a pristine main in this sandbox and touch none of this code.

@coderabbitai

coderabbitai Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 3ff14084-a3e1-46b0-ac5b-68319df7d0bf

📥 Commits

Reviewing files that changed from the base of the PR and between 89bd189 and 4de3256.

📒 Files selected for processing (9)
  • docs/reference/windows-edr-posture.md
  • docs/reference/windows-process-enumeration.md
  • src/main/providers/agent-foreground-process.ts
  • src/main/providers/windows-foreground-process-inspection-cost.test.ts
  • src/main/providers/windows-foreground-process-rows.ts
  • src/main/windows/windows-process-table-cim-scan.ts
  • src/main/windows/windows-process-table.test.ts
  • src/main/windows/windows-process-table.ts
  • src/shared/process-table-snapshot.ts

📝 Walkthrough

Walkthrough

The Windows process reader no longer collects working-set memory and requests only CommandLine | CreationTime. Process-row projections and process-table indexes are cached per snapshot. Generic index helpers now support Windows row shapes and indexed descendant traversal. Foreground-process providers use indexed PID lookups and descendant collection instead of repeated table scans. Documentation and tests now describe and verify the reduced flag set, cache behavior, handle usage, and foreground-process results.

✨ 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.

@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

  • Drop the unread Memory flag — windows-process-table.ts no longer requests ProcessDataFlag.Memory nor surfaces memoryBytes; the flag set is now CommandLine | CreationTime.
  • Share one projection per snapshot — windows-foreground-process-rows.ts memoizes native.map(toProcessRow) in a WeakMap keyed by the native rows array, feeding the existing per-snapshot index.
  • Generalize the shared index — process-table-snapshot.ts's build/get/lookup helpers are generic over ProcessIdentityRow, with the descendant walk extracted into collectDescendantsFromIndex; agent-foreground-process.ts migrates onto it.
  • Doc corrections — windows-edr-posture.md and windows-process-enumeration.md now describe the code as-shipped (one flag set, CommandLine still performs a PEB read), correcting three false claims.
  • New regression test — windows-foreground-process-inspection-cost.test.ts pins the flag bitfield, single-projection identity, and index-build count.

I verified the load-bearing claims against the vendored addon source: process.cc's GetProcessMemoryUsage opens PROCESS_QUERY_INFORMATION | PROCESS_VM_READ (dropped by this PR), and process_commandline.cc still opens the same handle class and issues three ReadProcessMemory calls against ProcessBasicInformation — so the EDR "suspicious memory activity" signal remains, and the doc now says so honestly. byPid first-wins matches the old rows.find/rows.some semantics, and childrenByPpid capture order makes descendant emission byte-identical to the old per-call walk. Fresh reads produce a new native array identity, so the projection memo cannot serve a stale row to teardown identity checks. The readonly return on queryWindowsProcessRowsFresh is honest — both callers are read-only.

One non-blocking observation: src/relay/pty-shell-utils.ts:202 still carries a byte-identical collectDescendants over ProcessTableIndex that collectDescendantsFromIndex now subsumes. It predates this PR and is off the hot Windows path, so leaving it is fine — flagging only as an optional follow-up consolidation.

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

…e projection per snapshot

Two costs on the Windows process-table hot path, plus the EDR doc that
described neither of them accurately.

1. The snapshot set `ProcessDataFlag.Memory` and surfaced `memoryBytes`,
   which nothing read. The addon serves that flag with a second
   `OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ)` and a
   `GetProcessMemoryInfo` per process (process.cc:47-63), so the flag was
   one wasted handle per process per snapshot.

2. The shared TTL cache gave every pane the same native rows array, but
   each pane still ran `native.map(toProcessRow)` over the whole table,
   rebuilt a `childrenByPpid` Map from scratch, and did two linear scans.
   The `.map()` also handed `getProcessTableIndex` a new array each call,
   defeating the POSIX memo by construction. Both now cache per snapshot
   identity, and the POSIX resolver drops its duplicate descendant walk.

`getProcessTableIndex` / `buildProcessTableIndex` are generic over the row
shape so the Windows rows reuse the existing pass instead of a parallel one.

No behavior change: same rows in, same rows out, same descendant ordering
and same has-children answers.
@nwparker
nwparker force-pushed the perf/windows-process-table-flags-and-index branch from 5a2f36f to 4de3256 Compare September 2, 2026 20:06
@nwparker
nwparker merged commit 53f1058 into main Sep 2, 2026
3 of 4 checks passed
nwparker added a commit that referenced this pull request Sep 2, 2026
…wn module (#18246)

`src/shared/process-table-snapshot.ts` is 308 code lines against the 300
cap for `**/*.ts`, so `static analysis` is red on `main` and every open PR
inherits it.

Neither PR that grew the file crossed the cap alone. #18151 took it to 427
raw lines; #18166 added ~35 more. #18166's branch predated #18151, so the
head CI linted was 428 raw lines and passed, while the squash onto main is
463 -> 308 code lines. The gate lints the PR head, not the merge result, so
nothing linted the sum until it was on main.

Pure move, no behaviour change: the generic index machinery
(ProcessIdentityRow, ProcessTableIndexOf, buildProcessTableIndex,
collectDescendantsFromIndex, lookupProcessTableIndex, getProcessTableIndex
and its WeakMap) moves to process-table-index.ts. `ProcessTableIndex` and
`scoreForegroundCandidateRow` stay behind because they need
`ProcessTableRow`, which keeps the new module free of any import back and
so introduces no cycle.
OrcaWin pushed a commit that referenced this pull request Sep 6, 2026
…n-host-materialization

Conflicts, and how each was resolved:

- config/nsis/daemon-host-uninstall.nsh: main deleted it (#17906 consolidated
  every NSIS hook into config/nsis/orca-installer-hooks.nsh, because
  electron-builder accepts exactly one `nsis.include`). Took the deletion; the
  rewritten uninstall macro is ported into the hooks file in the next commit.
  Doc references repointed at the surviving file.

- docs/reference/windows-edr-posture.md: add/add. This branch's base (#17856)
  squash-landed on main, and #18151 then corrected several process-table claims
  there. Took main's corrected text and re-applied only this branch's
  daemon-host edits (the rename removal, T1036.005, the spawn-tree line, the
  checklist row).

- .gitignore, AGENTS.md: kept both sides' added lines.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…e projection per snapshot (stablyai#18151)

Two costs on the Windows process-table hot path, plus the EDR doc that
described neither of them accurately.

1. The snapshot set `ProcessDataFlag.Memory` and surfaced `memoryBytes`,
   which nothing read. The addon serves that flag with a second
   `OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ)` and a
   `GetProcessMemoryInfo` per process (process.cc:47-63), so the flag was
   one wasted handle per process per snapshot.

2. The shared TTL cache gave every pane the same native rows array, but
   each pane still ran `native.map(toProcessRow)` over the whole table,
   rebuilt a `childrenByPpid` Map from scratch, and did two linear scans.
   The `.map()` also handed `getProcessTableIndex` a new array each call,
   defeating the POSIX memo by construction. Both now cache per snapshot
   identity, and the POSIX resolver drops its duplicate descendant walk.

`getProcessTableIndex` / `buildProcessTableIndex` are generic over the row
shape so the Windows rows reuse the existing pass instead of a parallel one.

No behavior change: same rows in, same rows out, same descendant ordering
and same has-children answers.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…wn module (stablyai#18246)

`src/shared/process-table-snapshot.ts` is 308 code lines against the 300
cap for `**/*.ts`, so `static analysis` is red on `main` and every open PR
inherits it.

Neither PR that grew the file crossed the cap alone. stablyai#18151 took it to 427
raw lines; stablyai#18166 added ~35 more. stablyai#18166's branch predated stablyai#18151, so the
head CI linted was 428 raw lines and passed, while the squash onto main is
463 -> 308 code lines. The gate lints the PR head, not the merge result, so
nothing linted the sum until it was on main.

Pure move, no behaviour change: the generic index machinery
(ProcessIdentityRow, ProcessTableIndexOf, buildProcessTableIndex,
collectDescendantsFromIndex, lookupProcessTableIndex, getProcessTableIndex
and its WeakMap) moves to process-table-index.ts. `ProcessTableIndex` and
`scoreForegroundCandidateRow` stay behind because they need
`ProcessTableRow`, which keeps the new module free of any import back and
so introduces no cycle.
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