Skip to content
TypeScript

fix(server): agents yield CPU, tasks, and reclaim to the server under pressure (#27176)

Julius Marminged7b6cf788402
diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts
index fca51dcac1e..5491328a304 100644
--- a/apps/server/src/cloud/bootService.test.ts
+++ b/apps/server/src/cloud/bootService.test.ts
@@ -48,6 +48,19 @@ it("reads the served T3 home back out of a rendered unit or plist", () => {
expect(BootService.bootServiceBaseDirOf("[Service]\nExecStart=/x\n")).toBeUndefined();
});
+it("protects the server unit from agents under CPU and memory pressure", () => {
+ const unit = BootService.renderBootServiceUnit({
+ program: ["/home/theo/.t3/runtime/versions/1.2.3/t3", "__service-launcher"],
+ baseDir: "/home/theo/.t3",
+ logPath: "/home/theo/.t3/userdata/logs/boot-service.log",
+ unitPath: "/home/theo/.config/systemd/user/t3code.service",
+ });
+ const service = unit.slice(unit.indexOf("[Service]"), unit.indexOf("[Install]"));
+ for (const line of ["CPUWeight=1000", "IOWeight=1000", "MemoryLow=1536M", "OOMPolicy=continue"]) {
+ expect(service.split("\n")).toContain(line);
+ }
+});
+
it.each([
["a unit", '/home/theo/T3 "Data"/100%\\x', BootService.renderBootServiceUnit],
[
diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts
index 15b3b16a7bc..5206992f269 100644
--- a/apps/server/src/cloud/bootService.ts
+++ b/apps/server/src/cloud/bootService.ts
@@ -110,9 +110,12 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
"OOMPolicy=continue",
"Restart=always",
"RestartSec=5",
- // Weights favor the server over the sibling agents slice during CPU or disk saturation.
+ // Weights favor the server over the sibling agents slice; IOWeight needs a delegated io controller.
"CPUWeight=1000",
"IOWeight=1000",
+ // Reclaim takes the agents' unprotected pages first. The kernel caps this at the
+ // protection of user.slice and [email protected], which only root can grant.
+ "MemoryLow=1536M",
// systemd-oomd ignores this preference when the watched cgroup is root-owned, as user-1000.slice usually is.
"ManagedOOMPreference=avoid",
`StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
diff --git a/apps/server/src/process/agentScope.test.ts b/apps/server/src/process/agentScope.test.ts
index 94ca314ac1f..286452a5c57 100644
--- a/apps/server/src/process/agentScope.test.ts
+++ b/apps/server/src/process/agentScope.test.ts
@@ -245,6 +245,34 @@ describe("AgentScope service", () => {
),
);
+ it.effect("caps agent memory and yields CPU, disk, and tasks to the server", () =>
+ withFakeSystemd(({ scope, calls }) =>
+ Effect.gen(function* () {
+ yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" });
+ const setProperties = calls.filter(([, verb]) => verb === "set-property");
+ expect(setProperties).toEqual([
+ [
+ "--user",
+ "set-property",
+ "--runtime",
+ "app-t3code-agents.slice",
+ expect.stringMatching(/^MemoryHigh=\d+$/),
+ expect.stringMatching(/^MemoryMax=\d+$/),
+ ],
+ [
+ "--user",
+ "set-property",
+ "--runtime",
+ "app-t3code.slice",
+ "CPUWeight=10",
+ "IOWeight=10",
+ "TasksMax=25%",
+ ],
+ ]);
+ }),
+ ),
+ );
+
it.effect("stops agents a killed server left before the first launch", () =>
withFakeSystemd(({ scope, units, calls, stateDir }) =>
Effect.gen(function* () {
diff --git a/apps/server/src/process/agentScope.ts b/apps/server/src/process/agentScope.ts
index cc6d3a04121..c72e4eed88a 100644
--- a/apps/server/src/process/agentScope.ts
+++ b/apps/server/src/process/agentScope.ts
@@ -19,6 +19,12 @@ import * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
const AGENT_SLICE = "app-t3code-agents.slice";
+// Owns every agent slice and competes with the server's unit or scope under app.slice.
+const AGENTS_PARENT_SLICE = "app-t3code.slice";
+// Low weights yield CPU and disk to the server under contention, where the user manager
+// has those controllers: current systemd delegates cpu, rarely io. TasksMax keeps agents
+// below logind's 33% per-user task limit, leaving forks for the server.
+const AGENTS_PARENT_PROPERTIES = ["CPUWeight=10", "IOWeight=10", "TasksMax=25%"];
export function ownedAgentSlice(stateDir: string): string {
const hash = NodeCrypto.createHash("sha256").update(stateDir).digest("hex").slice(0, 12);
@@ -173,20 +179,28 @@ export const make = Effect.gen(function* () {
yield* Effect.logInfo("Agent scopes are off: no systemd user manager");
return undefined;
}
+ const setProperties = Effect.fn("agentScope.setProperties")(function* (
+ slice: string,
+ properties: ReadonlyArray<string>,
+ ) {
+ const result = yield* run(systemctl, [
+ "--user",
+ "set-property",
+ "--runtime",
+ slice,
+ ...properties,
+ ]);
+ if (result._tag === "None" || result.value.code !== 0) {
+ yield* Effect.logWarning("Could not set resource limits on an agents slice", {
+ slice,
+ properties,
+ stderr: result._tag === "Some" ? result.value.stderr.trim() : 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,
- });
- }
+ yield* setProperties(AGENT_SLICE, [`MemoryHigh=${limits.high}`, `MemoryMax=${limits.max}`]);
+ yield* setProperties(AGENTS_PARENT_SLICE, AGENTS_PARENT_PROPERTIES);
yield* Effect.logInfo("Agent scopes are on", {
slice: AGENT_SLICE,
...limits,