Repository navigation
feat(cron): add up to eight runs past the default when memory is free - #197394
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: blocked before merge. What this changesThis PR allows each queue drain to admit one extra automation when at least 1 GiB is available, up to sixteen concurrent runs. Example: Twelve automation jobs become due with 3.3 GiB available.
Review scores
ProductKind: Feature · Worth it: Needs a maintainer decision · Fix scope: Partial Merge readiness⛔ Blocked before merge - 1 item remains Keep open: this PR contains a focused, demonstrated throughput improvement with no actionable code findings, but changing the default cron-and-hook capacity budget still needs a maintainer decision. Priority: P2 Decision needed
Before merge
FindingsNone. Agent review detailsHow this fits togetherThe Gateway supplies memory availability to the SQLite-owned cron queue, which selects scheduled and requested runs; agent payloads then enter command lanes sharing capacity with hook dispatch. flowchart TD
A[Scheduled and requested jobs] --> B[Gateway memory reading]
B --> C[Worker run queue]
C --> D[Automation execution]
D --> E[Shared command capacity]
F[Hook dispatch] --> E
Technical reviewBest possible solution: Retain the existing worker-owned admission design and obtain an explicit decision on its proposed automatic expansion and shared hook budget. Do we have a high-confidence way to reproduce the issue? Current-main source enforces eight runs, and the contributor's comparative Gateway traces demonstrate that limit and the proposed expansion; this review executed no target code. Is this the best way to solve the issue? The patch uses the existing admission owner with one shared memory reader and no new timer or persistence format, making it a small implementation of the proposed policy rather than a fix for the linked issue's entire monitoring problem. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against dab086c0d82b. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +35, Tests +58, Docs +1. Total +94 across 19 files. Added test files: 0. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (19 earlier review cycles; latest 8 shown)
Reviewed November 17, 2026, 9:22 AM ET / 14:22 UTC (Revision 20). |
6dcae75 to
1997e68
Compare
|
The parent-replacement result reflects existing main behavior for parents without a workspace binding. The slot wait lengthens the window; it does not introduce the behavior. Optional hardening is for maintainers and is not a blocker for this PR. Proof used a synthetic model and focused integration harness. Requester revocation remains inconclusive; stored-data upgrade was not run. |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
🦞👀 Re-review progress:
|
On Linux the exec budget comes from the test host's cgroup, so in a 2 GiB container admission capped at three runs and cases waiting for four or more timed out. The fixture now reads no exec budget, as off Linux; cases about exec memory set their own reading.
The case fakes the cgroup files below the root, but the walk also reads /sys/fs/cgroup/memory.max, which in a memory-limited container is that container's limit: at 4 GiB it admitted four runs instead of five.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Raise the fixed cron limit from 8 to 16 and add a free-memory gate in the form of GNU parallel's --memfree: while less than 4 GiB is free on the host, under the Gateway's cgroup v2 limits, or in the exec memory budget, no further run starts, and one may always run. 4 GiB holds a full burst of 16 runs at 256 MiB, since a drain starts all due runs at once, before their memory shows. Drop sharing the agent concurrency limit with conversations and the per-run memory figure; keep the cgroup and exec memory readers. Hook dispatch shares the cron budget again, as on main.
Keep the eight default automation run slots. While all eight are busy and runs are queued, each drain of the run queue starts one more run if process.availableMemory() reads at least 1 GiB, up to 16 at once. The reading counts a cgroup memory limit. Drains already follow run ends and due jobs, so there is no timer. Drop the 4 GiB threshold, serial mode, the cgroup parser, the exec memory reader and the per-minute recheck. The cron lane and the shared cron and hook budget widen to 16 so extra runs can execute; hook dispatch keeps its width of eight. Tests that fill exactly the eight default slots mock the memory reading.
The fixture fills the eight default run slots and expects the next run to queue. With memory to spare, as on CI, the queue admits an extra run, so the fixture reads no spare memory like the other slot-filling tests.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Gateway proof at 7872ef0Real isolated Gateways built from this head (
What this shows:
How memory was steered: a macOS guest swaps rather than staying under 1 GiB (with 6.7 GiB of random pages held, Node's reading dipped to 0.65 GiB and was back at 2 GiB five seconds later). For the low-memory steps only, the Gateway process was started with a scenario preload that makes Fresh install: each run starts the Gateway, adds the 14 jobs, stops it and starts it again on the same state. All 14 jobs (id, name, enabled, schedule, payload, delivery) were unchanged after the restart, and the config file kept the same SHA-256, on both builds. Upgrade from a released stable: not shown, and not caused by this PR. Starting this head on state written by the latest stable 2026.11.4 fails at startup with Redaction: temporary paths, the host name and the hook token are left out; no real provider, credential or account was used. Scenario script// Gateway scenario for openclaw/openclaw#197394: upgrade from the latest stable, then extra cron
// admission while memory is free, later drains, low-memory refusal and mixed hook capacity.
// Usage: node scenario.mjs <stable-openclaw.mjs> <head-openclaw.mjs> <out-dir>
import { spawn } from "node:child_process";
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { once } from "node:events";
import { mkdtemp, mkdir, readFile, writeFile } from "node:fs/promises";
import { createServer } from "node:http";
import { createRequire } from "node:module";
import os from "node:os";
import path from "node:path";
import { setTimeout as delay } from "node:timers/promises";
const [stableEntry, headEntry, out] = process.argv.slice(2).map((p) => path.resolve(p));
const require = createRequire(path.join(path.dirname(headEntry), "package.json"));
const WebSocket = require("ws");
await mkdir(out, { recursive: true });
const root = await mkdtemp(path.join(os.tmpdir(), "cron-197394-"));
await mkdir(root + "/home");
await mkdir(root + "/workspace");
const events = [];
const note = (kind, data = {}) => {
const e = { kind, at: new Date().toISOString(), ...data };
events.push(e);
console.log(JSON.stringify(e));
};
const gib = (b) => Math.round((b / 1024 ** 3) * 100) / 100;
// Synthetic model provider: every request stays open until the scenario releases its marker.
const open = new Map(); // marker -> release()
const model = createServer(async (req, res) => {
let raw = "";
for await (const c of req) raw += c;
if (!req.url.includes("chat/completions")) {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ object: "list", data: [{ id: "proof", object: "model" }] }));
return;
}
const body = JSON.parse(raw);
const marker = JSON.stringify(body.messages).match(/KZ_[a-z]+_\d+/g)?.at(-1) ?? "unknown";
await new Promise((resolve) => {
open.set(marker, resolve);
res.on("close", resolve);
});
open.delete(marker);
if (res.destroyed) return;
const usage = { prompt_tokens: 2, completion_tokens: 2, total_tokens: 4 };
const chunk = (delta, finish) =>
"data: " +
JSON.stringify({
id: "kz",
object: "chat.completion.chunk",
created: 1,
model: "proof",
choices: [{ index: 0, delta, finish_reason: finish }],
...(finish ? { usage } : {}),
}) +
"\n\n";
if (body.stream) {
res.writeHead(200, { "Content-Type": "text/event-stream" });
res.write(chunk({ role: "assistant", content: "Done" }, null));
res.write(chunk({}, "stop"));
res.end("data: [DONE]\n\n");
} else {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
id: "kz",
object: "chat.completion",
created: 1,
model: "proof",
choices: [{ index: 0, message: { role: "assistant", content: "Done" }, finish_reason: "stop" }],
usage,
}),
);
}
});
await new Promise((r) => model.listen(0, "127.0.0.1", r));
const release = (marker) => open.get(marker)?.();
const openOf = (kind) => [...open.keys()].filter((m) => m.startsWith("KZ_" + kind + "_")).length;
const reserve = createServer();
await new Promise((r) => reserve.listen(0, "127.0.0.1", r));
const port = reserve.address().port;
await new Promise((r) => reserve.close(r));
const hookToken = randomBytes(24).toString("hex");
const config = {
browser: { enabled: false },
update: { checkOnStart: false },
discovery: { mdns: { mode: "off" } },
gateway: {
mode: "local",
bind: "loopback",
auth: { mode: "none" },
controlUi: { enabled: false },
tailscale: { mode: "off" },
},
plugins: { enabled: false },
hooks: { enabled: true, token: hookToken, path: "/hooks", allowedAgentIds: ["main"] },
logging: { level: "info", file: root + "/runtime.log" },
agents: {
defaults: {
workspace: root + "/workspace",
model: { primary: "standin/proof" },
timeoutSeconds: 900,
},
entries: { main: {} },
},
models: {
mode: "merge",
providers: {
standin: {
baseUrl: `http://127.0.0.1:${model.address().port}/v1`,
apiKey: "synthetic-key",
api: "openai-completions",
timeoutSeconds: 900,
models: [
{
id: "proof",
name: "Synthetic local fixture",
reasoning: false,
input: ["text"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 120000,
maxTokens: 8192,
},
],
},
},
},
};
const configPath = root + "/config.json";
await writeFile(configPath, JSON.stringify(config, null, 2));
const env = {
HOME: root + "/home",
OPENCLAW_HOME: root + "/home",
OPENCLAW_STATE_DIR: root + "/state",
OPENCLAW_CONFIG_PATH: configPath,
PATH: process.env.PATH,
SHELL: "/bin/sh",
LANG: "en_US.UTF-8",
NO_COLOR: "1",
CI: "1",
OPENCLAW_NO_RESPAWN: "1",
OPENCLAW_SKIP_CHANNELS: "1",
npm_config_update_notifier: "false",
};
const memoryFile = root + "/memory-reading";
await writeFile(memoryFile, "");
env.CRON_PROOF_MEMORY_FILE = memoryFile;
const preload = path.join(path.dirname(new URL(import.meta.url).pathname), "memory-reading.mjs");
const hash = async (p) => createHash("sha256").update(await readFile(p)).digest("hex");
let gw;
let ws;
let seq = 0;
const pending = new Map();
let logs = "";
function rpc(method, params = {}, ms = 60000) {
return new Promise((resolve, reject) => {
const id = String(++seq);
const timer = setTimeout(() => {
pending.delete(id);
reject(Error("RPC timeout " + method));
}, ms);
pending.set(id, { resolve, reject, timer });
ws.send(JSON.stringify({ type: "req", id, method, params }));
});
}
async function startGateway(entry, label) {
logs += `\n--- ${label} ---\n`;
gw = spawn(process.execPath, ["--import", preload, entry, "gateway", "run", "--port", String(port)], {
cwd: path.dirname(entry),
env,
stdio: ["ignore", "pipe", "pipe"],
});
for (const s of [gw.stdout, gw.stderr]) s.on("data", (b) => (logs += b.toString()));
const until = Date.now() + 240000;
for (;;) {
if (gw.exitCode !== null) throw Error(`${label} exited ${gw.exitCode}: ${logs.slice(-2000)}`);
try {
if ((await fetch(`http://127.0.0.1:${port}/readyz`)).ok) break;
} catch {}
if (Date.now() > until) throw Error(label + " not ready");
await delay(500);
}
ws = new WebSocket(`ws://127.0.0.1:${port}`);
ws.on("error", () => {});
ws.on("message", (b) => {
const x = JSON.parse(b.toString());
if (x.type !== "res") return;
const p = pending.get(x.id);
if (!p) return;
clearTimeout(p.timer);
pending.delete(x.id);
x.ok ? p.resolve(x.payload) : p.reject(Error(JSON.stringify(x.error)));
});
await once(ws, "open");
const hello = await rpc("connect", {
minProtocol: 4,
maxProtocol: 4,
client: {
id: "gateway-client",
displayName: "Cron proof",
version: "1",
platform: process.platform,
mode: "backend",
instanceId: randomUUID(),
},
role: "operator",
scopes: ["operator.read", "operator.write", "operator.admin"],
});
note("gateway-ready", { label, version: hello.server?.version ?? hello.server });
}
async function stopGateway() {
ws?.terminate();
gw.kill("SIGTERM");
await Promise.race([once(gw, "exit"), delay(20000)]);
if (gw.exitCode === null && gw.signalCode === null) {
gw.kill("SIGKILL");
await once(gw, "exit");
}
}
const jobView = (j) => ({
id: j.id,
name: j.name,
enabled: j.enabled,
schedule: j.schedule,
payload: j.payload,
delivery: j.delivery,
});
async function counts(label) {
const listed = await rpc("cron.list", { includeDisabled: true }, 20000);
const jobs = listed.jobs ?? [];
const now = Date.now();
const c = {
label,
cronRunning: jobs.filter((j) => j.state?.runningAtMs).length,
cronDueNotStarted: jobs.filter(
(j) =>
!j.state?.runningAtMs &&
!j.state?.lastRunAtMs &&
((j.schedule?.kind === "at" && Date.parse(j.schedule.at) <= now) || j.state?.queuedAtMs),
).length,
cronQueued: jobs.filter((j) => j.state?.queuedAtMs).length,
cronModelTurnsOpen: openOf("job") + openOf("manual"),
hookModelTurnsOpen: openOf("hook"),
realAvailableMemoryGiB: gib(process.availableMemory()),
gatewayMemoryReadingGiB: (await readFile(memoryFile, "utf8")).trim()
? gib(Number(await readFile(memoryFile, "utf8")))
: "real",
};
note("counts", c);
return c;
}
async function settle(label, ms = 8000) {
await delay(ms);
return counts(label);
}
const summary = {};
try {
// 1. Latest stable: create jobs and settings.
await startGateway(stableEntry, "stable");
const due = Date.now() + 210000;
const ids = {};
for (let i = 0; i < 12; i++) {
const job = await rpc("cron.add", {
name: "timed-" + i,
agentId: "main",
enabled: true,
deleteAfterRun: false,
schedule: { kind: "at", at: new Date(due).toISOString() },
sessionTarget: "isolated",
payload: { kind: "agentTurn", message: "Reply briefly. KZ_job_" + i, timeoutSeconds: 900 },
delivery: { mode: "none" },
failureAlert: false,
});
ids["job_" + i] = job.id;
}
for (let i = 0; i < 2; i++) {
const job = await rpc("cron.add", {
name: "manual-" + i,
agentId: "main",
enabled: true,
deleteAfterRun: false,
schedule: { kind: "at", at: new Date(due + 86400000).toISOString() },
sessionTarget: "isolated",
payload: { kind: "agentTurn", message: "Reply briefly. KZ_manual_" + i, timeoutSeconds: 900 },
delivery: { mode: "none" },
failureAlert: false,
});
ids["manual_" + i] = job.id;
}
const before = ((await rpc("cron.list", { includeDisabled: true })).jobs ?? []).map(jobView);
await stopGateway();
const configBefore = await hash(configPath);
// 2. Upgrade in place to the PR head.
await startGateway(headEntry, "head");
const after = ((await rpc("cron.list", { includeDisabled: true })).jobs ?? []).map(jobView);
const byId = (list) => JSON.stringify([...list].sort((a, b) => a.id.localeCompare(b.id)));
summary.upgrade = {
jobsBefore: before.length,
jobsAfter: after.length,
jobsUnchanged: byId(before) === byId(after),
configUnchanged: configBefore === (await hash(configPath)),
headStartedBeforeDue: Date.now() < due,
};
note("upgrade", summary.upgrade);
await writeFile(out + "/jobs-before.json", JSON.stringify(before, null, 2));
await writeFile(out + "/jobs-after.json", JSON.stringify(after, null, 2));
// 3. Twelve jobs come due with memory free.
while (Date.now() < due + 2000) await delay(500);
summary.due = await settle("12 due, memory free");
// 4. Later drains: a newly requested run, then a run ending.
await rpc("cron.run", { id: ids.manual_0, mode: "force" });
summary.afterRequest = await settle("drain after a manual request, memory free");
release("KZ_job_0");
summary.afterRunEnd = await settle("drain after one run ends, memory free");
// 5. Low memory: a macOS guest swaps instead of staying under 1 GiB, so the Gateway's reading
// is pinned at 512 MiB through the preload while the queue works as shipped.
await writeFile(memoryFile, String(512 * 1024 ** 2));
summary.lowMemory = await settle("memory held under 1 GiB", 3000);
await rpc("cron.run", { id: ids.manual_1, mode: "force" });
summary.lowAfterRequest = await settle("drain after a manual request, memory under 1 GiB");
release("KZ_job_1");
summary.lowAfterRunEnd = await settle("drain after one run ends, memory under 1 GiB");
release("KZ_job_2");
summary.lowAfterSecondRunEnd = await settle("drain after another run ends, memory under 1 GiB");
await writeFile(memoryFile, "");
// 6. Mixed hook capacity: hook agent turns while automation holds its slots.
for (let i = 0; i < 10; i++) {
const res = await fetch(`http://127.0.0.1:${port}/hooks/agent`, {
method: "POST",
headers: { Authorization: `Bearer ${hookToken}`, "Content-Type": "application/json" },
body: JSON.stringify({
message: "Reply briefly. KZ_hook_" + i,
name: "hook-" + i,
agentId: "main",
deliver: false,
}),
});
note("hook-request", { i, status: res.status });
}
summary.hooks = await settle("10 hook requests, memory free", 15000);
// 7. Release everything and wait for terminal history.
const releaseAll = setInterval(() => [...open.keys()].forEach(release), 500);
const until = Date.now() + 300000;
let history;
for (;;) {
history = await rpc("cron.runs", { scope: "all", limit: 200 });
const done = new Set((history.entries ?? []).map((r) => r.jobId));
if (Object.values(ids).every((id) => done.has(id))) break;
if (Date.now() > until) throw Error("runs did not finish");
await delay(2000);
}
clearInterval(releaseAll);
const last = new Map((history.entries ?? []).map((r) => [r.jobId, r.status]));
summary.final = Object.fromEntries(
Object.entries(ids).map(([k, id]) => [k, last.get(id)]),
);
note("final", summary.final);
summary.ok = true;
} catch (error) {
summary.ok = false;
summary.error = String(error?.stack ?? error);
note("error", { error: summary.error, tail: logs.slice(-3000) });
process.exitCode = 1;
} finally {
[...open.keys()].forEach(release);
if (gw && gw.exitCode === null) await stopGateway().catch(() => {});
model.closeAllConnections();
model.close();
await writeFile(out + "/summary.json", JSON.stringify(summary, null, 2));
await writeFile(out + "/events.json", JSON.stringify(events, null, 2));
await writeFile(out + "/gateway.log", logs);
console.log("SCENARIO DONE exit=" + (process.exitCode ?? 0));
}Preload used for the low-memory steps: // Scenario-only preload: while the file named by CRON_PROOF_MEMORY_FILE holds a number, the
// Gateway's process.availableMemory() returns it; otherwise the real reading.
import { readFileSync } from "node:fs";
const real = process.availableMemory.bind(process);
const file = process.env.CRON_PROOF_MEMORY_FILE;
process.availableMemory = () => {
try {
const value = readFileSync(file, "utf8").trim();
if (value) return Number(value);
} catch {}
return real();
}; |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Gateway proof at 17da938: runs past 8 need spare memory, and stop at 16Real isolated Gateway built from this head (
How memory was steered: a macOS guest swaps instead of staying under 1 GiB, so for the one low-memory step the Gateway process ran with a scenario preload that makes Upgrade from the latest stable 2026.11.4 to this head: still not shown. In the same VM, starting this head on state written by 2026.11.4 fails right after the state migration with Redaction: temporary paths and the host name are left out; no real provider, credential or account was used. Scenario script and preload// Gateway scenario for openclaw/openclaw#197394: upgrade from the latest stable, then extra cron
// admission while memory is free, later drains, low-memory refusal and mixed hook capacity.
// Usage: node scenario.mjs <stable-openclaw.mjs> <head-openclaw.mjs> <out-dir>
import { spawn } from "node:child_process";
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { once } from "node:events";
import { mkdtemp, mkdir, readFile, writeFile } from "node:fs/promises";
import { createServer } from "node:http";
import { createRequire } from "node:module";
import os from "node:os";
import path from "node:path";
import { setTimeout as delay } from "node:timers/promises";
const [stableEntry, headEntry, out] = process.argv.slice(2).map((p) => path.resolve(p));
const require = createRequire(path.join(path.dirname(headEntry), "package.json"));
const WebSocket = require("ws");
await mkdir(out, { recursive: true });
const root = await mkdtemp(path.join(os.tmpdir(), "cron-197394-"));
await mkdir(root + "/home");
await mkdir(root + "/workspace");
const events = [];
const note = (kind, data = {}) => {
const e = { kind, at: new Date().toISOString(), ...data };
events.push(e);
console.log(JSON.stringify(e));
};
const gib = (b) => Math.round((b / 1024 ** 3) * 100) / 100;
// Synthetic model provider: every request stays open until the scenario releases its marker.
const open = new Map(); // marker -> release()
const model = createServer(async (req, res) => {
let raw = "";
for await (const c of req) raw += c;
if (!req.url.includes("chat/completions")) {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ object: "list", data: [{ id: "proof", object: "model" }] }));
return;
}
const body = JSON.parse(raw);
const marker = JSON.stringify(body.messages).match(/KZ_[a-z]+_\d+/g)?.at(-1) ?? "unknown";
await new Promise((resolve) => {
open.set(marker, resolve);
res.on("close", resolve);
});
open.delete(marker);
if (res.destroyed) return;
const usage = { prompt_tokens: 2, completion_tokens: 2, total_tokens: 4 };
const chunk = (delta, finish) =>
"data: " +
JSON.stringify({
id: "kz",
object: "chat.completion.chunk",
created: 1,
model: "proof",
choices: [{ index: 0, delta, finish_reason: finish }],
...(finish ? { usage } : {}),
}) +
"\n\n";
if (body.stream) {
res.writeHead(200, { "Content-Type": "text/event-stream" });
res.write(chunk({ role: "assistant", content: "Done" }, null));
res.write(chunk({}, "stop"));
res.end("data: [DONE]\n\n");
} else {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
id: "kz",
object: "chat.completion",
created: 1,
model: "proof",
choices: [{ index: 0, message: { role: "assistant", content: "Done" }, finish_reason: "stop" }],
usage,
}),
);
}
});
await new Promise((r) => model.listen(0, "127.0.0.1", r));
const release = (marker) => open.get(marker)?.();
const openOf = (kind) => [...open.keys()].filter((m) => m.startsWith("KZ_" + kind + "_")).length;
const reserve = createServer();
await new Promise((r) => reserve.listen(0, "127.0.0.1", r));
const port = reserve.address().port;
await new Promise((r) => reserve.close(r));
const hookToken = randomBytes(24).toString("hex");
const config = {
browser: { enabled: false },
update: { checkOnStart: false },
discovery: { mdns: { mode: "off" } },
gateway: {
mode: "local",
bind: "loopback",
auth: { mode: "none" },
controlUi: { enabled: false },
tailscale: { mode: "off" },
},
plugins: { enabled: false },
hooks: { enabled: true, token: hookToken, path: "/hooks", allowedAgentIds: ["main"] },
logging: { level: "info", file: root + "/runtime.log" },
agents: {
defaults: {
workspace: root + "/workspace",
model: { primary: "standin/proof" },
timeoutSeconds: 900,
},
entries: { main: {} },
},
models: {
mode: "merge",
providers: {
standin: {
baseUrl: `http://127.0.0.1:${model.address().port}/v1`,
apiKey: "synthetic-key",
api: "openai-completions",
timeoutSeconds: 900,
models: [
{
id: "proof",
name: "Synthetic local fixture",
reasoning: false,
input: ["text"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 120000,
maxTokens: 8192,
},
],
},
},
},
};
const configPath = root + "/config.json";
await writeFile(configPath, JSON.stringify(config, null, 2));
const env = {
HOME: root + "/home",
OPENCLAW_HOME: root + "/home",
OPENCLAW_STATE_DIR: root + "/state",
OPENCLAW_CONFIG_PATH: configPath,
PATH: process.env.PATH,
SHELL: "/bin/sh",
LANG: "en_US.UTF-8",
NO_COLOR: "1",
CI: "1",
OPENCLAW_NO_RESPAWN: "1",
OPENCLAW_SKIP_CHANNELS: "1",
npm_config_update_notifier: "false",
};
const memoryFile = root + "/memory-reading";
await writeFile(memoryFile, "");
env.CRON_PROOF_MEMORY_FILE = memoryFile;
const preload = path.join(path.dirname(new URL(import.meta.url).pathname), "memory-reading.mjs");
const hash = async (p) => createHash("sha256").update(await readFile(p)).digest("hex");
let gw;
let ws;
let seq = 0;
const pending = new Map();
let logs = "";
function rpc(method, params = {}, ms = 60000) {
return new Promise((resolve, reject) => {
const id = String(++seq);
const timer = setTimeout(() => {
pending.delete(id);
reject(Error("RPC timeout " + method));
}, ms);
pending.set(id, { resolve, reject, timer });
ws.send(JSON.stringify({ type: "req", id, method, params }));
});
}
async function startGateway(entry, label) {
logs += `\n--- ${label} ---\n`;
gw = spawn(process.execPath, ["--import", preload, entry, "gateway", "run", "--port", String(port)], {
cwd: path.dirname(entry),
env,
stdio: ["ignore", "pipe", "pipe"],
});
for (const s of [gw.stdout, gw.stderr]) s.on("data", (b) => (logs += b.toString()));
const until = Date.now() + 240000;
for (;;) {
if (gw.exitCode !== null) throw Error(`${label} exited ${gw.exitCode}: ${logs.slice(-2000)}`);
try {
if ((await fetch(`http://127.0.0.1:${port}/readyz`)).ok) break;
} catch {}
if (Date.now() > until) throw Error(label + " not ready");
await delay(500);
}
ws = new WebSocket(`ws://127.0.0.1:${port}`);
ws.on("error", () => {});
ws.on("message", (b) => {
const x = JSON.parse(b.toString());
if (x.type !== "res") return;
const p = pending.get(x.id);
if (!p) return;
clearTimeout(p.timer);
pending.delete(x.id);
x.ok ? p.resolve(x.payload) : p.reject(Error(JSON.stringify(x.error)));
});
await once(ws, "open");
const hello = await rpc("connect", {
minProtocol: 4,
maxProtocol: 4,
client: {
id: "gateway-client",
displayName: "Cron proof",
version: "1",
platform: process.platform,
mode: "backend",
instanceId: randomUUID(),
},
role: "operator",
scopes: ["operator.read", "operator.write", "operator.admin"],
});
note("gateway-ready", { label, version: hello.server?.version ?? hello.server });
}
async function stopGateway() {
ws?.terminate();
gw.kill("SIGTERM");
await Promise.race([once(gw, "exit"), delay(20000)]);
if (gw.exitCode === null && gw.signalCode === null) {
gw.kill("SIGKILL");
await once(gw, "exit");
}
}
const jobView = (j) => ({
id: j.id,
name: j.name,
enabled: j.enabled,
schedule: j.schedule,
payload: j.payload,
delivery: j.delivery,
});
async function counts(label) {
const listed = await rpc("cron.list", { includeDisabled: true }, 20000);
const jobs = listed.jobs ?? [];
const now = Date.now();
const c = {
label,
cronRunning: jobs.filter((j) => j.state?.runningAtMs).length,
cronDueNotStarted: jobs.filter(
(j) =>
!j.state?.runningAtMs &&
!j.state?.lastRunAtMs &&
((j.schedule?.kind === "at" && Date.parse(j.schedule.at) <= now) || j.state?.queuedAtMs),
).length,
cronQueued: jobs.filter((j) => j.state?.queuedAtMs).length,
cronModelTurnsOpen: openOf("job") + openOf("manual"),
hookModelTurnsOpen: openOf("hook"),
realAvailableMemoryGiB: gib(process.availableMemory()),
gatewayMemoryReadingGiB: (await readFile(memoryFile, "utf8")).trim()
? gib(Number(await readFile(memoryFile, "utf8")))
: "real",
};
note("counts", c);
return c;
}
async function settle(label, ms = 8000) {
await delay(ms);
return counts(label);
}
const summary = {};
try {
// 1. Latest stable: create jobs and settings.
await startGateway(stableEntry, "stable");
const due = Date.now() + 210000;
const ids = {};
for (let i = 0; i < 12; i++) {
const job = await rpc("cron.add", {
name: "timed-" + i,
agentId: "main",
enabled: true,
deleteAfterRun: false,
schedule: { kind: "at", at: new Date(due).toISOString() },
sessionTarget: "isolated",
payload: { kind: "agentTurn", message: "Reply briefly. KZ_job_" + i, timeoutSeconds: 900 },
delivery: { mode: "none" },
failureAlert: false,
});
ids["job_" + i] = job.id;
}
for (let i = 0; i < 9; i++) {
const job = await rpc("cron.add", {
name: "manual-" + i,
agentId: "main",
enabled: true,
deleteAfterRun: false,
schedule: { kind: "at", at: new Date(due + 86400000).toISOString() },
sessionTarget: "isolated",
payload: { kind: "agentTurn", message: "Reply briefly. KZ_manual_" + i, timeoutSeconds: 900 },
delivery: { mode: "none" },
failureAlert: false,
});
ids["manual_" + i] = job.id;
}
const before = ((await rpc("cron.list", { includeDisabled: true })).jobs ?? []).map(jobView);
await stopGateway();
const { execFileSync } = await import("node:child_process");
const leftovers = () =>
execFileSync("/bin/ps", ["-axo", "pid,command"], { encoding: "utf8" })
.split("\n")
.filter((l) => l.includes(path.dirname(stableEntry)) && !l.includes("scenario"));
note("after-stop-leftovers", { count: leftovers().length, lines: leftovers().map((l) => l.slice(0, 160)) });
for (let i = 0; i < 60 && leftovers().length > 0; i++) await delay(1000);
note("leftovers-before-head", { count: leftovers().length });
const configBefore = await hash(configPath);
// 2. Upgrade in place to the PR head.
await startGateway(headEntry, "head");
const after = ((await rpc("cron.list", { includeDisabled: true })).jobs ?? []).map(jobView);
const byId = (list) => JSON.stringify([...list].sort((a, b) => a.id.localeCompare(b.id)));
summary.upgrade = {
jobsBefore: before.length,
jobsAfter: after.length,
jobsUnchanged: byId(before) === byId(after),
configUnchanged: configBefore === (await hash(configPath)),
headStartedBeforeDue: Date.now() < due,
};
note("upgrade", summary.upgrade);
await writeFile(out + "/jobs-before.json", JSON.stringify(before, null, 2));
await writeFile(out + "/jobs-after.json", JSON.stringify(after, null, 2));
// 3. Twelve jobs come due with memory free.
while (Date.now() < due + 2000) await delay(500);
summary.due = await settle("12 due, memory free");
// 4. Reading pinned under 1 GiB: a newly requested run starts nothing past the default slots.
await writeFile(memoryFile, String(512 * 1024 ** 2));
await rpc("cron.run", { id: ids.manual_0, mode: "force" });
summary.lowAfterRequest = await settle("request manual-0, reading 512 MiB", 6000);
await writeFile(memoryFile, "");
// 5. Memory free: each further request is a drain that adds one run, up to 16.
summary.growth = [];
for (let i = 1; i < 9; i++) {
await rpc("cron.run", { id: ids["manual_" + i], mode: "force" });
summary.growth.push(await settle("request manual-" + i + ", memory free", 6000));
}
summary.atCap = summary.growth.at(-1);
// 7. Release everything and wait for terminal history.
const releaseAll = setInterval(() => [...open.keys()].forEach(release), 500);
const until = Date.now() + 300000;
let history;
for (;;) {
history = await rpc("cron.runs", { scope: "all", limit: 200 });
const done = new Set((history.entries ?? []).map((r) => r.jobId));
if (Object.values(ids).every((id) => done.has(id))) break;
if (Date.now() > until) throw Error("runs did not finish");
await delay(2000);
}
clearInterval(releaseAll);
const last = new Map((history.entries ?? []).map((r) => [r.jobId, r.status]));
summary.final = Object.fromEntries(
Object.entries(ids).map(([k, id]) => [k, last.get(id)]),
);
note("final", summary.final);
summary.ok = true;
} catch (error) {
summary.ok = false;
summary.error = String(error?.stack ?? error);
note("error", { error: summary.error, tail: logs.slice(-3000) });
process.exitCode = 1;
} finally {
[...open.keys()].forEach(release);
if (gw && gw.exitCode === null) await stopGateway().catch(() => {});
model.closeAllConnections();
model.close();
await writeFile(out + "/summary.json", JSON.stringify(summary, null, 2));
await writeFile(out + "/events.json", JSON.stringify(events, null, 2));
await writeFile(out + "/gateway.log", logs);
console.log("SCENARIO DONE exit=" + (process.exitCode ?? 0));
}// Scenario-only preload: while the file named by CRON_PROOF_MEMORY_FILE holds a number, the
// Gateway's process.availableMemory() returns it; otherwise the real reading.
import { readFileSync } from "node:fs";
const real = process.availableMemory.bind(process);
const file = process.env.CRON_PROOF_MEMORY_FILE;
process.availableMemory = () => {
try {
const value = readFileSync(file, "utf8").trim();
if (value) return Number(value);
} catch {}
return real();
}; |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Upgrade from the latest stable 2026.11.4 to this head (17da938), in one private macOS 26.6 VM (4 CPUs, 8 GB, Node 24.21). Same harness as the earlier proof: own temporary state and config, hooks on, plugins and channels off, a synthetic model on loopback that holds every request open.
Cron admission on the upgraded state, with 21 jobs created on this head after the second start (counts from
All 21 runs finished Why the proof uses jobs created after the update: the jobs created on 2026.11.4 do not run after this update. Each run is refused with The 512 MiB step uses a scenario-only preload that pins the Gateway's |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Upgrade from the latest stable, [email protected], with carried-over jobs running afterwards. One private macOS 26.6 VM (4 CPUs, 8 GB, Node 24.21), same harness as before: own temporary state and config, hooks on, plugins and channels off, a synthetic model on loopback that holds every request open. Build: this PR's head 3929481 with two main fixes applied on top: the #200596 fix (#200583, first start after the update) and the #200600 fix (fork branch daniel-lxs:fix/cron-upgrade-binding-shadow-path, commit 5bd0524; its PR is being opened). Without them the first start fails and the carried-over jobs are refused; that is tracked in #200583 and #200600, which main has without this PR.
Counts from
At request 7 two drains ran in one window (the request and the scheduler tick for the newly due carried-over jobs), so two new manual runs started, one per drain. At 16 runs, 15 model turns are open, as in the earlier proof. The carried-over jobs waited while 16 ran. Result: all 12 carried-over scheduled jobs ran The 512 MiB step uses a scenario-only preload that pins the Gateway's |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Related: #196859
What Problem This Solves
Due automations wait behind a fixed cap of eight runs, even on a host with plenty of memory to run more.
User Impact
process.availableMemory(), which counts the process's cgroup memory limit: in a 512 MiB container it reads about 500 MiB, whileos.freemem()reads the VM's 5.4 GB.Why This Change Was Made
The run queue owns admission. The host adds one fact to each drain, whether one memory reading shows 1 GiB free, and the queue uses it to start at most one run past its eight default slots per drain. Each later drain reads memory again with that run counted, so the extra runs stop once memory gets short. No timer, threshold ladder or per-run memory estimate is involved.
Automation agent turns run in the cron lane, which shares one capacity budget with hook dispatch. That budget is 16 wide, since with it at eight an extra run would only wait in the lane for a slot. Hook dispatch keeps its own width of eight, so hooks alone never use more than they could before. Together, hooks and automation can hold up to 16 slots where they shared eight. Keeping them at eight combined would mean republishing the lane budget from the run queue on every drain, which this change leaves out. With hooks enabled, one of the 16 stays reserved for hooks, as one of the eight was.
Accepted edge cases:
Evidence
Targeted tests pass:
service.cross-tick-admission(10),service.run-queue(16),service.one-shot-schedule-ownership(17),service/ops.native-attempt(7),service/ops.gateway-mutations(11),service/ops.run-admission(8),service/manual-ack-durability(3),service/timer.regression(16),store/scheduler-actor.worker(24),server-lanes.hook-group(2),server/hooks.early-failure(27).Tests that fill exactly the eight default slots mock the memory reading to report no spare memory, so they do not depend on the machine running them. With the memory reading set to 16 GiB, as on CI,
timer.regression's slot fixture without the mock fails its two queueing cases (a queued run starts instead, and a wait times out); with the mock all 16 cases pass.Cron suite, run once on this change with the memory mock applied to every cron test: 292 of 299 files passed. The mock then moved into the tests that fill the eight slots, and those tests were rerun (above). The seven failing files were rerun on this branch and on its merge base
4b0d586f272.maintenance-lifecycle(18),maintenance-snapshot(5),maintenance(1) andtrigger-script.mcp(3) fail the same on both.service.pr-automation-feedbackandservice/command-timeoutpass on rerun.service/manual-ack-durabilityfilled the eight slots with memory to spare and so started its queued request; it passes with the memory mock. Core, cron-test and gateway-server typechecks, lint and format pass; net test lines +63.Gateway run of this change and its merge base in a private macOS VM, with 12 cron agent jobs due together and a synthetic model that holds every request open (full table and script):
ok.ok.Validation Limits
The model was synthetic. In the VM a macOS guest swaps instead of staying under 1 GiB, so for the low-memory steps the Gateway's
process.availableMemory()was pinned at 512 MiB through a preload; the rest of the run was the shipped build. An upgrade from the latest stable was not shown, because main fails it on its own: starting mainb9a72b5bef8on state written by 2026.11.4, in the same VM and without any scenario preload, fails after the state migration withStartup failed: required secrets are unavailable. Error: disk I/O error | ERR_SQLITE_ERROR. This head fails the same way there, also with no stable process left running and with no plaintext secrets in the config; that startup failure is separate from this change. Windows, Bun, x86 Linux, real channels and the full suite were not exercised.