Repository navigation
Conversation
Greptile SummaryThis PR adds a process-lifetime memoization layer (
Confidence Score: 3/5Not 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 AIThis 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 |
|
Codex review: needs changes before merge. Summary 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 Next step before merge Security Review findings
Review detailsBest 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:
Overall correctness: patch is incorrect Security concerns:
Acceptance criteria:
What I checked:
Likely related people:
Remaining risk / open question:
Codex review notes: model gpt-5.5, reasoning high; reviewed against 90ae151154bf. |
1795a2d to
dcba937
Compare
|
Thanks for digging into the tool-prep cost here. I rechecked current 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 If there is still a separate web-tool factory cost after #78852/current |
perf(tools): memoize media + web tool factories in
createOpenClawToolsSummary
createOpenClawToolsis invoked once per agent turn frompi-embedded-runner/run/attempt.ts. Seven of its built-in tool factoriesre-resolve plugin manifests, provider auth, and capability metadata on every
call:
createImageToolcreateImageGenerateToolcreateVideoGenerateToolcreateMusicGenerateToolcreatePdfToolcreateWebSearchToolcreateWebFetchToolTheir output depends only on stable inputs (config identity,
agentDir,workspaceDir,sandboxRoot, etc.) — not on any session/turn data — socaching the result for the gateway-process lifetime is safe.
This PR adds a tiny
memoizeToolFactoryhelper (~30 LoC) and wraps the sevenfactory call-sites. Cache key:
(label, configRef-id, scalars). Configidentity is tracked via a
WeakMap<OpenClawConfig, number>so when theconfig 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 causeturned out to be these factories spending 3–17 seconds each in
buildMediaUnderstandingManifestMetadataRegistry(cfg)→loadPluginManifestRegistryForPluginRegistry({...}).Even on current
upstream/mainHEAD (b72414c94e), with the recentmetadata-snapshot caching commits (
94591c3cb3,58b4407cda,197c83138e,5a72378b27,9de2bc6ffc, …), each turn still pays ~13 s inthese factory builds because the existing
WeakMap<OpenClawConfig, ...>cache in
media-understanding/defaults.ts:resolveDefaultRegistryonly helpswithin a turn (the tool factories then each kick off a fresh
cfglookupchain through provider auth, capability resolution, and configured-image-
provider lookups).
Measurements
Telegram → openai/gpt-5.5 round trip on the same agent + config + workspace
6d8739fb863ca903cafdad63cf16db0d9915c7f1, ~5 k commits old)upstream/main(b72414c94e, this PR's base)upstream/main+ this PRThe 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/mainHEAD (cache MISS)These are eliminated entirely on the second turn.
Design notes
cfg-id + a small scalars tuple).Anything that varies across calls but should produce the same tool
descriptor (e.g.
agentChannelforcreateImageTool) is not part ofthe key — those values feed into closures captured by the returned tool's
execute()only when the tool actually runs, not at factory time.WeakMapkeying on theOpenClawConfigobject means a config reloadinvalidates the cache for free. No explicit invalidation call needed.
createMessageTool,createNodesTool, etc. are intentionally NOT memoized because they DOcapture 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: