Repository navigation
perf(agents): reuse prepared tool descriptors between turns - #170610
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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); |
There was a problem hiding this comment.
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 👍 / 👎.
|
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. |
…#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.
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
1c272f2ae919and candidate9205031d1e8e, with ten warmed turns each. Values below are median [min–max].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.
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; candidate9205031d1e8e.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.
Medians [min–max] across the three runs:
Owner samples by stack position, medians [min–max] per ten warmed turns. “Retirement” means
retireToolGenerationis 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.projectToolInputSchema/ otherprojectToolInputSchema/ retirementnormalizeOpenAIStrictToolParameters/ othernormalizeOpenAIStrictToolParameters/ retirementcatalogEntriesFingerprint/ othercatalogEntriesFingerprint/ retirementPer-run owner splits (other / retirement):
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
Evidence
Focused syntax lint, formatting, and
git diff --checkpass. 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 inheritedrenderBoardWidgetErrorexport inui/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 inc6ee92366b568ed72868c92c7910e2d0f9395c14. 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:41imports the now-privatereadConfigPreflightSnapshot(TS2724). The same import/private declaration is present on fetched maine932e521177bd6cab4f3d2c18bb6d80448452fb7. These files are untouched here. The test has now been migrated tocreateConfigPreflightSnapshotReaderon 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, andget_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
processand session lookup tools. This is recorded as a follow-up under the bounded review scope.