diff --git a/apps/server/src/process/agentScope.test.ts b/apps/server/src/process/agentScope.test.ts index f29cd867244af..a5841ba1c75fe 100644 --- a/apps/server/src/process/agentScope.test.ts +++ b/apps/server/src/process/agentScope.test.ts @@ -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", @@ -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", ); @@ -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. @@ -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* () { diff --git a/apps/server/src/process/agentScope.ts b/apps/server/src/process/agentScope.ts index bfe013827301f..19a4a4a5f74c0 100644 --- a/apps/server/src/process/agentScope.ts +++ b/apps/server/src/process/agentScope.ts @@ -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, @@ -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; @@ -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"; @@ -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"; @@ -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; @@ -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) => run(systemdRun, [ "--user", @@ -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)) @@ -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, diff --git a/packages/shared/src/AgentScope.ts b/packages/shared/src/AgentScope.ts index 61255e5a4e294..915f9d8fa4368 100644 --- a/packages/shared/src/AgentScope.ts +++ b/packages/shared/src/AgentScope.ts @@ -34,8 +34,8 @@ export interface AgentScopeShape { }) => Effect.Effect; /** * 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; /** @@ -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; }