Skip to content

fix(sandbox): cleanup workspace directories during prune - #43835

Closed
archerthegoat wants to merge 3 commits into
openclaw:mainfrom
archerthegoat:fix/sandbox-prune-workspace-cleanup
Closed

archerthegoat wants to merge 3 commits into
openclaw:mainfrom
archerthegoat:fix/sandbox-prune-workspace-cleanup

Conversation

@archerthegoat

Copy link
Copy Markdown

Summary

Fixes #43797

Sandbox prune removes Docker containers but leaves workspace directories behind, causing disk space leaks. This PR adds cleanup for the workspace directories.

Changes

  • Added workspace directory cleanup after container removal
  • Uses existing resolveSandboxScopeKey and resolveSandboxWorkspaceDir helpers
  • Skips cleanup for shared scope to avoid affecting other sessions

Test Plan

  • All 164 existing sandbox tests pass
  • Manually verified edge cases (shared scope, missing directories)

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS labels Mar 12, 2026
@greptile-apps

greptile-apps Bot commented Mar 12, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds workspace directory cleanup to the sandbox prune cycle to fix a disk-space leak (issue #43797). The intent is correct, but the implementation places the cleanup inside pruneSandboxRegistryEntries, a shared helper used by both pruneSandboxContainers and pruneSandboxBrowsers.

Key issues found:

  • Workspace deleted on browser-container prune — Because browser containers track their own idle time independently, a browser container can become eligible for pruning while the main sandbox container for the same session is still running. When pruneSandboxBrowsers calls the shared helper, the cleanup block fires and deletes the workspace directory that the active sandbox container is still using. The workspace cleanup must be opt-in per call-site so it only fires from pruneSandboxContainers.

  • agent scope not guarded — shared scope is correctly skipped, but agent scope maps multiple sessions to the same workspace directory. Pruning any one of those sessions' containers will delete the shared directory while sibling sessions may still be active. The same guard applied to shared should be considered for agent.

Confidence Score: 2/5

  • Not safe to merge — the workspace cleanup fires for browser-container pruning, which can silently delete an active session's workspace while the sandbox container is still running.
  • Two logic bugs exist: workspace cleanup runs for both container and browser pruning paths (should be container-only), and the agent scope is not guarded against multi-session scenarios. Both can cause workspace data loss or sandbox errors in production.
  • src/agents/sandbox/prune.ts requires attention — the cleanup block needs to be scoped to container pruning only.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/sandbox/prune.ts
Line: 64-73

Comment:
**Workspace deleted when browser container is pruned**

`pruneSandboxRegistryEntries` is shared by both `pruneSandboxContainers` and `pruneSandboxBrowsers`. This means the workspace cleanup block will also execute when a **browser container** is pruned — not just when the main sandbox container is pruned.

Browser container idle time is tracked independently. If a session's browser container becomes idle (eligible for pruning) while the main sandbox container is still active, `pruneSandboxBrowsers` will call this shared function, reach the cleanup block, and **delete the workspace directory that the still-running sandbox container is actively using**. This is a data-loss bug.

To fix this, the workspace cleanup should only happen for main sandbox container pruning. The simplest approach is to add an opt-in flag:

```typescript
async function pruneSandboxRegistryEntries<TEntry extends PruneableRegistryEntry>(params: {
  cfg: SandboxConfig;
  read: () => Promise<{ entries: TEntry[] }>;
  remove: (containerName: string) => Promise<void>;
  onRemoved?: (entry: TEntry) => Promise<void>;
  cleanupWorkspace?: boolean;  // add this
}) {
  // ...
  if (params.cleanupWorkspace && params.cfg.scope !== "shared") {
    // ...workspace cleanup...
  }
}
```

And then only pass `cleanupWorkspace: true` in `pruneSandboxContainers`:

```typescript
async function pruneSandboxContainers(cfg: SandboxConfig) {
  await pruneSandboxRegistryEntries<SandboxRegistryEntry>({
    cfg,
    read: readRegistry,
    remove: removeRegistryEntry,
    cleanupWorkspace: true,
  });
}
```

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

---

This is a comment left during a code review.
Path: src/agents/sandbox/prune.ts
Line: 65

Comment:
**`agent` scope workspace deleted while other sessions are still active**

The PR description says shared scope is skipped "to avoid affecting other sessions," but the same concern applies to the `agent` scope. When `scope === "agent"`, `resolveSandboxScopeKey` returns `agent:{agentId}` — a single directory shared by **all sessions of that agent**. If one session's container is pruned but another session of the same agent is still running, this code deletes the shared agent workspace while it is still in use.

Consider extending the scope guard or verifying that no other active registry entries share the same `scopeKey` before removing the directory.

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

Last reviewed commit: 71e956a

Comment thread src/agents/sandbox/prune.ts Outdated
Comment on lines +64 to +73
// Clean up workspace directory (only for non-shared scopes)
if (params.cfg.scope !== "shared") {
try {
const scopeKey = resolveSandboxScopeKey(params.cfg.scope, entry.sessionKey);
const workspaceDir = resolveSandboxWorkspaceDir(params.cfg.workspaceRoot, scopeKey);
await fs.rm(workspaceDir, { recursive: true, force: true });
} catch {
// ignore workspace cleanup failures
}
}

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.

Workspace deleted when browser container is pruned

pruneSandboxRegistryEntries is shared by both pruneSandboxContainers and pruneSandboxBrowsers. This means the workspace cleanup block will also execute when a browser container is pruned — not just when the main sandbox container is pruned.

Browser container idle time is tracked independently. If a session's browser container becomes idle (eligible for pruning) while the main sandbox container is still active, pruneSandboxBrowsers will call this shared function, reach the cleanup block, and delete the workspace directory that the still-running sandbox container is actively using. This is a data-loss bug.

To fix this, the workspace cleanup should only happen for main sandbox container pruning. The simplest approach is to add an opt-in flag:

async function pruneSandboxRegistryEntries<TEntry extends PruneableRegistryEntry>(params: {
  cfg: SandboxConfig;
  read: () => Promise<{ entries: TEntry[] }>;
  remove: (containerName: string) => Promise<void>;
  onRemoved?: (entry: TEntry) => Promise<void>;
  cleanupWorkspace?: boolean;  // add this
}) {
  // ...
  if (params.cleanupWorkspace && params.cfg.scope !== "shared") {
    // ...workspace cleanup...
  }
}

And then only pass cleanupWorkspace: true in pruneSandboxContainers:

async function pruneSandboxContainers(cfg: SandboxConfig) {
  await pruneSandboxRegistryEntries<SandboxRegistryEntry>({
    cfg,
    read: readRegistry,
    remove: removeRegistryEntry,
    cleanupWorkspace: true,
  });
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/sandbox/prune.ts
Line: 64-73

Comment:
**Workspace deleted when browser container is pruned**

`pruneSandboxRegistryEntries` is shared by both `pruneSandboxContainers` and `pruneSandboxBrowsers`. This means the workspace cleanup block will also execute when a **browser container** is pruned — not just when the main sandbox container is pruned.

Browser container idle time is tracked independently. If a session's browser container becomes idle (eligible for pruning) while the main sandbox container is still active, `pruneSandboxBrowsers` will call this shared function, reach the cleanup block, and **delete the workspace directory that the still-running sandbox container is actively using**. This is a data-loss bug.

To fix this, the workspace cleanup should only happen for main sandbox container pruning. The simplest approach is to add an opt-in flag:

```typescript
async function pruneSandboxRegistryEntries<TEntry extends PruneableRegistryEntry>(params: {
  cfg: SandboxConfig;
  read: () => Promise<{ entries: TEntry[] }>;
  remove: (containerName: string) => Promise<void>;
  onRemoved?: (entry: TEntry) => Promise<void>;
  cleanupWorkspace?: boolean;  // add this
}) {
  // ...
  if (params.cleanupWorkspace && params.cfg.scope !== "shared") {
    // ...workspace cleanup...
  }
}
```

And then only pass `cleanupWorkspace: true` in `pruneSandboxContainers`:

```typescript
async function pruneSandboxContainers(cfg: SandboxConfig) {
  await pruneSandboxRegistryEntries<SandboxRegistryEntry>({
    cfg,
    read: readRegistry,
    remove: removeRegistryEntry,
    cleanupWorkspace: true,
  });
}
```

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

Comment thread src/agents/sandbox/prune.ts Outdated
@@ -58,6 +60,17 @@ async function pruneSandboxRegistryEntries<TEntry extends PruneableRegistryEntry
await params.remove(entry.containerName);
await params.onRemoved?.(entry);
}

// Clean up workspace directory (only for non-shared scopes)
if (params.cfg.scope !== "shared") {

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.

agent scope workspace deleted while other sessions are still active

The PR description says shared scope is skipped "to avoid affecting other sessions," but the same concern applies to the agent scope. When scope === "agent", resolveSandboxScopeKey returns agent:{agentId} — a single directory shared by all sessions of that agent. If one session's container is pruned but another session of the same agent is still running, this code deletes the shared agent workspace while it is still in use.

Consider extending the scope guard or verifying that no other active registry entries share the same scopeKey before removing the directory.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/sandbox/prune.ts
Line: 65

Comment:
**`agent` scope workspace deleted while other sessions are still active**

The PR description says shared scope is skipped "to avoid affecting other sessions," but the same concern applies to the `agent` scope. When `scope === "agent"`, `resolveSandboxScopeKey` returns `agent:{agentId}` — a single directory shared by **all sessions of that agent**. If one session's container is pruned but another session of the same agent is still running, this code deletes the shared agent workspace while it is still in use.

Consider extending the scope guard or verifying that no other active registry entries share the same `scopeKey` before removing the directory.

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: 71e956acde

ℹ️ 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".

// Clean up workspace directory (only for non-shared scopes)
if (params.cfg.scope !== "shared") {
try {
const scopeKey = resolveSandboxScopeKey(params.cfg.scope, entry.sessionKey);

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.

P1 Badge Derive prune workspace path from stored scope key

In agent scope, entry.sessionKey is already the normalized scope key (for example agent:ops, written in ensureSandboxContainer/updateRegistry), so recomputing it with resolveSandboxScopeKey(params.cfg.scope, entry.sessionKey) is incorrect. resolveAgentIdFromSessionKey treats agent:ops as malformed and falls back to main, which makes prune delete the main workspace while leaving the intended agent workspace behind. Use the stored entry.sessionKey directly when resolving the workspace directory.

Useful? React with 👍 / 👎.

Comment thread src/agents/sandbox/prune.ts Outdated
Comment on lines +64 to +65
// Clean up workspace directory (only for non-shared scopes)
if (params.cfg.scope !== "shared") {

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.

P1 Badge Restrict workspace cleanup to sandbox-container prune path

Workspace cleanup now runs inside the shared pruneSandboxRegistryEntries helper, so it also executes when pruning browser registry entries. That is unsafe because maybePruneSandboxes prunes browsers even when browser support is disabled; in that state, browser entries can become stale while the main sandbox container entry remains fresh, and this block still removes the scope workspace directory used by the active container. Cleanup should only happen once you know no remaining container/browser for that scope is still in use.

Useful? React with 👍 / 👎.

@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: ad23a9ffd0

ℹ️ 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".

}
}
const workspaceDir = resolveSandboxWorkspaceDir(params.cfg.workspaceRoot, scopeKey);
await fs.rm(workspaceDir, { recursive: true, force: true });

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.

P1 Badge Gate workspace deletion on successful container removal

pruneSandboxRegistryEntries deletes the workspace directory even when docker rm -f fails, because the command is run with allowFailure: true and no exit-code check before fs.rm. In environments where Docker is temporarily unavailable (daemon down, permission error), this can delete a scope workspace while the container still exists or is still running with that mount, leading to data loss/inconsistent runtime state; workspace cleanup should happen only after container removal is confirmed.

Useful? React with 👍 / 👎.

try {
const scopeKey = resolveSandboxScopeKey(params.cfg.scope, entry.sessionKey);
// For agent scope, verify no other sessions are using the same workspace
if (params.cfg.scope === "agent") {

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 Keep session-scope duplicate guard before workspace cleanup

The duplicate-workspace safety check is limited to cfg.scope === "agent", but session scope can also have multiple registry entries for the same session key when container naming changes (for example a docker.containerPrefix change creates a new containerName while the old entry remains until prune). In that case, pruning the stale entry will still delete the session workspace used by the newer container, so the remaining-entry check should be applied by scope key for session scope too.

Useful? React with 👍 / 👎.

欧阳 added 2 commits March 12, 2026 18:18
When sandbox prune removes Docker containers, it now also cleans up
the associated workspace directories in ~/.openclaw/sandboxes/.

- Added fs.rm() call to delete workspace directory after container removal
- Skips cleanup for shared scope to avoid affecting other sessions
- Fixes disk space leak reported in openclaw#43797
@archerthegoat
archerthegoat force-pushed the fix/sandbox-prune-workspace-cleanup branch from ad23a9f to 45cdcde Compare March 12, 2026 10:18

@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: 45cdcde1ae

ℹ️ 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".

continue;
}
}
const workspaceDir = resolveSandboxWorkspaceDir(params.cfg.workspaceRoot, scopeKey);

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 Persist workspace root before pruning workspace directories

pruneSandboxRegistryEntries removes workspace paths using params.cfg.workspaceRoot (src/agents/sandbox/prune.ts:82), but it prunes every entry from the shared registry (src/agents/sandbox/prune.ts:49) and agent configs can override sandbox workspaceRoot per agent (src/agents/sandbox/config.ts:194-205). If a stale entry was created under a different root, this cleanup targets the current agent’s root instead of the entry’s original root, which can leave the real stale directory behind and potentially delete an unrelated workspace directory under the wrong root.

Useful? React with 👍 / 👎.

…rkspace

When pruning sandbox containers with agent scope, verify no other active
sessions are using the same workspace directory before deleting it.
This prevents data loss when multiple sessions share an agent workspace.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@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.

Close as superseded by the still-open canonical bug report: the branch is merge-conflicted and the proposed cleanup is unsafe to merge as-is, while #43797 keeps the remaining sandbox workspace leak tracked.

So I’m closing this here and keeping the remaining discussion on the canonical linked item.

Review details

Best possible solution:

Keep #43797 as the canonical tracker and implement a backend-aware prune cleanup there, preserving this PR's useful context without merging this branch.

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

Yes. Source inspection of current main shows sandbox prune removes expired runtimes and registry entries but does not delete non-shared workspace directories; no live Docker/SSH prune was run because this review is read-only.

Is this the best way to solve the issue?

No. Cleaning orphaned workspaces is the right direction, but this PR is not the best solution because it adds recursive deletion without confirmed runtime removal, persisted workspace identity, or current backend compatibility.

Security review:

Security review needs attention: The diff introduces recursive host workspace deletion in prune without sufficient proof that the target workspace is unused and belongs to the removed runtime.

  • [medium] Recursive deletion can target live workspace data — src/agents/sandbox/prune.ts:83
    The PR adds fs.rm(..., { recursive: true, force: true }) after best-effort runtime removal and fragile scope/path derivation, so prune can remove host data still used by another sandbox or by a runtime that failed to stop.
    Confidence: 0.87

What I checked:

Likely related people:

  • steipete: Recent commit history for prune/context/backend files shows repeated sandbox prune, backend, browser, and config refactors by this maintainer, including moving SSH sandboxing into core and later config/runtime refactors. (role: recent maintainer and sandbox backend owner; confidence: high; commits: 7f3f108521f4, b8bb8510a2a3, d8b927ee6a9f; files: src/agents/sandbox/prune.ts, src/agents/sandbox/context.ts, src/agents/sandbox/docker-backend.ts)
  • vincentkoc: Recent history shows shared seam extraction and cycle work touching sandbox backend/type boundaries that a safe prune cleanup would need to respect. (role: adjacent owner for shared seams and backend contracts; confidence: medium; commits: 81235fd92300, 350299401ff0; files: src/agents/sandbox/context.ts, src/agents/sandbox/docker-backend.ts, src/agents/sandbox/ssh-backend.ts)
  • kybrcore: Recent merged browser runtime matching work touched docker backend behavior around sandbox and browser runtime lifecycle, which overlaps the PR's browser-prune safety concerns. (role: recent browser-runtime contributor; confidence: medium; commits: 1ce410a7bebb; files: src/agents/sandbox/docker-backend.ts, src/agents/sandbox/prune.ts)

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

@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Apr 28, 2026
@clawsweeper clawsweeper Bot closed this May 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling size: XS

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Sandbox prune does not clean up workspace directory

1 participant