Skip to content

fix: recover sandbox file tools after stopping a run - #200669

Merged
steipete merged 3 commits into
mainfrom
codex/sandbox-file-queue-abort
Nov 17, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/sandbox-file-queue-abort

Conversation

@steipete

@steipete steipete commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Related: #200601

What Problem This Solves

After a sandbox file operation hangs, stopping the run can leave its file reservation occupied. Retrying read, edit, write, or apply_patch on the same file then waits silently until the reply watchdog stops another turn.

User Impact

Stopping a run now cancels queued file work and reaches active sandbox filesystem commands. A file operation waiting behind unfinished work reports an actionable busy-file error after three minutes, including the earlier operation's age. Other files remain usable. There is no configuration, watchdog-threshold, or container-command timeout change.

A running operation retains exclusion until its real settlement. A canceled or expired waiter never executes later, and never permits overlapping writes.

Why This Change Was Made

Root-cause chain (base a3dd700b): src/agents/sessions/tools/file-mutation-queue.ts:11 retains process-global tails; src/agents/sandbox/file-mutation-identity.ts:54 includes the sandbox root in the physical key; src/plugin-sdk/keyed-async-queue.ts:33 chains an unbounded predecessor; src/agents/agent-tools.read.ts:887–915 omits read/access/stat signals; src/agents/sandbox/fs-bridge-path-safety.ts:318 drops cancellation at the descriptor boundary. src/agents/sandbox/container-engine.ts:106 starts the helper without a deadline and can only cancel it when supplied a signal. The observer race in src/agents/embedded-agent-runner/run/attempt-tool-search-executor.ts:135 does not by itself settle the implementation holding the key.

The existing keyed queue now accepts an optional admission signal. Its returned waiter can reject immediately, but the reserved tail still joins its predecessor before skipping the canceled callback. The file-queue owner bounds waits and keeps running-age metadata on its existing tails; one warning records only a key hash, holder age, and waiter wait. No parallel registry is introduced. The sandbox adapters move into agent-tools.read.operations.ts because the existing read module’s mandatory line-cap ratchet forbids growth; this preserves one adapter owner and the existing factory path.

Execution/run signals propagate through read/edit/write operations, verification and memory-provenance readback, the mounted bridge's canonical path checks and stat commands, and the existing container-engine cancellation option. Ordinary descriptor reads use Node's signal support. openRootFile and the fs-safe bounded descriptor API lack signal support: they remain joined through real settlement, with abort checked afterward. Mutation checkpoints also retain their existing settlement contract.

#200601 preserves pending-tool attribution when the watchdog stops a reply; this change repairs file-operation cancellation and contention beneath that diagnostic. The separate codex/codemode-abandoned-call-cancel lane landed in #200647 and cancels abandoned worker-to-Gateway tool calls. This branch is rebased onto that change, with patch-identical commits. No Code Mode bridge or execution files are changed here.

Evidence

OPENCLAW_NODE_TEST_PLAN_CONTINUE_ON_FAILURE=1 pnpm test src/agents/agent-tools.read.sandbox-queue-abort.test.ts src/agents/sessions/tools/file-mutation-queue.test.ts --maxWorkers=1

On base a3dd700bb8677db62fe481cf692a2c9afe570c60, the production file-tool/real-bridge regression fails for sandbox access, read, and write-precheck stat: the held container command receives no abort while the same-file retry is queued. The queue-owner regression also fails: cancellation and expiry do not reject, and both callbacks execute after the holder is released. An unrelated file remains usable in each scenario.

The fixed tests use a synthetic container engine and fake timers. They verify same-file recovery after abort, queued callback suppression, the three-minute actionable error, unrelated-file progress, and exclusion through real settlement of a canceled active writer. This is production-owner boundary proof, not a live rootless Podman incident reproduction.

Checks passed: 247 tests across 15 affected files (one existing skip), production core typecheck, targeted test typecheck, touched-file lint/format, git diff --check, and pnpm build (3m42.6s). After the review-requested exclusion assertion, the two regression files passed again (5 tests). The adapter extraction also passed 27 tests across its sandbox/host consumers (five Windows-only skips on macOS), the line-cap ratchet, core typecheck, and lint; pnpm build passed after extraction in 2m54.5s and again on the final rebased head in 2m5.1s. The final rebased core typecheck and all five queue/bridge regressions also passed. Independent Codex autoreview through P2 finished scoped-clean after addressing that proof gap; a further clean review covers the fixture repair. Initial CI test-type failures were caused by five existing fixtures passing Node fs functions directly into the newly signal-aware contracts. Those fixtures now translate signals to Node options; both failed type graphs and all 61 runtime cases pass locally. The subsequent safety ratchet caught an assertion moved into the extracted adapter; it now uses a typed error declaration and shrinks the original file’s allowance. The assertion ratchet, core typecheck, lint/format, and independent Codex review pass for that repair. Run 44119346624 also exposed an unrelated lint failure: src/agents/subagents/registry/subagent-result-owed.expiry-discard.test.ts:53 declares _warning, rejected by eslint(no-underscore-dangle). That source is byte-identical in baseline 05243ef8, PR head, and the CI merge; lint configuration is unchanged, and focused local lint reproduces the same error. This inherited failure is retained as failed evidence rather than rerun. The assertion failure is repaired before landing. Final run 44123017046 passes build, security, all typechecks and baseline ratchets, but retains two inherited roots: that same lint error, and server.config-patch.test.ts > uses fresh revisions after agent create, update, and delete before reload applies timing out its agents.delete request at the existing 10,000ms client limit. The test, fixture, RPC client, and deletion handler/drain are identical in CI baseline 9122a49b and actual tested merge fe52c306; this flow issues config/skills RPCs and never invokes the changed file tools or queue. Its precise CI latency trigger remains unknown. The native exception evidence retains both failed jobs and the downstream gate, with source equality and causal attribution; it does not label CI green. A local replay in original file order passed all 67 cases (333.37s wrapper, 162.93s Vitest), including the timed-out case in 12.08s; that is reproduction evidence, not a claimed repair.

Test cost: 198 net test lines: two new test definitions (one parameterized over access/read/stat) plus signal adapters in five existing fixtures, below the 400-line budget. Local single-file wall time: sandbox adapter/bridge 62.04s (54.84s Vitest duration, dominated by a cold compiler generation); queue owner 15.71s. Fixture single-file wall times: bootstrap memory 18.44s; memory provenance 10.05s; channel recovery 18.69s; operator recovery 59.44s; sharing publication 23.34s. The existing operator suite already exercises full authority/worker flows; only its read adapter changes here. Exact-head CI run 44123017046 completed: 18 passing selected Node test jobs totaled 5,700 job-seconds, the config-RPC job with the unrelated timeout took 659 job-seconds, and build-artifacts passed in 801 seconds. These are whole-job costs including setup and selected consumers, not incremental per-file times; the run does not publish per-file observation artifacts. Added test bodies are under 0.1s per file; compilation dominates the real adapter/bridge graph. Fake timers cover the full three-minute wait without sleeping. Production growth is 231 net lines, plus eight documentation lines and a one-entry assertion-baseline reduction: optional signal propagation, admission cancellation in the existing queue, and age metadata on its existing tails replace the unbounded silent wait; there is no second queue owner or registry.

