Skip to content

fix: reuse compacted tool catalogs between agent runs - #199804

Merged
steipete merged 3 commits into
mainfrom
steipete/perf-micro-tool-catalog-reuse-20260919
Nov 15, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/perf-micro-tool-catalog-reuse-20260919

Conversation

@steipete

@steipete steipete commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes repeated tool-catalog compaction when Code Mode starts another run, session, subagent, or retry with the same effective tool definitions.

User Impact

Agent runs reuse identical catalog text and immutable metadata while keeping tool execution bound to the current run. No configuration or schema migration is required. This reduces catalog preparation CPU and allocation; it does not establish that catalog builds caused the reported production heap growth.

Why This Change Was Made

The old reuse boundary was a run-local catalog reference, and execution/prompt preparation followed fresh entries-array identities. The new owner keys detached metadata by ordered, finalized descriptors and schema fingerprints, sharing bindings, prompts and worker metadata across runs. Executable tools and lifecycle state remain run-local. Raw and published copies of the same native schema have the same key; opaque client schemas stay with the live describe/call path. MCP publication preserves schemas that cannot be published losslessly.

The shared owner is bounded to 32 catalogs, 1 Mi-character input per catalog and 4 Mi-character aggregate inputs, with bounded prompt variants. It replaces duplicate per-run preparation; the net +167 production lines supply the previously missing cross-run lifetime and bounds (282 added, 115 removed). Related: #199346 separately makes MCP output-validator compilation lazy; this change preserves its validation boundary.

Evidence

Production motivation supplied by the TS peer: Team r336, 2026-11-15, 19:57–21:30Z recorded 176 builtin Code Mode catalog reuse misses against 77 webchat turns (~2.3×). The turn denominator excludes subagents, cron and recovery/retry attempts, so this is an upper bound per run. Windows with 27–29 builds coincided with +73–91 MB after-GC floor steps; quiet windows with 5–9 builds ranged from −36 to +7 MB. This is correlation, not a demonstrated leak. No Team data was copied and no Team runtime was changed.

  • Five paired synthetic owner samples, 109 tools and 1,000 measured warm attempts: builds 1,000→0; median CPU 911.256→336.343 ms; allocation 1,549,322,752→500,435,056 bytes. Unchanged A/A variation was 2.7% wall time and 0.03% allocation. Cold construction was 5.338→5.706 ms; these are owner measurements, not user latency claims.
  • Prompt bytes remain identical (8,096 bytes; SHA-256 a4d4aa4417a8964a62754143ac1b90ea4bfd29b00b7cc1fa95027d86de99d32d). Prefix and affected consumer tests pass. Native/MCP/client regressions execute through the real headless bridge with current-run results. The original three cross-run regressions fail the intended reuse assertion on exact parent 913e6ea294413887fc9bb71a70a5e24a53936fbf.
  • After 10,000 stable-input turns: one retained descriptor catalog and zero executable entries/tools/run payloads. After 1,000 distinct versions: exactly 32 descriptor catalogs and zero executable survivors. The baseline also releases executors; this repair removes repeated work rather than claiming to fix an established executable-state leak.
  • Actual source Gateway dispatch with a deterministic loopback model completed on a synthetic btrfs fixture: 35.20 GiB agent database, 5,000 sessions, 200,640 transcript messages and 62,000 project-worktree files (~1.1 GB). Seven requested-path attempts built seven catalogs on the baseline and three with reuse: initial interactive, smaller subagent tool set, and cron-specific descriptors. Both fallback attempts reused the interactive catalog. A separately counted recovered child-completion turn rebuilt on the baseline. All cron runs completed successfully. Final A/A baseline owner spans were 25.681–29.165 ms wall / 108.800–118.107 ms process CPU / 8.64–8.99 MB sampled allocation. Candidate spans were 22.196–24.478 ms / 51.582–76.735 ms / 6.99–7.03 MB, including two additional completion-notification attempts that both reused metadata (nine observed attempts, three builds). Allocation per observed attempt was 1.23–1.28→0.777–0.781 MB. Baseline A/A allocation spread was 4.0%; candidate 0.6%. Concurrent worker CPU and differing completion counts limit full-Gateway speedup inference; there is no live-provider claim.
  • Codex local autoreview and focused checks are recorded with the final candidate. pnpm check:changed found unrelated unused exports, reproduced on the exact parent and introduced by ef930ebbad771ae219e033f8c5b59a12b5445ffb (state copy/swap upgrade) and cec47fd13f23df46069da1beb65ceaec6e66d04f / feat(openclaw-id): name invited members from their email and ask who they are on first visit #198491 (member welcome). These are existing main regressions, not ignored noise. Exact-head CI remains required.

CI on the first head exposed an old metadata test equating shared preparation with execution-session identity; the updated test preserves policy-driven lifetime replacement independently. It also exposed an inherited immediate-reply fixture regression from #199434 (37d977fd28b0): the exact parent fails, and substituting that owner’s preceding version passes all 20 parity tests. The fixture now completes asynchronous first-call middleware discovery before asserting immediate replies, retaining the existing single-execution, memory, call-count and cleanup assertions. Both affected files pass locally (36 tests), with type/lint/format checks and fresh Codex review. ClawSweeper reviewed final head 9244bf780b745318caef052e9685227e80f02e72 with zero findings and zero open checklist items. Exact-head CI remains required before landing.

The measurement model now scopes markers to each sample so pending completion notifications from a reused synthetic fixture cannot replay old spawn commands. This final follow-up affects only the measurement script; it passed script type/lint/format checks and Codex autoreview. Earlier diagnostic-heavy profiles and replay-contaminated samples are excluded from the final timing comparison.

Share bounded immutable catalog metadata by finalized descriptors and schema fingerprints while retaining current-run executors and cleanup. Preserve identical prompt bytes and full MCP output validation. Add cross-session bridge regressions and synthetic allocation, retention and Gateway workloads.
@clawsweeper

clawsweeper Bot commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation scripts Repository scripts agents Agent runtime and tooling size: XL labels Nov 15, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper review

Please review the final catalog ownership, canonical key, cache bounds, prompt byte stability, MCP validation, and current-run executor lifetime at 8c90e06c53c1c64041fef0af4a37f05a2dfa59f2. Local Codex autoreview is clean. Full-scale synthetic validation is continuing; the PR remains draft until that evidence is complete.

@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 15, 2026
@steipete
steipete marked this pull request as ready for review November 15, 2026 22:46
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 15, 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-15T23:22:09.923194Z 9244bf7 New commits
ℹ️ 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 commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR shares detached tool-catalog metadata and rendered prompts across runs with equivalent finalized tool definitions.

Example: Two agent sessions use the same 109 tool definitions.

  • Before: Each session rebuilds catalog projections and prompt text.
  • After: The second session reuses prepared metadata while tool calls execute through its own current-run bindings.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is coherent and supported by focused production-path regressions; performance evidence remains synthetic and the reported Gateway results have no attached diagnostic trace.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored performance change preserves user-facing behavior; supplied evidence covers synthetic production-owner measurements and reported loopback Gateway dispatch, with no live-provider or production-leak claim.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Repeated agent runs spend CPU and allocate memory preparing equivalent tool catalogs.
Reason: The maintainer-authored direction has measured owner-level gains, bounded retained metadata, and no new configuration or persisted-data contract.

Merge readiness

✅ Ready for maintainer review

This PR provides a useful, bounded performance improvement that current main lacks; no actionable correctness or security defect was found in the reviewed head.

Priority: P2
Reviewed head: 9244bf780b745318caef052e9685227e80f02e72

Before merge

None.

Findings

None.

Agent review details

How this fits together

Agent preparation supplies policy-filtered tool definitions to the catalog owner, which produces discovery prompts and Code Mode metadata while retaining executable bindings in the current run.

flowchart TD
  A[Finalized tool definitions] --> B[Run catalog]
  B --> C[Bounded descriptor cache]
  C --> D[Discovery prompts]
  C --> E[Code Mode projections]
  E --> F[Current run bridge]
  B --> F
  F --> G[Current tool executor]
Loading

Technical review

Best possible solution:

Keep one bounded owner for detached catalog projections while preserving current-run execution, policy, and cleanup.

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

Current-main source shows fresh run catalog identities bypassing the existing preparation caches; the PR supplies comparative synthetic measurements, but this read-only review executed no target code.

Is this the best way to solve the issue?

The change addresses the repeated projection work at its owner, removes superseded preparation paths, and justifies the bounded cache with measured reuse rather than claiming to fix the unproven heap-growth cause.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Current main retains the repeated preparation boundary: Current main keys prepared Code Mode metadata by a run's entries-array identity; its catalog registration has no equivalent content-keyed cross-run descriptor owner. (src/agents/code-mode-execution.ts:73, 7de99f0419bb)
  • Detached metadata and bounded retention: The new owner includes ordered descriptor fields and schema fingerprints in its key, omits client schemas from shared projections, excludes unpublished remote schemas from cross-run sharing, and enforces catalog-count and input-character limits. (src/agents/tool-search-prepared-catalog.ts:24, 9244bf780b74)
  • Execution remains run-local: Registration stores fresh executable entries; ToolSearchRuntime resolves calls through the current catalog, and the shared namespace runtime receives its executor at invocation. (src/agents/tool-search-runtime.ts:383, 9244bf780b74)
  • Latest follow-up is confined to measurement markers: The latest commit introduces one campaign-specific marker prefix and uses it consistently for request matching, interactive messages, child tasks, and cron messages; production files are unchanged from the preceding reviewed head. (scripts/perf/tool-catalog-gateway-measure.ts:193, 9244bf780b74)
  • Earlier cache removal had a different cost boundary: refactor(agents): release tool catalogs with their runs #135321 removed session-keyed snapshots that retained descriptors while saving only ordering and deduplication; this PR explains its different content-keyed lifetime and measures reuse of rendered projections. (src/agents/tool-search-catalog.ts:347, 3a04cac872d0)
  • Synthetic performance and regression evidence: The public body reports paired owner measurements, stable prompt bytes, executor-retention checks, baseline-failing cross-run regressions, and source Gateway dispatch with a deterministic loopback model. The inspected prepared images concern unrelated onboarding and supply no catalog evidence. (scripts/perf/tool-catalog-reuse-measure.ts:110, 9244bf780b74)

Likely related people:

  • Josh Lehman: Raw commit ac10e03 adds src/agents/tool-search-directory.ts:534 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ac10e03c407e; files: src/agents/tool-search-directory.ts)

PR surface

Source +167, Tests +158, Docs +15, Other +746. Total +1086 across 18 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 10 282 115 +167
Tests 5 165 7 +158
Docs 1 15 0 +15
Config 0 0 0 0
Generated 0 0 0 0
Other 2 746 0 +746
Total 18 1208 122 +1086

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
Runtime versus regression coverage Runtime +282/-115 lines; tests +165/-7 lines The production growth supplies detached cross-run lifetime, content identity, and bounds while removing the former preparation paths; tests cover current-run execution and schema separation.

Labels

Label changes:

  • add P2: Repeated agent preparation has measured CPU and allocation costs, without evidence of an urgent availability failure or established memory leak.
  • 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: Repeated agent preparation has measured CPU and allocation costs, without evidence of an urgent availability failure or established memory leak.
  • 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.

History

Review history (2 earlier review cycles)
  • reviewed 2026-11-15T22:52:53.422Z sha 8c90e06 :: needs maintainer review before merge. :: none
  • reviewed 2026-11-15T23:15:01.955Z sha 2cb6278 :: needs maintainer review before merge. :: none

Reviewed November 15, 2026, 6:25 PM ET / 23:25 UTC (Revision 3).

Keep policy-driven run lifetime replacement independent of detached metadata reuse. Establish ready middleware replies before the immediate-reply parity assertion; the previous cold fixture fails on the exact base after #199434. Select the populated synthetic workspace and require successful cron completion in the Gateway measurement.
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The previous review had no open items. The follow-up separates metadata reuse from execution-lifetime identity, initializes middleware before testing immediately ready replies, and selects the populated synthetic workspace with a successful-cron assertion. Production code is unchanged. The two affected test files now pass all 36 tests, with type/lint/format checks and fresh Codex autoreview clean. Please review final head 2cb627840156.

@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot removed the clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. label Nov 15, 2026
Scope loopback model commands to one sample so resumed child-completion messages from a reused fixture cannot replay an earlier synthetic spawn.
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Final head is 9244bf780b745318caef052e9685227e80f02e72. The only change after the preceding head scopes synthetic model markers to one measurement sample, preventing old fixture-recovery messages from replaying a spawn. Production code remains unchanged from the reviewed implementation. Script type/lint/format checks and Codex autoreview pass. The final paired profiles use this corrected harness.

@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added the clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. label Nov 15, 2026
@steipete
steipete enabled auto-merge (squash) November 15, 2026 23:32
@steipete
steipete merged commit 3d4bd2a into main Nov 15, 2026
140 of 142 checks passed
@steipete
steipete deleted the steipete/perf-micro-tool-catalog-reuse-20260919 branch November 15, 2026 23:35
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash auto-merge.

steipete added a commit that referenced this pull request Nov 16, 2026
Shared compacted tool catalogs (#199804) keyed MCP metadata with stableStringify, which keeps undefined members, then JSON.parsed those key bytes for the frozen snapshot. An MCP descriptor with an undefined optional field (mode) threw SyntaxError and failed subagent runs about 2 s after spawn on Team ea8bbbb. Snapshot through JSON.stringify instead; the cache key is unchanged.

Regression test fails on the parent with the production SyntaxError and passes with the fix. Focused tool-search tests 5/5, Codex autoreview scoped-clean. Admin-merged at the pinned head with no failed checks (15 pending) to restore subagents on Team.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 16, 2026
* fix: reuse compacted tool catalogs between agent runs

Share bounded immutable catalog metadata by finalized descriptors and schema fingerprints while retaining current-run executors and cleanup. Preserve identical prompt bytes and full MCP output validation. Add cross-session bridge regressions and synthetic allocation, retention and Gateway workloads.

* test: distinguish catalog reuse from execution lifetimes

Keep policy-driven run lifetime replacement independent of detached metadata reuse. Establish ready middleware replies before the immediate-reply parity assertion; the previous cold fixture fails on the exact base after openclaw#199434. Select the populated synthetic workspace and require successful cron completion in the Gateway measurement.

* test: isolate catalog measurement samples from recovered messages

Scope loopback model commands to one sample so resumed child-completion messages from a reused fixture cannot replay an earlier synthetic spawn.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 16, 2026
…w#199909)

Shared compacted tool catalogs (openclaw#199804) keyed MCP metadata with stableStringify, which keeps undefined members, then JSON.parsed those key bytes for the frozen snapshot. An MCP descriptor with an undefined optional field (mode) threw SyntaxError and failed subagent runs about 2 s after spawn on Team 9482c95. Snapshot through JSON.stringify instead; the cache key is unchanged.

Regression test fails on the parent with the production SyntaxError and passes with the fix. Focused tool-search tests 5/5, Codex autoreview scoped-clean. Admin-merged at the pinned head with no failed checks (15 pending) to restore subagents on Team.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. docs Improvements or additions to documentation scripts Repository scripts size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant