[Bug] Cut-off JSON tool calls with escaped quotes parse in quadratic time
Description
Follow-up to #1765, from @addyCooks's review.
findJSONObjectEnd only caches objects it sees outside a string. A cut-off call leaves a string open, and a \" then keeps the scan out of step with the quotes. No later call is cached, so each one is scanned again to the end of the reply.
Steps to Reproduce
const call = '{"name":"write_file","arguments":{"path":"a.ts","content":"console.log(\\"hi\\");';
parseToolCalls(Array(3000).fill(call).join('\n'));
Expected Behavior
Linear time, as with the same calls without \" (2.3 ms).
Actual Behavior
Quadratic: 969 ms, vs 54 ms before #1765. 8x the input takes 63x the time.
Proposed Fix
- Stop a scan at a raw newline inside a string (that object can't parse anyway).
- Cap total scan work per reply as a backstop.
Additional Context
On main only, not released yet.
- [x] I have searched existing issues to ensure this is not a duplicate
- [x] I can reproduce this issue consistently
hello, @addyCooks please verify this and assign it to me
Thanks @puri-adityakumar, I reproduced this on main (about 1.6 s for 3000 cut-off calls with ", and 8x the input takes ~64x the time), so it's a valid follow-up to #1765. Assigning it to you, go ahead.
Both parts of your fix are needed. I tried the raw-newline stop on a scratch copy and it fixes your repro, but if the cut-off calls are separated by spaces instead of newlines it's still quadratic (about 2 s at 300 KB). So please also add the cap on total scan work per reply, with a test for each case.