TypeScript
fix(server): keep the shared Codex app-server scope alive after a tool OOM kill (#18329)
Victor Vogelb2cc18d3f2cb
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.tsindex a4f46514204..d9316c7a691 100644--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts@@ -1366,6 +1366,7 @@ export const makeCodexAppServerSpawnCommand = Effect.fn(name: "codex",threadId: input.threadId,env: input.env,+ shared: true,});const spawnCommand = yield* resolveSpawnCommand(launch.command, launch.args, {...(input.env === undefined ? {} : { env: input.env }),diff --git a/apps/server/src/process/agentScope.test.ts b/apps/server/src/process/agentScope.test.tsindex 396fc22987d..6f9c161e95a 100644--- a/apps/server/src/process/agentScope.test.ts+++ b/apps/server/src/process/agentScope.test.ts@@ -4,13 +4,15 @@ import * as NodeOS from "node:os";import * as NodePath from "node:path";import * as NodeServices from "@effect/platform-node/NodeServices";-import { describe, expect, it } from "@effect/vitest";+import { assert, describe, expect, it } from "@effect/vitest";+import { AgentScope } from "@t3tools/shared/AgentScope";import * as HostProcess from "@t3tools/shared/HostProcess";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";-import { ChildProcessSpawner } from "effect/process";+import { ChildProcess, ChildProcessSpawner } from "effect/process";import * as ServerConfig from "../config.ts";+import { makeCodexAppServerSpawnCommand } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";import * as ProcessRunner from "../processRunner.ts";import {agentSliceMemoryLimits,@@ -68,6 +70,7 @@ const withFakeSystemd = <A, E>(readonly calls: ReadonlyArray<ReadonlyArray<string>>;readonly stateDir: string;}) => Effect.Effect<A, E>,+ { oomPolicy = true }: { readonly oomPolicy?: boolean } = {},) =>Effect.gen(function* () {const bin = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agent-scope-"));@@ -76,10 +79,10 @@ const withFakeSystemd = <A, E>(}const units = new Map<string, { activeState: string; result: string }>();const calls: Array<ReadonlyArray<string>> = [];- const output = (stdout: string): ProcessRunner.ProcessRunOutput => ({+ const output = (stdout: string, code = 0): ProcessRunner.ProcessRunOutput => ({stdout,stderr: "",- code: ChildProcessSpawner.ExitCode(0),+ code: ChildProcessSpawner.ExitCode(code),timedOut: false,stdoutTruncated: false,stderrTruncated: false,@@ -90,6 +93,9 @@ const withFakeSystemd = <A, E>(run: ({ args }) =>Effect.sync(() => {calls.push(args);+ if (!oomPolicy && args.some((arg) => arg.startsWith("--property=OOMPolicy="))) {+ return output("", 1);+ }const [, verb, unit = ""] = args;if (verb === "reset-failed") units.delete(unit);if (verb !== "show") return output("");@@ -125,6 +131,16 @@ const unitOf = (launch: { readonly args: ReadonlyArray<string> }) =>const sliceOf = (launch: { readonly args: ReadonlyArray<string> }) =>launch.args.find((arg) => arg.startsWith("--slice="))?.slice("--slice=".length) ?? "";+const launchCodex = (scope: Effect.Success<typeof make>, threadId: string) =>+ makeCodexAppServerSpawnCommand({ command: "agent", args: ["app-server"], threadId }).pipe(+ Effect.provideService(AgentScope, scope),+ Effect.provideService(HostProcess.Platform, "linux"),+ Effect.map((command) => {+ assert(ChildProcess.isStandardCommand(command));+ return command;+ }),+ );+describe("AgentScope service", () => {it.effect("labels a thread from its newest scope until its next session clears it", () =>withFakeSystemd(({ scope, units }) =>@@ -146,6 +162,47 @@ describe("AgentScope service", () => {),);+ it.effect(+ "keeps shared Codex scopes running without attributing their OOM to the launch thread",+ () =>+ withFakeSystemd(({ scope, units, calls }) =>+ Effect.gen(function* () {+ const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });+ expect(agent.args).toContain("--property=OOMPolicy=stop");+ units.set(unitOf(agent), { activeState: "failed", result: "oom-kill" });+ expect(yield* scope.oomKilled("a")).toBe(true);++ const codex = yield* launchCodex(scope, "a");+ expect(codex.args).toContain("--property=OOMPolicy=continue");+ expect(codex.args).not.toContain("--property=OOMPolicy=stop");+ expect(codex.args).toContain("--property=TimeoutStopSec=10s");+ expect(codex.args).toContain("--collect");+ units.set(unitOf(codex), { activeState: "active", result: "success" });+ expect(yield* scope.oomKilled("a")).toBe(false);+ units.set(unitOf(codex), { activeState: "failed", result: "oom-kill" });+ expect(yield* scope.oomKilled("a")).toBe(false);+ expect(+ calls.filter(([, verb, unit]) => verb === "show" && unit === unitOf(codex)),+ ).toEqual([]);+ }),+ ),+ );++ it.effect("labels the shared Codex app-server's OOM kill on systemd without OOMPolicy", () =>+ withFakeSystemd(+ ({ scope, units }) =>+ Effect.gen(function* () {+ const codex = yield* launchCodex(scope, "a");+ units.set(unitOf(codex), { activeState: "failed", result: "oom-kill" });+ expect(yield* scope.oomKilled("a")).toBe(true);+ expect(codex.args.filter((arg) => arg.includes("OOMPolicy"))).toEqual([]);+ expect(codex.args).not.toContain("--collect");+ expect(codex.args).toContain("--property=TimeoutStopSec=10s");+ }),+ { oomPolicy: false },+ ),+ );+it.effect("keeps a running scope while hundreds of other threads launch", () =>withFakeSystemd(({ scope, units }) =>Effect.gen(function* () {diff --git a/apps/server/src/process/agentScope.ts b/apps/server/src/process/agentScope.tsindex ed69eb2ad75..be92a8957fa 100644--- a/apps/server/src/process/agentScope.ts+++ b/apps/server/src/process/agentScope.ts@@ -166,17 +166,9 @@ 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.- const stopOptions = [STOP_TIMEOUT_OPTION];- const oomOptions = [...stopOptions, "--property=OOMPolicy=stop"];- const scopeOptions = (yield* probe(oomOptions))- ? oomOptions- : (yield* probe(stopOptions))- ? stopOptions- : undefined;- if (scopeOptions === undefined) {+ // Scopes take OOMPolicy from systemd 253; older managers still get scopes.+ const supportsOomPolicy = yield* probe([STOP_TIMEOUT_OPTION, "--property=OOMPolicy=stop"]);+ if (!supportsOomPolicy && !(yield* probe([STOP_TIMEOUT_OPTION]))) {yield* Effect.logInfo("Agent scopes are off: no systemd user manager");return undefined;}@@ -197,13 +189,13 @@ export const make = Effect.gen(function* () {yield* Effect.logInfo("Agent scopes are on", {slice: AGENT_SLICE,...limits,- oomPolicy: scopeOptions.length > 0,+ oomPolicy: supportsOomPolicy,});return {systemdRun,systemctl,runtimeDir,- scopeOptions,+ supportsOomPolicy,};}),);@@ -318,21 +310,32 @@ export const make = Effect.gen(function* () {threadId,env,survivesRestart,+ shared,}) {const resolved = yield* resolve(command, env ?? hostEnvironment);if (resolved === null) return { command, args };const scope = yield* systemd;if (scope === undefined) return agentScopeCommand({ command: resolved, args });const unit = `t3code-${name}-${NodeCrypto.randomUUID().slice(0, 8)}.scope`;- if (threadId !== undefined) yield* track(scope.systemctl, threadId, unit);+ // A continuing shared scope cannot attribute a tool's OOM to one thread.+ // Clear the launch thread's previous scope instead.+ const continuing = shared === true && scope.supportsOomPolicy;+ const owned = threadId !== undefined && !continuing;+ if (threadId !== undefined) yield* track(scope.systemctl, threadId, owned ? unit : undefined);const systemdScope: AgentSystemdScope = {systemdRun: scope.systemdRun,runtimeDir: scope.runtimeDir,slice: survivesRestart === true ? AGENT_SLICE : ownedSlice,unit,- // Without a thread nothing reads the result, so let systemd unload- // the unit even when it fails.- options: threadId === undefined ? [...scope.scopeOptions, "--collect"] : scope.scopeOptions,+ // Without an owning thread nothing reads the result, so let systemd+ // unload the unit even when it fails.+ options: [+ STOP_TIMEOUT_OPTION,+ ...(scope.supportsOomPolicy+ ? [`--property=OOMPolicy=${continuing ? "continue" : "stop"}`]+ : []),+ ...(owned ? [] : ["--collect"]),+ ],};return agentScopeCommand({ command: resolved, args, scope: systemdScope });}),diff --git a/packages/shared/src/AgentScope.ts b/packages/shared/src/AgentScope.tsindex 08af8f0ba23..80902e8bbd1 100644--- a/packages/shared/src/AgentScope.ts+++ b/packages/shared/src/AgentScope.ts@@ -14,6 +14,11 @@ export interface AgentScopeShape {* killed server left running before it resumes their sessions.*/readonly survivesRestart?: boolean | undefined;+ /**+ * Keep a shared process running after a tool OOM when supported.+ * Falls back to ordinary scope behavior on older systemd.+ */+ readonly shared?: boolean | undefined;}) => Effect.Effect<AgentScopeCommand>;readonly oomKilled: (threadId: string) => Effect.Effect<boolean>;/**