Skip to content

perf(agents): reuse prepared tool descriptors between turns - #170610

Merged
steipete merged 3 commits into
mainfrom
dbasync/toolstall
Oct 13, 2026
Merged

steipete merged 3 commits into
mainfrom
dbasync/toolstall

Conversation

@steipete

@steipete steipete commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Warmed Gateway turns repeatedly projected, serialized, parsed, normalized, and hashed the same tool schemas. The tool/schema/catalog group was the largest sampled contributor in the event-loop stall investigation (#170225). This change lets the existing tool-finalization owner publish a bounded, immutable descriptor snapshot when an attempt settles. The next attempt reuses it while tool membership, source schema identity, plugin inventory, provider/model/API, and configuration match.

User Impact

Warmed turns can reuse prepared tool descriptions without retaining execution or permission authority. There is no configuration change or migration. Latency improvement remains unmeasured until quiet-host evidence is available.

Why This Change Was Made

Published schemas retain JSON and fingerprint facts. Provider normalization reuses immutable variants, OpenAI Responses and Completions reuse wire descriptors, Anthropic prepares its tuple dialect separately, and the catalog hashes published schema fingerprints. Generic mutable provider inputs retain their existing projection behavior. Cache-control decoration copies only the request-specific outer wrapper.

Executors, hooks, cancellation, argument preparation, and availability/permission bindings remain per attempt. The snapshot contains descriptors, never authority. The old repeated projection/clone path is bypassed only for explicitly published immutable JSON; mutable external inputs keep their supported behavior.

Main-thread database and measurement

This lane changes descriptor preparation, not database operations. The touched owners have T1 0 → 0, no SQL operations, and no new database path. The global database-worker T1 ratchet stays 455 → 455; changed-file dialect groups stay 0 → 0.

The shared causal harness v2.1 ran one complete baseline/candidate pair, base 1c272f2ae919 and candidate 9205031d1e8e, with ten warmed turns each. Values below are median [min–max].

Warmed causal metric Base Candidate
All-thread statements/turn 170 [170–191] 170 [170–192]
Requests/turn 41 [41–46] 41 [41–46]
MAIN statements/turn 0 [0–0] 0 [0–0]

Mean causal statements/requests are 172.9/41.9 → 172.2/41.6. No SQL saving is attributed to this patch. Tool-preparation SQL operations/requests remain 0 → 0; the only request-family changes are −0.1/turn each for session-actor execution, worker-task input, and an unresolved task origin. All other request families are flat. Across the complete workload, causal statements are 2,944 → 2,966 and causal requests 688 → 682; including background activity, raw totals are 6,925 → 6,852 statements and 1,329 → 1,282 requests. This is scheduling variation outside the unchanged tool-preparation SQL boundary.

Shared reads per warmed turn Base Candidate
Exact-entry facts 4.2 4.2
Actor hydration 1.2 1.1
Entry-cache snapshots 0 0
Row facts 0 0
Transcript watermarks 1.0 1.0

Background SQL/min is 540.9 → 605.2; legacy window statements/turn average 217.7 → 215.9. The 32-core host's one-minute load ranged 47.6–92.5 at the SQL run boundaries, so these totals are not latency evidence. The immediate Testbox request queued and was cancelled. Event-loop p99 and turn latency remain unmeasured.

Task-local harness copies relocate fixture/proof output to external storage and use the documented 75-second pre-turn handshake budget symmetrically after a loaded-host handshake expired before the first turn. Workload and causal counting are unchanged; the shared harness is untouched.

Stall-window profiles

Base 1c272f2ae919; candidate 9205031d1e8e.
Three alternating profile pairs (M,C,M,C,M,C), ten warmed turns per run. The immediate Testbox request queued and was stopped, so these are loaded-local-host sample observations. No demonstrated overall CPU or latency reduction; no event-loop p99 or turn-latency claim. Samples locate work but are not causal CPU-time totals.

Run ≥8 ms windows Whole-profile tool/schema/catalog samples In-window tool samples, guaranteed–possible Whole-profile GC samples
M1 382 502 498–498 187
C1 386 454 446–446 189
M2 510 376 375–375 182
C2 328 606 235–605 163
M3 527 828 774–821 573
C3 298 586 168–586 125

Medians [min–max] across the three runs:

Metric per ten warmed turns Base Candidate
≥8 ms windows 510 [382–527] 328 [298–386]
Whole-profile tool/schema/catalog samples 502 [376–828] 586 [454–606]
Whole-profile GC samples 187 [182–573] 163 [125–189]
Whole-profile trajectory/prompt samples 382 [372–582] 406 [377–461]
In-window tool samples, guaranteed bound 498 [375–774] 235 [168–446]
In-window tool samples, possible bound 498 [375–821] 586 [446–605]

Owner samples by stack position, medians [min–max] per ten warmed turns. “Retirement” means retireToolGeneration is in the sampled synchronous stack; “other” means absent. Owners overlap and must not be summed. This distinguishes publication work from other preparation but does not measure request critical-path duration.

Owner / stack Base Candidate
projectToolInputSchema / other 57 [56–91] 27 [25–34]
projectToolInputSchema / retirement 0 [0–0] 95 [48–117]
normalizeOpenAIStrictToolParameters / other 15 [12–16] 11 [6–14]
normalizeOpenAIStrictToolParameters / retirement 0 [0–0] 51 [23–70]
catalogEntriesFingerprint / other 61 [45–63] 33 [29–35]
catalogEntriesFingerprint / retirement 0 [0–0] 0 [0–0]

Per-run owner splits (other / retirement):

Run Projection Strict normalization Catalog fingerprint
M1 56 / 0 16 / 0 45 / 0
C1 25 / 48 6 / 23 33 / 0
M2 57 / 0 15 / 0 61 / 0
C2 27 / 117 11 / 70 35 / 0
M3 91 / 0 12 / 0 63 / 0
C3 34 / 95 14 / 51 29 / 0

Clock-alignment uncertainty after source-backed monotone macOS clock bounds: M1 0.073 ms, C1 0.901 ms, M2 0.064 ms, C2 35.179 ms, M3 98.241 ms, C3 23.491 ms. In-window bounds are reported instead of hiding ambiguous assignments. Whole-profile sample counts and timer-window counts do not depend on this alignment.
GC counts are reported without attributing an allocating owner. Residual stacks include dynamic schema construction and snapshot publication during retirement, catalog fingerprinting, metadata copying, and tool-directory rendering. These observations do not establish which allocator triggered GC.

All six profile runs captured ten warmed profiles with zero dropped windows and clean shutdown. The profile-only post-warm tail was omitted symmetrically for C1/M2/C2/M3/C3; M1 measurements precede its longer tail. Setup and the measured prefix were unchanged. A C3 boot was interrupted before any warmed-turn measurements; its fixture processes and scratch were cleaned up before the missing capture resumed under the current four-slot gate with the existing build. No measured result was discarded.

Removed repeated work and accepted edges

  • Published-schema projection, validation traversal, and prepared normalization JSON cloning are reused until the finalization inputs change; schema owners publish edits by replacing their schema object.
  • Catalog schema rehashing uses the publication fingerprint; remote/client schemas retain their existing identity-based handling.
  • No security-boundary check is removed. Skill-read and collector availability, execution hooks, and abort checks remain live.
  • A late attempt settlement may replace a newer descriptor cache entry; input matching turns that into a recoverable cold miss. No fencing or generations are added.

Evidence

Focused syntax lint, formatting, and git diff --check pass. New regressions cover settlement reuse, tool/config/plugin/provider/model/API changes, schema replacement, fresh execution and abort/hook state, skill-read authority, provider tuple/strict variants, and request-specific cache markers. Final-head CI run 38344921650 passed every selected behavioral test job, including all eight changed test files (152 passing cases), production types, type-aware lint, source/export contracts, Madge (zero cycles), and database worker/dialect ratchets. CI timings: the tool-owner shard took 54.98 s, the package contract test 9.75 s, sandboxed execution 11.59 s, and tool-policy gates 9.29 s. The global T1 ratchet stayed 455 → 455; touched owners stay 0 → 0. The separate Knip scan completed: script exports are clean; production/full-tree report only the inherited renderBoardWidgetError export in ui/src/components/board/board-widget-cell-render.ts. The exact finding is present in scheduled main CI; the UI owner has already removed that obsolete adapter on main in c6ee92366b568ed72868c92c7910e2d0f9395c14. No touched-file Knip finding remains. Both isolated Codex autoreview rounds are scoped-clean at P0–P2; the second reviewed the corrected availability-schema capture. The new finalization suite passed all 10 tests: 166 ms of test execution, 274.19 s wrapper wall time (242.05 s Vitest) dominated by cold worker compilation (157.35 s) and source transformation on the loaded local host.

No schema, migration, update, Doctor, plugin-loading, service-lifecycle, or plugin SDK contract changes; the published-driver update cell and SDK surface diff do not apply. LOC: production +476/−69 (net +407); tests +394/−35 (net +359); docs +2/−0 (net +2). The initial CI exposed descriptor TypeScript boundary errors, missing assertion invariants, and strict-null errors in the new test fixture; follow-up commits correct those without changing the snapshot design. The only final CI failure is inherited: src/commands/config-preflight-snapshot.test.ts:41 imports the now-private readConfigPreflightSnapshot (TS2724). The same import/private declaration is present on fetched main e932e521177bd6cab4f3d2c18bb6d80448452fb7. These files are untouched here. The test has now been migrated to createConfigPreflightSnapshotReader on main by #170619 (72ccf43fdc6fbe8f4534b84b86f1c8a8909032f5). This qualifies for the authorized inherited-failure landing exception.

Follow-up

Hosted review raised a P2 concern about custom payload hooks mutating nested tool descriptors. The provider hook documents inspection/replacement, current bundled wrappers replace projected tools or patch request-level fields, and those request objects remain mutable. Explicitly published nested descriptors are immutable. Custom nested in-place mutation can throw after publication and remains a compatibility follow-up; generic mutable tool inputs retain their existing behavior.

Source-backed performance follow-ups: dynamic schema factories (automations, sessions_spawn, computer, message, skills_search/read, and get_goal) still create new schema identities each attempt, so settlement still publishes changed entries. Stable parameter schemas reuse correctly. Factory-owned descriptor variants can remove further allocations without retaining live tool instances.

A P2 mixed-catalog reuse miss also remains: after binding a published output schema, settlement records that publication as the next output-source identity; the next attempt supplies the original output schema and misses descriptor binding. It returns the current tool, preserving current descriptors and authority, but can repeat output projection/fingerprinting for tools such as process and session lookup tools. This is recorded as a follow-up under the bounded review scope.

@clawsweeper

clawsweeper Bot commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 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-10-13T04:12:34.924177Z 9205031 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: L labels Oct 13, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2838a2fa4e

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

for (const child of Object.values(value)) {
pending.push(child);
}
Object.freeze(value);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve mutable tool payloads at the hook boundary

When a descriptor is reused on a warm turn, this recursively freezes the exact schema object placed in the provider request; OpenAI descriptors are also frozen in openai-function-tool.ts. This violates the explicit mutable-payload contract in src/llm/providers/stream-wrappers/stream-payload-utils.ts:3-18: a wrapper or plugin that patches a tool description, strict flag, parameters, or Anthropic input_schema in place now throws only after snapshot publication, making behavior turn-dependent. Keep the immutable cached descriptors private and supply request-local mutable copies before invoking payload hooks.

Useful? React with 👍 / 👎.

@steipete

steipete commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Review follow-up: published tool descriptors are deliberately immutable. Request objects remain mutable, and hooks can replace a tool or its parameters object, as the inspected bundled wrappers do. A custom hook that mutates a nested reused descriptor in place can throw after publication; supporting that mutation pattern remains a compatibility follow-up. No failing bundled path was identified. The provider projection, cache-marker, and per-attempt authority regressions pass.

A separate source-backed P2 performance follow-up remains in mixed catalogs: settlement can capture the already-published output schema as its next source identity, causing a miss when the following attempt supplies the original schema. That path returns the current tool; it does not reuse stale data or restore authority, but can repeat output projection/fingerprinting. Stable parameter publication still reuses correctly. Dynamic schema factories also remain a source of per-attempt allocation and cleanup publication.

@steipete steipete changed the title improve: reuse prepared tool descriptors between turns perf(agents): reuse prepared tool descriptors between turns Oct 13, 2026
@steipete
steipete merged commit bca779e into main Oct 13, 2026
155 of 158 checks passed
@steipete
steipete deleted the dbasync/toolstall branch October 13, 2026 04:59
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 14, 2026
…#170610)

Publish immutable tool descriptor snapshots from the finalization owner at attempt settlement. Reuse projected schemas, provider-shaped descriptors, and fingerprints while their inputs match; bind executors, hooks, cancellation, and live availability separately for each attempt.

Keep descriptor caching bounded and invalidate it for tool membership, schema identity, plugin inventory, config, and provider/model changes. Cover provider variants, invalidation, and fresh per-attempt authority in regression tests.

Warmed SQL medians remain 170 statements / 41 requests, with zero main-thread statements in both revisions. Loaded-host profiles do not establish an overall CPU or latency improvement. Dynamic schema factories and output-schema identity misses remain follow-ups.

All 152 cases in changed test files passed in PR CI. The inherited config-preflight test-type error and unused UI export were fixed independently on main. Land under the authorized inherited-failure exception.
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 size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant