Skip to content

fix(state): record why a lease was lost - #183279

Merged
steipete merged 5 commits into
mainfrom
upd/upd-l1904
Oct 25, 2026
Merged

steipete merged 5 commits into
mainfrom
upd/upd-l1904

Conversation

@steipete

@steipete steipete commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #183154. Refs #182476. Thanks @ooiuuii for the source-level reproduction.

What Problem This Solves

Update repair records the same generic lease-loss error when the lease expired, another owner replaced it, or its row disappeared, leaving long Doctor/plugin-finalization failures unexplained.

User Impact

Update history and failure reports now retain the observed lease-loss reason, expiry and heartbeat timing, and measured native renewal-timer lateness when available. Replacement owner identities are redacted. Lease timing and ownership rules are unchanged.

Why This Change Was Made

The lease owner classifies the row when renewal or verification fails and attaches a closed, typed diagnostic to the original error. Worker transport and update failure facts preserve it independently of the bounded error message. Diagnostic reads are best effort: unavailable storage keeps the original failure. The existing wrapper source inventory includes the shared diagnostic module so extracted maintenance commands retain their complete runtime closure.

Evidence

CI repair follow-up — 27b75be

The restart VM fixture's explicit production-module map omitted the new shared lease-loss schema and typed lease-error module. Its fallback exported an unexpected-call function, so evaluating the real update schema failed at StateLeaseLossSchema.optional(). The map now loads both complete production modules; the generic state schema keeps its lease-owner boundary. Node's child test runner explicitly loads the repository TypeScript resolver. No verification, restart, or backup-retention assertion changed.

The exact restart wrapper passes locally on Node 26.12.1 and pinned Bun 1.4.4-canary.1+807211511, each running all 19 native restart/filesystem cases. The schema error was reproduced before the fix on both runtimes (Node with the repository loader). Commands used isolated HOME and OPENCLAW_STATE_DIR: OPENCLAW_VITEST_RUNTIME=node node scripts/run-vitest.mjs test/scripts/update-restart-module-outcome.test.ts and the same command with OPENCLAW_VITEST_RUNTIME=bun. All six originally touched lease-test files also pass on Node: 35 tests. Tooling test types, targeted lint/format, diff checks, and fresh review pass. Follow-up delta: production 0; test/fixture +8/-1 lines.

Rechecked the four earlier consumer assertions on Node with the repository runner and a test-name filter, in project-registry then CLI-process order:

Assertion Recheck Relationship to the schema stub
truncated fetched ref inventory Passed, 57.781 s Real Git refresh; no VM fallback module map
repair-deadline Passed, 13.345 s Real CLI module loader; no VM fallback module map
doctor-progress Passed, 6.148 s Real CLI module loader; no VM fallback module map
doctor-hang Failed, 7.708 s Same saved-run phase-detail assertion at line 271; logs say “Could not persist phase diagnostic,” without a schema-load error

These four are not the restart VM's schema-stub problem. Three passing replays do not prove their intermittent failures repaired. The remaining Doctor phase-persistence failure is unresolved. The earlier “inherited” attribution was too strong: unchanged test files alone do not establish base causality. No assertion, timeout, retry, or skip was weakened, and this follow-up does not claim the full consumer run is clean.

Original-head evidence (291252e1) follows.

Six regression cases (expired/replaced/missing × renewal/verification) fail on the original code and pass with this fix using real SQLite rows. Each checks worker error transport, persisted update history, report rendering, and owner-token redaction; an additional case preserves the generic error when diagnostics cannot be read. The native lease suite also verifies expiry and measured renewal-timer lateness.

Live proof on Node 26.12.1 used an isolated state directory and the real plugin lifecycle lease: a 1,000 ms lease with 1,200 ms of synchronous work produced expiredByMs=227, heartbeatAgeMs=1227, and renewalTimerLateByMs=875. The real ledger and artifact writers preserved the structured fact in SQLite, bounded failure JSON, and the saved Markdown report. Command: HOME=$PWD/.artifacts/home OPENCLAW_STATE_DIR=$PWD/.artifacts/state node --import ./scripts/tsx.mjs .artifacts/live-lease-loss.ts; the probe selects its own .artifacts/live-state for the real lease and artifacts.

Invoked all 133 selected consumer files on Node, preserving the discovered list through the repository runner. Results across the selected groups: 127 passing files, 3 existing skipped files, and 3 files with failures/setup blocks; 2,192 passing tests, 7 failures, and 11 existing skips. Of the failures, 3 were the host filesystem admission block described below. The four consumer assertion failures in two untouched files remain visible below; the overall consumer run is red and is not claimed as clean.

Core and state/logging test typechecks, touched-file oxlint and oxfmt, git diff --check, and Madge (0 cycles) pass. The mock-export baseline shrinks by one obsolete full-mock entry; no new exceptions. Fresh isolated review found no actionable P0–P2 findings. The full check:changed SQLite inventory was skipped under the campaign's local time budget; PR CI remains the broad proof. Proof ran on macOS/Node; Windows was not exercised locally.

Pre-existing slow proof is recorded rather than hidden: wrapper trust/extraction cases reached 59.9 s per test, the worktree-provision storage-failure case took 40.8 s, and Gateway archive/restore setup reached 37.9 s. These exercise real Git worktrees/extracted runtime commands. The tooling group took 1,012 s of tests. No timeouts, retries, skips, or assertions were weakened. The initially exposed async-cleanup mock failure was fixed at the controlled mock boundary; its corrected case passed in 38 ms.

Original consumer failure in an untouched file: src/projects/project-registry.test.ts — “rejects a truncated fetched ref inventory before deleting tracking refs” failed after 66.341 s. It writes 65,537 real refs and calls the unchanged Git refresh implementation; Git fetch hits its existing 60,000 ms deadline before the intended 8 MiB inventory assertion, yielding “Git fetch could not reach GitHub.” Both the test and its Git implementation are byte-identical to the base. This is a slow fixture/deadline failure, outside the changed lease path; it was recorded rather than retried or weakened.

Consumer timing failure in an untouched fixture: src/cli/update-finalization-output.process.test.ts — “repair-deadline preserves the output and exit contract” took 26.377 s and missed plugins-entered/late-write-refused. The fixture's 1,000 ms plugin-phase budget expired during real lease/setup work before its synthetic callback; the next deadline scenario passed. The test, fixture, and finalizer are unchanged from base. No lease-loss classification was triggered before the deadline. This timing-sensitive setup failure is recorded, not treated as a passing retry.

Two more assertions in that unchanged CLI process file failed: doctor-hang (12.551 s) and doctor-progress (11.553 s). Their terminal output retained the expected Doctor deadline/output, but the saved-run assertion failed after the fixture advanced its recovery clock; logs report “Could not persist phase diagnostic.” These consumer persistence/timing gaps remain unresolved; they are not counted as passing proof of this change. The independent real lease/history/artifact probe and touched lease regressions pass.

Additional pre-existing slow CLI proof: update-finalization-output.process.test.ts took 359.55 s total (90% test time), spawning a fresh CLI child for each of 20 output/exit scenarios; update-command-install-layout.test.ts's first container-image case took 45.226 s while initializing the real command/reporting path. No timeout or assertion was changed.

Host-blocked E2E proof: all 3 cases in src/gateway/worker-environments/destination-authority.e2e.test.ts failed setup at createNodeWorkerTempWorkspace: @openclaw/fs-safe rejected a temp-workspace ancestor with mode 0775 and no sticky bit (insecure-permissions). No shared directory permissions or admission guards were changed. Wall time was 124.01 s, with 61% transformation and 31% test time. This does not establish a destination-transfer product failure.

Classify failed lease renewal and verification at the row owner, retaining
expired, replaced, or missing facts through typed worker errors and bounded
update history and failure reports. Record native renewal timer lateness
without changing lease authority, cadence, or expiry semantics.

Fixes #183154. Refs #182476.
Thanks @ooiuuii for the reproduction.
@clawsweeper

clawsweeper Bot commented Oct 25, 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 scripts Repository scripts size: M labels Oct 25, 2026
@steipete
steipete marked this pull request as ready for review October 25, 2026 05:14
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-25T12:05:22.803235Z a401432 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 291252e154

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

destination: UpdateDestinationFailureSchema.optional(),
npmErrorCode: z.enum(UPDATE_NPM_ERROR_CODES).optional(),
packageSpec: z.string().max(200).optional(),
leaseLoss: StateLeaseLossSchema.optional(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Add lease-loss diagnostics to the update-run wire schema

When an update records a lease-loss diagnostic, toPublicUpdateRun() preserves this new field and the Gateway returns it through update.status, update.runs.get, and update.runs.list. However, the closed failure-fact object in packages/gateway-protocol/src/schema/update-runs.ts does not allow leaseLoss. I verified that all four generated record/result predicates accept an otherwise identical record without this field and reject it with { reason: "missing" }, so these failures produce responses that violate the published protocol contract. Extend the wire schema and regenerate its validators alongside the ledger schema.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 25, 2026
@clawsweeper

clawsweeper Bot commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR preserves redacted lease-loss reasons and timing through worker errors, update history, and failure reports.

Example: A lease expired 1,000 ms ago and its last heartbeat was 6,000 ms ago.

  • Before: The retained error only says the state lease was lost.
  • After: The error and update fact identify expiration and retain both timing values.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful diagnostic repair with real production-owner evidence, but an incomplete public contract, attributable fixture failure, and unverified upgrade compatibility prevent readiness.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Operators cannot distinguish expiration, replacement, and missing lease state from retained update failures.
Reason: The linked issue establishes a concrete diagnostic defect, and the supplied maintainer-authored classification establishes direction without another product approval.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep open: this PR addresses a verified diagnostic gap, but the public update schema and a failing restart fixture need matching changes.

Priority: P2
Reviewed head: 291252e1545127ebede10a29223609cdaa9eb318

Before merge

  • Add lease-loss facts to the public update wire schema (P2) - A failed update can now persist failureFacts containing leaseLoss, and toPublicUpdateRun returns that field unchanged through update.status, update.runs.get, and update.runs.list. The failure-fact object in packages/gateway-protocol/src/schema/update-runs.ts is closed and does not declare this property, so the new response violates its published validators. Add the bounded optional union to that schema, regenerate validators, and extend the existing wire-contract cases.
  • Include the new schema dependency in the restart fixture (P2) - The restart/recovery fixture evaluates update-run-schema.ts but replaces imports outside its realNames inventory with synthetic functions. This new StateLeaseLossSchema dependency is absent from that inventory, so evaluating StateLeaseLossSchema.optional() throws before the recovery scenarios run. The exact-head checks-node-compact-small-7 annotations show this failure repeatedly. Include the real shared schema module in scripts/tests/update-restart-module-outcome.mjs and rerun that fixture without weakening its assertions.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

  • [P2] Add lease-loss facts to the public update wire schema — src/infra/update-run-schema.ts:141
  • [P2] Include the new schema dependency in the restart fixture — src/infra/update-run-schema.ts:141

Tests

  • Missing end-to-end proof: No upgrade from v2026.10.7 demonstrates that existing update history remains readable and intact with the new persisted diagnostic shape.
Agent review details

How this fits together

State-lease storage verifies durable ownership; failed checks flow through worker error transport into update history, CLI reports, and Gateway responses.

flowchart TD
A[Lease caller] --> B[Ownership check]
B --> C[State lease row]
C --> D[Redacted loss diagnostic]
D --> E[Worker error transport]
E --> F[Update history]
F --> G[CLI reports and Gateway API]
Loading

Technical review

Best possible solution:

Keep classification at the existing lease owner and complete its public-schema and restart-fixture integration.

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

Current-main renewal and verification deterministically collapse expired, replaced, and missing rows into the same error; the reporter supplies matching real-release evidence and source regressions.

Is this the best way to solve the issue?

The diagnostic-only storage-boundary approach is appropriate and preserves existing fencing; the smallest complete fix also updates the public wire contract and affected fixture closure.

Full review comments:

  • [P2] Add lease-loss facts to the public update wire schema — src/infra/update-run-schema.ts:141
    A failed update can now persist failureFacts containing leaseLoss, and toPublicUpdateRun returns that field unchanged through update.status, update.runs.get, and update.runs.list. The failure-fact object in packages/gateway-protocol/src/schema/update-runs.ts is closed and does not declare this property, so the new response violates its published validators. Add the bounded optional union to that schema, regenerate validators, and extend the existing wire-contract cases.
    Confidence: 0.99
  • [P2] Include the new schema dependency in the restart fixture — src/infra/update-run-schema.ts:141
    The restart/recovery fixture evaluates update-run-schema.ts but replaces imports outside its realNames inventory with synthetic functions. This new StateLeaseLossSchema dependency is absent from that inventory, so evaluating StateLeaseLossSchema.optional() throws before the recovery scenarios run. The exact-head checks-node-compact-small-7 annotations show this failure repeatedly. Include the real shared schema module in scripts/tests/update-restart-module-outcome.mjs and rerun that fixture without weakening its assertions.
    Confidence: 1

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Lease storage and worker ownership keeps the original intent (65bc5f6: Move lease lifecycle work to existing state workers while retaining exact durable ownership, admission, and settlement checks.)
  • Shared lease error construction keeps the original intent (e5478ff: Consolidate lease error formatting and repeated state behavior without intended authority or persistence changes.)
  • Heartbeat loss diagnostics keeps the original intent (913a400: Retain the first observed operation and outcome without claiming which persisted row state caused loss.)
  • Heartbeat liveness keeps the original intent (44aa4e1: Use ordinary request correlation and finite lease-bounded deadlines while keeping durable ownership authoritative.)
  • Public failure reporting keeps the original intent (f642756: Expose fixed actionable facts while keeping arbitrary private diagnostics behind the established redaction boundary.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test packages/gateway-protocol/src/update-runs-validators.test.ts
  • node --experimental-vm-modules --test scripts/tests/update-restart-module-outcome.mjs
  • pnpm test src/state/openclaw-state-lease-loss.test.ts src/state/openclaw-state-lease.test.ts
  • pnpm protocol:check
  • git diff --check

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 6125c6b adds src/state/openclaw-state-lease-heartbeat.worker.ts:121 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 6125c6b44c23; files: src/state/openclaw-state-lease-heartbeat.worker.ts)

PR surface

Source +154, Tests +186, Docs +9, Other 0. Total +349 across 24 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 17 181 27 +154
Tests 4 187 1 +186
Docs 1 9 0 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 2 1 1 0
Total 24 378 29 +349

Root-cause cluster

Relationship: same_root_cause
Canonical: #183154
Summary: The canonical issue isolates lost lease-state diagnostics; another open PR implements overlapping classification, while the Windows availability investigation has distinct remaining causes.

Members:

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

Labels

Label changes:

  • add P2: This repairs an operator diagnostic gap without resolving or introducing an established runtime outage.
  • add merge-risk: 🚨 compatibility: Lease-loss records now contain a field rejected by the published closed Gateway response schema.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: This repairs an operator diagnostic gap without resolving or introducing an established runtime outage.
  • merge-risk: 🚨 compatibility: Lease-loss records now contain a field rejected by the published closed Gateway response schema.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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 execution lanes are retired.

Reviewed October 25, 2026, 1:32 AM ET / 05:32 UTC.

# Conflicts:
#	config/test-mock-exports-baseline.txt
#	src/state/openclaw-state-lease-native-admission.test.ts
steipete added a commit that referenced this pull request Oct 25, 2026
…et and host ports (#183578)

The requester-revoked package receipt test pinned Doctor's timeout to the full budget although #166000 passes the remaining admitted budget, so it failed whenever setup consumed time (seen on #183279 CI). The native systemd stop fixture inspected the host's real Gateway port; it now stubs port inspection like the rest of its service boundary.
@steipete
steipete merged commit 9db139f into main Oct 25, 2026
142 checks passed
@steipete
steipete deleted the upd/upd-l1904 branch October 25, 2026 12:28
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 26, 2026
…et and host ports (openclaw#183578)

The requester-revoked package receipt test pinned Doctor's timeout to the full budget although openclaw#166000 passes the remaining admitted budget, so it failed whenever setup consumed time (seen on openclaw#183279 CI). The native systemd stop fixture inspected the host's real Gateway port; it now stubs port inspection like the rest of its service boundary.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 26, 2026
OPENCLAW_STATE_LEASE_LOST reported the same generic message whether the lease expired, was replaced by another owner, or no longer existed, so Windows update repairs that failed with a lost plugin lifecycle lease (openclaw#182476) could not be diagnosed. The lease owner now classifies the loss as expired, replaced or missing from the persisted row and carries that reason through the error and the update failure report. Lease duration, renewal cadence, fencing and ownership are unchanged.

Fixes openclaw#183154. Thanks @ooiuuii for the report and the diagnostic-only fix in openclaw#183178.

Co-authored-by: luyifan <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 14, 2026
Backport diagnostic-only lease loss classification to release2026.11.4.
Retain the release heartbeat admission/ack protocol and inline test mocks;
exercise persisted failure history through the release ledger API.
No lease policy or database schema change.

(cherry picked from commit 9db139f)

Co-authored-by: luyifan <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vincentkoc <[email protected]>
(cherry picked from commit 9511547e4a640a45af8df1270d07b58312bd49eb)
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 merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: M 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.

[Bug]: OPENCLAW_STATE_LEASE_LOST hides the persisted loss reason

1 participant