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.
@@ -0,0 +1,144 @@
1
+ import { snapshotCapturedAt } from "../../platform/proctable.js";
2
+ /** Default consecutive ms a resource limit must be exceeded before fencing (avoids killing brief compilation spikes). */
3
+ export const DEFAULT_RESOURCE_GRACE_MS = 5_000;
4
+ /** Minimum interval between samples before computing a CPU % delta (avoids noisy spikes on sub-200ms back-to-back scans). */
5
+ const MIN_CPU_DELTA_MS = 200;
6
+ const round1 = (n) => Math.round(n * 10) / 10;
7
+ const bytesToMb = (bytes) => bytes / (1024 * 1024);
8
+ /** Format a human-readable error message for a sealed resource-limit failure. */
9
+ export function formatResourceViolation(v) {
10
+ const topText = v.top.length
11
+ ? `; top: ${v.top.map(p => `pid ${p.pid} ${round1(p.rssMb)} MiB${p.command ? ` \`${p.command.slice(0, 60)}\`` : ""}`).join(", ")}`
12
+ : "";
13
+ if (v.kind === "memory") {
14
+ return `Resource limit exceeded: memory ${round1(v.observed)} MiB > ${v.limit} MiB limit (peak ${round1(v.peak)} MiB across ${v.processes} process${v.processes === 1 ? "" : "es"}${topText})`;
15
+ }
16
+ if (v.kind === "processes") {
17
+ return `Resource limit exceeded: ${v.observed} processes > ${v.limit} maxProcesses limit (peak ${v.peak}${topText})`;
18
+ }
19
+ return `Resource limit exceeded: CPU ${Math.round(v.observed)}% > ${v.limit}% limit (peak ${Math.round(v.peak)}% across ${v.processes} process${v.processes === 1 ? "" : "es"}${topText})`;
20
+ }
21
+ /** Tracks live & peak memory, process count, and CPU % for one execution's entire process tree. */
22
+ export class ResourceMonitor {
23
+ limits;
24
+ peakMemoryMb = 0;
25
+ peakProcesses = 0;
26
+ peakCpuPercent;
27
+ lastStats;
28
+ lastSampleAt;
29
+ prevAt;
30
+ prevCpu = new Map();
31
+ exceededSince = {};
32
+ constructor(limits) {
33
+ this.limits = limits;
34
+ }
35
+ /** Update active limits in place (e.g. after a live config.json reload). */
36
+ setLimits(limits) {
37
+ this.limits = limits;
38
+ if (!limits?.memoryMb)
39
+ this.exceededSince.memory = undefined;
40
+ if (!limits?.maxProcesses)
41
+ this.exceededSince.processes = undefined;
42
+ if (!limits?.cpuPercent)
43
+ this.exceededSince.cpu = undefined;
44
+ }
45
+ /** Most recently computed stats, if at least one sample has been recorded. */
46
+ latest() {
47
+ return this.lastStats ? { ...this.lastStats } : undefined;
48
+ }
49
+ /** Feed one process-tree snapshot and current monotonic/wall timestamp in ms.
50
+ * `overheadPids` (command wrapper / Windows job host) are excluded from `processes` and `rssBytes` so
51
+ * `maxProcesses: 1` allows a single user command without counting internal harness processes. */
52
+ sample(procs, nowMs, overheadPids) {
53
+ // Deduplicate cached ProcessTable snapshots so repeated reads of the same scan never reset CPU % to 0,
54
+ // inflate the next real scan's CPU delta, or advance grace timers on stale spikes.
55
+ const sampleAt = snapshotCapturedAt(procs) ?? nowMs;
56
+ if (this.lastSampleAt !== undefined && sampleAt <= this.lastSampleAt && this.lastStats) {
57
+ return { stats: { ...this.lastStats } };
58
+ }
59
+ this.lastSampleAt = sampleAt;
60
+ const counted = overheadPids?.size ? procs.filter(p => !overheadPids.has(p.pid)) : procs;
61
+ let totalRssBytes = 0;
62
+ for (const p of counted) {
63
+ if (typeof p.rssBytes === "number" && Number.isFinite(p.rssBytes) && p.rssBytes > 0) {
64
+ totalRssBytes += p.rssBytes;
65
+ }
66
+ }
67
+ const memoryMb = round1(bytesToMb(totalRssBytes));
68
+ const processes = counted.length;
69
+ if (memoryMb > this.peakMemoryMb)
70
+ this.peakMemoryMb = memoryMb;
71
+ if (processes > this.peakProcesses)
72
+ this.peakProcesses = processes;
73
+ let cpuPercent;
74
+ const nextCpu = new Map();
75
+ for (const p of counted) {
76
+ if (typeof p.cpuMs === "number" && Number.isFinite(p.cpuMs) && p.cpuMs >= 0) {
77
+ nextCpu.set(`${p.pid}:${p.start}`, p.cpuMs);
78
+ }
79
+ }
80
+ if (this.prevAt !== undefined) {
81
+ const dt = sampleAt - this.prevAt;
82
+ if (dt >= MIN_CPU_DELTA_MS) {
83
+ let deltaCpuMs = 0;
84
+ for (const [id, cpu] of nextCpu) {
85
+ const prev = this.prevCpu.get(id);
86
+ // Count delta for surviving processes and full observed cpuMs for freshly spawned children in this interval.
87
+ deltaCpuMs += prev !== undefined ? Math.max(0, cpu - prev) : cpu;
88
+ }
89
+ cpuPercent = round1((deltaCpuMs / dt) * 100);
90
+ if (this.peakCpuPercent === undefined || cpuPercent > this.peakCpuPercent) {
91
+ this.peakCpuPercent = cpuPercent;
92
+ }
93
+ this.prevAt = sampleAt;
94
+ this.prevCpu = nextCpu;
95
+ }
96
+ else {
97
+ cpuPercent = this.lastStats?.cpuPercent;
98
+ }
99
+ }
100
+ else {
101
+ this.prevAt = sampleAt;
102
+ this.prevCpu = nextCpu;
103
+ }
104
+ const stats = {
105
+ memoryMb,
106
+ peakMemoryMb: this.peakMemoryMb,
107
+ processes,
108
+ peakProcesses: this.peakProcesses,
109
+ ...(cpuPercent !== undefined ? { cpuPercent } : {}),
110
+ ...(this.peakCpuPercent !== undefined ? { peakCpuPercent: this.peakCpuPercent } : {}),
111
+ };
112
+ this.lastStats = stats;
113
+ const limits = this.limits;
114
+ if (!limits)
115
+ return { stats };
116
+ const graceMs = limits.graceMs ?? DEFAULT_RESOURCE_GRACE_MS;
117
+ const top = () => [...counted]
118
+ .filter(p => typeof p.rssBytes === "number" && p.rssBytes > 0)
119
+ .sort((a, b) => (b.rssBytes ?? 0) - (a.rssBytes ?? 0))
120
+ .slice(0, 3)
121
+ .map(p => ({ pid: p.pid, rssMb: round1(bytesToMb(p.rssBytes)) }));
122
+ const check = (kind, observed, limit, peak) => {
123
+ if (limit === undefined || observed === undefined) {
124
+ this.exceededSince[kind] = undefined;
125
+ return undefined;
126
+ }
127
+ if (observed > limit) {
128
+ this.exceededSince[kind] ??= sampleAt;
129
+ if (sampleAt - this.exceededSince[kind] >= graceMs) {
130
+ return { kind, limit, observed, peak, graceMs, processes, top: top() };
131
+ }
132
+ }
133
+ else {
134
+ this.exceededSince[kind] = undefined;
135
+ }
136
+ return undefined;
137
+ };
138
+ // Priority: memory -> processes -> cpu (memory OOM is the most urgent threat to host stability).
139
+ const violation = check("memory", memoryMb, limits.memoryMb, this.peakMemoryMb) ??
140
+ check("processes", processes, limits.maxProcesses, this.peakProcesses) ??
141
+ check("cpu", cpuPercent, limits.cpuPercent, this.peakCpuPercent ?? 0);
142
+ return violation ? { stats, violation } : { stats };
143
+ }
144
+ }
@@ -397,6 +397,11 @@ function snapshotReducer(wid, entries) {
397
397
  call.selectedModel = call.model;
398
398
  }
399
399
  }
400
+ else if (e.type === "time" && e.resources && typeof e.resources === "object") {
401
+ const call = byExec.get(String(e.exec));
402
+ if (call)
403
+ call.resources = e.resources;
404
+ }
400
405
  else if (e.type === "observation") {
401
406
  // Only what the agent did counts as activity; tracker scans and time checkpoints are bookkeeping.
402
407
  const call = byExec.get(String(e.exec));
@@ -1339,7 +1344,7 @@ export function compactWorkflow(wf, leases) {
1339
1344
  const r = c.result, last = r?.output?.split("\n").map(l => l.trim()).filter(Boolean).at(-1);
1340
1345
  return { key: c.key, gen: c.gen, callId: c.callId, phase: c.phase, ...modelStatus(c), ...commandStatus(c), ...(r ? { status: r.status, ok: r.ok } : {}),
1341
1346
  ...(c.sharedWorktree ? { sharedWorktree: c.sharedWorktree } : {}),
1342
- ...(c.model ? { model: c.model } : {}), ...(c.tools ? { tools: c.tools } : {}), ...(c.pending ? { pending: c.pending } : {}), ...(c.switching ? { switching: c.switching } : {}), ...(c.switchFailed ? { switchFailed: c.switchFailed } : {}), ...(nonzero(c.usage) ? { usage: c.usage } : {}),
1347
+ ...(c.model ? { model: c.model } : {}), ...(c.tools ? { tools: c.tools } : {}), ...(c.pending ? { pending: c.pending } : {}), ...(c.switching ? { switching: c.switching } : {}), ...(c.switchFailed ? { switchFailed: c.switchFailed } : {}), ...(nonzero(c.usage) ? { usage: c.usage } : {}), ...(c.resources ? { resources: c.resources } : {}),
1343
1348
  ...(last ? { lastLine: clip(last, 200) } : {}), ...(r?.error ? { error: clip(r.error, 300) } : {}), ...(c.hibernated ? { hibernated: true } : {}),
1344
1349
  ...(c.answered ? { answered: c.answered } : {}), ...(c.answerForwarded ? { answerForwarded: c.answerForwarded } : {}), ...(c.writerWait && !r ? { writerWait: c.writerWait } : {}), ...(!r && leases?.get(c.callId) ? { lease: leases.get(c.callId) } : {}),
1345
1350
  ...(c.notesPending ? { notesPending: c.notesPending } : {}), ...(c.queuedFor && !r && !wf.paused ? { queued: queuedText(c.queuedFor) } : {}), ...(c.exact ? { exact: c.exact } : {}) };
@@ -1560,6 +1565,7 @@ export function statusBrief(home, options = {}) {
1560
1565
  ...(live && c.startedAt !== undefined ? { for: age(now - c.startedAt) } : {}),
1561
1566
  ...(agent && live && c.phase !== "asking" && quiet !== undefined && quiet >= 60_000 ? { quiet: age(quiet) } : {}),
1562
1567
  ...(agent && live && c.startedAt !== undefined ? { tokens: tokens(c.usage) } : {}),
1568
+ ...(live && c.resources && c.resources.peakMemoryMb > 0 ? { memory: `${Math.round(c.resources.memoryMb)} MiB (peak ${Math.round(c.resources.peakMemoryMb)} MiB, ${c.resources.processes} proc${c.resources.processes === 1 ? "" : "s"})` } : {}),
1563
1569
  ...(c.result ? { status: c.result.status, ...(c.result.error ? { error: clip(c.result.error, 200) } : {}) } : {}),
1564
1570
  ...(c.hibernated ? { hibernated: true } : {}), ...(c.answered ? { answered: c.answered } : {}), ...(c.answerForwarded ? { answerForwarded: c.answerForwarded } : {}), ...(live && c.writerWait ? { writerWait: c.writerWait } : {}),
1565
1571
  ...(live && byCall.get(c.callId) ? { lease: byCall.get(c.callId) } : {}),
@@ -26,6 +26,7 @@ import { retryWinSharing } from "../kernel/fsx.js";
26
26
  import { captureStart } from "./proctable.js";
27
27
  import { execTarget, findOnPath } from "./launch.js";
28
28
  import { prepareJob, spawnInJob } from "./job.js";
29
+ import { probeKernelLimits, wrapLinuxScope } from "./limits.js";
29
30
  import { DWORD_MAX, comspec, envValue, helperEnv, IS_WINDOWS, mergeEnv, normalizeEnv, systemRoot, winTagArg } from "./windows.js";
30
31
  export const COMMAND_LOG = "output.log";
31
32
  export const COMMAND_EXIT = "exit";
@@ -136,6 +137,22 @@ function windowsPlan(spec) {
136
137
  * then the group owner compiled (bounded and cancellable: `signal` ends the compiler, removes what it wrote and rejects
137
138
  * with a cancelled preparation). Nothing is started, so a crash here leaves no intent and no process: the attempt is
138
139
  * unambiguously prelaunch. POSIX prepares nothing (the wrapper is /bin/sh). */
140
+ /** Commit headroom reserved for Windows wrapper.mjs (Node.js) inside the Job Object so a tight memoryMb limit never
141
+ * OOM-kills the wrapper before it can run the user command or write its exit record; Layer 1 enforces exact memoryMb. */
142
+ const WIN_WRAPPER_MEMORY_OVERHEAD_MB = 64;
143
+ function winJobLimits(limits) {
144
+ if (!limits)
145
+ return undefined;
146
+ const { memoryMb, maxProcesses, cpuPercent } = limits;
147
+ if (memoryMb === undefined && maxProcesses === undefined && cpuPercent === undefined)
148
+ return undefined;
149
+ return {
150
+ ...(memoryMb !== undefined ? { memoryMb: memoryMb + WIN_WRAPPER_MEMORY_OVERHEAD_MB } : {}),
151
+ // Account for wrapper.mjs (1 Node process) running inside the Job Object alongside the user command.
152
+ ...(maxProcesses !== undefined ? { maxProcesses: maxProcesses + 1 } : {}),
153
+ ...(cpuPercent !== undefined ? { cpuPercent } : {}),
154
+ };
155
+ }
139
156
  export async function prepareCommand(spec) {
140
157
  if (!IS_WINDOWS)
141
158
  return undefined;
@@ -144,8 +161,9 @@ export async function prepareCommand(spec) {
144
161
  const plan = windowsPlan(spec);
145
162
  await writeFile(join(spec.dir, COMMAND_SPEC), JSON.stringify({ command: plan.command, cwd: spec.cwd, env: plan.env, ...(plan.verbatim ? { verbatim: true } : {}) }));
146
163
  await writeFile(join(spec.dir, COMMAND_WRAPPER), COMMAND_WRAPPER_SOURCE);
164
+ const limits = winJobLimits(spec.limits);
147
165
  return prepareJob(spec.dir, { exe: process.execPath, env: helperEnv({ SystemRoot: systemRoot() }), cwd: spec.cwd, log: join(spec.dir, COMMAND_LOG),
148
- args: plan.args, ...(spec.exec ? { exec: spec.exec } : {}) }, { ...(spec.signal ? { signal: spec.signal } : {}) });
166
+ args: plan.args, ...(spec.exec ? { exec: spec.exec } : {}), ...(limits ? { limits } : {}) }, { ...(spec.signal ? { signal: spec.signal } : {}) });
149
167
  }
150
168
  export async function spawnCommand(spec) {
151
169
  await mkdir(spec.dir, { recursive: true });
@@ -164,8 +182,9 @@ export async function spawnCommand(spec) {
164
182
  if (spec.proceed && !spec.proceed())
165
183
  return undefined;
166
184
  // Start the internal Node wrapper with OS defaults. It reads the command's environment from command.json.
185
+ const limits = winJobLimits(spec.limits);
167
186
  return await spawnInJob(spec.dir, { exe: process.execPath, env: helperEnv({ SystemRoot: systemRoot() }), cwd: spec.cwd, log: join(spec.dir, COMMAND_LOG),
168
- args: plan.args, ...(spec.exec ? { exec: spec.exec } : {}) }, { ...(spec.proceed ? { proceed: spec.proceed } : {}),
187
+ args: plan.args, ...(spec.exec ? { exec: spec.exec } : {}), ...(limits ? { limits } : {}) }, { ...(spec.proceed ? { proceed: spec.proceed } : {}),
169
188
  ...(spec.prepared ? { prepared: spec.prepared } : {}), ...(spec.signal ? { signal: spec.signal } : {}) });
170
189
  }
171
190
  // POSIX: the wrapper's stdout and stderr are this descriptor, which it inherits and this process closes after the
@@ -175,13 +194,17 @@ export async function spawnCommand(spec) {
175
194
  const mv = resolveMv(), argv = commandArgv(spec.command);
176
195
  if (spec.proceed && !spec.proceed())
177
196
  return undefined;
178
- const child = spawn("/bin/sh", ["-c", WRAPPER, "dsa-command", spec.dir, mv, ...argv], { cwd: spec.cwd, env: spec.env, detached: true, stdio: ["ignore", fd, fd] });
197
+ const baseArgs = ["-c", WRAPPER, "dsa-command", spec.dir, mv, ...argv];
198
+ const wrapped = spec.limits && process.platform === "linux"
199
+ ? wrapLinuxScope(spec.exec ?? `cmd-${Date.now()}`, "/bin/sh", baseArgs, spec.limits, probeKernelLimits({ platform: "linux", env: spec.env, kind: "command" }))
200
+ : { command: "/bin/sh", args: baseArgs };
201
+ const child = spawn(wrapped.command, wrapped.args, { cwd: spec.cwd, env: spec.env, detached: true, stdio: ["ignore", fd, fd] });
179
202
  const exited = new Promise(resolve => { child.once("exit", () => resolve()); child.once("error", () => resolve()); });
180
203
  await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
181
204
  child.unref();
182
205
  const pid = child.pid;
183
206
  const start = child.exitCode !== null || child.signalCode !== null ? "" : await captureStart(pid).catch(() => "");
184
- return { pid, start, exited };
207
+ return { pid, start, ...(wrapped.unit ? { scopeUnit: wrapped.unit } : {}), exited };
185
208
  }
186
209
  finally {
187
210
  closeSync(fd);
@@ -2,7 +2,7 @@ import { spawn } from "node:child_process";
2
2
  import { PassThrough } from "node:stream";
3
3
  import { setTimeout as delay } from "node:timers/promises";
4
4
  import { performance } from "node:perf_hooks";
5
- import { captureStart, ProcessTable } from "./proctable.js";
5
+ import { attachCapturedAt, captureStart, ProcessTable, snapshotCapturedAt } from "./proctable.js";
6
6
  import { DWORD_MAX, isOwnedWinChild, isWinKillTimeout, isWinStart, KILL_BATCH_SIZE, killTree, normalizeWinTargets, sameCreation } from "./windows.js";
7
7
  // One table per orchestrator process, including evaluator and gate observers.
8
8
  const sharedTable = new ProcessTable();
@@ -77,6 +77,7 @@ export class Containment {
77
77
  const windows = this.platform === "win32";
78
78
  const execs = new Set([...known.keys(), ...this.launched.keys()]);
79
79
  const all = await this.table.list(execs, options);
80
+ const capturedAt = snapshotCapturedAt(all);
80
81
  for (const p of all)
81
82
  if (p.tag !== undefined)
82
83
  execs.add(p.tag);
@@ -142,7 +143,8 @@ export class Containment {
142
143
  }
143
144
  }
144
145
  }
145
- result.set(exec, [...selected.values()]);
146
+ const list = [...selected.values()];
147
+ result.set(exec, capturedAt !== undefined ? attachCapturedAt(list, capturedAt) : list);
146
148
  }
147
149
  return result;
148
150
  }
@@ -58,6 +58,7 @@ import { join } from "node:path";
58
58
  import { setTimeout as delay } from "node:timers/promises";
59
59
  import { retryWinSharing, retryWinSharingSync, writeFileAtomic } from "../kernel/fsx.js";
60
60
  import { dword, helperEnv, isWinStart, killProcess, sameCreation, systemRoot, winProcessRows, winTag, winTagArg } from "./windows.js";
61
+ import { clampMemoryBytes, winCpuRate } from "./limits.js";
61
62
  export { sameCreation };
62
63
  /** The owner type: exported for the packaging check (the compiled name carries it; nothing separate is shipped). */
63
64
  export const JOB_HOST_MARKER = "DsaJob";
@@ -80,8 +81,15 @@ public static class DsaJob
80
81
  const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000;
81
82
  const int PROC_THREAD_ATTRIBUTE_HANDLE_LIST = 0x00020002;
82
83
  const int JobObjectBasicAccountingInformation = 1;
84
+ const int JobObjectAssociateCompletionPortInformation = 7;
83
85
  const int JobObjectExtendedLimitInformation = 9;
86
+ const int JobObjectCpuRateControlInformation = 15;
87
+ const uint JOB_OBJECT_MSG_JOB_MEMORY_LIMIT = 10;
88
+ const uint JOB_OBJECT_LIMIT_ACTIVE_PROCESS = 0x00000008;
89
+ const uint JOB_OBJECT_LIMIT_JOB_MEMORY = 0x00000200;
84
90
  const uint JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000;
91
+ const uint JOB_OBJECT_CPU_RATE_CONTROL_ENABLE = 0x00000001;
92
+ const uint JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP = 0x00000004;
85
93
  const int STD_INPUT_HANDLE = -10;
86
94
  const int STD_OUTPUT_HANDLE = -11;
87
95
  const int STD_ERROR_HANDLE = -12;
@@ -187,6 +195,20 @@ public static class DsaJob
187
195
  public UIntPtr PeakJobMemoryUsed;
188
196
  }
189
197
 
198
+ [StructLayout(LayoutKind.Sequential)]
199
+ struct JOBOBJECT_CPU_RATE_CONTROL_INFORMATION
200
+ {
201
+ public uint ControlFlags;
202
+ public uint CpuRate;
203
+ }
204
+
205
+ [StructLayout(LayoutKind.Sequential)]
206
+ struct JOBOBJECT_ASSOCIATE_COMPLETION_PORT
207
+ {
208
+ public IntPtr CompletionKey;
209
+ public IntPtr CompletionPort;
210
+ }
211
+
190
212
  [StructLayout(LayoutKind.Sequential)]
191
213
  struct JOBOBJECT_BASIC_ACCOUNTING_INFORMATION
192
214
  {
@@ -205,8 +227,18 @@ public static class DsaJob
205
227
  [DllImport("kernel32.dll", SetLastError = true)]
206
228
  static extern bool SetInformationJobObject(IntPtr job, int infoClass, ref JOBOBJECT_EXTENDED_LIMIT_INFORMATION info, uint length);
207
229
  [DllImport("kernel32.dll", SetLastError = true)]
230
+ static extern bool SetInformationJobObject(IntPtr job, int infoClass, ref JOBOBJECT_CPU_RATE_CONTROL_INFORMATION info, uint length);
231
+ [DllImport("kernel32.dll", SetLastError = true)]
232
+ static extern bool SetInformationJobObject(IntPtr job, int infoClass, ref JOBOBJECT_ASSOCIATE_COMPLETION_PORT info, uint length);
233
+ [DllImport("kernel32.dll", SetLastError = true)]
234
+ static extern IntPtr CreateIoCompletionPort(IntPtr fileHandle, IntPtr existingPort, UIntPtr completionKey, uint concurrentThreads);
235
+ [DllImport("kernel32.dll", SetLastError = true)]
236
+ static extern bool GetQueuedCompletionStatus(IntPtr port, out uint bytesTransferred, out UIntPtr completionKey, out IntPtr overlapped, uint timeoutMs);
237
+ [DllImport("kernel32.dll", SetLastError = true)]
208
238
  static extern bool QueryInformationJobObject(IntPtr job, int infoClass, out JOBOBJECT_BASIC_ACCOUNTING_INFORMATION info, uint length, IntPtr returnLength);
209
239
  [DllImport("kernel32.dll", SetLastError = true)]
240
+ static extern bool QueryInformationJobObject(IntPtr job, int infoClass, out JOBOBJECT_EXTENDED_LIMIT_INFORMATION info, uint length, IntPtr returnLength);
241
+ [DllImport("kernel32.dll", SetLastError = true)]
210
242
  static extern bool TerminateJobObject(IntPtr job, uint exitCode);
211
243
  [DllImport("kernel32.dll", SetLastError = true)]
212
244
  static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
@@ -262,7 +294,9 @@ public static class DsaJob
262
294
  try { WriteAtomic(Path.Combine(dir, "helper-begin"), ProcessIdentity(unchecked((int)GetCurrentProcessId()), GetCurrentProcess())); } catch (Exception) { }
263
295
  string application, workingDirectory, logPath;
264
296
  string[] arguments, environment;
265
- try { ReadSpec(dir, out application, out workingDirectory, out logPath, out arguments, out environment); }
297
+ ulong memoryBytes;
298
+ uint maxProcesses, cpuRate;
299
+ try { ReadSpec(dir, out application, out workingDirectory, out logPath, out arguments, out environment, out memoryBytes, out maxProcesses, out cpuRate); }
266
300
  catch (Exception failure)
267
301
  {
268
302
  Fail(dir, "job spec", 0, failure.GetType().Name + ": " + failure.Message);
@@ -272,23 +306,39 @@ public static class DsaJob
272
306
  // instead of turning into this host's own failure code. 125/126 are only ever written by a host that recorded
273
307
  // why it did not get to run (or did not get) the wrapper, so a caller can tell the two apart.
274
308
  uint status;
275
- return Run(dir, application, arguments, workingDirectory, logPath, environment, out status) ? unchecked((int)status) : 125;
309
+ return Run(dir, application, arguments, workingDirectory, logPath, environment, memoryBytes, maxProcesses, cpuRate, out status) ? unchecked((int)status) : 125;
276
310
  }
277
311
 
278
312
  /** The attempt's spec: ASCII lines, one base64-encoded UTF-16LE field each, so no code page, quoting rule or
279
- * surrogate can change it (Field decodes each one to its exact code units). DSAJOB1, exe, cwd, log, argument count,
280
- * arguments, environment count, NAME=value entries. */
281
- static void ReadSpec(string dir, out string application, out string workingDirectory, out string logPath, out string[] arguments, out string[] environment)
313
+ * surrogate can change it (Field decodes each one to its exact code units). DSAJOB1/DSAJOB2, exe, cwd, log,
314
+ * argument count, arguments, environment count, NAME=value entries, plus optional DSAJOB2 limit lines
315
+ * (memoryBytes, maxProcesses, cpuRate). */
316
+ static void ReadSpec(string dir, out string application, out string workingDirectory, out string logPath, out string[] arguments, out string[] environment, out ulong memoryBytes, out uint maxProcesses, out uint cpuRate)
282
317
  {
283
318
  string path = Path.Combine(dir, "job.json");
284
319
  string[] lines = File.ReadAllLines(path, Encoding.ASCII);
285
320
  int at = 0;
286
- if (lines.Length < 5 || lines[at++] != "DSAJOB1") throw new FormatException("unknown job spec header");
321
+ if (lines.Length < 5) throw new FormatException("unknown job spec header");
322
+ string header = lines[at++];
323
+ if (header != "DSAJOB1" && header != "DSAJOB2") throw new FormatException("unknown job spec header");
287
324
  application = Field(lines[at++]);
288
325
  workingDirectory = Field(lines[at++]);
289
326
  logPath = Field(lines[at++]);
290
327
  arguments = Fields(lines, ref at);
291
328
  environment = Fields(lines, ref at);
329
+ memoryBytes = 0;
330
+ maxProcesses = 0;
331
+ cpuRate = 0;
332
+ if (header == "DSAJOB2")
333
+ {
334
+ if (lines.Length - at < 3) throw new FormatException("truncated job spec limits");
335
+ if (!UInt64.TryParse(lines[at++], NumberStyles.Integer, CultureInfo.InvariantCulture, out memoryBytes))
336
+ throw new FormatException("bad job memory limit");
337
+ if (!UInt32.TryParse(lines[at++], NumberStyles.Integer, CultureInfo.InvariantCulture, out maxProcesses))
338
+ throw new FormatException("bad job process limit");
339
+ if (!UInt32.TryParse(lines[at++], NumberStyles.Integer, CultureInfo.InvariantCulture, out cpuRate))
340
+ throw new FormatException("bad job cpu rate limit");
341
+ }
292
342
  if (at != lines.Length) throw new FormatException("trailing job spec fields");
293
343
  try { File.Delete(path); } catch (Exception) { }
294
344
  }
@@ -325,10 +375,10 @@ public static class DsaJob
325
375
 
326
376
  /** Run the wrapper inside a new group. True means the wrapper ran and the returned status is the full exit code the
327
377
  * kernel gave it; false means this host failed, wrote start-error and started nothing (or killed what it started). */
328
- static bool Run(string dir, string application, string[] arguments, string workingDirectory, string logPath, string[] environment, out uint status)
378
+ static bool Run(string dir, string application, string[] arguments, string workingDirectory, string logPath, string[] environment, ulong memoryBytes, uint maxProcesses, uint cpuRate, out uint status)
329
379
  {
330
380
  status = 0;
331
- IntPtr job = IntPtr.Zero, output = IntPtr.Zero, errorHandle = IntPtr.Zero, input = IntPtr.Zero, block = IntPtr.Zero;
381
+ IntPtr job = IntPtr.Zero, iocp = IntPtr.Zero, output = IntPtr.Zero, errorHandle = IntPtr.Zero, input = IntPtr.Zero, block = IntPtr.Zero;
332
382
  IntPtr list = IntPtr.Zero, inheritable = IntPtr.Zero;
333
383
  // DeleteProcThreadAttributeList takes only a list InitializeProcThreadAttributeList produced.
334
384
  bool listReady = false;
@@ -339,9 +389,44 @@ public static class DsaJob
339
389
  job = CreateJobObjectW(IntPtr.Zero, null);
340
390
  if (job == IntPtr.Zero) return Fail(dir, "CreateJobObject", Marshal.GetLastWin32Error());
341
391
  JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
342
- limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
392
+ uint limitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
393
+ if (memoryBytes > 0)
394
+ {
395
+ limitFlags |= JOB_OBJECT_LIMIT_JOB_MEMORY;
396
+ ulong capped = IntPtr.Size == 4 && memoryBytes > UInt32.MaxValue ? (ulong)UInt32.MaxValue : memoryBytes;
397
+ limits.JobMemoryLimit = new UIntPtr(capped);
398
+ }
399
+ if (maxProcesses > 0)
400
+ {
401
+ limitFlags |= JOB_OBJECT_LIMIT_ACTIVE_PROCESS;
402
+ limits.BasicLimitInformation.ActiveProcessLimit = maxProcesses;
403
+ }
404
+ limits.BasicLimitInformation.LimitFlags = limitFlags;
343
405
  if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, ref limits, (uint)Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION))))
