Repository navigation
fix(server): isolate Linux agent and terminal workloads #14338
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
+248
−8
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| import * as NodeChildProcess from "node:child_process"; | ||
| import * as NodeFSP from "node:fs/promises"; | ||
| import * as NodeOS from "node:os"; | ||
| import * as NodePath from "node:path"; | ||
| import * as NodeUtil from "node:util"; | ||
|
|
||
| import { HostProcessPlatform } from "@t3tools/shared/hostProcess"; | ||
|
|
||
| import { afterEach, describe, expect, it } from "vite-plus/test"; | ||
| import { taskScopeCommand } from "./taskScope.ts"; | ||
|
|
||
| const execFile = NodeUtil.promisify(NodeChildProcess.execFile); | ||
| const directories: string[] = []; | ||
|
|
||
| afterEach(async () => { | ||
| await Promise.all( | ||
| directories.splice(0).map((dir) => NodeFSP.rm(dir, { recursive: true, force: true })), | ||
| ); | ||
| }); | ||
|
|
||
| async function fixture(busExit = 0, startExit = 0) { | ||
| const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-task-scope-")); | ||
| directories.push(directory); | ||
| const log = NodePath.join(directory, "calls"); | ||
| for (const [name, body] of Object.entries({ | ||
| timeout: 'shift; exec "$@"', | ||
| busctl: `printf 'busctl %s\\n' "$*" >> "$CALLS"; exit ${busExit}`, | ||
| systemctl: `printf 'systemctl %s\\n' "$*" >> "$CALLS"; exit ${startExit}`, | ||
| })) { | ||
| await NodeFSP.writeFile(NodePath.join(directory, name), `#!/bin/sh\n${body}\n`, { | ||
| mode: 0o755, | ||
| }); | ||
| } | ||
| return { directory, log, env: { PATH: directory, CALLS: log, VALUE: "inherited value" } }; | ||
| } | ||
|
|
||
| async function launch(f: Awaited<ReturnType<typeof fixture>>, script: string, args: string[] = []) { | ||
| const command = taskScopeCommand("/bin/sh", ["-c", script, "workload", ...args], "linux"); | ||
| return execFile(command.command, command.args, { cwd: f.directory, env: f.env }); | ||
| } | ||
|
|
||
| describe("taskScopeCommand", () => { | ||
| it.each(["darwin", "win32", "freebsd"] as const)("leaves %s launches unchanged", (platform) => { | ||
| expect(taskScopeCommand("agent", ["--arg", "a b"], platform)).toEqual({ | ||
| command: "agent", | ||
| args: ["--arg", "a b"], | ||
| }); | ||
| }); | ||
|
|
||
| it.skipIf(HostProcessPlatform.defaultValue() !== "linux")( | ||
| "waits for scope startup before exec and preserves PID, cwd, environment and arguments", | ||
| async () => { | ||
| const f = await fixture(); | ||
| const args = ["a b", "$(touch should-not-exist)", "$HOME", "", "--flag"]; | ||
| const result = await launch( | ||
| f, | ||
| 'printf "workload %s\\n" "$$" >> "$CALLS"; printf "%s\\n" "$PWD" "$VALUE" "$@"', | ||
| args, | ||
| ); | ||
| expect(result.stdout).toBe([f.directory, "inherited value", ...args, ""].join("\n")); | ||
| expect(result.stderr).toBe(""); | ||
| const calls = (await NodeFSP.readFile(f.log, "utf8")).trim().split("\n"); | ||
| const pid = calls[2]?.split(" ")[1]; | ||
| const unit = calls[0]?.match(/t3code-task-[0-9a-f-]+\.scope/)?.[0]; | ||
| expect(unit).toBeDefined(); | ||
| expect(calls[0]).toBe( | ||
| `busctl --user --timeout=2s call org.freedesktop.systemd1 /org/freedesktop/systemd1 org.freedesktop.systemd1.Manager StartTransientUnit ssa(sv)a(sa(sv)) ${unit} fail 3 PIDs au 1 ${pid} Slice s app.slice CollectMode s inactive-or-failed 0`, | ||
| ); | ||
| expect(calls[1]).toBe(`systemctl --user --no-ask-password start ${unit}`); | ||
| expect(await NodeFSP.readdir(f.directory)).not.toContain("should-not-exist"); | ||
| }, | ||
| ); | ||
|
|
||
| it.skipIf(HostProcessPlatform.defaultValue() !== "linux").each([ | ||
| [1, 0], | ||
| [0, 1], | ||
| ])("falls back when systemd setup fails (%s, %s)", async (busExit, startExit) => { | ||
| const f = await fixture(busExit, startExit); | ||
| const result = await launch(f, 'printf "ran\\n" >> "$CALLS"; printf ok'); | ||
| expect(result.stdout).toBe("ok"); | ||
| expect(result.stderr).toBe(""); | ||
| const calls = await NodeFSP.readFile(f.log, "utf8"); | ||
| expect(calls.match(/^ran$/gm)).toHaveLength(1); | ||
| if (busExit !== 0) expect(calls).not.toContain("systemctl"); | ||
| }); | ||
|
|
||
| it.skipIf(HostProcessPlatform.defaultValue() !== "linux")( | ||
| "falls back without systemd tools", | ||
| async () => { | ||
| const f = await fixture(); | ||
| await NodeFSP.unlink(NodePath.join(f.directory, "busctl")); | ||
| expect((await launch(f, "printf ok")).stdout).toBe("ok"); | ||
| await NodeFSP.unlink(NodePath.join(f.directory, "timeout")); | ||
| expect((await launch(f, "printf ok")).stdout).toBe("ok"); | ||
| }, | ||
| ); | ||
|
|
||
| it.skipIf(HostProcessPlatform.defaultValue() !== "linux")( | ||
| "does not retry a failing workload and preserves its exit code and stderr", | ||
| async () => { | ||
| const f = await fixture(); | ||
| await expect( | ||
| launch(f, 'printf "ran\\n" >> "$CALLS"; printf failure >&2; exit 42'), | ||
| ).rejects.toMatchObject({ code: 42, stderr: "failure" }); | ||
| expect((await NodeFSP.readFile(f.log, "utf8")).match(/^ran$/gm)).toHaveLength(1); | ||
| }, | ||
| ); | ||
|
|
||
| it.skipIf(HostProcessPlatform.defaultValue() !== "linux")("preserves stdin", async () => { | ||
| const f = await fixture(); | ||
| const command = taskScopeCommand("/bin/cat", [], "linux"); | ||
| const child = NodeChildProcess.spawn(command.command, command.args, { env: f.env }); | ||
| const output: Buffer[] = []; | ||
| child.stdout.on("data", (chunk: Buffer) => output.push(chunk)); | ||
| const closed = new Promise<number | null>((resolve, reject) => { | ||
| child.once("error", reject); | ||
| child.once("close", resolve); | ||
| }); | ||
| child.stdin.end("input\n"); | ||
| expect(await closed).toBe(0); | ||
| expect(Buffer.concat(output).toString()).toBe("input\n"); | ||
| }); | ||
| it.skipIf(HostProcessPlatform.defaultValue() !== "linux")( | ||
| "preserves termination signals after exec", | ||
| async () => { | ||
| const f = await fixture(); | ||
| const command = taskScopeCommand("/bin/sh", ["-c", "printf ready; exec /bin/cat"], "linux"); | ||
| const child = NodeChildProcess.spawn(command.command, command.args, { env: f.env }); | ||
| const closed = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>( | ||
| (resolve, reject) => { | ||
| child.once("error", reject); | ||
| child.once("close", (code, signal) => resolve({ code, signal })); | ||
| }, | ||
| ); | ||
| await new Promise<void>((resolve, reject) => { | ||
| child.once("error", reject); | ||
| child.stdout.once("data", () => resolve()); | ||
| }); | ||
| child.kill("SIGTERM"); | ||
| expect(await closed).toEqual({ code: null, signal: "SIGTERM" }); | ||
| }, | ||
| ); | ||
| it.skipIf(HostProcessPlatform.defaultValue() !== "linux")( | ||
| "bounds a hung user-manager setup", | ||
| async () => { | ||
| const f = await fixture(); | ||
| await NodeFSP.copyFile("/usr/bin/timeout", NodePath.join(f.directory, "timeout")); | ||
| await NodeFSP.writeFile( | ||
| NodePath.join(f.directory, "busctl"), | ||
| "#!/bin/sh\nexec /bin/sleep 30\n", | ||
| ); | ||
| expect((await launch(f, "printf fallback")).stdout).toBe("fallback"); | ||
| }, | ||
| 6000, | ||
| ); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| // @effect-diagnostics nodeBuiltinImport:off -- Unique scope names are generated at the process boundary. | ||
| import * as NodeCrypto from "node:crypto"; | ||
|
|
||
| import { HostProcessPlatform } from "@t3tools/shared/hostProcess"; | ||
| import { resolveSpawnCommand } from "@t3tools/shared/shell"; | ||
| import * as Effect from "effect/Effect"; | ||
|
|
||
| // Move the launcher before exec, so even the workload's first children inherit | ||
| // its scope. A separate helper performs the D-Bus call and waits for the start | ||
| // job. Failure (including missing tools/user bus) simply leaves the launcher in | ||
| // its original cgroup. Never retry the workload itself: a nonzero exit may have | ||
| // already performed side effects. exec preserves the PID, stdio and signals. | ||
| const SCOPE_LAUNCHER = ` | ||
| timeout 3s /bin/sh -c ' | ||
| busctl --user --timeout=2s call org.freedesktop.systemd1 \\ | ||
| /org/freedesktop/systemd1 org.freedesktop.systemd1.Manager \\ | ||
| StartTransientUnit "ssa(sv)a(sa(sv))" "$1" fail 3 \\ | ||
| PIDs au 1 "$2" Slice s app.slice CollectMode s inactive-or-failed 0 && | ||
| systemctl --user --no-ask-password start "$1" | ||
| ' t3code-scope "$1" "$$" </dev/null >/dev/null 2>&1 | ||
| shift | ||
| exec "$@" | ||
| `; | ||
|
|
||
| /** Only long-lived local workload roots belong here, not utility commands. */ | ||
| export function taskScopeCommand( | ||
| command: string, | ||
| args: ReadonlyArray<string>, | ||
| platform: NodeJS.Platform, | ||
| ) { | ||
| return platform === "linux" | ||
| ? { | ||
| command: "/bin/sh", | ||
| args: [ | ||
| "-c", | ||
| SCOPE_LAUNCHER, | ||
| "t3code-task", | ||
| `t3code-task-${NodeCrypto.randomUUID()}.scope`, | ||
| command, | ||
| ...args, | ||
| ], | ||
| } | ||
| : { command, args }; | ||
| } | ||
|
|
||
| export const resolveTaskSpawnCommand = Effect.fn("resolveTaskSpawnCommand")(function* ( | ||
| ...input: Parameters<typeof resolveSpawnCommand> | ||
| ) { | ||
| const resolved = yield* resolveSpawnCommand(...input); | ||
| const platform = yield* HostProcessPlatform; | ||
| return { ...resolved, ...taskScopeCommand(resolved.command, resolved.args, platform) }; | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟠 High
acp/AcpSessionRuntime.ts:463With
extendEnv: falseand a restrictedPATH, a valid absolute ACP command falls back to the unwrapped process whenresolveTaskSpawnCommandcannot findtimeout,busctl, orsystemctl, leaving the workload in T3's cgroup and unprotected from the intended OOM isolation. Keep the ACP-specificresolveSpawnCommandpath, or otherwise resolve these wrapper dependencies independently of the agent-suppliedPATH.🤖 Copy this AI Prompt to have your agent fix this: