[tools] CpuGuard: Full test runs wait for, then refuse, a machine above 80 % CPU

This commit is contained in:
2026-11-02 00:51:45 +01:00
parent 8b1c2eaee2
commit f9883e22ba
7 changed files with 195 additions and 4 deletions
+5 -4
View File
@@ -12,13 +12,14 @@
"build": "turbo run build",
"typecheck": "turbo run typecheck && tsc -p tsconfig.json --noEmit",
"lint": "eslint .",
"test": "turbo run test",
"test:e2e": "turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.config.ts",
"test:offline": "turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.offline.config.ts",
"test": "pnpm guard:cpu && turbo run test",
"test:e2e": "pnpm guard:cpu && turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.config.ts",
"test:offline": "pnpm guard:cpu && turbo run build --filter=@rosea/app && playwright test --config=e2e/playwright.offline.config.ts",
"validate:library": "tsx scripts/validate-library.ts",
"lint:copy": "tsx scripts/lint-copy.ts",
"art:board": "tsx tools/art-prep/src/cli-board.ts",
"art:accept": "tsx tools/art-prep/src/cli-accept.ts"
"art:accept": "tsx tools/art-prep/src/cli-accept.ts",
"guard:cpu": "tsx tools/cpu-guard/src/cli.ts"
},
"devDependencies": {
"@axe-core/playwright": "4.13.0",
+12
View File
@@ -238,6 +238,18 @@ importers:
specifier: 3.2.7
version: 3.2.7(@types/node@22.20.1)(jsdom@25.0.1)(terser@5.51.2)(tsx@4.23.12)
tools/cpu-guard:
devDependencies:
'@types/node':
specifier: 22.20.1
version: 22.20.1
typescript:
specifier: 5.9.3
version: 5.9.3
vitest:
specifier: 3.2.7
version: 3.2.7(@types/node@22.20.1)(jsdom@25.0.1)(terser@5.51.2)(tsx@4.23.12)
packages:
'@apideck/better-ajv-errors@0.3.7':
+16
View File
@@ -0,0 +1,16 @@
{
"name": "@rosea/cpu-guard",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "Refuses to start a full test run while the machine is busy (CLAUDE.md §5.7). Never imported by the app.",
"scripts": {
"typecheck": "tsc -p tsconfig.json",
"test": "vitest run --reporter=verbose"
},
"devDependencies": {
"@types/node": "22.20.1",
"typescript": "5.9.3",
"vitest": "3.2.7"
}
}
+45
View File
@@ -0,0 +1,45 @@
/**
* `pnpm guard:cpu` — samples the machine for 2 s; starts if it is at or under the
* limit, waits and samples again while it is not, and exits 1 once the wait is used
* up. The full runs (`pnpm test`, `test:e2e`, `test:offline`) call it first.
*/
import { cpus } from 'node:os';
import { setTimeout as sleep } from 'node:timers/promises';
import { busyPercent, decide, limitsFrom } from './guard.js';
const SAMPLE_MS = 2_000;
const PAUSE_MS = 10_000;
async function sample(): Promise<number> {
const before = cpus();
await sleep(SAMPLE_MS);
return busyPercent(before, cpus());
}
let limits;
try {
limits = limitsFrom(process.env);
} catch (error) {
console.error(`guard:cpu: ${(error as Error).message}`);
process.exit(2);
}
const started = Date.now();
for (;;) {
const busy = await sample();
const waited = Math.round((Date.now() - started) / 1000);
const verdict = decide(busy, waited, limits);
if (verdict === 'start') {
console.log(`guard:cpu: ${busy} % busy, at or under ${limits.max} %. Starting.`);
break;
}
if (verdict === 'refuse') {
console.error(
`guard:cpu: still ${busy} % busy after ${waited} s, above ${limits.max} % (CLAUDE.md §5.7). Not starting.\n` +
' Close what is busy, or on a dedicated machine set ROSEA_CPU_MAX (100 never refuses).'
);
process.exit(1);
}
console.log(`guard:cpu: ${busy} % busy, above ${limits.max} %. Waiting (${waited} of ${limits.waitSeconds} s).`);
await sleep(PAUSE_MS);
}
+53
View File
@@ -0,0 +1,53 @@
/**
* CLAUDE.md §5.7: do not start a full run above ~80 % CPU. Read by a person, the rule
* was broken three times in one day (lessons/process.md), so a full run now asks
* this guard first. The logic is pure; `cli.ts` does the sampling and the waiting.
*/
import type { CpuInfo } from 'node:os';
/** The default limit, CLAUDE.md §5.7. */
export const DEFAULT_MAX = 80;
/** How long a busy machine is waited for before the run is refused. */
export const DEFAULT_WAIT_SECONDS = 180;
/** Whole-machine busy share between two `os.cpus()` readings, 0–100. */
export function busyPercent(before: readonly CpuInfo[], after: readonly CpuInfo[]): number {
let busy = 0;
let total = 0;
for (let i = 0; i < Math.min(before.length, after.length); i++) {
const a = before[i]!.times;
const b = after[i]!.times;
const idle = b.idle - a.idle;
const all = b.user - a.user + (b.nice - a.nice) + (b.sys - a.sys) + (b.irq - a.irq) + idle;
busy += all - idle;
total += all;
}
return total <= 0 ? 0 : Math.round((busy / total) * 100);
}
export interface Limits {
readonly max: number;
readonly waitSeconds: number;
}
/**
* The limits, from the environment. `ROSEA_CPU_MAX` is for a dedicated machine such as
* CI (100 never refuses); `ROSEA_CPU_WAIT_SECONDS` for how long to wait. A value that
* is not a whole number in range is an error, never quietly the default.
*/
export function limitsFrom(env: Readonly<Record<string, string | undefined>>): Limits {
const read = (name: string, fallback: number, min: number, max: number): number => {
const raw = env[name];
if (raw === undefined || raw.trim() === '') return fallback;
const n = Number(raw);
if (!Number.isInteger(n) || n < min || n > max) throw new RangeError(`${name} must be a whole number from ${min} to ${max}, got '${raw}'`);
return n;
};
return { max: read('ROSEA_CPU_MAX', DEFAULT_MAX, 1, 100), waitSeconds: read('ROSEA_CPU_WAIT_SECONDS', DEFAULT_WAIT_SECONDS, 0, 3600) };
}
/** Start once a sample is at or under the limit; refuse once the wait is used up. */
export function decide(busy: number, waitedSeconds: number, limits: Limits): 'start' | 'wait' | 'refuse' {
if (busy <= limits.max) return 'start';
return waitedSeconds >= limits.waitSeconds ? 'refuse' : 'wait';
}
+57
View File
@@ -0,0 +1,57 @@
import type { CpuInfo } from 'node:os';
import { describe, expect, it } from 'vitest';
import { busyPercent, decide, DEFAULT_MAX, DEFAULT_WAIT_SECONDS, limitsFrom } from '../src/guard.js';
const core = (user: number, idle: number, sys = 0): CpuInfo => ({ model: 'test', speed: 1, times: { user, nice: 0, sys, idle, irq: 0 } });
describe('busyPercent', () => {
it('measures the whole machine between two readings, not since boot', () => {
// Since boot both cores look idle; between the readings one is full and one is idle.
const before = [core(1_000, 99_000), core(1_000, 99_000)];
const after = [core(2_000, 99_000), core(1_000, 100_000)];
expect(busyPercent(before, after)).toBe(50);
});
it('counts system time as busy, and an idle machine as 0', () => {
expect(busyPercent([core(0, 0)], [core(300, 100, 600)])).toBe(90);
expect(busyPercent([core(5, 5)], [core(5, 1005)])).toBe(0);
});
it('two readings with no time between them are 0, never NaN', () => {
expect(busyPercent([core(1, 1)], [core(1, 1)])).toBe(0);
});
});
describe('limitsFrom', () => {
it('defaults to CLAUDE.md §5.7: 80 %, waiting three minutes', () => {
expect(limitsFrom({})).toEqual({ max: DEFAULT_MAX, waitSeconds: DEFAULT_WAIT_SECONDS });
expect(DEFAULT_MAX).toBe(80);
});
it('reads a dedicated machine\'s limit and wait', () => {
expect(limitsFrom({ ROSEA_CPU_MAX: '100', ROSEA_CPU_WAIT_SECONDS: '0' })).toEqual({ max: 100, waitSeconds: 0 });
});
it.each(['abc', '0', '101', '80.5', '-5'])('refuses ROSEA_CPU_MAX=%s rather than quietly using the default', (raw) => {
expect(() => limitsFrom({ ROSEA_CPU_MAX: raw })).toThrow(/ROSEA_CPU_MAX must be a whole number from 1 to 100/);
});
});
describe('decide', () => {
const limits = { max: 80, waitSeconds: 180 };
it('starts at or under the limit', () => {
expect(decide(80, 0, limits)).toBe('start');
expect(decide(12, 500, limits)).toBe('start');
});
it('waits while busy, then refuses once the wait is used up', () => {
expect(decide(81, 0, limits)).toBe('wait');
expect(decide(100, 179, limits)).toBe('wait');
expect(decide(100, 180, limits)).toBe('refuse');
});
it('with no wait, refuses at once', () => {
expect(decide(95, 0, { max: 80, waitSeconds: 0 })).toBe('refuse');
});
});
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node"]
},
"include": ["src/**/*.ts", "test/**/*.ts"]
}