344
406
  return Fail(dir, "SetInformationJobObject", Marshal.GetLastWin32Error());
407
+ if (memoryBytes > 0)
408
+ {
409
+ iocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE, IntPtr.Zero, UIntPtr.Zero, 1);
410
+ if (iocp != IntPtr.Zero)
411
+ {
412
+ JOBOBJECT_ASSOCIATE_COMPLETION_PORT assoc = new JOBOBJECT_ASSOCIATE_COMPLETION_PORT();
413
+ assoc.CompletionKey = job;
414
+ assoc.CompletionPort = iocp;
415
+ if (!SetInformationJobObject(job, JobObjectAssociateCompletionPortInformation, ref assoc, (uint)Marshal.SizeOf(typeof(JOBOBJECT_ASSOCIATE_COMPLETION_PORT))))
416
+ {
417
+ CloseHandle(iocp);
418
+ iocp = IntPtr.Zero;
419
+ }
420
+ }
421
+ }
422
+ if (cpuRate > 0)
423
+ {
424
+ JOBOBJECT_CPU_RATE_CONTROL_INFORMATION cpuLimits = new JOBOBJECT_CPU_RATE_CONTROL_INFORMATION();
425
+ cpuLimits.ControlFlags = JOB_OBJECT_CPU_RATE_CONTROL_ENABLE | JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP;
426
+ cpuLimits.CpuRate = cpuRate > 10000u ? 10000u : cpuRate;
427
+ if (!SetInformationJobObject(job, JobObjectCpuRateControlInformation, ref cpuLimits, (uint)Marshal.SizeOf(typeof(JOBOBJECT_CPU_RATE_CONTROL_INFORMATION))))
428
+ return Fail(dir, "SetInformationJobObject(CpuRate)", Marshal.GetLastWin32Error());
429
+ }
345
430
 
346
431
  SECURITY_ATTRIBUTES inherit = new SECURITY_ATTRIBUTES();
347
432
  inherit.nLength = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES));
@@ -436,15 +521,46 @@ public static class DsaJob
436
521
  }
437
522
  string stopPath = Path.Combine(dir, "stop");
438
523
  bool stopped = false;
524
+ bool memoryLimitNotified = false;
439
525
  for (;;)
440
526
  {
527
+ if (iocp != IntPtr.Zero)
528
+ {
529
+ uint msg; UIntPtr key; IntPtr ov;
530
+ while (GetQueuedCompletionStatus(iocp, out msg, out key, out ov, 0))
531
+ {
532
+ if (msg == JOB_OBJECT_MSG_JOB_MEMORY_LIMIT) memoryLimitNotified = true;
533
+ }
534
+ }
441
535
  uint waited = WaitForSingleObject(child.hProcess, 50);
442
536
  if (waited == WAIT_OBJECT_0) break;
443
537
  if (waited != WAIT_TIMEOUT) return Fail(dir, "WaitForSingleObject", Marshal.GetLastWin32Error());
444
538
  if (File.Exists(stopPath)) { stopped = true; break; }
445
539
  }
540
+ if (iocp != IntPtr.Zero)
541
+ {
542
+ uint msg; UIntPtr key; IntPtr ov;
543
+ while (GetQueuedCompletionStatus(iocp, out msg, out key, out ov, 0))
544
+ {
545
+ if (msg == JOB_OBJECT_MSG_JOB_MEMORY_LIMIT) memoryLimitNotified = true;
546
+ }
547
+ }
446
548
  uint code = 1;
447
549
  if (!stopped && !GetExitCodeProcess(child.hProcess, out code)) return Fail(dir, "GetExitCodeProcess", Marshal.GetLastWin32Error());
550
+ if (!stopped && memoryBytes > 0 && code != 0)
551
+ {
552
+ // Require an actual kernel memory-limit notification or OOM NTSTATUS so unrelated non-zero exits
553
+ // are never misclassified as OOM merely because peak memory touched the ceiling earlier.
554
+ bool hit = memoryLimitNotified || code == 0xC000012Du || code == 0xC0000017u;
555
+ if (hit)
556
+ {
557
+ ulong peak = 0;
558
+ JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
559
+ if (QueryInformationJobObject(job, JobObjectExtendedLimitInformation, out info, (uint)Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION)), IntPtr.Zero))
560
+ peak = info.PeakJobMemoryUsed.ToUInt64();
561
+ try { WriteAtomic(Path.Combine(dir, "limit-exceeded"), @"{""kind"":""memory"",""peakBytes"":" + peak.ToString(CultureInfo.InvariantCulture) + "}"); } catch (Exception) { }
562
+ }
563
+ }
448
564
  DrainJob(job);
449
565
  if (!stopped)
450
566
  {
@@ -472,6 +588,7 @@ public static class DsaJob
472
588
  if (block != IntPtr.Zero) Marshal.FreeHGlobal(block);
473
589
  // The group's only handle (non-inherited): closing it kills every process the command left behind.
474
590
  if (job != IntPtr.Zero) CloseHandle(job);
591
+ if (iocp != IntPtr.Zero) CloseHandle(iocp);
475
592
  }
476
593
  }
477
594
 
@@ -674,6 +791,8 @@ export const JOB_HOST_EXIT = "host-exit";
674
791
  export const JOB_SPEC = "job.json";
675
792
  /** The spec's first line: the owner refuses a file it does not recognize. */
676
793
  export const JOB_SPEC_HEADER = "DSAJOB1";
794
+ /** Spec header when OS kernel Job Object resource limits are attached. */
795
+ export const JOB_SPEC_HEADER_V2 = "DSAJOB2";
677
796
  /** Written (atomically) after the wrapper is in the group and before it may run: `{"pid":<wrapper pid>}`. */
678
797
  export const JOB_GROUP = "group";
679
798
  /** Written when the owner saw the wrapper end: `{"status":<wrapper exit status>}`. */
@@ -682,6 +801,8 @@ export const JOB_END = "group-end";
682
801
  export const JOB_ERROR = "start-error";
683
802
  /** Written (atomically) by a caller requesting a controlled stop so the owner calls DrainJob and exits without `group-end`. */
684
803
  export const JOB_STOP = "stop";
804
+ /** Written (atomically) when the Windows Job Object kernel memory hard cap was hit before the wrapper exited. */
805
+ export const JOB_LIMIT_EXCEEDED = "limit-exceeded";
685
806
  /** Written by the owner's first statement: its absence proves the program never ran (a launcher problem, not a failure
686
807
  * of this attempt), which is what a bare "the owner ended" otherwise hides. */
687
808
  export const JOB_BEGIN = "helper-begin";
@@ -729,8 +850,14 @@ export function jobEnv(env) {
729
850
  * code unit, and refuses a field that is not a whole number of them. */
730
851
  export function jobSpecText(launch) {
731
852
  const env = jobEnv(launch.env);
732
- const lines = [JOB_SPEC_HEADER, field(launch.exe), field(launch.cwd), field(launch.log), String(launch.args.length),
733
- ...launch.args.map(field), String(env.length), ...env.map(field)];
853
+ const lim = launch.limits;
854
+ const memBytes = lim?.memoryMb !== undefined ? clampMemoryBytes(lim.memoryMb) : 0;
855
+ const maxProcs = lim?.maxProcesses !== undefined && lim.maxProcesses >= 1 ? Math.floor(lim.maxProcesses) : 0;
856
+ const cpuRate = lim?.cpuPercent !== undefined && lim.cpuPercent > 0 ? winCpuRate(lim.cpuPercent) : 0;
857
+ const hasLimits = memBytes > 0 || maxProcs > 0 || cpuRate > 0;
858
+ const lines = [hasLimits ? JOB_SPEC_HEADER_V2 : JOB_SPEC_HEADER, field(launch.exe), field(launch.cwd), field(launch.log), String(launch.args.length),
859
+ ...launch.args.map(field), String(env.length), ...env.map(field),
860
+ ...(hasLimits ? [String(memBytes), String(maxProcs), String(cpuRate)] : [])];
734
861
  return `${lines.join("\n")}\n`;
735
862
  }
736
863
  const field = (text) => Buffer.from(text, "utf16le").toString("base64");
@@ -807,7 +934,7 @@ export const prepareCancelled = (error) => error instanceof JobPrepareCancelled
807
934
  * or a {@link JobPrepareCancelled} (nothing was recorded and nothing stays). */
808
935
  export async function prepareJob(dir, launch, options = {}) {
809
936
  // Evidence of an earlier attempt in the same directory must never be read as this attempt's.
810
- for (const name of [JOB_BEGIN, JOB_GROUP, JOB_END, JOB_ERROR, JOB_STOP, JOB_HOST_EXIT, JOB_HOST_LOG])
937
+ for (const name of [JOB_BEGIN, JOB_GROUP, JOB_END, JOB_ERROR, JOB_STOP, JOB_LIMIT_EXCEEDED, JOB_HOST_EXIT, JOB_HOST_LOG])
811
938
  await rm(join(dir, name), { force: true });
812
939
  const host = await compileJobHost(dir, { ...(options.compiler ? { compiler: options.compiler } : {}),
813
940
  ...(options.compileMs ? { timeoutMs: options.compileMs } : {}), ...(options.signal ? { signal: options.signal } : {}),
@@ -1002,6 +1129,17 @@ function parseGroupText(text) {
1002
1129
  return { pid: parsed.pid, ...(start ? { start } : {}), ...(group ? { group } : {}) };
1003
1130
  }
1004
1131
  /** The group record written before ResumeThread (with legacy `{"pid":<n>}` compatibility); undefined while not ready. */
1132
+ /** Read a Windows Job Object `limit-exceeded` marker written by DsaJob.exe, if present. Never throws. */
1133
+ export async function readJobLimitExceeded(dir, options = {}) {
1134
+ try {
1135
+ const text = await retryWinSharing(() => readFile(join(dir, JOB_LIMIT_EXCEEDED), "utf8"), { timeoutMs: 250, maxAttempts: 6, ...options });
1136
+ const raw = JSON.parse(text);
1137
+ if (typeof raw.kind === "string")
1138
+ return { kind: raw.kind, peakBytes: Number(raw.peakBytes) || 0 };
1139
+ }
1140
+ catch { /* absent or unreadable */ }
1141
+ return undefined;
1142
+ }
1005
1143
  export async function readGroupRecord(dir, options = {}) {
1006
1144
  const readFn = options.readFile ?? ((path) => readFile(path, "utf8"));
1007
1145
  let text;