Skip to content

Cap tiktoken input length in countTokens to avoid O(n^2) hang#332

Open
stevegonzalez721-ux wants to merge 1 commit into
Conway-Research:mainfrom
stevegonzalez721-ux:fix/tiktoken-quadratic-tokenize-cap
Open

Cap tiktoken input length in countTokens to avoid O(n^2) hang#332
stevegonzalez721-ux wants to merge 1 commit into
Conway-Research:mainfrom
stevegonzalez721-ux:fix/tiktoken-quadratic-tokenize-cap

Conversation

@stevegonzalez721-ux

Copy link
Copy Markdown

Problem

createTokenCounter().countTokens() runs js-tiktoken's encode() on the full input string. js-tiktoken's BPE is O(n²) on long whitespace-free runs, so tokenizing a large tool result (e.g. a 10k+ char output with no spaces) pegs a core and blocks the event loop for minutes. This is reproducible on both Linux and Windows and causes the context-hardening suite to hang (the worker sits at ~98% CPU and the per-test timeout never fires because the event loop is blocked).

Fix

countTokens only uses the result for budget estimation, and the underlying text is truncated before rendering. So above an 8k-char cap, fall back to the existing char / 3.5 heuristic instead of paying the quadratic cost. Below the cap, behavior is unchanged.

Test

Adds a regression test asserting that a 50k-char whitespace-free string returns the heuristic count promptly (<1s) rather than hanging.

🤖 Generated with Claude Code

js-tiktoken's BPE is quadratic on long whitespace-free runs, so tokenizing
a large tool result (e.g. 10k+ chars with no spaces) can peg a core and
block the event loop for minutes — the context-hardening suite hangs on it.

countTokens only uses the count for budget estimation and the underlying
text is truncated before rendering, so above an 8k-char cap fall back to the
existing char/3.5 heuristic instead of paying the quadratic cost.

Adds a regression test that a 50k-char whitespace-free string returns the
heuristic count promptly (<1s) instead of hanging.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant