pi-durable-subagents 1.6.1 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/README.md +19 -0
- package/dist/agent/main/schema.js +9 -2
- package/dist/agent/main/tool.js +2 -2
- package/dist/agent/main.js +1 -1
- package/dist/cli/doctor.js +3 -1
- package/dist/compat/spec.js +21 -2
- package/dist/orchestrator/config.js +20 -2
- package/dist/orchestrator/executor/command.js +1 -0
- package/dist/orchestrator/executor/index.js +128 -15
- package/dist/orchestrator/executor/observe.js +40 -2
- package/dist/orchestrator/executor/resources.js +144 -0
- package/dist/orchestrator/snapshot.js +7 -1
- package/dist/platform/command.js +27 -4
- package/dist/platform/containment.js +4 -2
- package/dist/platform/job.js +150 -12
- package/dist/platform/limits.js +205 -0
- package/dist/platform/proctable.js +35 -13
- package/dist/platform/windows.js +10 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.7.0
|
|
4
|
+
|
|
5
|
+
- **Per-subagent process-tree resource limits (#13)**: Cap each subagent (agent calls and command calls) across its entire process tree via global `config.json` `limits` (live-reloaded) or per-call / run-level `limits` (`{ memoryMb?, maxProcesses?, cpuPercent?, graceMs?, strict? }`, merged field-by-field):
|
|
6
|
+
- **Layer 1 (all platforms — process-tree monitor & circuit breaker)**: Collects RSS with zero extra syscalls/subprocesses across Linux (`/proc/<pid>/stat`), macOS (`ps -o rss=`) and Windows (`Win32_Process.WorkingSetSize`); aggregates whole-tree RSS, process count (excluding internal command harnesses) and CPU % with snapshot `capturedAt` deduplication; waits `graceMs` (default 5000 ms) before appending durable `resource-limit` / `command-resource-limit` evidence with top-3 memory processes, fencing the process tree, and sealing `failed` deterministically without retrying or rerunning (`rerun: true` never re-executes).
|
|
7
|
+
- **Layer 2 (OS kernel hard limits & `strict` mode)**: On Linux with delegated unified cgroup v2, wraps agent and command launches in transient `systemd-run --user --scope` units (`MemoryMax`, `MemorySwapMax=0`, `CPUQuota`) and detects `Result=oom-kill` (with `reset-failed` cleanup); on Windows, extends `DsaJob.exe` (`DSAJOB2`) with `JOB_OBJECT_LIMIT_JOB_MEMORY` (+64 MiB wrapper headroom), `JOB_OBJECT_LIMIT_ACTIVE_PROCESS`, `JobObjectCpuRateControlInformation` hard cap and I/O Completion Port `JOB_OBJECT_MSG_JOB_MEMORY_LIMIT` detection. Hosts without kernel enforcement transparently fall back to Layer 1 unless `strict: true` is set, which fails the call before launch.
|
|
8
|
+
- **Observability**: Checkpoints live/peak memory, process count and CPU % onto agent `time` entries (surfaced in `status`, `compactWorkflow` and `statusBrief.memory`) and reports local kernel limit capabilities in `pi-durable-subagents doctor`.
|
|
9
|
+
|
|
3
10
|
## 1.6.1
|
|
4
11
|
|
|
5
12
|
- **Standalone `pi` binary safety (#11, #7)**: When `pi` runs as a standalone compiled Bun/SEA binary (`process.execPath` points to `pi` rather than `node`), `launchOrchestrator`, `install-service`, Windows shim unwrapping and `npmCommand` now resolve a real Node.js runtime (`DSA_NODE_BIN` -> verified Node `process.execPath` -> `node`/`nodejs` on `PATH`, preferring `.exe`/`.com` on Windows and wrapping `.cmd` shims through `cmd.exe`), refuse any runtime resolving to `pi` while keeping multi-call shims (`mise`/`volta`/`asdf`) working, and add a hard `DSA_ORCHESTRATOR_LAUNCH` self-spawn guard inside the extension so a misconfigured launch exits immediately instead of spawning recursive headless `pi` sessions.
|
package/README.md
CHANGED
|
@@ -1283,12 +1283,31 @@ State lives in `~/.pi/durable-subagents`; set `DSA_HOME` to move it.
|
|
|
1283
1283
|
}
|
|
1284
1284
|
},
|
|
1285
1285
|
"memory": { "reserveMb": 2048, "perChildMb": 300 },
|
|
1286
|
+
"limits": { "memoryMb": 4096, "maxProcesses": 64, "cpuPercent": 400, "graceMs": 5000, "strict": false },
|
|
1286
1287
|
"writerLock": "queue",
|
|
1287
1288
|
"askRequireDecision": false,
|
|
1288
1289
|
"exactCapture": true
|
|
1289
1290
|
}
|
|
1290
1291
|
```
|
|
1291
1292
|
|
|
1293
|
+
- **Per-subagent resource limits (`limits`):** caps each call's entire process
|
|
1294
|
+
tree (the subagent plus every tool/build/test child it spawns). Set global
|
|
1295
|
+
defaults in `config.json` (`limits`, live-reloaded) and override any field
|
|
1296
|
+
per call via `limits: { memoryMb?, maxProcesses?, cpuPercent?, graceMs?, strict? }`
|
|
1297
|
+
on agent calls, command calls, or `tasks`/`chain` defaults:
|
|
1298
|
+
- `memoryMb`: max total resident memory (RSS / WorkingSet) in MiB.
|
|
1299
|
+
- `maxProcesses`: max concurrent processes in the call's tree.
|
|
1300
|
+
- `cpuPercent`: max CPU usage across the tree (% of one core; e.g. `200` = 2 cores).
|
|
1301
|
+
- `graceMs`: consecutive ms a limit may stay exceeded before fencing (default `5000`).
|
|
1302
|
+
- `strict`: when `true`, refuse to start unless OS kernel hard limits cover the requested caps.
|
|
1303
|
+
- **Two-layer enforcement:** Layer 1 monitors the process tree on Linux, macOS
|
|
1304
|
+
and Windows, fences the whole tree on a sustained breach, and seals the call
|
|
1305
|
+
`failed` with the peak usage and top processes (never retried as a loss).
|
|
1306
|
+
Layer 2 automatically adds OS kernel hard limits where available — Linux
|
|
1307
|
+
transient user scopes via `systemd-run --user --scope` under delegated
|
|
1308
|
+
unified cgroup v2 (`MemoryMax` + `CPUQuota`), and Windows Job Object limits
|
|
1309
|
+
(`JobMemoryLimit`, `ActiveProcessLimit`, `CpuRateControl`) for command calls.
|
|
1310
|
+
Run `pi-durable-subagents doctor` to see which backend is active on your host.
|
|
1292
1311
|
- **Pools:** a model can name a pool (the `model` of a call, a `run --spec`
|
|
1293
1312
|
file or a model send). The first candidate with a free slot is
|
|
1294
1313
|
used, and a candidate that keeps failing is skipped for 10 minutes. The
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// The subagents tool's parameter schema. Kept apart from tool.ts because it needs the optional pi peer
|
|
2
2
|
// package, which the CLI (sharing tool.ts) must not import: it runs from the package directory.
|
|
3
3
|
import { Type } from "@earendil-works/pi-ai";
|
|
4
|
-
const stepsDoc = "Call specs {agent, task, model?, cwd?, timeoutMs?, output?, schema?, gate?, isolation?, context?, budget?, once?, tools?, skills?, writer?, key?} " +
|
|
5
|
-
"or command specs {command, cwd?, timeoutMs?, env?, rerun?, writer?, key?}; " +
|
|
4
|
+
const stepsDoc = "Call specs {agent, task, model?, cwd?, timeoutMs?, output?, schema?, gate?, isolation?, context?, budget?, limits?, once?, tools?, skills?, writer?, key?} " +
|
|
5
|
+
"or command specs {command, cwd?, timeoutMs?, limits?, env?, rerun?, writer?, key?}; " +
|
|
6
6
|
"each call is addressed as '<wid>/<key>', where key is the step's own unique key or else 'tasks:<i>' / 'chain:<i>'.";
|
|
7
7
|
export const parameters = Type.Object({
|
|
8
8
|
action: Type.Optional(Type.Union(["run", "agents", "send", "stop", "revise", "status", "resume", "drain", "restart"].map(v => Type.Literal(v)))),
|
|
@@ -23,6 +23,13 @@ export const parameters = Type.Object({
|
|
|
23
23
|
name: Type.Optional(Type.String()),
|
|
24
24
|
labels: Type.Optional(Type.Record(Type.String(), Type.String(), { description: "run: your labels, e.g. {node, attempt}: at most 32 keys [A-Za-z0-9_.:-]{1,64}, string values of at most 256 characters, 4096 bytes of JSON; part of the request's content (spec_digest), shown by describe and on its events." })),
|
|
25
25
|
timeoutMs: Type.Optional(Type.Number({ description: "Per-call limit on active time in milliseconds (a number; a command call: wall-clock time since it started). Omit unless a hard limit is needed; prefer budgets." })),
|
|
26
|
+
limits: Type.Optional(Type.Object({
|
|
27
|
+
memoryMb: Type.Optional(Type.Number({ exclusiveMinimum: 0, description: "Max resident memory (MiB) across the call's process tree." })),
|
|
28
|
+
maxProcesses: Type.Optional(Type.Integer({ minimum: 1, description: "Max concurrent processes in the call's process tree." })),
|
|
29
|
+
cpuPercent: Type.Optional(Type.Number({ exclusiveMinimum: 0, description: "Max CPU usage across the call's process tree (% of one core, e.g. 200 = 2 cores)." })),
|
|
30
|
+
graceMs: Type.Optional(Type.Number({ minimum: 0, description: "Consecutive ms a limit may be exceeded before fencing (default 5000)." })),
|
|
31
|
+
strict: Type.Optional(Type.Boolean({ description: "Refuse to launch if OS kernel hard limits (Linux cgroup v2 / Windows Job Object) are unavailable." })),
|
|
32
|
+
}, { additionalProperties: false, description: "Per-call process-tree resource limits (overrides config.json limits)." })),
|
|
26
33
|
key: Type.Optional(Type.String({ description: "A single agent/task run: the call's key. status with wid: that call's full result." })),
|
|
27
34
|
tail: Type.Optional(Type.Integer({ minimum: 1, description: "status with wid: the last N lines of each call's result (unclipped, at most 4000 characters per call)." })),
|
|
28
35
|
grep: Type.Optional(Type.String({ description: "status with wid: only the lines of each call's result matching this case-sensitive JS regular expression, run in-process: avoid nested quantifiers such as (a+)+; it tests the first 2000 characters of a line and the last 5000 lines (with tail: grep first, then the last N)." })),
|
package/dist/agent/main/tool.js
CHANGED
|
@@ -9,9 +9,9 @@ import { validateCallSpec } from "../../compat/spec.js";
|
|
|
9
9
|
import { compileFanout } from "../../compat/fanout.js";
|
|
10
10
|
import { checkLabels } from "../../events/labels.js";
|
|
11
11
|
/** Call fields a tasks/chain run applies to every step that does not set its own. */
|
|
12
|
-
export const stepDefaults = ["agent", "model", "timeoutMs", "budget", "isolation", "context", "tools", "skills", "once", "writer", "env", "rerun"];
|
|
12
|
+
export const stepDefaults = ["agent", "model", "timeoutMs", "budget", "limits", "isolation", "context", "tools", "skills", "once", "writer", "env", "rerun"];
|
|
13
13
|
/** The run-level defaults a command step takes; agent steps take the others (env and rerun belong to command calls). */
|
|
14
|
-
const commandDefaults = new Set(["timeoutMs", "writer", "env", "rerun"]), agentOnly = new Set(["env", "rerun"]);
|
|
14
|
+
const commandDefaults = new Set(["timeoutMs", "limits", "writer", "env", "rerun"]), agentOnly = new Set(["env", "rerun"]);
|
|
15
15
|
/** The run-level defaults that apply to one step: a command step skips agent-only fields, an agent step skips env/rerun. */
|
|
16
16
|
function defaultsFor(step, defaults) {
|
|
17
17
|
const command = step.command !== undefined;
|
package/dist/agent/main.js
CHANGED
|
@@ -511,7 +511,7 @@ export function registerMain(pi, ui) {
|
|
|
511
511
|
pi.registerTool(defineTool({
|
|
512
512
|
name: "subagents", label: "Subagents", description: [
|
|
513
513
|
"Durable asynchronous subagents; run returns {wid} when created (or {submitted:{rid}} while pending). A finished workflow (its notice carries every agent's result) or a question wakes you, so after starting work end your turn: never poll with sleep or repeated status. Crash recovery resumes sessions, not external side effects. Background helper processes (orchestrator, evaluator) exit by themselves about 10 s after all work ends: never kill processes or delete files to 'clean up'. When the user quits pi, this session's running workflows pause (nothing is spent); resume continues them.",
|
|
514
|
-
"run (action optional for exactly one launch form): agent+task; command (a command call); tasks:[call specs] parallel; chain:[call specs] sequential ({previous}); workflow:'./script.js' or source (runs.run(key,spec), runs.all([...]), emit(value), args, runs.input(name)). Optional name, cwd, usageBudget, maxCalls, inputs, labels. With tasks/chain, top-level agent (without task), model, timeoutMs, budget, isolation, context, tools, skills, once, writer are defaults for every step (a step's own value wins); a workflow/source script sets them per runs.run call. timeoutMs is milliseconds of active time (a number); omit it unless a hard limit is needed. A command call {command:[argv] or 'sh string', cwd?, timeoutMs? (wall-clock), env?, rerun?, writer?} runs a process instead of an agent: no model, slot or tokens; it keeps running across orchestrator restarts and a quit pi, and wakes you like any call; result ok on exit 0 else failed, data {exitCode, signal, durationMs}, output = last 16 KiB of stdout+stderr; only stop controls it. Run-level env/rerun apply to command steps, agent-only defaults skip them; in a chain an agent step after a command step gets its output as {previous}. Explicit unknown agents are rejected BEFORE creation, with available names; unknown script agents fail only their call.",
|
|
514
|
+
"run (action optional for exactly one launch form): agent+task; command (a command call); tasks:[call specs] parallel; chain:[call specs] sequential ({previous}); workflow:'./script.js' or source (runs.run(key,spec), runs.all([...]), emit(value), args, runs.input(name)). Optional name, cwd, usageBudget, maxCalls, inputs, labels. With tasks/chain, top-level agent (without task), model, timeoutMs, budget, limits, isolation, context, tools, skills, once, writer are defaults for every step (a step's own value wins); a workflow/source script sets them per runs.run call. timeoutMs is milliseconds of active time (a number); omit it unless a hard limit is needed. limits:{memoryMb?, maxProcesses?, cpuPercent?, graceMs?, strict?} caps each call's process tree (merges over config.json limits; fences and seals failed without retrying on sustained breach, plus OS cgroup v2 / Windows Job Object hard limits when available). A command call {command:[argv] or 'sh string', cwd?, timeoutMs? (wall-clock), limits?, env?, rerun?, writer?} runs a process instead of an agent: no model, slot or tokens; it keeps running across orchestrator restarts and a quit pi, and wakes you like any call; result ok on exit 0 else failed, data {exitCode, signal, durationMs}, output = last 16 KiB of stdout+stderr; only stop controls it. Run-level env/rerun apply to command steps, agent-only defaults skip them; in a chain an agent step after a command step gets its output as {previous}. Explicit unknown agents are rejected BEFORE creation, with available names; unknown script agents fail only their call.",
|
|
515
515
|
"agents: list names, descriptions, default models and source for this cwd; use these names for run.",
|
|
516
516
|
"send to:'<wid>/<key>' (bare '<wid>' only for a single-call workflow): steer on a running call delivers at the next safe point (receipt in status/UI); a steer to a call waiting on its question interrupts the question and the subagent usually asks again — use answer to answer it; sealed → finished:<status> — use kind 'follow-up'. notify tells a call a decision without disturbing it; the reply's delivery says how: steered (running: it gets the note at its next safe point), held-until-answer (waiting on its question: never interrupts it, delivered after the answer) or noted (not running: nothing starts; the note is recorded and the call's next follow-up opens with every pending note; status shows notesPending). to may list several calls for steer, notify, follow-up and model: one request per call, each decided on its own, one result line per target (request:<id> sends <id>:1...<id>:n; a retry with the same list is safe). follow-up continues a sealed call as generation g+1 (reply generation) or queues after a running turn (reply delivery forwarded; if that turn ends without taking it, it opens g+1); follow-up model:'provider/id' or a pool name runs that generation on it. answer: give the qid (or just the call, or nothing when one question is open); to and rev are filled in. A question that needs the user's decision goes to the user; if you answer one yourself, tell the user what you chose. model ('provider/id' or a pool name — its first model not used up): a running call switches at its next provider request; an asking, hibernated or queued call launches on it when it runs again; the reply's model/effect (next-request|next-execution|next-generation) says which. status model = model actually used by the last request; switching = requested, not used yet; switchFailed = refused. A provider content refusal (ToS/usage policy) fails the call at once, not retried. Unknown targets list valid addresses. replaces:[rid] supersedes an earlier send.",
|
|
517
517
|
"stop target:<wid|<wid>/<key>> is terminal stopped (usage and partial edits kept); a sealed call → already-sealed:<status>, a finished workflow → terminal:<status>. drain holds existing workflows reversibly (new runs unaffected); resume [wid] releases held workflows. restart (after an update) replaces the orchestrator with the installed version: refused with busy:<running executions> while any runs. Never force without the user's explicit approval: show the user the refusal's list first, then supply force:'<token>' and reason. Subagents cannot force; hibernated askers and queued calls do not block it. Never kill the orchestrator process. Commands that need the machine (benchmarks, timing) take a lease: tell the subagent to run them as `pi-durable-subagents hold machine [--shared] -- <command>` (FIFO; `hold <name> --slots N` admits N at a time; status lists lease holders and waiters). status: without wid, what runs (with its run labels, clipped), asks (with its answer address; hibernated:true holds no slot) or failed, writerWait: a call queued for its git worktree's writer lock (one call whose tools include edit/write runs per worktree; spec writer:false or isolation:'worktree' opts out), sharedWorktree names calls sharing observed edit/write roots (reminder), lease: a call holding or waiting for a resource lease, queued: why a queued call does not start (orchestrator starting while it recovers after a start, a used-up provider, a writer lock, full providers; absent when not known), finished workflows one line each, provider slots held/limit, the config in effect and providers whose usage window is used up (avoided until a probe finds them answering again), and the orchestrator version (with ', starting <age>' while it recovers; versionNote when it differs from the loaded one); wid: one workflow, outputs clipped; wid+tail:N: the last N lines of each call's result, wid+grep:'<regex>': only its matching lines (a JS regex run in-process: avoid nested quantifiers like (a+)+; first 2000 chars of a line, last 5000 lines; both: grep, then tail; at most 4000 chars per call); wid+key: one call's full result; full:true: everything. A run reply names calls already queued behind a writer lock (writerWait). A run's rid from {submitted:{rid}} works wherever a wid is expected. revise wid + workflow/source/args starts a revision.",
|
package/dist/cli/doctor.js
CHANGED
|
@@ -8,6 +8,7 @@ import { readJournalSnapshot } from "../kernel/journal.js";
|
|
|
8
8
|
import { reduceLifecycle } from "../kernel/lifecycle.js";
|
|
9
9
|
import { scanInbox } from "../kernel/mailbox.js";
|
|
10
10
|
import { OsLock } from "../platform/lock.js";
|
|
11
|
+
import { describeKernelLimits, probeKernelLimits } from "../platform/limits.js";
|
|
11
12
|
import { journalPath, orchInbox, orchLedger, orchLock } from "../paths.js";
|
|
12
13
|
import { runningStats, snapshotFromEntries } from "../orchestrator/snapshot.js";
|
|
13
14
|
import { emptyLedger, foldLedger } from "../orchestrator/ledger.js";
|
|
@@ -52,7 +53,7 @@ export async function doctor(home, env = process.env, now = Date.now()) {
|
|
|
52
53
|
const ledger = readJournalSnapshot(orchLedger(home));
|
|
53
54
|
const pruned = new Set(ledger.filter(e => e.type === "pruned").map(e => String(e.wid)));
|
|
54
55
|
const report = { home, bytes: await diskUsage(home), workflows: {}, ledger: { entries: ledger.length, bytes: await diskUsage(orchLedger(home)) },
|
|
55
|
-
largestJournals: [], parked: [], attention: [], fenceFailed: [], orphanStaging: [], tmpFiles: [], orchestrator: await lockHeld(home), service: "unavailable", findings: [], ...runningStats(home) };
|
|
56
|
+
largestJournals: [], parked: [], attention: [], fenceFailed: [], orphanStaging: [], tmpFiles: [], orchestrator: await lockHeld(home), service: "unavailable", resourceLimits: describeKernelLimits(probeKernelLimits({ env })), findings: [], ...runningStats(home) };
|
|
56
57
|
const last = foldLedger(emptyLedger(), ledger), o = last.orchestrator;
|
|
57
58
|
if (o && o.pi !== undefined)
|
|
58
59
|
report.pi = o.pi;
|
|
@@ -164,6 +165,7 @@ export function renderDoctor(r) {
|
|
|
164
165
|
`orchestrator: ${r.orchestrator === "running" ? "running (holds the lock)" : r.orchestrator}${r.lastExit ? `; ${exitLine(r.lastExit)}` : ""}${r.orchestratorStats ? `; ${statsLine(r.orchestratorStats)}` : ""}`,
|
|
165
166
|
...(r.pi !== undefined ? [`pi: ${r.pi ?? "not found (subagents launch \`pi\` from PATH; set DSA_PI_BIN)"}`] : []),
|
|
166
167
|
`service: ${r.service}`,
|
|
168
|
+
`resource limits: ${r.resourceLimits}`,
|
|
167
169
|
...(r.findings.length ? [`${r.findings.length} actionable finding(s):`, ...r.findings.flatMap(f => [` ${f.kind}: ${f.detail}`, ` ${f.command}`])] : ["nothing actionable"]),
|
|
168
170
|
].join("\n");
|
|
169
171
|
}
|
package/dist/compat/spec.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { schemaProblems } from "../agent/child/schema.js";
|
|
2
|
-
const fields = new Set(["agent", "task", "model", "cwd", "timeoutMs", "output", "schema", "gate", "isolation", "context", "budget", "once", "tools", "skills", "key", "writer", "command", "env", "rerun"]);
|
|
2
|
+
const fields = new Set(["agent", "task", "model", "cwd", "timeoutMs", "output", "schema", "gate", "isolation", "context", "budget", "once", "tools", "skills", "key", "writer", "command", "env", "rerun", "limits"]);
|
|
3
3
|
/** Fields a command call takes; every other known field belongs to agent calls. */
|
|
4
|
-
export const COMMAND_FIELDS = ["command", "cwd", "timeoutMs", "env", "rerun", "writer", "key"];
|
|
4
|
+
export const COMMAND_FIELDS = ["command", "cwd", "timeoutMs", "env", "rerun", "writer", "key", "limits"];
|
|
5
5
|
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
6
6
|
const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
7
7
|
const positive = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
|
|
@@ -36,6 +36,21 @@ function budget(value) {
|
|
|
36
36
|
errors.push(`budget.${k} must be a positive number${got(value[k])}`);
|
|
37
37
|
return errors;
|
|
38
38
|
}
|
|
39
|
+
function limits(value) {
|
|
40
|
+
if (!isObject(value))
|
|
41
|
+
return ["limits must be an object {memoryMb?, maxProcesses?, cpuPercent?, graceMs?, strict?}"];
|
|
42
|
+
const errors = unknown(value, ["memoryMb", "maxProcesses", "cpuPercent", "graceMs", "strict"], "limits.");
|
|
43
|
+
for (const k of ["memoryMb", "cpuPercent"])
|
|
44
|
+
if (value[k] !== undefined && !positive(value[k]))
|
|
45
|
+
errors.push(`limits.${k} must be a positive number${got(value[k])}`);
|
|
46
|
+
if (value.maxProcesses !== undefined && (!Number.isSafeInteger(value.maxProcesses) || Number(value.maxProcesses) < 1))
|
|
47
|
+
errors.push(`limits.maxProcesses must be a positive integer${got(value.maxProcesses)}`);
|
|
48
|
+
if (value.graceMs !== undefined && !(typeof value.graceMs === "number" && Number.isFinite(value.graceMs) && value.graceMs >= 0))
|
|
49
|
+
errors.push(`limits.graceMs must be a nonnegative number${got(value.graceMs)}`);
|
|
50
|
+
if (value.strict !== undefined && typeof value.strict !== "boolean")
|
|
51
|
+
errors.push(`limits.strict must be a boolean${got(value.strict)}`);
|
|
52
|
+
return errors;
|
|
53
|
+
}
|
|
39
54
|
/** P34, P24, T2/T3/T4: Validate a call spec at submission; `key` is accepted only for tasks/chain steps. Empty = valid. */
|
|
40
55
|
export function validateCallSpec(spec, options = {}) {
|
|
41
56
|
if (!isObject(spec))
|
|
@@ -73,6 +88,8 @@ export function validateCallSpec(spec, options = {}) {
|
|
|
73
88
|
errors.push(`context must be "fresh", "fork" or "exact"${got(s.context)}`);
|
|
74
89
|
if (has("budget"))
|
|
75
90
|
errors.push(...budget(s.budget));
|
|
91
|
+
if (has("limits"))
|
|
92
|
+
errors.push(...limits(s.limits));
|
|
76
93
|
if (has("once") && typeof s.once !== "boolean")
|
|
77
94
|
errors.push(`once must be a boolean${got(s.once)}`);
|
|
78
95
|
if (has("writer") && typeof s.writer !== "boolean")
|
|
@@ -117,6 +134,8 @@ function commandProblems(s, options) {
|
|
|
117
134
|
for (const k of ["rerun", "writer"])
|
|
118
135
|
if (has(k) && typeof s[k] !== "boolean")
|
|
119
136
|
errors.push(`${k} must be a boolean${got(s[k])}`);
|
|
137
|
+
if (has("limits"))
|
|
138
|
+
errors.push(...limits(s.limits));
|
|
120
139
|
if (options.fanout && has("key") && !text(s.key))
|
|
121
140
|
errors.push("key must be a non-empty string");
|
|
122
141
|
return errors;
|
|
@@ -9,7 +9,7 @@ import { readFile } from "node:fs/promises";
|
|
|
9
9
|
import { join } from "node:path";
|
|
10
10
|
import { contentHash } from "../kernel/ids.js";
|
|
11
11
|
/** The keys the orchestrator reads; config.json also holds pi-side settings (ui, onQuit) that it ignores. */
|
|
12
|
-
const KEYS = ["defaultModel", "pools", "providers", "memory", "writerLock", "askRequireDecision", "exactCapture", "k"];
|
|
12
|
+
const KEYS = ["defaultModel", "pools", "providers", "memory", "limits", "writerLock", "askRequireDecision", "exactCapture", "k"];
|
|
13
13
|
const K = ["lossBound", "checkpointMs", "stallMs", "progressMs", "switchTimeoutMs", "idleExitMs", "trackerMs", "hibernateMs", "spawnBudget", "probeMs", "eventRetentionMs", "waitCheckMs", "resumeSpillMs"];
|
|
14
14
|
export const configPath = (home) => join(home, "config.json");
|
|
15
15
|
/** The orchestrator's part of a parsed config.json. */
|
|
@@ -24,7 +24,7 @@ const count = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
|
|
|
24
24
|
export function configProblem(raw) {
|
|
25
25
|
if (!record(raw))
|
|
26
26
|
return "config.json must be a JSON object";
|
|
27
|
-
const { defaultModel, pools, providers, memory, writerLock, askRequireDecision, exactCapture, k } = raw;
|
|
27
|
+
const { defaultModel, pools, providers, memory, limits, writerLock, askRequireDecision, exactCapture, k } = raw;
|
|
28
28
|
if (askRequireDecision !== undefined && typeof askRequireDecision !== "boolean")
|
|
29
29
|
return 'askRequireDecision must be a boolean';
|
|
30
30
|
if (exactCapture !== undefined && typeof exactCapture !== "boolean")
|
|
@@ -94,6 +94,24 @@ export function configProblem(raw) {
|
|
|
94
94
|
if (memory[key] !== undefined && !count(memory[key]))
|
|
95
95
|
return `memory.${key} must be a nonnegative number`;
|
|
96
96
|
}
|
|
97
|
+
if (limits !== undefined) {
|
|
98
|
+
if (!record(limits))
|
|
99
|
+
return "limits must be { memoryMb?, maxProcesses?, cpuPercent?, graceMs?, strict? }";
|
|
100
|
+
for (const key of Object.keys(limits)) {
|
|
101
|
+
if (!["memoryMb", "maxProcesses", "cpuPercent", "graceMs", "strict"].includes(key))
|
|
102
|
+
return `limits.${key} is not a limits key (memoryMb, maxProcesses, cpuPercent, graceMs, strict)`;
|
|
103
|
+
}
|
|
104
|
+
for (const key of ["memoryMb", "cpuPercent"]) {
|
|
105
|
+
if (limits[key] !== undefined && !(count(limits[key]) && Number(limits[key]) > 0))
|
|
106
|
+
return `limits.${key} must be a positive number`;
|
|
107
|
+
}
|
|
108
|
+
if (limits.maxProcesses !== undefined && (!Number.isSafeInteger(limits.maxProcesses) || Number(limits.maxProcesses) < 1))
|
|
109
|
+
return "limits.maxProcesses must be a positive integer";
|
|
110
|
+
if (limits.graceMs !== undefined && !count(limits.graceMs))
|
|
111
|
+
return "limits.graceMs must be a nonnegative number";
|
|
112
|
+
if (limits.strict !== undefined && typeof limits.strict !== "boolean")
|
|
113
|
+
return "limits.strict must be a boolean";
|
|
114
|
+
}
|
|
97
115
|
if (k !== undefined) {
|
|
98
116
|
if (!record(k))
|
|
99
117
|
return "k must map K-parameters to numbers";
|
|
@@ -23,6 +23,7 @@ export const COMMAND_INTENT = "command-intent";
|
|
|
23
23
|
export const COMMAND_STARTED = "command-started";
|
|
24
24
|
export const COMMAND_SPAWN_FAILED = "command-spawn-failed";
|
|
25
25
|
export const COMMAND_TIMEOUT = "command-timeout";
|
|
26
|
+
export const COMMAND_RESOURCE_LIMIT = "command-resource-limit";
|
|
26
27
|
export const COMMAND_WITHDRAWN = "command-withdrawn";
|
|
27
28
|
/** The attempt id (and process tag DSA_EXEC) of attempt `n` of a command call. */
|
|
28
29
|
export const commandId = (call, n) => `command:${call}#${n}`;
|
|
@@ -29,6 +29,7 @@
|
|
|
29
29
|
import { mkdir, open, readdir, readFile, realpath, rm, stat, unlink, writeFile } from "node:fs/promises";
|
|
30
30
|
import { watch } from "node:fs";
|
|
31
31
|
import { setTimeout as delay } from "node:timers/promises";
|
|
32
|
+
import { performance } from "node:perf_hooks";
|
|
32
33
|
import { homedir } from "node:os";
|
|
33
34
|
import { delimiter, dirname, join } from "node:path";
|
|
34
35
|
import { fileURLToPath } from "node:url";
|
|
@@ -66,9 +67,13 @@ import { failedModel, modelFailures, MODEL_RETRY_MS, parentPinned, spillCandidat
|
|
|
66
67
|
import { PENDING_NOTE, UNDELIVERED_FOLLOW_UP } from "../notes.js";
|
|
67
68
|
import { COMMAND_LOG, exitMeaning, prepareCancelled, prepareCommand as stageCommand, readExitRecord, readTail, spawnCommand } from "../../platform/command.js";
|
|
68
69
|
import { captureStart } from "../../platform/proctable.js";
|
|
69
|
-
import { IS_WINDOWS, sameCreation } from "../../platform/windows.js";
|
|
70
|
+
import { IS_WINDOWS, sameCreation, scannedCommand } from "../../platform/windows.js";
|
|
71
|
+
import { commandLine } from "../../platform/cmdline.js";
|
|
72
|
+
import { checkLinuxScopeOom, kernelLimitsSatisfied, mergeLimits, probeKernelLimits, wrapLinuxScope } from "../../platform/limits.js";
|
|
73
|
+
import { readJobLimitExceeded } from "../../platform/job.js";
|
|
70
74
|
import { heldIn } from "../snapshot.js";
|
|
71
|
-
import { COMMAND_INTENT, COMMAND_SPAWN_FAILED, COMMAND_STARTED, COMMAND_TIMEOUT, COMMAND_WITHDRAWN, commandDirName, commandEnvironment, commandId, retiredCommandAttempts } from "./command.js";
|
|
75
|
+
import { COMMAND_INTENT, COMMAND_RESOURCE_LIMIT, COMMAND_SPAWN_FAILED, COMMAND_STARTED, COMMAND_TIMEOUT, COMMAND_WITHDRAWN, commandDirName, commandEnvironment, commandId, retiredCommandAttempts } from "./command.js";
|
|
76
|
+
import { formatResourceViolation, ResourceMonitor } from "./resources.js";
|
|
72
77
|
const MEM_RECORD_MS = 30000;
|
|
73
78
|
/** How long the processes of a stopped or timed-out command get between SIGTERM and SIGKILL. */
|
|
74
79
|
const COMMAND_GRACE_MS = 2000;
|
|
@@ -1333,9 +1338,9 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1333
1338
|
};
|
|
1334
1339
|
/** The processes of an attempt: tagged with its id, the wrapper while it lives, and their live descendants. A scan that
|
|
1335
1340
|
* fails transiently is not an empty result (`undefined`): an attempt is never called gone because the observer failed. */
|
|
1336
|
-
async function commandProcesses(id, known) {
|
|
1341
|
+
async function commandProcesses(id, known, scanOptions = { fresh: true }) {
|
|
1337
1342
|
try {
|
|
1338
|
-
return (await containment.scan(new Map([[id, known]]),
|
|
1343
|
+
return (await containment.scan(new Map([[id, known]]), scanOptions)).get(id) ?? [];
|
|
1339
1344
|
}
|
|
1340
1345
|
catch (error) {
|
|
1341
1346
|
if (closed)
|
|
@@ -1412,6 +1417,7 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1412
1417
|
throw shutdownError();
|
|
1413
1418
|
const started = entriesFor(journal, call).findLast(e => e.type === COMMAND_STARTED && e.id === id);
|
|
1414
1419
|
let { status, error } = outcome;
|
|
1420
|
+
const limitHit = entriesFor(journal, call).findLast(e => e.type === COMMAND_RESOURCE_LIMIT && e.id === id);
|
|
1415
1421
|
if (hasStopIntent(journal, call)) {
|
|
1416
1422
|
status = "stopped";
|
|
1417
1423
|
error = undefined;
|
|
@@ -1420,6 +1426,10 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1420
1426
|
status = "timeout";
|
|
1421
1427
|
error = `Command timed out after ${t.spec.timeoutMs} ms`;
|
|
1422
1428
|
}
|
|
1429
|
+
else if (limitHit) {
|
|
1430
|
+
status = "failed";
|
|
1431
|
+
error = String(limitHit.message ?? "Resource limit exceeded");
|
|
1432
|
+
}
|
|
1423
1433
|
const durationMs = started ? Math.max(0, Math.round((outcome.at ?? Date.now()) - started.ts)) : 0;
|
|
1424
1434
|
const result = { ...buildCallResult({ key: t.key, gen: t.gen, status, output, ...(error ? { error } : {}) }),
|
|
1425
1435
|
data: { exitCode: outcome.exitCode ?? null, signal: outcome.signal ?? null, durationMs }, usage: { input: 0, output: 0, costUsd: 0 } };
|
|
@@ -1509,8 +1519,9 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1509
1519
|
refused = "withdrawn";
|
|
1510
1520
|
return refused === undefined;
|
|
1511
1521
|
};
|
|
1522
|
+
const limits = mergeLimits(settings().limits, t.spec.limits);
|
|
1512
1523
|
const result = await spawnCommand({ command: t.spec.command, cwd: t.cwd, dir, proceed, exec: id,
|
|
1513
|
-
...(prepared ? { prepared } : {}), env: commandEnvironment(home, id, t.callId, t.spec.env) });
|
|
1524
|
+
...(limits ? { limits } : {}), ...(prepared ? { prepared } : {}), env: commandEnvironment(home, id, t.callId, t.spec.env) });
|
|
1514
1525
|
if (!result) {
|
|
1515
1526
|
if (refused === "withdrawn")
|
|
1516
1527
|
await serial(() => t.journal.append(COMMAND_WITHDRAWN, { call: t.callId, id }));
|
|
@@ -1525,7 +1536,7 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1525
1536
|
return undefined;
|
|
1526
1537
|
}
|
|
1527
1538
|
await serial(() => t.journal.append(COMMAND_STARTED, { call: t.callId, id, pid: spawned.pid, start: spawned.start, dir,
|
|
1528
|
-
...(spawned.group ? { group: spawned.group } : {}), ...(spawned.uncertain ? { uncertain: spawned.uncertain } : {}) }));
|
|
1539
|
+
...(spawned.group ? { group: spawned.group } : {}), ...(spawned.scopeUnit ? { scopeUnit: spawned.scopeUnit } : {}), ...(spawned.uncertain ? { uncertain: spawned.uncertain } : {}) }));
|
|
1529
1540
|
return spawned;
|
|
1530
1541
|
}
|
|
1531
1542
|
/** Run, adopt or settle a command call (see the journal records at the top). One attempt runs at a time; a lost first
|
|
@@ -1549,10 +1560,17 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1549
1560
|
const blocked = commandBlocked(a);
|
|
1550
1561
|
if (blocked)
|
|
1551
1562
|
return { blocked };
|
|
1563
|
+
const env = commandEnvironment(home, id, call, t.spec.env);
|
|
1564
|
+
const limits = mergeLimits(settings().limits, t.spec.limits);
|
|
1565
|
+
if (limits?.strict) {
|
|
1566
|
+
const problem = kernelLimitsSatisfied(limits, probeKernelLimits({ kind: "command", env }));
|
|
1567
|
+
if (problem)
|
|
1568
|
+
return { failure: problem };
|
|
1569
|
+
}
|
|
1552
1570
|
let prepared;
|
|
1553
1571
|
try {
|
|
1554
1572
|
prepared = await prepareStart({ command: t.spec.command, cwd: t.cwd, dir, exec: id,
|
|
1555
|
-
|
|
1573
|
+
...(limits ? { limits } : {}), env, signal: a.controller.signal });
|
|
1556
1574
|
}
|
|
1557
1575
|
catch (error) {
|
|
1558
1576
|
// The revocation is the cause, so it decides the attempt: the rejection cannot be told apart from one the abort
|
|
@@ -1667,10 +1685,30 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1667
1685
|
throw error;
|
|
1668
1686
|
}
|
|
1669
1687
|
};
|
|
1670
|
-
const
|
|
1688
|
+
const monitor = new ResourceMonitor(mergeLimits(settings().limits, t.spec.limits));
|
|
1689
|
+
const settleExit = async (exit, known, deadline, scopeUnit) => {
|
|
1671
1690
|
// Processes the command left behind (background ones included) end with it, as a call's processes always do.
|
|
1672
1691
|
if (!closed)
|
|
1673
1692
|
await endCommand(id, known);
|
|
1693
|
+
if (exit.status !== 0 && !entriesFor(journal, call).some(e => e.type === COMMAND_RESOURCE_LIMIT && e.id === id)) {
|
|
1694
|
+
const lim = mergeLimits(settings().limits, t.spec.limits);
|
|
1695
|
+
const winHit = IS_WINDOWS ? await readJobLimitExceeded(dir) : undefined;
|
|
1696
|
+
if (winHit) {
|
|
1697
|
+
const peakMb = Math.round((winHit.peakBytes / (1024 * 1024)) * 10) / 10;
|
|
1698
|
+
const message = `Resource limit exceeded: killed by Windows Job Object ${winHit.kind} limit (memoryMb limit: ${lim?.memoryMb ?? "?"} MiB${peakMb > 0 ? `, peak ${peakMb} MiB` : ""})`;
|
|
1699
|
+
await serial(async () => {
|
|
1700
|
+
if (!entriesFor(journal, call).some(e => e.type === COMMAND_RESOURCE_LIMIT && e.id === id))
|
|
1701
|
+
await journal.append(COMMAND_RESOURCE_LIMIT, { call, id, kind: winHit.kind, limit: lim?.memoryMb, peak: peakMb, message });
|
|
1702
|
+
});
|
|
1703
|
+
}
|
|
1704
|
+
else if (scopeUnit && await checkLinuxScopeOom(scopeUnit)) {
|
|
1705
|
+
const message = `Resource limit exceeded: killed by Linux cgroup OOM (memoryMb limit: ${lim?.memoryMb ?? "?"} MiB)`;
|
|
1706
|
+
await serial(async () => {
|
|
1707
|
+
if (!entriesFor(journal, call).some(e => e.type === COMMAND_RESOURCE_LIMIT && e.id === id))
|
|
1708
|
+
await journal.append(COMMAND_RESOURCE_LIMIT, { call, id, kind: "memory", limit: lim?.memoryMb, message });
|
|
1709
|
+
});
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1674
1712
|
// An exit after the deadline (seen late: the orchestrator was down) is a timeout, with the record's data.
|
|
1675
1713
|
const late = deadline !== undefined && exit.at > deadline;
|
|
1676
1714
|
return await sealCommand(journal, t, id, { status: late ? "timeout" : exit.status === 0 ? "ok" : "failed", ...exitResult(exit.status),
|
|
@@ -1679,12 +1717,13 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1679
1717
|
try {
|
|
1680
1718
|
for (;;) {
|
|
1681
1719
|
const started = entriesFor(journal, call).findLast(e => e.type === COMMAND_STARTED && e.id === id), known = commandKnown(started);
|
|
1720
|
+
const scopeUnit = typeof started?.scopeUnit === "string" ? started.scopeUnit : undefined;
|
|
1682
1721
|
// The timeout is wall clock from the start (command-started, else the intent: a crash before the started record),
|
|
1683
1722
|
// downtime included.
|
|
1684
1723
|
const deadline = t.spec.timeoutMs !== undefined ? (started ?? intent).ts + t.spec.timeoutMs : undefined;
|
|
1685
1724
|
const exit = await readExit();
|
|
1686
1725
|
if (exit)
|
|
1687
|
-
return await settleExit(exit, known, deadline);
|
|
1726
|
+
return await settleExit(exit, known, deadline, scopeUnit);
|
|
1688
1727
|
if (closed)
|
|
1689
1728
|
throw shutdownError();
|
|
1690
1729
|
if (a.retired || retiredCall(journal, call)) {
|
|
@@ -1701,16 +1740,63 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1701
1740
|
await endCommand(id, known);
|
|
1702
1741
|
return await sealCommand(journal, t, id, { status: "timeout" }, dir);
|
|
1703
1742
|
}
|
|
1743
|
+
const priorLimit = entriesFor(journal, call).findLast(e => e.type === COMMAND_RESOURCE_LIMIT && e.id === id);
|
|
1744
|
+
if (priorLimit) {
|
|
1745
|
+
await endCommand(id, known);
|
|
1746
|
+
return await sealCommand(journal, t, id, { status: "failed", error: String(priorLimit.message ?? "Resource limit exceeded") }, dir);
|
|
1747
|
+
}
|
|
1748
|
+
const limits = mergeLimits(settings().limits, t.spec.limits);
|
|
1704
1749
|
const observedStart = started?.start ? await captureStart(Number(started.pid)).catch(() => "") : "";
|
|
1705
1750
|
const wrapper = !!started?.start && (IS_WINDOWS ? sameCreation(observedStart, String(started.start)) : observedStart === started.start);
|
|
1706
1751
|
// A failed observation is not a loss: the attempt stays tracked and is watched again (never started over).
|
|
1707
|
-
const live = wrapper
|
|
1752
|
+
const live = wrapper
|
|
1753
|
+
? (limits ? await commandProcesses(id, known, { maxAgeMs: commandTick() }) : undefined)
|
|
1754
|
+
: await commandProcesses(id, known);
|
|
1755
|
+
if (limits && live && live.length) {
|
|
1756
|
+
monitor.setLimits(limits);
|
|
1757
|
+
const overhead = new Set(known.map(p => p.pid));
|
|
1758
|
+
const { violation } = monitor.sample(live, performance.now(), overhead);
|
|
1759
|
+
if (violation) {
|
|
1760
|
+
const byPid = new Map(live.map(p => [p.pid, p]));
|
|
1761
|
+
const ctl = new AbortController();
|
|
1762
|
+
const timer = setTimeout(() => ctl.abort(), 500);
|
|
1763
|
+
let top = violation.top;
|
|
1764
|
+
try {
|
|
1765
|
+
top = await Promise.all(violation.top.map(async (item) => {
|
|
1766
|
+
const p = byPid.get(item.pid);
|
|
1767
|
+
const scanned = p ? scannedCommand(p) : undefined;
|
|
1768
|
+
const cmd = scanned !== undefined ? scanned : await commandLine(item.pid, ctl.signal).catch(() => "");
|
|
1769
|
+
return cmd ? { ...item, command: cmd } : item;
|
|
1770
|
+
}));
|
|
1771
|
+
}
|
|
1772
|
+
finally {
|
|
1773
|
+
clearTimeout(timer);
|
|
1774
|
+
}
|
|
1775
|
+
const message = formatResourceViolation({ ...violation, top });
|
|
1776
|
+
await serial(async () => {
|
|
1777
|
+
if (!entriesFor(journal, call).some(e => e.type === COMMAND_RESOURCE_LIMIT && e.id === id)) {
|
|
1778
|
+
await journal.append(COMMAND_RESOURCE_LIMIT, { call, id, kind: violation.kind, limit: violation.limit,
|
|
1779
|
+
observed: violation.observed, peak: violation.peak, processes: violation.processes, top, message });
|
|
1780
|
+
}
|
|
1781
|
+
});
|
|
1782
|
+
await endCommand(id, known);
|
|
1783
|
+
return await sealCommand(journal, t, id, { status: "failed", error: message }, dir);
|
|
1784
|
+
}
|
|
1785
|
+
}
|
|
1708
1786
|
if (!wrapper && live !== undefined && !live.length) {
|
|
1709
1787
|
// The wrapper may have written its record just before it ended (or a Windows scanner may briefly hold it).
|
|
1710
1788
|
const late = await readExit();
|
|
1711
|
-
if (
|
|
1712
|
-
return
|
|
1713
|
-
|
|
1789
|
+
if (late)
|
|
1790
|
+
return await settleExit(late, known, deadline, scopeUnit);
|
|
1791
|
+
if (scopeUnit && await checkLinuxScopeOom(scopeUnit)) {
|
|
1792
|
+
const message = `Resource limit exceeded: killed by Linux cgroup OOM (memoryMb limit: ${limits?.memoryMb ?? "?"} MiB)`;
|
|
1793
|
+
await serial(async () => {
|
|
1794
|
+
if (!entriesFor(journal, call).some(e => e.type === COMMAND_RESOURCE_LIMIT && e.id === id))
|
|
1795
|
+
await journal.append(COMMAND_RESOURCE_LIMIT, { call, id, kind: "memory", limit: limits?.memoryMb, message });
|
|
1796
|
+
});
|
|
1797
|
+
return await sealCommand(journal, t, id, { status: "failed", error: message }, dir);
|
|
1798
|
+
}
|
|
1799
|
+
return "lost";
|
|
1714
1800
|
}
|
|
1715
1801
|
const wait = Math.max(1, Math.min(commandTick(), deadline !== undefined ? deadline - Date.now() : Infinity));
|
|
1716
1802
|
await new Promise(resolve => { const timer = setTimeout(resolve, wait); a.wake = () => { clearTimeout(timer); resolve(); }; });
|
|
@@ -1873,6 +1959,9 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1873
1959
|
return finish(journal, t.callId, exec, makeResult("timeout"));
|
|
1874
1960
|
if (ev.budget || reached(totalUsage(journal.entries(), t.callId), t.spec.budget))
|
|
1875
1961
|
return finish(journal, t.callId, exec, makeResult("budget"));
|
|
1962
|
+
const limitHit = entriesOf(journal, "resource-limit", exec).at(-1);
|
|
1963
|
+
if (limitHit)
|
|
1964
|
+
return finish(journal, t.callId, exec, makeResult("failed", "", String(limitHit.message ?? "Resource limit exceeded")));
|
|
1876
1965
|
const textFailure = entries.findLast(e => e.type === "custom" && e.customType === CT.exhausted && e.data?.exec === exec)?.data;
|
|
1877
1966
|
if (textFailure) {
|
|
1878
1967
|
const provider = String(textFailure.provider), text = String(textFailure.text).slice(0, 200);
|
|
@@ -1956,6 +2045,15 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1956
2045
|
await fence(journal, exec, { park: a });
|
|
1957
2046
|
return finish(journal, t.callId, exec, makeResult("failed", "", "workflow budget reached"));
|
|
1958
2047
|
}
|
|
2048
|
+
const effectiveLimits = () => mergeLimits(settings().limits, t.spec.limits);
|
|
2049
|
+
const launchLimits = effectiveLimits();
|
|
2050
|
+
if (launchLimits?.strict) {
|
|
2051
|
+
const problem = kernelLimitsSatisfied(launchLimits, probeKernelLimits({ kind: "agent" }));
|
|
2052
|
+
if (problem) {
|
|
2053
|
+
await fence(journal, exec, { park: a });
|
|
2054
|
+
return finish(journal, t.callId, exec, makeResult("failed", "", problem));
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
1959
2057
|
let decision;
|
|
1960
2058
|
try {
|
|
1961
2059
|
decision = await acquire(a, exec, () => launchModel(t, entries, previous), writer ??= await writerRoot(t, cwd));
|
|
@@ -2026,9 +2124,15 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
2026
2124
|
// PATH without node (a service's). execTarget resolves a bare `pi` on this PATH too, not on the orchestrator's: the
|
|
2027
2125
|
// shim it must run may be the call's own.
|
|
2028
2126
|
const childEnv = { DSA_HOME: home, PATH: [binDir(home), dirname(process.execPath), process.env.PATH].filter(Boolean).join(delimiter), DSA_EXEC: exec, DSA_CALL: t.callId, DSA_INBOX: inbox(t.callId), DSA_JOURNAL: journal.path, DSA_ASK_REQUIRE_DECISION: String(config.askRequireDecision ?? false), ...(Object.keys(patterns).length ? { DSA_EXHAUSTED_PATTERNS: JSON.stringify(patterns) } : {}), ...(t.spec.schema !== undefined ? { DSA_SCHEMA: schema } : {}), ...(t.spec.budget ? { DSA_BUDGET: JSON.stringify(t.spec.budget) } : {}), ...(model.provider && model.id ? { DSA_MODEL: `${model.provider}/${model.id}` } : {}), ...(exactTools && t.exactCapture ? { DSA_EXACT_CAPTURE: t.exactCapture.path, DSA_EXACT_TOOLS: JSON.stringify(exactTools) } : {}) };
|
|
2127
|
+
let scopeUnit;
|
|
2128
|
+
const fullChildEnv = { ...process.env, ...childEnv };
|
|
2029
2129
|
try {
|
|
2030
2130
|
const target = execTarget(piCommand, [...buildPiArgs(t.agent, t.spec, { sessionPath: session, systemPromptPath: prompt, continuation: decision.continuation, controlTools: t.spec.schema === undefined ? ["ask"] : ["ask", "report"], ...(model.id ? { model } : {}), ...(t.exactMode?.mode === "exact" ? { thinking: (await readPinnedCapture(t.exactCapture?.path))?.thinking ?? false } : {}) }), "-e", extension], { env: childEnv });
|
|
2031
|
-
|
|
2131
|
+
const wrapped = launchLimits && process.platform === "linux"
|
|
2132
|
+
? wrapLinuxScope(exec, target.command, target.args, launchLimits, probeKernelLimits({ platform: "linux", env: fullChildEnv, kind: "agent" }))
|
|
2133
|
+
: { command: target.command, args: target.args };
|
|
2134
|
+
scopeUnit = wrapped.unit;
|
|
2135
|
+
child = await containment.spawn({ exec, command: wrapped.command, args: wrapped.args, cwd, env: childEnv, ...(target.verbatim && !wrapped.unit ? { windowsVerbatimArguments: true } : {}) });
|
|
2032
2136
|
}
|
|
2033
2137
|
catch (error) {
|
|
2034
2138
|
const environment = environmentSpawnError(error);
|
|
@@ -2089,7 +2193,16 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
2089
2193
|
cacheWrite: usage.cacheWrite ?? 0, output: usage.output ?? 0, costUsd: usage.cost?.total ?? 0 }));
|
|
2090
2194
|
},
|
|
2091
2195
|
switched: event => switched(exec, journal, event), answered: event => answered(t, exec, event), pendingSwitch: () => pendingSwitch(exec),
|
|
2092
|
-
|
|
2196
|
+
limits: effectiveLimits, });
|
|
2197
|
+
if (scopeUnit && !has(journal, "resource-limit", exec) && await checkLinuxScopeOom(scopeUnit, fullChildEnv)) {
|
|
2198
|
+
const lim = effectiveLimits();
|
|
2199
|
+
const message = `Resource limit exceeded: killed by Linux cgroup OOM (memoryMb limit: ${lim?.memoryMb ?? "?"} MiB)`;
|
|
2200
|
+
await serial(async () => {
|
|
2201
|
+
if (!has(journal, "resource-limit", exec)) {
|
|
2202
|
+
await journal.append("resource-limit", { exec, call: t.callId, kind: "memory", limit: lim?.memoryMb, message });
|
|
2203
|
+
}
|
|
2204
|
+
});
|
|
2205
|
+
}
|
|
2093
2206
|
}
|
|
2094
2207
|
finally {
|
|
2095
2208
|
await fence(journal, exec, { child, park: a });
|
|
@@ -6,11 +6,14 @@ import { stat as fileStat } from "node:fs/promises";
|
|
|
6
6
|
import { performance } from "node:perf_hooks";
|
|
7
7
|
import { createInterface } from "node:readline";
|
|
8
8
|
import { CT, JT, attentionEntries } from "../../types.js";
|
|
9
|
+
import { commandLine } from "../../platform/cmdline.js";
|
|
10
|
+
import { scannedCommand } from "../../platform/windows.js";
|
|
9
11
|
import { callDir, callSession } from "../../paths.js";
|
|
10
12
|
import { monotoneTime } from "../../kernel/guards.js";
|
|
11
13
|
import { readSession } from "./session.js";
|
|
12
14
|
import { entriesOf } from "./indexes.js";
|
|
13
15
|
import { ActiveTime, activeTotal } from "./time.js";
|
|
16
|
+
import { formatResourceViolation, ResourceMonitor } from "./resources.js";
|
|
14
17
|
import { entryUsage, observation, reached, sessionUsage, totalUsage } from "./usage.js";
|
|
15
18
|
const UPDATE = '{"type":"tool_execution_update",';
|
|
16
19
|
export const sessionChanged = (name) => name === null || String(name) === "session.jsonl" || String(name) === "inbox";
|
|
@@ -25,6 +28,7 @@ export function toolCommand(args) {
|
|
|
25
28
|
export async function observeExecution(d) {
|
|
26
29
|
const { home, config, ticket: t, exec, child, serial } = d;
|
|
27
30
|
const session = callSession(home, t.wid, t.key, t.gen), clock = new ActiveTime(), started = clock.last;
|
|
31
|
+
const monitor = new ResourceMonitor(d.limits?.());
|
|
28
32
|
let progress = started, providerError;
|
|
29
33
|
// Diagnostic metadata only: checkpoint the latest received stream update, never its content.
|
|
30
34
|
let lastStream;
|
|
@@ -43,7 +47,8 @@ export async function observeExecution(d) {
|
|
|
43
47
|
const previous = entriesOf(t.journal, "time", exec).at(-1);
|
|
44
48
|
if (!monotoneTime({ active: Number(previous?.active ?? 0) }, { active: clock.active }))
|
|
45
49
|
throw new Error("Nonmonotone active time");
|
|
46
|
-
|
|
50
|
+
const resources = monitor.latest();
|
|
51
|
+
await t.journal.append("time", { exec, active: clock.active, ...(lastStream ? { lastStream } : {}), ...(resources ? { resources } : {}) });
|
|
47
52
|
});
|
|
48
53
|
const limits = async () => {
|
|
49
54
|
if (t.spec.timeoutMs !== undefined && prior + clock.active >= t.spec.timeoutMs) {
|
|
@@ -201,9 +206,11 @@ export async function observeExecution(d) {
|
|
|
201
206
|
// 2 s deadline right after the orchestrator was stopped or the machine slept (seen on CI as a spurious loss and
|
|
202
207
|
// a rerun). Only a scan that keeps failing for a minute ends the observation.
|
|
203
208
|
// Measured in elapsed time: the scan period is fixed at start while k.trackerMs can be reloaded.
|
|
209
|
+
let procs;
|
|
204
210
|
try {
|
|
205
211
|
if (processes) {
|
|
206
|
-
|
|
212
|
+
procs = await d.track();
|
|
213
|
+
clock.scan(procs);
|
|
207
214
|
failingSince = undefined;
|
|
208
215
|
}
|
|
209
216
|
}
|
|
@@ -212,6 +219,37 @@ export async function observeExecution(d) {
|
|
|
212
219
|
if (performance.now() - failingSince >= 60_000)
|
|
213
220
|
throw error;
|
|
214
221
|
}
|
|
222
|
+
if (procs) {
|
|
223
|
+
monitor.setLimits(d.limits?.());
|
|
224
|
+
const { violation } = monitor.sample(procs, performance.now());
|
|
225
|
+
if (violation && !ending && !has("resource-limit")) {
|
|
226
|
+
const byPid = new Map(procs.map(p => [p.pid, p]));
|
|
227
|
+
const readCmd = d.readCommand ?? commandLine;
|
|
228
|
+
const ctl = new AbortController();
|
|
229
|
+
const timer = setTimeout(() => ctl.abort(), 500);
|
|
230
|
+
let top = violation.top;
|
|
231
|
+
try {
|
|
232
|
+
top = await Promise.all(violation.top.map(async (item) => {
|
|
233
|
+
const p = byPid.get(item.pid);
|
|
234
|
+
const scanned = p ? scannedCommand(p) : undefined;
|
|
235
|
+
const cmd = scanned !== undefined ? scanned : await readCmd(item.pid, ctl.signal).catch(() => "");
|
|
236
|
+
return cmd ? { ...item, command: cmd } : item;
|
|
237
|
+
}));
|
|
238
|
+
}
|
|
239
|
+
finally {
|
|
240
|
+
clearTimeout(timer);
|
|
241
|
+
}
|
|
242
|
+
const message = formatResourceViolation({ ...violation, top });
|
|
243
|
+
await serial(async () => {
|
|
244
|
+
if (!has("resource-limit")) {
|
|
245
|
+
await t.journal.append("resource-limit", { exec, call: t.callId, kind: violation.kind, limit: violation.limit,
|
|
246
|
+
observed: violation.observed, peak: violation.peak, processes: violation.processes, top, message });
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
signal();
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
215
253
|
const nextSize = (await fileStat(session).catch(() => ({ size: 0 }))).size;
|
|
216
254
|
if (nextSize > size) {
|
|
217
255
|
clock.evidence();
|