Skip to content

perf(agents): hash provider prompts off the gateway thread - #159463

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-trajectory-and-prompt-hash-per-tool-call-20260919
Sep 27, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-trajectory-and-prompt-hash-per-tool-call-20260919

Conversation

@steipete

@steipete steipete commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Large provider requests block the Gateway thread while the context-overflow retry guard stably serializes and hashes the complete payload on every model call.

User Impact

Moves ordinary request hashing off the Gateway thread while preserving exact rejected-request replay detection. There are no configuration, audit, receipt, storage, or durable payload-retention changes.

Why This Change Was Made

The snapshot is used by assertProviderPromptRetryProgress to reject only an exact replay in the same provider/model/context-budget scope. Message count or last-message identity cannot replace it: hooks can replace the body or edit an earlier message without changing those values.

One process-owned worker uses the existing WorkerTaskPool, shared compute admission, byte accounting, and idle retirement. The main thread checks the object shape and estimates retained bytes without traversing string contents. Unsupported custom hook values keep the existing local canonicalization; worker failure also falls back locally so bookkeeping availability does not break model calls. There is no content cache or invalidation policy to maintain. Net production growth: 84 lines.

Evidence

Synthetic fixture on provider blacksmith-testbox, profile openclaw-check, lease tbx_01m3ghjkyn5bs46yv4tqwjtqmt: 200 KiB initial prompt, 50 calls with appended 30 KiB tool results; five sequential 50-operation trials. Main-thread time uses performance.eventLoopUtilization().active around the real wrapped transport callback. Baseline and final candidate ran in the same process with identical fixture objects.

Final fixture median Before After
Main-thread time / model payload 1.053 ms 0.087 ms
Wall time / model payload 1.053 ms 1.246 ms

That is 12.1× less main-thread time, at approximately 0.19 ms additional steady-state request latency. Source-mode cold worker startup was 361 ms. Fixture RSS rose from 224.8 MiB to 309.2 MiB after loading and exercising the TypeScript worker; these source-loader measurements are not a production memory or startup prediction. A separate packaged-worker smoke measured 100 ms cold startup and 45.0 MiB additional process RSS, and returned the identical digest for a Unicode fixture.

The initial four-owner fixture measured trajectory recording at 1.38 ms/tool result, request byte accounting at 0.55 ms/payload, and a 50-tool/200-KiB catalog registration at 0.36 ms. Those owners remain unchanged in this bounded fix. Trajectory capture already bounds and sanitizes data, and captureModelEvent retains final-answer isolation. Request byte accounting has no already-serialized transport body available at its current callback boundary. This change moves full hashing off the thread; it does not make the entire bookkeeping pipeline O(delta).

Validation on the same lease:

  • pnpm install --frozen-lockfile: passed after the initial fixture found missing lease dependencies.
  • node scripts/run-vitest.mjs src/agents/embedded-agent-runner/provider-prompt-state.test.ts src/trajectory/runtime.test.ts src/agents/embedded-agent-subscribe.tool-result-ordering.test.ts: all three suites passed.
  • pnpm test src/agents/embedded-agent-runner/provider-prompt-state.test.ts --maxWorkers=1: 12 passed, 19.14 s runner wall; 17.40 s Vitest duration, dominated by the source-worker compiler cache rebuild. The new cases protect exact canonical identity for ordinary nested payloads, callback-bearing hooks, custom Error names, and non-enumerable array elements. The callback and Error regressions failed against naive worker cloning before the compatibility fix.
  • node scripts/check-changed.mjs: passed (21m59s command time). Final review-fix recheck with -- src/agents/embedded-agent-runner/provider-prompt-state.ts src/agents/embedded-agent-runner/provider-prompt-state.test.ts: passed all 25 consuming test type graphs and closing guards (22m04s).
  • pnpm build: passed, including worker packaging and public SDK declaration checks (7m29s command time).
  • Packaged dist/agents/embedded-agent-runner/provider-prompt-state.worker.js through WorkerTaskPool: digest parity and owned shutdown passed (2.50s command time).
  • Lease stopped after validation.
  • Codex autoreview through P2: clean after fixing queued-byte accounting and clone eligibility for unusual arrays.

No production Gateway was modified or restarted. Live production impact remains unmeasured. Crabbox did not return a run URL because its external portal synchronization timed out; execution results came directly from the lease CLI.

Final GitHub proof: CI run 36298496783 passed on a6bf66842a38e864b413fe5f4c87a38a7b1bffe8 in 879 seconds elapsed, with no reruns. Final PR rollup: 170 passed, 47 skipped/neutral, zero pending or failed. The campaign watcher automatically merged the PR after CI passed. CI per-file timing was not extracted; the focused file cost measured on Testbox is recorded above.

@clawsweeper

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

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Sep 27, 2026
@steipete
steipete enabled auto-merge (squash) September 27, 2026 05:55
@clawsweeper

clawsweeper Bot commented Sep 27, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 27, 2026, 1:58 AM ET / 05:58 UTC.

ClawSweeper review

What this changes

Moves provider-request fingerprinting for context-overflow retries to a worker for ordinary payloads, while retaining local hashing for custom values and worker failures.

Merge readiness

✅ Ready for maintainer review

Current main still hashes provider requests on the Gateway thread. The PR addresses that active path, and this source review found no blocking defect in the introduced change.

Priority: P2
Reviewed head: a6bf66842a38e864b413fe5f4c87a38a7b1bffe8

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Focused implementation and parity tests are supported by a scoped before-and-after benchmark, with production impact still unmeasured.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The changed embedded-runner payload snapshot was exercised through its wrapped transport callback on a Testbox with growing synthetic requests; the PR reports median main-thread time of 1.053 ms before and 0.087 ms after, plus packaged-worker digest parity. Live Gateway impact was not measured. 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 (live_output): The changed embedded-runner payload snapshot was exercised through its wrapped transport callback on a Testbox with growing synthetic requests; the PR reports median main-thread time of 1.053 ms before and 0.087 ms after, plus packaged-worker digest parity. Live Gateway impact was not measured. No stored-data contract changes.
Evidence reviewed 8 items Current-main behavior: The current-main snapshot calls sha256StableValue on the provider payload in the request callback; it has no prompt-hash worker path.
Introduced worker path: The introduced hunk sends eligible payloads through a one-worker pool and falls back to the existing local hash on worker failure.
Transport boundary: The provider transport awaits the payload callback before constructing the request it sends, so the fingerprint remains before provider I/O.
Findings None None.
Security None None.

How this fits together

The embedded agent runner intercepts a provider request before model transport sends it. It fingerprints the request so context-overflow recovery can reject an exact replay of a payload the provider already rejected.

flowchart LR
 A[Agent turn] --> B[Provider request]
 B --> C[Payload hook]
 C --> D{Ordinary payload?}
 D -->|Yes| E[Worker fingerprint]
 D -->|No or worker failure| F[Local fingerprint]
 E --> G[Replay guard]
 F --> G
 G --> H[Model transport]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +84, Tests +47. Total +131 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 3 88 4 +84
Tests 1 47 0 +47
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 135 4 +131

Review metrics

Metric Value Why it matters
Measured main-thread cost 1.053 ms before; 0.087 ms after per payload The reported Testbox fixture measures the Gateway-thread work this performance change targets.
Code growth production +84 net; tests +47 The PR attributes the production growth to worker dispatch, eligibility checking, and fallback.
Packaged-worker footprint +45.0 MiB process RSS in the reported smoke This measured resource cost gives maintainers context for the event-loop improvement.

Technical review

Best possible solution:

Keep request fingerprinting in the embedded runner’s existing retry guard, with identical hashes across worker and local paths and bounded worker resources.

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

Yes. Current-main source shows synchronous hashing in the provider payload callback, and the PR describes a repeatable large-request benchmark; I did not independently run that benchmark.

Is this the best way to solve the issue?

Yes. The branch uses the existing worker pool and retains local canonical hashing where cloning could change payload identity.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: This is a bounded Gateway responsiveness improvement for large provider requests; production impact remains unmeasured.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The changed embedded-runner payload snapshot was exercised through its wrapped transport callback on a Testbox with growing synthetic requests; the PR reports median main-thread time of 1.053 ms before and 0.087 ms after, plus packaged-worker digest parity. Live Gateway impact was not measured. No stored-data contract changes.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.

Label justifications:

  • P2: This is a bounded Gateway responsiveness improvement for large provider requests; production impact remains unmeasured.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • proof: sufficient: Contributor real behavior proof is sufficient. The changed embedded-runner payload snapshot was exercised through its wrapped transport callback on a Testbox with growing synthetic requests; the PR reports median main-thread time of 1.053 ms before and 0.087 ms after, plus packaged-worker digest parity. Live Gateway impact was not measured. 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)
  • Vincent Koc: 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.

@steipete
steipete merged commit 5d9d5ee into main Sep 27, 2026
220 checks passed
@steipete
steipete deleted the steipete/perf-micro-trajectory-and-prompt-hash-per-tool-call-20260919 branch September 27, 2026 06:08
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant