Skip to content

Commit 7a2a7dc

Browse files
1stvampTrigger.dev RepoOps
authored andcommitted
fix(cli): report an out-of-memory kill of the task process as OOM_KILLED
Report a deployed task process that the kernel killed for running out of memory as `TASK_PROCESS_OOM_KILLED`, rather than as a generic exit after `SIGKILL`. When the out-of-memory killer ends only the task's process, the run controller survives and used to fail the attempt as a non-zero exit. The managed run controller now reads the `oom_kill` counter in its own cgroup v2 `memory.events`, which the task process shares: once before it dispatches the attempt, and again when the process dies by `SIGKILL`. If the count went up, the attempt fails as out of memory. The attempt waits for the first read, so an out-of-memory kill straight after dispatch is still counted. Each read takes well under a millisecond and is bounded to 100 ms; a read that does not finish in time turns detection off for that attempt. Where there is no such counter (cgroup v1, or a non-Linux host) nothing changes. Detection is off in dev, where several task processes share one cgroup and one task's kill could be read as another's. Retries are unchanged. The run engine already treated "exited with code -1 after signal SIGKILL" as out of memory, so both errors take the same path: a retry on the machine named in `retry.outOfMemory`, or failing the run when none is set. Both end the run as `CRASHED`. What changes is the error code stored on the attempt, and the dashboard showing it as an out-of-memory kill rather than a possible one. Mono-RevId: cc6443a4d7bf951ac3cb76b1b52360236ce1ccc4
1 parent 92eabfa commit 7a2a7dc

7 files changed

Lines changed: 347 additions & 6 deletions

File tree

‎.changeset/run-process-oom-kill.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"trigger.dev": patch
3+
---
4+
5+
Report a run whose process the kernel killed for running out of memory as `TASK_PROCESS_OOM_KILLED`, rather than as a generic exit after `SIGKILL`, when the out-of-memory kill is counted in the run's cgroup.

‎knip.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ export default {
7676
"src/shims/esm.ts",
7777
],
7878
ignoreDependencies: ["@epic-web/test-server", "execa", "find-up"],
79-
ignoreBinaries: ["xdg-open"],
79+
ignoreBinaries: ["xdg-open", "mkfifo"],
8080
},
8181
"packages/convex": {
8282
ignore: ["example/**"],
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
2+
import { tmpdir } from "node:os";
3+
import { join } from "node:path";
4+
import type { MachinePresetResources, WorkerManifest } from "@trigger.dev/core/v3";
5+
import { describe, expect, it } from "vitest";
6+
import { TaskRunProcessPool } from "./taskRunProcessPool.js";
7+
8+
describe("TaskRunProcessPool", () => {
9+
// Catches: dev task processes counting out-of-memory kills in the cgroup they share, so one
10+
// task's kill would fail another task's unrelated SIGKILL as out of memory.
11+
it("creates task processes without out-of-memory kill detection", async () => {
12+
const dir = await mkdtemp(join(tmpdir(), "task-run-process-pool-"));
13+
const pool = new TaskRunProcessPool({ env: {}, cwd: dir, enableProcessReuse: false });
14+
let pid: number | undefined;
15+
try {
16+
const entryPoint = join(dir, "child.mjs");
17+
await writeFile(entryPoint, "setInterval(() => {}, 1000);\n");
18+
const { taskRunProcess } = await pool.getProcess(
19+
{
20+
runtime: "node",
21+
workerEntryPoint: entryPoint,
22+
configEntryPoint: entryPoint,
23+
otelImportHook: {},
24+
} as unknown as WorkerManifest,
25+
{ id: "worker-1", version: "1", contentHash: "hash" },
26+
{ cpu: 1, memory: 1 } as MachinePresetResources
27+
);
28+
29+
pid = taskRunProcess.pid;
30+
31+
expect(taskRunProcess.options.oomKillCounter).toBeUndefined();
32+
} finally {
33+
if (pid) process.kill(pid, "SIGKILL");
34+
await rm(dir, { recursive: true, force: true });
35+
}
36+
});
37+
});

‎packages/cli-v3/src/entryPoints/managed/taskRunProcessProvider.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { WorkerManifest } from "@trigger.dev/core/v3";
22
import { generateFriendlyId } from "@trigger.dev/core/v3";
33
import { TaskRunProcess } from "../../executions/taskRunProcess.js";
4+
import { OWN_CGROUP_OOM_KILL_COUNTER } from "../../executions/oomKills.js";
45
import type { RunnerEnv } from "./env.js";
56
import type { RunLogger, SendDebugLogOptions } from "./logger.js";
67

@@ -265,6 +266,8 @@ export class TaskRunProcessProvider {
265266
memory: Number(this.env.TRIGGER_MACHINE_MEMORY),
266267
},
267268
isWarmStart,
269+
// This runner's cgroup holds only the controller and the one task process it runs.
270+
oomKillCounter: OWN_CGROUP_OOM_KILL_COUNTER,
268271
}).initialize();
269272

270273
return taskRunProcess;
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import { readFile } from "node:fs/promises";
2+
import { join } from "node:path";
3+
4+
export type OomKillCounterPaths = {
5+
procSelfCgroup: string;
6+
cgroupRoot: string;
7+
};
8+
9+
/** This process's own cgroup (cgroup v2), which a forked child shares. */
10+
export const OWN_CGROUP_OOM_KILL_COUNTER: OomKillCounterPaths = {
11+
procSelfCgroup: "/proc/self/cgroup",
12+
cgroupRoot: "/sys/fs/cgroup",
13+
};
14+
15+
/**
16+
* How many processes the kernel's out-of-memory killer has killed in the cgroup `paths` name, or
17+
* undefined when the read takes longer than `timeoutMs` or there is no such counter: cgroup v1, a
18+
* non-Linux host, or a file that cannot be read.
19+
*/
20+
export async function readOomKillCountWithin(
21+
paths: OomKillCounterPaths,
22+
timeoutMs: number
23+
): Promise<number | undefined> {
24+
let timer: NodeJS.Timeout | undefined;
25+
const timeout = new Promise<undefined>((resolve) => {
26+
timer = setTimeout(resolve, timeoutMs, undefined);
27+
});
28+
try {
29+
return await Promise.race([readOomKillCount(paths), timeout]);
30+
} finally {
31+
clearTimeout(timer);
32+
}
33+
}
34+
35+
async function readOomKillCount(paths: OomKillCounterPaths): Promise<number | undefined> {
36+
try {
37+
const cgroup = cgroupV2Path(await readFile(paths.procSelfCgroup, "utf8"));
38+
if (cgroup === undefined) {
39+
return undefined;
40+
}
41+
const events = await readFile(join(paths.cgroupRoot, cgroup, "memory.events"), "utf8");
42+
return parseOomKills(events);
43+
} catch {
44+
return undefined;
45+
}
46+
}
47+
48+
/** The unified hierarchy's entry in /proc/self/cgroup is the one with id 0 and no controllers. */
49+
function cgroupV2Path(procSelfCgroup: string): string | undefined {
50+
for (const line of procSelfCgroup.split("\n")) {
51+
if (line.startsWith("0::")) {
52+
return line.slice(3);
53+
}
54+
}
55+
return undefined;
56+
}
57+
58+
/** `oom_kill` counts kills; `oom` counts invocations, which can end without one. */
59+
function parseOomKills(memoryEvents: string): number | undefined {
60+
for (const line of memoryEvents.split("\n")) {
61+
const [key, value] = line.trim().split(/\s+/);
62+
if (key === "oom_kill") {
63+
const count = Number(value);
64+
return Number.isInteger(count) ? count : undefined;
65+
}
66+
}
67+
return undefined;
68+
}

‎packages/cli-v3/src/executions/taskRunProcess.test.ts‎

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
import { TaskRunProcess, trustStoreEnv, type TaskRunProcessOptions } from "./taskRunProcess.js";
22
import { describe, it, expect, vi } from "vitest";
3+
import { execFileSync } from "node:child_process";
4+
import { closeSync, constants, openSync } from "node:fs";
5+
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
6+
import { tmpdir } from "node:os";
7+
import { join } from "node:path";
38
import { UncaughtExceptionError, UnexpectedExitError } from "@trigger.dev/core/v3/errors";
49
import type {
510
TaskRunExecution,
@@ -195,4 +200,171 @@ describe("TaskRunProcess", () => {
195200
expect(result.message).toBe("boom");
196201
});
197202
});
203+
204+
describe("a child killed with SIGKILL", () => {
205+
type Cgroup = { dir: string; events: string; writeEvents: (kills: number) => Promise<void> };
206+
207+
// A fake cgroup whose out-of-memory counter the test writes.
208+
async function withCgroup<T>(run: (cgroup: Cgroup) => Promise<T>): Promise<T> {
209+
const dir = await mkdtemp(join(tmpdir(), "task-run-process-oom-"));
210+
try {
211+
await writeFile(join(dir, "cgroup"), "0::/run\n");
212+
await mkdir(join(dir, "sys", "run"), { recursive: true });
213+
const events = join(dir, "sys", "run", "memory.events");
214+
return await run({
215+
dir,
216+
events,
217+
writeEvents: (kills) => writeFile(events, eventsWith(kills)),
218+
});
219+
} finally {
220+
await rm(dir, { recursive: true, force: true });
221+
}
222+
}
223+
224+
function eventsWith(kills: number) {
225+
return `low 0\nhigh 0\nmax 3\noom 4\noom_kill ${kills}\noom_group_kill 0\n`;
226+
}
227+
228+
// Starts an attempt on a child running `childSource`, and returns what it fails with.
229+
async function attemptOn(
230+
cgroup: Cgroup,
231+
childSource: string,
232+
options: Partial<TaskRunProcessOptions> = {}
233+
) {
234+
const entryPoint = join(cgroup.dir, "child.mjs");
235+
await writeFile(entryPoint, childSource);
236+
const proc = new TaskRunProcess(
237+
createTaskRunProcessOptions({
238+
workerManifest: {
239+
runtime: "node",
240+
workerEntryPoint: entryPoint,
241+
configEntryPoint: entryPoint,
242+
otelImportHook: {},
243+
} as unknown as WorkerManifest,
244+
serverWorker: { id: "worker-1", version: "1", contentHash: "hash" },
245+
env: { OOM_EVENTS: cgroup.events, OOM_EVENTS_AFTER: eventsWith(1) },
246+
oomKillCounter: {
247+
procSelfCgroup: join(cgroup.dir, "cgroup"),
248+
cgroupRoot: join(cgroup.dir, "sys"),
249+
},
250+
...options,
251+
})
252+
).initialize();
253+
254+
const failure = proc
255+
.execute(
256+
{
257+
payload: { execution: createExecution("run-1", 1), traceContext: {}, metrics: [] },
258+
messageId: "run_run-1",
259+
env: {},
260+
},
261+
false
262+
)
263+
.then(
264+
() => {
265+
throw new Error("the attempt resolved");
266+
},
267+
(error: unknown) => TaskRunProcess.parseExecuteError(error)
268+
);
269+
return { proc, failure };
270+
}
271+
272+
// Opens the FIFO for writing once its reader is waiting, so the blocked read sees end of file
273+
// and does not outlive the test.
274+
async function releaseReader(fifo: string) {
275+
const deadline = Date.now() + 5_000;
276+
while (Date.now() < deadline) {
277+
try {
278+
closeSync(openSync(fifo, constants.O_WRONLY | constants.O_NONBLOCK));
279+
return;
280+
} catch {
281+
await new Promise((resolve) => setTimeout(resolve, 10));
282+
}
283+
}
284+
}
285+
286+
const IDLE_CHILD = "setInterval(() => {}, 1000);\n";
287+
288+
// Counts an out-of-memory kill and dies by SIGKILL as soon as the attempt reaches it.
289+
const OOM_ON_EXECUTE_CHILD = [
290+
'import { writeFileSync } from "node:fs";',
291+
'process.on("message", () => {',
292+
" writeFileSync(process.env.OOM_EVENTS, process.env.OOM_EVENTS_AFTER);",
293+
' process.kill(process.pid, "SIGKILL");',
294+
"});",
295+
"",
296+
].join("\n");
297+
298+
async function killedAfterBaseline(oomKillsBefore: number, oomKillsAtKill: number) {
299+
return withCgroup(async (cgroup) => {
300+
await cgroup.writeEvents(oomKillsBefore);
301+
const { proc, failure } = await attemptOn(cgroup, IDLE_CHILD);
302+
// Let the attempt read its baseline before the kill is counted.
303+
await new Promise((resolve) => setTimeout(resolve, 50));
304+
await cgroup.writeEvents(oomKillsAtKill);
305+
process.kill(proc.pid!, "SIGKILL");
306+
return failure;
307+
});
308+
}
309+
310+
// Catches: an out-of-memory kill of the child failing the attempt as a generic non-zero
311+
// exit, so the run gets the wrong error and is retried as an ordinary crash.
312+
it("reports TASK_PROCESS_OOM_KILLED when the cgroup counted an out-of-memory kill", async () => {
313+
const error = await killedAfterBaseline(0, 1);
314+
315+
expect(error.code).toBe("TASK_PROCESS_OOM_KILLED");
316+
expect(error.message).toBe("Process exited with code -1 after signal SIGKILL.");
317+
});
318+
319+
// Catches: the counter read as a total rather than a change, so one earlier out-of-memory
320+
// kill in the cgroup makes every later SIGKILL read as out of memory.
321+
it("reports a non-zero exit when no out-of-memory kill was counted during the attempt", async () => {
322+
const error = await killedAfterBaseline(1, 1);
323+
324+
expect(error.code).toBe("TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE");
325+
});
326+
327+
// Catches: the baseline read racing the attempt's dispatch, so a kill right after the
328+
// attempt starts lands in the baseline and is reported as a non-zero exit.
329+
it("counts an out-of-memory kill that happens as soon as the attempt starts", async () => {
330+
const error = await withCgroup(async (cgroup) => {
331+
await cgroup.writeEvents(0);
332+
return (await attemptOn(cgroup, OOM_ON_EXECUTE_CHILD)).failure;
333+
});
334+
335+
expect(error.code).toBe("TASK_PROCESS_OOM_KILLED");
336+
});
337+
338+
// Catches: a child that exits while the attempt waits on the counter rejecting the attempt
339+
// before anything handles it, an unhandled rejection that can take the controller down, and
340+
// the exit then being reported as a child that was never connected.
341+
it("reports a child that exits during a slow counter read as the attempt's error", async () => {
342+
const unhandled: unknown[] = [];
343+
const onUnhandled = (reason: unknown) => unhandled.push(reason);
344+
process.on("unhandledRejection", onUnhandled);
345+
try {
346+
const error = await withCgroup(async (cgroup) => {
347+
// Nothing writes to it, so the read blocks until the test releases it.
348+
execFileSync("mkfifo", [cgroup.events]);
349+
try {
350+
const { proc, failure } = await attemptOn(cgroup, IDLE_CHILD);
351+
const exited = new Promise((resolve) => proc.onExit.attachOnce(resolve));
352+
process.kill(proc.pid!, "SIGKILL");
353+
await exited;
354+
// Gives Node a turn to report an unhandled rejection while the read is still blocked.
355+
await new Promise((resolve) => setImmediate(resolve));
356+
return await failure;
357+
} finally {
358+
await releaseReader(cgroup.events);
359+
}
360+
});
361+
362+
expect(error.code).toBe("TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE");
363+
expect(error.message).toBe("Process exited with code -1 after signal SIGKILL.");
364+
expect(unhandled).toEqual([]);
365+
} finally {
366+
process.off("unhandledRejection", onUnhandled);
367+
}
368+
});
369+
});
198370
});

0 commit comments

Comments
 (0)