Skip to content

perf(agents): reuse prompt diagnostic text measurements - #160807

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-prompt-stats-per-turn-cost-20260919
Sep 29, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-prompt-stats-per-turn-cost-20260919

Conversation

@steipete

@steipete steipete commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

With diagnostics enabled, each model request re-encodes large unchanged prompt strings to measure JSON character counts, adding recurring work to long tool loops.

User Impact

Reduces diagnostic bookkeeping CPU for repeated large prompts. Prompt bytes, diagnostic sizes, request/response byte counts, and provider cache keys are unchanged. No configuration or migration is required.

Why This Change Was Made

Retain measured character counts in the existing per-attempt diagnostic wrapper, keyed by the native JSON holder, field name, and exact text revision. Each observation retains only fields seen in that prompt, so deletions and compaction drop prior facts even if old message objects remain live.

Whole-prefix totals would be unsafe here: context transforms can rewrite earlier messages in place without a revision. Native JSON traversal therefore still observes structure, getters, toJSON, omissions, and serialization errors; only unchanged strings of at least 4096 characters skip encoding. New holders and changed text are measured normally. This is an intentionally narrower optimization than caching entire message-prefix totals. The boundary key already uses session ID and boundary count without traversing messages; the CJK estimator is unchanged. Net production growth: 42 lines.

Evidence

Blacksmith Testbox (blacksmith-testbox, profile openclaw-check), lease tbx_01m3n25epyhte782xyfcym15ex, base 2e7f4f8fcd1f596e8551ab4c2fb5065b00a2a0b0:

  • Source-level Node microbenchmark: 80 retained messages × 8000 UTF-16 characters = 640,000 characters (nominally 160k tokens at four characters/token), mixed Unicode/escaping, then 80 appended turns. Median of seven warmed trials: 1.0172 → 0.04597 ms/turn, 22.1× faster / 95.5% less time. Identical accumulated character counts (414701805). Peak RSS: 75.86 → 76.51 MiB. This isolates diagnostic statistics; it is not an end-to-end Gateway measurement.

  • node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/attempt.model-diagnostic-events.test.ts -t 'reuses prompt text sizes' with the original wrapper: expected failure, because the unchanged prefix was encoded again. Restoring the candidate makes it pass.

  • pnpm test src/agents/embedded-agent-runner/run/attempt.model-diagnostic-events.test.ts src/agents/embedded-agent-runner/run/session-boundary-prompt-cache-key.test.ts --maxWorkers=1: 27 passed. Covers exact full-JSON equality across appends, in-place rewrites, compaction, mixed JSON values, disabled diagnostics, and existing key lifecycle behavior. New regression: 5 ms. Combined wall time 40.64 s, including 31.87 s cold worker compilation; the existing diagnostic file's test bodies total roughly 150 ms.

  • The initial test launch found missing dependencies; one pnpm install --frozen-lockfile on this lease succeeded, then the tests ran successfully.

  • node scripts/check-changed.mjs initially selected unrelated changes against the lease's origin/main and stopped at unrelated line-cap violations. Re-running with --base HEAD -- <three changed files> passed the scoped line-cap checks but hit an inherited environment-count failure: 477 names / budget 476. git diff --cached --quiet plus node --import ./scripts/tsx.mjs scripts/check-env-var-count.mts --base HEAD --staged reproduced the same failure on the untouched index. This patch adds no environment variables and does not change that baseline.

  • Ran the remaining native createChangedCheckPlan commands serially on the same lease, retaining every result instead of stopping at the inherited environment-budget failure: all 28 passed. Includes production typechecking, all 26 selected test typecheck graphs, targeted lint (0 warnings/errors), formatting, full-tree dead exports, plugin boundaries, schema/storage guards, and import cycles. Remote command wall time: 28m 53.9s. The full aggregate check remains explicitly non-green only for the inherited 477/476 budget mismatch.

  • The Testbox lease was stopped successfully after validation. Its portal link was unavailable (CLI reported a portal-sync timeout); the lease ID above identifies all remote runs.

  • Independent Codex autoreview: no P0–P2 findings; patch correct. The initial review transport failed and its retry timed out; the supported configured command-auth route completed review with isolation preserved.

No live Gateway was modified or restarted. Benefit depends on retaining text-holder identity between model requests in an attempt; cloned holders and short strings retain the existing full measurement path.

CI fixture repair

The first CI run passed all 87 executed assertions in its Gateway shard, then failed suite collection with EnvironmentTeardownError. The preceding cursor-history fixture launched optional workspace-icon preparation from chat.startup; its detached sessions-files import continued after that fixture's environment was torn down. The stack matches this path exactly. The five-line fixture repair stubs optional icon preparation while retaining the cursor/startup assertions and real icon coverage in its owning suite. Production behavior is unchanged.

Additional Blacksmith Testbox proof (blacksmith-testbox, openclaw-check), lease tbx_01m3n7vj7kky61xawcvcvwgkar:

  • The ACP completion suite passed alone (12 tests). The initial order-forcing launcher hit a Vitest sequencer configuration error before collection; a temporary config corrected that tooling issue.
  • The pre-change replay of the original 14-file order passed (155 tests at this branch's base), so the intermittent failure did not reproduce. Root-cause evidence comes from the detached import in the CI stack.
  • Candidate: 3/3 ordered 14-file replays passed, 155 tests each; 20/20 standalone cursor runs passed, 12 tests each. Real workspace-icon suite: 38 passed. Targeted lint and the Gateway-server test typecheck passed. Fresh autoreview: no P0–P2 findings.
  • pnpm test src/gateway/server.chat-history-cursor.test.ts --maxWorkers=1: warm native-wrapper median 16.13 s over 20 runs. An additional source-hash-verified cold run passed in 45.99 s wall, including about 30 s of compilation. No test cases were added.
  • The second lease was stopped after validation. No CI jobs were rerun to mask the failure; the repair is a new commit on this PR.

Final CI run: success on 043e6951507616f25673028e63ab4141c912241f, all jobs finished without failures. Workflow wall time: 710 s (00:41:38–00:53:28 UTC).

Reuse large-string JSON character counts within the diagnostic attempt wrapper, using exact text revisions and dropping fields absent from each new prompt. Preserve structural JSON observation for in-place rewrites and compaction; leave provider cache-key behavior unchanged.
@clawsweeper

clawsweeper Bot commented Sep 28, 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.

@steipete
steipete enabled auto-merge (squash) September 28, 2026 23:50
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Sep 28, 2026
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 28, 2026
@clawsweeper

clawsweeper Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 28, 2026, 8:51 PM ET / September 29, 2026, 00:51 UTC (Revision 2).

ClawSweeper review

What this changes

The branch reuses JSON character measurements for unchanged long prompt text during an agent attempt and isolates a Gateway cursor test from asynchronous workspace-icon preparation.

Merge readiness

✅ Ready for maintainer review

Keep open. Current main still repeats the measurement work this PR addresses, and the branch remains a coherent contribution. The prior review reported no findings; this review found no actionable introduced defect.

Priority: P3
Reviewed head: 043e6951507616f25673028e63ab4141c912241f

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Focused before-and-after measurement, regression coverage, and a small production change support a normal good PR rating.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The changed production owner is diagnostic prompt-size measurement. The PR reports a Blacksmith Testbox source-level run of repeated large prompts with identical measured counts and an observed 1.0172-to-0.04597 ms median improvement per turn; this proves the scoped measurement behavior, not full Gateway latency. The Gateway change is test-only, and no stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The changed production owner is diagnostic prompt-size measurement. The PR reports a Blacksmith Testbox source-level run of repeated large prompts with identical measured counts and an observed 1.0172-to-0.04597 ms median improvement per turn; this proves the scoped measurement behavior, not full Gateway latency. The Gateway change is test-only, and no stored-data contract changes.
Evidence reviewed 7 items Current-main behavior: The current-main diagnostic measurement encodes each large string during every prompt-size calculation; it has no cross-call measurement cache.
Production path: The embedded attempt installs the diagnostic wrapper on the agent stream function, and the PR creates one measurement cache for that wrapper.
Cache behavior: The patch reuses a character count only for the same holder, field, and exact text; it still traverses JSON structure and replaces the retained observations after each measurement.
Findings None None.
Security None None.

How this fits together

The embedded agent runner measures prompt sizes while wrapping model requests with diagnostic events; the measurements do not alter the provider request. A Gateway cursor test also exercises chat startup, which can start optional workspace-icon preparation.

flowchart LR
A[Agent turn] --> B[Prompt messages and tools]
B --> C[Diagnostic wrapper]
C --> D[JSON traversal]
D --> E{Long text unchanged?}
E -->|Yes| F[Reuse character count]
E -->|No| G[Encode and measure text]
F --> H[Model call diagnostic event]
G --> H
C --> I[Provider request]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +42, Tests +71. Total +113 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 2 53 11 +42
Tests 2 72 1 +71
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 125 12 +113

Review metrics

Metric Value Why it matters
Diagnostic benchmark 1.0172 → 0.04597 ms/turn; 22.1× faster The reported Testbox measurement targets the repeated large-prompt diagnostic work, with identical accumulated counts.
Code delta production +42 lines; tests +71 lines The production growth is explained by a bounded cache with explicit invalidation; the test growth checks its measurement contract.

Technical review

Best possible solution:

Retain the attempt-scoped cache and its regression coverage, leave icon behavior covered by the owning icon suite, and land through the normal PR gates.

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

Yes. Current-main source re-encodes retained long strings on each measurement, and the PR reports a before-and-after repeated-prompt benchmark. I did not execute code in this read-only review.

Is this the best way to solve the issue?

Yes. The cache skips encoding only when holder, field, and text match, while native JSON traversal still observes structural changes; the fixture change isolates optional work that has its own tests.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 4a448bdd2656.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The changed production owner is diagnostic prompt-size measurement. The PR reports a Blacksmith Testbox source-level run of repeated large prompts with identical measured counts and an observed 1.0172-to-0.04597 ms median improvement per turn; this proves the scoped measurement behavior, not full Gateway latency. The Gateway change is test-only, and no stored-data contract changes.

Label justifications:

  • P3: This is a scoped diagnostic CPU optimization with no reported broken user workflow.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The changed production owner is diagnostic prompt-size measurement. The PR reports a Blacksmith Testbox source-level run of repeated large prompts with identical measured counts and an observed 1.0172-to-0.04597 ms median improvement per turn; this proves the scoped measurement behavior, not full Gateway latency. The Gateway change is test-only, and no stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The changed production owner is diagnostic prompt-size measurement. The PR reports a Blacksmith Testbox source-level run of repeated large prompts with identical measured counts and an observed 1.0172-to-0.04597 ms median improvement per turn; this proves the scoped measurement behavior, not full Gateway latency. The Gateway change is test-only, and no stored-data contract changes.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-28T23:56:27.767Z sha b2aff7c :: needs maintainer review before merge. :: none

The cursor suite launched optional workspace-icon preparation from chat.startup without awaiting its lazy import. CI observed that import after the cursor environment was torn down while collecting the next suite. Stub the unrelated icon boundary in this fixture; retain real icon coverage in its owning suite.
@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Sep 29, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Sep 29, 2026
@steipete
steipete merged commit caf7778 into main Sep 29, 2026
225 checks passed
@steipete
steipete deleted the steipete/perf-micro-prompt-stats-per-turn-cost-20260919 branch September 29, 2026 00:54
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 29, 2026
)

* perf(agents): reuse prompt diagnostic text measurements

Reuse large-string JSON character counts within the diagnostic attempt wrapper, using exact text revisions and dropping fields absent from each new prompt. Preserve structural JSON observation for in-place rewrites and compaction; leave provider cache-key behavior unchanged.

* test(gateway): isolate cursor startup from icon preparation

The cursor suite launched optional workspace-icon preparation from chat.startup without awaiting its lazy import. CI observed that import after the cursor environment was torn down while collecting the next suite. Stub the unrelated icon boundary in this fixture; retain real icon coverage in its owning suite.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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