Skip to content

fix(state): avoid false worktree lease loss after parent stalls - #168214

Merged
RomneyDa merged 1 commit into
mainfrom
fix/worktree-heartbeat-reply-deadline
Oct 10, 2026
Merged

RomneyDa merged 1 commit into
mainfrom
fix/worktree-heartbeat-reply-deadline

Conversation

@RomneyDa

@RomneyDa RomneyDa commented Oct 10, 2026 •

Copy link
Copy Markdown
Member

What Problem This Solves

Fixes: managed worktree allocation reports lease loss when the parent delivers an already-completed heartbeat reply more than one second late, even though the same owner still has a valid lease.

User Impact

Worktree allocation survives short parent-thread stalls without weakening rejection of expired leases or unresponsive workers. No configuration, schema, lease-duration, or operator-action changes.

Why This Change Was Made

Publish asynchronous request completion before notifying the parent. The existing reply handler and deadline timer can then distinguish queued delivery from an unanswered request. Completion does not grant ownership: the actual reply, running worker state, lease expiry, and fixed operation bound still apply.

Evidence

  • Four delayed verify/renew regressions fail before the repair and pass afterward, covering reply-first and timer-first ordering.
  • 50 distinct heartbeat cases pass: lifetime 27, startup 3, diagnostics 6, real-worker 14. Includes stale completion, expired/lost replies, and a completed-but-undelivered reply remaining operation-bounded.
  • Isolated production allocator withWorktreeAllocationLease proof: worker verifies within 1 ms; parent stalls 1,504 ms; original owner retains 58,474 ms; allocation completes. Healthy control completes; expired-owner and unanswered-worker controls reject. All four release their leases. No live Gateway used.
  • Independent diff-scoped review completed with no P0-P2 findings. node scripts/check-changed.mjs passed, including production/test types, formatting, lint, dead exports, import cycles, and ownership guards.
  • Cost: pnpm test src/state/openclaw-state-lease-heartbeat.lifetime.test.ts --maxWorkers=1 takes 24.63 s wall time (16.04 s compiled-worker preparation; about 0.17 s test execution). New cases use fake clocks; no added CI sleeps or process boots. Existing real-worker suite takes 45.57 s, reused as worker-contract proof. Hosted CI timing was not measured.

Also ran the native qaRuntime build and built-Gateway E2E below. The full packaging build and full test suite were not run.

Built Gateway E2E proof

Pinned reviewed head: f0d5acb3eb7748da51f49e2639cb4812652ae4cc. OPENCLAW_BUILD_PRIVATE_QA=1 pnpm build qaRuntime passes; the manual proof runner exits 0.

The maintained QA Lab lifecycle boots the actual built dist/index.js gateway run, authenticates a real WebSocket RPC client, and calls sessions.create with an initial message and worktree: true. Allocation therefore runs through the deferred admitted-first-turn path, not a direct allocator call. agent.wait, sessions.list, worktrees.list, real Git branch/base-commit checks, and checkout file contents establish the outcome.

Gateway control Public result Worktree outcome
Healthy verification agent.wait: ok Real checkout and session binding published
Completed verification, then parent-thread stall agent.wait: ok Real checkout and session binding published
Unanswered verification agent.wait: error naming the allocation lease loss No new checkout, registry record, or binding
Fresh allocation after that rejection agent.wait: ok New real checkout and session binding published

For the stalled case, the real SQLite worker completed verification inside the original one-second response budget. A proof-only preload then blocked the parent for 1,503 ms. The successful reply was delivered 1,506 ms after request publication, with 58,494 ms remaining on the verified lease grant. The preload neither fabricates replies nor changes SQLite, product completion state, ownership checks, or product deadlines. The negative control withholds one verification request and produces the exact public error:

Error: managed worktree allocation lease core:managed-worktrees:create/capacity was lost | state lease heartbeat is not responsive

One isolated Gateway serves all four cases with a loopback-only synthetic model service; no live provider or operator Gateway is used. Native cleanup deletes all four synthetic sessions, verifies zero active managed worktrees and zero capacity lease rows, and confirms the Gateway stopped. Existing removed-worktree snapshot records and template-cache retention are honored. Adding this proof does not change the reviewed code head or add production hooks or CI tests.

Sanitized receipt, reproducer and isolation details, complete artifact manifest. All seven uploaded files and the manifest were downloaded and verified; file SHA-256 values match the locally tested bundle. Download links expire on 2026-10-17 UTC; the observed result stays inline below.

Observed Gateway RPC output
Built Gateway listening; isolated authenticated RPC connected.
healthy: ok; 1 published worktrees; 14052ms
stalled: ok; 2 published worktrees; 6275ms
unanswered: error; 2 published worktrees; 1970ms
recovery: ok; 3 published worktrees; 5053ms
All four Gateway E2E controls passed; native cleanup joined; no capacity lease rows remain.

To reproduce, place the three harness files from the artifact bundle in .local/lease-gateway-e2e/ in a clean, task-owned checkout at the pinned head, with the repository-declared toolchain and dependencies:

OPENCLAW_BUILD_PRIVATE_QA=1 pnpm build qaRuntime
python3 .local/lease-gateway-e2e/run-proof.py

This is built-Gateway RPC evidence, not package-install, live-provider, cross-platform, or full-suite validation. The manual proof adds no hosted-CI seconds.

@clawsweeper

clawsweeper Bot commented Oct 10, 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.

@RomneyDa
RomneyDa marked this pull request as ready for review October 10, 2026 05:12
@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

The heartbeat worker publishes request completion so delayed parent delivery does not falsely invalidate a healthy lease.

Example: A completed verification reply arrives after 1,506 ms with 58,494 ms remaining on its lease.

  • Before: Allocation rejects the reply because the one-second response deadline elapsed.
  • After: Allocation accepts the unexpired reply and publishes the worktree and session binding.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused repair with meaningful deterministic regressions, supplied shipped-Gateway proof, successful exact-head checks, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied output for the reviewed head exercises the built Gateway through authenticated sessions.create with worktree enabled: delayed completed verification publishes a real checkout and binding, unanswered verification publishes neither, recovery succeeds, and native cleanup removes capacity lease rows.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Managed worktree allocation can report lease loss after a short parent-thread stall even though verification completed and the original lease remains valid.
Reason: This maintainer-authored repair restores the existing allocation contract through the shared heartbeat owner without adding settings or changing lease duration.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR fixes a current asynchronous heartbeat race, and no actionable defects were found.

Priority: P2
Reviewed head: f0d5acb3eb7748da51f49e2639cb4812652ae4cc

Before merge

None.

Findings

None.

Agent review details

How this fits together

Managed worktree allocation uses shared-state leases whose worker verifies SQLite ownership; the parent consumes replies and shared observations before continuing guarded allocation.

flowchart TD
  A[Gateway session creation] --> B[Worktree allocation]
  B --> C[State lease owner]
  C --> D[Heartbeat worker]
  D --> E[SQLite lease row]
  D --> F[Completion observation and reply]
  F --> C
  C --> G[Guarded worktree publication]
Loading

Technical review

Best possible solution:

Land the shared heartbeat completion repair while preserving durable-owner checks and existing expiry bounds.

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

Current-main source rejects completed asynchronous replies after the response deadline despite remaining lease validity; the PR supplies base-failing regressions and a matching Gateway scenario, which were not rerun during this read-only review.

Is this the best way to solve the issue?

Publishing completion in the existing worker fixes the completion-versus-delivery race at its shared owner without extending lease duration or treating completion as authorization.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Asynchronous heartbeat response budgeting changes intended behavior with a stated reason (09e30a1: Permit slow native renewal while bounding unanswered requests and requiring fresh replies and valid ownership.)
  • Delayed synchronous acknowledgment handling keeps the original intent (4720657: Accept an already-completed current acknowledgment after delayed parent wake while rejecting expired grants; this PR preserves that path.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Pinned introduction: The introduced diff publishes completion before worker reply delivery and consumes it only when budgeting asynchronous requests. (src/state/openclaw-state-lease-heartbeat.worker.ts:288, f0d5acb3eb77)
  • Current main remains affected: Fetched main retains the original asynchronous response deadline without the completion observation; its heartbeat production files differ from the reviewed head by this repair. (src/state/openclaw-state-lease-heartbeat.ts:214, bb7d32e55d48)
  • Completion does not grant ownership: Completion bypasses only the unanswered-response deadline; lease expiry, the fixed operation bound, the actual reply, reply expiry, and running-worker checks remain mandatory. (src/state/openclaw-state-lease-heartbeat.ts:229, f0d5acb3eb77)
  • Durable authority remains with existing owners: Worker transaction admission reads the exact owned, unexpired lease and rechecks it after host admission; the patch changes neither those checks nor their final transaction boundary. (src/state/openclaw-state-lease-worker.ts:140, f0d5acb3eb77)
  • Focused regression coverage: The added fake-clock cases cover verify and renew under both delivery orderings, expired and lost replies, stale completion, and a completed request whose reply never arrives. (src/state/openclaw-state-lease-heartbeat.lifetime.test.ts:399, f0d5acb3eb77)
  • Shipped Gateway behavior supplied: The full PR body supplies exact-head built-Gateway RPC output for sessions.create with worktree enabled: healthy and delayed-delivery allocation succeed, an unanswered verification publishes no worktree, subsequent allocation succeeds, and cleanup leaves no capacity lease rows. (f0d5acb3eb77)

Likely related people:

  • Peter Steinberger: Raw commit dfd2e74 adds src/state/openclaw-state-lease-heartbeat.worker.ts:57 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: dfd2e744caa3; files: src/state/openclaw-state-lease-heartbeat.worker.ts)
  • Jason (Json): Raw commit 09e30a1 adds src/state/openclaw-state-lease-heartbeat.ts:225 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 09e30a19aa20; files: src/state/openclaw-state-lease-heartbeat.ts)
  • Dallin Romney: Raw commit 3328283 adds src/state/openclaw-state-lease-heartbeat.worker.ts:164 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 332828375cd7; files: src/state/openclaw-state-lease-heartbeat.worker.ts)

PR surface

Source +11, Tests +122. Total +133 across 5 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 16 5 +11
Tests 2 125 3 +122
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 141 8 +133

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P2: False lease loss interrupts managed worktree allocation after parent-thread stalls, with a focused repair and limited blast radius.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-10T05:11:57.434Z sha f0d5acb :: needs changes before merge. :: none
  • reviewed 2026-10-10T05:18:20.235Z sha f0d5acb :: needs maintainer review before merge. :: none

Reviewed October 10, 2026, 2:19 AM ET / 06:19 UTC (Revision 3).

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 10, 2026
@RomneyDa
RomneyDa merged commit 6d3f75a into main Oct 10, 2026
207 checks passed
@RomneyDa
RomneyDa deleted the fix/worktree-heartbeat-reply-deadline branch October 10, 2026 06:23
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor 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