Skip to content

perf(tool-call-repair): stop re-parsing the whole response for a bare bracket - #120067

Closed
harjothkhara wants to merge 1 commit into
openclaw:mainfrom
harjothkhara:oss-find/119478-normalizer-quadratic
Closed

harjothkhara wants to merge 1 commit into
openclaw:mainfrom
harjothkhara:oss-find/119478-normalizer-quadratic

Conversation

@harjothkhara

Copy link
Copy Markdown
Contributor

What Problem This Solves

Closes #119478.

Streaming an answer that contains many [ characters re-parses the entire accumulated response as Markdown once per bracket-shaped delta. The work is quadratic in response size and changes nothing — the emitted text is byte-identical with and without it.

Measured through normalizePlainTextToolCallStreamEvents, counting characters handed to resolveProtectedRanges:

response    re-parses    characters re-parsed
10.3 KB          450                 762,430
21.0 KB          900               3,107,155
42.3 KB        1,800              12,589,105

Response size doubles, characters re-parsed quadruple. The identical document with ( instead of [ costs zero re-parses.

This contradicts the expectations pinned in this file's own coverage: stream-normalizer.test.ts asserts resolverCalls is 0 for ordinary streamed text and resolvedLengths.length <= 3 once a candidate-shaped delta appears.

Why This Change Was Made

Tokenizers emit [ as its own token, so a bracket-dense answer ends many deltas exactly at [. At grammar.ts:203 a bracket opener with no name characters yet produces:

const firstName = text.slice(firstNameStart, cursor);   // ""
if (cursor === text.length && "tool".startsWith(firstName)) {
  return { kind: "prefix" };
}

"tool".startsWith("") is true, so a bare [ is reported as a potential call start. stream-normalizer.ts then materializes the whole accumulated response and hands it to resolveProtectedRanges.

Tracing one bracket showed three resolutions, only one of them expensive:

resolve(len 74)   <- prefix + "["      the whole response, per bracket
resolve(len  1)   <- "["               candidate buffer only
resolve(len 10)   <- "[section-0"      candidate buffer only

A bare opener carries no evidence: the empty name matches every tool. The next delta brings the name and settles it against the candidate buffer, which is already cheap. So the fix skips protection resolution for an opener that has no name yet, and changes nothing else.

Protection is still resolved for every candidate that carries name characters, so a real [read] is unaffected. Scope is one guard plus a predicate — no change to the resolver contract, the matcher, or the candidate state machine.

User Impact

Long bracket-dense answers — [tool.poetry], [Unit], pasted [2026-08-04T…] INFO log lines, i.e. routine coding-agent output — stop burning CPU proportional to the square of the response.

Protection work becomes linear:

response    characters re-parsed     before
10.3 KB                    1,840    762,430
21.0 KB                    3,790  3,107,155
42.3 KB                    7,690 12,589,105

Emitted text is byte-identical before and after, at every size.

Honest limits:

  • This bounds the number of whole-response re-parses; it does not make the remaining ones incremental. A response that genuinely contains many named tool-call candidates still resolves once per candidate.
  • Measured as characters handed to the resolver, not wall-clock, so the numbers are deterministic and machine-independent. The issue reports 3.2 s of CPU for the 35 KB case.

Separate pre-existing defect found while verifying this, not fixed here and not caused by this change. A fenced tool call whose opener arrives as its own delta has its body silently deleted:

input:   ```\n[read]\n{"path":"x.txt"}\n[/read]\n```
emitted: ```\n```

The same call in a single delta is preserved correctly. I confirmed this reproduces byte-identically on unmodified main, so it predates this patch — the pending-candidate classification resolves protected ranges against the candidate buffer without the accumulated fence prefix, so a fenced call reads as executable. That is user-visible content loss and deserves its own issue; I did not widen this PR to chase it.

Evidence

Production diff is +15 net LOC in one file (tests counted separately):

16  1  packages/tool-call-repair/src/stream-normalizer.ts
--- tests ---
39  0  packages/tool-call-repair/src/stream-normalizer.test.ts

Proof command:

node scripts/run-vitest.mjs packages/tool-call-repair

The regression test sits directly beside the two pinned expectations it extends, and asserts the shape rather than a timing: a 4x longer response must not cost more than 8x the protection work, and the absolute cost must stay proportional to the candidates.

Negative control. With only stream-normalizer.ts restored to origin/main and the new test kept, it fails for the right reason:

FAIL  keeps protection work linear when streamed text is bracket-dense
AssertionError: expected 6299605 to be less than 2970440

With the patch, the same measurement is 7,690.

Blast radius, found by symbol across the whole repo — every consumer of the normalizer:

packages/tool-call-repair/src/index.ts
src/agents/embedded-agent-runner/run/attempt-stream.ts
src/agents/embedded-agent-runner/run/attempt.tool-call-normalization.ts
src/plugin-sdk/provider-stream-shared.ts
node scripts/run-vitest.mjs packages/tool-call-repair \
  src/agents/embedded-agent-runner/run/attempt.tool-call-normalization.test.ts \
  src/plugin-sdk/provider-stream-shared.test.ts \
  src/agents/embedded-agent-runner/stream-resolution.test.ts
-> all shards passed (155 package tests, including every fence-protection case)

Typecheck node scripts/run-tsgo.mjs -p tsconfig.core.json clean; oxfmt --check and oxlint clean; git diff --check clean.

Reviewed with codex review --base origin/main. It raised one P1 — the fenced-split content loss above — attributing it to this patch. Running the same fixture against restored upstream sources produced byte-identical output, proving it pre-existing; it is reported above rather than folded into this diff.

No Crabbox/Testbox on this machine, so cross-OS breadth is CI's.

AI-assisted: investigated, implemented and proved with Claude Code; the diff and evidence above are human-reviewed.

@harjothkhara
harjothkhara marked this pull request as ready for review August 6, 2026 23:40
@harjothkhara

Copy link
Copy Markdown
Contributor Author

Closing this — the perf change is not behaviour-preserving, and the PR body contains a claim of mine that is wrong. Correcting it here rather than editing it away.

The body says the fenced-call content loss "reproduces byte-identically on unmodified main, so it predates this patch". That is false. The regression is introduced by this patch.

codex review flagged it correctly and I misattributed it. My baseline check was:

git stash push -q -- <file> 2>/dev/null || git checkout origin/main -- <file>

The file was committed and clean, so git stash push exited 0 and the || fallback never ran — I measured the patched file and reported it as upstream.

Re-verified with a hash-checked toggle of only stream-normalizer.ts, one probe, separate module caches:

stream-normalizer.ts sha256 (16) fenced call split at the opener
origin/main 9730d5998b7f2caa preserved
this branch d1cb976de5a79721 body deleted

Repro — a fenced example whose [ opener arrives as its own delta:

input:   ```\n[read]\n{"path":"x.txt"}\n[/read]\n```
main:    ```\n[read]\n{"path":"x.txt"}\n[/read]\n```
this PR: ```\n```

Mechanism: skipping protection resolution for a nameless opener leaves it buffered as a pending candidate, and the pending classification resolves protected ranges against the candidate buffer without the accumulated fence prefix — so a fenced call reads as executable and its text deltas are dropped. The existing suite misses it because no case splits a fenced call at the opener.

The measurements in the body still hold and the underlying defect in #119478 is real — protection work is quadratic in response size (12.6M characters re-parsed for a 42 KB answer, byte-identical output). But the fix shape here is wrong: a correct version has to keep the accumulated protection context available to the pending classification while still refuting non-matching names without resolving. That is a change to the protected-range contract and belongs with the maintainers rather than in a drive-by patch.

Leaving #119478 open. Apologies for the noise.

AI-assisted: investigated and written with Claude Code.

@harjothkhara

Copy link
Copy Markdown
Contributor Author

Closing: not behaviour-preserving (see the correction above). #119478 stays open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

tool-call-repair: streamed bracket-dense answers re-parse the whole response as Markdown per delta (quadratic normalizer CPU)

1 participant