Skip to content

perf(agents): keep turn-path model catalog reads off the full live build - #120834

Merged
steipete merged 5 commits into
mainfrom
claude/openclaw-perf-optimization-089643
Aug 9, 2026
Merged

steipete merged 5 commits into
mainfrom
claude/openclaw-perf-optimization-089643

Conversation

@steipete

@steipete steipete commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

A fresh gateway's first agent turn took 65-73 seconds with a 36.6s event-loop block and ~+600MB heap — on a default config with a manifest-backed model (openai/gpt-5.6-luna). During the stall the gateway is unresponsive (healthz timeouts, WS closes), which on production source checkouts also manifests as slow post-update recovery and degraded event-loop health.

Root cause: embedded (and cron isolated-agent) model selection could not resolve a model's thinking capability from any cheap catalog — configuredThinkingCatalog is empty without models.providers, and the manifest catalog is only consulted when an allowlist or configured models exist — so it fell back to loadPreparedModelCatalogSnapshot without readOnly, which materializes the full live prepared-model-runtime catalog. That live build runs ambient synthetic-auth discovery across every registered provider ref, and resolveProviderSyntheticAuthWithPlugin's last-resort branch loads all provider plugins unfiltered. On source checkouts these loads go through jiti source transform: 3,172 TS modules transpiled inside the first turn (CPU profile: ~50s under jiti/babel stacks + 11s GC).

The answer it was looking for (Luna reasoning: true) sits in the openai plugin manifest, loadable in ~7ms.

Why This Change Was Made

Per the repo architecture rules: hot paths must carry prepared facts forward instead of broad request-time plugin/provider discovery, and full catalog materialization belongs to explicit control-plane reads.

  • New loadProviderScopedThinkingCatalog (in prepared-model-catalog.ts, exported via the model-catalog.runtime barrel): manifest metadata → provider-scoped read-only static catalog → provider-scoped live discovery only when the entry is still unresolved (preserves the fix(agents): preserve thinking for runtime-selected Ollama models #116584 runtime-selected-Ollama-model semantics). Used by both the embedded and cron thinking fallbacks (previously two copies of the unscoped pattern).
  • scopedLiveProviderDiscovery param routes scoped read-only loads to prepareScopedReadOnlyLiveModelCatalog.
  • Live-mode ambient synthetic-auth refs are intersected with providerDiscoveryProviderIds when the build is provider-scoped.
  • The providerRefs.length === 1 last-resort synthetic-auth sweep is bounded to discovery entry modules (discoveryEntriesOnly + includeSyntheticAuthProviders) instead of full plugin loads.
  • Per-turn skills refresh no longer re-walks and re-publishes every plugin skill dir before its signature cache check: single-slot memo keyed on (workspaceDir, config identity, metadata snapshot identity), evicted by the plugin metadata lifecycle clear.

Deliberately NOT changed: media-understanding catalog reads stay non-readOnly — runner.vision-skip.test.ts asserts that contract from the lifecycle-owner refactor (#111173).

User Impact

  • Cold first turn (fresh gateway, default config, live OpenAI): 72.7s → ~22s wall; agent.startup stage=model-selection 58,726ms → 124-508ms; no event-loop block, no memory spike. Remaining cold-turn latency is provider prefill of the ~19.5k-token default first-turn payload (cacheWrite 19,534, cacheRead 0) — follow-up below.
  • Cron isolated-agent turns and provider-scoped catalog reads no longer trigger full live discovery.
  • Warm turns: ~3s (provider-bound); Control UI end-to-end verified ("Done in 3 seconds").

Evidence

  • Baseline/after measurements, CPU-profile attribution, and jiti-cache module counts: campaign notes in the session (summary in commit message). Key numbers: model-selection 58,726ms → 124ms; 3,172 jiti-transpiled modules → 0 on the turn path; cold turn 72.7s → 21-48s (provider-prefill-bound, cacheRead: 0 confirms).
  • Focused tests green: src/skills/runtime/refresh.test.ts (35), src/skills/loading/plugin-sandbox-sync.test.ts, src/media-understanding/runner.vision-skip.test.ts (18), src/cron/isolated-agent/run.cron-runtime-model-thinking.test.ts, src/plugins/provider-runtime.synthetic-auth-discovery.test.ts, src/plugins/provider-discovery.runtime.test.ts (30), src/agents/prepared-model-runtime.startup-static.test.ts, src/agents/model-selection-display.test.ts.
  • pnpm build green (no INEFFECTIVE_DYNAMIC_IMPORT; cli-bootstrap-imports check passed).
  • Codex autoreview (gpt-5.6-sol, xhigh): clean, no accepted findings.
  • Live browser proof: Control UI chat round-trip on the built gateway, reply rendered in 3s.

Follow-ups (named, not in this PR):

  1. Default first-turn payload is ~19.5k tokens — dominates cold-turn latency and per-session cost; needs an owner decision on the default tool/prompt budget.
  2. Source-checkout deployments resolve providerDiscoverySource to TS sources when no installed index exists; control-plane full reads still jiti-compile once per process. Mapping manifest records to built dist artifacts would remove that class.
  3. update.status reports install.git.status="unavailable" reason="no-upstream" on campaign-managed detached-HEAD checkouts (observed on production team host) — reporting gap, separate surface.

@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Aug 9, 2026
@steipete
steipete marked this pull request as ready for review August 9, 2026 02:24
@openclaw-barnacle openclaw-barnacle Bot added size: S maintainer Maintainer-authored PR labels Aug 9, 2026
@clawsweeper clawsweeper Bot added 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. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Aug 9, 2026
@clawsweeper

clawsweeper Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed August 9, 2026, 1:44 AM ET / 05:44 UTC.

ClawSweeper review

What this changes

This PR replaces full live model-catalog construction during embedded and cron thinking selection with manifest-first, provider-scoped reads and memoizes plugin skill-directory publication.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

Keep open: the model-catalog repair is well-targeted, but the new plugin-skill memo can retain ACPX skills across a mutable ACP availability change, hiding available tools or exposing unavailable ones.

Priority: P1
Reviewed head: 59992e542e12faf3f9f0d01a53fe7bd53c240daf

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The performance repair has strong focused source coverage, but the ACPX availability regression blocks merge readiness.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: Repository context identifies this as a maintainer-authored PR; the external-contributor proof gate does not apply, and the supplied live-performance claims were not independently inspectable artifacts.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Repository context identifies this as a maintainer-authored PR; the external-contributor proof gate does not apply, and the supplied live-performance claims were not independently inspectable artifacts.
Evidence reviewed 6 items Current-main problem path: Current main still invokes an unscoped prepared catalog when embedded model selection lacks a thinking entry, which can materialize the full live catalog on a turn path.
Shared repair shape: The PR centralizes manifest, scoped-static, and scoped-live fallback at the catalog owner, and both embedded and cron callers use it.
Runtime-only model coverage: Focused tests prove the manifest/static/live tiers and retain runtime-only Ollama thinking through provider-scoped live discovery; cron also skips hydration for thinking=off.
Findings 1 actionable finding [P1] Include ACP availability in the plugin-skill memo key
Security None None.

How this fits together

Agent and cron turns consult model metadata to validate thinking levels before starting a run. Separately, skills refresh publishes eligible plugin skill directories so the agent sees only tools supported by the current runtime.

flowchart TD
A[Agent or cron turn] --> B[Thinking capability lookup]
B --> C[Manifest and scoped model catalog]
C --> D[Provider discovery]
D --> E[Selected model run]
F[Skills refresh] --> G[Plugin skill directories]
G --> H[Agent tool availability]
Loading

Before merge

  • Include ACP availability in the plugin-skill memo key (P1) - The memo returns before reevaluating isAcpRuntimeSpawnAvailable, although ACPX skill inclusion depends on it. ACP backend registration and health can change without clearing plugin metadata, so a first refresh can permanently hide newly usable ACPX skills or keep unavailable skills injected; include the availability state in the key (or bypass this memo for ACPX) and add a transition test.
  • Resolve merge risk (P1) - The memo can cache ACPX skill eligibility across ACP backend registration, health, or removal, so an agent may receive stale tool availability until plugin metadata happens to reload.
  • Resolve merge risk (P1) - Provider-scoped live discovery now narrows synthetic-auth work; its focused static and runtime-only tests should remain green when repairing the memo.
  • Complete next step (P2) - A narrow mechanical repair can preserve the performance work while restoring ACPX skill eligibility when the runtime changes state.

Findings

  • [P1] Include ACP availability in the plugin-skill memo key — src/skills/loading/plugin-skills.ts:58-66
Agent review details

Security

None.

PR surface

Source +133, Tests +220. Total +353 across 50 files.

View PR surface stats
Area Files Added Removed Net
Source 14 197 64 +133
Tests 36 225 5 +220
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 50 422 69 +353

Review metrics

Metric Value Why it matters
Production vs test LOC production +192/-64 (net +128); tests +230/-5 (net +225) The production growth is justified by the new provider-scoped catalog owner, but the independent skills memo needs the ACP-state repair before merge.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/flows/doctor-core-checks.runtime-errors.test.ts, migration/backfill/repair: src/flows/doctor-core-checks.runtime.test.ts, migration/backfill/repair: src/flows/doctor-core-checks.test.ts, migration/backfill/repair: src/flows/doctor-health-contributions.test.ts, serialized state: src/auto-reply/reply/session-reset-model.test.ts, serialized state: src/auto-reply/reply/session.test.ts, and 1 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Key the memo on ACP availability (recommended)
    Recompute published plugin skills whenever ACP availability changes, while retaining the provider-scoped catalog behavior and its runtime-only-model coverage.
  2. Remove the skill-directory memo
    Keep the catalog optimization but drop this memo if ACP state cannot be represented safely in its cache identity.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Include ACP availability in the plugin-skill memo identity, add unavailable-to-available and available-to-unavailable transition coverage with one stable config and metadata snapshot, then run the focused skill-loading test.

Technical review

Best possible solution:

Keep the scoped catalog repair, but make skill-directory caching depend on current ACP availability and prove both unavailable-to-available and available-to-unavailable transitions with one stable config and metadata snapshot.

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

Yes. With one stable config and metadata snapshot, call the skill resolver, change ACP backend availability, and call it again; the memo returns the prior ACPX directory set without reevaluating the gate.

Is this the best way to solve the issue?

No. The provider-scoped catalog design is the best fix for the turn-path stall, but the memo must also reflect the ACP state that controls whether ACPX skills are eligible.

Full review comments:

  • [P1] Include ACP availability in the plugin-skill memo key — src/skills/loading/plugin-skills.ts:58-66
    The memo returns before reevaluating isAcpRuntimeSpawnAvailable, although ACPX skill inclusion depends on it. ACP backend registration and health can change without clearing plugin metadata, so a first refresh can permanently hide newly usable ACPX skills or keep unavailable skills injected; include the availability state in the key (or bypass this memo for ACPX) and add a transition test.
    Confidence: 0.96

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 562129d5df37.

Labels

Label changes:

  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: Repository context identifies this as a maintainer-authored PR; the external-contributor proof gate does not apply, and the supplied live-performance claims were not independently inspectable artifacts.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: ⏳ waiting on author.

Label justifications:

  • P1: The patch can make ACPX agent tools persistently unavailable or incorrectly available during a running gateway.
  • merge-risk: 🚨 auth-provider: Scoped live catalog construction changes the synthetic-auth discovery path used for provider model resolution.
  • merge-risk: 🚨 availability: The new memo freezes a decision derived from mutable ACP backend availability.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: Repository context identifies this as a maintainer-authored PR; the external-contributor proof gate does not apply, and the supplied live-performance claims were not independently inspectable artifacts.

Evidence

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/skills/loading/plugin-skills.test.ts.
  • [P1] git diff --check.

What I checked:

Likely related people:

  • steipete: Current-main blame attributes both replaced turn-path fallbacks to this contributor, who also has substantial history in the prepared catalog and plugin-skill surfaces. (role: recent area contributor; confidence: high; commits: c9d2ad7c42db, 196131d056bd; files: src/agents/command/model-selection.ts, src/cron/isolated-agent/model-selection.ts, src/skills/loading/plugin-skills.ts)
  • civiltox: The merged runtime-only Ollama thinking work is the compatibility behavior preserved by the new scoped-live fallback. (role: prior runtime-model behavior contributor; confidence: medium; commits: f943a94a3303; files: src/agents/agent-command.live-model-switch.test.ts, src/cron/isolated-agent/model-selection.ts)

Rank-up moves

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

  • Make ACP availability part of the skill-directory memo identity and add same-snapshot transition coverage.

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 (1 earlier review cycle)
  • reviewed 2026-08-09T03:45:52.041Z sha 6057be5 :: needs maintainer review before merge. :: none

@steipete
steipete requested a review from a team as a code owner August 9, 2026 04:19
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime cli CLI command changes commands Command implementations labels Aug 9, 2026
@steipete

steipete commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

Addressing the ClawSweeper review (reviewed head 6057be5a; all items below are on the current head):

  • Exact-head CI: head 46a8dca0 completed fully green (87 SUCCESS / 0 failing; the one flaky checks-node-compact-large-6 shard self-recovered on CI retry and passes 5/5 locally in serial isolation). New head e89eec69 adds tests only.
  • Runtime-only provider boundary proof (the P1 "cron test replaces the scoped helper" gap): added two focused suites —
    • src/agents/prepared-model-catalog.scoped-thinking.test.ts: proves the three-tier helper stops at manifest (no scoped build at all) or scoped-static when they resolve, and runs provider-scoped live discovery only for a runtime-only Ollama model — asserting the live tier is invoked with providerDiscoveryProviderIds=["ollama"], i.e. no broad plugin fanout — while preserving reasoning: true for the runtime-only model (fix(agents): preserve thinking for runtime-selected Ollama models #116584 semantics).
    • src/cron/isolated-agent/model-selection.scoped-thinking.test.ts: proves cron selection hydrates a runtime-only model's thinking through the same scoped helper (exact provider/model/owner params) and skips hydration entirely for thinking=off.
    • The existing agent-command.live-model-switch.test.ts Ollama hydration test now asserts the scoped seam end-to-end in the embedded command path.
  • "Stored data model" flag: false positive — the plugin-skills.ts change is a single-slot in-process memo (lifecycle-cleared via registerPluginMetadataProcessMemoLifecycleClear); nothing is persisted, so no migration surface exists.

Measured impact recap (isolated dist gateway, live OpenAI gpt-5.6-luna): first-turn model-selection 58,726ms → 124-508ms; 3,172 jiti-transpiled modules on the turn path → 0; cold first turn 72.7s → ~22s with the remainder being provider prefill of the ~19.5k-token default payload (cacheRead: 0 in usage), which is filed as a named follow-up in the PR body.

First agent turns (embedded and cron) resolved thinking capability through
loadPreparedModelCatalogSnapshot without readOnly, which materialized the
full live model-runtime catalog: ambient synthetic-auth discovery fanned out
to every registered provider and loaded plugin discovery modules through
jiti source transform (3,172 TS modules, 36s event-loop block, +600MB heap,
58.7s model-selection on a cold gateway).

- add loadProviderScopedThinkingCatalog: manifest metadata first, then a
  provider-scoped read-only static catalog, then scoped live discovery only
  for runtime-discovery providers (preserves #116584 Ollama semantics)
- route scopedLiveProviderDiscovery through the scoped read-only loader
- scope live-mode ambient synthetic-auth refs to the requested providers
- bound the last-resort synthetic-auth sweep to discovery entry modules
- memoize per-turn plugin skill dir resolution/republish (single-slot,
  lifecycle-cleared; was a full walk + symlink republish every turn)

Cold first turn 72.7s -> ~22s wall (remaining cost is provider prefill of
the ~19.5k-token default prompt); model-selection 58,726ms -> 124ms.
…catalog seam

Explicit vi.mock factories must export every binding prod touches; the new
loadProviderScopedThinkingCatalog export is now mocked everywhere the module
is stubbed, and the live-model-switch Ollama hydration test asserts the new
provider-scoped seam instead of the retired unscoped snapshot call shape.
…log mock; split synthetic-auth helpers

- add loadProviderScopedThinkingCatalog to all explicit prepared-model-catalog
  and model-catalog.runtime mock factories (vi.mock factories must export every
  binding prod touches)
- move synthetic-auth ref scoping/resolution into
  prepared-model-runtime.synthetic-auth.ts; keeps facts under the max-lines cap
Boundary proof for the ClawSweeper review gap: the three-tier helper stops at
manifest or scoped-static when they resolve, and runs provider-scoped live
discovery (no broad fanout) only for runtime-only models; cron selection
hydrates through the same scoped helper and skips it entirely for thinking=off.
@steipete
steipete force-pushed the claude/openclaw-perf-optimization-089643 branch from b80c1e9 to 59992e5 Compare August 9, 2026 05:17
@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 9, 2026
@steipete
steipete merged commit 7a8eee4 into main Aug 9, 2026
125 checks passed
@steipete
steipete deleted the claude/openclaw-perf-optimization-089643 branch August 9, 2026 05:48
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 10, 2026
…ild (openclaw#120834)

* perf(agents): keep turn-path model catalog reads off the full live build

First agent turns (embedded and cron) resolved thinking capability through
loadPreparedModelCatalogSnapshot without readOnly, which materialized the
full live model-runtime catalog: ambient synthetic-auth discovery fanned out
to every registered provider and loaded plugin discovery modules through
jiti source transform (3,172 TS modules, 36s event-loop block, +600MB heap,
58.7s model-selection on a cold gateway).

- add loadProviderScopedThinkingCatalog: manifest metadata first, then a
  provider-scoped read-only static catalog, then scoped live discovery only
  for runtime-discovery providers (preserves openclaw#116584 Ollama semantics)
- route scopedLiveProviderDiscovery through the scoped read-only loader
- scope live-mode ambient synthetic-auth refs to the requested providers
- bound the last-resort synthetic-auth sweep to discovery entry modules
- memoize per-turn plugin skill dir resolution/republish (single-slot,
  lifecycle-cleared; was a full walk + symlink republish every turn)

Cold first turn 72.7s -> ~22s wall (remaining cost is provider prefill of
the ~19.5k-token default prompt); model-selection 58,726ms -> 124ms.

* test(agents): align model-catalog.runtime mocks with scoped thinking catalog seam

Explicit vi.mock factories must export every binding prod touches; the new
loadProviderScopedThinkingCatalog export is now mocked everywhere the module
is stubbed, and the live-model-switch Ollama hydration test asserts the new
provider-scoped seam instead of the retired unscoped snapshot call shape.

* test(agents): export scoped thinking catalog from every prepared-catalog mock; split synthetic-auth helpers

- add loadProviderScopedThinkingCatalog to all explicit prepared-model-catalog
  and model-catalog.runtime mock factories (vi.mock factories must export every
  binding prod touches)
- move synthetic-auth ref scoping/resolution into
  prepared-model-runtime.synthetic-auth.ts; keeps facts under the max-lines cap

* test(agents): prove scoped thinking hydration for runtime-only models

Boundary proof for the ClawSweeper review gap: the three-tier helper stops at
manifest or scoped-static when they resolve, and runs provider-scoped live
discovery (no broad fanout) only for runtime-only models; cron selection
hydrates through the same scoped helper and skips it entirely for thinking=off.

* test(agents): accept rest args in scoped thinking catalog mocks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling cli CLI command changes commands Command implementations gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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.

1 participant