Skip to content

perf(runtime): reuse optional module loads after first use - #183208

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-main-module-lazy-c-steady-20261025
Oct 25, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-main-module-lazy-c-steady-20261025

Conversation

@steipete

@steipete steipete commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Repeated MCP requests/connections, invalid-config diagnostics, public-session reads and completion streams kept issuing dynamic imports after their implementation modules had loaded. Follow-up to #183017.

User Impact

A small reduction in repeated loader work. Optional features remain lazy, and request behavior is unchanged. This does not change the shell parser or its WASM heap.

Why This Change Was Made

Retain fixed module promises at the existing process-lifetime owners. A small sibling module owns the MCP import group reused by catalog loading, cleanup and error handling; this keeps the existing large runtime below its line-growth ratchet. Request state, credentials, authority decisions, config results and parser instances keep their existing lifetimes.

Production delta: +52 net lines (90 added, 38 removed). The added state holds module promises; it removes repeat loading work without adding a second behavior path. The diagnostic scripts extend the existing heap-rig workflow and provide reproducible feature-level count guards.

Evidence

Synchronized source MCP proof: four A/A controls and five A/B pairs, 200 warm samples per family per side. Mean paired medians: calls 2.433→2.303 ms (−0.130 ms); fresh-session lifecycles 9.207→8.782 ms (−0.424 ms). Mean operation latency: 3.478→3.284 ms and 13.466→12.901 ms respectively. No steady regression observed. A/A median shifts were −5.18% for calls and +2.85% for fresh sessions, so these figures do not establish a precise speedup. The traced validation separately verified warm baseline call/fresh-session imports 2/22 versus candidate 0/0, with no reevaluations.

Final verdict: keep the lazy boundaries and land this explicitly requested repeat-import cleanup. Latency remains inconclusive; no regression has been attributed to the lazy loaders. This is a small loader-work reduction, not a latency speedup or proof of zero cost.

Five concurrent A/B pairs compared the immediate pre-#183017 parent (649734aa02bc) with #183017 plus the reviewed cache changes (2b3d0e8faa53); all nine changed production files match the reviewed build’s source hashes. Two identical-source A/A controls preceded them. Each side used a separate built Gateway, fresh 500-session synthetic state, four clients, a mock provider, Node 26.12.1, synchronized starts, alternating preparation order, and 50 verified turns in a fixed five-minute window. No trace/build/test/lint ran during timings. Values below average per-pair metrics; warm means turns 2–50 (49 samples per side per pair), and median values are not pooled medians.

Metric Baseline → candidate Paired delta
First turn, five first samples per side 3304.2 → 3311.8 ms +7.6 ms (+0.23%)
Warm full-turn median 755.4 → 766.0 ms +10.6 ms (+1.40%)
Warm full-turn mean 1703.74 → 1720.15 ms +16.40 ms (+0.96%)
Warm chat median 490.6 → 490.6 ms 0 ms
Warm chat mean 622.98 → 640.40 ms +17.42 ms (+2.80%)

A/A warm full-turn medians rose 68/65 ms, averaging +66.5 ms (+8.05%); mean cost changed −7.19 ms (−0.36%). A/B full-turn median deltas were −81/+95/−53/+61/+31 ms. However, same-index full-turn median differences were positive in every A/B pair (+9/+20/+18/+6/+5 ms). Subagent warm chat medians also rose in all five pairs, 651.6→695.0 ms (+43.4 ms,+6.66%); subagent full-operation medians averaged +75.4 ms (+6.38%), while A/A subagent chat medians fell. Those subgroup figures use nine samples per side per pair, excluding each kind’s first occurrence; no samples are removed from the full-turn metrics above. The positive mean and subagent patterns remain explicit limitations. They do not meet the standing rejection thresholds, and no offending lazy boundary has been identified for reversion.

A bounded source audit also ruled out a fresh model worker per child on this fixture: CodeMode guest JavaScript calls through the host bridge; sessions_spawn dispatches agent in-process and reaches runEmbeddedAgent on the Gateway host. The worker does not execute these four feature owners. This does not explain the subagent timing increase; scheduling, supporting work and other module evaluation remain outside that audit.

The initial three-minute A/A attempt completed only 45/50 turns on each side and was excluded in full: first 3636→3822 ms, warm median 940.5→924.0 ms, mean 2051.25→2047.34 ms. Before replacement results, the window was extended to five minutes with fresh state/marker paths and the same fixed 50-turn workload. All seven replacement pairs completed with identical lifecycle receipt counts; no maintenance windows or pauses were trimmed.

First-use versus steady feature operations, uncached lazy implementation → cached implementation:

Feature First operation, base → cached (ms) Warm median, base → cached (ms) Warm samples per side
MCP initial catalog / cached catalog 781.560 → 834.314 0.001200 → 0.001125 5 × 200
MCP call 6.767 → 6.192 2.433379 → 2.303150 5 × 200
MCP fresh session lifecycle 11.464 → 9.897 9.206521 → 8.782042 5 × 200
Invalid-config diagnostics 247.219 → 235.478 0.594083 → 0.594708 19
Public-session HTTP GET 5139.529 → 3774.297 1.216916 → 0.897834 19
Completion reasoning parser 55.203 → 52.344 0.223125 → 0.211792 19

These are source-owner feature probes, separate from full Gateway turns. MCP entries average five pairs: first samples are means, warm entries are means of per-pair medians (200 samples per side per family). Only initial catalog preparation is sequential; first call/fresh-session samples are unsynchronized between barriers, and fresh-session operation 1 already has warm modules. Other features have one first sample and 19 warm samples per side, so their differences are descriptive. The tiny +0.625 µs config warm difference does not establish an adverse latency change.

Exact-head CI run 40158735278 passed all 55 jobs on 859ddc028ba9e1aab417d081ed443182a4704d01, including the required CI gate, changed-test shards, types, lint, architecture guards and PostgreSQL conformance.

  • Initial seven-file proof passed 129 tests. After extracting the MCP loader, 64/65 cases passed; one concurrent stdio-catalog fixture settled at 2085 ms before its tools/list receipt, with a 2000 ms connection deadline. The same-order serial replay passed all 65 cases. The original failure is retained; no timeout/assertion changes. Its underlying timing cause is unproven. The module group was already warm, and the connection deadline begins after the import await.
  • Changed-file format and lint passed. Both eager-import/PR-wrapper closure files passed all 22 tests; export-name collision guard passed.
  • Independent subagent review (autoreview route unavailable): all eight production owners and diagnostic tooling reviewed clean. The final formatted production diff matches the reviewed patches semantically.
  • The committed feature probe verifies 20 operations per primary path. Final count guards pass for MCP (60 operations including fresh-session disposal), config, public HTTP (20 GETs plus conditional GET), and completion parsing. Warm imports/evaluations are zero. The six-cache intermediate version failed at the second fresh MCP session with 11 imports; the complete owner cutover passes.

The original mixed Responses/CodeMode workload did not invoke any of these four lazy features: source, completed module census and a separate traced Gateway run agree. Its pooled +38/+56 ms median shifts therefore cannot be described as first-use loading overhead. The completed paired protocol above preserves that workload and separates first-turn, full-operation, chat-only and per-kind results.

A separate built-Gateway shell mix completed ten verified turns, including two actual shell commands. The first shell command's control-command guard initialized web-tree-sitter's 33,554,432-byte heap on main thread 0; the second command reused it. Six parse calls and one initialization were observed. The original CodeMode arithmetic mix never invoked the shell tool. The .javascript heap-retainer key is Node's default ESM cache type, not a JavaScript grammar. This identifies a normal feature trigger, not the exact historical command that initialized a production snapshot.

Feature source-probe timings are contextual. Full Gateway latency remains inconclusive, with the positive mean and subagent patterns disclosed above. No GC, promotion or tail-latency improvement is claimed. No production Gateway was changed or restarted.

@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 gateway Gateway runtime scripts Repository scripts commands Command implementations agents Agent runtime and tooling size: L labels Oct 25, 2026
@steipete
steipete marked this pull request as ready for review October 25, 2026 03:34
@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-25T03:36:55.601541Z 859ddc0 Draft marked ready
ℹ️ 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:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro 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: needs maintainer review before merge.

What this changes

This PR reuses optional-module promises and adds diagnostic probes for repeated imports and Gateway performance.

Example: Create another MCP session after the implementation modules are warm.

  • Before: The reported baseline issues 22 dynamic imports during the fresh-session lifecycle.
  • After: The reported candidate issues zero warm dynamic imports while still connecting, listing tools, and disposing the session.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation is focused and source-consistent, with useful reported feature-level count evidence but an unfinished performance acceptance check.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; reported source probes exercise MCP and public HTTP owners, invalid-config reads, and completion parsing, while the author retains an explicit pause for the unfinished paired Gateway check.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Repeated optional-feature operations perform avoidable loader work after their implementation modules are already loaded.
Reason: The maintainer-authored direction has a concrete work-count improvement and preserves existing behavior without adding a product configuration or public API.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it removes measurable repeated loader work, preserves the existing lazy boundaries, and has no concrete introduced defect identified.

Priority: P2
Reviewed head: 859ddc028ba9e1aab417d081ed443182a4704d01

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The author explicitly leaves the paired built-Gateway performance verdict pending; the unrelated shell run does not exercise these optional-feature changes.
Agent review details

How this fits together

MCP operations, config diagnostics, public-session HTTP requests, and completion streams load optional implementations; the changed owners retain module promises while continuing to create request-specific results and resources.

flowchart TD
  A[Feature operation] --> B[Existing runtime owner]
  B --> C[Retained module promise]
  C --> D[Optional implementation]
  D --> E[Request-specific processing]
  E --> F[Response or cleanup result]
Loading

Technical review

Best possible solution:

Reuse fixed module namespaces at the existing owners while preserving request-specific state, lazy initialization, cancellation, and authorization.

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

Current-main source issues dynamic imports on repeated operations, and the author reports baseline-versus-candidate count probes through the affected production owners; no target code was executed during this review.

Is this the best way to solve the issue?

Retaining fixed module promises is a small owner-local solution, and the MCP extraction reuses the existing lazy-promise utility while keeping mutable clients, results, and parser instances separate.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Optional MCP, config, public-session, and completion implementation loads keeps the original intent (d3ae513: Defer optional implementation graphs until first use while preserving synchronous factories, cancellation, deadlines, and ownership.)
  • Synthetic Gateway workload and turn records keeps the original intent (05ce3c3: Provide repeatable isolated Gateway retention diagnostics with verified workload outcomes.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Pinned production change: The introduced diff retains fixed import promises and moves the existing nine-module MCP import group into one reusable loader; catalog loading, cleanup, and error handling consume it. (src/agents/agent-bundle-mcp-runtime-modules.ts:3, 859ddc028ba9)
  • Current-main behavior remains distinct: Fetched main still performs the MCP import group within catalog loading and imports lifecycle code during disposal, so this PR's central optimization is not already implemented there. (src/agents/agent-bundle-mcp-runtime.ts:316, 1d0d6db70218)
  • Author-recorded evidence and merge pause: The complete live body reports warm MCP import counts falling from 2/22 to 0/0, explicitly limits the timing claims, retains an unexplained concurrent stdio fixture timeout, and says not to merge before the paired Gateway verdict is recorded. (859ddc028ba9)
  • Existing intent preserved: The merged predecessor, perf(gateway): load optional module graphs on first use #183017, deliberately deferred optional implementation graphs while retaining synchronous factories, request deadlines, cancellation, and ownership; this PR retains those boundaries. (src/agents/agent-bundle-mcp-runtime.ts:304, d3ae5134e207)
  • Meaningful feature probes: The committed probe exercises production MCP clients over loopback HTTP, public HTTP serving, invalid-config snapshots, and completion parsing; its warm-operation guard rejects further imports or evaluations. (scripts/perf/lazy-import-feature-probe.mjs:127, 859ddc028ba9)
  • Review policy and checkout: Root and all applicable ancestor AGENTS.md files were read and applied; no maintainer-notes directory exists, and the final status and diff remained clean. (AGENTS.md:1, 859ddc028ba9)

PR surface

Source +52, Docs +43, Other +648. Total +743 across 14 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 9 90 38 +52
Tests 0 0 0 0
Docs 1 43 0 +43
Config 0 0 0 0
Generated 0 0 0 0
Other 4 650 2 +648
Total 14 783 40 +743

Review metrics

Metric Value Why it matters
Runtime production delta +90 / -38 lines; net +52 Growth retains module promises and centralizes the existing MCP import group without introducing a parallel request implementation.
Diagnostic options 4 new heap-rig flags Adds --lazy-import-trace, --turn-count, --gateway-preload, and --shell-turns to source-checkout diagnostics; no persisted product setting is added.

Labels

Label changes:

  • add P2: A focused performance improvement removes repeated loader work across optional runtime paths with limited user-visible impact.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: A focused performance improvement removes repeated loader work across optional runtime paths with limited user-visible impact.
  • 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.

  • Record the paired built-Gateway verdict against the immediate pre-PR baseline before lifting the author's merge pause.

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 24, 2026, 11:51 PM ET / October 25, 2026, 03:51 UTC.

@steipete

Copy link
Copy Markdown
Contributor Author

Follow-up on the historical +43.4 ms (+6.7%) warm subagent parent-chat median increase in all five pairs.

The current-base counterfactual does not reproduce that steady increase. Across five synchronized eager/cached pairs, the mean of the five per-pair warm subagent medians is 683.6→677.6 ms (−6.0 ms, −0.9% relative to that baseline statistic). The corresponding mean latency is 778.2→758.3 ms (−19.9 ms). Each side has nine subsequent subagent operations per pair, 45 total. Every operation still creates a fresh child; “warm” means the Gateway process has already run one subagent operation, not reuse of a child session.

Pair First subagent chat, ms (one each) Subsequent subagent median, ms (nine each)
1 663→605 438→464
2 689→659 477→448
3 2113→2170 1273→1331
4 554→740 652→597
5 911→816 578→548

Two matched A/A controls had median deltas −19/−211 ms and mean deltas +7.2/+8.1 ms. All pairs completed 50 verified mixed turns per side in fixed five-minute windows; no pauses or samples were removed. These are local isolated-dev measurements on a shared Mac, without CPU affinity; no tail-percentile or production speedup claim is made.

All three variants use common base 5d204234f2d209b996da7337de5becf53ea37ca4, Node 26.12.1, the same dependencies and harness. Eager reverses only #183208 and #183017 production patches; lazy-only reverses #183208; cached retains both. Both merged fixes are ancestors of this common base. This avoids the unrelated changes between the two merge commits.

Separate instrumented eager/cached, eager/lazy and lazy/cached contrasts traced parent and child preparation, model starts, schema construction, first/repeated imports and CodeMode worker assignments. Subsequent subagent medians changed −4/+6/−6 ms respectively (nine per side). No fresh child repeated the MCP, config-diagnostic, public-session or completion-parser imports/evaluation. Those features are inactive in this Responses/CodeMode mix; the earlier feature-specific probes remain the first-use coverage. Each warm parent and child finalized tools once, normalized five schemas, and published six. One CodeMode pool was reused; synthetic children return text rather than executing their own CodeMode tools.

Two further diagnostic pairs used 10,000 synthetic sessions, including 2,000 archived sessions and 8,000 settled retained runs, 40 synthetic startup plugins, and 64 MiB logical transcript text. Inventory and actual nonempty history responses were checked. Their warm subagent median deltas were −35/+11 ms, with mean deltas −57.4/−18.0 ms. Parent terminal completeTurn dispatch means were 14.3→9.6 and 25.4→20.9 ms, with one committed command per warm parent. Final-command admission waits averaged 0→0 and 0→0.11 ms. Diagnostic timings are separate from the uninstrumented latency result.

The final narrow probe names the repeating completion owner: deferred trajectory persistence, through flushEmbeddedAttemptTrajectoryRecorder → appendSqliteTrajectoryRuntimeEventsInWorker in src/trajectory/runtime-store-writer.ts. All 18 warm parent reservations (nine per side) had exact enclosing trajectory-flush ancestry; no reservation was left unattributed. Each parent performed one flush, one append, one terminal-write drain and one fallback settlement.

Warm parent completion phase Eager mean ms Cached mean ms
Deferred trajectory flush, including its append 24.805 24.424
Terminal-write drainage 5.963 6.201
Fallback settlement 2.539 2.531
Other gaps before reply.run_agent_turn settles 2.712 2.780
Whole post-embedded/pre-accounting interval 36.020 35.936

The append nested inside that flush averaged 20.639→20.882 ms; it is not added again to the table. Native admission wait was 3.778→3.222 ms, and admitted execution 20.667→20.889 ms. These are elapsed waits, not pure SQLite CPU. Final accounting afterward averaged 11.009→12.464 ms. The matching functions and persistence contract are unchanged by the two lazy PRs.

The same probe measured first/subsequent parent start→model at 190.956/156.039→204.345/145.379 ms and child start→model at 473.800/247.825→386.097/248.526 ms (one first and nine subsequent observations per side). The first trajectory flush was 16.896→49.410 ms, while subsequent flushes averaged 24.805→24.424 ms; neither loaded a deferred feature. Parent and child identities are tracked independently, and deferred work after a retired owner is reported separately without removing any turn samples.

Verdict for the tested current base: keep #183017/#183208. There is no demonstrated repeated lazy-boundary cost to cache again, prewarm, or revert. The observed residual completion cost belongs to trajectory persistence and terminal write settlement; this follow-up makes no production change.

The original +43.4 ms observation remains disclosed. Its artifacts did not record these phases, and intervening session/transcript changes separate that historical build from this common base. Current results do not retroactively identify its cause or justify calling it noise. No lazy boundary has been shown to cause a persistent regression on the tested current base.

Validation: all three builds succeeded with the same six existing UI ineffective-dynamic-import warnings, none on these boundaries; changed-file format/lint and 28 focused closure/harness tests passed. The diagnostic instrumentation and analyzers received independent subagent review (autoreview route unavailable). No production code changed in this follow-up (production LOC delta 0).

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 26, 2026
…183208)

* perf(runtime): reuse optional module loads after first use

* test(perf): synchronize warm lazy-module 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 commands Command implementations gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: L 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