Skip to content

perf(plugins): move runtime lifecycle lease checks off the Gateway thread - #184784

Merged
steipete merged 4 commits into
mainfrom
steipete/perf-micro-main-sync-fs-under-writeback-20260919
Oct 26, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/perf-micro-main-sync-fs-under-writeback-20260919

Conversation

@steipete

@steipete steipete commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Plugin installation, metadata refresh, setup, and config reload still entered native SQLite lifecycle leases on the Gateway main thread. Under filesystem writeback, repeated ownership and path inspection could block unrelated requests. This completes the plugin/package caller cutover to the async owners established by #184275 and #184586.

User Impact

Plugin runtime mutations await worker-owned lease verification while retaining their original authority through publication and rollback. Native CLI, Doctor bootstrap, and synchronous SDK entry points retain their existing contracts. No schema, configuration, or install-policy changes.

Why This Change Was Made

Use the existing async plugin lifecycle lease in runtime callers. Carry the original lease set to worker commits and await ownership before external effects, followed by the existing synchronous current-owner and filesystem identity guards. Deferred package transactions retain their producer's settlement preparation through commit, rollback, and internal failure cleanup; rollback does not replay forward consent. Refusals stay sticky. Doctor cleanup preserves cancellation rather than aggregating it as an ordinary I/O failure.

The old native runtime paths are removed from migrated callers. Production delta: +646/−373, net +273 lines. Growth carries the same authority across asynchronous effect boundaries and settlement; no second lease owner or new cache. Two single-use install-record helpers were removed. Existing install-path helpers moved unchanged into their existing owner to keep the installer within its line cap.

Evidence

The real installed-plugin inventory writer runs under a real synthetic Gateway owner. Restoring only its prior native lease calls makes the regression fail: successful publication performs 16 owner-file reads plus 16 identity resolutions; owner replacement performs 2 plus 2. The candidate performs zero host ownership filesystem reads and zero host lease SQL, persists the requested inventory, and refuses both Gateway-lock replacement and physical database replacement. Fault injection adds 20 ms per host ownership read.

The owner benchmark in #184586 uses 10,000 retained keys across 40 scopes, 2,000 checks per arm, five alternating pairs. Main-thread CPU falls 70.8%, total sampled allocation falls 10.4%, and injected-delay heartbeat stalls fall from 523.760 ms to 0.068 ms. Total process CPU rises 45.7% (+76 µs/check), a disclosed cost of fresh worker verification. Across the five paired means, each check saves 97.9 µs of main-thread CPU and adds 161.0 µs of measured-worker CPU; the remaining process-counter delta is unattributed (+12.8 µs/check, including differing counter windows). Source inspection shows two explicit worker round trips: fresh Gateway-owner verification, then physical database and keyed lease-expiry verification. The measured extra work is per explicit ownership check, with reused workers and no scan of retained keys. Existing periodic renewal is separate (30 seconds in this benchmark; CPU loops under 0.5 seconds). These are observed per-operation costs, not a universal CPU upper bound; individual filesystem/SQL/messaging shares were not profiled. These are shared-owner measurements, not plugin throughput or whole-Gateway results. No Team or production server was used.

Focused checks passed for plugin metadata and physical replacement, transaction commit/rollback, Doctor repair and cancellation, capability consent, config migration, ClawAdd handoff, package runtime, archive install, channel setup, reload, and system-agent setup. The final installer/inventory run passed 52 tests in 4 files; the five updated mock consumers passed 95 tests. Core typecheck, scoped production/test lint, formatting, and one-page MDX passed. The two import-closure files passed 26 tests, and the export-collision guard passed. The mock-export baseline removes exactly six obsolete entries; no exception was added. Final-head CI will be recorded after publication. The local bootstrap publication file has three investigated failures: native Darwin descriptor-ACL inspection is unavailable (helper-unavailable). Restoring the unchanged native bootstrap producer reproduces the same three failures; the candidate source was restored afterward. This is a local environment limitation, not passing proof of those paths, and the exact native-helper availability remains unresolved locally. Linux PR CI supplies the broader platform proof. Independent subagent review (autoreview route unavailable) covers the complete cutover and retained settlement authority.

The runtime prerequisite #184586 is merged as e0b550b0ababbf011ec2aaee40c00a228070562a. On the restored plugin-only stage, the lifecycle cutover matches the reviewed source; unchanged candidate-admission and onboarding filesystem-fixture helpers were subsequently moved into their existing owners to satisfy the file-size ratchet. Current-main uninstall ownership changes remain intact; their 14 tests passed alongside the project integration proof. The isolated plugin-stage mock-export guard passes with the plugin baseline removals. No project or placement changes are included.

The final file-cap refactor moves unchanged candidate-admission and onboarding fixture helpers into existing owners. The affected three test files pass all 120 tests; scoped lint, line-cap, export-collision and import-closure checks (26 tests) pass. Independent review found no behavioral change.

First CI investigation

CI run 40356507081 on head 1a390c9444ae9fe4adde725f1921ca2ea570bb01 exposed a real missed marker-effect boundary: passing only the in-memory guard let marker-directory cleanup run before a transient durable lease-read failure was observed. The repair carries the existing async authority callback through marker creation, removal and restoration, removing redundant outer checks. Forward operations retain their caller guard; compensation uses only its original lease authority. The existing regression stays unchanged. All 78 tests in the five focused retention, install-commit and Doctor-repair files pass; independent review is clean.

Directory and uninstall CLI expectations were stale after the async adapter cutover. The repairs require both config-write guards and strict identity of the inherited state lease; all 34 tests pass. Preflight now tracks both lease APIs while preserving real module exports and asserts the intended marketplace failure, preventing an early setup error from passing. Its 21 tests pass. The restart fixture uses a real async borrowed lease and requires OPENCLAW_STATE_LEASE_LOST after reload closes before testing the provider write.

The missing-state Doctor notice fails identically on unchanged parent dea6ff0cd0a3b4f3c65518167a4fac013ba742f6. The candidate's diagnostic probe shows the valid CRITICAL: state directory missing note instead of the test's expected initialized-during-startup message. This is retained as inherited failure evidence; the assertion was not relaxed. The legacy-migration timeout and agent-deletion draining failure did not reproduce in their full files on that parent; the same full candidate files also pass (2 deletion tests and 4 migration tests). Final-head CI remains to be recorded. Passing replays alone do not establish fixes for those CI failures.

Final local repair proof also passes all 9 channel-restart tests, targeted core typecheck, scoped lint, line-cap and the mock-export guard. The preflight mock conversion removes one additional obsolete baseline entry, bringing the plugin PR total to six removals with no additions.

The projection config-commit fixture now mocks the async lifecycle API used by reload (one-line test-only correction); its full file passes. Independent review is clean. The three repair commits rebase patch-identically onto current main; no production projection code changed.

Second CI repair

Run 40364847440 on 19088a72a8c4beb74502c16215aee6aad888d4e7 passed the earlier plugin/reload/retention repairs and reported three remaining failures. The Doctor missing-state fixture expected the initialized-during-startup branch even though its directory stays absent. Its correction requires the critical missing-state warning, the exact target path, and that the directory remains absent; all 17 tests pass. No production behavior changed.

The legacy-migration case reached its existing 30-second deadline after spending 12.406 seconds in unrelated physical database-engine diagnostics. Its partial importOriginal mock now replaces only noteDatabaseEngines; real contribution routing, migration dispatch, OAuth repair, other exports, and the 30-second deadline remain. The physical inspection owner has separate tests. All four migration/OAuth cases pass, with the migration case taking 17.318 seconds locally. This removes the identified extra fixture work; a local pass alone is not a claim about arbitrary CI load.

The reload fixture's captured assertion is explicitly async so its real return type satisfies Promise<void> even though the shared metadata interface also permits synchronous owners. The exact failing gateway-server test-typecheck configuration and all nine restart tests pass. Scoped lint/format and independent review are clean. The next exact-head CI run will validate these three test-only corrections; no CI jobs were rerun.

Real-owner filesystem settlement proof

On cb0f5c043c44a2ec63899eb01196a946068a93de, a standalone synthetic local proof composed the actual async plugin lifecycle owner with deferred package installation and filesystem commit/rollback, without authority mocks or test hooks. All eight cases passed: permitted commit and rollback; both settlement operations after identical-byte, different-inode Gateway-lock replacement; both after physical database replacement; and both attempted under a live successor after the original lease closed. Refused operations preserved the installed and backup directories and marker files by device, inode, and bytes. Restoring replaced paths did not revive refused transactions. The successor remained healthy but could not authorize the original transaction (OPENCLAW_STATE_LEASE_LOST). The run finished in 48.565 seconds, exit 0. An initial proof matcher missed the actual Gateway-owner error wording; it was corrected to match the source's exact refusal message before the successful run.

This qualifies real filesystem settlement in addition to the committed inventory and injected-failure regressions. No schema, stored shape, migration, config option, or SDK contract changes are introduced. Existing inventory and package data are read back in the focused proofs. A latest-stable upgrade was not run; these results are not an upgrade claim.

Final CI

Exact-head run 40372504088 completed successfully on cb0f5c043c44a2ec63899eb01196a946068a93de, including openclaw/ci-gate. All three previously failing jobs passed after the fixture repairs. No CI rerun or inherited-failure merge exception was used.

@clawsweeper

clawsweeper Bot commented Oct 26, 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 gateway Gateway runtime cli CLI command changes commands Command implementations agents Agent runtime and tooling size: XL labels Oct 26, 2026
@steipete
steipete marked this pull request as ready for review October 26, 2026 16:10
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 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-26T17:55:36.283633Z cb0f5c0 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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 26, 2026
@clawsweeper

clawsweeper Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR moves plugin and package lifecycle verification to existing workers while preserving original ownership through publication and rollback.

Example: Plugin inventory publication with 20 ms injected delay per host ownership read.

  • Before: The reported baseline performs 16 owner-file reads and 16 identity resolutions on the Gateway thread.
  • After: The candidate reports zero host ownership reads and zero host lease SQL while persisting the inventory.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation appears correct and the composed authority evidence is materially stronger; required upgrade qualification remains incomplete.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Plugin and package operations can stall unrelated Gateway requests while synchronous ownership checks wait on filesystem writeback.
Reason: The maintainer-directed change addresses a demonstrated responsiveness problem using existing owners, with the additional CPU cost explicitly disclosed.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-directed PR completes a useful runtime caller cutover beyond the merged prerequisites; the prior finding is fixed, and no new concrete defect was found.

Priority: P2
Reviewed head: cb0f5c043c44a2ec63899eb01196a946068a93de

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Supply a latest-stable upgrade run preserving existing plugin records and configuration while exercising the changed Doctor/config settlement paths.
Agent review details

How this fits together

Gateway, setup, and plugin management callers acquire lifecycle ownership before changing package files, inventory, or configuration; existing workers verify durable custody and callers check current authority before effects.

flowchart TD
  A[Gateway and setup callers] --> B[Plugin lifecycle owner]
  B --> C[Worker ownership verification]
  C --> D[Inventory and config commits]
  C --> E[Package publication and settlement]
  D --> F[Runtime reload]
  E --> F
Loading

Technical review

Best possible solution:

Complete the existing async-owner cutover while preserving original-owner settlement and existing installation state.

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

Fetched main retains native runtime lease calls, and the submitted inventory control reports failure when those calls are restored; this read-only review ran no target code.

Is this the best way to solve the issue?

Reusing established worker owners and carrying original authority through settlement is the smallest coherent fix; the added guards protect distinct publication, compensation, and custody-loss boundaries.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Lifecycle verification and reload keeps the original intent (f738523: Separate current lifetime checks from durable assertions while preserving final publication authority.)
  • Sticky refusal and retained package settlement keeps the original intent (3ca2b4e: Keep the first authority refusal visible across metadata publication, Doctor effects, and outer package settlement.)
  • Shared-directory recovery keeps the original intent (f1098ee: Retain previous payloads until replacement publication settles and stop cleanup when filesystem ownership changes.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

PR surface statistics unavailable: the file list is incomplete.

Review metrics

Metric Value Why it matters
Production versus regression code Production +646/−373; tests and support +473/−150 Growth carries awaited verification through existing publication and settlement owners without adding a competing lease owner or persistent cache.

Labels

Label changes:

  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove merge-risk: 🚨 security-boundary: Current PR review selected no merge-risk labels.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: The change improves Gateway responsiveness during slow ownership filesystem operations in bounded plugin and package workflows.
  • 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.

Rank-up moves

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

  • Qualify the changed Doctor/config paths through an upgrade from the latest stable release with existing settings and plugin data intact.

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-26T16:30:53.323Z sha 1a390c9 :: needs real behavior proof before merge. :: [P2] Update directory CLI expectations for guarded config writes

Reviewed October 26, 2026, 2:13 PM ET / 18:13 UTC (Revision 2).

@steipete
steipete force-pushed the steipete/perf-micro-main-sync-fs-under-writeback-20260919 branch from 1a390c9 to 19088a7 Compare October 26, 2026 17:02
@steipete
steipete force-pushed the steipete/perf-micro-main-sync-fs-under-writeback-20260919 branch from 19088a7 to cb0f5c0 Compare October 26, 2026 17:51
@steipete

Copy link
Copy Markdown
Contributor Author

Addressed the findings on cb0f5c043c44a2ec63899eb01196a946068a93de.

The directory and uninstall expectations now require both config-write guards and the inherited lease identity while preserving source-config/base-hash checks; all 34 focused tests pass. Subsequent CI also exposed and prompted repairs to the marker-effect boundary and three test fixtures; the body records their causes and focused results.

The requested composed filesystem proof now passes all eight cases using the real async lifecycle owner and deferred package transactions, with synthetic local state and no authority mocks: permitted commit/rollback, Gateway-lock replacement, database replacement, and attempted settlement under a live successor after the original lease closed. Replacements preserve bytes but change inode identity. Refused operations preserve both installed and backup directory/file identities and bytes; pathname restoration does not revive them. The successor remains healthy but cannot authorize the old transaction. This proves the composed refusal behavior, not isolated transaction stickiness. Independent review of the proof found no actionable issue.

No schema, serialized shape, migration, configuration option, or SDK contract changes are introduced. Existing inventory/package readback is covered. A latest-stable upgrade was not run, and no upgrade qualification is claimed; the task's focused performance proof scope is retained.

The PR body now includes these results and the per-operation CPU attribution. Exact-head CI run 40372504088 is still being observed; landing will wait for green.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 26, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 26, 2026
@steipete
steipete merged commit 71eacdf into main Oct 26, 2026
204 of 206 checks passed
@steipete
steipete deleted the steipete/perf-micro-main-sync-fs-under-writeback-20260919 branch October 26, 2026 18:20
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 27, 2026
…read (openclaw#184784)

* perf(plugins): move runtime lifecycle lease checks off the Gateway thread

* fix(plugins): retain lease verification across marker filesystem effects

* test(gateway): mock async plugin lease in projection fixture

* test(doctor): isolate migration fixtures from engine probes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. cli CLI command changes commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. 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