Cap tiktoken input length in countTokens to avoid O(n^2) hang#332
Open
stevegonzalez721-ux wants to merge 1 commit into
Open
Conversation
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
createTokenCounter().countTokens()runs js-tiktoken'sencode()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 thecontext-hardeningsuite to hang (the worker sits at ~98% CPU and the per-test timeout never fires because the event loop is blocked).Fix
countTokensonly uses the result for budget estimation, and the underlying text is truncated before rendering. So above an 8k-char cap, fall back to the existingchar / 3.5heuristic 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