Skip to content

fix: keep cloud sessions stopped and surface cleanup failures - #135583

Merged
steipete merged 1 commit into
mainfrom
codex/cloud-session-lifecycle-refactor
Sep 2, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/cloud-session-lifecycle-refactor

Conversation

@steipete

@steipete steipete commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where users stopping or recovering cloud sessions could see a reclaimed session while provider deletion was still failing. A late WebSocket hello could also report a stopped, fenced, or already-closing worker as ready.

Why This Change Was Made

Keep each lifecycle decision with its authoritative owner: the connection controls admission and readiness; environment teardown owns the provider cleanup acknowledgement; the placement store resolves journal ownership. Startup and runtime recovery now share those checks, accepted workspace results retain their recovery fence until cleanup succeeds, and the UI uses one canonical reclaim request instead of issuing a second abort.

The refactor removes duplicate recovery, journal-ownership, capability-fallback, and launcher checks. Production code shrinks by 160 lines; regression coverage adds 138 test/support lines, for 22 fewer lines overall. There are no configuration keys, protocol changes, database/schema migrations, dependency changes, or changelog edits.

User Impact

Stopped workers stay stopped. Failed cleanup remains visible and retryable instead of reporting success while a paid worker is still retained. Accepted workspace changes remain protected through cleanup retries and restart recovery. The cloud-session and worker docs now describe these outcomes consistently.

Evidence

  • Real TCP/WebSocket regressions reproduce late admission after stop/fence and invalid input, plus reentrant readiness observers. The final connection, endpoint, and RPC suites pass: 56 tests.
  • Startup UI coverage passes: 109 tests, including cancellation, delayed dispatch completion, disconnect/reload recovery, and incognito cleanup.
  • Both staged-result variants fail on pristine production code: Stop incorrectly resolves as reclaimed while provider deletion fails. The repaired real-state/Git probes preserve accepted workspace changes and retain the pending-result fence and lease until cleanup succeeds, then clear pending cleanup state and reclaim without losing the accepted work.
  • Clean Linux verification on 3766b9f99975188731a1c2ac7d8d6ea294a01dd5: 46 files / 723 tests passed (56 worker tests, 558 Gateway tests, 109 UI tests), with an unchanged-source check afterward. This covers dispatch/reclaim, recovery, accepted results, journal ownership, placement barriers, startup maintenance, both launcher modes, cancellation, media, computer operations, and UI recovery.
  • node scripts/check-changed.mjs and complete normal-production Node 24 builds passed, including runtime postbuild, SDK exports, UI asset/performance guards, and startup metadata. The isolated exact-head Linux Testbox build completed in 1m28s; its filtered node inventory has 9,332 files with zero missing imports. Both canonical bootstrap modes passed in about ten seconds each, including archive hash/size verification and complete owned-file cleanup. Pinned Chromium launched, verified a synthetic page, and closed.
  • Preserved infrastructure failures: an earlier private-QA build produced three imports of an excluded QA-only chunk and was rejected before provider allocation. The subsequent Mac production build/import closure passed, but its bootstrap preflight hit the unchanged ten-minute bound during slow staging cleanup; canonical close drained and removed every owned file. Linux proof used a native exact-head build with the same scripts and deadlines, not the CI merge-commit archive. No AWS worker was allocated by these failed attempts.
  • Exact-head CI passed on 3766b9f99975188731a1c2ac7d8d6ea294a01dd5.
  • Authenticated AWS/Control UI startup cancellation reached a real broker lease. The browser issued one reclaim and no extra abort or initial send. When the broker retained unresolved cleanup metadata, the UI displayed the failure and the real SQLite placement remained failed with its destroying environment and lease retained. After canonical broker recovery cleared that debt, the same Gateway state was reopened and one ordinary UI Stop retry succeeded: local placement generation 4, destroyed environment, unchanged allocation identity and workspace files. No replacement worker, model credential, model turn, or direct provider stop was used for recovery; the Gateway and all task processes closed cleanly.
  • The first runtime roundtrip attempt stopped before model execution because the test's 40 GB disk override was smaller than the selected image's 400 GB minimum. Its broker record subsequently showed released state, cleared cleanup metadata, and no remaining resource uncertainty. The corrected test uses the repository's existing 400 GB setting, with unchanged runtime, workspace, cancellation, and cleanup assertions. No product change was made for this test-setup error.
  • The real OpenClaw cloud-worker roundtrip passed: a remote Linux command wrote a nonce-bearing file that reconciled into the managed local worktree; model-key and Gateway-token presence checks were both false. A follow-up used the same environment and lease, the UI cancelled its turn after a reported tool start, and one Stop-worker reclaim returned with an immediate released/cleanup-clear broker receipt before safety cleanup. Shell-process termination and independent physical EC2 termination were not separately observed.
  • An initial Codex attempt displayed its one-shot approval correctly, but the harness incorrectly required a run ID on a valid session-bound node-launch approval whose diagnostic run metadata was null. It expired and the worker was cleaned up. The corrected Codex-only test matched the exact fresh approval and verified its real UI acknowledgement; no approval policy, timeout, or product code was changed.
  • The corrected Codex remote-exec flow passed on the same exact head/build: two distinct Allow-once approvals were durably allowed and consumed; the real remote Linux nonce file reconciled into the managed workspace and appeared in the assistant transcript; model-key/Gateway-token presence checks were false. A follow-up used the same worker, the UI acknowledged turn cancellation after a reported native bash tool start, and one Stop-worker reclaim returned with an immediate released/cleanup-clear broker receipt. Final SQLite state was reclaimed/destroyed with no turn claim or recovery error; the driver, observer, Gateway and listener all stopped.
  • All five task-owned AWS lease intents have independently read, exact-owner broker receipts with released state and cleared cleanup metadata. The cancelled-startup and rejected-volume records have no remaining provisioning-resource uncertainty. Broker acknowledgement is not an independent physical EC2 audit. One heartbeat deadline warning occurred during Codex reclaim; it did not prevent the final cleanup acknowledgement.
  • Temporary model/broker credentials were removed and the owned Testbox was stopped and verified completed. Its hosting Actions workflow is consequently cancelled; this is deliberate runner cleanup after the successful native build/live commands, not a failed PR CI gate.
  • P0-only Codex autoreview found no P0 blockers. The separate manual owner-boundary review found no accepted actionable source findings. Both runtime roundtrips, UI turn-abort acknowledgements, worker reclamation, and same-state startup cleanup retry are now observed. Native shell termination after turn abort remains explicitly outside the proof claim; see the concrete follow-up below.

Real startup cleanup failure

This is the exact PR build and a synthetic project. The recording shows Stop returning a visible cleanup-pending error instead of claiming the cloud worker is gone. It is failure/retention evidence, not a completed cleanup result.

cloud-startup-stop-pending-cleanup.mp4

Cleanup failure stays visible and the cloud session remains tracked

Same-session recovery after cleanup

After the broker confirmed no remaining provider resource, an ordinary UI Stop retry returned the original session to local without replacing its allocation identity or changing its workspace. This genuine after-capture intentionally shows no model credential: cleanup recovery did not need one.

The original session is local after the successful Stop retry

Review scope and follow-ups

The reviewed path runs from Control UI startup through sessions dispatch/reclaim, worker admission, turn claims and launcher callbacks, environment teardown, journal ownership, and accepted-result recovery. OpenClaw worker-turn and Codex remote-exec paths are both included. Codex contracts were inspected directly: environment registration/status and environment transport ownership. The inspected files match that official commit byte-for-byte, and GitHub's commit API independently resolves the revision. This change does not alter the Codex protocol.

The automated stored-data warning does not reflect a schema change: tables, columns, representations, schema versions, and migrations are unchanged. This repairs existing cleanup and pending-result ownership; both restart and retained-reference paths have regression proof. Provider-deletion failures were injected at the real state/Git owner boundary. The live pending-cleanup failure occurred naturally during cancelled broker provisioning; AWS deletion was not deliberately made to fail. The ClawSweeper rank-up requests, including its 2026-09-02 02:19 UTC request for authenticated Codex evidence, are covered by the exact-head runtime flows and real UI Stop/failure/retained-state/successful-retry evidence above. No live-proof waiver is being used.

Source provenance: the admission/readiness holes appear in #105865, premature no-result reclamation in #106332, and the staged-result exact-epoch cleanup guard in #110952. #111244 carried the guard forward and added the accepted-but-missing-reference variant. These attributions were checked against raw commit parents; historical builds, first observed incidents, and earliest stable-release exposure were not established.

A separate source-only audit of recent main changes through 00baa02687d7d4cdc707746f6dbd0979f47b0f34 found no concrete integration conflict: newer Codex native-configuration ownership explicitly supports isolated cloud-node clients and leaves placement/provider cleanup separate. Later hook-context, worker-label, sandbox, observer, client-projection, and plugin-loader changes retain their inspected owner boundaries. The latest review's unavailable-main limitation is also resolved locally: dfa8b7df9e6f58dd7baab29ee7e2e238c74580a8 is available and is an ancestor of fetched aec22ecc73019282592e503948a68716ef10da51; that commit only changes CI planning/docs/tests. The test totals and CI above remain proof of the exact PR head, not an executed combined tree.

The separate completed-result/restart finalization work in #132027 remains outside this change; it needs its own accepted persistence design. A possible model-overridden child-session routing issue still needs a concrete reproduction and is not claimed as fixed here.

Follow-up: the reclaim barrier reports “has active work” for an already-local session even when it has no active turn. This was observed on a redundant safety RPC after failed bootstrap recovery; the normal UI does not offer Stop for local sessions. The rejection is correct, but its diagnostic wording needs a separate cleanup.

Follow-up — Codex node-channel cancellation versus native background-terminal cleanup acknowledgement ordering. During the live Codex cancellation, the node channel closed and the separate background-terminal termination request exceeded its fresh five-second cleanup deadline. The runtime surfaced that failure before worker reclaim completed successfully. The cancellation owners in extensions/codex/src/app-server/attempt-client-cleanup.ts and run-attempt-active-turn.ts are not changed by this PR; the competing lifetimes also exist on its base. Node-side process-tree cleanup is attempted separately, but the shell's state between turn cancellation and worker reclaim was not observed. This is a real unresolved acknowledgement gap, not a cosmetic warning or a proven surviving process. It needs focused ownership/proof work; no timeout increase or error suppression is included here.

Keep admission and readiness closed after terminal ownership or transport closure. Preserve accepted workspace recovery fences until provider teardown succeeds, including drain epoch changes. Share recovery and journal ownership checks, simplify turn-launch validation, and let reclaim own UI cancellation.
@clawsweeper

clawsweeper Bot commented Sep 1, 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 app: web-ui App: web-ui gateway Gateway runtime size: XL maintainer Maintainer-authored PR labels Sep 1, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 1, 2026
@clawsweeper

clawsweeper Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 1, 2026, 10:19 PM ET / September 2, 2026, 02:19 UTC.

ClawSweeper review

What this changes

This PR makes cloud-worker Stop retain failed provider cleanup for retry and prevents terminal workers from becoming ready through late WebSocket traffic.

Regression provenance

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

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

Keep open for maintainer review: the introduced lifecycle changes have no concrete correctness finding, but the PR is maintainer-labeled and its stated authenticated Codex remote-exec cancellation proof remains pending.

Priority: P1
Reviewed head: 3766b9f99975188731a1c2ac7d8d6ea294a01dd5
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The owner-boundary refactor and focused regressions are strong, but the stated Codex remote-exec runtime proof has not yet been completed.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: This maintainer-authored PR is outside the external-contributor proof gate; its body reports visible Control UI recovery evidence, while separately acknowledging that authenticated Codex remote-exec cancellation proof is still pending.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored PR is outside the external-contributor proof gate; its body reports visible Control UI recovery evidence, while separately acknowledging that authenticated Codex remote-exec cancellation proof is still pending.
Evidence reviewed 5 items Cleanup owner boundary: The introduced reclaim path transitions to reclaimed only after cleanup succeeds; teardown errors instead retain a failed placement.
Regression coverage: The new recovery test injects provider deletion failure, verifies failed retained state, then verifies a later reclaim becomes local after cleanup succeeds.
Late-admission guard: Admission now rejects messages once the connection is terminal or no longer current; its real TCP/WebSocket regression test covers buffered hello and reentrant ready observers.
Findings None None.
Security None None.

How this fits together

Cloud sessions run work on remote workers while the Gateway retains the session, workspace, and placement record. Reclaim, pending-result recovery, and worker connection admission decide whether a remote worker is released or remains visibly retryable.

flowchart LR
  UI[Control UI Stop] --> Reclaim[Gateway reclaim]
  Reclaim --> Placement[Placement lifecycle]
  Placement --> Cleanup[Provider cleanup]
  Cleanup --> Confirm{Release confirmed?}
  Confirm -->|yes| Local[Local or reclaimed session]
  Confirm -->|no| Retry[Visible retryable failure]
  Worker[Worker WebSocket] --> Admission[Connection admission]
  Admission --> Placement
Loading

Decision needed

Question Recommendation
Is the supplied Control UI recovery evidence sufficient to land while authenticated Codex remote-exec roundtrip and active-turn cancellation proof remains pending? Require Codex proof: Keep the PR open until an exact-head authenticated Codex remote-exec roundtrip and active-turn cancellation demonstrate terminal recovery.

Why: The patch changes both worker-turn and remote-exec lifecycle paths; source tests are strong, but the PR expressly leaves the latter runtime proof incomplete.

Before merge

  • Resolve merge risk (P1) - The authenticated Codex remote-exec roundtrip and active-turn cancellation described as pending in the PR body remain unverified on this exact head.
  • Resolve merge risk (P1) - Current-main source at dfa8b7d was unavailable from the partial clone because the promisor remote could not resolve GitHub.
  • Complete next step (P2) - A maintainer must decide whether the documented remaining Codex runtime proof is required before merge; no mechanical repair is currently established.
Agent review details

Security

None.

PR surface

Source -160, Tests +138, Docs 0. Total -22 across 20 files.

View PR surface stats
Area Files Added Removed Net
Source 12 179 339 -160
Tests 6 422 284 +138
Docs 2 3 3 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 20 604 626 -22

Review metrics

Metric Value Why it matters
Production versus test delta production −160 (179 added, 339 removed); tests/support +138 (422 added, 284 removed); docs net 0 The lifecycle repair absorbs behavior into existing owners while adding focused regression coverage rather than expanding production surface.

Stored data model

Persistent data-model change detected: durable storage schema: src/gateway/worker-environments/placement-dispatch-failure.ts, durable storage schema: src/gateway/worker-environments/placement-dispatch-pending-results.ts, durable storage schema: src/gateway/worker-environments/placement-dispatch-recovery.ts, durable storage schema: src/gateway/worker-environments/placement-workspace-journal.ts, durable storage schema: src/gateway/worker-environments/service-contract.ts, durable storage schema: src/gateway/worker-environments/worker-turn-launcher.ts, and 7 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Add exact-head Codex evidence (recommended)
    Capture the pending authenticated Codex remote-exec roundtrip and active-turn cancellation before merging.
  2. Accept the evidence boundary
    A maintainer may deliberately accept the unproven Codex runtime path while retaining the documented source and Control UI evidence.

Technical review

Best possible solution:

Preserve the owner-level cleanup and admission refactor, then record exact-head Codex remote-exec cancellation evidence or have the responsible maintainer explicitly accept that bounded proof gap.

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

Yes, source provides focused failure-injection and real WebSocket boundary tests for the reported lifecycle conditions, though this review did not execute them and the Codex live scenario remains pending.

Is this the best way to solve the issue?

Yes, provisionally: moving cleanup confirmation, journal ownership, and readiness closure to their respective owners removes duplicate policy; the remaining question is proof coverage rather than a better code path.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: Cloud-session stop and recovery can retain a remote worker or prevent a user from returning the session to a usable state.
  • merge-risk: 🚨 session-state: The patch changes placement transitions, pending workspace-result fencing, and recovery ownership.
  • merge-risk: 🚨 availability: The patch changes worker cleanup and readiness behavior that can leave a remote session unable to proceed if wrong.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This maintainer-authored PR is outside the external-contributor proof gate; its body reports visible Control UI recovery evidence, while separately acknowledging that authenticated Codex remote-exec cancellation proof is still pending.

Evidence

What I checked:

  • Cleanup owner boundary: The introduced reclaim path transitions to reclaimed only after cleanup succeeds; teardown errors instead retain a failed placement. (src/gateway/worker-environments/placement-dispatch-failure.ts:329, 3766b9f99975)
  • Regression coverage: The new recovery test injects provider deletion failure, verifies failed retained state, then verifies a later reclaim becomes local after cleanup succeeds. (src/gateway/worker-environments/placement-dispatch-recovery.test.ts:48, 3766b9f99975)
  • Late-admission guard: Admission now rejects messages once the connection is terminal or no longer current; its real TCP/WebSocket regression test covers buffered hello and reentrant ready observers. (src/worker/worker-connection-admission.ts:90, 3766b9f99975)
  • Codex dependency boundary: Direct inspection of the available sibling Codex source shows environment registration/status handling and a shared environment manager for remote execution. The PR does not change that protocol, but its body-cited Codex revision could not be verified because the local cache lacked it and network DNS resolution failed. (codex-rs/app-server/src/request_processors/environment_processor.rs:16, 78c290807ce710180111df227df3b7a4fe845452)
  • Current-main inspection limitation: The supplied current-main SHA could not be hydrated from this partial clone because its promisor remote could not resolve github.com; this review therefore does not claim current-main equivalence.

Likely related people:

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

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Record the authenticated Codex remote-exec roundtrip and active-turn cancellation on the exact head.

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-09-01T22:15:51.206Z sha 3766b9f :: needs maintainer review before merge. :: none
  • reviewed 2026-09-02T00:33:57.052Z sha 3766b9f :: needs maintainer review before merge. :: none
  • reviewed 2026-09-02T01:58:34.895Z sha 3766b9f :: needs maintainer review before merge. :: none

@steipete steipete self-assigned this Sep 1, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Sep 2, 2026
@steipete
steipete merged commit 3a60bd3 into main Sep 2, 2026
336 checks passed
@steipete
steipete deleted the codex/cloud-session-lifecycle-refactor branch September 2, 2026 02:38
@steipete

steipete commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 2, 2026
…aw#135583)

Keep admission and readiness closed after terminal ownership or transport closure. Preserve accepted workspace recovery fences until provider teardown succeeds, including drain epoch changes. Share recovery and journal ownership checks, simplify turn-launch validation, and let reclaim own UI cancellation.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui 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: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant