Skip to content

fix: stop cloud work before unrelated provider inspection finishes - #133476

Merged
steipete merged 3 commits into
mainfrom
codex/cloud-reclaim-cancellation
Aug 30, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/cloud-reclaim-cancellation

Conversation

@steipete

@steipete steipete commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Related: #133241

What Problem This Solves

Fixes an issue where stopping an active cloud session through sessions.reclaim lets its agent keep working while an unrelated worker's provider inspection is slow. The request previously waited for the global placement queue before it could cancel the session. A second overlapping Stop of an already failed worker could also report an error after the first successfully returned it to local execution.

Why This Change Was Made

The Gateway now closes session ingress and drains canonical cancellation before reserving serialized teardown. A lifecycle-owned admission closure keeps queued messages from reviving the worker without holding the mutexes that cancellation recovery needs. The coordinator retains every in-flight Stop for that session; later dispatches and moves wait outside the global fence, while recovery can finish the cancelled run. Workspace reconciliation, provider destruction, terminal persistence and move/recovery barriers retain their existing owners.

Caller authorization, session identity and lifecycle revision are checked across waits, with the exact worker owner rechecked immediately before cancellation. Failed-to-local completion uses the initial generation only to recognize that exact successful cleanup, never as authority to tear down replacement work. No configuration, protocol, schema, dependency or public tool surface is added. The cloud-worker documentation explains cancellation versus resource-release timing.

User Impact

An active cloud agent stops without waiting for unrelated provider inspection. Cleanup can still take time, but new work cannot overtake Stop or silently restart the worker. Concurrent Stops recognize an exact completed failed-worker cleanup. The existing two-step Control UI flow (stop the turn, then stop the idle worker) is unchanged.

Evidence

Exact candidate 0e8b476fc34892a1c7e0a8e196f3dbf2ca8a790f passed hosted CI 33332652305 and the changed cancellation behavior through real cloud sessions created in the Control UI. The canonical package build and remote bootstrap identities matched this head; the native runtime was Codex 0.151.0.

Three real native CUA click runs, fresh subsequent screenshots, and GUI turn Stop passed. The model screenshots, independent RFB images, and actual Chrome WebVNC all showed the same desktop counter advancing from 0 to 3. In the latest ordinary API Stop run, the exact active native turn emitted TurnAborted/interrupted 33 ms after the request and acknowledged execution close after 247 ms. Canonical history recorded that run as killed.

Resource-release proof is separately failed, not converted to success: that same RPC later timed out in provider Stop, and the observer WebSocket closed much later. An unrelated allocation was still pending; stopping its task-owned warmup process was a separately recorded manual cleanup intervention. An earlier synthetic held-inspection attempt missed its strict coordination criterion and also failed provider cleanup. Those failed attempts are retained. They do not invalidate the independently observed prompt cancellation, but this PR does not claim that the complete cloud teardown flow is repaired. Broker ingress serialization is tracked in crabbox#1679 and crabbox#1680; the discovered producer-side provisioning cancellation gap is being repaired separately. The existing blocked-inspection RED/GREEN regression proves the precise queue-order invariant.

  • Before repair, the real Gateway cancellation/placement fixture reproduces continued execution during blocked provider inspection. The repaired test observes cancellation before inspection is released and no early provider destruction.
  • The expanded regression set passes 126 tests across six files. It covers cancellation that itself needs coordinated recovery, actual pending dispatch, overlapping Stops, later move/dispatch ordering, revoked authorization, same-session-ID reset, worker replacement, pending-ingress fencing and idle suspension.
  • Another 233 tests across 18 sibling files pass: move and failure recovery, staged workspace results, terminal persistence failures, startup/shutdown, provisioning replay, device placement and session admission.
  • Separate red/green proof covers the failed-to-local overlap. The caller-order tests failed before adding per-session Stop custody, then passed; one failed Stop cannot release another Stop's custody.
  • Codex autoreview: scoped clean at P0-only. Independent all-severity source review found no remaining concrete issue; the native proof above independently covers the changed behavior.

Production delta is +235/-56 (net +179); test/test-support delta is +450/-39 (net +411), with two documentation lines added. The growth establishes two necessary ownership boundaries: admission closure without a held lifecycle mutex, and same-session Stop ordering without a held global placement fence. Removing either reproduces a race or deadlock. Existing cancellation and teardown remain canonical; the old mutation-only admission-closure path is replaced by the shared closure owner. The type-only contract extraction is included in this raw count; moves do not add runtime behavior.

Review dispositions

The latest ClawSweeper finding and its first two rank-up moves ask for compatibility with an older in-process lifecycle singleton. We checked the producing and loading contracts and are not adding that shim: tsdown.config.ts:776 builds core, SDK and bundled runtimes in one graph; src/plugins/sdk-alias.ts:1371 captures the host package root for the loader lifecycle; official plugin packaging leaves OpenClaw imports external (scripts/lib/plugin-npm-runtime-build.mts:101). The supported package-update flow stops the Gateway before replacement (docs/install/updating.md:207 and :377), while plugin metadata changes require restart (docs/gateway/configuration.md:587). Duplicated modules from one build share the current shape. The historical adjacent fallback was accompanied by a same-source duplicate-module test, not proof of mixed-version support. Merely initializing the new Set would also leave an older admission implementation unable to honor the new fence. No supported mixed-version producer or observed affected installation was identified.

The latest review’s two Rank-up moves concern the same old/new chunk premise; the source and history disposition above applies to both. Exact-candidate native cancellation and sibling desktop proof are recorded above; full provider cleanup remains a separately reported failure. Automated persistent-schema classification is not applicable: this change adds process-local cancellation ownership, with no schema or durable-store change. The production increase is justified above by the two separately tested ownership boundaries.

CI found and we corrected mechanical lint/style issues, then an unused type-only export. The export correction changes no runtime behavior. Final exact-head CI passed at 0e8b476 (run 33332652305), including the hosted full validation required by the native workflow. Fresh native cancellation proof is recorded above; a duplicate local full gate is not claimed.

@clawsweeper

clawsweeper Bot commented Aug 30, 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 gateway Gateway runtime size: L maintainer Maintainer-authored PR labels Aug 30, 2026
@steipete
steipete marked this pull request as ready for review August 30, 2026 19:32
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 30, 2026
@clawsweeper

clawsweeper Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed August 30, 2026, 6:13 PM ET / 22:13 UTC.

ClawSweeper review

What this changes

The PR makes cloud-session Stop cancel active work before unrelated provider inspection while preserving serialized teardown and later same-session move/dispatch ordering.

Regression provenance

Possible regression — probable (reviewed change; failure trace). No predecessor PR is attributed.

Merge readiness

⛔ Blocked by patch quality or review findings - 4 items remain

Keep this PR open: the prior P1 remains. A preexisting shared lifecycle singleton lacks the newly required closure set, so an active cloud Stop can throw before it cancels the running work.

Priority: P1
Reviewed head: 0e8b476fc34892a1c7e0a8e196f3dbf2ca8a790f

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The intended ordering repair is well-scoped, but a P1 shared-state compatibility crash prevents the patch from being merge-ready.
Proof confidence 🌊 off-meta tidepool Not applicable: This MEMBER-authored PR is exempt from the external-contributor proof gate. Its supplied native evidence is useful supporting context but was not independently inspectable here; the blocking issue is source-proven compatibility, not missing contributor proof.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This MEMBER-authored PR is exempt from the external-contributor proof gate. Its supplied native evidence is useful supporting context but was not independently inspectable here; the blocking issue is source-proven compatibility, not missing contributor proof.
Evidence reviewed 6 items Introduced singleton access can be undefined: The PR destructures the newly added admission-closure field without initializing it on an already-existing shared state object.
Global singleton preserves old object shape: The singleton helper returns an existing global value unchanged, so a state created before this field existed is not migrated.
Failure occurs before cancellation: The introduced preparation path creates the closure before entering cancellation; adding to an undefined closure set therefore aborts Stop while the cloud turn remains active.
Findings 1 actionable finding [P1] Initialize the shared closure registry for older runtime chunks
Security None None.

How this fits together

Gateway cloud-worker placement manages remote session execution and worker teardown. A reclaim request must fence new work, cancel the active turn, then serialize provider and workspace cleanup without allowing a replacement worker to overtake Stop.

flowchart LR
  A[Active cloud session] --> B[Stop request]
  B --> C[Close new session work]
  C --> D[Cancel active turn]
  D --> E[Serialize teardown]
  E --> F[Provider and workspace release]
  E --> G[Later move or dispatch]
Loading

Before merge

  • Initialize the shared closure registry for older runtime chunks (P1) - The process-global lifecycle state can already exist without admissionClosures; resolveGlobalSingleton returns it unchanged, so this destructure is undefined and closeSessionWorkAdmissions() throws at .add before this PR cancels the cloud run. Initialize it with the same ??= compatibility pattern used by activeMutationRuns, and cover the legacy state shape. This repeats the still-unfixed prior finding.
  • Resolve merge risk (P1) - An existing process-global lifecycle state created by an older runtime chunk will make Stop fail before cancellation, leaving active cloud work running.
  • Complete next step (P2) - A narrow mechanical repair and focused regression can address the remaining P1 without changing product direction.
  • Improve patch quality - Initialize admissionClosures for an existing singleton and add a regression that loads the old state shape before active reclaim.

Findings

  • [P1] Initialize the shared closure registry for older runtime chunks — src/sessions/session-lifecycle-admission.ts:88
Agent review details

Security

None.

PR surface

Source +184, Tests +406, Docs +2. Total +592 across 18 files.

View PR surface stats
Area Files Added Removed Net
Source 7 240 56 +184
Tests 10 445 39 +406
Docs 1 2 0 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 18 687 95 +592

Review metrics

Metric Value Why it matters
Production versus test delta production +235/-56 (net +179); tests/test support +449/-39 (net +410); docs +2 The added ownership boundary is substantial for a bug fix, and the remaining compatibility defect sits in that new production surface.

Stored data model

Persistent data-model change detected: durable storage schema: src/gateway/worker-environments/placement-dispatch-coordinator.ts, durable storage schema: src/gateway/worker-environments/placement-dispatch-test-harness.ts, durable storage schema: src/gateway/worker-environments/placement-dispatch.ts, durable storage schema: src/gateway/worker-environments/placement-move-service.ts, durable storage schema: src/gateway/worker-environments/placement-reclaim-contract.ts, unknown-data-model-change: src/gateway/worker-environments/placement-dispatch-coordinator.ts, and 1 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Preserve the shared-state upgrade invariant (recommended)
    Initialize the admission-closure Set when an existing lifecycle singleton is reused, then prove an active Stop reaches cancellation from that legacy state.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Initialize the shared admission-closure registry for preexisting singleton state and add a legacy-state regression.

Technical review

Best possible solution:

Initialize the new closure registry on an existing shared lifecycle state and add a regression that seeds the pre-field state before exercising active cloud Stop.

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

Yes, from source: seed the existing process-global lifecycle state without the new field, then reclaim an active cloud placement; the new closure creation reaches an undefined Set before cancellation.

Is this the best way to solve the issue?

No. The cancellation ordering is coherent, but it must preserve the module's documented cross-chunk singleton invariant or enforce a restart boundary before accessing the new field.

Full review comments:

  • [P1] Initialize the shared closure registry for older runtime chunks — src/sessions/session-lifecycle-admission.ts:88
    The process-global lifecycle state can already exist without admissionClosures; resolveGlobalSingleton returns it unchanged, so this destructure is undefined and closeSessionWorkAdmissions() throws at .add before this PR cancels the cloud run. Initialize it with the same ??= compatibility pattern used by activeMutationRuns, and cover the legacy state shape. This repeats the still-unfixed prior finding.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.99

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 214deebc6698.

Labels

Label changes:

  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🌊 off-meta tidepool and patch quality is 🦪 silver shellfish.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🦪 silver shellfish, so this older rating label is no longer current.

Label justifications:

  • P1: A failed Stop can leave an active cloud agent running instead of interrupting it.
  • merge-risk: 🚨 compatibility: The new shared-state field is incompatible with an already-created lifecycle singleton.
  • merge-risk: 🚨 availability: The incompatibility throws before the cancellation path can stop active cloud work.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🌊 off-meta tidepool and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: This MEMBER-authored PR is exempt from the external-contributor proof gate. Its supplied native evidence is useful supporting context but was not independently inspectable here; the blocking issue is source-proven compatibility, not missing contributor proof.

Evidence

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/gateway/server-worker-placement-reclaim.preparation.test.ts.
  • [P1] node scripts/run-vitest.mjs src/gateway/server-worker-placement-reclaim.test.ts.
  • [P1] git diff --check.

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-08-30T19:39:52.134Z sha 8fe9372 :: found issues before merge. :: [P1] Initialize the shared closure registry for older runtime chunks
  • reviewed 2026-08-30T19:53:51.341Z sha 7f1e073 :: found issues before merge. :: [P1] Initialize the shared closure registry for older runtime chunks
  • reviewed 2026-08-30T20:17:06.908Z sha 0e8b476 :: found issues before merge. :: [P1] Preserve the singleton's cross-chunk closure invariant

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 30, 2026
@steipete
steipete merged commit 76e96cc into main Aug 30, 2026
250 checks passed
@steipete
steipete deleted the codex/cloud-reclaim-cancellation branch August 30, 2026 22:19
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Aug 30, 2026
* origin/main: (55 commits)
  test: include v2026.8.1 release navigation (#133581)
  fix: stop cloud work before unrelated provider inspection finishes (#133476)
  fix(e2e): keep delete fixture target-compatible (#133526)
  fix(release): detect optional target E2E capability (#133525)
  fix(package): publish readable dist inventory (#133549)
  docs: add complete v2026.8.1 maintainer change index (#133585)
  fix(browser): preserve contextless worker and iframe sessions (#133571)
  fix(voice): discover configured provider candidates (#133507)
  refactor(ui): simplify chat rendering and lifecycle state (#133567)
  test: reduce maturity fixture cleanup time (#133566)
  improve: speed up legacy imports and transcript replacement (#133546)
  docs: add draft v2026.8.1 release notes (#133557)
  test: guard multi-project Vitest cache ownership (#133554)
  fix(memory): clarify default agent scope in command help (#133560)
  fix(clawdock): keep credentials out of diagnostic output (#133547)
  refactor(ui): avoid redundant presence work in avatar lists (#133548)
  fix(agents): recognize internal requester completion replies (#133543)
  fix: prevent duplicate queued user messages in chat clients (#133542)
  chore(ui): refresh control ui locales (#133544)
  fix(beam): restart delivery when the receiver changes (#133533)
  ...
vincentkoc added a commit to shojikumaru/openclaw that referenced this pull request Aug 30, 2026
…cked-delivery

* origin/main:
  test: include v2026.8.1 release navigation (openclaw#133581)
  fix: stop cloud work before unrelated provider inspection finishes (openclaw#133476)
  fix(e2e): keep delete fixture target-compatible (openclaw#133526)
  fix(release): detect optional target E2E capability (openclaw#133525)
  fix(package): publish readable dist inventory (openclaw#133549)
  docs: add complete v2026.8.1 maintainer change index (openclaw#133585)
  fix(browser): preserve contextless worker and iframe sessions (openclaw#133571)
  fix(voice): discover configured provider candidates (openclaw#133507)
  refactor(ui): simplify chat rendering and lifecycle state (openclaw#133567)
  test: reduce maturity fixture cleanup time (openclaw#133566)
  improve: speed up legacy imports and transcript replacement (openclaw#133546)
  docs: add draft v2026.8.1 release notes (openclaw#133557)
  test: guard multi-project Vitest cache ownership (openclaw#133554)
  fix(memory): clarify default agent scope in command help (openclaw#133560)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 31, 2026
…penclaw#133476)

* fix: cancel cloud work before waiting for provider inspection

* refactor: share cloud reclaim lifecycle contracts

* refactor: keep reclaim start placement type private
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant