Skip to content

fix(agents): avoid rescanning long prompts before each model request - #190952

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-token-pressure-estimate-per-request-20260919
Nov 2, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-token-pressure-estimate-per-request-20260919

Conversation

@steipete

@steipete steipete commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes repeated full-prompt scanning before model requests in long tool conversations.

User Impact

Request preparation uses less CPU and allocation while retaining exactly the same token-pressure estimates and compaction thresholds. No configuration or migration is required.

Why This Change Was Made

The attempt now prepares fixed system/tool costs once and carries those facts through preflight, hard admission, and compaction budgeting. Frozen message/content estimates reuse the existing immutable-projection owner. Mutable envelopes, content, and tool schemas remain observable; changed descriptions and replacement parameter publications invalidate fixed facts. Whole-tool-set rounding is preserved. Replay admission selects its outgoing checkpoint before calculating a fallback estimate, and the separate foreground-budget stream wrapper is removed.

Evidence

Acceptance defined before measurement: identical numerical pressure/budget vectors; steady scans proportional to appended content; lower CPU/allocation without a >20% latency regression. Five alternating baseline/candidate samples of 32 successive requests, separate A/A controls, and separate timing, allocation, and scan-count runs.

The committed scripts/perf/token-pressure-attempt-measure.ts replays the real AgentSession loop, attempt submission, stream observer and context guards: 360 seeded mixed CJK/Latin messages, images, calls/results, 100 production-finalized tools, and ~379k initial estimated tokens. The provider is synthetic and reports context usage unavailable, exercising fresh estimation on each request; this is request-owner proof, not network latency or whole-Gateway/storage-scale proof.

Metric per request Base Candidate
Main-thread CPU, median 33.790 ms 2.170 ms
Process CPU, median 36.337 ms 4.146 ms
Request boundary p50 32.250 ms 1.157 ms
Request boundary p95 34.978 ms 1.958 ms
Sampled allocation 5,702,723 B 2,126,715 B
Characters scanned across 32 requests 68,883,084 162,074

Final A/A controls (five pairs each): main-thread CPU 33.389 vs 33.512 ms/request (+0.37%); sampled allocation 5,707,158 vs 5,685,089 B/request (-0.39%). Boundary p50 differs by -0.15%, p95 by +9.16%. Measurements use Node 26.12.1 on macOS arm64 / Apple M3 Ultra; these gains describe this stressed request path, not total production CPU.

All 32 pressure and fixed-budget values match the pinned base exactly. Warm continuation scans are constant at 5,226 characters, covering only the new assistant call and tool result. The baseline p95 range includes one scheduling outlier (33.221–235.178 ms); candidate p95 ranges 1.881–2.164 ms.

Focused validation: 136 tests passed across eight affected owner/consumer files; final rerun passed 72 tests across five files including prompt-prefix stability and preflight. The new repeated-scan regression fails against exact base 7a8ace2809e5e7c96dcb4719a81c95994558631c while its golden numeric assertions pass. Core/script typechecks, corrected fixture typecheck, core lint, corrected benchmark lint, formatting and import-cycle checks pass. Final staged Codex autoreview is clean. No changed module is imported by the Control UI.

pnpm check:changed completed and caught fixture typing and benchmark style errors, both corrected and verified with the affected checks. Its remaining dead-export failure is FollowupSummaryEntry in untouched src/sessions/session-controller.contracts.ts, introduced by e41e6d55f9b3de1e6cc407f2661a28870128485a (#190318); the exact production Knip scan reproduces the same sole failure on detached parent 7a8ace2809e5e7c96dcb4719a81c95994558631c. Main subsequently repaired it in 1cd403ee2bfeaaec412d25409bfa32bec55ce6a9, already present in the final CI main parent; the original local check result remains recorded as failed.

Runtime delta: +110 lines (238 added / 128 removed); regression tests +96, reproducible benchmark +588. The runtime growth carries fixed facts explicitly across existing owners and preserves mutable-input invalidation and exact whole-set rounding. It removes the duplicate budget wrapper and discarded full-history calculation; no new configuration, persistence, or dependencies.

First CI run 41406835554: 43 jobs passed; only the plugin test-placement guard and aggregate gate failed. The guard flags the Baseten private runtime import introduced on main by 91f4975d99f9df8939d84729a4927ed427384de4. It fails identically on exact CI main parent d3e890c70f304685f567a41670f6e2cc7609deed; guard and offending file are unchanged in CI merge 64e47b66e5e0df3f2b2cc5f6648d59e01bde8032. This is an independently reproduced main regression. The guard passes on the original PR head.

Hosted review also caught an existing foreground-budget fixture still calling the deleted wrapper while swallowing its failed assertion. The follow-up migrates it to the supplied request-preparation callback and asserts no prompt error was swallowed. The strengthened test fails before the fixture repair; all 23 tests in the file pass afterward. Runtime and benchmark are unchanged.

The same Baseten boundary failure was reproduced again on final CI main parent e9b3e2aacbb4d7b733352d8a24d751d3c643aeff; final tested merge 2ddac5b84ced215d6b27c0790a03c1fb7a12be60 contains reviewed head 908714ff07d23c28be063e1332624aa2347241ff. Guard and offending test blobs remain identical to the introducing commit.

Final-head CI run 41408830374 completed with 43 successful jobs and only the same independently reproduced boundary failure plus its aggregate gate. Task-owned focused proof is green. Landing uses the authorized inherited-failure exception pinned to 908714ff07d23c28be063e1332624aa2347241ff; failed CI is not described as green.

Share immutable message and fixed system/tool estimates across request admission and compaction budgeting. Resolve replay before fallback estimation and remove the separate foreground budget wrapper. Preserve exact rounding and mutable-input invalidation.
@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 in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts agents Agent runtime and tooling size: XL labels Nov 2, 2026
@steipete
steipete marked this pull request as ready for review November 2, 2026 07:31
@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-02T07:52:20.188829Z 908714f 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.

@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: 187ba429ce

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

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 2, 2026
@steipete
steipete merged commit 4a0b683 into main Nov 2, 2026
137 of 142 checks passed
@steipete
steipete deleted the steipete/perf-micro-token-pressure-estimate-per-request-20260919 branch November 2, 2026 08:08
@steipete

steipete commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

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

* perf(agents): reuse prepared token pressure per request

Share immutable message and fixed system/tool estimates across request admission and compaction budgeting. Resolve replay before fallback estimation and remove the separate foreground budget wrapper. Preserve exact rounding and mutable-input invalidation.

* test(agents): exercise prepared foreground budget callback
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-repro Preliminary submission classification; full source review pending. scripts Repository scripts size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant