Repository navigation
perf(agents): reuse prompt diagnostic text measurements - #160807
Conversation
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.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed September 28, 2026, 8:51 PM ET / September 29, 2026, 00:51 UTC (Revision 2). ClawSweeper reviewWhat this changesThe 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 Review scores
Verification
How this fits togetherThe 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]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +42, Tests +71. Total +113 across 4 files. View PR surface stats
Review metrics
Technical reviewBest 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. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
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.
) * 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.
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, profileopenclaw-check), leasetbx_01m3n25epyhte782xyfcym15ex, base2e7f4f8fcd1f596e8551ab4c2fb5065b00a2a0b0: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-lockfileon this lease succeeded, then the tests ran successfully.node scripts/check-changed.mjsinitially selected unrelated changes against the lease'sorigin/mainand 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 --quietplusnode --import ./scripts/tsx.mjs scripts/check-env-var-count.mts --base HEAD --stagedreproduced the same failure on the untouched index. This patch adds no environment variables and does not change that baseline.Ran the remaining native
createChangedCheckPlancommands 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 fromchat.startup; its detachedsessions-filesimport 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), leasetbx_01m3n7vj7kky61xawcvcvwgkar: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.Final CI run: success on
043e6951507616f25673028e63ab4141c912241f, all jobs finished without failures. Workflow wall time: 710 s (00:41:38–00:53:28 UTC).