Skip to content

fix(agents): bound shell snapshot memory in long-running Gateways - #162967

Merged
steipete merged 2 commits into
mainfrom
upd/upd-shell-snapshot-cache-bound
Oct 1, 2026
Merged

steipete merged 2 commits into
mainfrom
upd/upd-shell-snapshot-cache-bound

Conversation

@steipete

@steipete steipete commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Closes #162582

What Problem This Solves

Long-running Gateways permanently retain shell snapshot cache entries for every distinct working directory and trusted environment they encounter.

User Impact

Shell snapshot memory now tracks recent keys instead of lifetime key history. Frequently used snapshots stay cached; evicted keys can reuse fresh files on disk. Existing snapshots remain valid across updates, with no configuration or state migration required.

Why This Change Was Made

The snapshot owner has no session identity or session-disposal hook: its keys are shared process-wide across cwd/environment combinations. Reuse the existing LruCache with a documented 128-entry cap at that owner. The existing five-minute freshness check and disk snapshot lifecycle remain unchanged.

Production: +6/-1 lines (net +5). Tests: +66 lines. Documentation: +1/-1. The small production increase consists of the shared-cache import, named bound and reason, and cache construction.

Evidence

Linux Node 24.19.0 / pnpm 12.5.1 on Blacksmith Testbox tbx_01m3wdnxgj8y3ahtkdh47cr7nd (lease run). Final head: 0c9073485a34c4fa48f2cb733c5f3052008ec328. Source fetched by exact commit, without a local tree sync.

  • Regression exercises maybeWrapCommandWithShellSnapshot with 256 distinct keys plus an interleaved active key. Original production code fails: expected 257 to be 128; fixed code retains 128 and keeps the active key hot. Single-file command: pnpm test src/agents/shell-snapshot.cache.test.ts --maxWorkers=1, Final-head cost: 79 ms test time, 1.93 s measured command wall time. Hosted CI timing is not yet available at this authoring handoff.
  • Eight related test files passed three times on 5795d07b2690 (the subsequent fixture correction changes only erased TypeScript syntax): 89 passed and one existing /bin/zsh authorization skip per run; zsh is not installed on the lease, so real zsh behavior was not proven. Wall times: 63.78 s, 39.81 s, 38.01 s, including shared preparation. Longest observed individual test: 16.77 s.
  • Synthetic RSS loop invokes the real snapshot owner for 201,000 keys with filesystem/process I/O mocked. Post-GC RSS: 265.3 MiB before, 232.0 MiB after. Live heap: 74.4 MiB before, 6.0 MiB after; fixed live heap stays about 6.0 MiB between 101,000 and 201,000 keys. Newest-key probe: 256 retained before, 128 after. Loop time: 7.85 s before, 7.72 s after. RSS includes V8's retained allocation capacity; this is cache-retention proof, not a whole-Gateway memory benchmark.
  • Final-head node scripts/check-changed.mjs --base 84dc4c73ceee27d8067570fc1cdc6e2bc5dbe272 --head 0c9073485a34c4fa48f2cb733c5f3052008ec328 passed, exit 0, in 441.12 s: production types, all 27 test-type graphs, lint, formatting, and selected repository guards. The preceding cold pass took 1,305.21 s but its SSH transport failed to return a completion status, so the cached rerun recorded an explicit remote exit marker.
  • Independent Codex P1 review: full candidate reviewed; the committed fixture correction was separately reviewed clean, with no remaining actionable findings.

The first changed-file run caught an unnecessary ChildProcess cast in the new fixture; the cast and unused type import were removed. Production behavior and the regression's runtime behavior are unchanged by that correction.

Related suites
src/process/supervisor/supervisor.one-shot-tools.test.ts
src/agents/bash-tools.exec-host-gateway.test.ts
src/agents/shell-snapshot.spawn.test.ts
src/agents/shell-snapshot.test.ts
src/agents/bash-tools.exec-authorization.integration.test.ts
src/agents/bash-tools.exec-github-credential.test.ts
src/agents/shell-snapshot.broker.test.ts
src/agents/shell-snapshot.cache.test.ts

@clawsweeper

clawsweeper Bot commented Oct 1, 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 agents Agent runtime and tooling size: S labels Oct 1, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 1, 2026
@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 1, 2026, 4:31 PM ET / 20:31 UTC (Revision 2).

ClawSweeper review

What this changes

This PR limits shell startup snapshots held in memory to 128 recently used keys, adds a retention regression, and documents reuse of fresh disk snapshots after eviction.

Merge readiness

✅ Ready for maintainer review

The fix remains necessary: current main and v2026.9.7 retain an unbounded snapshot cache. The pinned patch addresses that retention site without changing snapshot formats or execution policy; no actionable introduced defect was found.

Priority: P2
Reviewed head: 0c9073485a34c4fa48f2cb733c5f3052008ec328

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with meaningful owner-boundary coverage, measured validation, and no actionable findings.
Proof confidence 🌊 off-meta tidepool Not applicable: The author is independently verified as a repository admin, so external-contributor runtime proof is exempt. The wrapping-entrypoint regression and mocked-I/O heap comparison support bounded retention but do not constitute a live Gateway benchmark. No persisted format or storage contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The author is independently verified as a repository admin, so external-contributor runtime proof is exempt. The wrapping-entrypoint regression and mocked-I/O heap comparison support bounded retention but do not constitute a live Gateway benchmark. No persisted format or storage contract changes.
Evidence reviewed 10 items Pinned introduced change: The merge-base-to-head delta changes only cache construction, its bound, the owner-boundary regression, and exec documentation.
Current main still needs the repair: Current main uses a module-level Map with get/set and no eviction. Its snapshot module is identical to the pinned merge-base module.
Latest release remains affected: The v2026.9.7 source also retains snapshots in an unbounded Map; the requested cache bound is absent.
Findings None None.
Security None None.

How this fits together

Gateway-hosted shell execution prepares startup snapshots containing safe aliases, functions, and environment values. The snapshot cache reuses that preparation across working directories before wrapping commands for execution.

flowchart TD
  A[Gateway shell command] --> B[Working directory and trusted environment]
  B --> C[Snapshot key]
  C --> D[Bounded recent snapshot cache]
  D --> E[Fresh disk snapshot or capture]
  E --> F[Wrapped shell command]
  D --> F
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +5, Tests +66, Docs 0. Total +71 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 1 6 1 +5
Tests 1 66 0 +66
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 73 2 +71

Review metrics

Metric Value Why it matters
Snapshot retention bound Unbounded → 128 recent keys Retained cache entries now track recent use rather than lifetime working-directory and environment history.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #162582
Summary: This PR is the candidate fix for the linked issue's exact unbounded snapshot-retention site.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Keep snapshot retention bounded at its existing process-wide owner while preserving freshness, trusted capture, and disk reuse.

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

Yes, source establishes the current-main retention path: each distinct snapshot key enters a process-wide Map with no eviction. The PR records a failing baseline regression; this review did not execute it.

Is this the best way to solve the issue?

Yes, reusing the existing LRU at the snapshot owner is a narrow repair that preserves its callers and disk lifecycle.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 95af525a2f8b.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This repairs gradual memory retention in long-running Gateways with a small, focused owner-level change.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The author is independently verified as a repository admin, so external-contributor runtime proof is exempt. The wrapping-entrypoint regression and mocked-I/O heap comparison support bounded retention but do not constitute a live Gateway benchmark. No persisted format or storage contract changes.

Evidence

What I checked:

  • Pinned introduced change: The merge-base-to-head delta changes only cache construction, its bound, the owner-boundary regression, and exec documentation. (src/agents/shell-snapshot.ts:76, 0c9073485a34)
  • Current main still needs the repair: Current main uses a module-level Map with get/set and no eviction. Its snapshot module is identical to the pinned merge-base module. (src/agents/shell-snapshot.ts:73, 95af525a2f8b)
  • Latest release remains affected: The v2026.9.7 source also retains snapshots in an unbounded Map; the requested cache bound is absent. (src/agents/shell-snapshot.ts, c074824a27c9)
  • Existing cache contract: The shared LRU promotes reads and evicts oldest entries on insertion. The complete snapshot owner preserves its five-minute freshness check, disk validation, trusted-environment key construction, and fallback behavior. (src/infra/lru-cache.ts:54, 0c9073485a34)
  • Regression and measured validation: The new test exercises the public wrapping entrypoint with 256 distinct keys and an interleaved active key, without adding a production test seam. The captured PR body reports baseline failure at 257 retained entries, fixed retention at 128, 79 ms test time, 1.93 s command wall time, and a final-head changed-check pass. The RSS experiment mocks filesystem/process I/O and is supplemental cache-retention evidence, not a live Gateway benchmark. No tests were executed during this read-only review. (src/agents/shell-snapshot.cache.test.ts:35, 0c9073485a34)
  • Author trust independently verified: Live GitHub permission lookup identifies steipete as a repository admin. This establishes trusted-author proof treatment despite the pull endpoint reporting CONTRIBUTOR rather than the supplied Repository State MEMBER association.

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-01T20:00:31.492Z sha 0c90734 :: needs maintainer review before merge. :: none

@steipete
steipete marked this pull request as ready for review October 1, 2026 20:23
@steipete
steipete merged commit 24baf01 into main Oct 1, 2026
197 of 198 checks passed
@steipete
steipete deleted the upd/upd-shell-snapshot-cache-bound branch October 1, 2026 21:08
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
snapshotCache in src/agents/shell-snapshot.ts was a process-wide Map that retained one entry per distinct cwd/environment key for the Gateway's lifetime, so long-running Gateways with many sessions grew without bound. The owner now reuses the existing LRU cache with a documented 128-entry limit; the active key stays cached and a miss recomputes. At 201k synthetic keys RSS fell from 265 MiB to 232 MiB and live heap from 74 MiB to 6 MiB.

Closes openclaw#162582
RomneyDa added a commit that referenced this pull request Oct 2, 2026
* fix(state): state read worker loads the whole Gateway graph (+486 MB RSS) (#161003)

* fix(state): keep the state read worker out of the update write graph

Move reconciliation inspection and candidate selection into a read-only
module shared by the state reader and reconciliation writer. The standalone
reader disables code splitting, so its former write-side import also
bundled dynamic failure-fact/Doctor imports and the Gateway runtime.

At release tip 56fb887, the built worker was 52,186,708 bytes with
9,768 esbuild inputs. After this split it is 3,491,598 bytes with 1,025
inputs, measured with packages external for both input graphs.

Keep the read queries, eligibility checks, and transactional reconciliation
bodies unchanged. The full build and 95 focused tests pass.

* test(state): keep standalone workers out of the Gateway server graph

Bundle each standalone entry with esbuild and reject transitive Gateway server, flow, wizard, in-process dispatch, and update-write inputs. Restoring the release-tip reader import and writer exports fails only the state reader with 682 forbidden inputs; the fixed graph passes all nine entries.

Validation: pnpm test test/scripts/runtime-process-build-graph.test.ts --maxWorkers=1 (3.67s wall, 0.678s Vitest); negative control 3.732s wall. oxfmt, oxlint, and independent review pass.
(cherry picked from commit f2715ed)

* fix: retain SQLite workers through package replacement (#162076)

Resolve read-only worker launches through the running updater's retained
generation. Keep session reuse generation-aware and join child work before
retiring its runtime files. This protects future self-updates; an already
loaded 2026.9.6 driver retains its first-hop limitation.

Refs #161865

(cherry picked from commit f59e979)

* fix(update): retry the Windows backup rename on transient locks (#162231)

On Windows the managed update swap renamed the live package tree to its backup location once; a transient EPERM/EBUSY/EACCES from an antivirus, indexer, or Scheduled Task handle failed the swap and rolled the update back. The filesystem owner of the swap now retries those codes with bounded backoff (16 attempts), records each retry, re-checks package identity and update authority between attempts, and reports a named failure after the bound. POSIX behavior is unchanged.

Refs #162027

(cherry picked from commit b5555b0)

* fix: avoid duplicate SQLite copies during update rehearsal (#162403)

* fix: avoid duplicating SQLite snapshots during update rehearsal

* test: target final snapshot publication in race hooks

* test: exercise staging cleanup after snapshot transfer

* docs: describe row-preserving update rehearsals

(cherry picked from commit c77a055)

* perf(update): allow native Git runtime directory copies (#162387)

Co-authored-by: Peter Steinberger <[email protected]>
(cherry picked from commit 1129326)

* fix: prevent slow Gateway shutdown during memory sync (#162616)

* fix(state): retain publication leases while Gateway drains

* perf(state): preserve normal publication close scheduling

(cherry picked from commit defb7cf)

* perf(gateway): reduce session publication allocations and repeated redaction scans (#162810)

Reduce repeated session-publication allocations and redaction prefilter scans at their lifecycle owners, preserving live recipient authority and byte-identical redaction.

Validated with Node 24 and fork Bun tests, authority negative controls, fixture differential checks, pinned AWS kernel and three-round load benchmarks, a clean post-rebase spot quartet, and green exact-head CI.

(cherry picked from commit 4e4e315)

* fix(agents): bound the shell snapshot cache (#162967)

snapshotCache in src/agents/shell-snapshot.ts was a process-wide Map that retained one entry per distinct cwd/environment key for the Gateway's lifetime, so long-running Gateways with many sessions grew without bound. The owner now reuses the existing LRU cache with a documented 128-entry limit; the active key stays cached and a miss recomputes. At 201k synthetic keys RSS fell from 265 MiB to 232 MiB and live heap from 74 MiB to 6 MiB.

Closes #162582

(cherry picked from commit 24baf01)

* improve: deliver sessions_send replies once

(cherry picked from commit 84c6eb8)

* fix: prevent delegated work from stopping silently

(cherry picked from commit 4f0541e)

* fix(update): canonicalize package activation paths

* test(update): fix the Windows backup-rename regression on native Windows

Inject the platform only into the backup-rename policy. Leave native filesystem staging, verification, and cleanup on the host platform so the Linux policy case reaches its injected EPERM on Windows. Preserve all existing failure, retry, rollback, and content assertions. Refs #162027.

* fix(sessions): keep announce skip token private

* test(sessions): avoid awaiting detached reply flow

* test(ci): include infra in shared Windows partitions (#162310)

* test(release): align backport companion expectations

* test(sqlite): verify snapshot content receipts

* test(subagents): align retired reply token expectations

* test(release): align completion cutover integrations

* test(release): recognize direct peer replies

* test(release): align requester yield guidance

* test(release): align direct session reply fixtures

* fix(release): preserve session continuation authority

* fix(codex): avoid startup app-server bursts for idle agents (#163129)

Closes #163026

## What Problem This Solves

Fixes a burst of Codex app-server processes when a Gateway starts with many configured agents and explicit Codex homes. Thanks to @609NFT for reporting the remaining startup pressure after #162912.

## User Impact

Idle agents no longer start catalog-only app-servers at Gateway activation. Explicit homes hydrate when an authorized catalog request first needs them, using the existing progressive loading behavior. Native turns remain available without prior catalog hydration.

## Why This Change Was Made

A concurrency limit on initialization alone would still accumulate retained shared clients. Removing eager fleet hydration avoids both startup fanout and catalog-only retention without changing shared-client pooling, active-turn ownership, stored data, or cache schemas. The service still captures its background execution scope; on-demand catalog hydration and refresh keep their existing owner.

No overlap with Pash/Sarah changes: their history on the touched documentation concerns output projection, scheduled app authority, Computer Use, and managed binary selection, not catalog activation.

## Evidence

Real Gateway and packaged native Codex app-servers in an isolated Linux arm64/Node 24.21 container, with 739 synthetic agents and seven additional explicit homes:

| Startup measurement | Main baseline | Candidate |
| --- | --- | --- |
| App-server processes spawned / peak live | 16 / 16 (8 wrapper/native pairs) | 0 / 0 |
| Peak aggregate process RSS, 180-second window | 3,315,548 KiB | 1,744,276 KiB; repeat 2,247,344 KiB |
| Gateway readiness | 77.84 seconds (earlier sample 78.42) | 78.78 seconds; repeat 80.97 |

Readiness remains approximately 80 seconds; this does not claim a latency improvement. The synthetic profile demonstrates elimination of activation-driven native processes, not reproduction of the reporter's host OOM or blocked-egress timeout count.

- On-demand catalog RPCs returned the exact three seeded session IDs for agents `agent000`, `agent001`, and `agent738`, including the normal cold `catalog_pending` transition.
- Exact-head live gate: zero app-server processes before the request, then agent `agent738` completed a real `openai/gpt-5.4-mini` turn through the **codex** harness in 4.65 seconds with the expected reply. Utility-model jobs, heartbeat, cron, and model discovery were disabled; one inference turn.
- Regression fails on the baseline because activation starts resident work; passes on the candidate and verifies that subsequent demand initializes the home. The stop, request-lifetime, homes, backoff, and listing-cache files pass: **41 tests**, 34.39 seconds wall total; the changed stop file's three tests took 136 ms.
- `git diff --check` passes.
- Inspected Codex app-server lifecycle at `codex-rs/app-server/src/lib.rs:244–307`: shutdown drains admitted turns. This fix does not alter that lifecycle or retire a sibling turn's shared connection.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 01d479d)

* test(release): make session describe drain bound structural

* fix(release): complete session and drain backports

* test(release): cover cron send cutover

* test(release): align completion prompt expectations

* refactor(gateway): satisfy line caps

* test(gateway): remove stale fixture import

* test(gateway): isolate heartbeat lifecycle cases

* test(gateway): start lazy catalog hydration

* test(ui): tolerate sub-pixel sidebar roster layout (#161068)

(cherry picked from commit 4d638fd)

* test(ui): stabilize model refresh tooltip hover

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: Jason (Json) <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

1 participant