Skip to content

Commit c13a44c

Browse files
fix(server): sample pinned CPUs by id from /proc/stat
os.cpus() compacts online CPUs, so its indices are not CPU ids when a CPU is offline. AI-assisted; verified with the tests and tools listed above.
1 parent 1b61f24 commit c13a44c

2 files changed

Lines changed: 51 additions & 21 deletions

File tree

‎apps/server/src/resourceTelemetry/HostResources.test.ts‎

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,25 +12,28 @@ import { vi } from "vite-plus/test";
1212

1313
import * as HostResources from "./HostResources.ts";
1414

15-
// An 8-CPU host; every cpus() call advances each CPU by 100 ms at its `host.busy` utilization.
16-
const host = vi.hoisted(() => ({ busy: [] as ReadonlyArray<number>, reads: 0 }));
15+
// An 8-CPU host; every cpus() call advances each CPU by 100 ms at `host.busy` utilization.
16+
const host = vi.hoisted(() => ({ busy: 0, reads: 0 }));
1717
vi.mock("node:os", async (importOriginal) => {
1818
const actual = await importOriginal<typeof NodeOS>();
1919
return {
2020
...actual,
2121
totalmem: () => 4 * 1024 ** 3,
2222
cpus: () => {
2323
const elapsed = 100 * host.reads++;
24-
return host.busy.map((busy) => ({
25-
model: "test",
26-
speed: 1,
27-
times: { user: elapsed * busy, nice: 0, sys: 0, idle: elapsed * (1 - busy), irq: 0 },
28-
}));
24+
const times = {
25+
user: elapsed * host.busy,
26+
nice: 0,
27+
sys: 0,
28+
idle: elapsed * (1 - host.busy),
29+
irq: 0,
30+
};
31+
return Array.from({ length: 8 }, () => ({ model: "test", speed: 1, times }));
2932
},
3033
};
3134
});
32-
const setup = (busy: number | ReadonlyArray<number> = 0) => {
33-
host.busy = typeof busy === "number" ? Array.from({ length: 8 }, () => busy) : busy;
35+
const setup = (busy = 0) => {
36+
host.busy = busy;
3437
host.reads = 0;
3538
};
3639

@@ -148,20 +151,28 @@ describe("HostResources.layer", () => {
148151
),
149152
);
150153

151-
it.effect("counts only the CPUs the server is pinned to as host idle", () =>
154+
it.effect("samples the CPUs the server is pinned to by id, not by os.cpus() index", () =>
152155
Effect.gen(function* () {
153-
// A neighbour saturates CPUs 0-1, the server's whole cpuset; CPUs 2-7 sit idle.
154-
setup([1, 1, 0, 0, 0, 0, 0, 0]);
156+
setup();
155157
const snapshot = yield* read;
156158

157-
assert.strictEqual(snapshot.cpuCount, 2);
159+
assert.strictEqual(snapshot.cpuCount, 1);
158160
assert.strictEqual(snapshot.cpuUtilization, 1);
159161
}).pipe(
160162
Effect.provide(
161163
linuxHost({
162164
...unlimitedCgroup,
163-
"/proc/self/status": ["Name:\tnode\nCpus_allowed_list:\t0-1\n"],
164-
[`${cgroup}/cpu.max`]: ["400000 100000\n"],
165+
"/proc/self/status": ["Name:\tnode\nCpus_allowed_list:\t4\n"],
166+
// CPU 1 is offline; the server's CPU 4 is saturated, everything else is idle.
167+
"/proc/stat": [0, 100].map((elapsed) =>
168+
[0, 2, 3, 4, 5, 6, 7]
169+
.map((id) =>
170+
id === 4
171+
? `cpu${id} ${elapsed} 0 0 0 0 0 0 0`
172+
: `cpu${id} 0 0 0 ${elapsed} 0 0 0 0`,
173+
)
174+
.join("\n"),
175+
),
165176
}),
166177
),
167178
),

‎apps/server/src/resourceTelemetry/HostResources.ts‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,24 @@ function parseCpuList(list: string): ReadonlySet<number> | null {
2626
return cpus;
2727
}
2828

29-
function readCpu(allowed: ReadonlySet<number> | null) {
30-
const all = NodeOS.cpus();
31-
const pinned = allowed ? all.filter((_, index) => allowed.has(index)) : all;
32-
const cpus = pinned.length > 0 ? pinned : all;
29+
// os.cpus() compacts online CPUs, so its indices are not CPU ids; /proc/stat lines are keyed.
30+
function pinnedCpu(stat: string, allowed: ReadonlySet<number>) {
31+
const cpu = { idle: 0, total: 0, count: 0 };
32+
for (const [, id, fields] of stat.matchAll(/^cpu(\d+) (.+)$/gm)) {
33+
if (!allowed.has(Number(id))) continue;
34+
const counters = (fields ?? "").trim().split(/\s+/).map(Number);
35+
const at = (index: number) => counters[index] ?? 0;
36+
// user nice system idle iowait irq softirq steal
37+
const idle = at(3) + at(4);
38+
cpu.idle += idle;
39+
cpu.total += idle + at(0) + at(1) + at(2) + at(5) + at(6) + at(7);
40+
cpu.count++;
41+
}
42+
return cpu.count > 0 ? cpu : null;
43+
}
44+
45+
function readCpu() {
46+
const cpus = NodeOS.cpus();
3347
const cpu = cpus.reduce(
3448
(sum, { times }) => ({
3549
idle: sum.idle + times.idle,
@@ -88,11 +102,16 @@ const make = Effect.fn("makeHostResources")(function* () {
88102
)
89103
: null;
90104

91-
const previousCpu = readCpu(allowedCpus);
105+
const sampleCpu = () =>
106+
allowedCpus
107+
? Effect.map(readFile("/proc/stat"), (stat) => pinnedCpu(stat, allowedCpus) ?? readCpu())
108+
: Effect.sync(readCpu);
109+
110+
const previousCpu = yield* sampleCpu();
92111
const previousUsage = yield* readCpuUsage();
93112
const startedAt = yield* Clock.currentTimeMillis;
94113
yield* Effect.sleep("200 millis");
95-
const cpu = readCpu(allowedCpus);
114+
const cpu = yield* sampleCpu();
96115
const usage = yield* readCpuUsage();
97116
const elapsedMicros = ((yield* Clock.currentTimeMillis) - startedAt) * 1000;
98117
const totalDelta = cpu.total - previousCpu.total;

0 commit comments

Comments
 (0)