Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(minions): --max-rss caps each job child's process tree under process isolation (GBRA-133)

garrytan70e0762410d7
diff --git a/docs/guides/minions-deployment.md b/docs/guides/minions-deployment.md
index 918bc3ed25..fc08d2cc6e 100644
--- a/docs/guides/minions-deployment.md
+++ b/docs/guides/minions-deployment.md
@@ -166,11 +166,12 @@ Sizing notes:
real server backend while open. Budget the pooler-lane count against your
pooler's client limit and the session-lane count against
`max_connections`.
-- **Memory:** `--max-rss` covers the WORKER process only in this mode
- (handler memory lives in the children; the worker prints a note when both
- are set). There is no per-child RSS cap yet — a runaway child is contained
- only by host/container limits. Size host memory for concurrency × handler
- footprint.
+- **Memory:** `--max-rss` applies to the worker and, separately, to each
+ job child's process tree (RssAnon + RssShmem, measured every 5 s). A child
+ past the cap gets SIGTERM, then SIGKILL after the 25 s grace, and its
+ attempt fails with `ChildRssLimitError`, so a job that grows the same way
+ on every retry ends at its `max_attempts` instead of exhausting the host.
+ Size host memory for (concurrency + 1) × the cap.
- **Spawn cost:** ~0.3–1s per job (engine connect included) — noise for
long-running handlers, meaningful for sub-second ones (`lint`,
`backlinks`). Keep those inline or on a separate inline worker.
diff --git a/src/commands/jobs/work.ts b/src/commands/jobs/work.ts
index 088c25d55a..ddd48db5c5 100644
--- a/src/commands/jobs/work.ts
+++ b/src/commands/jobs/work.ts
@@ -142,9 +142,9 @@ export async function runJobsWork({ args, engine, queue }: JobsCommandContext):
childTiniPath = detectTini();
if (maxRssMb > 0) {
console.error(
- '[gbrain jobs] note: with process isolation on, the --max-rss watchdog covers the ' +
- 'WORKER process only — handler memory now lives in job children. Per-child caps are ' +
- 'a filed follow-up; size host memory for concurrency x handler footprint.',
+ `[gbrain jobs] note: with process isolation on, --max-rss ${maxRssMb} MB applies to the worker and to each ` +
+ 'job child\'s process tree separately; a child past it is stopped and its attempt fails. ' +
+ 'Size host memory for (concurrency + 1) x the cap.',
);
}
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 1946b434de..d78b75c359 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1215,6 +1215,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.424.0', text: 'A Git or mirror effect that finds its canonical worktree held by another gbrain process now waits for it (up to 5 seconds per pass) instead of trying once between that process\'s writes, and once it has waited a second the other process yields: its lane leases drain and its no-wait takes report busy until the effect took its turn. Before, a long sync in one process could win every race for the worktree, so another process\'s backlog of Git effects never ran. Waiters mark themselves beside the worktree\'s coordination lock (`<lock>.waiters/<pid>`); a marker its process stopped refreshing is ignored.' },
{ since: '0.60.424.0', text: 'An effect that still finds its worktree busy retries as `writer_busy` with a backoff that grows per consecutive busy retry (250 ms doubling to 60 s) instead of every 250 ms, and it never parks on contention. While it waits its data records `busy_retries`, `busy_since` and `busy_at`; they are dropped when it completes.' },
{ since: '0.60.424.0', text: 'doctor `parked_effects` and `gbrain sources writer status` now report `stalled_catchups`: per source, effects that have waited on a busy canonical worktree for over 10 minutes, with when the wait began and the read-only writer status command that shows who holds the worktree. doctor warns "Catch-up not progressing" for them even when nothing is parked.' },
+ { since: 'TBD', text: 'With `--job-isolation process`, `--max-rss` now caps each job child too: the worker measures the child\'s process tree (RssAnon + RssShmem) every 5 seconds, and a child past the cap gets SIGTERM, then SIGKILL after the 25-second grace. Its attempt fails with `ChildRssLimitError`, so a job that grows the same way on every retry ends at its `max_attempts`. Before, the cap read only the worker\'s own memory, and a runaway child grew until the host or container limit restarted every process.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/minions/child-job-runner.ts b/src/core/minions/child-job-runner.ts
index 1cf703d483..8d64d864f1 100644
--- a/src/core/minions/child-job-runner.ts
+++ b/src/core/minions/child-job-runner.ts
@@ -60,6 +60,7 @@ import {
killProcessGroup,
observeTiniChildProcessGroups,
captureChildCleanup,
+ childTreeRss,
confirmChildCleanup,
validateChildExecutable,
type ChildCleanupSnapshot,
@@ -84,6 +85,21 @@ export class ChildWorkerShutdownError extends Error {
}
}
+/** How often the worker measures a job child's tree against --max-rss. */
+export const CHILD_RSS_CHECK_MS = 5_000;
+
+/**
+ * GBRA-133: the job child's process tree passed the worker's --max-rss, so the worker stopped it (group SIGTERM, then
+ * SIGKILL after the grace). The job's own memory ran away, so the attempt counts: the queue's backoff and max_attempts
+ * bound a job that grows the same way on every retry instead of letting it restart the host.
+ */
+export class ChildRssLimitError extends Error {
+ constructor(readonly rssMb: number, readonly maxRssMb: number) {
+ super(`job child used ${rssMb} MB (RssAnon+RssShmem over its process tree), past the worker's --max-rss ${maxRssMb} MB; the worker stopped it`);
+ this.name = 'ChildRssLimitError';
+ }
+}
+
/** Child found the job reclaimed/cancelled (exit 14) — provably owned
* elsewhere. The worker releases without failJob (the fenced failJob would
* no-op anyway); definitely not an attempt against THIS claim. */
@@ -130,6 +146,12 @@ export interface RunJobInChildOpts {
signalProcessGroup?: typeof killProcessGroup;
onConfigurationError?: (error: LocalConfigurationError) => void;
onExecutionStopped?: () => void;
+ /** GBRA-133: the worker's --max-rss in MB, applied to the child's process tree (0 or absent: no cap). */
+ maxRssMb?: number;
+ /** Injectable for tests. Default CHILD_RSS_CHECK_MS. */
+ rssCheckIntervalMs?: number;
+ /** Injectable for tests. Default childTreeRss (Linux /proc). */
+ readChildRss?: (pid: number, groups: Set<number>) => number | null;
}
interface ChildExit {
@@ -174,6 +196,27 @@ export async function runJobInChild(opts: RunJobInChildOpts): Promise<unknown> {
}
}
+/**
+ * GBRA-133: measures the child's process tree every `rssCheckIntervalMs` and calls `stop` once it passes `maxRssMb`
+ * (no timer without a cap, a pid or a readable process table).
+ */
+function watchChildRss(opts: RunJobInChildOpts, pid: number | undefined, groups: Set<number>, stopping: () => boolean,
+ stop: (error: ChildRssLimitError) => void): ReturnType<typeof setInterval> | null {
+ const maxRssMb = opts.maxRssMb ?? 0;
+ if (maxRssMb <= 0 || pid == null) return null;
+ const timer = setInterval(() => {
+ if (stopping()) return;
+ const bytes = (opts.readChildRss ?? childTreeRss)(pid, groups);
+ if (bytes === null) return;
+ const rssMb = Math.round(bytes / (1024 * 1024));
+ if (rssMb <= maxRssMb) return;
+ console.warn(`[watchdog] job ${opts.jobId} (${opts.jobName}) child pid ${pid} rss=${rssMb}MB threshold=${maxRssMb}MB — stopping the child`);
+ stop(new ChildRssLimitError(rssMb, maxRssMb));
+ }, opts.rssCheckIntervalMs ?? CHILD_RSS_CHECK_MS);
+ timer.unref();
+ return timer;
+}
+
async function runJobChildProcess(opts: RunJobInChildOpts): Promise<unknown> {
const base = opts.env ?? process.env;
let executable: string;
@@ -343,6 +386,8 @@ async function runJobChildProcess(opts: RunJobInChildOpts): Promise<unknown> {
else opts.abortSignal.addEventListener('abort', onAbort, { once: true });
if (opts.shutdownSignal.aborted) onShutdown();
else opts.shutdownSignal.addEventListener('abort', onShutdown, { once: true });
+ let rssStop: ChildRssLimitError | null = null;
+ const rssTimer = watchChildRss(opts, child.pid, processGroups, () => termed, error => { rssStop = error; terminate(); });
console.log(
`[isolation] job ${opts.jobId} (${opts.jobName}) child pid ${child.pid ?? '?'} spawned`,
@@ -404,6 +449,7 @@ async function runJobChildProcess(opts: RunJobInChildOpts): Promise<unknown> {
}
// No usable outcome. Classify by WHY the child died.
if (decodeErr instanceof UnrecoverableError) throw decodeErr; // oversize cap — dead on attempt 1
+ if (rssStop) throw rssStop;
if (isShutdownClass) {
throw new ChildWorkerShutdownError(
`job child terminated by worker shutdown before reporting (exit code=${exit.code} signal=${exit.signal})`,
@@ -438,6 +484,7 @@ async function runJobChildProcess(opts: RunJobInChildOpts): Promise<unknown> {
}
if (outcome.outcome === 'success') return outcome.result;
+ if (rssStop) throw rssStop;
const handlerError = reconstructHandlerError(outcome);
if (isLocalConfigurationError(handlerError)) {
opts.onConfigurationError?.(handlerError);
@@ -463,6 +510,7 @@ async function runJobChildProcess(opts: RunJobInChildOpts): Promise<unknown> {
if (naturalCleanupConfirmed) publishExecutionStopped();
if (killTimer != null) clearTimeout(killTimer);
if (groupObserver != null) clearInterval(groupObserver);
+ if (rssTimer != null) clearInterval(rssTimer);
opts.abortSignal.removeEventListener('abort', onAbort);
opts.shutdownSignal.removeEventListener('abort', onShutdown);
rmSync(dir, { recursive: true, force: true });
diff --git a/src/core/minions/job-isolation.ts b/src/core/minions/job-isolation.ts
index 263585f9d5..748232f56e 100644
--- a/src/core/minions/job-isolation.ts
+++ b/src/core/minions/job-isolation.ts
@@ -43,6 +43,7 @@ import { RateLeaseUnavailableError } from './handlers/subagent.ts';
import { SpendGroupRefusedError, type SpendRefusalEnvelope } from './spend-authorization.ts';
import { LocalConfigurationError, isLocalConfigurationError } from './configuration-error.ts';
import { basename, delimiter, resolve, win32 } from 'node:path';
+import { readProcessRss } from './proc-rss.ts';
/** Grace between group-SIGTERM and group-SIGKILL on abort. Deliberately
* inside the worker's 30s force-evict window so the evict path stays a
@@ -389,6 +390,16 @@ export function captureChildCleanup(pid: number, groups: Set<number>): ChildClea
};
}
+/**
+ * GBRA-133: RssAnon + RssShmem summed over a job child's whole tree (the tini wrapper, the handler process and anything it
+ * spawned), in bytes; null where the process table cannot be read (non-Linux), so the caller applies no cap it cannot measure.
+ */
+export function childTreeRss(pid: number, groups: Set<number>, readRss: (pid: number) => number | null = readProcessRss): number | null {
+ const tree = captureChildCleanup(pid, groups).observed.filter(entry => entry.state !== 'Z' && entry.state !== 'X');
+ if (!tree.length) return null;
+ return tree.reduce((sum, entry) => sum + (readRss(entry.pid) ?? 0), 0);
+}
+
export function confirmChildCleanup(snapshot: ChildCleanupSnapshot): boolean {
if (!snapshot.supported) return false;
const entries = readProcessSnapshot();
diff --git a/src/core/minions/proc-rss.ts b/src/core/minions/proc-rss.ts
new file mode 100644
index 0000000000..0178e8cc2a
--- /dev/null
+++ b/src/core/minions/proc-rss.ts
@@ -0,0 +1,38 @@
+/**
+ * Resident memory as the RSS watchdogs count it: RssAnon + RssShmem from /proc/<pid>/status, the non-file-backed pages a
+ * leak grows (file-backed mappings such as Git packfiles are cache the kernel reclaims). The worker reads its own; since
+ * GBRA-133 the worker also reads each job child's process tree (child-job-runner.ts), so --max-rss bounds a run-child too.
+ */
+import { readFileSync } from 'node:fs';
+
+/**
+ * Pure parser for /proc/self/status RSS fields. Returns bytes of
+ * RssAnon + RssShmem when either field is present, or null when the
+ * status text is from a kernel that doesn't expose those fields
+ * (kernels older than 4.5) or the values are malformed. Exported so
+ * the test suite can unit-test the field-presence + malformed-value
+ * edge cases without mocking the filesystem.
+ *
+ * M1 fix: field-presence check, not value-presence check. The earlier
+ * `if (anonKb > 0)` form conflated "field exists with value 0" with
+ * "field missing", which mis-routed to VmRSS fallback in the legitimate
+ * shmem-only worker case (RssAnon: 0 + RssShmem: 512).
+ */
+export function parseRssFromProcStatus(status: string): number | null {
+ const anonMatch = status.match(/^RssAnon:\s+(\d+)/m);
+ const shmemMatch = status.match(/^RssShmem:\s+(\d+)/m);
+ if (anonMatch === null && shmemMatch === null) {
+ return null;
+ }
+ const anonKb = parseInt(anonMatch?.[1] ?? '0', 10);
+ const shmemKb = parseInt(shmemMatch?.[1] ?? '0', 10);
+ if (isNaN(anonKb) || isNaN(shmemKb)) {
+ return null;
+ }
+ return (anonKb + shmemKb) * 1024; // bytes
+}
+
+/** RssAnon + RssShmem of one process in bytes, or null when it is gone or the kernel does not report the fields. */
+export function readProcessRss(pid: number, readStatus: (pid: number) => string = p => readFileSync(`/proc/${p}/status`, 'utf8')): number | null {
+ try { return parseRssFromProcStatus(readStatus(pid)); } catch { return null; }
+}
diff --git a/src/core/minions/worker.ts b/src/core/minions/worker.ts
index a967d828d7..d013449aa4 100644
--- a/src/core/minions/worker.ts
+++ b/src/core/minions/worker.ts
@@ -93,33 +93,9 @@ import { jobOutcomeResult, jobResultOutcome } from './job-outcome.ts';
import { DEFAULT_LONG_JOB_NAMES, DEFAULT_SHORT_JOB_RESERVED_SLOTS, claimExclusions } from './lanes.ts';
import { jobRefusal, refusedJobResult } from './refusal.ts';
import { readFileSync } from 'fs';
+import { parseRssFromProcStatus } from './proc-rss.ts';
-/**
- * Pure parser for /proc/self/status RSS fields. Returns bytes of
- * RssAnon + RssShmem when either field is present, or null when the
- * status text is from a kernel that doesn't expose those fields
- * (kernels older than 4.5) or the values are malformed. Exported so
- * the test suite can unit-test the field-presence + malformed-value
- * edge cases without mocking the filesystem.
- *
- * M1 fix: field-presence check, not value-presence check. The earlier
- * `if (anonKb > 0)` form conflated "field exists with value 0" with
- * "field missing", which mis-routed to VmRSS fallback in the legitimate
- * shmem-only worker case (RssAnon: 0 + RssShmem: 512).
- */
-export function parseRssFromProcStatus(status: string): number | null {
- const anonMatch = status.match(/^RssAnon:\s+(\d+)/m);
- const shmemMatch = status.match(/^RssShmem:\s+(\d+)/m);
- if (anonMatch === null && shmemMatch === null) {
- return null;
- }
- const anonKb = parseInt(anonMatch?.[1] ?? '0', 10);
- const shmemKb = parseInt(shmemMatch?.[1] ?? '0', 10);
- if (isNaN(anonKb) || isNaN(shmemKb)) {
- return null;
- }
- return (anonKb + shmemKb) * 1024; // bytes
-}
+export { parseRssFromProcStatus };
/**
* Read accurate RSS from /proc/self/status (RssAnon + RssShmem).
@@ -1547,7 +1523,7 @@ export class MinionWorker extends EventEmitter {
abortSignal: abort.signal,
shutdownSignal: this.shutdownAbort.signal,
invocation: this.opts.childCliInvocation as { cmd: string; argsPrefix: string[] },
- tiniPath: this.opts.childTiniPath,
+ tiniPath: this.opts.childTiniPath, maxRssMb: this.opts.maxRssMb,
onExecutionStopped: () => {
childExecutionStopped = true;
const execution = this.executions.get(lockToken);
diff --git a/test/child-job-rss-cap-gbra133.test.ts b/test/child-job-rss-cap-gbra133.test.ts
new file mode 100644
index 0000000000..72068c4e5b
--- /dev/null
+++ b/test/child-job-rss-cap-gbra133.test.ts
@@ -0,0 +1,61 @@
+/**
+ * GBRA-133: --max-rss bounds a job child too. With process isolation on, handler memory lives in `jobs run-child`, and the
+ * worker's watchdog read only the worker's own /proc entry, so a child that grew without bound (a managed sync pass
+ * importing a whole large tree) ran until the container's memory limit restarted every process. The worker now measures
+ * the child's process tree (RssAnon + RssShmem) and stops it past the same cap; the attempt counts.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { ChildRssLimitError, runJobInChild } from '../src/core/minions/child-job-runner.ts';
+import { childTreeRss } from '../src/core/minions/job-isolation.ts';
+
+let dir: string;
+beforeAll(() => { dir = mkdtempSync(join(tmpdir(), 'gbrain-child-rss-')); });
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+/** A child that holds `mb` of anonymous memory, then reports success after `ms` (or never, with ms < 0). */
+function harness(name: string, mb: number, ms: number): string {
+ const path = join(dir, `${name}.mjs`);
+ writeFileSync(path, `import { writeFileSync, renameSync } from 'node:fs';
+const RESULT = process.env.GBRAIN_JOB_RESULT_PATH;
+const held = []; for (let i = 0; i < ${mb}; i++) held.push(Buffer.alloc(1024 * 1024, 1));
+globalThis.held = held;
+if (${ms} >= 0) setTimeout(() => { writeFileSync(RESULT + '.tmp', JSON.stringify({ outcome: 'success', result: { ok: true } })); renameSync(RESULT + '.tmp', RESULT); process.exit(0); }, ${ms});
+else setInterval(() => {}, 1000);
+`);
+ return path;
+}
+
+const opts = (path: string) => ({ jobId: 4242, jobName: 'sync', lockToken: 'tok-rss', abortSignal: new AbortController().signal, shutdownSignal: new AbortController().signal,
+ invocation: { cmd: process.execPath, argsPrefix: [path] }, tiniPath: '', killGraceMs: 2_000, rssCheckIntervalMs: 100 });
+
+test.skipIf(process.platform !== 'linux')('a job child past --max-rss is stopped and the attempt fails with ChildRssLimitError', async () => {
+ const started = Date.now();
+ const error = await runJobInChild({ ...opts(harness('grows', 400, 8_000)), maxRssMb: 200 }).then(() => null, (e: unknown) => e);
+ expect(error).toBeInstanceOf(ChildRssLimitError);
+ expect((error as ChildRssLimitError).maxRssMb).toBe(200);
+ expect((error as ChildRssLimitError).rssMb).toBeGreaterThan(200);
+ // Stopped by the cap, not after the child's own 8 s.
+ expect(Date.now() - started).toBeLessThan(7_000);
+}, 30_000);
+
+test.skipIf(process.platform !== 'linux')('a child that ignores SIGTERM past the cap is SIGKILLed at the grace', async () => {
+ const path = join(dir, 'stubborn.mjs');
+ writeFileSync(path, "process.on('SIGTERM', () => {}); const held = []; for (let i = 0; i < 300; i++) held.push(Buffer.alloc(1024 * 1024, 1)); globalThis.held = held; setInterval(() => {}, 1000);\n");
+ const started = Date.now();
+ await expect(runJobInChild({ ...opts(path), maxRssMb: 150 })).rejects.toBeInstanceOf(ChildRssLimitError);
+ expect(Date.now() - started).toBeLessThan(10_000);
+}, 30_000);
+
+test.skipIf(process.platform !== 'linux')('a child under the cap, and a worker without one, run to their result', async () => {
+ expect(await runJobInChild({ ...opts(harness('small', 20, 500)), maxRssMb: 1024 })).toEqual({ ok: true });
+ expect(await runJobInChild({ ...opts(harness('uncapped', 300, 500)) })).toEqual({ ok: true });
+}, 30_000);
+
+test.skipIf(process.platform !== 'linux')('childTreeRss sums RssAnon+RssShmem over the tree and is null for a process table without it', () => {
+ const own = childTreeRss(process.pid, new Set([process.pid]), pid => pid === process.pid ? 7 * 1024 * 1024 : 0);
+ expect(own).toBe(7 * 1024 * 1024);
+ expect(childTreeRss(2 ** 22 + 12345, new Set([2 ** 22 + 12345]), () => 1)).toBeNull();
+});