Skip to content

perf(ai): keep streaming responsive while large tool call arguments assemble - #128166

Merged
vyctorbrzezowski merged 3 commits into
mainfrom
perf/tool-call-argument-assembly
Aug 23, 2026
Merged

vyctorbrzezowski merged 3 commits into
mainfrom
perf/tool-call-argument-assembly

Conversation

@vyctorbrzezowski

@vyctorbrzezowski vyctorbrzezowski commented Aug 23, 2026 •

Copy link
Copy Markdown
Member

What Problem This Solves

Fixes an issue where agents emitting large tool calls could stall streaming and consume excessive CPU while arguments were still arriving. Each argument delta re-parsed the complete accumulated JSON, making assembly cost grow quadratically.

Refs #113124, Closes #121770

Why This Change Was Made

Parsed mid-stream arguments are previews; terminal parsing remains authoritative. This change refreshes previews at geometric length checkpoints across the accumulating provider, transport, proxy, and worker paths, keeping total parse work linear while preserving exact completed arguments. Proxy calls that legitimately contain no argument deltas retain {} at toolcall_end.

The OpenAI Responses stream contracts were moved to a focused internal type module so the runtime implementation remains below the 700-line limit without suppressions. The Bedrock plugin has a similar per-delta pattern but requires a separate Plugin SDK boundary decision and is not changed here.

User Impact

Large tool calls continue streaming responsively instead of spending progressively more CPU on argument previews. Completed arguments remain exact, and terminal-only empty tool calls continue to work.

Evidence

Anthropic Messages benchmark:

args total deltas before after
32KB 32 42.2ms 7.5ms
128KB 128 1160.9ms 43.8ms
512KB 512 >600s 2044.6ms
  • Terminal-only proxy regression: the focused test fails before the compatibility repair with stopReason: "error"; it passes after preserving {} for toolcall_start → toolcall_end with no deltas.
  • Focused validation: OPENCLAW_VITEST_MAX_WORKERS=2 node scripts/run-vitest.mjs src/agents/runtime/proxy.test.ts src/worker/inference-stream.runtime.test.ts packages/ai/src/transports/anthropic-transport-stream.test.ts packages/ai/src/transports/openai-responses-stream-parity.test.ts packages/ai/src/transports/openai-responses-stream-terminal-recovery.test.ts — 190 tests passed across both shards.
  • node scripts/check-changed.mjs — passed all selected format, typecheck, lint, max-lines, cycle, and architecture guards.
  • pnpm build — passed with no ineffective dynamic-import warning.
  • .agents/skills/autoreview/scripts/autoreview --mode uncommitted — clean; no accepted or actionable findings.
  • Exact-head CI: run 32643485122, attempt 2 passed for 2fbc4b29398964af1e8992cf1634697d27b5aba3.
  • OpenAI Responses runtime module: 672 lines, with no max-lines suppression.
  • Current PR surface: production +272/-108 (net +164); tests +300.

@vyctorbrzezowski vyctorbrzezowski self-assigned this Aug 23, 2026
@clawsweeper

clawsweeper Bot commented Aug 23, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added size: M maintainer Maintainer-authored PR labels Aug 23, 2026
@vyctorbrzezowski
vyctorbrzezowski marked this pull request as ready for review August 23, 2026 09:09
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 23, 2026
@clawsweeper

clawsweeper Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 23, 2026, 11:30 AM ET / 15:30 UTC.

ClawSweeper review

What this changes

This PR refreshes parsed previews of streamed tool-call arguments at geometric size checkpoints across AI transports, proxy streaming, and worker inference, while preserving exact terminal arguments.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep open for maintainer review. The patch appears to repair the repeated full-buffer parsing path, but it intentionally makes interim parsed argument snapshots stale between checkpoints; the MEMBER-authored, maintainer-labelled PR needs an explicit compatibility decision before merge.

Priority: P2
Reviewed head: 35799803955ae4685cf32ddc8294eceba72418d9
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch and focused boundary tests are coherent; the remaining merge question is compatibility of intentionally stale preview snapshots.
Proof confidence 🌊 off-meta tidepool Not applicable: Not applicable: the PR author is a repository MEMBER; its body nonetheless provides an after-fix benchmark and focused validation evidence.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Not applicable: the PR author is a repository MEMBER; its body nonetheless provides an after-fix benchmark and focused validation evidence.
Evidence reviewed 6 items Current-main defect: Current main reparses the entire accumulated OpenAI Responses argument buffer on every delta, establishing the reported quadratic work in an owned stream path.
Repair and terminal invariant: The PR schedules preview parses geometrically, while the Anthropic terminal path still passes the full buffered JSON through the shared terminal validator before emitting toolcall_end.
Worker sibling boundary: The worker-side producer reconciles a completed tool call by emitting its complete JSON when no argument delta was sent, so the adapter's strict terminal parse receives a complete value.
Findings None None.
Security None None.

Live Verification

Command: OPENCLAW_VITEST_MAX_WORKERS=2 node scripts/run-vitest.mjs src/worker/inference-stream.runtime.test.ts

Result: FAIL (partial) — step 2 expect_output delays worker tool argument previews while preserving exact terminal arguments: expected terminal output was not visible within 30 seconds: "delays worker tool argument previews while preserving exact terminal arguments"

runner@runnervm76f27:/tmp/clawsweeper-live-proof-128166-R9aHNr/target$ OPENCLAW_VITEST_MAX_WORKERS=2 node scripts/run-vitest.mjs src/worker/inference-stream.run
time.test.ts
[test] starting test/vitest/vitest.unit.config.ts
OPENCLAW_VITEST_MAX_WORKERS=2 node scripts/run-vitest.mjs src/worker/inference-stream.runtime.test.ts

 RUN  v4.1.10 /tmp/clawsweeper-live-proof-128166-R9aHNr/target

 ✓  unit  src/worker/inference-stream.runtime.test.ts (1 test) 68ms

 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  15:31:23
   Duration  1.38s (transform 1.01s, setup 735ms, import 327ms, tests 68ms, environment 0ms)

[test] passed 1 Vitest shard in 8.40s
runner@runnervm76f27:/tmp/clawsweeper-live-proof-128166-R9aHNr/target$ OPENCLAW_VITEST_MAX_WORKERS=2 node scripts/run-vitest.mjs src/worker/inference-stream.run
time.test.ts
[test] starting test/vitest/vitest.unit.config.ts

 RUN  v4.1.10 /tmp/clawsweeper-live-proof-128166-R9aHNr/target

 ✓  unit  src/worker/inference-stream.runtime.test.ts (1 test) 37ms

 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  15:31:32
   Duration  726ms (transform 335ms, setup 316ms, import 216ms, tests 37ms, environment 0ms)

[test] passed 1 Vitest shard in 7.90s
runner@runnervm76f27:/tmp/clawsweeper-live-proof-128166-R9aHNr/target$





















Assertions:

  • FAIL expect_output: delays worker tool argument previews while preserving exact terminal arguments

How this fits together

Model providers emit tool-call JSON in chunks. AI transports plus the proxy and worker adapters assemble those chunks for progress events, then validate the complete arguments before a tool call becomes executable.

flowchart LR
  A[Provider stream] --> B[Tool argument chunks]
  B --> C[Transport or adapter accumulator]
  C --> D[Geometric preview checkpoint]
  D --> E[Interim stream events]
  C --> F[Terminal argument validation]
  F --> G[Executable tool call]
Loading

Decision needed

Question Recommendation
Should OpenClaw formally accept bounded staleness in interim parsed tool-argument previews, with exact arguments guaranteed only at the terminal event? Confirm preview semantics: Merge with the explicit contract that raw deltas stream immediately while parsed previews are best-effort until terminal finalization.

Why: The implementation changes observable preview timing across several stream surfaces; source proves final execution correctness but cannot establish every external consumer's compatibility expectation.

Before merge

  • Resolve merge risk (P1) - Interim arguments snapshots now remain stale until 512 characters and later geometric checkpoints; consumers that treated previews as authoritative could observe a compatibility change before toolcall_end.
  • Resolve merge risk (P1) - This bug repair has a positive production delta (+164); the added per-stream schedules and terminal-boundary handling appear necessary, but maintainers should retain the single shared scheduling policy rather than allow path-specific variants.
Agent review details

Security

None.

PR surface

Source +164, Tests +300. Total +464 across 14 files.

View PR surface stats
Area Files Added Removed Net
Source 11 272 108 +164
Tests 3 300 0 +300
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 572 108 +464

Review metrics

Metric Value Why it matters
Production versus test delta production +164 net; tests +300 The production growth adds shared checkpoint state and terminal handling across stream owners; tests cover three representative boundaries.

Stored data model

Persistent data-model change detected: durable storage schema: src/worker/inference-stream.runtime.test.ts, durable storage schema: src/worker/inference-stream.runtime.ts, serialized state: packages/ai/src/transports/anthropic-transport-stream.test.ts, serialized state: src/agents/runtime/proxy.test.ts, unknown-data-model-change: src/worker/inference-stream.runtime.test.ts, unknown-data-model-change: src/worker/inference-stream.runtime.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Confirm bounded preview staleness (recommended)
    Accept geometric preview updates only if stream consumers are documented or verified to use raw deltas or the terminal tool call for authoritative arguments.
  2. Keep eager preview parsing
    Pause this PR if parsed preview freshness on every delta is a required compatibility promise.

Technical review

Best possible solution:

Keep raw deltas and terminal parsing authoritative, and merge only once maintainers confirm that checkpointed parsed previews are compatible with the stream-consumer contract.

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

Yes — source-reproducible: current main reparses the growing argument buffer for every streamed delta in the affected transport path.

Is this the best way to solve the issue?

Yes, subject to the preview-compatibility decision: one shared geometric schedule at the accumulators removes quadratic preview work while existing terminal validation preserves executable arguments.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: The defect degrades streamed tool-call responsiveness and CPU use but does not establish an emergency availability or security impact.
  • merge-risk: 🚨 compatibility: The PR deliberately changes when existing consumers observe parsed preview arguments during a stream.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Not applicable: the PR author is a repository MEMBER; its body nonetheless provides an after-fix benchmark and focused validation evidence.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Authored the prior AI terminal-finalization refactor and is the available current-history routing signal for the shared parser contract. (role: terminal argument contract refactor author; confidence: medium; commits: 37c7de0148de; files: packages/ai/src/transports/transport-stream-shared.ts, packages/ai/src/utils/json-parse.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Confirm that external stream consumers do not require parsed arguments to refresh on every delta.

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 (6 earlier review cycles)
  • reviewed 2026-08-23T09:21:44.157Z sha 7b035a8 :: found issues before merge. :: [P2] Apply the schedule to the proxy reassembler
  • reviewed 2026-08-23T09:27:16.570Z sha 7b035a8 :: needs changes before merge. :: [P2] Apply the schedule to the proxy reassembler
  • reviewed 2026-08-23T10:07:29.298Z sha 7b035a8 :: found issues before merge. :: [P2] Schedule and finalize proxy tool arguments
  • reviewed 2026-08-23T10:34:25.986Z sha f4bc9ab :: found issues before merge. :: [P1] Preserve terminal-only proxy tool calls
  • reviewed 2026-08-23T13:56:10.857Z sha 2fbc4b2 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-23T14:40:20.771Z sha 2fbc4b2 :: needs maintainer review before merge. :: none

@vyctorbrzezowski vyctorbrzezowski changed the title improve: keep streaming responsive while large tool call arguments assemble Keep streaming responsive while large tool call arguments assemble Aug 23, 2026
@vyctorbrzezowski vyctorbrzezowski changed the title Keep streaming responsive while large tool call arguments assemble perf(ai): keep streaming responsive while large tool call arguments assemble Aug 23, 2026
@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Aug 23, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. and removed P2 Normal backlog priority with limited blast radius. labels Aug 23, 2026
@vyctorbrzezowski

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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. and removed P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 23, 2026
…hedule

Every input_json_delta re-parsed the entire accumulated argument buffer
(quote scan, strict parse attempt, repair scan, partial parse), making
assembly quadratic in argument size. A 128KB tool call spent ~1.2s of CPU
on re-parsing alone while blocking token delivery; previews are
preview-only by contract since the terminal parse re-reads the full
buffer authoritatively at content_block_stop.

Refresh previews on a geometric length checkpoint instead: bounded
staleness, linear total work. Applied across every accumulating
packages/ai transport/provider surface sharing the invariant.

(hook bypassed per run-node-tool.sh contract: no local node_modules in
this worktree and pnpm install is out of scope; oxfmt --check green on
all staged files via sibling checkout binary.)
@vyctorbrzezowski
vyctorbrzezowski force-pushed the perf/tool-call-argument-assembly branch from 2fbc4b2 to 3579980 Compare August 23, 2026 15:23
@vyctorbrzezowski

Copy link
Copy Markdown
Member Author

Land-ready verification on head 35799803955ae4685cf32ddc8294eceba72418d9:

  • Maintainer decision accepted bounded-stale interim argument previews; terminal arguments remain exact and authoritative.
  • Focused boundary proof: node scripts/run-vitest.mjs packages/ai/src/transports/anthropic-transport-stream.test.ts src/agents/runtime/proxy.test.ts src/worker/inference-stream.runtime.test.ts (151 passed).
  • Anti-slop proof: reverting the production owner independently for transport, proxy, and worker made each new regression fail on the former per-delta preview behavior; restoring the head made all pass.
  • node scripts/check-changed.mjs passed.
  • Fresh autoreview returned no accepted/actionable findings.
  • Exact-head CI run 32648424818 passed.
  • Native review-validate-artifacts and OPENCLAW_TESTBOX=1 scripts/pr prepare-run 128166 passed using hosted exact-head evidence.

Known proof gap: no live external-provider run; this deterministic member-authored performance repair is covered by owner-boundary regressions, benchmark evidence, and exact-head CI.

@vyctorbrzezowski
vyctorbrzezowski merged commit ddd12ca into main Aug 23, 2026
225 checks passed
@vyctorbrzezowski

Copy link
Copy Markdown
Member Author

Merged via squash.

@vyctorbrzezowski
vyctorbrzezowski deleted the perf/tool-call-argument-assembly branch August 23, 2026 15:37
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 24, 2026
…ssemble (openclaw#128166)

* perf(ai): refresh streamed tool-call argument previews on a length schedule

Every input_json_delta re-parsed the entire accumulated argument buffer
(quote scan, strict parse attempt, repair scan, partial parse), making
assembly quadratic in argument size. A 128KB tool call spent ~1.2s of CPU
on re-parsing alone while blocking token delivery; previews are
preview-only by contract since the terminal parse re-reads the full
buffer authoritatively at content_block_stop.

Refresh previews on a geometric length checkpoint instead: bounded
staleness, linear total work. Applied across every accumulating
packages/ai transport/provider surface sharing the invariant.

(hook bypassed per run-node-tool.sh contract: no local node_modules in
this worktree and pnpm install is out of scope; oxfmt --check green on
all staged files via sibling checkout binary.)

* perf(agents): throttle proxied tool argument previews

* fix(agents): preserve terminal-only proxy tool calls
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L 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.

Streaming tool-call arguments still parsed in O(n^2) on Anthropic and OpenAI Responses paths

1 participant