Trigger investigation (incident/base trace; #200643 subsequently adds FIFO workspace admission and a 60s acquisition bound): the helper path has no OpenClaw per-container exec queue (src/agents/sandbox/docker-backend.ts:132). The engine also awaits a state-path preflight without a signal (container-engine.ts:103 → state-owner.ts:41 → state-owner-path.ts:40 → host realpath); a blocked host filesystem can stall before Podman starts. Rootless native Podman may enter a systemd user scope (src/agents/sandbox/container-engine.ts:73) before exec; Podman startup/lock/attach or a filesystem stall can therefore wait without a workspace cwd. Workspace serialization is the reconciliation lease (src/gateway/worker-environments/local-workspace-store.ts:221; the incident base used ten-minute acquisition, and #200643 now owns FIFO/60s acquisition), held through helper execution (src/agents/sandbox/local-workspace.ts:293). Normal checkpoint pause and helper exec are ordered by that lease; pause/unpause commands themselves have 30s control deadlines (src/agents/sandbox/local-workspace-quiescence.ts:354,395). Current upstream Podman source rejects already-paused containers after acquiring its lock, while its attach wait has no explicit timeout; the deployed Podman version has not been reproduced here. A freeze after exec starts remains possible outside normal custody. No source evidence singles out pasta networking.

The checkpoint final host-work join (src/infra/git-worker.ts:578) and mutation checkpoint (src/agents/sandbox/local-workspace.ts:366) intentionally await actual host work. They can retain a queue slot if that work never settles. A normal live operation renews its lease, but cancellation/loss can stop renewal (src/state/openclaw-state-lease.ts:190–196) while an uncooperative callback remains pending; absence of a live lease does not identify the blocked await. Checkpoint/preparation sharing (src/gateway/worker-environments/local-workspace-projection.ts:100–143) is another workspace wait, separate from the per-file queue; its checkpoint API has no caller signal. No speculative checkpoint or pause fix is included. Remaining uncancellable boundaries are engine host preflight (container-engine.ts:103), fs-safe open (fs-bridge-path-safety.ts:324) and bounded descriptor read (fs-bridge.ts:391); caller cancellation is checked around the latter two without releasing write exclusion early. The existing 30s convention is for control commands, not filesystem helpers, so this adds no filesystem command deadline.

Release-note context: recover same-file sandbox operations after stopping a run; report bounded file contention without weakening write exclusion.

@clawsweeper

clawsweeper Bot commented Nov 17, 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 gateway Gateway runtime docker Docker and sandbox tooling agents Agent runtime and tooling size: XL labels Nov 17, 2026
@steipete
steipete marked this pull request as ready for review November 17, 2026 15:34
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 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-17T15:55:45.386904Z 7c46ddc 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.

@github-actions

github-actions Bot commented Nov 17, 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: fa47a173b078b58fc4cd9aed6af0729d63613d01
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/sandbox/fs-bridge-path-safety.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/agents/sandbox/fs-bridge.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. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 17, 2026
@steipete
steipete force-pushed the codex/sandbox-file-queue-abort branch from bf65112 to 7c46ddc Compare November 17, 2026 15:52
@steipete
steipete enabled auto-merge (squash) November 17, 2026 16:01
@steipete
steipete disabled auto-merge November 17, 2026 16:06
@clawsweeper

clawsweeper Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Propagates cancellation through sandbox file operations and bounds same-file queue waits while preserving write exclusion.

Example: Stop a sandbox read of /workspace/same.txt, then retry that file.

  • Before: The first command can retain its reservation and leave the retry waiting silently.
  • After: Cancellation reaches cooperative filesystem commands; unresolved contention produces a busy-file error after 180 seconds without admitting overlapping writes.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The implementation is coherent and has focused regression support, but required real-runtime proof is absent and failing CI remains incompletely attributed.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: After stopping a stuck sandbox file operation, retries on the same file can silently stall again.
Reason: Maintainer direction is established, and recovering cooperative filesystem operations while preserving write exclusion has clear user value.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR addresses a current cancellation defect that main still contains; no definite introduced correctness or security defect was found.

Priority: P1
Reviewed head: fa47a173b078b58fc4cd9aed6af0729d63613d01

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Provide redacted Gateway or CLI logs showing a real sandbox command canceled by Stop and a successful same-file retry, with unrelated-file progress and no overlapping writer.
Agent review details

How this fits together

Agent read, edit, write, and apply_patch calls reserve physical file identities through a shared queue before accessing the sandbox filesystem bridge and container backend.

flowchart TD
  A[Agent file tool call] --> B[Physical file identity]
  B --> C[Shared file queue]
  C --> D[Sandbox filesystem bridge]
  D --> E[Container backend]
  F[Run cancellation] --> C
  F --> D
  E --> G[Settlement and reservation release]
Loading

Technical review

Best possible solution:

Keep cancellation and bounded admission in the existing queue and bridge owners, retaining reservations until actual operation settlement.

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

Current-main source shows unbounded queue waits and omitted sandbox operation signals, supported by the supplied base-failing regressions; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The patch repairs cancellation at existing owners, preserves FIFO and settlement, and documents uncancellable boundaries without adding speculative recovery machinery.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Physical-file queue ordering keeps the original intent (b87f6d3: Serialize same-file reads and mutations in source-call order while keeping independent files usable.)
  • Shared keyed queue admission changes intended behavior with a stated reason (d503884: Consolidate FIFO reservation and predecessor settlement without adding cancellation guarantees; this PR explicitly adds admission cancellation while preserving settlement.)
  • Canonical sandbox mutation targets keeps the original intent (628a549: Authorize canonical destinations and pin mutations so symlink changes cannot redirect approved writes.)
  • Sandbox adapter extraction keeps the original intent (b87f6d3: Bridge-owned physical identity coordinates sandbox file tools; extraction retains that implementation and factory path to satisfy the existing module line cap.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit d503884 adds src/plugin-sdk/keyed-async-queue.ts:29 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: d5038842a0df; files: src/plugin-sdk/keyed-async-queue.ts)
  • Mohit Malik: Raw commit b87f6d3 adds src/agents/sessions/tools/file-mutation-queue.ts:35 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b87f6d374c56; files: src/agents/sessions/tools/file-mutation-queue.ts)

PR surface

Source +231, Tests +198, Docs +8, Other 0. Total +437 across 21 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 12 530 299 +231
Tests 7 204 6 +198
Docs 1 8 0 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 21 743 306 +437

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 growth Production +231 net lines; tests +198 net lines Growth threads cancellation through existing owners and adds distinct queue-settlement and bridge-propagation regressions; the adapter extraction replaces the previous implementation.

Labels

Label changes:

  • add P1: Stopping a sandbox operation can leave subsequent same-file agent work repeatedly stalled.
  • add merge-risk: 🚨 compatibility: The public keyed-queue helper gains an optional cancellation contract; maintainer direction accepts this additive extension and existing callers retain their previous behavior.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P1: Stopping a sandbox operation can leave subsequent same-file agent work repeatedly stalled.
  • merge-risk: 🚨 compatibility: The public keyed-queue helper gains an optional cancellation contract; maintainer direction accepts this additive extension and existing callers retain their previous behavior.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.
  • 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.

Reviewed November 17, 2026, 11:30 AM ET / 16:30 UTC.

@steipete
steipete merged commit 88e9e3b into main Nov 17, 2026
146 of 153 checks passed
@steipete
steipete deleted the codex/sandbox-file-queue-abort branch November 17, 2026 16:36
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
* fix: recover sandbox file tools after stopping a run

* test: adapt file fixtures to cancellation signals

* fix: use a typed sandbox filesystem error
RomneyDa added a commit that referenced this pull request Nov 19, 2026
* fix: recover sandbox file tools after stopping a run

* test: adapt file fixtures to cancellation signals

* fix: use a typed sandbox filesystem error

(cherry picked from commit 88e9e3b)

Co-authored-by: RomneyDa <[email protected]>
github-actions Bot pushed a commit to clawhaven/openclaw that referenced this pull request Nov 23, 2026
* fix: recover sandbox file tools after stopping a run

* test: adapt file fixtures to cancellation signals

* fix: use a typed sandbox filesystem error

Release adaptation: Reviewed sandbox cancellation and source-preserved caller adapters.

(cherry picked from commit 88e9e3b)

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot added a commit that referenced this pull request Nov 24, 2026
Baseline adaptation: Make ordered physical-file reservation abortable before execution with the existing FIFO lease registry while preserving executing writer custody.

(cherry picked from commit 88e9e3b)

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 452f36f142d60413e920863e792d3e7601c582cf)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. docker Docker and sandbox tooling docs Improvements or additions to documentation gateway Gateway runtime security-sensitive-changed size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant