Skip to content

fix: keep agent temporary files in owned scratch - #202074

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-agent-tmp-scratch-ttl-20260919
Nov 19, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-agent-tmp-scratch-ttl-20260919

Conversation

@steipete

@steipete steipete commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Agent validation commands can leave large temporary trees in host /tmp, outside OpenClaw's 24-hour scratch cleanup. On hosts where /tmp is tmpfs, that consumes memory and swap until an operator intervenes.

User Impact

Local agent commands now default TMPDIR, TMP, and TEMP to their workspace's .openclaw/tmp. Temporary validation output is disposable under the existing 24-hour rule, even when artifacts reference it. Live and queued agent work remains protected; durable outputs belong outside scratch. After those runs settle, a detached background service alone does not extend the 24-hour lifetime of unchanged workspace scratch. Services needing longer-lived files must place them outside scratch or explicitly select a temp root with their own cleanup.

Why This Change Was Made

Connect core exec, local CLI execution, and native Codex shell/Code Mode environment preparation to the existing scratch owner. Codex obtains the path through its run-bound host capability and applies it through thread shell policy, preserving shared app-server reuse. Docker/Podman commands use scratch in their writable workspace mount. Read-only workspaces keep writable temporary files in the container-private /tmp tmpfs, owned and released by the container lifecycle.

The existing cleanup inventory now includes configured agent and local sandbox workspaces, including sandbox directories left after container retirement. Queued protection uses the production session selector, including attachment grants and immutable skill-library isolation. Sandbox scope resolution and active-command custody reuse their existing owners. No new TTL implementation, configuration option, schema, reference-protection index, or cache. Explicit CLI/command/container environment overrides remain supported. Remote execution keeps its own paths. Programs that explicitly choose /tmp can bypass the policy; arbitrary host temp entries are not swept by name. Deep workspace paths can exceed Unix-domain socket limits: those tools need a short workspace or an explicit short-temp override with their own cleanup. The existing test runner already owns that exception.

Related: #193677. The short-lived native socket-path workaround from #196509 remains intact.

Evidence

A real core exec from a nested working directory creates its temporary file inside checkout scratch. The committed regression fails on base f685aad5977d707e47ba402b3d072e482a6b091b at that assertion and passes with this change. Native Codex engine tests cover fresh and cold-resumed shells, login/snapshot variations, and restrictive environment filters. Local CLI tests cover default routing and explicit overrides; the generated sandbox shell creates an actual temporary directory. Hosted review identified a read-only-workspace regression; two real-shell tests reproduced it for Docker and Podman, and all 40 backend tests pass after preserving container-private temp for that mode. Cleanup tests verify expiry, live/queued protection, and queued sandbox protection after its last container registry row retires. Attachment and skill-library isolation regressions fail before the correction; all 17 custody and five managed-custody tests pass afterward. A real Docker read-only bind-mount probe fails before the temp-path correction and succeeds afterward.

Synthetic btrfs workload: 62,000 scratch files / 1.181 GB, beside a physical 37.63 GB synthetic SQLite storage fixture with 5,000 session rows. Five serial A1/A2 pairs per variant (10 observations each), using the same unchanged TTL owner:

Metric Inherited temp Workspace temp
Expired validation scratch reclaimed 0 670.56 MB
Total reclaimed, including existing coverage cleanup 38.10 MB 708.66 MB
Owner wall median / p95 2.118 / 3.123 s 41.630 / 54.049 s
Deliberate pacing 1.5 s 29.0 s
Process CPU median / p95, workers included 0.559 / 1.616 s 11.075 / 14.684 s
Main-thread CPU median / p95 12.475 / 27.676 ms 171.015 / 265.320 ms
Separate sampled main-isolate allocation A1 / A2 1.257 / 0.757 MB 2.325 / 1.936 MB

Every run preserves fresh/live/outside files and reports zero cleanup errors. This is the added cost of reclaiming previously unowned scratch, not a speedup comparison or a production-stall reproduction. A/A wall variation reached 24% on the shared virtual disk. The SQLite file supplies storage shape; this filesystem benchmark does not query the agent schema or measure whole-Gateway latency. Worker/native allocations are excluded from the heap sample.

Reproduce with node --expose-gc --import ./scripts/tsx.mjs scripts/perf/scratch-cleanup-measure.ts --root <new-btrfs-directory> --samples 5 --mode timing --agent-temp; use --samples 1 --mode allocation for the separate allocation pair.

Focused tests, the full package build, targeted typechecks/lint, formatting, line-cap checks, and final pnpm check:changed at 8c3d312db0fa258486ab502ad7ad128a83ed8600 pass. An earlier expanded check exposed an inherited SDK surface-budget regression: exact base and candidate both have 3,908 exports / 2,250 callables against limits 3,894 / 2,243. The check passes at 422ff062032e6; the first expansion at 5795128db2d0c (#201073) fails at 3,896 / 2,244. This is a main regression, not a budget change in this PR. No standalone SDK export was added. Final snapshot Codex autoreview is clean through P2. Production delta: +197/-49 = +148 lines, required for the missing environment handoffs, run-bound host operation, and root/custody coverage; repeated Codex placement checks and duplicate sandbox active-use logic were consolidated.

@clawsweeper

clawsweeper Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-19T22:08:53.348113Z 8c3d312 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper review

Please review final head 516ec9f, especially execution placement, explicit environment overrides, and live/queued scratch custody after container retirement. Local Codex autoreview is clean through P2; regression and synthetic btrfs evidence are in the PR body.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling extensions: codex size: L labels Nov 19, 2026
@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@github-actions

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 8c3d312db0fa258486ab502ad7ad128a83ed8600
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/sandbox/container-usage.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/agents/sandbox/docker-backend.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/agents/sandbox/prune.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/agents/sandbox/session-selection.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 19, 2026

@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: 516ec9ff9f

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/sandbox/docker-backend.ts Resolved
@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Routes local agent temporary files into workspace scratch and extends existing cleanup discovery and custody to those workspaces.

Example: An agent runs Node temporary-file creation from /workspace/project/nested.

  • Before: The file uses inherited host temporary storage outside workspace scratch cleanup.
  • After: The file uses /workspace/project/.openclaw/tmp, eligible for existing 24-hour cleanup after agent work settles.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The implementation appears correct and prior findings are resolved or explicitly accepted; required product-flow proof remains incomplete.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Agent validation output accumulates outside managed cleanup and can consume host disk, memory, and swap.
Reason: The maintainer owns this direction and explicitly accepts disposable-scratch expiry for detached services; no renewed retention decision is needed.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR addresses unowned temporary-file growth; the earlier sandbox defects are fixed, and detached-service expiry is an explicitly accepted tradeoff.

Priority: P2
Reviewed head: 8c3d312db0fa258486ab502ad7ad128a83ed8600

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Provide redacted terminal or live output showing workspace temp routing through shipped OpenClaw execution on fresh and latest-stable-upgraded setups, with explicit overrides preserved; redact credentials, IPs, and non-public endpoints.
Agent review details

How this fits together

Agent execution prepares child environments for core exec, local CLI backends, and native Codex; Gateway maintenance discovers their scratch roots and applies existing expiry and live-run protection.

flowchart TD
 A[Admitted agent run] --> B[Shared scratch preparation]
 B --> C[Local execution environments]
 C --> D[Workspace scratch files]
 E[Session and sandbox custody] --> F[Existing scratch maintenance]
 D --> F
 F --> G[Expired files removed]
Loading

Technical review

Best possible solution:

Use shared scratch preparation and existing execution and custody owners while preserving explicit overrides and the accepted 24-hour policy.

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

Current-main source inherits host temporary storage without routing it into checkout scratch; the committed regression exercises temporary-file creation, but this review ran no target code.

Is this the best way to solve the issue?

The implementation addresses allocation at its producer, shares one scratch preparer across local paths, and reuses existing cleanup, sandbox selection, and active-container custody without a competing retention owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Scratch cleanup and custody keeps the original intent (99ba844: Expire disposable scratch after 24 hours while protecting live and queued agent work.)
  • Inherited temporary-directory prompt guidance changes intended behavior with a stated reason (7cba067: Prevent native Unix-socket failures beneath deep temporary roots.)
  • Active sandbox usage keeps the original intent (25bb300: Reclaim idle container tmpfs while retaining active turns and tracked commands.)
  • Local CLI environment composition keeps the original intent (968f641: Apply native-login credential filtering after environment overlays.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +148, Tests +300, Docs +32, Other +33. Total +513 across 26 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 16 197 49 +148
Tests 7 313 13 +300
Docs 2 33 1 +32
Config 0 0 0 0
Generated 0 0 0 0
Other 1 36 3 +33
Total 26 579 66 +513

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
Production versus regression coverage Production +197/-49; tests +313/-13 Growth covers distinct environment handoffs, admitted capability lifetime, and sandbox custody; existing cleanup and active-container policy are reused.

Labels

Label changes:

  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Unowned agent temporary files can accumulate disk usage or tmpfs memory and swap without bounded cleanup.
  • merge-risk: 🚨 compatibility: Default temporary paths and cleanup coverage change; the maintainer explicitly accepts fixed expiry and documents the socket-path tradeoff.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

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 (2 earlier review cycles)
  • reviewed 2026-11-19T21:42:36.121Z sha 516ec9f :: needs changes before merge. :: [P1] Preserve execution when the sandbox workspace is read-only | [P2] Protect the sandbox workspace selected for the queued session
  • reviewed 2026-11-19T22:18:48.816Z sha 8c3d312 :: needs changes before merge. :: [P2] Protect active Gateway processes before expiring their scratch

Reviewed November 19, 2026, 5:30 PM ET / 22:30 UTC (Revision 3).

@steipete

Copy link
Copy Markdown
Contributor Author

Addressed both items from the latest ClawSweeper review in 8c3d312db0fa258486ab502ad7ad128a83ed8600:

  1. Read-only workspace execution: docker-backend.ts:126 preserves writable container-private /tmp for read-only workspaces. Writable workspaces retain owned disk scratch. Both Docker/Podman shell regressions failed before the correction; all 40 backend tests pass afterward. A real Docker read-only bind-mount probe also changes from Read-only file system before to successful source reads and temporary-directory creation afterward. This addresses the separate hosted Codex finding as well.

  2. Queued session isolation: scratch-maintenance-custody.ts:298 now consumes the production resolveSandboxSession result, including attachment grants, required sandbox settings, and immutable skill-library selection. The selector accepts only the metadata slice it uses, so cleanup does not load prompt snapshots. Attachment and library-isolation cases both failed before the correction; all 17 custody tests and five managed-custody tests pass, including protection after container retirement and deletion after queued work settles.

Final staged Codex autoreview is clean through P2. Targeted typechecks/lint and the line-cap check pass. The PR body is current, and new exact-head CI is running. The documentation also calls out the existing Unix-socket path-length tradeoff and explicit short-temp overrides with caller-owned cleanup.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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: 8c3d312db0

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 19, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Addressing item 1 in the latest review (detached Gateway processes) at unchanged head 8c3d312db0fa258486ab502ad7ad128a83ed8600: declined as a retention-policy expansion.

The scope here is the fixed 24-hour disposable-scratch contract established by #193677 and documented in managed-worktrees.md:838: live or queued agent runs protect their checkout; idle sessions and artifact references do not; durable outputs belong outside scratch. An explicitly detached service is deliberately started with no requestOwners and independentService: true at exec-run.ts:575. Its continued existence is not an active or queued agent-run claim.

Consequently, once agent work has settled, unchanged scratch older than 24 hours remains eligible even if a detached service still wants it. This is an intentional product tradeoff. Such services must use ordinary workspace storage for retained state, or an explicit temp override with caller-owned cleanup. Making every detached service pin its scratch owner until process finalization would introduce an additional potentially indefinite retention exception, contrary to this lane's fixed-expiry requirement. No process-reference index or new retention rule is being added. The PR's User Impact now states this consequence explicitly.

The two earlier findings remain fixed, with the numbered response and red/green proof in the previous review response. Final pnpm check:changed also passes on this unchanged head. Please assess the late item against the stated disposable-scratch contract and record the intentional limitation rather than requiring expanded retention.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot removed the status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. label Nov 19, 2026
@clawsweeper clawsweeper Bot added the status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. label Nov 19, 2026
@steipete
steipete merged commit f91bc99 into main Nov 19, 2026
165 of 167 checks passed
@steipete
steipete deleted the steipete/perf-micro-agent-tmp-scratch-ttl-20260919 branch November 19, 2026 22:42
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 20, 2026
* fix: keep agent temporary files in owned scratch

* fix: preserve sandbox temp access and queued isolation custody
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
* fix(worktrees): retain recently used session checkouts

* test(agents): decouple admission proof from workspace creation

(cherry picked from commit f5d35bc)

Release adaptation: reuse the beta.3 adaptation aef0b19dc08b for the stable workspace owner: add existing reader/error imports and the minimal #200691 removed-checkout preflight so activity marking never recreates a removed checkout. Omit only the changed assertion in the Gateway test file absent on this branch; retain existing Gateway readiness and owner coverage.

Companions: #202074 is selected next. #202068 is present-equivalent (5631d96); #202204 changes later main-only GC owner-census behavior; #203057 is an independent probe optimization. Other later overlap concerns unrelated worktree refresh/reclamation, policy, restore UX, or the later absent removed-checkout fixture; not prerequisites (enumerated in lane audit).

Release adaptation: reuse the sibling path-specific realpath spy and no-recreation regression (abce9babd5cab). The original one-shot spy closed authority at the preflight read instead of the target workspace boundary.

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit e3495dac6afc80bd3fe36110008dec96013d2514)
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
* fix: keep agent temporary files in owned scratch

* fix: preserve sandbox temp access and queued isolation custody

(cherry picked from commit f91bc99)

Release adaptation: keep the staged #202815 Git shim implementation and independently assert both Git shim execution and writable owned temp in its merged Docker/Podman fixture. Use the beta.3 isolated custody configuration (896f33d52174), not ambient sandbox inventory.

Companions: #193677 scratch expiry owner is present (99ba844); #202815 is present-equivalent (7d33d1a). #202122 is independent Git/scratch clone reclamation, #202428 is CLI history ownership, #202644 is host file-write authority, and #202874 is workspace cleanup scheduling; none prerequisite. Other later same-path commits concern separate template, sandbox, prompt, sharing, or run-lifecycle policy; see the lane companion audit.

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit a4070bc5b669308210b62a0b80b92c16af768b34)
YuriyPopovDev added a commit to YuriyPopovDev/openclaw that referenced this pull request Nov 26, 2026
Main extracted the same local-execution placement predicate as ownsLocalExecution (openclaw#202074); keep main's helper and drop this branch's duplicate.
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 extensions: codex gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts security-sensitive-changed size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant