Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
monitor: read Windows disk counters from one long-lived PowerShell instead of a cold one every 3 s (#3939)
Niko12214b49729a1ef2
diff --git a/apps/host/server/system-telemetry.mjs b/apps/host/server/system-telemetry.mjsindex 4d7c9c6df..768a83ffb 100644--- a/apps/host/server/system-telemetry.mjs+++ b/apps/host/server/system-telemetry.mjs@@ -1,5 +1,6 @@/** Host counters. CPU sockets are measured only when their logical CPU IDs are known. */import os from 'node:os';+import { spawn } from 'node:child_process';import { readFile, readdir } from 'node:fs/promises';import { availableMemoryGb } from './hardware.mjs';import { probe } from './util.mjs';@@ -18,7 +19,7 @@ export function cpuUtilization(previous, current, ids) {}export function diskRate(previous, current, time) {- const elapsed=previous?(time-previous.time)/1000:0;+ const elapsed=previous?((current?.at??time)-(previous.counters?.at??previous.time))/1000:0;if(elapsed<=0||!current||!previous?.counters)return {readMbs:null,writeMbs:null};const read=current.read-previous.counters.read,write=current.write-previous.counters.write;return {readMbs:read>=0?read/1024**2/elapsed:null,writeMbs:write>=0?write/1024**2/elapsed:null};@@ -41,6 +42,53 @@ export function parseMacDiskCounters(raw) {return reads.length&&writes.length?{read:reads.reduce((n,m)=>n+Number(m[1]),0),write:writes.reduce((n,m)=>n+Number(m[1]),0)}:null;}+export function parseWindowsDiskLine(line) {+ const m=/^\s*(\d+)\s+(\d+)\s*$/.exec(String(line));+ return m?{read:Number(m[1]),write:Number(m[2])}:null;+}++/**+ * One long-lived PowerShell reads the disk counters in a loop. A new PowerShell per sample+ * paid the cold WMI start every time, missed its timeout and burned WmiPrvSE (#3939).+ * Gives up after repeated early exits, so a broken counter stays quiet.+ */+export function createWindowsDiskReader({ spawnFn=spawn, intervalSec=4, maxStarts=3, now=Date.now }={}) {+ let child=null,latest=null,starts=0,buffer='';+ const script=`while($true){$d=Get-CimInstance Win32_PerfRawData_PerfDisk_PhysicalDisk -Filter "Name='_Total'";if($d){[Console]::Out.WriteLine(([string]$d.DiskReadBytesPersec)+' '+([string]$d.DiskWriteBytesPersec));[Console]::Out.Flush()};Start-Sleep -Seconds ${intervalSec}}`;+ function start() {+ if(child||starts>=maxStarts)return;+ starts++;+ let proc;+ try { proc=spawnFn('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{windowsHide:true,stdio:['ignore','pipe','ignore']}); }+ catch { return; }+ child=proc;+ proc.on?.('error',()=>{ if(child===proc)child=null; });+ proc.on?.('exit',()=>{ if(child===proc){child=null;latest=null;} });+ proc.stdout?.on('data',chunk=>{+ buffer+=chunk;+ let i;+ while((i=buffer.indexOf('\n'))>=0){+ const parsed=parseWindowsDiskLine(buffer.slice(0,i));+ buffer=buffer.slice(i+1);+ if(parsed){latest={...parsed,at:now()};starts=0;}+ }+ });+ proc.unref?.();+ proc.stdout?.unref?.();+ }+ return {+ read() { start(); return latest; },+ stop() { try{child?.kill();}catch{} child=null; },+ get starts() { return starts; },+ };+}++let windowsReader=null;+function windowsDisks() {+ if(!windowsReader){windowsReader=createWindowsDiskReader();process.once('exit',()=>windowsReader.stop());}+ return windowsReader.read();+}+async function disks() {try {if(process.platform==='linux') {@@ -49,24 +97,26 @@ async function disks() {}if(process.platform==='darwin')return parseMacDiskCounters(await probe('ioreg',['-r','-c','IOBlockStorageDriver','-l'],1500));if(process.platform==='win32') {- const raw=await probe('powershell.exe',['-NoProfile','-NonInteractive','-Command',"Get-CimInstance Win32_PerfRawData_PerfDisk_PhysicalDisk -Filter \"Name='_Total'\" | Select-Object DiskReadBytesPersec,DiskWriteBytesPersec | ConvertTo-Json -Compress"],2000);- const value=JSON.parse(raw);- if(value.DiskReadBytesPersec!=null&&value.DiskWriteBytesPersec!=null)return {read:Number(value.DiskReadBytesPersec),write:Number(value.DiskWriteBytesPersec)};+ return windowsDisks();}} catch { /* An unsupported counter stays unavailable. */ }return null;}export function createSystemSampler() {- let previousCpu=null,previousDisk=null;+ let previousCpu=null,previousDisk=null,lastRate={readMbs:null,writeMbs:null};return async processors => {const current=os.cpus(),time=Date.now();const cpuLoad=cpuUtilization(previousCpu,current,current.map((_,i)=>i));const cpus=processors.map(p=>({id:p.id,utilizationPct:cpuUtilization(previousCpu,current,p.logicalIds??(processors.length===1?current.map((_,i)=>i):[]))}));previousCpu=current;const [available,counters]=await Promise.all([availableMemoryGb(process.platform),disks()]);- const rate=diskRate(previousDisk,counters,time);- previousDisk={time,counters};+ let rate=lastRate;+ if(!(counters&&counters.at!==undefined&&previousDisk?.counters?.at===counters.at)) {+ rate=diskRate(previousDisk,counters,time);+ previousDisk={time,counters};+ lastRate=rate;+ }const total=os.totalmem()/1024**3,free=available??os.freemem()/1024**3;return {cpuLoad,cpus,ramUsedGb:Math.max(0,Math.min(total,total-free)),ramTotalGb:total,diskReadGbs:rate.readMbs===null?null:rate.readMbs/1024,diskWriteMbs:rate.writeMbs};};diff --git a/apps/host/tests/windows-disk-reader.test.mjs b/apps/host/tests/windows-disk-reader.test.mjsnew file mode 100644index 000000000..d8960b6fa--- /dev/null+++ b/apps/host/tests/windows-disk-reader.test.mjs@@ -0,0 +1,43 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { EventEmitter } from 'node:events';+import { parseWindowsDiskLine, createWindowsDiskReader, diskRate } from '../server/system-telemetry.mjs';++function fakeSpawn(log) {+ return (cmd, args) => {+ const proc = new EventEmitter();+ proc.stdout = new EventEmitter();+ proc.stdout.unref = () => {};+ proc.unref = () => {};+ proc.kill = () => { proc.killed = true; };+ log.push({ cmd, args, proc });+ return proc;+ };+}++test('one PowerShell is started and reused for every sample (#3939)', () => {+ const log = [];+ const reader = createWindowsDiskReader({ spawnFn: fakeSpawn(log), now: () => 1000 });+ assert.equal(reader.read(), null, 'nothing before the first line');+ reader.read(); reader.read();+ assert.equal(log.length, 1);+ log[0].proc.stdout.emit('data', '1000 2');+ log[0].proc.stdout.emit('data', '000\n');+ assert.deepEqual(reader.read(), { read: 1000, write: 2000, at: 1000 });+ assert.equal(log.length, 1);+});++test('after repeated early exits it stops starting processes', () => {+ const log = [];+ const reader = createWindowsDiskReader({ spawnFn: fakeSpawn(log), maxStarts: 3 });+ for (let i = 0; i < 6; i++) { reader.read(); log.at(-1).proc.emit('exit'); }+ assert.equal(log.length, 3);+ assert.equal(reader.read(), null);+});++test('garbage lines are ignored and a repeated reading gives no new rate', () => {+ assert.equal(parseWindowsDiskLine('Name : x'), null);+ assert.deepEqual(parseWindowsDiskLine('12 34\r'), { read: 12, write: 34 });+ const prev = { time: 0, counters: { read: 0, write: 0, at: 1000 } };+ assert.deepEqual(diskRate(prev, { read: 1048576, write: 0, at: 2000 }, 5000), { readMbs: 1, writeMbs: 0 });+});