Repository navigation
fix: bound token estimation cost for large context inputs - #450
Open
basudevghadai1999 wants to merge 1 commit into
Open
basudevghadai1999 wants to merge 1 commit into
basudevghadai1999 wants to merge 1 commit into
Conversation
Co-Authored-By: Claude Sonnet 5.5 <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
estimateTokens()insrc/agent/context.tstokenized its whole input withjs-tiktoken(cl100k_base). The pure-JS BPE merge is roughly quadratic in the length of a single unbroken piece: measured ~11s for 16k chars ofx, an extrapolated ~100s for 50k, and hours for 500k. Unbroken CJK costs ~0.4s per 1k chars.estimateTurnTokenscalls it for every turn, andbuildContextMessagesuses the result for its summarization split, so three tests incontext-hardening.test.ts(50k-500k char turns) never finished and the full suite hung. Because untrusted inbound messages become turn input, this is also a CPU-exhaustion vector.Solution: budgeted mask-and-encode
#placeholder stands in for each long word so surrounding whitespace is still tokenized in place.len / 4floor is kept.An earlier iteration sampled a few windows and extrapolated. Review showed that could undercount adversarial input by ~1.6x (for example one non-plain word per sample window disabled its calibration) and that whitespace runs were not actually covered. It was replaced by this design.
Special-token handling
js-tiktokenthrows on strings like<|endoftext|>, and the previous path then fell back tolen / 3.5. A 900-char base64 string plus that marker estimated 262 against an actual 649 (0.40x).estimateTokensnow uses its owncl100k_baseencoder withencode(text, [], []), so these strings are ordinary text.createTokenCounter()andsrc/memory/context-manager.tsare untouched.Regression coverage (
context-hardening.test.ts)83 tests in the file; all pre-existing tests are unchanged. References are full-string tokenization, not chunked counts.
encode(total chars, per-call chars, call count; no wall-clock assertions).1.every 500 chars, lowercase/uppercase/mixed-case gibberish, base64/hex/symbol words, single digits and letters, tab/space/newline/CRLF separators, oversized whitespace, unbroken dense runs, long words, dense Unicode (CJK, emoji), special-token strings, and a seeded 60-document property test.Performance
xxThe three formerly hanging tests now pass, and the full suite completes.
Adversarial estimate vs. real tokenizer count was 1.00x for the gibberish, separator and Unicode-word cases above. Ordinary content measured 1.07x (prose), 1.12-1.20x (markdown docs), 1.38-1.50x (TypeScript) and 1.37x (
pnpm-lock.yaml). No tested case was an underestimate.Validation
pnpm typecheck: passedpnpm build: passed (0 warnings)better-sqlite3@11.10.0, which is unrelated to this change.Limitations
cl100k_base. The provider's real tokenizer differs, so budgets should keep headroom.pendingInput(up to 10 inbox messages of 50KB each) is appended inbuildContextMessageswithout being counted against the existing context budget. That is a separate, larger gap and is intentionally not changed here.context.tsnow holds its ownjs-tiktokenencoder rather than sharingcreateTokenCounter()'s (about 80ms extra one-time load, no shared cache).🤖 Generated with Claude Code