Skip to content

feat(cron): add up to eight runs past the default when memory is free - #197394

Merged
hannesrudolph merged 17 commits into
openclaw:mainfrom
daniel-lxs:cron-shared-session-limit
Nov 19, 2026
Merged

hannesrudolph merged 17 commits into
openclaw:mainfrom
daniel-lxs:cron-shared-session-limit

Conversation

@daniel-lxs

@daniel-lxs daniel-lxs commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

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

  • Up to eight automation jobs run at once, as before.
  • While all eight are busy and more jobs are due, each drain of the run queue starts one more job if at least 1 GiB of memory is free, up to 16 at once. The queue drains when a run ends and when jobs come due, so on a host with room the count grows by one job per drain.
  • The reading is Node's process.availableMemory(), which counts the process's cgroup memory limit: in a 512 MiB container it reads about 500 MiB, while os.freemem() reads the VM's 5.4 GB.
  • Running jobs are never stopped, condition checks do not use run slots, and there is no new setting.

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:

  • The eight default runs do not read memory. A small container with a heavy neighbour can still be OOM-killed with eight runs, as on main.
  • One reading admits one run, and that run's memory may not show yet at the next drain. A run that later needs more than the memory left can still run short; each drain adds at most one run.

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).

  • Twelve due jobs with 1 GiB free: the first drain starts nine, the next starts a tenth, and with one byte under 1 GiB a further drain starts none. With extra runs disabled it fails: eight start, not nine.

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) and trigger-script.mcp (3) fail the same on both. service.pr-automation-feedback and service/command-timeout pass on rerun. service/manual-ack-durability filled 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):

  • Memory free: 9 runs start where the merge base starts 8; a drain without a run ending adds a tenth; a drain after a run ends refills that slot.
  • Gateway memory reading at 512 MiB: no extra run starts, and the count falls back to 8 as runs end and holds there.
  • Hooks: beside 8 automation runs, 10 hook requests get 8 hook turns running (the merge base runs 1 and answers the other 9 with 503).
  • Restart on the same state keeps all 14 jobs and the config unchanged; all 14 runs end ok.
  • Up to the cap (table and script): with 21 jobs, each request with memory free adds one run, 9 to 16; a request at 16 leaves the run waiting; a request with the reading at 512 MiB starts nothing; all 21 runs end 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 main b9a72b5bef8 on state written by 2026.11.4, in the same VM and without any scenario preload, fails after the state migration with Startup 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.

@clawsweeper

clawsweeper Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: L labels Nov 11, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Nov 11, 2026
@clawsweeper

clawsweeper Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This 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.

  • Before: Eight runs start and four wait.
  • After: Nine runs start; later drains can admit one additional run each, stopping at sixteen.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong production-entry-point evidence and a focused implementation; overall readiness remains limited by the unresolved default-capacity decision.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Real isolated macOS Gateway runs exercise scheduled/manual admission, incremental growth to sixteen, low-memory refusal, hook sharing, restart preservation, and completion through a synthetic HTTP model endpoint; the latest upgrade report additionally exercises carried-over 2026.11.5 jobs using the reviewed head plus independently inspected baseline repairs, with low-memory readings explicitly injected.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Feature · Worth it: Needs a maintainer decision · Fix scope: Partial
User problem: Due automation payloads wait behind eight active runs even when the host has spare memory.
Reason: The demonstrated throughput benefit is useful, but it changes an intentional default resource contract and does not by itself resolve the linked monitoring issue.

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
Reviewed head: 3929481d15e087a69cf287ee94afe7e9c32fd792
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should automation expand automatically from eight to sixteen runs using the 1 GiB gate, while the shared cron-and-hook budget becomes sixteen regardless of that gate?
  • Recommendation: Approve the bounded expansion: Accept the documented resource tradeoff, retaining eight baseline runs, one extra admission per drain, and the existing hook reservation.
  • Why: The implementation and Gateway evidence support the stated behavior, but the previous aggregate-eight contract was deliberate and no maintainer approval of this replacement direction is recorded.

Before merge

  • Await maintainer action - A maintainer must decide whether to accept the proposed automatic concurrency policy and wider shared hook budget.

Findings

None.

Agent review details

How this fits together

The 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
Loading

Technical review

Best 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

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 18e6653 adds src/cron/store/run-queue.worker.ts:344 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 18e665348fa5; files: src/cron/store/run-queue.worker.ts)
  • Daniel: Raw commit 1b8c08a adds src/cron/store/run-queue.worker.ts:433 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1b8c08a72825; files: src/cron/store/run-queue.worker.ts)
  • Spencer Fuller: Raw commit 3374f78 adds src/gateway/server-lanes.ts:33 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 3374f78ad8e9; files: src/gateway/server-lanes.ts)

PR surface

Source +35, Tests +58, Docs +1. Total +94 across 19 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 8 51 16 +35
Tests 9 65 7 +58
Docs 2 4 3 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 19 120 26 +94

Preflight source

Source 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

Metric Value Why it matters
Capacity policy 8 baseline runs; 16 maximum; 1 GiB gate; 0 new settings The user-visible default expands automatically, and the shared cron-and-hook budget doubles while hook-only width remains eight.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add status: ⏳ waiting on maintainer: Only explicit maintainer approvals or decisions remain; merge is still blocked.
  • remove status: 📣 needs proof: Current PR status label is status: ⏳ waiting on maintainer.

Label justifications:

  • P2: This is a bounded throughput improvement for busy automation workloads.
  • merge-risk: 🚨 compatibility: Existing installations automatically receive a wider concurrency policy, including a shared cron-and-hook budget of sixteen instead of eight.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on maintainer: Only explicit maintainer approvals or decisions remain; merge is still blocked.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (19 earlier review cycles; latest 8 shown)
  • reviewed 2026-11-15T16:56:56.147Z sha 4608a13 :: needs real behavior proof before merge. :: [P2] Account for other cgroup residents before widening admission
  • reviewed 2026-11-16T01:18:49.252Z sha eb15eab :: blocked before merge. :: [P2] Stub the exec-memory budget in the cron memory fixture
  • reviewed 2026-11-16T02:22:15.270Z sha 0fe8e93 :: ready, awaiting a maintainer decision. :: none
  • reviewed 2026-11-17T05:27:48.595Z sha 7872ef0 :: needs real behavior proof before merge. :: none
  • reviewed 2026-11-17T06:27:55.376Z sha 7872ef0 :: needs real behavior proof before merge. :: none
  • reviewed 2026-11-17T07:16:36.901Z sha 17da938 :: needs real behavior proof before merge. :: none
  • reviewed 2026-11-17T07:37:49.616Z sha 17da938 :: needs real behavior proof before merge. :: none
  • reviewed 2026-11-17T13:22:06.046Z sha 17da938 :: needs real behavior proof before merge. :: none

Reviewed November 17, 2026, 9:22 AM ET / 14:22 UTC (Revision 20).

@daniel-lxs
daniel-lxs marked this pull request as draft November 11, 2026 23:52
@daniel-lxs
daniel-lxs force-pushed the cron-shared-session-limit branch 2 times, most recently from 6dcae75 to 1997e68 Compare November 12, 2026 19:06
@daniel-lxs

Copy link
Copy Markdown
Member Author

1997e68: the VM trace reached 12 overlapping agent-turn requests; all 12 jobs finished ok. Focused checks passed for allowed continuation and owner reassignment.

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.

@daniel-lxs

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. and removed merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Nov 12, 2026
@daniel-lxs
daniel-lxs marked this pull request as ready for review November 12, 2026 23:09
@daniel-lxs

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

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.
@daniel-lxs

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

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.
@daniel-lxs

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@daniel-lxs

Copy link
Copy Markdown
Member Author

Gateway proof at 7872ef0

Real isolated Gateways built from this head (pnpm build:runtime) and, for comparison, from its merge base 4b0d586f272e, in a private macOS 26.6 VM (4 CPUs, 8 GB, Node 24.21). Each run used its own temporary state and config, hooks enabled with a random token, plugins and channels off, and a synthetic OpenAI-compatible model on loopback that holds every model request open until the scenario releases it, so every started automation keeps its slot. 12 cron agent jobs are due at the same moment, plus 2 jobs started by cron.run (mode: "force"). Counts come from cron.list (runningAtMs) and from the model requests open at the synthetic provider, read 8 s after each step.

Step Merge base This PR
12 jobs due, memory free (about 4.4 GiB available) 8 running, 7 model turns open, 4 due not started 9 running, 9 model turns open, 3 due not started
cron.run of another job (a drain with no run ending) 8 10
One run ends (its drain) 8 10 (the freed slot is refilled, no further extra)
Gateway memory reading 512 MiB, cron.run of another job 8 10, nothing new starts
Same, one run ends 8 9 (not refilled)
Same, another run ends 8 8 (base slot refilled to eight, no extra)
Memory free again, 10 POST /hooks/agent (deliver: false) 1 hook turn open, 9 requests answered 503 8 hook turns open beside 8 automation runs, 2 answered 503
All released 14/14 runs ok 14/14 runs ok

What this shows:

  • The ninth run starts only once the eight default slots are busy, and only while the Gateway's memory reading is at least 1 GiB. Each later drain adds at most one run: a drain without a run ending adds one, a drain after a run ends refills that slot.
  • With the reading under 1 GiB, drains start no extra run, and the count falls back to eight as runs end, then holds at eight.
  • Mixed hook capacity: on the merge base, eight automation runs leave room for one hook turn (seven automation turns run while one slot stays reserved for hooks). With this PR, hook dispatch keeps its own width of eight and the shared cron and hook budget is 16, so eight hook turns run beside eight automation runs. This is the budget change the review asks a maintainer to decide on.

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 process.availableMemory() return 512 MiB while a file holds that value; at every other step it returned the real reading. The queue, lanes and Gateway are the shipped build in both columns.

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 Startup failed: required secrets are unavailable. Error: disk I/O error | ERR_SQLITE_ERROR after the state migration. This head's package version is 2026.11.3, so that path is a downgrade. Starting it on state written by 2026.11.3 fails the same way, and so does the merge base 4b0d586f272e without this change, in the same VM. An upgrade proof needs this branch on top of a main that includes 2026.11.4.

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();
};

@daniel-lxs

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@daniel-lxs

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@daniel-lxs

Copy link
Copy Markdown
Member Author

Gateway proof at 17da938: runs past 8 need spare memory, and stop at 16

Real isolated Gateway built from this head (pnpm build:runtime, version 2026.11.4) in a private macOS 26.6 VM (4 CPUs, 8 GB, Node 24.21), with its own temporary state and config, hooks enabled, plugins and channels off, and a synthetic OpenAI-compatible model on loopback that holds every model request open, so every started automation keeps its slot. 12 cron agent jobs come due at the same moment; 9 more are started one at a time with cron.run (mode: "force"), each request being one drain of the run queue. Counts come from cron.list (runningAtMs) and from the model requests open at the provider, read 6 to 8 s after each step.

Step Gateway memory reading Runs active Due, not started
12 jobs due real (3.3 GiB available) 9 3
request manual-0 pinned at 512 MiB 9 (nothing new starts) 3 + manual-0
request manual-1 real 10 2
request manual-2 real 11 1
request manual-3 real 12 0
request manual-4 real 13 0
request manual-5 real 14 0
request manual-6 real 15 0
request manual-7 real 16 0
request manual-8 real 16 (stops at the cap) manual-8 waits
all released 21/21 runs ok
  • Past the eight default slots, a run starts only on a drain that reads at least 1 GiB, one per drain; with the reading at 512 MiB the request queued and nothing started.
  • The count stops at 16: the request made at 16 left that run waiting until a slot freed.
  • With hooks enabled, 15 model turns were open at 16 runs: the shared cron and hook budget keeps one of its 16 slots for hooks, as main keeps one of its 8 (main shows 8 runs with 7 open turns), so the 16th run's model turn waits for that slot while no hook runs.
  • The Gateway was stopped and started again on the same state before the jobs came due; all 21 jobs (id, name, enabled, schedule, payload, delivery) and the config file's SHA-256 were unchanged.

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 process.availableMemory() return 512 MiB while a file holds that value; at every other step it returned the real reading. The queue, lanes and Gateway are the shipped build.

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 Startup failed: required secrets are unavailable. Error: disk I/O error | ERR_SQLITE_ERROR. It fails the same way with no stable process left running before the head starts, and with a config that holds no plaintext secrets (the model key as an env SecretRef, hooks off). The state database itself is intact (a copy opens with integrity_check ok, schema 40). Main b9a72b5bef8 without this change fails identically on state written by 2026.11.4 in the same kind of VM, so this startup failure is separate from this PR.

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();
};

@daniel-lxs

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@daniel-lxs

Copy link
Copy Markdown
Member Author

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.

  1. 2026.11.4 starts, 21 jobs are created (12 due at one moment, 9 started by hand later), and it stops.
  2. The first start of this head on that state fails right after the state migration with Startup failed: required secrets are unavailable. Error: disk I/O error | ERR_SQLITE_ERROR. That is First Gateway start after upgrading from 2026.11.4 fails with SQLite I/O error; restart recovers #200583, which main has without this PR. Nothing is repaired between the two starts.
  3. The second start of this head reaches ready. All 21 jobs and their settings are unchanged (compared through cron.list).

Cron admission on the upgraded state, with 21 jobs created on this head after the second start (counts from cron.list 6 to 8 s after each step):

Step Cron runs running Due, not started
12 due, memory free 9 3
one more requested, memory reading pinned at 512 MiB 9 3
requests 2 to 8 with memory free, one per drain 10, 11, 12, 13, 14, 15, 16 2, 1, 0, 0, 0, 0, 0
one more request at 16 16 0

All 21 runs finished ok. At 16 runs, 15 model turns were open, as in the earlier proof.

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 Automation "<name>" (<id>) runs on account standin:default, which was signed in again or replaced since the job recorded it. That is #200600. Main without this PR does the same: on main eea1d5a, and on main 176f2ff with the #200583 first-start fix applied, all 12 carried-over jobs that came due were refused with the same message, while 21 jobs created after the update ran ok. This PR does not change that code.

The 512 MiB step uses a scenario-only preload that pins the Gateway's process.availableMemory() reading; the guest's real reading was about 3.3 GiB throughout.

@daniel-lxs

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@daniel-lxs

Copy link
Copy Markdown
Member Author

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.

  1. 2026.11.5 starts, 21 jobs are created (12 due at one moment, 9 manual jobs due the next day), and it stops.
  2. The first start of the build reaches ready. Its log has no Gateway failed to start, no ERR_SQLITE_ERROR and no "signed in again or replaced" refusal. All 21 jobs and their settings are unchanged (compared through cron.list).
  3. 21 more jobs are created on the build. The 12 carried-over scheduled jobs come due while those run.

Counts from cron.list and from the model requests open at the provider, 6 to 8 s after each step:

Step Cron runs running Due, not started Model turns open
12 new jobs due, memory free 9 3 9
one more requested, memory reading pinned at 512 MiB 9 3 9
requests 2 to 6 with memory free, one per drain 10, 11, 12, 13, 14 2, 1, 0, 0, 0 10, 11, 12, 13, 14
request 7: the 12 carried-over jobs come due in the same window 16 12 15
requests 8 and 9 at 16 16 12 15

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 ok, and all 21 jobs created on the build ran ok. The 9 carried-over manual jobs were not requested in this run.

The 512 MiB step uses a scenario-only preload that pins the Gateway's process.availableMemory() reading; the guest's real reading was about 3.3 GiB throughout.

@daniel-lxs

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants