Skip to content

fix(bench): make the idle-CPU benchmark run and report CPU on Windows - #25238

Closed
paoValle wants to merge 3 commits into
stablyai:mainfrom
paoValle:fix/windows-idle-cpu-build
Closed

paoValle wants to merge 3 commits into
stablyai:mainfrom
paoValle:fix/windows-idle-cpu-build

Conversation

@paoValle

@paoValle paoValle commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Author: @paolovalletta_

ELI5

On Windows the idle-CPU benchmark could not build the app (it asked for npx, which Windows cannot run that way), and — worse — once it did run, it reported 0% CPU for everything. The app's real CPU use was invisible in the report. Both are fixed: the build goes through the repo's own build helper, and the benchmark now reads the per-process CPU time Windows exposes.

What Changed

Before, on Windows:

$ node config/scripts/run-idle-cpu-benchmark.mjs
[idle-cpu] building Electron app with electron-vite --mode e2e
Error: spawnSync npx ENOENT
    at run (config/scripts/run-idle-cpu-benchmark.mjs:150:3)
    at buildAppIfNeeded (config/scripts/run-idle-cpu-benchmark.mjs:162:3)

and with --skip-build (so the sampling loop is reached), the report had meanCpuPercent: 0, p95CpuPercent: 0, maxCpuPercent: 0 for every process class while RSS was reported normally.

After, bench:idle-cpu completes on Windows and reports real CPU.

Fix 1 — build through the repo's own helper

buildAppIfNeeded ran run('npx', ['electron-vite', 'build', '--mode', 'e2e']) via execFileSync, which cannot start npx.cmd on Windows (ENOENT). It now spawns config/scripts/run-electron-vite-build.mjs with process.execPath — the repo's existing Windows-safe wrapper for exactly this build, which also runs the renderer boot-graph verification, so there is still one build path.

Fix 2 — report CPU instead of a hardcoded zero

The sampler derives CPU from the per-process time delta and only falls back to ps-style percentCpu when that is unavailable (idle-cpu-process-sampling.mjs:198). readWindowsProcesses returned cpuTimeSeconds: null, and its percentCpu was hardcoded 0, so on Windows both sides were empty and the delta was always zero. Win32_Process does expose UserModeTime and KernelModeTime (100 ns units); they were simply not requested. They are now selected and summed, and the field stays null if a host does not return them, which keeps the previous fallback.

Measured before/after

Same command, same machine, same --mode e2e build, one empty worktree, 15 s sample, only the CPU-reading change applied between the two runs:

ORCA_BACKGROUND_LAUNCH=1 node config/scripts/run-idle-cpu-benchmark.mjs \
  --skip-build --warmup-ms 5000 --sample-ms 15000 --output idle.json
process class mean CPU before mean CPU after
renderer 0 2.20
gpu 0 2.08
utility 0 0.11
agent-or-node 0 0.06
main 0 0
daemon 0 0
total 0 4.51 (p95 8.40)

Total mean RSS is unchanged across the two runs (934 MiB → 937 MiB), so only CPU reporting changed. A full run including the build step (no --skip-build) also exits 0 and writes its JSON report.

ORCA_BACKGROUND_LAUNCH=1 is set so the measured window is never shown, per the launch policy in AGENTS.md.

Why

#25235 tracks this: Windows performance work is tracked in #9300, and it cannot cite numbers the platform cannot produce. An all-zero CPU column is worse than a crash, because it looks like a successful measurement of an idle app — I only caught it by sampling the same app independently over CDP and Get-Process, which showed non-zero idle CPU.

