Skip to content

chore(perf): add renderer agent-status benchmark harness - #13905

Merged
nwparker merged 1 commit into
mainfrom
nwparker/perf-agent-status-tooling
Aug 12, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/perf-agent-status-tooling

Conversation

@nwparker

@nwparker nwparker commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Splits run-idle-cpu-benchmark.mjs into three composable pieces — a renderer scale fixture, an in-page timing probe, and process sampling — and records a measured origin/main baseline so the agent-status batching slice has an auditable before that someone other than its author can reproduce.

Touches nothing under src/. Worst case is a broken dev script.

The baseline

macOS arm64, 100 worktrees at lineage depth 99, 100 agent rows, 10s warmup / 30s sample, 3 reps, median, measured on origin/main:

Metric Idle control 2,000 no-op publications @ 1ms
Renderer mean CPU 6.63% 18.25%
Renderer p95 CPU 17.11% 32.59%
p50 scheduling drift — 5,150.3 ms
p95 scheduling drift 1.6 ms 9,802.9 ms
Store listeners 9,279 9,279

~11.6 points of mean renderer CPU are attributable to publication fanout alone, with 200 spinner animations running in both arms.

One thing worth knowing before you audit the batching PR

The long-task observer recorded zero entries in all four runs. Individual publications are each well under 50 ms, so at this scale the cost surfaces as scheduling drift and sustained CPU, not as discrete long tasks.

Do not read a zero long-task count as contradicting the "p95 long task 4,653 ms" figure in earlier write-ups — that came from a payload workload, not bare publications.

Deviations

  • The agent-status write workload is not included: it needs setAgentStatuses/transactAgentStatuses, which are not on main. It lands with the store slice. The --agent-status-write-mode flags, import, and call site were stripped rather than left dangling, since keeping the import with the module excluded leaves the script unloadable.
  • The HTML report generator (~1,000 lines, no identified consumer) and its committed output artifact are excluded.
  • The accompanying doc is labelled as a prototype target rather than a shipped result, with a note that the work lands in slices. Landing an unqualified "this design is adopted" doc would be misleading while the store slice is still in review.

Validation

typecheck:tsc:web exit 0. 1 test file / 2 tests pass. check:code-quality:changed 0 new findings. check:max-lines-ratchet OK. oxfmt --check and oxlint clean.

Test results here are author-reported and were not independently re-run.

Made with Orca 🐋

Splits run-idle-cpu-benchmark.mjs into a scale fixture, an in-page timing
probe, and process sampling, and records a measured origin/main baseline so
the agent-status batching slice has an auditable before.

The agent-status write workload is not included: it needs setAgentStatuses,
so it lands with the store slice.
@coderabbitai

coderabbitai Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR adds cross-platform process-tree sampling with workload-aware timing, process classification, statistics, inventory reporting, and termination. It adds renderer scaling fixtures, census collection, timer and long-task probes, and Zustand publication workloads. The benchmark CLI gains scaling controls, readiness checks, concurrent workload execution, imported sampling, and expanded reports. A renderer agent-status performance specification documents the measured design and acceptance criteria.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the benchmark and validation, but it omits the required Screenshots, AI Review Report, Security Audit, and Notes sections. Add all required template sections, complete the Testing checklist, and document AI review, security audit, platform checks, and relevant risks.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: adding a renderer agent-status benchmark harness.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
config/scripts/run-idle-cpu-benchmark.mjs (1)

436-454: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

The report embeds data that the new specification forbids in a shareable artifact.

docs/reference/renderer-agent-status-performance.md states that raw process inventories, temporary paths, pane identifiers, and DOM text are diagnostic-only and must not be embedded in the shareable report. The report assembled here contains all of them:

  • processInventory carries commandSamples, which are full command lines that include the developer home path and username.
  • samples[].processes[].command carries the same command lines for every sample.
  • options, fixtureState, and scaleFixtureState carry temporary repository paths, worktree IDs, and pane-derived tab IDs.
  • rendererCensus* carries mountedIds and the typing-diagnostic census.

The console block at Lines 460-476 also prints processInventory. Split the artifact into a redacted shareable report and an opt-in diagnostic report, or redact command lines and paths before writing.

🧹 Nitpick comments (6)
config/scripts/idle-cpu-process-sampling.mjs (3)

84-109: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Index rows by pid to avoid the repeated linear scan.

descendantsOf calls rows.find for every visited pid. The process list already exists in memory, and the sampler calls this function on every interval. A pid map removes the quadratic scan.

♻️ Proposed refactor
 export function descendantsOf(rows, rootPid) {
   const children = new Map()
+  const rowByPid = new Map()
   for (const row of rows) {
     const list = children.get(row.ppid) ?? []
     list.push(row)
     children.set(row.ppid, list)
+    rowByPid.set(row.pid, row)
   }
   const result = []
   const stack = [rootPid]
   const seen = new Set()
   while (stack.length > 0) {
     const pid = stack.pop()
     if (seen.has(pid)) {
       continue
     }
     seen.add(pid)
-    const row = rows.find((candidate) => candidate.pid === pid)
+    const row = rowByPid.get(pid)

58-78: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Windows sampling reports 0% CPU for every process.

readWindowsProcesses sets percentCpu: 0 and cpuTimeSeconds: null. The sampler then falls back to row.percentCpu, so every Windows sample records 0% CPU and the report looks like a valid measurement. docs/reference/renderer-agent-status-performance.md already states that Windows CPU collection cannot support this comparison. Make that explicit in the data, for example by adding a cpuSupported: false marker that the report surfaces, or by reading Win32_Process UserModeTime/KernelModeTime so a CPU-time delta is available.


317-323: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Terminating by recorded pid can signal a recycled pid.

terminateProcesses receives the descendant list that run-idle-cpu-benchmark.mjs captures before app.close() and a 250 ms wait. The OS can reuse a pid in that interval. The blast radius is small for a local benchmark, but a pid-existence recheck before the signal removes the risk.

config/scripts/idle-cpu-process-sampling.test.mjs (1)

30-65: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the pure parsing and classification functions.

The suite covers only the sampling window. parseCpuTimeSeconds, parseUnixProcesses, descendantsOf, classify, and summarizeSamples are pure and deterministic, and they carry the platform-specific ps format assumptions. A rejected workloadPromise path is also untested; the sampler is expected to rethrow that error. These tests are cheap and protect the measurement correctness.

config/scripts/idle-cpu-renderer-scale-fixture.mjs (1)

163-167: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Select agent rows with a CSS selector instead of scanning every element.

querySelectorAll('*') materializes the whole sidebar subtree, then filters by class. A direct selector is equivalent and avoids the full scan.

♻️ Proposed refactor
-    const mountedAgentRows = [...(sidebar?.querySelectorAll('*') ?? [])].filter(
-      (element) =>
-        element.classList.contains('group/agent-row') ||
-        element.classList.contains('compact-agent-row')
-    ).length
+    const mountedAgentRows =
+      sidebar?.querySelectorAll('.group\\/agent-row, .compact-agent-row').length ?? 0
config/scripts/idle-cpu-renderer-timing-probe.mjs (1)

102-113: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Make probe installation and stop idempotent.

startRendererTimingProbe overwrites window.__orcaIdleCpuTimingProbe without stopping a previously installed probe, so a second call leaves an orphan 100 ms timer that adds CPU work to the measurement. stop also leaves the object in place, so a repeated stop call returns a second snapshot from a stopped timer. Clear the previous probe on install and delete the global on stop.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 22f7a30f-889a-453f-b0e7-9e6f6a65ef91

📥 Commits

Reviewing files that changed from the base of the PR and between 96c17b4 and 64e2959.

📒 Files selected for processing (7)
  • .gitignore
  • config/scripts/idle-cpu-process-sampling.mjs
  • config/scripts/idle-cpu-process-sampling.test.mjs
  • config/scripts/idle-cpu-renderer-scale-fixture.mjs
  • config/scripts/idle-cpu-renderer-timing-probe.mjs
  • config/scripts/run-idle-cpu-benchmark.mjs
  • docs/reference/renderer-agent-status-performance.md

Comment on lines +345 to +392
const fixtureState = await page.evaluate(async (repoPath) => {
const added = await window.api.repos.add({ path: repoPath })
if ('error' in added) {
return { error: added.error }
}
const store = window.__store
await store?.getState().fetchRepos()
const repo = store?.getState().repos.find((candidate) => candidate.path === repoPath)
const repo = store?.getState().repos.find((candidate) => candidate.id === added.repo.id)
if (repo) {
await store.getState().updateRepo(repo.id, { externalWorktreeVisibility: 'show' })
await store.getState().fetchWorktrees(repo.id)
const detected = await store
.getState()
.fetchWorktrees(repo.id, { requireAuthoritative: true })
const importedWorktreePaths = (
store.getState().detectedWorktreesByRepo[repo.id]?.worktrees ?? []
)
.filter((worktree) => !worktree.selectedCheckout)
.map((worktree) => worktree.path)
const updated = await store.getState().updateRepo(repo.id, {
externalWorktreeVisibility: 'show',
importedExternalWorktreePaths: importedWorktreePaths,
externalWorktreeInboxBaselinePaths: importedWorktreePaths
})
const refreshed = await store
.getState()
.fetchWorktrees(repo.id, { requireAuthoritative: true })
return {
detected,
updated,
refreshed,
detectedCount: store.getState().detectedWorktreesByRepo[repo.id]?.worktrees.length ?? 0,
importedCount: importedWorktreePaths.length,
visibleCount: store.getState().worktreesByRepo[repo.id]?.length ?? 0
}
}
return { error: 'repo-not-found' }
}, repoDir)
console.log(`[idle-cpu] fixture ${JSON.stringify(fixtureState)}`)
await page.waitForFunction(
() => window.__store?.getState().workspaceSessionReady === true,
(expectedWorktrees) => {
const state = window.__store?.getState()
return (
state?.workspaceSessionReady === true &&
Object.values(state.worktreesByRepo).flat().length === expectedWorktrees
)
},
options.worktrees,
{ timeout: 180_000 }
)

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Fail fast when repository setup returns an error.

fixtureState can be { error: ... } from Line 348 or { error: 'repo-not-found' } from Line 379. The script only logs it at Line 381 and then enters the 180-second waitForFunction at Line 382, which can never satisfy the worktree count. The run then fails with a timeout that hides the real cause. Throw as soon as fixtureState.error is set.

🐛 Proposed fix
     console.log(`[idle-cpu] fixture ${JSON.stringify(fixtureState)}`)
+    if (fixtureState.error) {
+      throw new Error(`Repository fixture setup failed: ${JSON.stringify(fixtureState.error)}`)
+    }
     await page.waitForFunction(
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const fixtureState = await page.evaluate(async (repoPath) => {
const added = await window.api.repos.add({ path: repoPath })
if ('error' in added) {
return { error: added.error }
}
const store = window.__store
await store?.getState().fetchRepos()
const repo = store?.getState().repos.find((candidate) => candidate.path === repoPath)
const repo = store?.getState().repos.find((candidate) => candidate.id === added.repo.id)
if (repo) {
await store.getState().updateRepo(repo.id, { externalWorktreeVisibility: 'show' })
await store.getState().fetchWorktrees(repo.id)
const detected = await store
.getState()
.fetchWorktrees(repo.id, { requireAuthoritative: true })
const importedWorktreePaths = (
store.getState().detectedWorktreesByRepo[repo.id]?.worktrees ?? []
)
.filter((worktree) => !worktree.selectedCheckout)
.map((worktree) => worktree.path)
const updated = await store.getState().updateRepo(repo.id, {
externalWorktreeVisibility: 'show',
importedExternalWorktreePaths: importedWorktreePaths,
externalWorktreeInboxBaselinePaths: importedWorktreePaths
})
const refreshed = await store
.getState()
.fetchWorktrees(repo.id, { requireAuthoritative: true })
return {
detected,
updated,
refreshed,
detectedCount: store.getState().detectedWorktreesByRepo[repo.id]?.worktrees.length ?? 0,
importedCount: importedWorktreePaths.length,
visibleCount: store.getState().worktreesByRepo[repo.id]?.length ?? 0
}
}
return { error: 'repo-not-found' }
}, repoDir)
console.log(`[idle-cpu] fixture ${JSON.stringify(fixtureState)}`)
await page.waitForFunction(
() => window.__store?.getState().workspaceSessionReady === true,
(expectedWorktrees) => {
const state = window.__store?.getState()
return (
state?.workspaceSessionReady === true &&
Object.values(state.worktreesByRepo).flat().length === expectedWorktrees
)
},
options.worktrees,
{ timeout: 180_000 }
)
const fixtureState = await page.evaluate(async (repoPath) => {
const added = await window.api.repos.add({ path: repoPath })
if ('error' in added) {
return { error: added.error }
}
const store = window.__store
await store?.getState().fetchRepos()
const repo = store?.getState().repos.find((candidate) => candidate.id === added.repo.id)
if (repo) {
const detected = await store
.getState()
.fetchWorktrees(repo.id, { requireAuthoritative: true })
const importedWorktreePaths = (
store.getState().detectedWorktreesByRepo[repo.id]?.worktrees ?? []
)
.filter((worktree) => !worktree.selectedCheckout)
.map((worktree) => worktree.path)
const updated = await store.getState().updateRepo(repo.id, {
externalWorktreeVisibility: 'show',
importedExternalWorktreePaths: importedWorktreePaths,
externalWorktreeInboxBaselinePaths: importedWorktreePaths
})
const refreshed = await store
.getState()
.fetchWorktrees(repo.id, { requireAuthoritative: true })
return {
detected,
updated,
refreshed,
detectedCount: store.getState().detectedWorktreesByRepo[repo.id]?.worktrees.length ?? 0,
importedCount: importedWorktreePaths.length,
visibleCount: store.getState().worktreesByRepo[repo.id]?.length ?? 0
}
}
return { error: 'repo-not-found' }
}, repoDir)
console.log(`[idle-cpu] fixture ${JSON.stringify(fixtureState)}`)
if (fixtureState.error) {
throw new Error(`Repository fixture setup failed: ${JSON.stringify(fixtureState.error)}`)
}
await page.waitForFunction(
(expectedWorktrees) => {
const state = window.__store?.getState()
return (
state?.workspaceSessionReady === true &&
Object.values(state.worktreesByRepo).flat().length === expectedWorktrees
)
},
options.worktrees,
{ timeout: 180_000 }
)

Comment on lines +167 to +176
The benchmark launches an E2E-mode Electron build with the store exposed only
for instrumentation. It creates 100 worktrees in one expanded lineage, verifies
100 mounted cards, captures the store listener census, and then applies seeded
ordered agent-status traffic through the real store action.

The benchmark measures the synchronous store action, not the live IPC leading
edge or post-commit notification path. A real-store snapshot test covers the
end-to-end budget for 100 panes with auto-generated titles enabled: one status,
one bulk generated-title, and one bulk resolved-title publication. Disabling
generated titles removes that middle publication, independent of pane count.

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

The "Benchmark contract" section contradicts the "Harness" section.

Lines 168-170 state that the benchmark applies seeded ordered agent-status traffic through the real store action, and Lines 172-176 describe measuring that store action. Lines 219-221 state that the agent-status write workload is not in the harness yet. Mark the write-workload parts of this section as planned, in the same way the Status section does.

Comment on lines +208 to +211
The sampling window extends past `--sample-ms` until the workload settles, and
fails the run rather than reporting a truncated window if the workload overruns
the guard. That is why a 2,000-publication run reports a measured window longer
than the requested one.

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

The stated reason for a longer measured window does not match the documented baseline.

The sampler extends the window only when the workload settles after --sample-ms. The baseline in this document uses --sample-ms 30000 and reports a median completion of 12,325.7 ms, so the window is not extended in that run. Correct the sentence, or state the configuration in which the extension actually applies.

@nwparker
nwparker merged commit 9c091cf into main Aug 12, 2026
45 checks passed
@nwparker
nwparker deleted the nwparker/perf-agent-status-tooling branch August 12, 2026 07:37
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
)

Splits run-idle-cpu-benchmark.mjs into a scale fixture, an in-page timing
probe, and process sampling, and records a measured origin/main baseline so
the agent-status batching slice has an auditable before.

The agent-status write workload is not included: it needs setAgentStatuses,
so it lands with the store slice.
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