Repository navigation
fix(sandbox): cleanup workspace directories during prune - #43835
archerthegoat wants to merge 3 commits into
Conversation
Greptile SummaryThis 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 Key issues found:
Confidence Score: 2/5
Prompt To Fix All With AIThis 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 |
| // 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 | ||
| } | ||
| } |
There was a problem hiding this 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:
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.| @@ -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") { | |||
There was a problem hiding this 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.
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.There was a problem hiding this comment.
💡 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); |
There was a problem hiding this comment.
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 👍 / 👎.
| // Clean up workspace directory (only for non-shared scopes) | ||
| if (params.cfg.scope !== "shared") { |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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 }); |
There was a problem hiding this comment.
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") { |
There was a problem hiding this comment.
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 👍 / 👎.
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
ad23a9f to
45cdcde
Compare
There was a problem hiding this comment.
💡 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); |
There was a problem hiding this comment.
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]>
45cdcde to
c99a72a
Compare
|
This pull request has been automatically marked as stale due to inactivity. |
|
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 detailsBest 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.
What I checked:
Likely related people:
Codex review notes: model gpt-5.5, reasoning high; reviewed against a90be474f441. |
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
resolveSandboxScopeKeyandresolveSandboxWorkspaceDirhelperssharedscope to avoid affecting other sessionsTest Plan