@devries-cameron20 / t3code-1 / commits / b2cc18d3f2
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): keep the shared Codex app-server scope alive after a tool OOM kill (#18329)

Co-authored-by: Victor Vogel <263261067+only21mil@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Victor Vogel committed Oct 19, 2026 at 13:39 UTC b2cc18d3f2cbb5978e1e074ac4495b9a8b52504e
4 files changed +87 -21
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+1
@@ -1366,6 +1366,7 @@ export const makeCodexAppServerSpawnCommand = Effect.fn(
1366 name: "codex",
1367 threadId: input.threadId,
1368 env: input.env,
1369 + shared: true,
1370 });
1371 const spawnCommand = yield* resolveSpawnCommand(launch.command, launch.args, {
1372 ...(input.env === undefined ? {} : { env: input.env }),
apps/server/src/process/agentScope.test.ts
+61 -4
@@ -4,13 +4,15 @@ import * as NodeOS from "node:os";
4 import * as NodePath from "node:path";
5
6 import * as NodeServices from "@effect/platform-node/NodeServices";
7 -import { describe, expect, it } from "@effect/vitest";
7 +import { assert, describe, expect, it } from "@effect/vitest";
8 +import { AgentScope } from "@t3tools/shared/AgentScope";
9 import * as HostProcess from "@t3tools/shared/HostProcess";
10 import * as Effect from "effect/Effect";
11 import * as Layer from "effect/Layer";
11 -import { ChildProcessSpawner } from "effect/process";
12 +import { ChildProcess, ChildProcessSpawner } from "effect/process";
13
14 import * as ServerConfig from "../config.ts";
15 +import { makeCodexAppServerSpawnCommand } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
16 import * as ProcessRunner from "../processRunner.ts";
17 import {
18 agentSliceMemoryLimits,
@@ -68,6 +70,7 @@ const withFakeSystemd = <A, E>(
70 readonly calls: ReadonlyArray<ReadonlyArray<string>>;
71 readonly stateDir: string;
72 }) => Effect.Effect<A, E>,
73 + { oomPolicy = true }: { readonly oomPolicy?: boolean } = {},
74 ) =>
75 Effect.gen(function* () {
76 const bin = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agent-scope-"));
@@ -76,10 +79,10 @@ const withFakeSystemd = <A, E>(
79 }
80 const units = new Map<string, { activeState: string; result: string }>();
81 const calls: Array<ReadonlyArray<string>> = [];
79 - const output = (stdout: string): ProcessRunner.ProcessRunOutput => ({
82 + const output = (stdout: string, code = 0): ProcessRunner.ProcessRunOutput => ({
83 stdout,
84 stderr: "",
82 - code: ChildProcessSpawner.ExitCode(0),
85 + code: ChildProcessSpawner.ExitCode(code),
86 timedOut: false,
87 stdoutTruncated: false,
88 stderrTruncated: false,
@@ -90,6 +93,9 @@ const withFakeSystemd = <A, E>(
93 run: ({ args }) =>
94 Effect.sync(() => {
95 calls.push(args);
96 + if (!oomPolicy && args.some((arg) => arg.startsWith("--property=OOMPolicy="))) {
97 + return output("", 1);
98 + }
99 const [, verb, unit = ""] = args;
100 if (verb === "reset-failed") units.delete(unit);
101 if (verb !== "show") return output("");
@@ -125,6 +131,16 @@ const unitOf = (launch: { readonly args: ReadonlyArray<string> }) =>
131 const sliceOf = (launch: { readonly args: ReadonlyArray<string> }) =>
132 launch.args.find((arg) => arg.startsWith("--slice="))?.slice("--slice=".length) ?? "";
133
134 +const launchCodex = (scope: Effect.Success<typeof make>, threadId: string) =>
135 + makeCodexAppServerSpawnCommand({ command: "agent", args: ["app-server"], threadId }).pipe(
136 + Effect.provideService(AgentScope, scope),
137 + Effect.provideService(HostProcess.Platform, "linux"),
138 + Effect.map((command) => {
139 + assert(ChildProcess.isStandardCommand(command));
140 + return command;
141 + }),
142 + );
143 +
144 describe("AgentScope service", () => {
145 it.effect("labels a thread from its newest scope until its next session clears it", () =>
146 withFakeSystemd(({ scope, units }) =>
@@ -146,6 +162,47 @@ describe("AgentScope service", () => {
162 ),
163 );
164
165 + it.effect(
166 + "keeps shared Codex scopes running without attributing their OOM to the launch thread",
167 + () =>
168 + withFakeSystemd(({ scope, units, calls }) =>
169 + Effect.gen(function* () {
170 + const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
171 + expect(agent.args).toContain("--property=OOMPolicy=stop");
172 + units.set(unitOf(agent), { activeState: "failed", result: "oom-kill" });
173 + expect(yield* scope.oomKilled("a")).toBe(true);
174 +
175 + const codex = yield* launchCodex(scope, "a");
176 + expect(codex.args).toContain("--property=OOMPolicy=continue");
177 + expect(codex.args).not.toContain("--property=OOMPolicy=stop");
178 + expect(codex.args).toContain("--property=TimeoutStopSec=10s");
179 + expect(codex.args).toContain("--collect");
180 + units.set(unitOf(codex), { activeState: "active", result: "success" });
181 + expect(yield* scope.oomKilled("a")).toBe(false);
182 + units.set(unitOf(codex), { activeState: "failed", result: "oom-kill" });
183 + expect(yield* scope.oomKilled("a")).toBe(false);
184 + expect(
185 + calls.filter(([, verb, unit]) => verb === "show" && unit === unitOf(codex)),
186 + ).toEqual([]);
187 + }),
188 + ),
189 + );
190 +
191 + it.effect("labels the shared Codex app-server's OOM kill on systemd without OOMPolicy", () =>
192 + withFakeSystemd(
193 + ({ scope, units }) =>
194 + Effect.gen(function* () {
195 + const codex = yield* launchCodex(scope, "a");
196 + units.set(unitOf(codex), { activeState: "failed", result: "oom-kill" });
197 + expect(yield* scope.oomKilled("a")).toBe(true);
198 + expect(codex.args.filter((arg) => arg.includes("OOMPolicy"))).toEqual([]);
199 + expect(codex.args).not.toContain("--collect");
200 + expect(codex.args).toContain("--property=TimeoutStopSec=10s");
201 + }),
202 + { oomPolicy: false },
203 + ),
204 + );
205 +
206 it.effect("keeps a running scope while hundreds of other threads launch", () =>
207 withFakeSystemd(({ scope, units }) =>
208 Effect.gen(function* () {
apps/server/src/process/agentScope.ts
+20 -17
@@ -166,17 +166,9 @@ export const make = Effect.gen(function* () {
166 "--",
167 "true",
168 ]).pipe(Effect.map((result) => result._tag === "Some" && result.value.code === 0));
169 - // Stop the whole scope when the kernel kills one of its processes, and
170 - // record the result as oom-kill. Scopes take OOMPolicy from systemd 253;
171 - // older user managers still get scopes, without the OOM label.
172 - const stopOptions = [STOP_TIMEOUT_OPTION];
173 - const oomOptions = [...stopOptions, "--property=OOMPolicy=stop"];
174 - const scopeOptions = (yield* probe(oomOptions))
175 - ? oomOptions
176 - : (yield* probe(stopOptions))
177 - ? stopOptions
178 - : undefined;
179 - if (scopeOptions === undefined) {
169 + // Scopes take OOMPolicy from systemd 253; older managers still get scopes.
170 + const supportsOomPolicy = yield* probe([STOP_TIMEOUT_OPTION, "--property=OOMPolicy=stop"]);
171 + if (!supportsOomPolicy && !(yield* probe([STOP_TIMEOUT_OPTION]))) {
172 yield* Effect.logInfo("Agent scopes are off: no systemd user manager");
173 return undefined;
174 }
@@ -197,13 +189,13 @@ export const make = Effect.gen(function* () {
189 yield* Effect.logInfo("Agent scopes are on", {
190 slice: AGENT_SLICE,
191 ...limits,
200 - oomPolicy: scopeOptions.length > 0,
192 + oomPolicy: supportsOomPolicy,
193 });
194 return {
195 systemdRun,
196 systemctl,
197 runtimeDir,
206 - scopeOptions,
198 + supportsOomPolicy,
199 };
200 }),
201 );
@@ -318,21 +310,32 @@ export const make = Effect.gen(function* () {
310 threadId,
311 env,
312 survivesRestart,
313 + shared,
314 }) {
315 const resolved = yield* resolve(command, env ?? hostEnvironment);
316 if (resolved === null) return { command, args };
317 const scope = yield* systemd;
318 if (scope === undefined) return agentScopeCommand({ command: resolved, args });
319 const unit = `t3code-${name}-${NodeCrypto.randomUUID().slice(0, 8)}.scope`;
327 - if (threadId !== undefined) yield* track(scope.systemctl, threadId, unit);
320 + // A continuing shared scope cannot attribute a tool's OOM to one thread.
321 + // Clear the launch thread's previous scope instead.
322 + const continuing = shared === true && scope.supportsOomPolicy;
323 + const owned = threadId !== undefined && !continuing;
324 + if (threadId !== undefined) yield* track(scope.systemctl, threadId, owned ? unit : undefined);
325 const systemdScope: AgentSystemdScope = {
326 systemdRun: scope.systemdRun,
327 runtimeDir: scope.runtimeDir,
328 slice: survivesRestart === true ? AGENT_SLICE : ownedSlice,
329 unit,
333 - // Without a thread nothing reads the result, so let systemd unload
334 - // the unit even when it fails.
335 - options: threadId === undefined ? [...scope.scopeOptions, "--collect"] : scope.scopeOptions,
330 + // Without an owning thread nothing reads the result, so let systemd
331 + // unload the unit even when it fails.
332 + options: [
333 + STOP_TIMEOUT_OPTION,
334 + ...(scope.supportsOomPolicy
335 + ? [`--property=OOMPolicy=${continuing ? "continue" : "stop"}`]
336 + : []),
337 + ...(owned ? [] : ["--collect"]),
338 + ],
339 };
340 return agentScopeCommand({ command: resolved, args, scope: systemdScope });
341 }),
packages/shared/src/AgentScope.ts
+5
@@ -14,6 +14,11 @@ export interface AgentScopeShape {
14 * killed server left running before it resumes their sessions.
15 */
16 readonly survivesRestart?: boolean | undefined;
17 + /**
18 + * Keep a shared process running after a tool OOM when supported.
19 + * Falls back to ordinary scope behavior on older systemd.
20 + */
21 + readonly shared?: boolean | undefined;
22 }) => Effect.Effect<AgentScopeCommand>;
23 readonly oomKilled: (threadId: string) => Effect.Effect<boolean>;
24 /**