Skip to content

improve: reduce CPU and memory for large tool catalogs - #207900

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-tool-catalog-rewrap-per-run-20260919
Nov 29, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-tool-catalog-rewrap-per-run-20260919

Conversation

@steipete

@steipete steipete commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Code Mode and Tool Search rebuild the execution wrappers for deferred tools while preparing each run's catalog. A run can keep both sets of wrappers live, and the extra work grows with the number of tools.

User Impact

Large tool catalogs use less CPU during preparation and hold less heap while runs are live. Tool calls keep their hook order, admitted caller and cancellation behavior. The synthetic provider requests stayed byte-identical.

Why This Change Was Made

Tool assembly already owns the hook, caller identity and cancellation bindings. Compaction carries the prepared executor forward when its hook context meets the catalog's requirements. It rebuilds tools when a real context override or independently prepared availability view requires one. The embedded attempt supplies one deadline reader to both paths. Catalog registration builds one initial row per executable tool and continues to use the prepared descriptors for the model-facing view.

Production runtime LOC +50/−37 (+13). The added lines preserve the distinct binding and availability cases. Tests +101/−1, benchmark +240, Knip entry +1.

Evidence

A retained-only production sample on 90ab1fad from 17:03 to 17:13 PST on November 28, 2026 recorded 374 MB allocated during the window and still live at the end. About 42 MB was attributed to this catalog build across before-tool-call (15.4 MB), caller context (14.5 MB) and abort (12.5 MB). Individual rebuild sites accounted for 8.0 MB in caller context, 6.9 MB in abort and 6.3 MB in the before-tool-call wrapper. The same sample attributed 6.4 MB and 5.3 MB to schema publication under MCP catalog and provider normalization and 5.7 MB to MCP header rendering. This change reuses the existing prepared schema and prompt paths on eligible catalog hits. The sample measures live allocations within the window.

The synthetic workload compiled 96 tools (64 native and 32 bundle MCP) through the production catalog and provider serializer. It warmed 100 attempts per process and held 600 live attempts for the heap checkpoint. A uses the parent catalog on the same prepared inputs. Five A/A and five A/B pairs ran in independent processes with alternating arm order. These are per-run median / sample p95 values.

Metric Parent Candidate A/B median change A/A median change
Wrapper closures 2,248 1,128 −49.8% —
Catalog CPU (µs) 1,995 / 2,205 696 / 738 -65.1% -2.54%
Catalog wall time (µs) 1,367 / 1,507 462 / 476 -66.2% -0.43%
Heap allocation (bytes) 2,640,044 / 2,645,283 1,627,402 / 1,636,331 -38.4% +0.41%
Live heap after GC (bytes) 817,566 / 821,503 404,701 / 404,704 -50.5% +0.00%
Heap delta after disposal and GC (bytes) 69,029 / 72,927 34,702 / 34,928 -49.7% +0.00%

All samples produced provider request SHA-256 39c0285896b0bc00ff5efd1dc7d690765ce320e27c070088496bb3e2e2d0b80e. This proof exercises the catalog boundary with synthetic executors and no live provider or MCP traffic.

git show 9f63c3c17e48e5:src/agents/tool-search-catalog.ts > /tmp/tool-catalog-parent.ts
node --expose-gc --import ./scripts/tsx.mjs scripts/perf/tool-catalog-rewrap-measure.ts --baseline /tmp/tool-catalog-parent.ts
node --expose-gc --import ./scripts/tsx.mjs scripts/perf/tool-catalog-rewrap-measure.ts
# Add --count to each command for the constructor census.

The focused regression fails on the parent at executor reuse. It passes with the fix and verifies that the two plugin hooks each run once in priority order under the bound caller identity, the tool receives the bound abort signal, a subsequent aborted call is refused, and the catalog declarations and prompt stay byte-identical. 167 focused tests passed across eight files, including prompt-prefix stability and the Code Mode agent loop.

Codex autoreview of the final staged change against 9f63c3c17e48e5 completed with no actionable P0–P2 findings. The benchmark script typecheck passed after correcting the synthetic MCP capability summary. Core lint and the core and test typechecks passed. The Knip production and full-tree scans reproduced the same unused exports on the exact parent. #202209 introduced the now-unused AgentCommandPluginIngressOpts and clearNativeRepositorySourceModulesForTest exports. #207581 removed the last external use of resolveUpdateInstallSurfaceMock.

The auxiliary CI Planner Benchmark validate job failed on an unused upgrade fixture. pnpm deadcode:unused-files on the exact parent reproduced the same failure for scripts/e2e/lib/upgrade-survivor/system-event-account.mjs, added by #207275 (b9ddb611c5dce9). This job is outside the required CI gate. Failed check

Carry the bound hook, caller, and abort closures into Code Mode and Tool Search when compaction has no new execution context. Preserve the rebuild path for actual overrides and availability projections.
@clawsweeper

clawsweeper Bot commented Nov 29, 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.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts agents Agent runtime and tooling size: M labels Nov 29, 2026
@clawsweeper clawsweeper Bot added the P2 Normal backlog priority with limited blast radius. label Nov 29, 2026
@steipete
steipete marked this pull request as ready for review November 29, 2026 02:17
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-29T02:19:13.283083Z b4f7f62 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:feature Preliminary submission classification; full source review pending. 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:feature Preliminary submission classification; full source review pending. labels Nov 29, 2026
@clawsweeper

clawsweeper Bot commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

Codex review: passed.

What this changes

This PR reuses prepared tool executors during catalog compaction when their hook context already matches.

Example: Code Mode prepares a synthetic catalog containing 64 native tools and 32 bundle MCP tools.

  • Before: The reported workload creates 2,248 wrapper closures per run.
  • After: The reported workload creates 1,128 wrapper closures with identical serialized provider requests.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, worthwhile optimization with sound source-level behavior and green required checks; performance evidence is limited to an in-process synthetic workload.
Proof confidence 🦐 gold shrimp (3/6) This PR is exempt from the contributor proof gate; its benchmark exercises production compaction and provider serialization with synthetic executors, providing useful allocation evidence without demonstrating live Gateway or MCP behavior.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Large tool catalogs spend additional CPU and retain duplicate execution wrappers during agent-run preparation.
Reason: The measured workload shows substantial savings from removing redundant work while preserving the existing tool surface and execution contracts.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR addresses measured catalog overhead, and the reviewed changes introduce no actionable correctness or security findings.

Reviewed head: b4f7f625c05f556f5fd1eba35b14bb348c0c1645

Before merge

None.

Findings

None.

Agent review details

How this fits together

Tool assembly binds execution hooks, caller identity, and cancellation; catalog compaction consumes those tools and produces model-facing declarations plus run-local executable entries.

flowchart TD
  A[Tool definitions] --> B[Tool assembly]
  B --> C[Bound executors]
  C --> D[Catalog compaction]
  D --> E[Model declarations]
  D --> F[Run local catalog]
  F --> G[Tool execution]
Loading

Technical review

Best possible solution:

Keep executor ownership in tool assembly and reuse its bindings when equivalent, retaining independent catalog projections where availability or context differs.

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

Current-main source exposes unconditional catalog rewrapping, and the PR supplies a repeatable synthetic benchmark and reported parent-red regression; this review executed no target code.

Is this the best way to solve the issue?

The approach removes redundant construction at the existing owner without adding a cache, public option, or parallel execution path.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Catalog execution-context rebinding keeps the original intent (eb768cb: Preserve execution-owner deadlines for silent nested Code Mode calls that lack the original ambient caller frame.)
  • Catalog metadata reuse keeps the original intent (3d4bd2a: Reuse detached immutable catalog metadata across equivalent runs while keeping executors and lifecycle state run-local.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 3d4bd2a adds src/agents/tool-search-catalog.ts:24 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 3d4bd2a708bc; files: src/agents/tool-search-catalog.ts)
  • Ayaan Zaidi: Raw commit 8eb9596 adds src/agents/tool-search-catalog.ts:661 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 8eb959678b1f; files: src/agents/tool-search-catalog.ts)

PR surface

Source +13, Tests +100, Other +241. Total +354 across 7 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 50 37 +13
Tests 1 101 1 +100
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 241 0 +241
Total 7 392 38 +354

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Production versus regression coverage Runtime +50/−37; tests +101/−1 The small runtime increase preserves distinct binding and availability cases, while one focused regression checks reuse and execution behavior.

Labels

Label changes:

  • 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:

  • 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.

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 November 28, 2026, 9:43 PM ET / November 29, 2026, 02:43 UTC.

@steipete
steipete merged commit c876514 into main Nov 29, 2026
244 of 253 checks passed
@steipete
steipete deleted the steipete/perf-micro-tool-catalog-rewrap-per-run-20260919 branch November 29, 2026 02:52
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Nov 29, 2026
…line

* commit 'c876514dc21154a07f3755320495d2a93584b46b': (538 commits)
  perf(agents): reuse prepared tool catalog executors (#207900)
  fix: show the Gateway command default beside host rules in Devices (#207887)
  fix: verify chat Stop recovery after dashboard pairing (#207888)
  test(activity): check midnight refresh against the elapsed window (#207859)
  test(ui): use one persisted message ID in queued-image handoff (#207861)
  test(agents): release configured MCP fixture resources (#207716)
  fix(workboard): clear CI failures in the session filter editor (#207858)
  perf(ai): reduce allocation in OpenAI Responses streams (#207889)
  chore: stop the Workboard resident-owner CLI test from failing on main (#207898)
  test(agents): isolate endpoint-based overflow classification (#207688)
  chore(doctor): record why the root defaultModel migration stays (#207890)
  refactor(infra): simplify audit recovery write progress (#157141)
  fix: show restart blockers in service logs (#207879)
  test(infra): exercise group identity in session roundtrip (#207671)
  test(infra): exercise live owner expiry policy (#207672)
  feat: let Knowledge learn from your Gmail through Composio (#207266)
  test: stop the history-worker overload test from failing CI on slow runners (#207862)
  test(auth): assert SecretRef plaintext is absent from storage (#207698)
  chore(doctor): hold expired doctor migrations as removal-pending (#207865)
  fix: show ended one-time automations in History (#201280)
  ...
vincentkoc added a commit that referenced this pull request Nov 29, 2026
* commit '2194d14488091e2047d2f87ebbb093212f30840e': (540 commits)
  fix: stop reporting a child worker as finished when the Gateway loses contact (#207713)
  fix: keep the Activity visibility test stable at midnight (#207847)
  perf(agents): reuse prepared tool catalog executors (#207900)
  fix: show the Gateway command default beside host rules in Devices (#207887)
  fix: verify chat Stop recovery after dashboard pairing (#207888)
  test(activity): check midnight refresh against the elapsed window (#207859)
  test(ui): use one persisted message ID in queued-image handoff (#207861)
  test(agents): release configured MCP fixture resources (#207716)
  fix(workboard): clear CI failures in the session filter editor (#207858)
  perf(ai): reduce allocation in OpenAI Responses streams (#207889)
  chore: stop the Workboard resident-owner CLI test from failing on main (#207898)
  test(agents): isolate endpoint-based overflow classification (#207688)
  chore(doctor): record why the root defaultModel migration stays (#207890)
  refactor(infra): simplify audit recovery write progress (#157141)
  fix: show restart blockers in service logs (#207879)
  test(infra): exercise group identity in session roundtrip (#207671)
  test(infra): exercise live owner expiry policy (#207672)
  feat: let Knowledge learn from your Gmail through Composio (#207266)
  test: stop the history-worker overload test from failing CI on slow runners (#207862)
  test(auth): assert SecretRef plaintext is absent from storage (#207698)
  ...
vincentkoc added a commit that referenced this pull request Nov 29, 2026
…seline

* commit '32403124cae2ccbcfc556e844b218682b133956e': (547 commits)
  perf(gateway): skip session display preparation for transcript recall (#207916)
  test(agents): verify complete bracketed paste payload (#207733)
  test: stop timing out the cron recovery settlement test on slow runners (#207920)
  fix: show when worktree cleanup stopped or will retry (#207883)
  fix: show approval destinations only when the forwarding mode uses them (#207885)
  fix: keep inherited tools when changing agent settings (#207884)
  feat: let Knowledge add someone's email or other alias to a page without rewriting it (#207881)
  fix: stop reporting a child worker as finished when the Gateway loses contact (#207713)
  fix: keep the Activity visibility test stable at midnight (#207847)
  perf(agents): reuse prepared tool catalog executors (#207900)
  fix: show the Gateway command default beside host rules in Devices (#207887)
  fix: verify chat Stop recovery after dashboard pairing (#207888)
  test(activity): check midnight refresh against the elapsed window (#207859)
  test(ui): use one persisted message ID in queued-image handoff (#207861)
  test(agents): release configured MCP fixture resources (#207716)
  fix(workboard): clear CI failures in the session filter editor (#207858)
  perf(ai): reduce allocation in OpenAI Responses streams (#207889)
  chore: stop the Workboard resident-owner CLI test from failing on main (#207898)
  test(agents): isolate endpoint-based overflow classification (#207688)
  chore(doctor): record why the root defaultModel migration stays (#207890)
  ...
vincentkoc added a commit that referenced this pull request Nov 29, 2026
…eline

* commit 'eee1e0553d29456424ac367008c3cf080f9866ec': (550 commits)
  fix(acp): deliver bound channel replies to the pending question (#207035)
  fix(cron): keep required reports from going silent when nothing changes (#207044)
  test(sessions): assert participant queue rollback state (#207891)
  perf(gateway): skip session display preparation for transcript recall (#207916)
  test(agents): verify complete bracketed paste payload (#207733)
  test: stop timing out the cron recovery settlement test on slow runners (#207920)
  fix: show when worktree cleanup stopped or will retry (#207883)
  fix: show approval destinations only when the forwarding mode uses them (#207885)
  fix: keep inherited tools when changing agent settings (#207884)
  feat: let Knowledge add someone's email or other alias to a page without rewriting it (#207881)
  fix: stop reporting a child worker as finished when the Gateway loses contact (#207713)
  fix: keep the Activity visibility test stable at midnight (#207847)
  perf(agents): reuse prepared tool catalog executors (#207900)
  fix: show the Gateway command default beside host rules in Devices (#207887)
  fix: verify chat Stop recovery after dashboard pairing (#207888)
  test(activity): check midnight refresh against the elapsed window (#207859)
  test(ui): use one persisted message ID in queued-image handoff (#207861)
  test(agents): release configured MCP fixture resources (#207716)
  fix(workboard): clear CI failures in the session filter editor (#207858)
  perf(ai): reduce allocation in OpenAI Responses streams (#207889)
  ...
vincentkoc added a commit that referenced this pull request Nov 29, 2026
…ions suite

* commit '60e80f1c5fd439f7aa4ce33f54985c7efdc30884': (555 commits)
  refactor: remove the bundled GBrain adapter (#207924)
  improve(ui): show optional run limits beside the automation schedule (#201283)
  test(onboarding): inspect recorded output for credential leaks (#207872)
  perf(exec): reduce host memory sampler allocations (#207927)
  test(mcp-relay): isolate the Connected apps fallback locale (#207923)
  fix(acp): deliver bound channel replies to the pending question (#207035)
  fix(cron): keep required reports from going silent when nothing changes (#207044)
  test(sessions): assert participant queue rollback state (#207891)
  perf(gateway): skip session display preparation for transcript recall (#207916)
  test(agents): verify complete bracketed paste payload (#207733)
  test: stop timing out the cron recovery settlement test on slow runners (#207920)
  fix: show when worktree cleanup stopped or will retry (#207883)
  fix: show approval destinations only when the forwarding mode uses them (#207885)
  fix: keep inherited tools when changing agent settings (#207884)
  feat: let Knowledge add someone's email or other alias to a page without rewriting it (#207881)
  fix: stop reporting a child worker as finished when the Gateway loses contact (#207713)
  fix: keep the Activity visibility test stable at midnight (#207847)
  perf(agents): reuse prepared tool catalog executors (#207900)
  fix: show the Gateway command default beside host rules in Devices (#207887)
  fix: verify chat Stop recovery after dashboard pairing (#207888)
  ...
vincentkoc added a commit that referenced this pull request Nov 29, 2026
* commit 'ba0a7a5fac3e2f1b642d05502273b98dc75adf4f': (556 commits)
  test(agents): fix provider header filtering coverage (#207732)
  refactor: remove the bundled GBrain adapter (#207924)
  improve(ui): show optional run limits beside the automation schedule (#201283)
  test(onboarding): inspect recorded output for credential leaks (#207872)
  perf(exec): reduce host memory sampler allocations (#207927)
  test(mcp-relay): isolate the Connected apps fallback locale (#207923)
  fix(acp): deliver bound channel replies to the pending question (#207035)
  fix(cron): keep required reports from going silent when nothing changes (#207044)
  test(sessions): assert participant queue rollback state (#207891)
  perf(gateway): skip session display preparation for transcript recall (#207916)
  test(agents): verify complete bracketed paste payload (#207733)
  test: stop timing out the cron recovery settlement test on slow runners (#207920)
  fix: show when worktree cleanup stopped or will retry (#207883)
  fix: show approval destinations only when the forwarding mode uses them (#207885)
  fix: keep inherited tools when changing agent settings (#207884)
  feat: let Knowledge add someone's email or other alias to a page without rewriting it (#207881)
  fix: stop reporting a child worker as finished when the Gateway loses contact (#207713)
  fix: keep the Activity visibility test stable at midnight (#207847)
  perf(agents): reuse prepared tool catalog executors (#207900)
  fix: show the Gateway command default beside host rules in Devices (#207887)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 29, 2026
Carry the bound hook, caller, and abort closures into Code Mode and Tool Search when compaction has no new execution context. Preserve the rebuild path for actual overrides and availability projections.

Co-authored-by: Peter Steinberger <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts 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