Skip to content

fix: bound token estimation cost for large context inputs - #450

Open
basudevghadai1999 wants to merge 1 commit into
Conway-Research:mainfrom
basudevghadai1999:fix/bounded-token-estimation
Open

basudevghadai1999 wants to merge 1 commit into
Conway-Research:mainfrom
basudevghadai1999:fix/bounded-token-estimation

Conversation

@basudevghadai1999

Copy link
Copy Markdown

Problem

estimateTokens() in src/agent/context.ts tokenized its whole input with js-tiktoken (cl100k_base). The pure-JS BPE merge is roughly quadratic in the length of a single unbroken piece: measured ~11s for 16k chars of x, an extrapolated ~100s for 50k, and hours for 500k. Unbroken CJK costs ~0.4s per 1k chars. estimateTurnTokens calls it for every turn, and buildContextMessages uses the result for its summarization split, so three tests in context-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

  • Up to 1,000 chars: exact tokenization, as before.
  • Larger inputs: one linear pass over whitespace runs and words.
    • Short words (ASCII <= 24 chars, non-ASCII <= 8) and whitespace runs <= 128 chars are copied into a masked string and tokenized exactly, in chunks of ~4k chars cut only at whitespace-run boundaries (+1 token slack per chunk).
    • Long words, oversized whitespace runs, and everything past a 96,000-char work budget are not tokenized. They are charged their UTF-8 byte length (a byte-level BPE never yields more tokens than bytes). A one-char # placeholder stands in for each long word so surrounding whitespace is still tokenized in place.
    • Non-ASCII words and whitespace runs longer than 16 chars count 4x toward the budget because BPE is slower on them.
  • The existing len / 4 floor is kept.
  • Tokenizer work is capped at 96,000 chars total in calls of at most 4,248 chars (about 24 calls), independent of input size.

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-tiktoken throws on strings like <|endoftext|>, and the previous path then fell back to len / 3.5. A 900-char base64 string plus that marker estimated 262 against an actual 649 (0.40x). estimateTokens now uses its own cl100k_base encoder with encode(text, [], []), so these strings are ordinary text. createTokenCounter() and src/memory/context-manager.ts are 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.

  • Work bounds at 500KB for 11 input types, asserted deterministically by spying on encode (total chars, per-call chars, call count; no wall-clock assertions).
  • No underestimation for: a non-plain 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.
  • Chunk-boundary behavior across several patterns and offsets, plus a check that no chunk starts mid-word.
  • Ordinary prose (<= 1.15x), TypeScript and markdown (<= 1.8x) accuracy.
  • Mutation checks confirmed the tests fail when dense content is undercharged, chunks are cut mid-word, oversized whitespace is not charged, or special tokens are not treated as text.

Performance

Input (500KB) Before After
50k unbroken x ~100s (extrapolated) ~1 ms
500k unbroken x hours (extrapolated) ~5 ms
prose n/a ~40 ms
gibberish / 24-char words n/a ~50-65 ms
CJK words, long whitespace runs (worst cases) n/a ~90-130 ms

The 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

  • Full test suite: 64 files, 1,697 tests passed, no timeouts
  • pnpm typecheck: passed
  • pnpm build: passed (0 warnings)
  • Run on Node 24; Node 26 cannot compile better-sqlite3@11.10.0, which is unrelated to this change.

Limitations

  • Tokenizer mismatch. Everything is calibrated to cl100k_base. The provider's real tokenizer differs, so budgets should keep headroom.
  • No formal guarantee. The byte-length bound is a property of byte-level BPE, and the whitespace/chunk-boundary slack is a design argument validated by experiments, not a proof. In 4,000 random documents chunk cuts never lowered the total, so the +1 per chunk is a precaution that no test can demonstrate.
  • Deliberate overestimation. Inputs beyond the work budget (about 96k chars) are charged ~1 token per char, roughly 4x high for prose. Unbroken dense runs are 1.3-2.5x high, and whitespace runs just over 128 chars can be far higher (up to 44x on a synthetic case) because they are charged their byte length.
  • Exact path is still quadratic. An unbroken 1,000-char CJK run in the exact path can take ~0.4s; unchanged from before.
  • Pending input is not budgeted. pendingInput (up to 10 inbox messages of 50KB each) is appended in buildContextMessages without being counted against the existing context budget. That is a separate, larger gap and is intentionally not changed here.
  • context.ts now holds its own js-tiktoken encoder rather than sharing createTokenCounter()'s (about 80ms extra one-time load, no shared cache).

🤖 Generated with Claude Code

Co-Authored-By: Claude Sonnet 5.5 <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