Skip to content

perf: reduce CPU spent resolving model references - #149799

Merged
steipete merged 4 commits into
mainfrom
steipete/perf-provider-policy-surface-cache-20260916
Sep 16, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/perf-provider-policy-surface-cache-20260916

Conversation

@steipete

@steipete steipete commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Model selection and large session/model lists repeatedly resolve the same bundled provider policy artifacts, spending CPU on candidate paths and filesystem-cache lookups for every model reference.

User Impact

Repeated model-reference canonicalization uses less CPU while preserving provider policy and catalog behavior. No configuration changes or migration are required.

Why This Change Was Made

The module loader already caches exports, but runtime facade resolution happens before that cache. Keep resolved policy surfaces, including missing surfaces, in the existing plugin metadata cache. Entries follow the selected registry and its publication version plus the existing bundled-directory selection. Mutable registration/unpublished registries bypass the memo, and managed surfaces retain instance admission checks. Shared policy types live in a leaf contract so the metadata cache does not depend on the runtime resolver.

The memo is discarded by the existing metadata invalidation/reload lifecycle. The generic facade loader retains its cold-resolution and boundary checks; no Plugin SDK exports, time-based expiry, or filesystem freshness polling are added.

Evidence

Regression first: repeated present and missing policy lookups both failed on the original code with “expected 1 call, received 2” at candidate resolution.

Real-module coverage exercises replacement and retained generations, different registries sharing a cache, metadata invalidation, registry republication, retirement, unpublished registration, and bundled environment changes.

Warm local microbenchmark: seven batches of 10,000 bundled-provider model-reference canonicalizations after 1,000 warmups, using the real bundled policy and a published fixture registry on Node 26.8.2.

Measurement Before After
Median time / 10,000 canonicalizations 96.35 ms 19.83 ms

This is 4.86× faster (79.4% less time) for the canonicalization path; it does not measure end-to-end Gateway throughput.

The Plugin SDK surface-budget check passed; no public exports were added.

The full repository build passed. Focused proof passed 724 tests across 38 files: plugin/cache/facade owners, model selection, model-list results and lifecycle, and session-list catalog behavior.

CI initially caught a type-import cycle that the runtime-only cycle check did not detect. Extracting the existing policy contracts removed the dependency back into the resolver: Madge reports zero cycles, emitted runtime JavaScript is unchanged, and all 120 affected owner tests passed again. No guard, baseline, or budget was changed.

Regression excerpt:

Before, for both present and missing artifacts:
expected "vi.fn()" to be called 1 times, but got 2 times

After:
✓ resolves candidate locations once per generation (missing=false)
✓ resolves candidate locations once per generation (missing=true)

The native-catalog test initially hit its existing 120-second timeout before a full build, on both the candidate (120.86 s) and original owner source (120.49 s). After the full build, all three cases passed serially; the formerly failing case took 31.54 s with a load average around 124. The subsequent freshness file also passed all three cases in a clean process. No timeout, assertion, or retry changes were made.

node scripts/check-changed.mjs completed successfully, git diff --check passed, and fresh independent autoreview was clean at P2. No production deployment or live Gateway profile was performed.

Exact-head CI: run 35065846225 completed successfully for 0f1b57d57e1452bfcd924afd8e91fc7dee1eb1d0. The canonical watcher returned GREEN with zero pending checks and six superseded records excluded.

Exercise repeated candidate resolution, missing artifacts, generation replacement, environment selection, and retirement through model canonicalization.
Avoid repeating artifact candidate resolution for every model reference in session and model lists. Retain resolved surfaces in the plugin metadata owner while respecting registry publication, bundled-directory selection, and instance admission.
Document generation invalidation and runtime selection for bundled provider policy resolution.
@clawsweeper

clawsweeper Bot commented Sep 16, 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 size: M maintainer Maintainer-authored PR labels Sep 16, 2026
@steipete
steipete marked this pull request as ready for review September 16, 2026 06:19
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 16, 2026
@clawsweeper

clawsweeper Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 16, 2026, 3:23 AM ET / 07:23 UTC (Revision 3).

ClawSweeper review

What this changes

Caches resolved provider policy hooks within the existing plugin metadata lifecycle so repeated model-reference lookups avoid resolving the same artifact paths.

Merge readiness

✅ Ready for maintainer review

This remains a useful performance improvement absent from current main and the latest release. No blocking defect was found; the related merged optimization addresses a different lookup layer.

Priority: P2
Reviewed head: 0f1b57d57e1452bfcd924afd8e91fc7dee1eb1d0

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization with relevant performance evidence, lifecycle coverage, and successful CI for the reviewed head.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied Node 26.8.2 benchmark exercises model canonicalization with real bundled policy and a published fixture registry, reporting lower after-fix runtime; lifecycle tests supplement that focused evidence.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied Node 26.8.2 benchmark exercises model canonicalization with real bundled policy and a published fixture registry, reporting lower after-fix runtime; lifecycle tests supplement that focused evidence.
Evidence reviewed 8 items Introduced cache preserves lifecycle selection: The pinned introduced diff keys reusable surfaces by plugin ID, selected registry, publication version, and bundled-directory selection. Registration and unpublished registries bypass caching; managed cache hits call instance.run.
Existing admission and invalidation owners remain authoritative: PluginInstance.run checks current admission and revocation, and loadModule returns wrapped exports. Metadata invalidation replaces the entire metadata object, including the new map. This retains existing lifecycle checks without introducing credentials, persistent state, or a new authorization path.
Meaningful regression coverage: Inspected both complete test files. Coverage checks repeated present/missing lookups, replacement and retained generations, shared-cache registry changes, invalidation, republication, retirement, unpublished assembly, and environment selection. Tests were inspected, not executed during this read-only review.
Findings None None.
Security None None.

How this fits together

Model selection and catalog listing ask provider plugins to normalize model references. The plugin loader supplies those policy hooks, while its metadata cache controls their reuse across registry generations.

flowchart TD
  A[Model references] --> B[Provider policy lookup]
  B --> C{Matching cached generation?}
  C -->|Yes| D[Check instance admission]
  C -->|No| E[Resolve and load policy artifact]
  E --> F[Retain policy in metadata cache]
  F --> D
  D --> G[Canonical model reference]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +56, Tests +184, Docs +8. Total +248 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 4 150 94 +56
Tests 2 184 0 +184
Docs 1 8 0 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 342 94 +248

Review metrics

Metric Value Why it matters
Reported warm canonicalization time 96.35 → 19.83 ms per 10,000 calls The supplied real-policy microbenchmark demonstrates the targeted CPU improvement without claiming end-to-end Gateway gains.

Technical review

Best possible solution:

Reuse resolved policy surfaces through the existing metadata owner while preserving registry selection, invalidation, and instance admission.

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

Yes, source establishes repeated candidate resolution on current main, and the supplied benchmark exercises canonicalization through real bundled policy. This review did not execute the benchmark or tests.

Is this the best way to solve the issue?

Yes. The change extends the existing cache owner, preserves public policy contracts, and avoids another cache lifecycle or configuration option.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The supplied Node 26.8.2 benchmark exercises model canonicalization with real bundled policy and a published fixture registry, reporting lower after-fix runtime; lifecycle tests supplement that focused evidence.

Label justifications:

  • P2: This is a bounded performance improvement to repeated model and session catalog lookups.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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 Node 26.8.2 benchmark exercises model canonicalization with real bundled policy and a published fixture registry, reporting lower after-fix runtime; lifecycle tests supplement that focused evidence.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied Node 26.8.2 benchmark exercises model canonicalization with real bundled policy and a published fixture registry, reporting lower after-fix runtime; lifecycle tests supplement that focused evidence.

Evidence

What I checked:

  • Introduced cache preserves lifecycle selection: The pinned introduced diff keys reusable surfaces by plugin ID, selected registry, publication version, and bundled-directory selection. Registration and unpublished registries bypass caching; managed cache hits call instance.run. (src/plugins/provider-policy-surface.ts:85, 0f1b57d57e14)
  • Existing admission and invalidation owners remain authoritative: PluginInstance.run checks current admission and revocation, and loadModule returns wrapped exports. Metadata invalidation replaces the entire metadata object, including the new map. This retains existing lifecycle checks without introducing credentials, persistent state, or a new authorization path. (src/plugins/plugin-instance.ts:100, 0f1b57d57e14)
  • Meaningful regression coverage: Inspected both complete test files. Coverage checks repeated present/missing lookups, replacement and retained generations, shared-cache registry changes, invalidation, republication, retirement, unpublished assembly, and environment selection. Tests were inspected, not executed during this read-only review. (src/plugins/provider-policy-surface.generation.test.ts:59, 0f1b57d57e14)
  • Current main still repeats candidate resolution: At the fetched main revision, resolveDirectBundledProviderPolicySurface calls the candidate loader on each lookup and extracts a new surface. The existing lower-level module cache does not eliminate that preceding work. (src/plugins/provider-policy-surface.ts:163, e1472df83942)
  • Latest release also lacks this optimization: The direct resolver in the supplied latest-release commit likewise invokes candidate resolution for every call; it does not contain the proposed surface memo. (src/plugins/provider-policy-surface.ts, 3a9d69db306c)
  • Related merged work is complementary: GitHub confirms perf(plugins): speed up model catalogs with provider aliases #149528 merged. Its body and inspected commit add manifest-derived provider-owner indexes while retaining per-invocation artifact resolution, so it does not supersede this PR. (src/plugins/plugin-cache-metadata.ts, c2c3d53d557f)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • obviyus: 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 (2 earlier review cycles)
  • reviewed 2026-09-16T06:34:45.904Z sha 48a8170 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-16T07:03:01.441Z sha 0f1b57d :: needs maintainer review before merge. :: none

Share provider policy types through a leaf contract so metadata does not import the runtime resolver. Preserve the resolver companion exports and unchanged runtime behavior while satisfying the type-aware architecture guard.
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Sep 16, 2026
@steipete
steipete merged commit 1c44067 into main Sep 16, 2026
199 of 200 checks passed
@steipete
steipete deleted the steipete/perf-provider-policy-surface-cache-20260916 branch September 16, 2026 07:49
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 17, 2026
* test: cover provider policy cache generations

Exercise repeated candidate resolution, missing artifacts, generation replacement, environment selection, and retirement through model canonicalization.

* perf: reuse bundled provider policies during model selection

Avoid repeating artifact candidate resolution for every model reference in session and model lists. Retain resolved surfaces in the plugin metadata owner while respecting registry publication, bundled-directory selection, and instance admission.

* docs: explain provider policy cache lifetime

Document generation invalidation and runtime selection for bundled provider policy resolution.

* fix: keep provider policy cache contracts acyclic

Share provider policy types through a leaf contract so metadata does not import the runtime resolver. Preserve the resolver companion exports and unchanged runtime behavior while satisfying the type-aware architecture guard.
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 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: M 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