Skip to content

fix(code-mode): canceled timers stall automation and closed cells exhaust slots - #131186

Merged
steipete merged 1 commit into
mainfrom
steipete/code-mode-cancellation-443e40
Aug 27, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/code-mode-cancellation-443e40

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Closes #131112
Closes #131124

AI-assisted implementation and validation. Maintainers can edit this same-repository branch.

What Problem This Solves

Fixes an issue where users running Code Mode automation scripts would hit their deadline after canceling a timer across awaits, even though the guest program had completed. Also fixes canceled agent runs retaining parked Code Mode cells until expiry: after enough abandoned cells, unrelated runs could fail with too many suspended code mode runs.

The second failure depends on order: exec returns waiting, the owning chat is aborted, and no wait is called. Canceling host work alone did not release the parked execution slot.

Why This Change Was Made

Headless execution now consumes the worker's canceled request IDs using the same reconciliation helper as interactive execution. Parked VM snapshots now belong to their exact context/tool/catalog owner, with subscriptions released on transfer and disposal. Catalog description-observer replacement is separated from real catalog teardown, so refresh and client-tool append do not kill valid cells.

This repairs ownership at snapshot publication rather than increasing capacity, shortening TTL, retrying, or compensating in a downstream consumer. A stale snapshot callback cannot delete a replacement with the same cell ID. Parked waits observe owner closure at their deadline, while worker execution retains the existing initiating sessions_yield handoff semantics. Existing reservation accounting, unrelated owners, metadata-only recovery/mutation controls, and destroyed-catalog exception presentation remain intact.

Production LOC: +86/-22 (net +64). Tests/support: +371/-103 (net +268, including moved existing tests and a shared fixture). Docs: +6. Growth supplies the missing transferable snapshot-owner binding and distinguishes actual catalog close from description refresh; existing cancellation, expiry, reservation and disposal primitives are reused, and duplicate aborted-result construction is removed. No configuration, schema, protocol, dependency, timeout, or capacity change.

User Impact

Canceled guest timers no longer keep headless automation draining stale work. Aborted or normally closed owners release their parked cells promptly, allowing subsequent runs to allocate and resume without waiting for the default 900-second TTL. Valid refreshes and repeated resumes remain usable.

This concerns OpenClaw's QuickJS-WASI Code Mode, not native Codex's separate V8 runtime. Stable-release reachability has not been established; this PR does not claim a particular stable release is affected. Release-note context is contained here; no changelog edit is included.

Evidence

Failing before, passing after

On unchanged pre-fix production, the saved real-QuickJS timer regression failed at the original five-second limit with zero tool calls, and both no-wait context/tool-abort regressions retained the canceled owner's snapshot. Additional catalog-close and publication/deadline cases also failed before the repair. The same cases now pass, including unrelated-owner preservation, two resumes, stale callback rejection, subscription cleanup, normal catalog teardown, and initiating sessions_yield completion.

370 tests in 15 files passed through normal routing: 15 tests/two files in unit-fast-isolated, 350/11 in agents-core, and 5/two in embedded-agent-run; 136.83 seconds. The new cancellation file was included, not an empty shard. The complete changed-file gate and frozen build passed. Independent structured P0/P1 autoreview reported no accepted/actionable findings; the reviewer did not run tests and reviewed the supplied bundle, so runtime proof comes from the separate runs below. All 13 source hashes stayed unchanged across review, tests, build and real-flow proof.

An initial validation attempt lacked the already-declared jsdom types. Restoring the frozen-lockfile dependencies and forcing the unchanged UI typecheck cleared stale incremental results; the complete changed gate then passed without UI, manifest, or lockfile edits. The installer printed Done but remained alive after other-platform fetch warnings and was stopped after the restored tree was verified; a clean installer exit is not claimed.

Exact local test/check/build commands:

OPENCLAW_VITEST_MAX_WORKERS=1 node scripts/run-vitest.mjs \
  src/agents/code-mode-headless.test.ts \
  src/agents/code-mode-headless.cancellation.test.ts \
  src/agents/code-mode-headless.validation.test.ts \
  src/agents/code-mode.bridge.test.ts \
  src/agents/code-mode.bridge.lifecycle.test.ts \
  src/agents/code-mode-worker-lifecycle.test.ts \
  src/agents/code-mode.wait.test.ts \
  src/agents/code-mode.limits.test.ts \
  src/agents/code-mode.agent-loop.test.ts \
  src/agents/code-mode-swarm.test.ts \
  src/agents/agent-tools.runtime.test.ts \
  src/agents/embedded-agent-runner/run/attempt-client-tools.test.ts \
  src/agents/embedded-agent-runner/run/attempt-session-settle.test.ts \
  src/agents/embedded-agent-runner/run/attempt.tool-search-catalog-abort.test.ts \
  src/agents/tool-search.test.ts \
  --maxWorkers=1 --no-file-parallelism

node scripts/check-changed.mjs -- \
  docs/tools/code-mode.md \
  src/agents/code-mode-execution.ts \
  src/agents/code-mode-headless.cancellation.test.ts \
  src/agents/code-mode-headless.test.ts \
  src/agents/code-mode-headless.ts \
  src/agents/code-mode-state.ts \
  src/agents/code-mode-swarm.test.ts \
  src/agents/code-mode.bridge.lifecycle.test.ts \
  src/agents/code-mode.test-support.ts \
  src/agents/code-mode.ts \
  src/agents/code-mode.wait.test.ts \
  src/agents/tool-search-catalog.ts \
  src/agents/tool-search-types.ts

OPENCLAW_BUILD_PRIVATE_QA=1 pnpm build

Real Gateway capacity proof

The same isolated scenario ran on Node 26.7.0 through a real Gateway/OpenClaw/QuickJS runtime with AIMock at the model protocol boundary. This is neither a live-model test nor a mocked Control UI/Gateway test. For each of 64 chats: send a yielding exec, observe its actual waiting result, abort that exact chat run, verify its exact abort acknowledgment and terminal settlement, and independently inspect history for one exec/one parked result/zero waits. Only then admit chat 65, execute another yielding cell, and resume it through one actual wait.

Before: the 65th actual exec failed with too many suspended runs, 13,514ms after the first parked result. After: the 65th actual exec returned waiting, then one actual wait completed with RESUMED_OK, within a 16,671ms window. All 64 abort acknowledgments and terminal settlements were verified; 131 mock protocol requests. No cap/TTL override or Gateway restart; default snapshot TTL remained 900 seconds. Source, scenario, and dist hashes stayed unchanged. All owned helpers/services/temporary roots were cleaned up.

{"runtime":"real Gateway/OpenClaw/QuickJS","provider":"AIMock","abandonedAdmissions":64,"exactAbortAcknowledgments":64,"terminalSettlements":64,"abandonedWaitCalls":0,"admission65":{"exec":"waiting","waitCalls":1,"result":"completed","value":"RESUMED_OK"},"beforeWindowMs":13514,"afterWindowMs":16671,"snapshotTtlMs":900000,"gatewayRestarts":0,"capOrTtlOverrides":false}

Before:

65th execution blocked before owner cleanup

After:

65th execution resumes successfully after 64 aborted owners

code-mode-capacity-video.mp4

The UI activity summary displays Wait ×3; authoritative history and the model sequence show one actual wait. Control UI activity-count semantics is a separate named follow-up, not execution-count evidence and not fixed here. An initial recorder attempt lacked ffmpeg in its isolated environment; owned resources were cleaned, the existing recorder cache selected, and the unchanged runtime/scenario rerun. Final captures and video frames/contact sheets were inspected; all media contains approved synthetic fixtures only.

Real scheduler timer proof, with matched setup and cold caveat

The original disabled, no-delivery scheduler job retained the exact script, toolsAllow: ["*"], tool budget 1, and timeout 5 seconds:

const timer = setTimeout(() => {}, 60000);
await new Promise((resolve) => setTimeout(resolve, 1));
clearTimeout(timer);
await new Promise((resolve) => setTimeout(resolve, 1));
return { notify: "CM-TIMER-DONE" };

Before: failed at 5167ms. Final after: succeeded at 4023ms with CM-TIMER-DONE, following the same ordinary OpenClaw agent file-read task before the automation run as the original before case. Actual agent/bridge/read effects and unchanged job payload were verified. A fully cached same-job diagnostic completed in 125ms; that is distinct from the matched-setup proof. No deadline enlargement and no delivery requested.

Cold preparation remains a separate limitation. The first uninstrumented cold after run exceeded the nondefault five-second ceiling at 8688ms. A separate fresh-process V8-coverage diagnostic timed out at 5862ms and recorded preparation, runner, and catalog registration entry, but zero headless entry calls. That failure occurs before guest execution and is not the canceled-timer defect; it is not claimed fixed. The normal script budget remains 300 seconds. Cold script preparation performance is a separate named follow-up. The successful matched and cached runs do not erase these failures.

Before:

Scheduler timer script times out before cancellation repair

Matched after:

Unchanged scheduler job completes with CM-TIMER-DONE

code-mode-timer-video.mp4

Source and contract evidence

The canonical owner is src/agents/code-mode-state.ts (publication, transfer and disposal), called from code-mode-execution.ts; headless reconciliation belongs in code-mode-headless.ts. Attempt teardown reaches clearToolSearchCatalog from embedded-agent-runner/run/attempt-session-settle.ts. Client-tool/description-replacement siblings and the existing abort-wrapper handoff were read and tested. Docs: https://docs.openclaw.ai/tools/code-mode.

Installed quickjs-wasi 3.4.0 was inspected directly: dist/index.js:310 restore copies memory into a fresh VM, :1276 promise states, :1751 snapshot copy, :1770 named callbacks/disposal; declarations at dist/index.d.ts:795 and :873. Host timer and snapshot lifetime remains OpenClaw's responsibility. Native Codex source was also inspected at 92cbfb4d2431bdc53dc03507aea2dc5b8e932e40, codex-rs/code-mode-runtime/src/v8_init.rs:42 and session_runtime/mod.rs:135-209; its separate V8 implementation is unchanged.

History: timer cancellation propagation in #124879 (6bddfed5302) covered interactive execution but omitted headless reconciliation. Snapshot module/expiry work in #113669 and #114945 did not bind parked state to owner closure. Larger limits, shorter TTL, a wait-only guard, or disposal on every description refresh would leave the invariant broken or kill valid cells; none is used.

Remaining scope limits: no full heap/GC proof, no claim of stable-release impact, no change to destroyed-catalog exception presentation, and no change to the separately deferred read-only failed-wait recovery policy. Exact-head CI and native landing evidence will be recorded before merge.

@clawsweeper

clawsweeper Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: L maintainer Maintainer-authored PR labels Aug 27, 2026
@steipete
steipete marked this pull request as ready for review August 27, 2026 21:14
@steipete

Copy link
Copy Markdown
Contributor Author

Land-ready proof for bf21011c840a86ad22ad10d6dae8abadf42a31aa.

Exact-head CI33117242183 passed on attempt1, including required openclaw/ci-gate. The draft-era skipped run is not the success evidence. Native review artifacts validated; OPENCLAW_TESTBOX=1 scripts/pr prepare-run 131186 passed with selection.mode=exact-head. No rebase, source change, or second push was needed. Workflow Sanity also passed: https://github.com/openclaw/openclaw/actions/runs/33117156871. Dedicated Testbox workflows were not applicable; no new Testbox lease was launched.

The owner repair,370 tests/15 files, restored complete changed gate, frozen build, fresh independent P0/P1 review, and real Gateway/scheduler before-after proof all cover the same13 source hashes. Production+86/-22(net+64) supplies missing exact parked-owner lifetime; tests/support+371/-103 includes moved tests, docs+6. Existing cancellation/expiry/reservation/disposal are reused; overloaded description disposal and duplicate aborted construction are removed.

Latest ClawSweeper state is still the review-started placeholder, not a published verdict. No Rank-up moves have been published to apply or skip, and no bot approval is claimed. No submitted reviews or enforced approval rule are present; required CI is satisfied without bypass.

Real after proof:64 parked execs were aborted with64 exact acknowledgments/terminal settlements and zero abandoned waits; admission65 then completed through one actual wait with RESUMED_OK, without cap/TTL changes or restart. This uses a real Gateway/QuickJS and AIMock, not a live-model claim. The unchanged scheduler job succeeded4023ms under matched original setup, after5167ms failure before. Cold preparation still exceeded the nondefault5s ceiling before guest entry; the separate cached125ms diagnostic does not erase that failure. UI Wait-count semantics, cold preparation performance, stable-release reachability, fullheap/GC proof, and unchanged catalog-destroyed exception presentation remain the documented limits/follow-ups. Inspected images/videos and exact QA action order are in the PR body.

Commands used for source verification:

OPENCLAW_VITEST_MAX_WORKERS=1 node scripts/run-vitest.mjs \
  src/agents/code-mode-headless.test.ts \
  src/agents/code-mode-headless.cancellation.test.ts \
  src/agents/code-mode-headless.validation.test.ts \
  src/agents/code-mode.bridge.test.ts \
  src/agents/code-mode.bridge.lifecycle.test.ts \
  src/agents/code-mode-worker-lifecycle.test.ts \
  src/agents/code-mode.wait.test.ts \
  src/agents/code-mode.limits.test.ts \
  src/agents/code-mode.agent-loop.test.ts \
  src/agents/code-mode-swarm.test.ts \
  src/agents/agent-tools.runtime.test.ts \
  src/agents/embedded-agent-runner/run/attempt-client-tools.test.ts \
  src/agents/embedded-agent-runner/run/attempt-session-settle.test.ts \
  src/agents/embedded-agent-runner/run/attempt.tool-search-catalog-abort.test.ts \
  src/agents/tool-search.test.ts \
  --maxWorkers=1 --no-file-parallelism

node scripts/check-changed.mjs -- \
  docs/tools/code-mode.md \
  src/agents/code-mode-execution.ts \
  src/agents/code-mode-headless.cancellation.test.ts \
  src/agents/code-mode-headless.test.ts \
  src/agents/code-mode-headless.ts \
  src/agents/code-mode-state.ts \
  src/agents/code-mode-swarm.test.ts \
  src/agents/code-mode.bridge.lifecycle.test.ts \
  src/agents/code-mode.test-support.ts \
  src/agents/code-mode.ts \
  src/agents/code-mode.wait.test.ts \
  src/agents/tool-search-catalog.ts \
  src/agents/tool-search-types.ts

OPENCLAW_BUILD_PRIVATE_QA=1 pnpm build

Native commands completed:

scripts/pr review-init 131186
scripts/pr review-checkout-main 131186
scripts/pr review-checkout-pr 131186
scripts/pr review-artifacts-init 131186
scripts/pr review-validate-artifacts 131186
node scripts/watch-pr-ci.mjs 131186 bf21011c840a86ad22ad10d6dae8abadf42a31aa --after 33117156910 --interval 120 --attach-timeout 900 --timeout 3600
OPENCLAW_TESTBOX=1 scripts/pr prepare-run 131186

Proceeding through scripts/pr merge-run 131186; no release, version, or package publication is part of this landing.

@steipete
steipete merged commit 3f4cefc into main Aug 27, 2026
300 checks passed
@steipete
steipete deleted the steipete/code-mode-cancellation-443e40 branch August 27, 2026 21:29
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

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 maintainer Maintainer-authored PR size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Aborting parked Code Mode cells exhausts shared execution slots [Bug]: Code Mode automation scripts time out after clearTimeout across awaits

1 participant