Skip to content

fix: avoid duplicate cloud worker teardown during recovery - #140377

Merged
steipete merged 3 commits into
mainfrom
codex/cloud-session-lifecycle-latency
Sep 6, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/cloud-session-lifecycle-latency

Conversation

@steipete

@steipete steipete commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where Gateway shutdown waits for a second physical cloud-worker Stop after background recovery has already tried to clean up the same lease. A failed deletion can add tens of seconds to shutdown and repeats provider work without gaining new evidence.

Related: #138900 and the requested cloud-session performance follow-ups.

Why This Change Was Made

Environment reconciliation performed the first teardown attempt, then placement recovery unconditionally called destruction again. Background recovery now requests cleanup through the same environment owner, which checks the existing destroy intent under its existing lock. Already-requested, unfinished cleanup reports pending instead of invoking the provider again. Explicit Stop and Move retain their retry behavior.

Pending-result recovery receives the same background service view, so a pending deletion cannot be mistaken for successful cleanup or release an accepted checkpoint/turn fence. No schema, stored representation, public protocol, configuration option, provider deadline, or physical-operation join changes.

User Impact

Failed cleanup is attempted once per background recovery sweep. Operators can still explicitly retry Stop and receive the current provider error. The Gateway continues to wait for admitted physical cleanup; an unknown lease is not treated as proof that resources are gone.

Evidence

  • Before fix on main ff930fa95e359b59960b7c911f549c1bb79f2a6f with temporary timing instrumentation: a real periodic recovery sweep held an in-flight Crabbox Stop through SIGINT, then started a second Stop for the same historical task lease. The first took approximately 47.8s and the duplicate another 36.6s. Natural Gateway shutdown took 84.738s, with 84.209s in placement reconciliation. Every owned process was joined; no allocation or state rewrite was requested.
  • Existing real-service regression cases failed before the repair: two provider destroy calls per startup/active sweep and per subsequent failed-placement sweep, while explicit Stop retried exactly once. They now pass.
  • 148 focused and sibling tests pass, including timed-out but physically live provider work, queued stale-owner retry, dedicated-node attachment/epoch preservation, accepted checkpoint fencing, later successful cleanup, startup ownership and dispatch/recovery concurrency.
  • Changed-file typechecks and guards passed; final targeted lint passed after correcting a fixture method and removing temporary diagnostic spans. Independent P0–P2 reviews found no actionable issues.
  • Full build passed on candidate aaa7957e8d0ec48adb770525bda5b5b5fca5a930 in 3m56.7s. The matched live periodic-shutdown probe passed: 84.738s before → 46.639s after, and two physical Stops → one. The provider call remained joined; the Gateway exited naturally with code 0, all owned processes were absent, the test port was closed, and the unresolved historical lease remained recorded as destroying. Provider latency varies; the independent command count proves duplicate elimination.
  • Healthy paired-native lifecycle passed on the same candidate: creation83ms, dispatch8.057s, real write/read10.362s, accepted editor save, Stop/checkpoint readback, new-environment restore2.405s, exact restored read7.810s and finalStop. Pairing was removed, prior owners preserved, all owned processes absent, and the test port closed. Gateway shutdown exited naturally with code0 in14.864s.
  • CI exposed a late-sweep fixture that installed its spy after the recovery runtime captured service methods. The fixture now installs the same interception before construction; the original case hung and all 26 corrected provisioning-cancellation tests pass. The earlier Discord backlog failure passed its exact retry unchanged; its cause remains unproven. npm audit remains non-blocking at the maintainer's request.
  • A subsequent CI run exposed a separate provider timeout race. The guarded request aborts with TimeoutError, but shared HTTP error extraction swallowed it, and Vydra guessed timeout from wall-clock time. The shared extractor now preserves the actual timeout; Vydra labels that cause and removes the clock inference. Real loopback HTTP regressions for 200 and 500 responses fail before this fix and pass afterward, with native timers and unchanged deadlines. Another regression preserves the exact error identity. All 133 owner and media-provider sibling cases pass, including ordinary broken-body metadata and custom body-timeout labels; independent P2 review is clean.

The normal Move recovery path already rejects a destroy-requested attachment at its reclaim admission check. Paired-device abandonment replay retains its separate, explicit durable-decision contract. No background retry behavior is inferred from a missing authorization callback.

Production: +20 net lines: +17 for the cloud request-versus-retry boundary and +3 to preserve the existing transport timeout through shared error handling. Tests/support: +88 net lines. Temporary diagnostic instrumentation used to isolate the delay is excluded from the patch.

Build and live cloud proof remain attributed to aaa7957e8d0ec48adb770525bda5b5b5fca5a930. Later changes fix the captured-method fixture and the separately reproduced HTTP timeout race; earlier proof is not relabeled. Exact-head CI on 6d0ad0487fc667e662b0c189cb14ad4a2042c983 passed: 107 successful jobs, 17 skipped, including every previously failing job. Fresh ClawSweeper review on that head reports no findings or before-merge requirements.

@clawsweeper

clawsweeper Bot commented Sep 6, 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 gateway Gateway runtime size: S maintainer Maintainer-authored PR labels Sep 6, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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 6, 2026
@clawsweeper

clawsweeper Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 6, 2026, 4:08 PM ET / 20:08 UTC.

ClawSweeper review

What this changes

Prevents background cloud-worker recovery from repeating pending teardown and preserves request timeout errors while reading provider responses.

Merge readiness

✅ Ready for maintainer review

This PR remains useful: current main still contains both defects, and the related merged PRs do not replace it. No blocking correctness or security finding remains after reviewing the timeout addition and retained cleanup behavior.

Priority: P2
Reviewed head: 6d0ad0487fc667e662b0c189cb14ad4a2042c983

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused owner-level repair with strong behavior evidence, preserved proof provenance, and no actionable blocking finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied live observations exercise periodic Gateway recovery through real Crabbox teardown and show one joined Stop with pending state retained on aaa7957; those cloud production changes remain identical at HEAD. The later timeout repair has reported before/after real loopback HTTP coverage through Vydra and the shared error reader.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied live observations exercise periodic Gateway recovery through real Crabbox teardown and show one joined Stop with pending state retained on aaa7957; those cloud production changes remain identical at HEAD. The later timeout repair has reported before/after real loopback HTTP coverage through Vydra and the shared error reader.
Evidence reviewed 7 items Cleanup guard preserves the existing owner: The new retryRequested guard executes inside the existing environment lock after reading canonical state. Initial cleanup still enters finishDestroy; explicit destroy retains its retry behavior, and queued provider calls still revalidate the current owner before I/O.
Background recovery receives the non-retrying service: Both ordinary recovery failure actions and pending-result recovery receive requestDestroy through the recovery service view. Explicit reclaim and Move continue using the original environment service.
Timeout producer and consumer agree: The guarded fetch timeout producer aborts with an Error named TimeoutError. Shared error extraction now preserves that error, and Vydra translates that actual cause into its download timeout message. Existing custom body-timeout handling and ordinary broken-body metadata remain intact.
Findings None None.
Security None None.

How this fits together

The Gateway coordinates cloud-worker cleanup and session recovery, retaining unfinished workspace results until teardown succeeds. Separately, shared HTTP helpers turn provider responses into bounded results or actionable errors for plugins such as Vydra.

flowchart TD
  A[Background recovery] --> B[Environment cleanup owner]
  C[Explicit Stop or Move] --> B
  B --> D{Cleanup already requested?}
  D -->|Background request| E[Report pending and retain recovery state]
  D -->|First request or explicit retry| F[Provider teardown]
  G[Provider response body] --> H[Preserve transport timeout]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +20, Tests +88. Total +108 across 14 files.

View PR surface stats
Area Files Added Removed Net
Source 5 25 5 +20
Tests 9 116 28 +88
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 141 33 +108

Review metrics

Metric Value Why it matters
Observed cleanup work 2 physical Stops → 1; shutdown 84.738s → 46.639s The reported matched live probe demonstrates duplicate elimination independently of variable provider latency.

Technical review

Best possible solution:

Keep cleanup retries with the environment owner, preserve unfinished workspace fences, and propagate actual transport timeout causes through the existing HTTP helpers.

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

Yes: current source exposes the duplicate teardown path and swallowed request timeout, with focused regressions and reported before/after runs matching both mechanisms; this read-only review did not execute them.

Is this the best way to solve the issue?

Yes: the patch distinguishes cleanup requests from retries at the existing lifecycle owner and preserves timeout identity at the shared HTTP boundary without changing deadlines or stored formats.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 9474ff67da1f.

Labels

Label justifications:

  • P2: This repairs bounded cloud-cleanup latency and provider timeout reporting without evidence of a widespread urgent outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The supplied live observations exercise periodic Gateway recovery through real Crabbox teardown and show one joined Stop with pending state retained on aaa7957; those cloud production changes remain identical at HEAD. The later timeout repair has reported before/after real loopback HTTP coverage through Vydra and the shared error reader.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied live observations exercise periodic Gateway recovery through real Crabbox teardown and show one joined Stop with pending state retained on aaa7957; those cloud production changes remain identical at HEAD. The later timeout repair has reported before/after real loopback HTTP coverage through Vydra and the shared error reader.

Evidence

What I checked:

  • Cleanup guard preserves the existing owner: The new retryRequested guard executes inside the existing environment lock after reading canonical state. Initial cleanup still enters finishDestroy; explicit destroy retains its retry behavior, and queued provider calls still revalidate the current owner before I/O. (src/gateway/worker-environments/provider-owner-lifecycle.ts:262, 6d0ad0487fc6)
  • Background recovery receives the non-retrying service: Both ordinary recovery failure actions and pending-result recovery receive requestDestroy through the recovery service view. Explicit reclaim and Move continue using the original environment service. (src/gateway/worker-environments/placement-dispatch.ts:98, 6d0ad0487fc6)
  • Timeout producer and consumer agree: The guarded fetch timeout producer aborts with an Error named TimeoutError. Shared error extraction now preserves that error, and Vydra translates that actual cause into its download timeout message. Existing custom body-timeout handling and ordinary broken-body metadata remain intact. (src/agents/provider-http-errors.ts:278, 6d0ad0487fc6)
  • Real HTTP regression boundary: The new table-driven cases invoke downloadVydraAsset with real fetch against a dripping loopback HTTP server for status 200 and 500. Only Date is faked, keeping request timers real while deterministically exposing the clock-ordering race. The supplied body reports before-fix failure and after-fix success; these tests were inspected, not executed during this review. (extensions/vydra/shared.test.ts:117, 6d0ad0487fc6)
  • Live cleanup proof retains its original identity: The supplied PR body records a real periodic-recovery/SIGINT probe on aaa7957: physical Stops fell from two to one and natural shutdown from 84.738s to 46.639s, with unresolved cleanup retained and owned processes joined. A healthy paired-native lifecycle also completed. The inspected diff from that candidate to HEAD is empty for the three changed cloud production files; later changes do not relabel the earlier proof. (aaa7957e8d0e)
  • Still necessary on main and in the release: Inspected fetched main still wires recovery directly to the retrying environment service, swallows request TimeoutError during error-body extraction, and uses Vydra's wall-clock inference. The v2026.9.2 error extractor also lacks timeout preservation. The release's worker-dispatch path could not be inspected, so no release claim is made for that path. (src/agents/provider-http-errors.ts:273, 3928bad9badf)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Yiğit ERDOĞAN: 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-09-06T19:13:39.879Z sha aaa7957 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-06T19:23:30.388Z sha aaa7957 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-06T19:39:34.230Z sha 04b3352 :: needs maintainer review before merge. :: none

@steipete

steipete commented Sep 6, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The current head also repairs the provider timeout race exposed by CI: shared HTTP error extraction now preserves the request's TimeoutError, and Vydra classifies that cause without a wall-clock guess. Real HTTP 200/500 regressions fail before the repair and pass afterward; 133 owner/provider sibling tests, changed-file gates, and independent P2 review pass. The PR body preserves the exact earlier cloud build/live provenance.

@clawsweeper

clawsweeper Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@steipete
steipete merged commit e1c1bc3 into main Sep 6, 2026
184 of 185 checks passed
@steipete
steipete deleted the codex/cloud-session-lifecycle-latency branch September 6, 2026 20:17
@steipete

steipete commented Sep 6, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Sep 6, 2026
…rol-ui

* origin/main:
  docs: remove the empty release-sections nav group (#140427)
  fix(tooling): omit Codex machine squash credit (#140420)
  chore(ui): refresh control ui locales (#140384)
  refactor(plugin-sdk): reuse native approval input contracts (#140415)
  fix: silent model WebSocket streams hang past the idle timeout (#140335)
  perf(ai): avoid unused text extraction for image results (#140409)
  fix(ui): distinguish failed GitHub status checks from disconnected accounts (#140333)
  refactor(cron): share runtime feedback schema fields (#140408)
  fix: avoid duplicate cloud worker teardown during recovery (#140377)
  fix(cli): show executable approval scope (#138386)
  refactor(ui): reuse shared requirement records (#140407)
  test(gateway): table-drive device token lifecycle checks (#140403)
  fix(chat): fence delayed history at terminal retirement (#140379)
  test(skills): compare large upload bytes natively (#140402)
  refactor(delivery): reuse the canonical rendered batch plan type (#140386)
  docs(start): repair the first-run path from landing page to first channel (#140390)

# Conflicts:
#	docs/.i18n/glossary.zh-CN.json
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 7, 2026
…140377)

* fix: avoid duplicate cloud worker teardown during recovery

* test: install recovery interception before runtime creation

* fix: preserve request timeout causes during body reads
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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