Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion server/jobs/supervisor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";

import { CRASH_STREAK, JOB_TOKEN_PREFIX, JobSupervisor, restartDelay, type JobNote, type JobRecord, type JobSpec, type SupervisorOptions } from "./supervisor.ts";
import { CRASH_STREAK, JOB_TOKEN_PREFIX, JobSupervisor, restartDelay, SAMPLE_MS, type JobNote, type JobRecord, type JobSpec, type SupervisorOptions } from "./supervisor.ts";

const roots: string[] = [];
const supervisors: JobSupervisor[] = [];
Expand Down Expand Up @@ -168,3 +168,35 @@ describe.skipIf(process.platform === "win32")("background job supervisor", () =>
expect(supervisor.list()).toEqual([]);
});
});

describe("background job CPU limit", () => {
it("stops a run that stays over the CPU share for 5 minutes even when sample ticks drift", async () => {
let clock = 1_000_000, cpuMs = 0;
const killed: Array<[number, NodeJS.Signals]> = [];
const fakeProcess = { pid: 4242, stdout: null, stderr: null, once: () => {} };
const { supervisor } = harness({
now: () => clock,
launch: () => ({ process: fakeProcess, secrets: [] }),
kill: (pid, signal) => { killed.push([pid, signal]); },
usage: async (pids) => new Map(pids.map((pid) => [pid, { rssBytes: 10, cpuMs }])),
});
const { job } = supervisor.start(spec("busy"));

for (let i = 0; i <= 10; i += 1) {
await supervisor.sample();
clock += SAMPLE_MS + 5;
if (i < 4) cpuMs += SAMPLE_MS + 5;
}
expect(killed).toEqual([]);

for (let i = 0; i <= 10; i += 1) {
await supervisor.sample();
if (killed.length) break;
clock += SAMPLE_MS + 5;
cpuMs += SAMPLE_MS + 5;
}
expect(killed).toEqual([[4242, "SIGKILL"]]);
expect(supervisor.get(job.id, "bot-a")?.lastExit).toBe("cpu");
expect(supervisor.logs(job.id, "bot-a")).toContain("stopped this run: cpu");
});
});
2 changes: 1 addition & 1 deletion server/jobs/supervisor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ export class JobSupervisor {
continue;
}
live.cpu.push([at, used.cpuMs]);
while (live.cpu.length > 1 && at - live.cpu[0]![0] > CPU_WINDOW_MS) live.cpu.shift();
while (live.cpu.length > 1 && at - live.cpu[1]![0] >= CPU_WINDOW_MS) live.cpu.shift();
const [firstAt, firstCpu] = live.cpu[0]!;
if (at - firstAt >= CPU_WINDOW_MS && (used.cpuMs - firstCpu) / (at - firstAt) > this.limits.cpuShare) {
this.endRun(job, live, "cpu: kept a whole CPU busy for 5 minutes");
Expand Down
Loading