Skip to content

fix(daemon/launchd): cap unbounded gateway stdout/stderr log growth (refs #79422) - #79892

Closed
adhirajhangal wants to merge 2 commits into
openclaw:mainfrom
adhirajhangal:fix/79422-daemon-log-retention
Closed

adhirajhangal wants to merge 2 commits into
openclaw:mainfrom
adhirajhangal:fix/79422-daemon-log-retention

Conversation

@adhirajhangal

@adhirajhangal adhirajhangal commented May 9, 2026 •

Copy link
Copy Markdown
Contributor

What this fixes

gateway.err.log (and gateway.log) under ~/.openclaw/logs/ can grow without bound on macOS because the LaunchAgent plist sets StandardOutPath / StandardErrorPath to fixed paths and launchd appends forever. The reporter on #79422 saw the stderr sink reach 18-19 GB across two separate incidents from a tight acpx/runway/tts-local-cli dep-staging error loop, with openclaw gateway restart as the only workaround.

This PR addresses the log-retention half of that report only. The dep-staging CPU loop itself needs live profiling against current main and is intentionally out of scope. Per clawsweeper's triage the log retention defect is independent and actionable now, so the language in this PR (commit message, CHANGELOG, references below) is deliberately non-closing for #79422 — that issue stays open for the maintainer-led CPU investigation.

What changes

A new src/daemon/log-retention.ts helper:

  • rotateOversizedDaemonLog({ path, limits }), pure, fs-injectable, async. If the file is larger than limits.maxBytes, it renames path to path.1, deleting any pre-existing path.1 first. With archives > 1 it cascades path.{n-1} to path.{n} so the oldest archive is dropped.
  • applyGatewayLogRetention(env), resolves the gateway log paths and runs rotation on both stdoutPath and stderrPath in parallel.
  • resolveGatewayLogRetentionLimits(env), reads OPENCLAW_GATEWAY_LOG_MAX_BYTES and OPENCLAW_GATEWAY_LOG_ARCHIVES. Defaults: 64 MB per stream, 1 archive. OPENCLAW_GATEWAY_LOG_MAX_BYTES=0 disables retention. Archives are clamped to 9.

src/daemon/launchd.ts calls applyGatewayLogRetention(env) at every transition that can lead to a fresh launchd write into the sinks:

  1. writeLaunchAgentPlist (install / stage path), right after ensureSecureDirectory(logDir).
  2. rewriteLaunchAgentPlistForRestart, same seam, so the restart-recovery rewrite path rotates too.
  3. restartLaunchAgent, before the isCurrentProcessLaunchdServiceLabel self-handoff branch, so both the direct launchctl kickstart -k path and the in-process detached-handoff path rotate. The detached helper itself stays unchanged because the in-process call already rotated before scheduling.

Healthy non-oversized paths just stat once per stream and return. Routing semantics are unchanged: rotation only fires when the file is over the cap.

Why this layer

Per AGENTS.md owner boundary: launchd is the daemon owner that wires StandardErrorPath. Linux/systemd journals through journald (already bounded), and the Windows scheduled-task path doesn't hit this sink, so the fix lives in src/daemon/launchd.ts rather than a generic core seam.

Real behavior proof

Behavior or issue addressed: the launchd-owned gateway stderr sink at ~/.openclaw/logs/gateway.err.log grows unbounded because nothing rotates it. With this patch, applyGatewayLogRetention rotates oversize sinks to .1 at install, plist rewrite, and gateway restart (both kickstart and self-handoff paths), and launchd recreates a fresh sink on the next start.

Real environment tested: my own macOS workstation, profile default, the live ai.openclaw.gateway LaunchAgent already installed via openclaw gateway install. ~/.openclaw/logs/gateway.err.log had grown to 25 MB during normal use, so I temporarily lowered the cap to 1 MB to exercise the patched helper end-to-end against the live LaunchAgent rather than synthesize a fake oversize log.

Exact steps or command run after this patch:

  1. ls -lh ~/.openclaw/logs/gateway.err.log* ~/.openclaw/logs/gateway.log* to record the starting state.
  2. Ran the patched applyGatewayLogRetention from this branch via tsx with OPENCLAW_GATEWAY_LOG_MAX_BYTES=1048576 and OPENCLAW_GATEWAY_LOG_ARCHIVES=1.
  3. ls -lh ~/.openclaw/logs/gateway.err.log* ~/.openclaw/logs/gateway.log* again to confirm the rotation happened.
  4. launchctl kickstart -k gui/$UID/ai.openclaw.gateway to drive the live LaunchAgent through a restart, the same path the reporter uses as their workaround.
  5. ls -lh ~/.openclaw/logs/gateway.err.log* ~/.openclaw/logs/gateway.log* once more to confirm launchd recreated the sink and the archive was preserved.

Evidence after fix: copied terminal output from the run on my machine.

Before the patched helper ran:

$ ls -lh ~/.openclaw/logs/gateway.err.log* ~/.openclaw/logs/gateway.log* 2>&1
-rw-r--r--  1 adhi  staff    25M May  9 09:57 /Users/adhi/.openclaw/logs/gateway.err.log
-rw-r--r--  1 adhi  staff   322K May  9 09:57 /Users/adhi/.openclaw/logs/gateway.log

Helper return value:

{
  "stdout": { "rotated": false, "reason": "below-cap", "sizeBytes": 329469 },
  "stderr": {
    "rotated": true,
    "archivedTo": "/Users/adhi/.openclaw/logs/gateway.err.log.1",
    "sizeBytes": 25740576
  },
  "limits": { "maxBytes": 1048576, "archives": 1 }
}

State right after the helper, before kickstart:

$ ls -lh ~/.openclaw/logs/gateway.err.log* ~/.openclaw/logs/gateway.log* 2>&1
-rw-r--r--@ 1 adhi  staff    25M May  9 09:57 /Users/adhi/.openclaw/logs/gateway.err.log.1
-rw-r--r--  1 adhi  staff   322K May  9 09:57 /Users/adhi/.openclaw/logs/gateway.log

State after launchctl kickstart -k gui/$UID/ai.openclaw.gateway:

$ ls -lh ~/.openclaw/logs/gateway.err.log* ~/.openclaw/logs/gateway.log* 2>&1
-rw-------  1 adhi  staff   205B May  9 10:03 /Users/adhi/.openclaw/logs/gateway.err.log
-rw-r--r--@ 1 adhi  staff    25M May  9 10:03 /Users/adhi/.openclaw/logs/gateway.err.log.1
-rw-r--r--  1 adhi  staff   322K May  9 10:03 /Users/adhi/.openclaw/logs/gateway.log

Observed result after fix:

  1. The 25 MB stderr sink rotated to .1 because it was over the 1 MB cap.
  2. The 322 KB stdout sink stayed put because it was below the cap. Healthy paths are a no-op, the helper just stats once and returns.
  3. After launchctl kickstart -k, launchd recreated gateway.err.log fresh (205 bytes of fresh runtime output) and the archive at .1 was preserved with the original 25 MB intact.

This matches the design: rotation only fires when the file is over the cap, archive is kept exactly once, and the next restart starts writing into a fresh sink instead of appending to the tens-of-gigabytes file.

What was not tested: I did not live-reproduce the original 18-19 GB CPU/dep-staging loop on current main; that half of the linked report stays open for separate maintainer-led investigation as clawsweeper recommended. I also did not exercise the Windows or Linux daemon paths because launchd is the only daemon owner that wires StandardErrorPath to a fixed file (Linux journals through journald, Windows uses Scheduled Tasks).

Validation

pnpm vitest run src/daemon/log-retention.test.ts src/daemon/launchd.test.ts src/daemon/launchd-restart-handoff.test.ts src/daemon/restart-logs.test.ts
Test Files  4 passed (4)
     Tests  77 passed (77)

log-retention.test.ts covers: defaults, env parsing, junk-value fallback, cap clamping, missing file, below-cap no-op, oversize rotation, archive cascade with archives>1, archives=0 drop-without-backup, maxBytes=0 disabled escape hatch, ENOENT-tolerant pre-existing-archive cleanup, and non-ENOENT stat error propagation.

launchd.test.ts adds two new regression tests pinning the call order in restartLaunchAgent: retention runs before scheduleDetachedLaunchdRestartHandoff on the self-handoff path, and retention runs before launchctl kickstart on the direct path. The existing launchd.test.ts suite (which mocks node:fs/promises without populating the log paths) keeps passing because retention sees ENOENT and no-ops on those test runs.

pnpm format:check and pnpm exec oxlint are clean on the four touched files. pnpm check:changelog-attributions passes with the new entry.

Scope

What changes:

  • New applyGatewayLogRetention helper, hooked into install, plist rewrite, and both restart paths.
  • Two new env vars (OPENCLAW_GATEWAY_LOG_MAX_BYTES, OPENCLAW_GATEWAY_LOG_ARCHIVES); no new JSON config knob.
  • One CHANGELOG entry under Unreleased > Fixes, with non-closing Refs #79422 wording.

What does not change:

AI / vibe-coding disclosure

Per CONTRIBUTING.md's AI-assisted disclosure policy:

  • Model: Claude Opus 4.7 (Anthropic)
  • I added the helper, the integration points, and the test suite, then hand-reviewed each file before opening this PR.
  • I ran the four-file vitest suite from clawsweeper's acceptance criteria locally; all 77 tests pass.
  • I did not live-reproduce the CPU/dep-staging loop on macOS. That half of the report is left to maintainer triage as clawsweeper suggested.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 9, 2026
@clawsweeper

clawsweeper Bot commented May 9, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I did a careful shell check against current main, and the useful part of this older PR is already implemented there.

Close this older PR: current main has a bounded, rotating Gateway file logger, while the remaining raw launchd stderr policy is separately tracked and cannot safely be revived from this stale branch.

So I’m closing this older PR as already covered on main rather than keeping a mostly-duplicated branch open.

Review details

Best possible solution:

Keep retention in the structured logger and address raw macOS stderr visibility, if desired, through a fresh current-main change for #90711.

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

No current-main failure path was established: source and tests show structured Gateway logs rotate at the write owner, while launchd raw stderr now follows a different policy.

Is this the best way to solve the issue?

No; current main’s logger is the canonical active-write owner, so the branch’s restart-time daemon rotation is no longer the best solution.

Security review:

Security review cleared: The proposed rotation code adds no dependency, credential, permission, or supply-chain surface.

AGENTS.md: found and applied where relevant.

What I checked:

Likely related people:

  • Peter Steinberger: Current-main blame attributes both the rotating file transport and LaunchAgent service-file boundary to this commit. (role: current logging and launchd source contributor; confidence: medium; commits: a0f4d5462a4e; files: src/logging/logger-file-transport.ts, src/daemon/launchd-service-files.ts)

Codex review notes: model internal, reasoning high; reviewed against 2d3612da6bd2; fix evidence: commit a0f4d5462a4e, main fix timestamp 2026-08-16T19:57:34Z.

@openclaw-barnacle openclaw-barnacle Bot added proof: supplied External PR includes structured after-fix real behavior proof. and removed triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 9, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 9, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 9, 2026
@adhirajhangal

Copy link
Copy Markdown
Contributor Author

Thanks @clawsweeper. Addressed the P2 in fixup ad6e8df5 on this same branch.

applyGatewayLogRetention(serviceEnv) now runs before the isCurrentProcessLaunchdServiceLabel self-handoff branch in restartLaunchAgent, so both restart paths rotate the launchd-owned stdout/stderr sinks:

  • Direct kickstart path (operator runs openclaw gateway restart from a separate process tree): retention runs, then enable + kickstart -k.
  • Self-handoff path (gateway calling restart on itself from inside the managed LaunchAgent): retention runs, then scheduleDetachedLaunchdRestartHandoff schedules the detached helper. The detached helper itself stays unchanged (it only invokes launchctl enable/kickstart/bootstrap on a delay), since the rotation already happened in-process before scheduling.

Added two regression tests in src/daemon/launchd.test.ts to lock the order in:

  • rotates oversize launchd-owned logs before scheduling the self-handoff — asserts the call sequence is ["retention", "handoff"].
  • rotates oversize launchd-owned logs before kickstart on direct restarts — asserts retention is called and indexed before any kickstart launchctl call.

Acceptance criteria results on this fixup:

$ pnpm vitest run src/daemon/log-retention.test.ts src/daemon/launchd.test.ts src/daemon/launchd-restart-handoff.test.ts src/daemon/restart-logs.test.ts
 Test Files  4 passed (4)
      Tests  77 passed (77)
$ pnpm exec oxfmt --check --threads=1 src/daemon/launchd.ts src/daemon/log-retention.ts src/daemon/log-retention.test.ts src/daemon/launchd-restart-handoff.ts
All matched files use the correct format.

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 9, 2026
The launchd plist points StandardOutPath and StandardErrorPath at
~/.openclaw/logs/gateway.log and gateway.err.log, and launchd just
appends forever. When a tight error loop fires (the reporter on
openclaw#79422 saw acpx/runway/tts-local-cli dep-staging
spinning), gateway.err.log can reach 18-19 GB between restarts and
fill the disk.

Add a pure helper that rotates either sink to {path}.1 once it crosses
a configurable cap, dropping any pre-existing archive. Hook it into
the four daemon transitions that touch the log dir or restart the
LaunchAgent: install, plist rewrite, and openclaw gateway restart on
both the direct-kickstart and the in-process self-handoff path
(retention runs before scheduleDetachedLaunchdRestartHandoff so the
detached helper does not need a copy of the rotation logic).

Default cap is 64 MB per stream with one archive (so up to 128 MB on
disk per stream). Configurable via OPENCLAW_GATEWAY_LOG_MAX_BYTES and
OPENCLAW_GATEWAY_LOG_ARCHIVES; setting MAX_BYTES=0 disables retention
entirely. Healthy non-oversized paths just stat once and return.

Refs openclaw#79422 (log-retention half only; the
CPU/dep-staging loop in that issue stays open for separate
live-profiling).
@adhirajhangal
adhirajhangal force-pushed the fix/79422-daemon-log-retention branch from ad6e8df to 9be6dae Compare May 9, 2026 17:56
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 9, 2026
@adhirajhangal adhirajhangal changed the title fix(daemon/launchd): cap unbounded gateway stdout/stderr log growth (#79422) fix(daemon/launchd): cap unbounded gateway stdout/stderr log growth (refs #79422) May 9, 2026
@adhirajhangal

Copy link
Copy Markdown
Contributor Author

Thanks @clawsweeper. Addressed the P2 in 9be6dae3 (force-push on this fork branch with the explicit reason of reworking the closing language Codex called out).

Changes:

  • PR title: now fix(daemon/launchd): cap unbounded gateway stdout/stderr log growth (refs #79422) (was (#79422)).
  • CHANGELOG.md: line now ends with Refs #79422 (log-retention half only; the CPU/dep-staging loop in that issue stays open for separate live-profiling). No Fixes #79422 anywhere.
  • Commit message: collapsed to a single commit (the previous fixup is folded in) and rewritten to end with Refs openclaw/openclaw#79422 (log-retention half only; the CPU/dep-staging loop in that issue stays open for separate live-profiling). No Closes keyword anywhere.
  • PR body: explicitly calls out at the top that the language is non-closing for [Bug]: Gateway CPU pegged at 100%+ continuously; gateway.err.log grows to 18-19 GB #79422 and the issue stays open for the CPU investigation.

Verified locally:

$ pnpm exec oxfmt --check --threads=1 CHANGELOG.md
All matched files use the correct format.

$ git log --format=%B -n 1 fix/79422-daemon-log-retention | grep -iE "closes|fixes|resolves" || echo "no closing keywords"
no closing keywords

$ grep -iE "closes|fixes" CHANGELOG.md | grep "79422" || echo "no closing keywords for 79422 in CHANGELOG"
no closing keywords for 79422 in CHANGELOG

Tests still green on the rewritten branch:

$ pnpm vitest run src/daemon/log-retention.test.ts src/daemon/launchd.test.ts src/daemon/launchd-restart-handoff.test.ts src/daemon/restart-logs.test.ts
 Test Files  4 passed (4)
      Tests  77 passed (77)

If a maintainer later wants to release-note this as fully closing #79422 once the CPU side has its own fix, that can happen at squash-merge time by adding a closing keyword in the merge commit body.

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 9, 2026
…uence

Codex P3 on openclaw#79892 noted the direct-restart regression test only
checked that retention and kickstart were each called, not that
retention preceded kickstart. Push "kickstart" into the same
callOrderState event log the retention/handoff mocks already use,
then assert the strict sequence ["retention", "kickstart"] for the
direct-restart test, matching the ["retention", "handoff"] sequence
the self-handoff test already pins.
@adhirajhangal

Copy link
Copy Markdown
Contributor Author

Thanks @clawsweeper. Addressed the P3 in 89150648.

The direct-restart test now pins the strict order in a single sequence the same way the self-handoff test does. I extended the existing execFileUtf8 mock to push "kickstart" into callOrderState.events whenever a launchctl kickstart is invoked, so both tests now read symmetrically:

// self-handoff path
expect(callOrderState.events).toStrictEqual(["retention", "handoff"]);

// direct path
expect(callOrderState.events).toStrictEqual(["retention", "kickstart"]);

If retention ever drifts back below the kickstart call (or below the self-handoff scheduling), one of those two assertions fails immediately rather than just confirming both events happened.

$ pnpm vitest run src/daemon/log-retention.test.ts src/daemon/launchd.test.ts src/daemon/launchd-restart-handoff.test.ts src/daemon/restart-logs.test.ts
 Test Files  4 passed (4)
      Tests  77 passed (77)

$ pnpm exec oxfmt --check --threads=1 src/daemon/launchd.test.ts
All matched files use the correct format.

$ pnpm exec oxlint src/daemon/launchd.test.ts
Found 0 warnings and 0 errors.

Separately, the checks-node-agentic-plugin-sdk job on the previous head SHA was failing on src/plugin-sdk/qa-runner-runtime.integration.test.ts (Unable to resolve bundled plugin public surface qa-linked/runtime-api.js), a file this PR does not touch and a path this PR does not exercise. The same job is FAILURE on every other open PR I checked (#79914, #79913, #79912, #79911, #79901), so it looks like upstream plugin-sdk breakage rather than anything caused here. Happy to file a separate small PR to add the missing fixture if it would help unblock everyone, otherwise will let main settle and ride the next CI run on this branch.

@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 Jun 1, 2026
@clawsweeper clawsweeper Bot added rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. labels Jun 1, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Jun 2, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 2, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. labels Jun 2, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jun 14, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. and removed merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Jun 23, 2026
@clawsweeper

clawsweeper Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

@adhirajhangal thanks for the PR. ClawSweeper is still waiting on real behavior proof before this can move forward.

Useful proof can be a screenshot, short video, terminal output, copied live output, linked artifact, or redacted logs that show the changed behavior after the fix. Please redact private tokens, phone numbers, private endpoints, customer data, and anything else sensitive.

Once proof is added to the PR body or a comment, ClawSweeper or a maintainer can re-check it.

@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. label Aug 5, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. P2 Normal backlog priority with limited blast radius. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. P1 High-priority user-facing bug, regression, or broken workflow. labels Aug 16, 2026
@clawsweeper

clawsweeper Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

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

Labels

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: supplied External PR includes structured after-fix real behavior proof. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant