Skip to content

improve: reduce repeated tool preparation and expose prompt timings - #191437

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-turn-prep-system-prompt-tail-bundle-tools-20260919
Nov 2, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-turn-prep-system-prompt-tail-bundle-tools-20260919

Conversation

@steipete

@steipete steipete commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Chat turn preparation repeats a schema depth traversal even when normalization already has a prepared result, and slow-chat diagnostics hide system-prompt owner timings unless trace logging is enabled.

User Impact

Repeated tool preparation avoids discarded schema work. Slow chat startup records identify the prompt and MCP/LSP preparation owners without enabling trace logging. Prompt bytes, tool definitions, policy filtering, and per-run execution authority retain their existing contracts.

Why This Change Was Made

Check the existing normalization cache before walking the input schema. A miss still follows the same normalization and depth-bounding path; no new cache or lifecycle is introduced. Publish the existing prompt phases through the request observer and add a fixed set of bundle phases, including failure cleanup.

Workspace bootstrap and skills execute in separate stages. This change does not introduce a session snapshot or reuse executable closures. The workspace manifest revision describes projection synchronization, not every file mutation; workspace snapshot work overlaps #174235.

Evidence

Acceptance rule, recorded before comparison: use the same synthetic fixture with 62,000 workspace files, 64 plugin factories, 100 skills, and a real local MCP server. Compare first-turn and warm wall time, CPU, and sampled allocation in at least five alternating pairs with A/A controls; require exact unchanged prompt and tool bytes, fewer schema traversals, and no unexplained metric regression above 20%. Owner composition is not a full Gateway, Linux/btrfs, or production database benchmark.

Focused owner result (64 MCP tools × 20 nested fields, five alternating process pairs, 7,500 warm bindings/arm): wall p50/p95 1.426/1.452 → 0.0619/0.0735 ms, main CPU 1.4258 → 0.0612 ms/bind, process CPU 1.4875 → 0.0962 ms/bind, sampled allocation 6,065,777 → 153,947 B/bind (separate allocation passes). Tool bytes match exactly. A/A warm wall variation was 1.3%, process CPU 2.5%.

First catalog in each fresh process (n=5/arm): wall 23.693 → 24.165 ms, main CPU 23.718 → 24.208 ms, process CPU 38.334 → 40.121 ms, sampled allocation 51.115 → 50.928 MB. Later repeated fresh-catalog cohorts show a process-CPU median increase 31.338 → 40.121 ms (+28%), with flat main-thread/wall medians; unequal warm-loop duration may shift background compilation into those windows. That explanation is an inference, and the discrepancy is retained rather than called neutral. The subsequent whole-process check includes imports, setup, GC, warmups, verification and shutdown: CPU 12.21 → 2.46 s, wall 11.16 → 1.46 s, peak RSS 258.75 → 248.55 MB for 7,500 bindings. This supports reduced total work rather than moving it outside the owner timer.

The composed fixture uses 62,000 synthetic files (1.21 GB), 64 native plugin factories, 100 skills, 80 real stdio MCP tools, 5,002 session records and two 1,000-message histories. Five counterbalanced pairs with 100 warm observations per cohort/arm, plus A/A and separate allocation passes:

Stage Warm wall p50/p95 before → after Main CPU p50 before → after Allocation before → after
Host bundle 8.772/12.589 → 6.731/7.349 ms 8.781 → 6.739 ms 11.656 → 6.015 MB
Host prompt 2.024/3.520 → 2.008/2.861 ms 2.018 → 1.992 ms 1.265 → 1.271 MB
Sandbox bundle 8.194/14.470 → 6.635/7.017 ms 8.201 → 6.643 ms 11.673 → 6.023 MB
Sandbox prompt 1.688/3.747 → 1.852/2.414 ms 1.681 → 1.831 ms 1.242 → 1.235 MB

First host prompt wall p50/p95 74.13/357.62 → 73.71/75.84 ms; first bundle 1095.18/2539.10 → 1145.55/1183.91 ms, including real MCP initialization. First host prompt/bundle main CPU 39.57/180.91 → 40.86/194.29 ms. Sandbox session-first prompt/bundle wall 2.366/927.55 → 2.448/993.06 ms, sharing already-warm process imports; main CPU 2.336/29.52 → 2.434/31.36 ms. Cold allocation holds (host bundle 159.17 → 158.55 MB, prompt 27.93 → 28.05 MB). Exact prompt and tool bytes match all 924 campaign attempts and 84 diagnostic attempts.

Total five-owner warm wall p50/p95: host 28.686/38.731 → 27.397/35.376 ms, sandbox 28.220/63.264 → 28.052/31.522 ms. Total process CPU is flat (69.918 → 69.377 ms host, 68.758 → 69.393 ms sandbox). A/A total wall p50/p95: host 31.590/35.055 → 28.292/31.504 ms, sandbox 31.929/33.605 → 28.893/38.478 ms.

The first candidate pair has worse total p95 (host 30.55 → 37.37 ms, sandbox 28.31 → 50.15 ms), including 16–17 ms bootstrap CPU spikes; these samples remain in all aggregates. Later pairs and bounded unchanged-script CPU/GC diagnostics did not reproduce those spikes. Their cause remains unknown; neither GC nor scheduler noise is claimed as established. The aggregate first/warm latency and total-work measurements meet the performance rule; the individual adverse pair remains an unresolved limitation. This is a narrow optimization, not a universal per-pair win. Per-phase process CPU can include concurrent worker work and is not exclusive owner attribution.

Reproduce composition with node --expose-gc --import ./scripts/tsx.mjs scripts/perf/turn-preparation-measure.mjs --root <same-owned-absolute-path> --files 62000 --plugins 64 --sessions 5000 --history 1000 --iterations 20 --keep; add --allocation in separate runs. This source-runtime owner benchmark forces GC between turns and does not run inference or a full Gateway. The synthetic database is 16.77 MB. Sandbox commands are disabled; memory plugins, active-project memory, watches, subagent registry and default reference discovery are not exercised. The reported long production prompt tail was not reproduced: attribution is the deliverable for that remaining unknown.

CPU profiles locate the removed work under truncateToolSchemaDepth: 9,472.8 → 35.0 ms sampled in 7,500 bindings; candidate retains depth preparation on misses. Reproduction: node --expose-gc --import ./scripts/tsx.mjs scripts/perf/mcp-tool-materialization-measure.ts candidate timing 300; run the same committed script against the pinned baseline with its documented source override. Allocation uses allocation 100 separately.

Validation: regressions fail before the fixes and pass afterward; 45 preparation/diagnostic/prefix-stability tests, 35 normalization tests, five existing skill/plugin invalidation cases, 27 UI tools browser tests, and nine bundled chat messaging E2E tests passed. Codex autoreview against b8ed94ff73d6, P0–P2, was scoped-clean with no actionable findings. The final prefix suite was rerun after the schema reorder (14 passed). pnpm check:changed --base b8ed94ff73d6 completed: 35 gates passed; benchmark type/lint defects were corrected and both failed gates now pass on focused rerun. The sole remaining local red is inherited: unused buildRequestBody in openai-chatgpt-responses-request.ts, reproduced with zero dependency-resolution errors on exact parent b8ed94ff73d6d10a2e0bbae56cbe6c68f72064c1. It was introduced by 1c03d49956ed (#191261) and is already repaired on main by 7a96bac8ed5e. No gate was skipped or relabeled green.

Production LOC: 0 for the optimization, +4 for attribution. The 53 test-line allocation covers the missing-observation and repeated-work regressions. No schema, configuration, dependency, or executable-lifetime changes.

Reuse the existing normalized schema before depth traversal and record fixed prompt and bundle preparation phases in slow-chat diagnostics. Preserve prompt/tool bytes and per-run execution authority; include reproducible synthetic workloads and missing-observation/work-count regressions.
@clawsweeper

clawsweeper Bot commented Nov 2, 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 docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: L labels Nov 2, 2026
@steipete
steipete marked this pull request as ready for review November 2, 2026 20:11
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 2, 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-11-02T20:18:19.131332Z e4ef806 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.

@steipete
steipete enabled auto-merge (squash) November 2, 2026 20:26
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature 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:feature Preliminary submission classification; full source review pending. labels Nov 2, 2026
@clawsweeper

clawsweeper Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR checks the existing schema-normalization cache before depth traversal and exposes prompt and bundled-tool preparation timings without trace logging.

Example: An operator investigates a slow chat using 80 MCP tools at info log level.

  • Before: Cached schemas still undergo depth traversal, and prompt subphase timings require trace logging.
  • After: Cache hits skip the traversal, and slow-chat records include prompt and MCP preparation phases.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is focused and appears correct; owner-composition measurements support the optimization, with limited evidence of behavior through the shipped entry point.
Proof confidence 🦐 gold shrimp (3/6) The ordinary contributor proof gate does not apply to this maintainer-authored PR; its supplied measurements exercise real preparation owners and a local stdio MCP transport, while explicitly excluding a shipped Gateway run and the unreproduced production prompt tail.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Repeated chat preparation spends CPU on discarded schema traversal, and ordinary slow-chat diagnostics lack enough detail to locate prompt preparation delays.
Reason: The maintainer-authored direction has measured owner-level value, preserves existing product contracts, and clearly limits its latency claims.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR provides a useful, maintainer-directed optimization and diagnostic improvement that current main lacks; no actionable correctness or security defect was found.

Priority: P2
Reviewed head: e4ef806d2bd83ebd332dc81e42c27c399c256077

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied evidence does not show an isolated shipped Gateway emitting the new slow-chat phases at info level.
Agent review details

How this fits together

Embedded turn preparation consumes tool schemas, provider options, workspace context, and run facts to produce model-facing tools and prompts, while the request observer collects preparation timings.

flowchart LR
  A[Chat request] --> B[Embedded preparation]
  B --> C[Tool normalization cache]
  C --> D[Model tools]
  B --> E[System prompt preparation]
  E --> F[Model prompt]
  B --> G[Request timing observer]
  G --> H[Slow chat diagnostics]
Loading

Technical review

Best possible solution:

Retain the existing normalization and diagnostic owners, skip depth work on cache hits, and publish fixed preparation phases without changing prompt bytes or execution authority.

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

Current main visibly traverses schema depth before consulting its normalization cache and gates prompt phases on trace logging; the PR reports matching red/green regressions, but no target code was executed during this read-only review.

Is this the best way to solve the issue?

The smallest complete fix is the proposed cache-order change and reuse of the existing timing observer; the benchmark tooling supports measurement without adding a runtime cache, wrapper, or competing owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 7e27d6c adds packages/ai/src/providers/agent-tools-parameter-schema.ts:368 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 7e27d6cebec6; files: packages/ai/src/providers/agent-tools-parameter-schema.ts)
  • pick-cat: Raw commit 1f89d6d adds src/agents/agent-tools-parameter-schema.ts:780 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 1f89d6d7f762; files: src/agents/agent-tools-parameter-schema.ts)

PR surface

Source +4, Tests +53, Docs +8, Other +769. Total +834 across 10 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 29 25 +4
Tests 3 57 4 +53
Docs 1 9 1 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 3 769 0 +769
Total 10 864 30 +834

Review metrics

Metric Value Why it matters
Runtime versus regression growth Runtime +4 net lines; tests +53 net lines The optimization reorders existing code; runtime growth supplies timing observations, and tests cover repeated work plus missing success/failure observations.

Labels

Label changes:

  • add P2: Reduces repeated turn-preparation work and improves slow-chat diagnosis without establishing an urgent workflow outage.
  • 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: Reduces repeated turn-preparation work and improves slow-chat diagnosis without establishing an urgent workflow outage.
  • 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.

  • For stronger confidence, capture an isolated Gateway slow-chat record at info level showing the new prompt and bundle phases, with sensitive details redacted.

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 2, 2026, 3:32 PM ET / 20:32 UTC.

@steipete
steipete merged commit 3bbe6e2 into main Nov 2, 2026
136 of 138 checks passed
@steipete
steipete deleted the steipete/perf-micro-turn-prep-system-prompt-tail-bundle-tools-20260919 branch November 2, 2026 20:34
@steipete

steipete commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash auto-merge.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 3, 2026
…penclaw#191437)

* perf(agents): avoid repeated schema walks during turn preparation

Reuse the existing normalized schema before depth traversal and record fixed prompt and bundle preparation phases in slow-chat diagnostics. Preserve prompt/tool bytes and per-run execution authority; include reproducible synthetic workloads and missing-observation/work-count regressions.

* style(perf): satisfy benchmark script lint
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation 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