Fix Windows Resource Manager memory and CPU attribution (#8845)

Use a single CIM sample for Windows process memory and CPU attribution, with bounded Typeperf memory fallback and safe CPU delta recovery.
This commit is contained in:
Cal
2026-07-21 02:04:37 -04:00
committed by GitHub
parent 6785f9d1a8
commit 4877d0b65c
3 changed files with 786 additions and 119 deletions
+437 -49
View File
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import os from 'node:os'
import type { MemorySnapshotStore } from './collector'
type AppMetricFixture = {
@@ -8,8 +9,9 @@ type AppMetricFixture = {
memory: { workingSetSize: number }
}
const { appMetricsMock, execMock, listRegisteredPtysMock } = vi.hoisted(() => ({
const { appMetricsMock, execFileMock, execMock, listRegisteredPtysMock } = vi.hoisted(() => ({
appMetricsMock: vi.fn<() => AppMetricFixture[]>(() => []),
execFileMock: vi.fn(),
execMock: vi.fn(),
listRegisteredPtysMock: vi.fn()
}))
@@ -22,7 +24,13 @@ vi.mock('electron', () => ({
vi.mock('child_process', () => ({
exec: (cmd: string, opts: unknown, cb: (err: Error | null, out: { stdout: string }) => void) =>
execMock(cmd, opts, cb)
execMock(cmd, opts, cb),
execFile: (
file: string,
args: string[],
opts: unknown,
cb: (err: Error | null, stdout: string, stderr: string) => void
) => execFileMock(file, args, opts, cb)
}))
vi.mock('./pty-registry', () => ({
@@ -34,6 +42,11 @@ async function loadCollector() {
return await import('./collector')
}
async function loadWindowsProcessResourceCollector() {
vi.resetModules()
return await import('./windows-process-resource-collector')
}
const emptyStore = {
getWorktreeMeta: () => undefined,
getRepo: () => undefined
@@ -102,48 +115,65 @@ describe('parsePsOutput', () => {
})
})
describe('parseWmicOutput', () => {
it('emits one row per blank-line-delimited stanza', async () => {
const { parseWmicOutput } = await loadCollector()
const stdout = [
'ParentProcessId=1',
'ProcessId=100',
'WorkingSetSize=2048',
'',
'ParentProcessId=100',
'ProcessId=200',
'WorkingSetSize=1024',
''
].join('\r\n')
describe('parseWindowsProcessOutput', () => {
it('parses tab-delimited CIM process rows', async () => {
const { parseWindowsProcessOutput } = await loadWindowsProcessResourceCollector()
const rows = parseWmicOutput(stdout)
expect(rows).toEqual([
expect(parseWindowsProcessOutput('100\t1\t2048\r\n200\t100\t1024')).toEqual([
{ pid: 100, ppid: 1, cpu: 0, memory: 2048 },
{ pid: 200, ppid: 100, cpu: 0, memory: 1024 }
])
})
it('flushes the final stanza even without a trailing blank line', async () => {
const { parseWmicOutput } = await loadCollector()
const rows = parseWmicOutput('ProcessId=100\nParentProcessId=1\nWorkingSetSize=512')
expect(rows).toEqual([{ pid: 100, ppid: 1, cpu: 0, memory: 512 }])
it('skips malformed rows and clamps invalid memory to zero', async () => {
const { parseWindowsProcessOutput } = await loadWindowsProcessResourceCollector()
expect(
parseWindowsProcessOutput(
[
'garbage',
'abc\t1\t100',
'10\txyz\t100',
'0\t0\t100',
'-5\t0\t100',
'30\t-1\t100',
'20\t1\t-50'
].join('\n')
)
).toEqual([{ pid: 20, ppid: 1, cpu: 0, memory: 0 }])
})
it('skips stanzas missing pid or ppid', async () => {
const { parseWmicOutput } = await loadCollector()
// Why: wmic occasionally emits a stanza with only WorkingSetSize set
// (e.g. a process that exited mid-query). Dropping such rows avoids
// injecting ghost zero-pid entries into the index.
const stdout = ['WorkingSetSize=999', '', 'ProcessId=100', 'ParentProcessId=1'].join('\n')
const rows = parseWmicOutput(stdout)
expect(rows).toEqual([{ pid: 100, ppid: 1, cpu: 0, memory: 0 }])
it('preserves empty CIM field positions instead of shifting CPU ticks into memory', async () => {
const { parseWindowsProcessOutput } = await loadWindowsProcessResourceCollector()
expect(parseWindowsProcessOutput('100\t1\t\t200\t300\t638830000000000000')).toEqual([
{ pid: 100, ppid: 1, cpu: 0, memory: 0 }
])
})
})
describe('parseTypeperfProcessOutput', () => {
it('joins PID, parent PID, and working-set counters by process instance', async () => {
const { parseTypeperfProcessOutput } = await loadWindowsProcessResourceCollector()
const stdout = [
'"(PDH-CSV 4.0)","\\\\HOST\\Process(node)\\ID Process","\\\\HOST\\Process(node#1)\\ID Process","\\\\HOST\\Process(node)\\Creating Process ID","\\\\HOST\\Process(node#1)\\Creating Process ID","\\\\HOST\\Process(node)\\Working Set","\\\\HOST\\Process(node#1)\\Working Set"',
'"07/15/2026 01:44:54.514","100.000000","200.000000","1.000000","100.000000","2048.000000","4096.000000"'
].join('\r\n')
expect(parseTypeperfProcessOutput(stdout)).toEqual([
{ pid: 100, ppid: 1, cpu: 0, memory: 2048 },
{ pid: 200, ppid: 100, cpu: 0, memory: 4096 }
])
})
it('ignores lines without an equals separator', async () => {
const { parseWmicOutput } = await loadCollector()
const rows = parseWmicOutput(['garbage line', 'ProcessId=5', 'ParentProcessId=1'].join('\n'))
expect(rows).toEqual([{ pid: 5, ppid: 1, cpu: 0, memory: 0 }])
it('ignores aggregate and incomplete rows and clamps invalid memory', async () => {
const { parseTypeperfProcessOutput } = await loadWindowsProcessResourceCollector()
const stdout = [
'"(PDH-CSV 4.0)","\\\\HOST\\Process(_Total)\\ID Process","\\\\HOST\\Process(cmd)\\ID Process","\\\\HOST\\Process(orphan)\\ID Process","\\\\HOST\\Process(_Total)\\Creating Process ID","\\\\HOST\\Process(cmd)\\Creating Process ID","\\\\HOST\\Process(_Total)\\Working Set","\\\\HOST\\Process(cmd)\\Working Set"',
'"time","0.000000","100.000000","200.000000","0.000000","1.000000","999999.000000","-1.000000"'
].join('\r\n')
expect(parseTypeperfProcessOutput(stdout)).toEqual([{ pid: 100, ppid: 1, cpu: 0, memory: 0 }])
})
})
@@ -209,21 +239,27 @@ describe('collectSubtree', () => {
describe('collectMemorySnapshot', () => {
beforeEach(() => {
vi.restoreAllMocks()
appMetricsMock.mockReset()
appMetricsMock.mockReturnValue([])
execFileMock.mockReset()
execMock.mockReset()
listRegisteredPtysMock.mockReset()
listRegisteredPtysMock.mockReturnValue([])
})
function mockPsResponse(stdout: string) {
const processStdout = process.platform === 'win32' ? psFixtureToWmic(stdout) : stdout
execMock.mockImplementation((_cmd, _opts, cb) =>
cb(null, { stdout: processStdout, stderr: '' })
)
execMock.mockImplementation((_cmd, _opts, cb) => cb(null, { stdout, stderr: '' }))
execFileMock.mockImplementation((file, _args, _opts, cb) => {
const output =
file === 'typeperf.exe'
? psFixtureToTypeperfOutput(stdout)
: psFixtureToWindowsProcessOutput(stdout)
cb(null, output, '')
})
}
function psFixtureToWmic(stdout: string): string {
function psFixtureToWindowsProcessOutput(stdout: string): string {
return stdout
.split('\n')
.map((line) => line.trim())
@@ -232,14 +268,361 @@ describe('collectMemorySnapshot', () => {
const [pid, ppid, _cpu, rssKb] = line.split(/\s+/, 4)
const memory = Number.parseInt(rssKb ?? '', 10)
return [
`ParentProcessId=${ppid ?? ''}`,
`ProcessId=${pid ?? ''}`,
`WorkingSetSize=${Number.isFinite(memory) && memory > 0 ? memory * 1024 : 0}`
].join('\r\n')
pid ?? '',
ppid ?? '',
Number.isFinite(memory) && memory > 0 ? memory * 1024 : 0,
'0',
'0',
'1'
].join('\t')
})
.join('\r\n\r\n')
.join('\r\n')
}
function psFixtureToTypeperfOutput(stdout: string): string {
const rows = stdout
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
.map((line, index) => {
const [pid, ppid, _cpu, rssKb] = line.split(/\s+/, 4)
const memoryKb = Number.parseInt(rssKb ?? '', 10)
return {
instance: `fixture${index}`,
pid: pid ?? '',
ppid: ppid ?? '',
memory: Number.isFinite(memoryKb) && memoryKb > 0 ? memoryKb * 1024 : 0
}
})
const counterColumns = (counter: string): string[] =>
rows.map((row) => `"\\\\HOST\\Process(${row.instance})\\${counter}"`)
const valueColumns = (field: 'pid' | 'ppid' | 'memory'): string[] =>
rows.map((row) => `"${row[field]}"`)
return [
[
'"(PDH-CSV 4.0)"',
...counterColumns('ID Process'),
...counterColumns('Creating Process ID'),
...counterColumns('Working Set')
].join(','),
['"time"', ...valueColumns('pid'), ...valueColumns('ppid'), ...valueColumns('memory')].join(
','
)
].join('\r\n')
}
function expectProcessSweepCount(count: number): void {
if (os.platform() === 'win32') {
expect(execFileMock).toHaveBeenCalledTimes(count)
return
}
expect(execMock).toHaveBeenCalledTimes(count)
}
it('uses one CIM process for Windows memory and CPU sampling', async () => {
vi.spyOn(os, 'platform').mockReturnValue('win32')
mockPsResponse('10 1 0 1024')
const { collectMemorySnapshot } = await loadCollector()
await collectMemorySnapshot(emptyStore)
expect(execMock).not.toHaveBeenCalled()
expect(execFileMock).toHaveBeenCalledTimes(1)
const [file, args] = execFileMock.mock.calls[0]
expect(file).toBe('powershell.exe')
expect(args.join(' ')).toContain('Get-CimInstance Win32_Process')
expect(args.join(' ')).toContain('KernelModeTime')
expect(args.join(' ')).toContain('UserModeTime')
expect(args.join(' ')).toContain('CreationDate')
expect(execFileMock.mock.calls[0][2]).toMatchObject({
maxBuffer: 10 * 1024 * 1024,
timeout: 5_000,
windowsHide: true
})
})
it('attributes Windows process CPU from cumulative time deltas between sweeps', async () => {
vi.spyOn(os, 'platform').mockReturnValue('win32')
vi.spyOn(performance, 'now').mockReturnValueOnce(1_000).mockReturnValueOnce(3_000)
const cpuOutputs = [
'10\t1\t1048576\t10000000\t0\t638830000000000000',
'10\t1\t1048576\t30000000\t0\t638830000000000000'
]
execFileMock.mockImplementation((_file, _args, _opts, cb) =>
cb(null, cpuOutputs.shift() ?? '', '')
)
listRegisteredPtysMock.mockReturnValue([
{
ptyId: 'windows-cpu-pty',
worktreeId: 'repo-1::C:\\repo',
sessionId: 'session-1',
paneKey: 'pane-1',
pid: 10
}
])
const { collectMemorySnapshot } = await loadCollector()
const first = await collectMemorySnapshot(emptyStore)
const second = await collectMemorySnapshot(emptyStore)
expect(first.worktrees[0].sessions[0].cpu).toBe(0)
expect(second.worktrees[0].sessions[0].cpu).toBe(100)
expect(execFileMock.mock.calls.map(([file]) => file)).toEqual([
'powershell.exe',
'powershell.exe'
])
})
it('does not attribute prior CPU time after Windows reuses a process id', async () => {
vi.spyOn(os, 'platform').mockReturnValue('win32')
vi.spyOn(performance, 'now').mockReturnValueOnce(1_000).mockReturnValueOnce(3_000)
const cpuOutputs = [
'10\t1\t1048576\t10000000\t0\t638830000000000000',
'10\t1\t1048576\t30000000\t0\t638830000000000001'
]
execFileMock.mockImplementation((_file, _args, _opts, cb) =>
cb(null, cpuOutputs.shift() ?? '', '')
)
listRegisteredPtysMock.mockReturnValue([
{
ptyId: 'reused-pid-pty',
worktreeId: 'repo-1::C:\\repo',
sessionId: 'session-1',
paneKey: 'pane-1',
pid: 10
}
])
const { collectMemorySnapshot } = await loadCollector()
await collectMemorySnapshot(emptyStore)
const second = await collectMemorySnapshot(emptyStore)
expect(second.worktrees[0].sessions[0].cpu).toBe(0)
})
it('supports cumulative CPU counters above JavaScript safe integers', async () => {
vi.spyOn(os, 'platform').mockReturnValue('win32')
vi.spyOn(performance, 'now').mockReturnValueOnce(1_000).mockReturnValueOnce(3_000)
const cpuOutputs = [
'10\t1\t1048576\t90071992547409920\t0\t638830000000000000',
'10\t1\t1048576\t90071992567409920\t0\t638830000000000000'
]
execFileMock.mockImplementation((_file, _args, _opts, cb) =>
cb(null, cpuOutputs.shift() ?? '', '')
)
listRegisteredPtysMock.mockReturnValue([
{
ptyId: 'large-counter-pty',
worktreeId: 'repo-1::C:\\repo',
sessionId: 'session-1',
paneKey: 'pane-1',
pid: 10
}
])
const { collectMemorySnapshot } = await loadCollector()
await collectMemorySnapshot(emptyStore)
const second = await collectMemorySnapshot(emptyStore)
expect(second.worktrees[0].sessions[0].cpu).toBe(100)
})
it('keeps the older CPU baseline when forced snapshots are too close together', async () => {
vi.spyOn(os, 'platform').mockReturnValue('win32')
vi.spyOn(performance, 'now')
.mockReturnValueOnce(1_000)
.mockReturnValueOnce(1_100)
.mockReturnValueOnce(3_000)
const cpuOutputs = [
'10\t1\t1048576\t0\t0\t638830000000000000',
'10\t1\t1048576\t1000000\t0\t638830000000000000',
'10\t1\t1048576\t20000000\t0\t638830000000000000'
]
execFileMock.mockImplementation((_file, _args, _opts, cb) =>
cb(null, cpuOutputs.shift() ?? '', '')
)
listRegisteredPtysMock.mockReturnValue([
{
ptyId: 'short-sample-pty',
worktreeId: 'repo-1::C:\\repo',
sessionId: 'session-1',
paneKey: 'pane-1',
pid: 10
}
])
const { collectMemorySnapshot } = await loadCollector()
await collectMemorySnapshot(emptyStore)
const tooSoon = await collectMemorySnapshot(emptyStore)
const normalPoll = await collectMemorySnapshot(emptyStore)
expect(tooSoon.worktrees[0].sessions[0].cpu).toBe(0)
expect(normalPoll.worktrees[0].sessions[0].cpu).toBe(100)
})
it('caps impossible Windows CPU deltas at the host core capacity', async () => {
vi.spyOn(os, 'platform').mockReturnValue('win32')
vi.spyOn(os, 'cpus').mockReturnValue([{}, {}] as ReturnType<typeof os.cpus>)
vi.spyOn(performance, 'now').mockReturnValueOnce(1_000).mockReturnValueOnce(3_000)
const cpuOutputs = [
'10\t1\t1048576\t0\t0\t638830000000000000',
'10\t1\t1048576\t1000000000\t0\t638830000000000000'
]
execFileMock.mockImplementation((_file, _args, _opts, cb) =>
cb(null, cpuOutputs.shift() ?? '', '')
)
listRegisteredPtysMock.mockReturnValue([
{
ptyId: 'impossible-cpu-pty',
worktreeId: 'repo-1::C:\\repo',
sessionId: 'session-1',
paneKey: 'pane-1',
pid: 10
}
])
const { collectMemorySnapshot } = await loadCollector()
await collectMemorySnapshot(emptyStore)
const capped = await collectMemorySnapshot(emptyStore)
expect(capped.worktrees[0].sessions[0].cpu).toBe(200)
})
it('warms CPU sampling again after Resource Manager was closed', async () => {
vi.spyOn(os, 'platform').mockReturnValue('win32')
vi.spyOn(performance, 'now').mockReturnValueOnce(1_000).mockReturnValueOnce(12_000)
const cpuOutputs = [
'10\t1\t1048576\t0\t0\t638830000000000000',
'10\t1\t1048576\t100000000\t0\t638830000000000000'
]
execFileMock.mockImplementation((_file, _args, _opts, cb) =>
cb(null, cpuOutputs.shift() ?? '', '')
)
listRegisteredPtysMock.mockReturnValue([
{
ptyId: 'stale-counter-pty',
worktreeId: 'repo-1::C:\\repo',
sessionId: 'session-1',
paneKey: 'pane-1',
pid: 10
}
])
const { collectMemorySnapshot } = await loadCollector()
await collectMemorySnapshot(emptyStore)
const reopened = await collectMemorySnapshot(emptyStore)
expect(reopened.worktrees[0].sessions[0].cpu).toBe(0)
})
it('preserves Windows process memory when CPU counters are unavailable', async () => {
vi.spyOn(os, 'platform').mockReturnValue('win32')
execFileMock.mockImplementation((_file, _args, _opts, cb) =>
cb(null, '10\t1\t1048576\t\t\t638830000000000000', '')
)
listRegisteredPtysMock.mockReturnValue([
{
ptyId: 'cpu-failure-pty',
worktreeId: 'repo-1::C:\\repo',
sessionId: 'session-1',
paneKey: 'pane-1',
pid: 10
}
])
const { collectMemorySnapshot } = await loadCollector()
const snapshot = await collectMemorySnapshot(emptyStore)
expect(snapshot.worktrees[0].sessions[0]).toMatchObject({ cpu: 0, memory: 1024 * 1024 })
})
it('uses Typeperf during the CIM retry cooldown', async () => {
vi.spyOn(os, 'platform').mockReturnValue('win32')
execFileMock.mockImplementation((file, _args, _opts, cb) => {
if (file === 'powershell.exe') {
cb(new Error('CIM unavailable'), '', '')
return
}
cb(null, psFixtureToTypeperfOutput('10 1 0 1024'), '')
})
listRegisteredPtysMock.mockReturnValue([
{
ptyId: 'cim-pty',
worktreeId: null,
sessionId: null,
paneKey: null,
pid: 10
}
])
const { collectMemorySnapshot } = await loadCollector()
const first = await collectMemorySnapshot(emptyStore)
const second = await collectMemorySnapshot(emptyStore)
expect(execFileMock).toHaveBeenCalledTimes(3)
expect(execFileMock.mock.calls.map(([file]) => file)).toEqual([
'powershell.exe',
'typeperf.exe',
'typeperf.exe'
])
expect(execFileMock.mock.calls[1][2]).toMatchObject({ windowsHide: true, timeout: 5_000 })
expect(first.worktrees[0].memory).toBe(1048576)
expect(second.worktrees[0].memory).toBe(1048576)
})
it('retries CIM after fallback and warms CPU sampling before restoring deltas', async () => {
vi.spyOn(os, 'platform').mockReturnValue('win32')
vi.spyOn(performance, 'now')
.mockReturnValueOnce(1_000)
.mockReturnValueOnce(2_000)
.mockReturnValueOnce(31_001)
.mockReturnValueOnce(32_000)
.mockReturnValueOnce(34_000)
const cimOutputs = [
'10\t1\t1048576\t10000000\t0\t638830000000000000',
'10\t1\t1048576\t30000000\t0\t638830000000000000'
]
let cimCalls = 0
execFileMock.mockImplementation((file, _args, _opts, cb) => {
if (file === 'typeperf.exe') {
cb(null, psFixtureToTypeperfOutput('10 1 0 1024'), '')
return
}
cimCalls += 1
if (cimCalls === 1) {
cb(new Error('transient CIM failure'), '', '')
return
}
cb(null, cimOutputs.shift() ?? '', '')
})
listRegisteredPtysMock.mockReturnValue([
{
ptyId: 'recovering-cim-pty',
worktreeId: 'repo-1::C:\\repo',
sessionId: 'session-1',
paneKey: 'pane-1',
pid: 10
}
])
const { collectMemorySnapshot } = await loadCollector()
await collectMemorySnapshot(emptyStore)
await collectMemorySnapshot(emptyStore)
const warming = await collectMemorySnapshot(emptyStore)
const recovered = await collectMemorySnapshot(emptyStore)
expect(execFileMock.mock.calls.map(([file]) => file)).toEqual([
'powershell.exe',
'typeperf.exe',
'typeperf.exe',
'powershell.exe',
'powershell.exe'
])
expect(warming.worktrees[0].sessions[0].cpu).toBe(0)
expect(recovered.worktrees[0].sessions[0].cpu).toBe(100)
})
it('coalesces concurrent callers onto a single in-flight sweep', async () => {
// Why: the collector exists in part to prevent a burst of renderer
// polls from spawning overlapping `ps` children. If a regression ever
@@ -254,7 +637,7 @@ describe('collectMemorySnapshot', () => {
collectMemorySnapshot(emptyStore)
])
expect(execMock).toHaveBeenCalledTimes(1)
expectProcessSweepCount(1)
// All three callers see the same snapshot object (same promise).
expect(a).toBe(b)
expect(b).toBe(c)
@@ -267,7 +650,7 @@ describe('collectMemorySnapshot', () => {
await collectMemorySnapshot(emptyStore)
await collectMemorySnapshot(emptyStore)
expect(execMock).toHaveBeenCalledTimes(2)
expectProcessSweepCount(2)
})
it('uses host process RSS for Electron app metrics when available', async () => {
@@ -388,14 +771,19 @@ describe('collectMemorySnapshot', () => {
expect(snap.worktrees[0].memory).toBe(2048 * 1024)
})
it('returns an empty snapshot when ps fails', async () => {
execMock.mockImplementation((_cmd, _opts, cb) => cb(new Error('ps blew up'), { stdout: '' }))
it('returns an empty snapshot when process enumeration fails', async () => {
execMock.mockImplementation((_cmd, _opts, cb) =>
cb(new Error('process enumeration failed'), { stdout: '' })
)
execFileMock.mockImplementation((_file, _args, _opts, cb) =>
cb(new Error('process enumeration failed'), '', '')
)
listRegisteredPtysMock.mockReturnValue([])
const { collectMemorySnapshot } = await loadCollector()
const snap = await collectMemorySnapshot(emptyStore)
// ps failure should not surface as a rejected promise or crash the
// Enumeration failure should not surface as a rejected promise or crash the
// renderer; the collector swallows and returns zeros so the UI can
// render an empty state.
expect(snap.worktrees).toEqual([])
+8 -70
View File
@@ -1,8 +1,6 @@
/* eslint-disable max-lines -- Why: the collector's platform-specific
enumeration paths (`ps` on Unix, `wmic` on Windows) plus the history
ring buffer plus the Electron bucketing live together to keep one
snapshot's worth of code in one place. Splitting them produces extra
modules whose only consumer is this file. */
/* eslint-disable max-lines -- Why: the collector's host-process index,
history ring buffer, Electron bucketing, and worktree attribution live
together to keep one snapshot's orchestration in one place. */
/**
* Memory dashboard collector.
*
@@ -10,7 +8,7 @@
* - Orca's own Electron processes, via `app.getAppMetrics()`, bucketed
* into main / renderer / other.
* - Each registered PTY's process subtree, enumerated once from a host-
* wide `ps` sweep (`wmic` on Windows).
* wide process sweep (PowerShell CIM with a Typeperf fallback on Windows).
*
* Memory samples are held in a per-key ring (one key per worktree, plus
* a reserved app-total key) so the UI can draw a trend sparkline.
@@ -39,6 +37,7 @@ import type {
import type { Store } from '../persistence'
import { ORPHAN_WORKTREE_ID } from '../../shared/constants'
import { listRegisteredPtys } from './pty-registry'
import { enumerateWindowsProcessResources } from './windows-process-resource-collector'
export type MemorySnapshotStore = Pick<Store, 'getRepo' | 'getWorktreeMeta'>
@@ -77,13 +76,13 @@ const PS_MAX_BUFFER = 10 * 1024 * 1024
type ProcRow = {
pid: number
ppid: number
/** Percent of one core (may exceed 100 on multi-core). 0 on Windows. */
/** Percent of one core (may exceed 100 on multi-core). */
cpu: number
/** Resident memory in bytes. */
memory: number
}
/** Indexed view of a single `ps`/`wmic` sweep. */
/** Indexed view of a single host process sweep. */
type ProcIndex = {
byPid: Map<number, ProcRow>
childrenOf: Map<number, number[]>
@@ -226,69 +225,8 @@ export function parsePsOutput(stdout: string): ProcRow[] {
}
async function enumerateWindows(): Promise<ProcRow[]> {
// Why: `wmic` ships with stock Windows and emits a plain, tab-separated
// table without the CSV-quoting edge cases PowerShell's ConvertTo-Csv
// introduces. CPU% would require delta sampling between two queries; for
// v1 we report 0% on Windows — memory attribution is the primary signal.
try {
const { stdout } = await execAsync(
'wmic process get ProcessId,ParentProcessId,WorkingSetSize /format:value',
{ maxBuffer: PS_MAX_BUFFER, timeout: PS_EXEC_TIMEOUT_MS }
)
return parseWmicOutput(stdout)
} catch (err) {
console.warn('[memory] wmic enumeration failed', err)
return []
}
return enumerateWindowsProcessResources()
}
/** Exported for tests: parses `wmic /format:value` stanza output. */
export function parseWmicOutput(stdout: string): ProcRow[] {
// wmic /format:value emits stanzas of `Key=Value` lines separated by blank
// lines. We accumulate a record until a blank line, then flush.
const rows: ProcRow[] = []
let pid = Number.NaN
let ppid = Number.NaN
let ws = Number.NaN
const flush = (): void => {
if (!Number.isNaN(pid) && !Number.isNaN(ppid)) {
rows.push({
pid,
ppid,
cpu: 0,
memory: Number.isFinite(ws) && ws > 0 ? ws : 0
})
}
pid = Number.NaN
ppid = Number.NaN
ws = Number.NaN
}
for (const raw of stdout.split(/\r?\n/)) {
const line = raw.trim()
if (line.length === 0) {
flush()
continue
}
const eq = line.indexOf('=')
if (eq < 0) {
continue
}
const key = line.slice(0, eq)
const value = line.slice(eq + 1)
if (key === 'ProcessId') {
pid = Number.parseInt(value, 10)
} else if (key === 'ParentProcessId') {
ppid = Number.parseInt(value, 10)
} else if (key === 'WorkingSetSize') {
ws = Number.parseInt(value, 10)
}
}
flush()
return rows
}
/** Walk every descendant PID of `root`, inclusive. Exported for tests. */
export function collectSubtree(index: ProcIndex, root: number): number[] {
const result: number[] = []
@@ -0,0 +1,341 @@
import { execFile } from 'node:child_process'
import os from 'node:os'
import { performance } from 'node:perf_hooks'
import {
iterateProcessOutputLines,
PROCESS_OUTPUT_FIELD_SCAN_MAX_CHARS
} from '../../shared/process-output-field-scanner'
const PROCESS_QUERY_TIMEOUT_MS = 5_000
const PROCESS_QUERY_MAX_BUFFER = 10 * 1024 * 1024
const TYPEPERF_COUNTERS = [
'\\Process(*)\\ID Process',
'\\Process(*)\\Creating Process ID',
'\\Process(*)\\Working Set'
] as const
const TYPEPERF_MAX_FIELDS = 8_192
const TYPEPERF_MAX_LINE_CHARS = 1024 * 1024
const CPU_MIN_SAMPLE_MS = 250
const CPU_STALE_AFTER_MS = 10_000
const HUNDRED_NS_TICKS_PER_MS = 10_000
const CIM_RETRY_AFTER_MS = 30_000
export type WindowsProcessResourceRow = {
pid: number
ppid: number
/** Percent of one core (may exceed 100 on multi-core). */
cpu: number
/** Resident memory in bytes. */
memory: number
}
type WindowsCpuTimes = {
cpuTicks: bigint
startTimeId: string
}
type WindowsProcessSample = {
sampledAtMs: number
rows: WindowsProcessResourceRow[]
cpuByPid: Map<number, WindowsCpuTimes>
}
type ParsedWindowsProcessSample = Omit<WindowsProcessSample, 'sampledAtMs'>
type TypeperfProcessFields = {
pid?: number
ppid?: number
memory?: number
}
let processBackend: 'cim' | 'typeperf' = 'cim'
let previousCpuSample: WindowsProcessSample | null = null
let retryCimAtMs = 0
export async function enumerateWindowsProcessResources(): Promise<WindowsProcessResourceRow[]> {
// Why: one CIM sweep supplies both resource values and process identity,
// avoiding a second host-wide PowerShell process on every open-popover poll.
if (processBackend === 'typeperf') {
if (performance.now() < retryCimAtMs) {
return enumerateWindowsWithTypeperf()
}
processBackend = 'cim'
}
const sample = await enumerateWindowsWithCim()
if (sample) {
return applyWindowsCpuSample(sample)
}
// Why: avoid repeating a blocked CIM timeout every two-second poll while
// still recovering CPU attribution after a transient PowerShell failure.
processBackend = 'typeperf'
retryCimAtMs = performance.now() + CIM_RETRY_AFTER_MS
previousCpuSample = null
return enumerateWindowsWithTypeperf()
}
function applyWindowsCpuSample(sample: WindowsProcessSample): WindowsProcessResourceRow[] {
const previous = previousCpuSample
if (!previous) {
previousCpuSample = sample
return sample.rows
}
const elapsedMs = sample.sampledAtMs - previous.sampledAtMs
if (elapsedMs < CPU_MIN_SAMPLE_MS) {
// Why: forced snapshots can land too close together for a stable rate.
// Keep the older baseline so the next normal poll spans a useful interval.
return sample.rows
}
previousCpuSample = sample
if (elapsedMs > CPU_STALE_AFTER_MS) {
// Why: closing Resource Manager or sleeping the machine leaves a stale
// baseline whose long-term average is not the current CPU usage.
return sample.rows
}
const maxProcessCpu = Math.max(1, os.cpus().length) * 100
for (const row of sample.rows) {
const currentTimes = sample.cpuByPid.get(row.pid)
const previousTimes = previous.cpuByPid.get(row.pid)
// Why: process start time prevents a recycled PID from inheriting the old
// process's cumulative CPU time; counter resets likewise warm up again.
if (
!currentTimes ||
!previousTimes ||
currentTimes.startTimeId !== previousTimes.startTimeId ||
currentTimes.cpuTicks < previousTimes.cpuTicks
) {
continue
}
const cpuMs = Number(currentTimes.cpuTicks - previousTimes.cpuTicks) / HUNDRED_NS_TICKS_PER_MS
row.cpu = Math.min(maxProcessCpu, nonNegativeNumber((cpuMs / elapsedMs) * 100))
}
return sample.rows
}
async function enumerateWindowsWithCim(): Promise<WindowsProcessSample | null> {
const args = [
'-NoLogo',
'-NoProfile',
'-NonInteractive',
'-Command',
"$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; " +
'Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId,WorkingSetSize,KernelModeTime,UserModeTime,CreationDate | ' +
'ForEach-Object { try { [string]::Join([char]9, @($_.ProcessId, $_.ParentProcessId, $_.WorkingSetSize, [string]$_.KernelModeTime, [string]$_.UserModeTime, $_.CreationDate.ToUniversalTime().Ticks)) } catch {} }'
]
try {
const stdout = await execFileText('powershell.exe', args)
const parsed = parseWindowsProcessSample(stdout)
return parsed.rows.length > 0 ? { ...parsed, sampledAtMs: performance.now() } : null
} catch (err) {
console.warn('[memory] PowerShell process enumeration failed; falling back to typeperf', err)
return null
}
}
async function enumerateWindowsWithTypeperf(): Promise<WindowsProcessResourceRow[]> {
try {
// Why: an immediate sample keeps the memory-only fallback inside the
// Resource Manager's two-second poll interval without inventing CPU rates.
const stdout = await execFileText('typeperf.exe', [
...TYPEPERF_COUNTERS,
'-sc',
'1',
'-si',
'0'
])
return parseTypeperfProcessOutput(stdout)
} catch (err) {
console.warn('[memory] typeperf process enumeration failed', err)
return []
}
}
function execFileText(file: string, args: string[]): Promise<string> {
return new Promise<string>((resolve, reject) => {
execFile(
file,
args,
{
encoding: 'utf8',
maxBuffer: PROCESS_QUERY_MAX_BUFFER,
timeout: PROCESS_QUERY_TIMEOUT_MS,
windowsHide: true
},
(err, output) => {
if (err) {
reject(err)
return
}
resolve(String(output))
}
)
})
}
function parseWindowsProcessSample(stdout: string): ParsedWindowsProcessSample {
const rows: WindowsProcessResourceRow[] = []
const cpuByPid = new Map<number, WindowsCpuTimes>()
for (const line of iterateProcessOutputLines(stdout)) {
const fields = parseCimTabFields(line)
if (fields.length < 3) {
continue
}
const pid = Number.parseInt(fields[0], 10)
const ppid = Number.parseInt(fields[1], 10)
const memory = Number.parseInt(fields[2], 10)
if (!Number.isSafeInteger(pid) || pid <= 0 || !Number.isSafeInteger(ppid) || ppid < 0) {
continue
}
rows.push({
pid,
ppid,
cpu: 0,
memory: Number.isFinite(memory) && memory > 0 ? memory : 0
})
const kernelTicks = parseUnsignedBigInt(fields[3])
const userTicks = parseUnsignedBigInt(fields[4])
const startTimeId = fields[5] ?? ''
if (
kernelTicks !== null &&
userTicks !== null &&
/^\d+$/.test(startTimeId) &&
!/^0+$/.test(startTimeId)
) {
cpuByPid.set(pid, { cpuTicks: kernelTicks + userTicks, startTimeId })
}
}
return { rows, cpuByPid }
}
function parseCimTabFields(line: string): string[] {
// Why: CIM serializes null properties as empty tab fields; collapsing
// whitespace would shift CPU counters into the working-set column.
if (line.length > PROCESS_OUTPUT_FIELD_SCAN_MAX_CHARS) {
return []
}
return line.split('\t', 6).map((field) => field.trim())
}
/** Parse tab-delimited PowerShell CIM process rows without deriving CPU deltas. */
export function parseWindowsProcessOutput(stdout: string): WindowsProcessResourceRow[] {
return parseWindowsProcessSample(stdout).rows
}
/** Parse one CSV sample from Windows Typeperf. */
export function parseTypeperfProcessOutput(stdout: string): WindowsProcessResourceRow[] {
let headers: string[] | null = null
let values: string[] | null = null
for (const line of iterateProcessOutputLines(stdout)) {
if (!line || line.length > TYPEPERF_MAX_LINE_CHARS) {
continue
}
const fields = parseTypeperfCsvLine(line)
if (!headers && fields[0]?.startsWith('(PDH-CSV')) {
headers = fields
continue
}
if (headers && fields.length === headers.length) {
values = fields
break
}
}
if (!headers || !values) {
return []
}
const byInstance = new Map<string, TypeperfProcessFields>()
for (let index = 1; index < headers.length; index += 1) {
const path = parseTypeperfCounterPath(headers[index])
if (!path || path.instance === '_Total') {
continue
}
const value = Number.parseFloat(values[index])
if (!Number.isFinite(value)) {
continue
}
const row = byInstance.get(path.instance) ?? {}
if (path.counter === 'ID Process') {
row.pid = Math.trunc(value)
} else if (path.counter === 'Creating Process ID') {
row.ppid = Math.trunc(value)
} else if (path.counter === 'Working Set') {
row.memory = value
}
byInstance.set(path.instance, row)
}
const rows: WindowsProcessResourceRow[] = []
for (const row of byInstance.values()) {
if (row.pid === undefined || row.pid <= 0 || row.ppid === undefined || row.ppid < 0) {
continue
}
rows.push({
pid: row.pid,
ppid: row.ppid,
cpu: 0,
memory: row.memory !== undefined && row.memory > 0 ? row.memory : 0
})
}
return rows
}
function parseTypeperfCounterPath(path: string): { instance: string; counter: string } | null {
const processStart = path.lastIndexOf('\\Process(')
const counterStart = path.lastIndexOf(')\\')
if (processStart < 0 || counterStart <= processStart + 9) {
return null
}
return {
instance: path.slice(processStart + 9, counterStart),
counter: path.slice(counterStart + 2)
}
}
function parseTypeperfCsvLine(line: string): string[] {
const fields: string[] = []
let value = ''
let quoted = false
for (let index = 0; index < line.length; index += 1) {
const char = line[index]
if (char === '"') {
if (quoted && line[index + 1] === '"') {
value += '"'
index += 1
} else {
quoted = !quoted
}
continue
}
if (char === ',' && !quoted) {
fields.push(value)
value = ''
if (fields.length >= TYPEPERF_MAX_FIELDS) {
return []
}
continue
}
value += char
}
fields.push(value)
return fields
}
function parseUnsignedBigInt(value: string | undefined): bigint | null {
if (!value || !/^\d+$/.test(value)) {
return null
}
try {
return BigInt(value)
} catch {
return null
}
}
function nonNegativeNumber(value: unknown): number {
return typeof value === 'number' && Number.isFinite(value) ? Math.max(0, value) : 0
}