Repository navigation
perf(windows): drop the unread Memory flag and share one process-table projection per snapshot - #18151
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (9)
📝 WalkthroughWalkthroughThe Windows process reader no longer collects working-set memory and requests only ✨ Finishing Touches📝 Generate docstrings
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. Comment |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Drop the unread
Memoryflag —windows-process-table.tsno longer requestsProcessDataFlag.Memorynor surfacesmemoryBytes; the flag set is nowCommandLine | CreationTime. - Share one projection per snapshot —
windows-foreground-process-rows.tsmemoizesnative.map(toProcessRow)in aWeakMapkeyed 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 overProcessIdentityRow, with the descendant walk extracted intocollectDescendantsFromIndex;agent-foreground-process.tsmigrates onto it. - Doc corrections —
windows-edr-posture.mdandwindows-process-enumeration.mdnow describe the code as-shipped (one flag set,CommandLinestill performs a PEB read), correcting three false claims. - New regression test —
windows-foreground-process-inspection-cost.test.tspins 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.
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.
5a2f36f to
4de3256
Compare
…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.
…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.
…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.
…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.

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
Memoryfield with zero consumerssrc/main/windows/windows-process-table.tssetProcessDataFlag.Memory | CommandLine | CreationTimeand surfaced the result asWindowsProcessRow.memoryBytes.A full
rg memoryBytes src/finds no reader. The only other hits are an unrelated local variable insrc/main/memory/collector.ts/memory-snapshot-buckets.ts(the Resource Manager's own CIM sweep, which needsPageFileUsageand CPU counters in one pass and cannot use this table), plus the module's own test and a comment inwindows-process-table-cim-scan.tssaying the CIM fallback deliberately leaves it undefined. Nothing consumed it, somemoryBytesis removed along with the flag.Cost, read out of the vendored addon source (
@vscode/[email protected], as patched byconfig/patches/):So
Memorycosts oneOpenProcessplus oneGetProcessMemoryInfoper process, per snapshot, and the handle it takes carriesPROCESS_VM_READ.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-tableMapplus ~1050 child arrays, rebuilt from scratch;rows.find(row => row.pid === anchorPid)— a second linear scan.POSIX already had the fix:
getProcessTableIndex()insrc/shared/process-table-snapshot.tsmemoizesbyPid/childrenByPpidper snapshot identity in aWeakMap. 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 wiringgetProcessTableIndexin directly would have missed every time.Now: a
WeakMapcaches thetoProcessRowprojection keyed by the native rows array, and the projected array (now stable) feeds the existinggetProcessTableIndex. Both lookups becomebyPidhits and the descendant walk reads the sharedchildrenByPpid.Rather than adding a parallel Windows index,
buildProcessTableIndex/getProcessTableIndex/lookupProcessTableIndexare now generic over the row shape (ProcessIdentityRow = { pid; ppid }), and the descendant walk moved into a sharedcollectDescendantsFromIndex.ProcessTableIndexstays 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.tshad a byte-identical duplicatecollectDescendantswith 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.mdwas wrong in three placesI checked all three against the vendored source. All three claims were false at the base commit.
Memoryis retired"windows-process-table.tsset it on every snapshot. It is retired now — by this PR.NtQueryInformationProcess'sProcessCommandLineInformation…ReadProcessMemoryis absent from the compiled addon, asserted against the binary's import table"process_commandline.cc:32opensPROCESS_QUERY_INFORMATION | PROCESS_VM_READ;:38queriesProcessBasicInformation(to find the PEB, not the command line);:41,:43,:47are threeReadProcessMemorycalls 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 (onePROCESS_VM_READhandle and a PEB read per process, fromCommandLine). Moving toProcessCommandLineInformationwould 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.setcalls (scoped patch, restored infinally) and distinct projected-row object identities. Fail-first confirmed by revertingsrc/and re-running.native.map(toProcessRow)passes)Mapinsertions during the sweepMapinsertions, one-time index build (amortised over all 11 panes).some+.find)Memory|CommandLine|CreationTime)CommandLine|CreationTime)OpenProcesscalls the addon makes per snapshotNet 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 indocs/reference/windows-process-enumeration.md, measured on Windows 11 at 1,050 processes:Get-CimInstancevia PowerShell: 706 ms p50Those are the module's figures for both extra fields together. This PR removes one of the two. I have not measured where
CommandLinealone 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:
Get-Counter '\Process(Orca)\Handle Count' -SampleInterval 1 -MaxSamples 60, with 11 panes inspecting, before vs afterCommandLine-only vs both flagsMeasure-Commandaround a loop callinggetProcessListat each bitfield, on a ≥1000-process hostGet-Counter '\Process(Orca)\% Processor Time' -SampleInterval 1 -MaxSamples 120at 11 panes, idleCommandLinestill does the PEB read. Only an addon patch toProcessCommandLineInformationwould test that.Negative user-facing trade-offs
None. Specifically:
byPidis built first-wins on duplicate pids, which is exactlyrows.find()semantics;childrenByPpidis built in capture order and the walk pops last-pushed-first, socollectDescendantsFromIndexemits 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-existingwindows-agent-foreground-process-scan-volume.test.ts,windows-foreground-process-rows.test.ts,agent-foreground-process*.test.tsandstructured-tui-process-identity.test.tsall pass unchanged.Memoryhas no reader. Full-repo grep above; the only othermemoryBytesidentifiers 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:59storespmc.WorkingSetSizeinto aDWORD, so anything above 4 GB wraps — already documented, and now cross-referenced from the flag comment.queryWindowsProcessRowsFreshnow returnsreadonly 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, andanchorRowis read-only at every use site.WeakMaps keyed by the snapshot array identity, so an entry dies with its snapshot — no new retention, no cross-snapshot staleness, andresetWindowsProcessTableForTests()still invalidates everything by producing a new array.child_process. Enumeration still goes solely throughwindows-process-table.ts.Verification
pnpm tc— clean (run once, at the end)npx oxlint <changed files>— clean;npx oxfmt --check— cleannpx 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.tsreal-PTY tests, which need node-pty built from source; they fail identically on a pristinemainin this sandbox and touch none of this code.