Alternatives considered:

  • Fixing npx by spawning through a shell. Rejected: it changes quoting/argument handling and duplicates what run-electron-vite-build.mjs already does correctly, including the boot-graph check.
  • Computing instantaneous CPU from Win32_PerfFormattedData for percentCpu. Rejected as unnecessary: the delta path already exists and is what the other classes use; it only needed a real timestamp source. This keeps one code path instead of two.
  • Rewriting the Windows reader to stop parsing PowerShell output entirely. That is the right direction for the intermittent JSON.parse failure ([Perf] bench:idle-cpu on Windows: intermittent JSON.parse failure while reading the process table #25236) and is deliberately not mixed into this PR, because I could not reproduce that failure on demand and did not want to change the reader without a verifiable result.

Linked Issue

Fixes #25235

(The other PR from this issue makes three benchmark scripts run on Windows at all; the intermittent JSON.parse failure this issue also mentions is #25236.)

Visual Proof

N/A

No UI or user-facing behaviour change: build tooling and a benchmark's JSON report.

Testing

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

No new test file for the benchmark itself: the benchmark is the test. Before the change the build step fails and the report contains zeros; after it, the same invocation exits 0 and contains the numbers above. The Windows time mapping that replaced the all-zero report is now covered directly: it lives in cimCpuSeconds(), a pure helper the test can assert without mocking Get-CimInstance (added after review, following the CodeRabbit finding).

Check Command (Windows, Node 22.19) Result
Build step, full run ORCA_BACKGROUND_LAUNCH=1 node config/scripts/run-idle-cpu-benchmark.mjs --warmup-ms 5000 --sample-ms 10000 --output idle.json before: spawnSync npx ENOENT; after: exit 0, 77 KB report written
CPU reporting same with --skip-build --sample-ms 15000 before: all-zero CPU; after: table above
Lint on changed files node node_modules/oxlint/bin/oxlint <2 files> pass
Changed-code gate node config/scripts/check-changed-code-quality.mjs pass, 0 findings across 2 files

Platforms tested: Windows only, the platform that was broken. The Unix reader is untouched, and the Windows reader keeps its previous null fallback, so macOS/Linux behaviour is unchanged; I did not run them.

AI Disclosure

Written with an AI coding agent, session model deepseek-v4.1-flash (provider opencode-go). Every command and number above was produced on this machine.

Review

  • Cross-platform: the Unix path is untouched (readUnixProcesses unchanged). The new Windows fields are additive and guarded with Number.isFinite, falling back to the previous behaviour, so a host that does not return them behaves exactly as before. The build change removes a POSIX-only assumption rather than adding a platform branch.
  • SSH / remote / local: not applicable — a local benchmark harness; no host, wire, provider or credential path.
  • Agent and integration compatibility: none touched.
  • Performance risk: none to the app. The added CIM fields are two integers per process already being enumerated; the benchmark's own overhead is unchanged. The accuracy change makes the harness more sensitive, which is the point.
  • UI quality: not applicable.
  • Security: the PowerShell invocation shape is unchanged (same cmdlet, same -NoProfile, same parsing), no new subprocess, network or filesystem access, and AGENTS.md's rule about process enumeration applies to Orca's own code rather than this diagnostic harness.
  • Self-review of the diff: the arrow function changed from an expression body to a block body to compute the timestamp, so I re-checked bracket balance and that readProcessRows's contract ({pid, ppid, percentCpu, cpuTimeSeconds, rssBytes, command}) is unchanged; percentCpu: 0 is kept because the delta path takes precedence and is what the other platforms use.

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

  • Limitations: the numbers above are a development-mode --mode e2e build with no terminal panes and no agents, from a single machine, so they are not a production baseline and not a performance claim about the app — they are evidence that the instrument now reports CPU at all. And the intermittent JSON.parse failure in the same reader ([Perf] bench:idle-cpu on Windows: intermittent JSON.parse failure while reading the process table #25236) is still present; if it hits, the run fails loudly in the sampling loop rather than reporting zeros.
  • Remote SSH / WSL / mobile: unaffected; the harness measures the local desktop app.
  • Backwards compatibility: no user data, persisted state, wire format or build output changes.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • 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 — lint on changed files and the changed-code gate pass; the full suite could not run here (no MSVC, ensure-native-runtime gates pnpm test); CI will cover

@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 — both fixes look correct. One documentation follow-up worth folding in.

Reviewed changes

  • Windows CPU reporting — readWindowsProcesses now selects UserModeTime and KernelModeTime from Win32_Process and derives cpuTimeSeconds from their sum (÷ 10,000,000). This feeds the sampler's existing delta path, which previously always produced 0 on Windows because both cpuTimeSeconds was null and percentCpu was hardcoded 0. The null fallback is preserved when a host omits the fields.
  • Build invocation — buildAppIfNeeded now spawns config/scripts/run-electron-vite-build.mjs via process.execPath instead of npx electron-vite build, removing the Windows spawnSync npx ENOENT (npx.cmd is not executable by execFileSync) and reusing the repo's single build path, which also runs the renderer boot-graph check.

I verified the unit conversion (100 ns ticks → seconds), that the wrapper accepts --mode e2e and forwards VITE_EXPOSE_STORE, that the Unix reader is untouched, and that run still propagates cwd/env/stdio.

ℹ️ Nitpicks

  • docs/reference/renderer-agent-status-performance.md:203-206 still states "Windows process CPU collection currently cannot support this comparison." This PR is exactly what makes Windows produce CPU numbers, so that caveat is now stale and should be updated (or narrowed to the remaining --mode e2e / PowerShell caveats).

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b89a1894-45d3-4c25-9f74-8746e55027de
📥 Commits

Reviewing files that changed from the base of the PR and between 31fef6a4eadfb7eff5578157fbae0390606706b9 and 517ff72.

📒 Files selected for processing (2)
  • config/scripts/idle-cpu-process-sampling.mjs
  • config/scripts/idle-cpu-process-sampling.test.mjs

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.


📝 Walkthrough

Walkthrough

The idle CPU benchmark now runs the Electron Vite build through the Node-run wrapper. The Windows process query requests user-mode and kernel-mode CPU times. The sampler maps their valid sum to seconds and uses null when either value is unavailable or non-finite.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to 517ff

The Windows idle-CPU benchmark build and CPU-reporting changes appear mergeable after normal checks.

Architecture Summary

Architecture risk: 🟡 Medium · up to 517ff

The change affects 1 system.

Changed systems: config

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — config (service) was modified; 3 changed files map to changed impact.

Before / after behavior

  • observed — Modified behavior in config/scripts/run-idle-cpu-benchmark.mjs: buildAppIfNeeded replaces the direct npx electron-vite build --mode e2e invocation with the Node-run run-electron-vite-build.mjs wrapper, preserving the working directory, inherited stdio, and VITE_EXPOSE_STORE environment setting.
  • observed — Modified behavior in config/scripts/idle-cpu-process-sampling.mjs: Adds cimTimeSeconds, which converts finite numeric CIM time values from 100-nanosecond units to seconds and returns null otherwise, and exports cimCpuSeconds, which returns the sum only when both user-mode and kernel-mode times convert successfully; otherwise it returns null.
  • observed — Modified behavior in config/scripts/idle-cpu-process-sampling.mjs: The Windows PowerShell query now selects UserModeTime and KernelModeTime alongside the existing process fields.
  • observed — Modified behavior in config/scripts/idle-cpu-process-sampling.mjs: Windows process rows now derive cpuTimeSeconds from both CIM time fields using cimCpuSeconds, replacing the previous unconditional null.

Reliability and maintainability

  • inferred — Risk-relevant change factors for config: blast_radius_1; direct_dependents_1
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning [#25235] The PR routes the idle-CPU build through run-electron-vite-build.mjs and reads finite numeric UserModeTime and KernelModeTime values. Added tests cover conversion and invalid or missing… Use pathToFileURL(...).href for the computed import specifiers in the three files identified by [#25235], then verify the affected scripts load on Windows.
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Out of Scope Changes check ✅ Passed The changed build path, Windows CPU-time mapping, and mapping tests all support the idle-CPU fixes requested by [#25235]. The diff shows no unrelated changes.
Title check ✅ Passed The title clearly summarizes both main changes: fixing the idle-CPU benchmark build and CPU reporting on Windows.
Description check ✅ Passed The description covers the required sections, links the issue, explains the changes and rationale, and reports Windows testing and limitations. The manual-testing checkbox is unchecked despite the det…
Full details: Linked Issues check

Explanation

[#25235] The PR routes the idle-CPU build through run-electron-vite-build.mjs and reads finite numeric UserModeTime and KernelModeTime values. Added tests cover conversion and invalid or missing values. The Windows import-path defects remain: session-write-hot-path-benchmark.mjs, agent-inspection-cadence-batching-benchmark.mjs, and capture-fish-mode2031-trace.mjs still pass path.join(...) results directly to import(). The separate sampler parse failure in [#25236] is not a requirement of this issue.

  • Fix all pre-merge checks with AI
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: f9492146-3745-4c1e-8fc1-84c53db9bbcb
📥 Commits

Reviewing files that changed from the base of the PR and between 87bc51d and 77bc6f9100d919334b6b858b4f3cd257a39363b7.

📒 Files selected for processing (2)
  • config/scripts/idle-cpu-process-sampling.mjs
  • config/scripts/run-idle-cpu-benchmark.mjs

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

@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

Incremental delta since the prior pullfrog review (77bc6f9 → 31fef6a). The new commit tightens the Windows CIM time handling raised in prior feedback:

  • Rejects a non-numeric Win32_Process time instead of coercing it — readWindowsProcesses now reads UserModeTime/KernelModeTime through a new cimTimeSeconds helper that returns null unless the CIM payload delivered a finite number. This replaces Number(entry.UserModeTime), whose Number(null) === 0 coercion could have produced a kernel-only delta rather than the percentCpu fallback. The null fallback is preserved for null, a missing field, and strings.

I verified the helper's contract, that both fields must be numeric before the delta is used, that 0 remains a valid counter value, and that the Unix reader and the build-invocation fix are untouched by this commit.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@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)
config/scripts/idle-cpu-process-sampling.mjs (1)

82-98: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a focused test for Windows CIM time mapping.

idle-cpu-process-sampling.test.mjs supplies synthetic readRows, so its tests bypass readWindowsProcesses() and cimTimeSeconds(). Mock node:child_process and set process.platform to win32. Assert the converted CPU-time sum and that a missing or non-finite time field maps to null, preserving the sampler’s percentCpu fallback.


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 3830789a-0784-47da-8b5b-1db493cb8310
📥 Commits

Reviewing files that changed from the base of the PR and between 77bc6f9100d919334b6b858b4f3cd257a39363b7 and 31fef6a4eadfb7eff5578157fbae0390606706b9.

📒 Files selected for processing (1)
  • config/scripts/idle-cpu-process-sampling.mjs

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

@paoValle

paoValle commented Oct 4, 2026

Copy link
Copy Markdown
Contributor Author

Both findings on this PR are addressed. The sentinel one was correct, and I verified the fix against real data before tightening the check.

Analysis. Number(null) is 0, and 0 is also a real counter value, so an absent UserModeTime/KernelModeTime passed the finite check and the reader would have produced a kernel-only delta instead of taking the ps-style fallback. That is the same "silently wrong number" class this PR exists to remove, so it was worth fixing rather than dismissing as theoretical — reporting a plausible-looking number is worse here than failing loudly.

What changed — 31fef6a4ea: a field is accepted only when the CIM payload actually delivered a number (typeof value === 'number' && Number.isFinite(value)), so null, a missing field and a string all take the fallback. The extraction moved into a small named helper so the reason is visible at the call site.

Verified before tightening, because an over-strict check would have reverted the CPU reporting this PR restores: Get-CimInstance Win32_Process | Select-Object UserModeTime,KernelModeTime | ConvertTo-Json returns JSON numbers on this host — 234 entries, none null or absent, and 0 for PID 0 is a legitimate counter value rather than a sentinel.

Results (Windows, --mode e2e build, one empty worktree, 12 s sample, measured after the tightened check):

KPI before this PR after
total mean CPU 0 (hardcoded) 4.40%
total p95 CPU 0 14.48%
renderer mean CPU 0 3.51%
gpu mean CPU 0 0.74%
total mean RSS 934 MiB 962 MiB

RSS is unchanged within run-to-run variation, so the change affects CPU reporting only. The build fix is verified separately: a full run including the build step now exits 0 and writes its report, where it previously died with spawnSync npx ENOENT before sampling anything.

Not addressed in this PR: the intermittent JSON.parse failure in the same reader is filed as #25236. I could not reproduce it on demand — 15 consecutive captures with the app running parsed fine, and control characters in process command lines are escaped correctly by PowerShell 5.1 — so I did not want to change the parse without a verifiable result.

Three independent Windows defects in the idle-CPU benchmark (its report is
what Windows performance work would cite):

- `buildAppIfNeeded` spawned `npx`, which is `npx.cmd` on Windows, so
  execFileSync failed with ENOENT before any sampling. Build through
  `config/scripts/run-electron-vite-build.mjs` instead — the repo's own
  Windows-safe wrapper, which also runs the boot-graph verification.
- `readWindowsProcesses` returned `cpuTimeSeconds: null`, so the sampler's
  per-process CPU delta (idle-cpu-process-sampling.mjs:198) fell back to
  the hardcoded `percentCpu: 0` and every CPU KPI in the report was zero.
  Read `UserModeTime`/`KernelModeTime` from `Win32_Process` (100 ns units)
  and keep `null` when a host does not return them.

Measured on Windows, same options before and after the CPU fix:

| class | mean CPU before | mean CPU after |
| --- | ---: | ---: |
| renderer | 0 | 2.20 |
| gpu | 0 | 2.08 |
| utility | 0 | 0.11 |
| agent-or-node | 0 | 0.06 |
| total | 0 | 4.51 (p95 8.40) |

RSS is unchanged (934 MiB -> 937 MiB), so only the CPU reporting changed.

Refs stablyai#25235
… as zero

Review follow-up (CodeRabbit). `Number(null)` is `0`, which is also a real
counter value, so an absent `UserModeTime`/`KernelModeTime` passed the
finite check and the sampler would report a kernel-only delta instead of
taking the fallback. Require an actual number from the CIM payload.

Verified on Windows that the real payload still reports CPU once the check
is tight: total mean 4.40%, p95 14.48%, renderer 3.51%.
The mapping was only reachable through Get-CimInstance, so no test ran it.
Lift it into cimCpuSeconds and assert the 100ns-to-seconds sum plus the
missing / string / non-finite cases that must stay null.
@paoValle
paoValle force-pushed the fix/windows-idle-cpu-build branch from 31fef6a to 517ff72 Compare October 5, 2026 07:30
@paoValle

paoValle commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the CodeRabbit finding. cimCpuSeconds() is now a pure helper rather than an inline expression inside readWindowsProcesses(), so it can be asserted without mocking Get-CimInstance: the test covers the 100ns-to-seconds sum and the missing / string / non-finite cases that must stay null (the sentinel case this PR was already tightened for).

config/scripts/idle-cpu-process-sampling.test.mjs — 4 passed. Also rebased onto current main; core suite unchanged.

@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

Incremental delta since the prior pullfrog review (31fef6a → 517ff72). The branch was rebased onto 2b0ce17; aaafe3a is a rebase of the previously reviewed 31fef6a, so the only new content is 517ff72:

  • Extracted the Windows CPU-time mapping into an exported pure helper — cimCpuSeconds(entry) now holds the UserModeTime/KernelModeTime handling that previously lived inline in readWindowsProcesses. The null-unless-both-finite contract is unchanged, so the sampler's percentCpu fallback and the real delta path behave exactly as before.
  • Covered the mapping with direct tests — idle-cpu-process-sampling.test.mjs asserts the 100 ns sum (10_000_000 + 25_000_000 → 3.5) and that missing, string, NaN, and Infinity inputs map to null. The non-numeric case fails if the old Number(...) coercion were reintroduced, so the test is real coverage rather than a tautology.

I verified the extraction is behavior-preserving and ran the test file and linter locally: vitest run config/scripts/idle-cpu-process-sampling.test.mjs → 4 passed; oxlint on both changed files → 0 warnings.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@paoValle

paoValle commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Closing this rather than letting it age, for the same reason as the other Windows-benchmark PR: it repairs the harness, not a user-visible path, and seven small PRs at once is a worse trade for you than four fewer. #25235 stays open with what was measured — the npx spawn failure and the 0%-CPU report. Nothing here is wrong.

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.

[Perf] Windows: two benchmarks crash on import and bench:idle-cpu cannot build or sample, so Windows KPIs are unmeasurable

1 participant