Skip to content

feat(daemon): auto-detect Node.js heap limit; add gateway.nodeMaxOldSpaceMb config - #42853

Closed
sburl-bot wants to merge 2 commits into
openclaw:mainfrom
sburl-bot:feat/gateway-node-memory-config
Closed

sburl-bot wants to merge 2 commits into
openclaw:mainfrom
sburl-bot:feat/gateway-node-memory-config

Conversation

@sburl-bot

Copy link
Copy Markdown

Problem

Node.js defaults to a ~1.5 GB V8 heap ceiling regardless of available system RAM. On machines with 8–128 GB this leaves most memory unused and causes hard OOM aborts (CheckIneffectiveMarkCompact → FatalProcessOutOfMemory → SIGABRT) under heavy parallel agent workloads. The issue also affects child Node processes spawned by the gateway, which inherit no heap configuration at all.

Solution

At gateway install time, automatically compute a sane heap limit (85% of os.totalmem()) and inject it into NODE_OPTIONS=--max-old-space-size=N in the service environment. This propagates to child Node processes automatically via environment inheritance.

Users who want a specific value can set gateway.nodeMaxOldSpaceMb in their config. The interactive onboarding wizard shows the auto-detected value and lets them override it.

Changes

  • src/config/types.gateway.ts — adds nodeMaxOldSpaceMb?: number to GatewayConfig
  • src/config/zod-schema.ts — schema: z.number().int().min(256).optional()
  • src/config/schema.labels.ts / schema.help.ts — label + help text following existing conventions
  • src/daemon/service-env.ts — adds resolveDefaultNodeMaxOldSpaceMb() and resolveNodeOptions() (both exported for testing); injects NODE_OPTIONS in buildCommonServiceEnvironment; adds nodeMaxOldSpaceMb? param to buildServiceEnvironment
  • src/commands/daemon-install-helpers.ts — threads config?.gateway?.nodeMaxOldSpaceMb into buildServiceEnvironment
  • src/wizard/onboarding.gateway-config.ts — adds heap prompt to non-quickstart flow, showing auto-detected value as hint, blank = auto-detect
  • src/daemon/service-env.test.ts — 10 new tests covering auto-detect math, env override precedence, flag composition, buildServiceEnvironment integration

Behaviour details

Scenario Result
No config, no NODE_OPTIONS NODE_OPTIONS=--max-old-space-size=<85% of RAM>
gateway.nodeMaxOldSpaceMb: 6144 set NODE_OPTIONS=--max-old-space-size=6144
User already has --max-old-space-size in NODE_OPTIONS Left unchanged (no override)
User has other flags in NODE_OPTIONS Heap flag appended: <existing> --max-old-space-size=<N>
Quickstart flow Auto-detect applied silently, no prompt shown

Testing

pnpm vitest run src/daemon/service-env.test.ts src/config/config-misc.test.ts src/config/schema.test.ts

59 + 32 + 20 = 111 tests, all passing.

…y.nodeMaxOldSpaceMb

Node.js defaults to a ~1.5 GB V8 heap ceiling regardless of available RAM.
On machines with 8–128 GB this leaves most memory unused and causes
OOM aborts (CheckIneffectiveMarkCompact) under heavy parallel agent
workloads, even though the OS has plenty of headroom.

This change:

- Adds `gateway.nodeMaxOldSpaceMb` to the config schema (integer, min 256,
  optional). When set, the value is used as-is. When absent, the gateway
  install plan automatically computes 85% of `os.totalmem()` at install time.
- Injects the resolved limit into `NODE_OPTIONS=--max-old-space-size=N` in
  the service environment so the gateway process *and* any child Node processes
  it spawns inherit the raised ceiling automatically.
- Respects an existing `--max-old-space-size` flag in the user's `NODE_OPTIONS`
  env var — no override in that case.
- Adds an interactive prompt to the gateway onboarding wizard (non-quickstart
  flow) so users can see the auto-detected value and override it if needed.
- Adds schema label + help text following existing conventions.
- Adds 10 unit tests covering auto-detect math, env override precedence,
  flag composition, and buildServiceEnvironment integration.
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime commands Command implementations size: S labels Mar 11, 2026
@greptile-apps

greptile-apps Bot commented Mar 11, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR auto-detects and injects a sane Node.js V8 heap limit (85% of system RAM) into the service environment at install time, solving OOM crashes under heavy parallel workloads. The implementation is well-structured, with clean precedence logic, an optional config override (gateway.nodeMaxOldSpaceMb), and good test coverage.

Issues found:

  • Logic bug (src/wizard/onboarding.gateway-config.ts): Leaving the heap-limit field blank in the onboarding wizard does not remove a previously saved nodeMaxOldSpaceMb from the config. The conditional spread ...(nodeMaxOldSpaceMb !== undefined ? { nodeMaxOldSpaceMb } : {}) emits {} when blank, silently preserving the old value — contradicting the "Leave blank to use auto-detect" hint. The key needs to be written as undefined explicitly to clear it.
  • Potential inconsistency (src/daemon/service-env.ts): buildNodeServiceEnvironment does not accept or thread nodeMaxOldSpaceMb, so a separately-installed node-host system service always gets an auto-detected heap limit regardless of what the user configured in gateway.nodeMaxOldSpaceMb. At runtime, env inheritance covers this for child processes, but the frozen environment written into the node-host service unit at install time may diverge from the gateway's configured value.

Confidence Score: 3/5

  • Safe to merge after fixing the wizard's blank-input logic bug, which silently persists previously saved heap values instead of clearing them.
  • The core resolveNodeOptions / resolveDefaultNodeMaxOldSpaceMb logic and schema additions are correct and well-tested. However, the wizard has a clear logic error where a blank entry (intended to revert to auto-detect) does not actually clear a previously stored nodeMaxOldSpaceMb value. Additionally, buildNodeServiceEnvironment does not propagate the user-configured value, creating a potential inconsistency for independently installed node-host services.
  • Pay close attention to src/wizard/onboarding.gateway-config.ts (blank-clear bug) and src/daemon/service-env.ts (buildNodeServiceEnvironment not forwarding the configured value).

Comments Outside Diff (1)

  1. src/daemon/service-env.ts, line 306-327 (link)

    buildNodeServiceEnvironment ignores nodeMaxOldSpaceMb config

    buildNodeServiceEnvironment calls buildCommonServiceEnvironment(env, sharedEnv) without forwarding a nodeMaxOldSpaceMb parameter. This means node-host services installed as independent system services (launchd / systemd / Windows Task) always receive an auto-detected heap limit, regardless of whatever value the user set in gateway.nodeMaxOldSpaceMb.

    The PR description says the intent is for "child Node processes spawned by the gateway" to inherit the limit via env propagation, which is true at runtime. However, the separately-installed node-host service reads its environment from the frozen service unit written at install time — it does not inherit the gateway's runtime environment. If the two values diverge (e.g. user sets nodeMaxOldSpaceMb: 6144 on a machine with 4 GB RAM where auto-detect gives 3481 MB), the gateway and the node-host service will operate under different heap ceilings.

    Consider accepting and threading nodeMaxOldSpaceMb through buildNodeServiceEnvironment the same way it is threaded through buildServiceEnvironment, so both installed services share the same explicit cap.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: src/daemon/service-env.ts
    Line: 306-327
    
    Comment:
    **`buildNodeServiceEnvironment` ignores `nodeMaxOldSpaceMb` config**
    
    `buildNodeServiceEnvironment` calls `buildCommonServiceEnvironment(env, sharedEnv)` without forwarding a `nodeMaxOldSpaceMb` parameter. This means node-host services installed as independent system services (launchd / systemd / Windows Task) always receive an auto-detected heap limit, regardless of whatever value the user set in `gateway.nodeMaxOldSpaceMb`.
    
    The PR description says the intent is for "child Node processes spawned by the gateway" to inherit the limit via env propagation, which is true at runtime. However, the separately-installed node-host service reads its environment from the frozen service unit written at install time — it does **not** inherit the gateway's runtime environment. If the two values diverge (e.g. user sets `nodeMaxOldSpaceMb: 6144` on a machine with 4 GB RAM where auto-detect gives 3481 MB), the gateway and the node-host service will operate under different heap ceilings.
    
    Consider accepting and threading `nodeMaxOldSpaceMb` through `buildNodeServiceEnvironment` the same way it is threaded through `buildServiceEnvironment`, so both installed services share the same explicit cap.
    
    How can I resolve this? If you propose a fix, please make it concise.

Last reviewed commit: e7930db

Comment on lines +330 to +338
const trimmed = typeof rawInput === "string" ? rawInput.trim() : "";
const nodeMaxOldSpaceMb = trimmed ? Number.parseInt(trimmed, 10) : undefined;
nextConfig = {
...nextConfig,
gateway: {
...nextConfig.gateway,
...(nodeMaxOldSpaceMb !== undefined ? { nodeMaxOldSpaceMb } : {}),
},
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blank input does not clear an existing nodeMaxOldSpaceMb value

When the user leaves the heap-limit field blank (to "use auto-detect"), nodeMaxOldSpaceMb is undefined and the conditional spread ...(nodeMaxOldSpaceMb !== undefined ? { nodeMaxOldSpaceMb } : {}) becomes {}. Because ...nextConfig.gateway is spread first, any previously saved nodeMaxOldSpaceMb (e.g. 6144) is retained in the resulting config rather than being removed.

The hint tells the user "Leave blank to use auto-detect", but that instruction is silently ignored if a value was previously stored. The user would need to reinstall or manually edit the config file to revert to auto-detection.

Fix: always write the resolved value (including undefined) so a blank entry explicitly clears the field:

Suggested change
const trimmed = typeof rawInput === "string" ? rawInput.trim() : "";
const nodeMaxOldSpaceMb = trimmed ? Number.parseInt(trimmed, 10) : undefined;
nextConfig = {
...nextConfig,
gateway: {
...nextConfig.gateway,
...(nodeMaxOldSpaceMb !== undefined ? { nodeMaxOldSpaceMb } : {}),
},
};
nextConfig = {
...nextConfig,
gateway: {
...nextConfig.gateway,
nodeMaxOldSpaceMb,
},
};

Spreading { nodeMaxOldSpaceMb: undefined } onto the gateway object sets the key to undefined, which JSON/YAML serialisers will omit — effectively deleting the setting and restoring auto-detect behaviour.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/wizard/onboarding.gateway-config.ts
Line: 330-338

Comment:
**Blank input does not clear an existing `nodeMaxOldSpaceMb` value**

When the user leaves the heap-limit field blank (to "use auto-detect"), `nodeMaxOldSpaceMb` is `undefined` and the conditional spread `...(nodeMaxOldSpaceMb !== undefined ? { nodeMaxOldSpaceMb } : {})` becomes `{}`. Because `...nextConfig.gateway` is spread first, any previously saved `nodeMaxOldSpaceMb` (e.g. `6144`) is retained in the resulting config rather than being removed.

The hint tells the user "Leave blank to use auto-detect", but that instruction is silently ignored if a value was previously stored. The user would need to reinstall or manually edit the config file to revert to auto-detection.

Fix: always write the resolved value (including `undefined`) so a blank entry explicitly clears the field:

```suggestion
    nextConfig = {
      ...nextConfig,
      gateway: {
        ...nextConfig.gateway,
        nodeMaxOldSpaceMb,
      },
    };
```

Spreading `{ nodeMaxOldSpaceMb: undefined }` onto the gateway object sets the key to `undefined`, which JSON/YAML serialisers will omit — effectively deleting the setting and restoring auto-detect behaviour.

How can I resolve this? If you propose a fix, please make it concise.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e7930db935

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/wizard/onboarding.gateway-config.ts Outdated
Comment on lines +335 to +336
...nextConfig.gateway,
...(nodeMaxOldSpaceMb !== undefined ? { nodeMaxOldSpaceMb } : {}),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Remove saved heap override when user leaves prompt blank

When onboarding starts with an existing gateway.nodeMaxOldSpaceMb, submitting an empty heap-limit prompt is documented as “Leave blank to use auto-detect,” but this assignment keeps the prior value because ...nextConfig.gateway already contains nodeMaxOldSpaceMb and the blank branch adds nothing. In practice, users cannot clear a previously set heap override back to auto-detect through the wizard.

Useful? React with 👍 / 👎.

…vice forwards config

- onboarding.gateway-config.ts: always spread `{ nodeMaxOldSpaceMb }` (even when
  undefined) so a blank wizard entry explicitly clears a previously saved value,
  restoring auto-detect behaviour as the hint promises
- service-env.ts: add nodeMaxOldSpaceMb param to buildNodeServiceEnvironment and
  forward it to buildCommonServiceEnvironment so separately-installed node-host
  services respect the user-configured cap rather than always using auto-detect
- node-daemon-install-helpers.ts: accept optional config and thread
  config?.gateway?.nodeMaxOldSpaceMb into buildNodeServiceEnvironment
- service-env.test.ts: two new tests covering nodeMaxOldSpaceMb in node service env

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5199ee82b9

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/daemon/service-env.ts
configuredMb?: number,
): string | undefined {
const existing = env.NODE_OPTIONS ?? "";
if (existing.includes("--max-old-space-size")) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Detect underscore heap flag before appending NODE_OPTIONS

resolveNodeOptions only checks for "--max-old-space-size", so an existing NODE_OPTIONS value like --max_old_space_size=2048 is treated as missing and gets a second heap flag appended. Because Node accepts both spellings and the later one wins, users who already pinned heap via underscore syntax will be silently overridden to the auto/configured value, which can unexpectedly increase memory use.

Useful? React with 👍 / 👎.

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Apr 27, 2026
@clawsweeper

clawsweeper Bot commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

Keep open for maintainer follow-up, but this PR is not merge-ready. It targets a real Gateway OOM/config gap, yet the branch conflicts with current main, copies ambient NODE_OPTIONS into durable service metadata, misses a Node heap flag alias, does not fully wire the node-service config path, and has only unit-test proof rather than real regenerated-service proof.

Canonical path: Close this stale PR. The latest review rated it F, the branch still lacks merge-ready proof, and there has been no human follow-up after the durable review.

So I’m closing this here because the remaining work is already tracked in the canonical issue.

Review details

Best possible solution:

Close this stale PR. The latest review rated it F, the branch still lacks merge-ready proof, and there has been no human follow-up after the durable review.

Do we have a high-confidence way to reproduce the issue?

No high-confidence live OOM reproduction was run against current main. Source inspection confirms current main has no typed heap config or generated heap-only service flag, and linked Linux/macOS reports provide real crash and workaround evidence.

Is this the best way to solve the issue?

No, not as currently implemented. A typed heap config is a good direction, but the patch should emit a heap-only startup flag, preserve the existing NODE_OPTIONS security boundary, wire both service install paths, and include real regenerated-service proof.

Security review:

Security review needs attention: The diff introduces a concrete service-startup security concern by copying ambient NODE_OPTIONS into durable managed daemon environments.

  • [high] Ambient NODE_OPTIONS becomes durable startup control — src/daemon/service-env.ts:340
    buildCommonServiceEnvironment writes resolveNodeOptions(env, ...) into generated service metadata, and resolveNodeOptions preserves or appends to env.NODE_OPTIONS; non-heap flags such as --require or --import could become persistent daemon startup behavior despite the host-env blocklist.
    Confidence: 0.94

What I checked:

  • stale F-rated PR: PR was opened 2026-03-11T05:49:45Z, is older than 60 days, and the latest review rated it F.
  • proof blocker: real behavior proof is mock_only and proof tier is F, so this branch is not merge-ready without contributor follow-up.
  • no human follow-up: live comments and timeline hydrated by apply contain no non-automation activity after the ClawSweeper review.

Likely related people:

  • steipete: Recent commits and blame touch service-env, daemon install planning, and Gateway config/schema surfaces that this PR must rebase onto and preserve. (role: recent area contributor; confidence: high; commits: 85ce75c005a2, e510042870cf; files: src/daemon/service-env.ts, src/commands/daemon-install-helpers.ts, src/config/types.gateway.ts)
  • vincentkoc: Recent daemon install and macOS launchd startup hardening is adjacent to generated service environment behavior and durable install metadata. (role: recent daemon/install contributor; confidence: medium; commits: d7c173b69456, 448a33b90c05; files: src/daemon/service-env.ts, src/commands/daemon-install-helpers.ts, src/infra/host-env-security-policy.json)
  • jacobtomlinson: The host-env blocklist change shapes the NODE_OPTIONS security boundary that this PR risks bypassing. (role: adjacent host-env policy contributor; confidence: medium; commits: d1bfe084241a; files: src/commands/daemon-install-helpers.ts, src/infra/host-env-security-policy.json)
  • jbetala7: Recent Gateway service PATH work touches the same buildServiceEnvironment call path that must survive a rebase. (role: recent daemon service PATH contributor; confidence: medium; commits: 66d1d1388924; files: src/commands/daemon-install-helpers.ts, src/daemon/service-env.ts)
  • WarrenJones: Recent safe Gateway env preservation work is directly adjacent to LaunchAgent/systemd regeneration and managed env behavior. (role: adjacent env-regeneration contributor; confidence: medium; commits: 40c5edb5b1ca; files: src/daemon/service-env.ts, src/commands/daemon-install-helpers.ts)

Codex review notes: model gpt-5.5, reasoning high; reviewed against a705a9c911bc.

@EthanSK

EthanSK commented May 3, 2026

Copy link
Copy Markdown

Strong +1 on landing this. Real-world impact from the user side:

  • openclaw install strips NODE_OPTIONS via the host-env-security blocker (host-env-security-DZcto3_u.js's blockedEverywhereKeys), so user-side workarounds (manually editing the macOS LaunchAgent plist's NODE_OPTIONS key) are wiped on every install / update. openclaw restart preserves the edit; only install (which auto-update calls via runDaemonInstall({ force: true })) wipes it.
  • Hit a hard OOM crash on a 16 GB Mac mini running long OC sessions — V8 Ineffective mark-compacts near heap limit. Allocation failed - JavaScript heap out of memory around ~3.9 GB resident. Two main-target sessions wedged for 36+ hours and the watchdog hadn't reaped them; without a configurable heap, the slow transcript bloat turned into a fatal SIGABRT instead of just a slow session.
  • Currently working around it with a SessionStart hook (maybe-add-openclaw-heap.sh) that re-injects NODE_OPTIONS=--max-old-space-size=8192 into the plist on every Claude Code boot. Functional but a band-aid — it races with openclaw install and has to be repeated per machine.

defaults.gateway.nodeMaxOldSpaceMb (this PR) is exactly the right shape: durable in openclaw.json, threaded through buildServiceEnvironment, survives force: true regenerates because it's not arbitrary env pass-through. Auto-detect from os.totalmem() is a great default for the long tail of users who'd never set this manually.

Filed #76658 with macOS-specific repro to add evidence on top of the systemd-flavoured #52092. Happy to test a build locally on the Mac mini once the open Greptile comments (wizard blank-clear, buildNodeServiceEnvironment threading for independently-installed node-host services) are addressed.

@clawsweeper clawsweeper Bot added the P1 High-priority user-facing bug, regression, or broken workflow. label May 16, 2026
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. label May 16, 2026
@clawsweeper clawsweeper Bot added impact:security Security boundary, credential, authz, sandbox, or sensitive-data risk. impact:crash-loop Crash, hang, restart loop, or process-level availability failure. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. 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. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. and removed impact:security Security boundary, credential, authz, sandbox, or sensitive-data risk. impact:crash-loop Crash, hang, restart loop, or process-level availability failure. labels May 17, 2026
@clawsweeper

clawsweeper Bot commented May 20, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat.

Where did the egg go?
  • The egg game starts only after the PR passes the real-behavior proof check.
  • Before that, no creature or rarity is rolled. The treat waits for real proof.
  • This is still just collectible flavor: proof affects review readiness, not creature quality.

@clawsweeper

clawsweeper Bot commented May 23, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

@clawsweeper clawsweeper Bot closed this May 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants