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
48 changes: 28 additions & 20 deletions apps/server/src/process/agentScope.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,7 @@ import { ChildProcessSpawner } from "effect/process";

import * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
import {
agentSliceMemoryLimits,
classifyScope,
make,
ownedAgentSlice,
type ScopeState,
} from "./agentScope.ts";

const GiB = 1024 ** 3;
import { classifyScope, make, ownedAgentSlice, type ScopeState } from "./agentScope.ts";

const running: ScopeState = {
loadState: "loaded",
Expand All @@ -36,13 +28,15 @@ describe("classifyScope", () => {
"oom-killed",
);
// The agent pipe can close before systemd handles the kill.
expect(classifyScope({ ...running, oomKills: 1 })).toBe("stopping");
expect(classifyScope({ ...running, populated: false })).toBe("stopping");
expect(classifyScope({ ...running, activeState: "deactivating" })).toBe("stopping");
});

it("does not wait on a live agent or a scope that ended for another reason", () => {
expect(classifyScope(running)).toBe("running");
// OOMPolicy=continue keeps a scope running after the kernel kills one of
// its processes.
expect(classifyScope({ ...running, oomKills: 1 })).toBe("running");
expect(classifyScope({ ...running, activeState: "inactive", populated: undefined })).toBe(
"gone",
);
Expand All @@ -52,16 +46,6 @@ describe("classifyScope", () => {
});
});

describe("agentSliceMemoryLimits", () => {
it("leaves 6 GB before throttling and 4 GB before a kill on large machines", () => {
expect(agentSliceMemoryLimits(64 * GiB)).toEqual({ high: 58 * GiB, max: 60 * GiB });
});

it("still gives agents most of a small machine", () => {
expect(agentSliceMemoryLimits(8 * GiB)).toEqual({ high: 4 * GiB, max: 6 * GiB });
});
});

// Runs the real service against a fake user manager. `units` holds the
// ActiveState and Result that `systemctl show` reports for each scope or
// slice, and `calls` records every command in order.
Expand Down Expand Up @@ -191,6 +175,30 @@ describe("AgentScope service", () => {
),
);

it.effect("launches scopes that outlive an OOM kill on a slice without memory limits", () =>
withFakeSystemd(({ scope, calls }) =>
Effect.gen(function* () {
const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
// OOMPolicy=stop would end the shared Codex app-server for every thread.
expect(agent.args).toContain("--property=OOMPolicy=continue");
// An older build may have left its limits on the shared slice.
expect(calls.filter(([, verb]) => verb === "set-property")).toEqual([
[
"--user",
"set-property",
"--runtime",
"app-t3code-agents.slice",
"MemoryHigh=infinity",
"MemoryMax=infinity",
],
]);
// A throttled slice could stall the probe scopes, so the limits go first.
const verbs = calls.map(([, verb]) => verb);
expect(verbs.indexOf("set-property")).toBeLessThan(verbs.indexOf("--scope"));
}),
),
);

it.effect("leaves a quiet slice alone", () =>
withFakeSystemd(({ scope, calls }) =>
Effect.gen(function* () {
Expand Down
67 changes: 27 additions & 40 deletions apps/server/src/process/agentScope.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// @effect-diagnostics nodeBuiltinImport:off -- unit names and RAM size come from the host.
// @effect-diagnostics nodeBuiltinImport:off -- unit names come from node:crypto.
import * as NodeCrypto from "node:crypto";
import * as NodeOS from "node:os";

import {
AgentScope,
Expand Down Expand Up @@ -37,21 +36,6 @@ export function ownedAgentSlice(stateDir: string): string {
return `app-t3code-agents-${hash}.slice`;
}

const GiB = 1024 ** 3;

/**
* Memory limits for the agents slice. Agents together leave about 6 GB free
* before they are throttled and 4 GB before the kernel kills one, so the
* server, sshd, and tailscaled keep working. Small machines still give agents
* at least half of RAM before throttling and three quarters before a kill.
*/
export function agentSliceMemoryLimits(totalBytes: number) {
return {
high: Math.max(totalBytes - 6 * GiB, Math.floor(totalBytes / 2)),
max: Math.max(totalBytes - 4 * GiB, Math.floor(totalBytes * 0.75)),
};
}

export interface ScopeState {
readonly loadState: string;
readonly activeState: string;
Expand All @@ -64,9 +48,9 @@ export interface ScopeState {

/**
* Reads one scope as the server sees it right after the agent process exits.
* Our pipe can close before systemd handles the kill, so a scope that is
* still stopping, is empty, or already counted an OOM kill is "stopping":
* systemd records `Result=oom-kill` for it in a moment.
* Our pipe can close before systemd finishes with the scope, so a scope that
* is still stopping or is empty is "stopping": systemd records its result in
* a moment.
*/
export function classifyScope(state: ScopeState): "oom-killed" | "gone" | "running" | "stopping" {
if (state.result === "oom-kill") return "oom-killed";
Expand All @@ -77,7 +61,7 @@ export function classifyScope(state: ScopeState): "oom-killed" | "gone" | "runni
) {
return "gone";
}
if (state.activeState === "deactivating" || state.oomKills > 0 || state.populated === false) {
if (state.activeState === "deactivating" || state.populated === false) {
return "stopping";
}
return "running";
Expand Down Expand Up @@ -167,7 +151,7 @@ export const make = Effect.gen(function* () {

// Runs once, on the first agent or terminal launch. It proves this process
// can reach a systemd user manager, stops agents a previous server left,
// creates the agents slice, and sets its limits.
// clears memory limits on the agents slice, and creates it.
const systemd = yield* Effect.cached(
Effect.gen(function* () {
const runtimeDir = hostEnvironment.XDG_RUNTIME_DIR;
Expand All @@ -176,6 +160,17 @@ export const make = Effect.gen(function* () {
const systemctl = yield* resolve("systemctl", hostEnvironment);
if (systemdRun === null || systemctl === null) return undefined;
yield* stopLeftoverAgents(systemctl);
// Every T3 build for this user shares the slice name, and the last build
// to write its properties wins. Clear the limits earlier builds set
// before the probes below start scopes in a slice they may throttle.
const cleared = yield* run(systemctl, [
"--user",
"set-property",
"--runtime",
AGENT_SLICE,
"MemoryHigh=infinity",
"MemoryMax=infinity",
]);
const probe = (options: ReadonlyArray<string>) =>
run(systemdRun, [
"--user",
Expand All @@ -187,11 +182,13 @@ export const make = Effect.gen(function* () {
"--",
"true",
]).pipe(Effect.map((result) => result._tag === "Some" && result.value.code === 0));
// Stop the whole scope when the kernel kills one of its processes, and
// record the result as oom-kill. Scopes take OOMPolicy from systemd 253;
// older user managers still get scopes, without the OOM label.
// When the kernel kills one process for memory, such as a command an
// agent ran, the rest of its scope keeps running: the agent itself, or
// the Codex app-server or opencode serve that many threads share.
// Scopes take OOMPolicy from systemd 253. Older user managers get plain
// scopes, which 252 still stops on an OOM kill.
const stopOptions = [STOP_TIMEOUT_OPTION];
const oomOptions = [...stopOptions, "--property=OOMPolicy=stop"];
const oomOptions = [...stopOptions, "--property=OOMPolicy=continue"];
const scopeOptions = (yield* probe(oomOptions))
? oomOptions
: (yield* probe(stopOptions))
Expand All @@ -201,24 +198,14 @@ export const make = Effect.gen(function* () {
yield* Effect.logInfo("Agent scopes are off: no systemd user manager");
return undefined;
}
const limits = agentSliceMemoryLimits(NodeOS.totalmem());
const limited = yield* run(systemctl, [
"--user",
"set-property",
"--runtime",
AGENT_SLICE,
`MemoryHigh=${limits.high}`,
`MemoryMax=${limits.max}`,
]);
if (limited._tag === "None" || limited.value.code !== 0) {
yield* Effect.logWarning("Could not set memory limits on the agents slice", {
stderr: limited._tag === "Some" ? limited.value.stderr.trim() : undefined,
if (cleared._tag === "None" || cleared.value.code !== 0) {
yield* Effect.logWarning("Could not clear memory limits on the agents slice", {
stderr: cleared._tag === "Some" ? cleared.value.stderr.trim() : undefined,
});
}
yield* Effect.logInfo("Agent scopes are on", {
slice: AGENT_SLICE,
...limits,
oomPolicy: scopeOptions.length > 0,
oomPolicy: scopeOptions === oomOptions,
});
return {
systemdRun,
Expand Down
6 changes: 3 additions & 3 deletions packages/shared/src/AgentScope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ export interface AgentScopeShape {
}) => Effect.Effect<AgentScopeCommand>;
/**
* Whether the latest agent scope of this thread was killed because the
* machine or the agents slice ran out of memory. The answer holds until the
* thread launches its next agent, so a retried failure reads the same.
* machine ran out of memory. The answer holds until the thread launches its
* next agent, so a retried failure reads the same.
*/
readonly oomKilled: (threadId: string) => Effect.Effect<boolean>;
/**
Expand Down Expand Up @@ -94,7 +94,7 @@ export interface AgentSystemdScope {
readonly slice: string;
readonly unit: string;
readonly runtimeDir: string;
/** Extra `systemd-run` options, such as `--property=OOMPolicy=stop`. */
/** Extra `systemd-run` options, such as `--property=OOMPolicy=continue`. */
readonly options: ReadonlyArray<string>;
}

Expand Down
Loading