Skip to content

fix(gateway): reclaim a dead owner lease with the same liveness evidence as the state lock - #164546

Merged
steipete merged 1 commit into
mainfrom
upd/upd-owner-lease-stale-after-crash
Oct 3, 2026
Merged

steipete merged 1 commit into
mainfrom
upd/upd-owner-lease-stale-after-crash

Conversation

@steipete

@steipete steipete commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

Closes #155644

What Problem This Solves

Fixes Gateway startup and Doctor maintenance getting stuck behind a crashed predecessor's SQLite owner lease after container recreation changes its hostname, including leases without an expiry.

User Impact

A provably dead local owner is reclaimed immediately. A replacement Gateway waits up to 95 seconds for an unverifiable predecessor's heartbeat to become older than 90 seconds; Doctor refuses fresh ownership and explains the wait. A verified live owner still blocks takeover, even after its lease deadline.

No configuration, flags, dependencies, database columns, or schema migration change. Existing lease payloads remain readable, and image updates need no manual lease deletion.

Why This Change Was Made

The lease's hostname-only liveness gate could not recognize a dead owner in a recreated container. File locks and SQLite leases now share the existing boot/PID-namespace classifier and 90-second heartbeat policy. The lease records namespace identity in its existing JSON payload and renews every 15 seconds. Physical state custody remains authoritative; acquisition rechecks the observed lease inside the write transaction. Doctor retains its existing old-schema admission path.

Predicate before: dead-owner reclamation required a matching hostname plus a dead PID or mismatched known process-start identities. Generic acquisition could also delete a non-null elapsed expiry. A foreign hostname remained unknown, and a null expiry could not clear through that path.

Predicate after: comparable platform/boot/PID-namespace identity admits PID evidence; a changed boot on the same host proves death. Foreign or unverifiable identity becomes dead only when its heartbeat is strictly older than 90 seconds. Fresh unverifiable ownership refuses regardless of expiry. Qualified live owners refuse even when expired; qualified owners whose PID identity remains unknown use the expiry fallback (expiresAt === null || expiresAt <= now). Legacy local records preserve local PID classification. Deletion is fenced to the observed owner token.

Evidence

  • All six touched suites (131 tests) passed three local runs. The Gateway lease and namespace suites also passed three earlier Linux runs on the unchanged production candidate.
  • Completed the 105-file direct/one-barrel importer selection, reusing the prior Linux results and running the remaining files locally in sequential batches of at most 15. All discovered failures were corrected and reproven.
  • node scripts/check-changed.mjs --base 3f4e6a1689c3f38fb7b238bdf46b2cf63f8907dc: passed to completion, including production types, all 27 test graphs, lint, unused exports, runtime import cycles, and repository guards.
  • Required new-export checks passed: eager-import-closure, pr-wrapper-source-closure, pr-worktree-provision, check-export-name-collisions.mts, and update-restart-swap-fixture.mjs.
  • Formatting and git diff --check: passed.

Representative one-worker measurements use node scripts/run-vitest.mjs <file> --maxWorkers=1, the repository-supported route that avoids reconciling the shared installation:

Touched suite Tests Test time Standalone wrapper wall time
gateway-owner-lease.test.ts 31 6.894 s 37.91 s
gateway-lock.namespace.test.ts 11 0.245 s 19.52 s
openclaw-state-lease-acquisition.test.ts 18 27.371 s 63.05 s
lifecycle.restart-intent.test.ts 15 2.996 s 12.69 s
doctor-maintenance.finish-revalidation.test.ts 45 98.196 s 111.66 s
doctor-maintenance.foreground-update.test.ts 11 17.714 s 31.15 s

The Doctor suites retain full storage/admission/service-restoration proof; the acquisition suite retains native SQLite contention and worker-generation settlement. The first local importer batch also prepared the E2E runtime: its compiler phase took 15m 28.3s, separate from test time. CI timing is pending when opened.

The stale-container regression originally failed with Another Gateway owner lease is still active for this state directory. Coverage includes legacy and qualified container identities, dead/recycled local PIDs, null expiry, live expired owners, renewal, the 90-second boundary, bounded Gateway startup, and Doctor's wait hint. Startup tests use the existing injected clock and wait hooks.

Importer validation exposed and fixed three fixture assumptions without relaxing liveness or custody checks:

  • The retained-worker test counted every process worker while an earlier heartbeat was still exiting. It now observes the exact retained worker's exit and verifies that generation teardown joined it.
  • The restart-intent service fixture changed the apparent OS after publishing a real lease. Synthetic service selection now leaves real namespace/PID probes on the native host.
  • Two Doctor fixtures released physical custody while retaining a live lease for the test process. Their simulated shutdown now clears only its own lease first. The legacy-catalog fixture still checks exact bytes before stop and after the fixture-owned cleanup.

Direct-route Codex P1 review: clean on the final tree. No Docker two-container probe was run. The release-only sustained-contention test and native Windows Scheduled Task lifecycle were skipped by their existing gates; the Windows integration file's four platform-independent assertions passed.

Slow pre-existing suites (waived)

The campaign lead explicitly waived pre-existing slow suites; no performance fixture changes were made. Measured test time, excluding compiler/setup work:

Suite Test time
src/flows/doctor-health.test.ts 252.796 s
src/infra/state-migrations.test.ts 148.129 s
src/cli/local-state-owner.process.test.ts 139.424 s
Required test/scripts/pr-worktree-provision.test.ts gate 334.230 s

Auto-merge is off.

Use the state lock's boot/PID-namespace evidence and 90-second heartbeat
policy for SQLite Gateway ownership. Renew every 15 seconds, preserve live
owners, bound startup recovery, and explain fresh-lease refusals in Doctor.

Keep the existing schema and payload compatibility. Cover stale container
leases and repair worker-exit, platform, and shutdown fixture assumptions.

Fixes #155644.
@clawsweeper

clawsweeper Bot commented Oct 3, 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 docs Improvements or additions to documentation cli CLI command changes commands Command implementations docker Docker and sandbox tooling size: L labels Oct 3, 2026
@steipete
steipete marked this pull request as ready for review October 3, 2026 21:22
@clawsweeper

clawsweeper Bot commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 3, 2026, 5:24 PM ET / 21:24 UTC.

ClawSweeper review

What this changes

The branch makes Gateway SQLite owner leases use the state lock’s namespace and heartbeat evidence for crash recovery, with bounded startup waiting and clearer Doctor guidance.

Merge readiness

✅ Ready for maintainer review

This PR remains useful: current main still has the hostname-only SQLite lease guard. No concrete introduced defect was found, and the author’s repository-admin status independently confirms maintainer handling.

Priority: P1
Reviewed head: ac05d87c24c16da42b65d721dbd7d4550dc37232

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with meaningful boundary coverage, compatible legacy payload handling, and no actionable correctness findings.
Proof confidence 🌊 off-meta tidepool Not applicable: Verified repository-admin authorship exempts ordinary contributor proof. The body reports native SQLite and production acquisition-boundary tests, but explicitly no Docker two-container probe; prior physical-lock Docker evidence is supplemental only. Existing-state compatibility is supported by optional payload metadata, unchanged schema, legacy-row coverage, and reported passing admission tests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Verified repository-admin authorship exempts ordinary contributor proof. The body reports native SQLite and production acquisition-boundary tests, but explicitly no Docker two-container probe; prior physical-lock Docker evidence is supplemental only. Existing-state compatibility is supported by optional payload metadata, unchanged schema, legacy-row coverage, and reported passing admission tests.
Evidence reviewed 8 items Pinned patch and merge ownership: Inspected merge-base-to-head hunks and the verified test merge against its main parent. The original head records parent 3f4e6a1; the test merge records the supplied main followed by the exact PR head. Base-only work was not attributed to this PR.
Still necessary on current main: Current main returns unknown immediately when a lease owner’s hostname differs. Its Gateway acquisition still uses generic dead-owner reclamation, leaving the reported unexpired foreign-host lease held. The PR head is not an ancestor of fetched main; no shipped fix is claimed.
Final mutation fencing: Acquisition checks current state-write authority, rereads the predecessor inside BEGIN IMMEDIATE, and deletes only that observed owner token before publishing the replacement. Fresh unverifiable ownership and comparable live owners are refused; renewal and release retain owner-token predicates.
Findings None None.
Security None None.

How this fits together

Gateway ownership coordinates processes sharing an OpenClaw state directory. Physical locks and a SQLite owner lease admit startup or Doctor maintenance while excluding competing writers.

flowchart TD
  A[Gateway startup or Doctor] --> B[Acquire physical state custody]
  B --> C[Read SQLite owner lease]
  C --> D[Check namespace and heartbeat]
  D --> E[Preserve live or fresh unknown owner]
  D --> F[Reclaim stopped owner in transaction]
  F --> G[Publish and renew replacement lease]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +101, Tests +313, Docs +8. Total +422 across 15 files.

View PR surface stats
Area Files Added Removed Net
Source 8 124 23 +101
Tests 6 339 26 +313
Docs 1 9 1 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 15 472 50 +422

Review metrics

Metric Value Why it matters
SQLite heartbeat cadence 30 seconds → 15 seconds Lease renewal now matches the existing physical custody heartbeat and its 90-second recovery policy.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/commands/doctor-maintenance-inspection.ts. Migration or upgrade compatibility proof is recorded; maintainers should verify it before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #155644
Summary: This PR is the explicit implementation candidate for the Docker SQLite owner-lease recovery issue.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Keep one namespace-qualified recovery policy for physical custody and SQLite leases, preserving live owners and automatic recovery of legacy container state.

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

Yes, from source: a recreated container’s changed hostname leaves an unexpired predecessor lease unknown and held on current main. The linked report supplies repeated Docker failures; this review did not run Docker.

Is this the best way to solve the issue?

Yes. Reusing the established namespace classifier while retaining physical custody and transaction-local owner fencing is a focused repair of the existing startup contract.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P1: The linked report documents repeated multi-minute Gateway outages after Docker container recreation.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.

Label justifications:

  • P1: The linked report documents repeated multi-minute Gateway outages after Docker container recreation.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 99fccf4 adds src/infra/gateway-lock-payload.ts:11 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 99fccf43358c; files: src/infra/gateway-lock-payload.ts)

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.

@steipete
steipete merged commit 06da0de into main Oct 3, 2026
178 of 213 checks passed
@steipete
steipete deleted the upd/upd-owner-lease-stale-after-crash branch October 3, 2026 21:39
steipete added a commit that referenced this pull request Oct 4, 2026
…lease liveness policy (#164697)

After #164546 made the owner lease share the state lock's liveness policy, Doctor's maintenance entry inherited runtime schema admission and strict snapshot-cleanup requirements from the acquisition path and refused with GatewayLockError / DoctorSqliteMaintenanceLockUnavailableError on state it exists to repair (doctor-health.dangling-workshop-index and doctor-session-sqlite.retirement-disposal went red on main). Maintenance lease inspection is now separate from runtime schema admission while keeping the lease check and the native-reader closure requirement; foreign-owner refusal is unchanged. Bisected: passes at 5421a78, fails from 06da0de.
RomneyDa pushed a commit that referenced this pull request Oct 4, 2026
…lease liveness policy (#164697)

After #164546 made the owner lease share the state lock's liveness policy, Doctor's maintenance entry inherited runtime schema admission and strict snapshot-cleanup requirements from the acquisition path and refused with GatewayLockError / DoctorSqliteMaintenanceLockUnavailableError on state it exists to repair (doctor-health.dangling-workshop-index and doctor-session-sqlite.retirement-disposal went red on main). Maintenance lease inspection is now separate from runtime schema admission while keeping the lease check and the native-reader closure requirement; foreign-owner refusal is unchanged. Bisected: passes at 5421a78, fails from 06da0de.

(cherry picked from commit 9aee9ad)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 4, 2026
…nce as the state lock (openclaw#164546)

A Gateway could not start, and Doctor could not enter maintenance, on its own state after a crash loop or a container recreate: the SQLite owner lease's recovery was hostname-only, so a changed hostname made the dead owner 'unknown' and a lease without expiry blocked startup indefinitely ('Another Gateway owner lease is still active for this state directory'). Lease liveness now uses the state lock's shared boot/PID-namespace classifier and the 90 s heartbeat policy from openclaw#164236: a proven-dead owner (dead PID in the same namespace, or a changed boot on the same host) or an unverifiable namespace whose heartbeat is older than 90 s is reclaimed; fresh unverifiable owners and qualified live owners still refuse; renewal every 15 s; Gateway startup waits out a fresh unverifiable lease; Doctor names the wait. Acquisition rechecks ownership transactionally. No schema change. Closes openclaw#155644. Reported again today on Discord (main crash loop; Docker 2026.9.8 container).
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 4, 2026
…lease liveness policy (openclaw#164697)

After openclaw#164546 made the owner lease share the state lock's liveness policy, Doctor's maintenance entry inherited runtime schema admission and strict snapshot-cleanup requirements from the acquisition path and refused with GatewayLockError / DoctorSqliteMaintenanceLockUnavailableError on state it exists to repair (doctor-health.dangling-workshop-index and doctor-session-sqlite.retirement-disposal went red on main). Maintenance lease inspection is now separate from runtime schema admission while keeping the lease check and the native-reader closure requirement; foreign-owner refusal is unchanged. Bisected: passes at 9cee184, fails from 24dbf43.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes commands Command implementations docker Docker and sandbox tooling docs Improvements or additions to documentation size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Gateway owner-lease reclaim can never fire in Docker: owner.host is the container ID, which changes on every recreate

1 participant