Skip to content

perf(tools): memoize media + web tool factories in createOpenClawTools - #73039

Closed
lironsher wants to merge 6 commits into
openclaw:mainfrom
lironsher:perf/memoize-tool-factories
Closed

lironsher wants to merge 6 commits into
openclaw:mainfrom
lironsher:perf/memoize-tool-factories

Conversation

@lironsher

Copy link
Copy Markdown

perf(tools): memoize media + web tool factories in createOpenClawTools

Summary

createOpenClawTools is invoked once per agent turn from
pi-embedded-runner/run/attempt.ts. Seven of its built-in tool factories
re-resolve plugin manifests, provider auth, and capability metadata on every
call:

  • createImageTool
  • createImageGenerateTool
  • createVideoGenerateTool
  • createMusicGenerateTool
  • createPdfTool
  • createWebSearchTool
  • createWebFetchTool

Their output depends only on stable inputs (config identity, agentDir,
workspaceDir, sandboxRoot, etc.) — not on any session/turn data — so
caching the result for the gateway-process lifetime is safe.

This PR adds a tiny memoizeToolFactory helper (~30 LoC) and wraps the seven
factory call-sites. Cache key: (label, configRef-id, scalars). Config
identity is tracked via a WeakMap<OpenClawConfig, number> so when the
config object is replaced (config reload), the cache is naturally invalidated
without leaking memory.

Motivation

I was debugging a 3-minute-per-turn latency regression on a fork rebased onto
main. After bisecting through dist/ with timing markers, the root cause
turned out to be these factories spending 3–17 seconds each in
buildMediaUnderstandingManifestMetadataRegistry(cfg) →
loadPluginManifestRegistryForPluginRegistry({...}).

Even on current upstream/main HEAD (b72414c94e), with the recent
metadata-snapshot caching commits (94591c3cb3, 58b4407cda,
197c83138e, 5a72378b27, 9de2bc6ffc, …), each turn still pays ~13 s in
these factory builds because the existing WeakMap<OpenClawConfig, ...>
cache in media-understanding/defaults.ts:resolveDefaultRegistry only helps
within a turn (the tool factories then each kick off a fresh cfg lookup
chain through provider auth, capability resolution, and configured-image-
provider lookups).

Measurements

Telegram → openai/gpt-5.5 round trip on the same agent + config + workspace

  • plugins, only the openclaw build varies:
Build Cold turn Warm turn
6d8739fb863ca903cafdad63cf16db0d9915c7f1, ~5 k commits old) 11 s 5 s
upstream/main (b72414c94e, this PR's base) 27 s 18 s
upstream/main + this PR 23 s 7.6 s

The warm turn matches v2base (5–11 s window). The cold-turn delta vs v2base
is fine — it pays for the manifest scan once and amortizes for the rest of
the gateway lifetime.

Per-factory cost on upstream/main HEAD (cache MISS)

[memoize-MISS] createImageTool          2730 ms
[memoize-MISS] createImageGenerateTool  1394 ms
[memoize-MISS] createVideoGenerateTool  1413 ms
[memoize-MISS] createMusicGenerateTool  1143 ms
[memoize-MISS] createPdfTool            4377 ms
[memoize-MISS] createWebSearchTool      1135 ms
                                       ── total
                                       12.2 s

These are eliminated entirely on the second turn.

Design notes

  • Cache keying is intentionally minimal (cfg-id + a small scalars tuple).
    Anything that varies across calls but should produce the same tool
    descriptor (e.g. agentChannel for createImageTool) is not part of
    the key — those values feed into closures captured by the returned tool's
    execute() only when the tool actually runs, not at factory time.
  • WeakMap keying on the OpenClawConfig object means a config reload
    invalidates the cache for free. No explicit invalidation call needed.
  • The seven targeted factories are session-agnostic. createMessageTool,
    createNodesTool, etc. are intentionally NOT memoized because they DO
    capture session-specific values at factory time.

Risk

Low. The change is additive (new helper + call-site wraps). All inputs to
each factory that affect output are part of the cache key. Existing tests
exercise the factories' behavior; cache-related tests can be added if
desired, but I'd argue the helper is small enough not to need them.

How to verify

In a real telegram-driven flow on a config with the standard
provider/plugin set:

1. Restart gateway.
2. Send message #1, observe `[memoize-MISS]` lines (one per factory).
3. Send message #2, observe ZERO `[memoize-MISS]` lines.
4. Total turn time on message #2 should drop from ~18 s to ~7 s.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Apr 27, 2026
@greptile-apps

greptile-apps Bot commented Apr 27, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds a process-lifetime memoization layer (memoizeToolFactory) for seven costly tool factories inside createOpenClawTools, targeting a ~10 s per-turn latency regression. The WeakMap-based config-id strategy and overall structure are sound, but there is one correctness issue with the cache key design for the web tools.

  • runtimeWebTools missing from web-tool cache keys (P1): getActiveRuntimeWebToolsMetadata() is backed by a mutable module-level variable that can be updated at any time via setActiveRuntimeWebToolsMetadata. createWebSearchTool consumes runtimeWebSearch at factory time to compute preferRuntimeProviders and resolve the tool's description/parameters — not only inside execute(). If the active runtime provider changes after the first turn, subsequent turns receive a stale cached tool with the wrong descriptor and wrong provider selection.
  • factoryCache is never pruned (P2): Old string-keyed entries in the module-level Map outlive their associated config objects because WeakMap GC does not propagate to plain Map string keys.

Confidence Score: 3/5

Not safe to merge as-is: the web tool cache keys omit runtimeWebTools, causing stale tool descriptors when the active runtime web provider changes.

A P1 correctness bug in the cache key for createWebSearchTool and createWebFetchTool means users could silently receive a tool built with a stale runtime provider after the active provider changes. This is not a theoretical edge case — setActiveRuntimeWebToolsMetadata is a live API used in the gateway.

src/agents/openclaw-tools.ts — the cache-key arrays for createWebSearchTool and createWebFetchTool need a runtime-provider identity fingerprint added. src/agents/tools/memoize-tool-factory.ts — factoryCache needs a pruning strategy for config reload scenarios.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/openclaw-tools.ts
Line: 244-257

Comment:
**`runtimeWebTools` excluded from cache key causes stale tool descriptors**

`getActiveRuntimeWebToolsMetadata()` is a mutable module-level variable — `setActiveRuntimeWebToolsMetadata` / `clearActiveRuntimeWebToolsMetadata` can be called at any time. In `createWebSearchTool`, `runtimeWebSearch` is used at factory time to compute `preferRuntimeProviders`, which determines the resolved `description` and `parameters` baked into the returned tool object (not just inside `execute()`). If the active runtime web search/fetch provider changes after the first turn, subsequent turns receive a cached tool built with the stale provider selection and stale tool descriptor.

The same applies to `createWebFetchTool` at the analogous call-site below. The fix is to include a stable identity for `runtimeWebTools` in the scalars key — even a simple fingerprint like `runtimeWebTools?.search?.selectedProvider ?? null` would capture provider identity changes.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/agents/tools/memoize-tool-factory.ts
Line: 35

Comment:
**`factoryCache` accumulates stale entries across config reloads**

When an `OpenClawConfig` object is garbage collected, its entry in `cfgIds` (`WeakMap`) is pruned as expected. However, the corresponding string-keyed entries in `factoryCache` (a plain `Map`) are never removed — the GC of the config object does not propagate to `factoryCache` keys like `"createImageTool|1|[...]"`. Each config reload creates 7 new entries while the previous 7 linger for the process lifetime.

For long-running gateways that reload config many times, this is unbounded growth. A separate per-config `Map` nested inside the `WeakMap` would let GC collect the inner map with the config.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "perf(tools): memoize media + web tool fa..." | Re-trigger Greptile

Comment thread src/agents/openclaw-tools.ts Resolved
@clawsweeper

clawsweeper Bot commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

Summary
The PR adds a memoizeToolFactory helper and wraps media, PDF, web_search, and web_fetch construction inside createOpenClawTools.

Reproducibility: yes. for the patch regressions: PR-head source shows cached media/PDF factories bypass current planning, and cached web tools omit lateBindRuntimeConfig. I did not rerun the original latency benchmark in this read-only review.

Real behavior proof
Sufficient (live_output): The PR body includes live Telegram-to-OpenAI timing measurements and copied per-factory timing output showing warm-turn improvement, though a repaired branch should refresh this proof after rebase.

Next step before merge
The remaining blockers are concrete, file-local correctness and policy regressions that an automated repair can attempt on the maintainer-modifiable PR branch or a narrow replacement branch.

Security
Needs attention: The patch can turn web_fetch into a stale network-policy surface unless execute-time runtime binding is preserved.

Review findings

  • [P2] Preserve optional-media factory planning — src/agents/openclaw-tools.ts:145-253
  • [P2] Pass late runtime binding through cached web tools — src/agents/openclaw-tools.ts:255-276
Review details

Best possible solution:

Rebase the memoization onto current main, wrap it around the existing planning and late-bound runtime contracts, add regression coverage for those contracts, and refresh real timing proof.

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

Yes for the patch regressions: PR-head source shows cached media/PDF factories bypass current planning, and cached web tools omit lateBindRuntimeConfig. I did not rerun the original latency benchmark in this read-only review.

Is this the best way to solve the issue?

No, not in the current branch shape. Factory memoization may be the right fix, but it must preserve current optional-media gating, auth/runtime inputs, and execute-time web runtime binding.

Full review comments:

  • [P2] Preserve optional-media factory planning — src/agents/openclaw-tools.ts:145-253
    The cached media/PDF factories are direct calls and do not run current main's optional-media plan before construction. That plan applies allow/deny policy, plugins.enabled, authProfileStore, availabilityConfig, and deferred model-resolution behavior, so this stale block can expose unavailable or denied tools and reintroduce expensive registration-time resolution.
    Confidence: 0.92
  • [P2] Pass late runtime binding through cached web tools — src/agents/openclaw-tools.ts:255-276
    The cached web_search and web_fetch factories capture runtimeWebTools but omit lateBindRuntimeConfig: true. The execute path only rereads active runtime metadata and active secrets config when that flag is set, so later provider, disablement, proxy, or fetch-policy changes can be ignored.
    Confidence: 0.91

Overall correctness: patch is incorrect
Overall confidence: 0.91

Security concerns:

  • [medium] Preserve web_fetch runtime policy binding — src/agents/openclaw-tools.ts:271
    PR head constructs cached web_fetch without lateBindRuntimeConfig, so execution can use captured fetch config/runtime metadata after provider, proxy, disablement, or fetch-policy changes.
    Confidence: 0.84

Acceptance criteria:

  • node scripts/run-vitest.mjs src/agents/tools/memoize-tool-factory.test.ts src/agents/openclaw-tools.media-factory-plan.test.ts src/agents/openclaw-tools.image-generation.test.ts src/agents/openclaw-tools.video-generation.test.ts src/agents/openclaw-tools.pdf-registration.test.ts src/agents/tools/web-search.late-bind.test.ts src/agents/tools/web-tool-runtime-context.test.ts src/agents/tools/web-fetch.provider-fallback.test.ts
  • git diff --check
  • node scripts/crabbox-wrapper.mjs run --shell -- "pnpm check:changed"
  • Capture redacted before/after core-plugin-tools or openclaw-tools prep timings from a real or Testbox embedded run after the repair.

What I checked:

  • Live PR state: The PR is open, external-authored, maintainer-modifiable, and currently CONFLICTING/DIRTY with current main; changed files are src/agents/openclaw-tools.ts and the new memoize-tool-factory helper/test. (6312a19ca7e5)
  • PR head media behavior: PR head memoizes direct createImageTool/createImageGenerateTool/createVideoGenerateTool/createMusicGenerateTool/createPdfTool calls without current main's optional-media planning gate, authProfileStore, availabilityConfig, or deferred auto-model resolution flags. (src/agents/openclaw-tools.ts:145, 6312a19ca7e5)
  • Current main media contract: Current main computes availabilityConfig, resolves optional media tool planning with auth and allow/deny policy, and only constructs media/PDF factories when the plan permits them. (src/agents/openclaw-tools.ts:196, 90ae151154bf)
  • Current main planner contract: The optional-media planner gates image/video/music/PDF factories on plugins.enabled, allow/deny policy, metadata capability availability, configured model signals, and auth facts. (src/agents/openclaw-tools.media-factory-plan.ts:164, 90ae151154bf)
  • PR head web behavior: PR head wraps web_search and web_fetch in the cache while passing captured runtime metadata but not lateBindRuntimeConfig: true. (src/agents/openclaw-tools.ts:255, 6312a19ca7e5)
  • Current main web runtime contract: Current main passes lateBindRuntimeConfig to both web tools, and the runtime context helper only rereads active runtime metadata and active secrets runtime config when that flag is true. (src/agents/tools/web-tool-runtime-context.ts:60, 90ae151154bf)

Likely related people:

  • vincentkoc: Recent current-main history includes web runtime/provider binding and the latest blame boundary on the relevant createOpenClawTools and web runtime files. (role: recent area contributor; confidence: high; commits: 0668f1e003ed, fbf9132b32da, 7d96d1f41adb; files: src/agents/openclaw-tools.ts, src/agents/tools/web-tool-runtime-context.ts, src/agents/tools/web-fetch.ts)
  • steipete: Recent commits added and refined optional-media policy planning and adjacent createOpenClawTools behavior that this PR must preserve. (role: recent area contributor; confidence: high; commits: 9340105bb570, 36f8a8603d95, fb9030ff67c6; files: src/agents/openclaw-tools.ts, src/agents/openclaw-tools.media-factory-plan.ts, src/agents/tools/web-tool-runtime-context.ts)
  • hclsys: Authored the merged PDF model-resolution deferral work on the same PDF/createOpenClawTools latency surface. (role: related hot-path contributor; confidence: high; commits: 02b1075a57a8; files: src/agents/openclaw-tools.ts, src/agents/tools/pdf-tool.ts, src/agents/tools/pdf-tool.test.ts)
  • dorukardahan: Authored the optional media/PDF denylist mitigation that is now part of the factory-planning contract this PR must preserve. (role: adjacent latency-fix contributor; confidence: medium; commits: 0739cb19b72b, fb9030ff67c6; files: src/agents/openclaw-tools.ts, src/agents/openclaw-tools.media-factory-plan.test.ts)
  • jesse-merhi: Authored recent Proxyline managed proxy routing work that touched the same current-main createOpenClawTools and web/runtime policy surface. (role: adjacent runtime contributor; confidence: medium; commits: 6921d9072e91; files: src/agents/openclaw-tools.ts, src/agents/tools/web-tool-runtime-context.ts)

Remaining risk / open question:

  • The branch is conflicting against main, so the current diff cannot be merged or fully validated without a rebase or replacement branch.
  • The timing proof in the PR body predates later optional-media planning and web runtime changes, so a repaired branch should refresh redacted before/after timing output.
  • Merging the current web_fetch wrapper without late runtime binding can preserve stale provider, proxy, disablement, or fetch-policy state.

Codex review notes: model gpt-5.5, reasoning high; reviewed against 90ae151154bf.

@lironsher
lironsher force-pushed the perf/memoize-tool-factories branch from 1795a2d to dcba937 Compare April 28, 2026 07:31
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 12, 2026
@openclaw-barnacle openclaw-barnacle Bot added triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. labels May 12, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 14, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 14, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 14, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 14, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 14, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 14, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 14, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 14, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 14, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 15, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 15, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 15, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 15, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 15, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 15, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 15, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 15, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 15, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 15, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 15, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 15, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 16, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 16, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 16, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 16, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 16, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 16, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 16, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 16, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 16, 2026
@shakkernerd

Copy link
Copy Markdown
Contributor

Thanks for digging into the tool-prep cost here.

I rechecked current main at c93d6d8daa37 with an OCM clone of CodexClaw upgraded to a packaged current-main runtime. The relevant current branch to carry forward is #78852, which keeps the useful lesson from this PR but narrows it to passing resolved media tool availability through the tool plan instead of memoizing whole tool factories.

I’m closing this PR because the broad factory memoization is too easy to make stale: the cache key has to account for mutable runtime tool metadata, auth/provider availability, sandbox/FS policy, workspace, delivery context, and config state. #78852 is the safer shape for the media-tool part of the same problem, and this branch is now dirty against current main.

If there is still a separate web-tool factory cost after #78852/current main, please open a focused PR with current-main timing and a cache key that includes the runtime metadata that can change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling proof: sufficient ClawSweeper judged the real behavior proof convincing. size: L triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants