From d993b2c3725fb62536c6cb3196416f21284b7c1a Mon Sep 17 00:00:00 2001 From: "ScrewTSW (public-projects)" Date: Thu, 27 Aug 2026 15:24:33 +0200 Subject: [PATCH 1/3] perf(core): cache per-message token counts `compileChatMessages` counts tokens for every message on every request, and nothing memoised the result. For non-GPT models `encodingForModel` returns `llamaEncoding` - a pure-JS BPE running synchronously on the extension host - so each turn re-tokenised the entire conversation from scratch. Turn N paid again for all N-1 previous turns. Measured at ctx 288768 before this change: a 20-turn session with 128KB tool outputs spent ~4.5s inside `compileChatMessages` before a single byte reached the model. VS Code reports this as an unresponsive extension host; a CPU profile attributed ~85% of a 6s sample to the BPE merge loop (`addToMergeQueue`, `encode`, PriorityQueue `pop`). Token counts are a pure function of (model, message), so memoising is exact. The cache is keyed on content, not object identity: the compiler rebuilds every message (`msgs.map((m) => ({ ...m }))`) and messages cross the messenger boundary as JSON, so a WeakMap could never hit. Keys are SHA-256 digests over the fields that affect the count. Fixed-size keys are what make the entry cap an actual memory bound - embedding message content instead would let 4096 entries of large tool outputs retain gigabytes after the conversation was released, and would keep raw prompt and tool text in a long-lived map. The digest costs ~0.66ms for 1MB against ~3187ms to tokenize the same text, so it does not erode the win. Parts are length- prefixed before hashing so content cannot forge another message's key. After, same simulated sessions: - growing 20-turn session, 32KB/turn: 92ms cold -> 1ms warm, 93.5% hit rate - 20 turns x 128KB: 255ms cold -> 2ms warm Verified the cache does not change results: compiled messages, didPrune and contextPercentage are byte-identical across cached and uncached runs at four context sizes, including pruning paths. Adds 9 tests covering hits, cross-instance hits, model/role/tool-call key separation, fixed-size keys, absence of raw content in keys, and eviction. --- core/llm/countTokens.ts | 14 +++ core/llm/tokenCountCache.test.ts | 154 +++++++++++++++++++++++++++++++ core/llm/tokenCountCache.ts | 144 +++++++++++++++++++++++++++++ 3 files changed, 312 insertions(+) create mode 100644 core/llm/tokenCountCache.test.ts create mode 100644 core/llm/tokenCountCache.ts diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index b742d70b0f0..f295ae3ed21 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -20,6 +20,7 @@ import { AsyncEncoder, LlamaAsyncEncoder } from "./asyncEncoder.js"; import { DEFAULT_PRUNING_LENGTH } from "./constants.js"; import { getAdjustedTokenCountFromModel } from "./getAdjustedTokenCount.js"; import llamaTokenizer from "./llamaTokenizer.js"; +import { withCachedMessageTokens } from "./tokenCountCache.js"; interface Encoding { encode: Tiktoken["encode"]; decode: Tiktoken["decode"]; @@ -179,6 +180,19 @@ function countToolsTokens(tools: Tool[], modelName: string): number { function countChatMessageTokens( modelName: string, chatMessage: ChatMessage, +): number { + // Memoised: this is a pure function of (modelName, chatMessage), and the + // compiler calls it for every message on every request. Without the cache a + // long session re-tokenises its whole history each turn, blocking the + // extension host for seconds. See tokenCountCache.ts. + return withCachedMessageTokens(modelName, chatMessage, () => + computeChatMessageTokens(modelName, chatMessage), + ); +} + +function computeChatMessageTokens( + modelName: string, + chatMessage: ChatMessage, ): number { // Doing simpler, safer version of what is here: // https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb diff --git a/core/llm/tokenCountCache.test.ts b/core/llm/tokenCountCache.test.ts new file mode 100644 index 00000000000..cedc5eb9537 --- /dev/null +++ b/core/llm/tokenCountCache.test.ts @@ -0,0 +1,154 @@ +import { ChatMessage } from "../index.js"; +import { + __resetTokenCountCacheForTests, + getTokenCountCacheKeysForTests, + getTokenCountCacheStats, + withCachedMessageTokens, +} from "./tokenCountCache.js"; + +describe("tokenCountCache", () => { + beforeEach(() => { + __resetTokenCountCacheForTests(); + }); + + const msg = (content: string): ChatMessage => + ({ role: "user", content }) as ChatMessage; + + it("computes on first call and serves the second from cache", () => { + let calls = 0; + const compute = () => { + calls++; + return 42; + }; + + expect(withCachedMessageTokens("m", msg("hello"), compute)).toBe(42); + expect(calls).toBe(1); + + expect(withCachedMessageTokens("m", msg("hello"), compute)).toBe(42); + expect(calls).toBe(1); // still 1 - served from cache + + const stats = getTokenCountCacheStats(); + expect(stats.hits).toBe(1); + expect(stats.misses).toBe(1); + }); + + // The compiler rebuilds message objects on every call + // (`msgs.map((m) => ({ ...m }))`), and messages also cross the messenger + // boundary as JSON. Identity-keyed caching (WeakMap) can therefore never + // hit; the key must be derived from content. + it("hits across distinct object instances with equal content", () => { + let calls = 0; + const compute = () => { + calls++; + return 7; + }; + + withCachedMessageTokens( + "m", + { role: "user", content: "abc" } as ChatMessage, + compute, + ); + withCachedMessageTokens( + "m", + { role: "user", content: "abc" } as ChatMessage, + compute, + ); + + expect(calls).toBe(1); + }); + + it("does not confuse different content", () => { + const compute = (n: number) => () => n; + + expect(withCachedMessageTokens("m", msg("aaa"), compute(1))).toBe(1); + expect(withCachedMessageTokens("m", msg("bbb"), compute(2))).toBe(2); + expect(withCachedMessageTokens("m", msg("aaa"), compute(99))).toBe(1); + }); + + it("keys on model - the same text tokenizes differently per tokenizer", () => { + const compute = (n: number) => () => n; + + expect(withCachedMessageTokens("llama", msg("x"), compute(10))).toBe(10); + expect(withCachedMessageTokens("gpt-4", msg("x"), compute(20))).toBe(20); + expect(withCachedMessageTokens("llama", msg("x"), compute(99))).toBe(10); + }); + + it("distinguishes messages that differ only by role", () => { + const compute = (n: number) => () => n; + + const user = { role: "user", content: "same" } as ChatMessage; + const assistant = { role: "assistant", content: "same" } as ChatMessage; + + expect(withCachedMessageTokens("m", user, compute(1))).toBe(1); + expect(withCachedMessageTokens("m", assistant, compute(2))).toBe(2); + }); + + it("distinguishes tool calls that differ only in arguments", () => { + const compute = (n: number) => () => n; + + const call = (args: string) => + ({ + role: "assistant", + content: "", + toolCalls: [ + { + id: "1", + type: "function", + function: { name: "f", arguments: args }, + }, + ], + }) as ChatMessage; + + expect(withCachedMessageTokens("m", call('{"a":1}'), compute(1))).toBe(1); + expect(withCachedMessageTokens("m", call('{"a":2}'), compute(2))).toBe(2); + }); + + // The entry-count cap alone does not bound memory: a key that embeds full + // message content means 4096 large tool outputs can retain hundreds of MiB + // (a 1MB message x 4096 is ~4 GiB) long after the conversation is released. + // Keys are fixed-size digests so worst-case memory is a function of the cap + // alone, and raw prompt/tool text is not retained by the cache. + it("stores fixed-size keys regardless of message size", () => { + const small = msg("x"); + const huge = msg("y".repeat(2 * 1024 * 1024)); + + withCachedMessageTokens("m", small, () => 1); + withCachedMessageTokens("m", huge, () => 2); + + const keys = getTokenCountCacheKeysForTests(); + expect(keys).toHaveLength(2); + + const [a, b] = keys.map((k) => k.length); + expect(a).toBe(b); + // Comfortably smaller than either message; a content-embedding key would + // be megabytes here. + expect(a).toBeLessThan(512); + }); + + it("does not retain raw message content in its keys", () => { + const secret = "correct-horse-battery-staple-" + "z".repeat(5000); + withCachedMessageTokens("m", msg(secret), () => 1); + + for (const key of getTokenCountCacheKeysForTests()) { + expect(key).not.toContain("correct-horse-battery-staple"); + } + }); + + it("evicts oldest entries past the cap so a long session cannot grow unbounded", () => { + const cap = getTokenCountCacheStats().maxEntries; + + for (let i = 0; i < cap + 50; i++) { + withCachedMessageTokens("m", msg(`msg-${i}`), () => i); + } + + expect(getTokenCountCacheStats().size).toBeLessThanOrEqual(cap); + + // The most recent entries must still be present. + let calls = 0; + withCachedMessageTokens("m", msg(`msg-${cap + 49}`), () => { + calls++; + return -1; + }); + expect(calls).toBe(0); + }); +}); diff --git a/core/llm/tokenCountCache.ts b/core/llm/tokenCountCache.ts new file mode 100644 index 00000000000..c03d81bb600 --- /dev/null +++ b/core/llm/tokenCountCache.ts @@ -0,0 +1,144 @@ +import { createHash } from "crypto"; + +import { ChatMessage } from "../index.js"; + +/** + * Memoises per-message token counts across `compileChatMessages` calls. + * + * Why this exists: the chat tokenizer for non-GPT models is a pure-JS BPE + * (`llamaTokenizer`) running synchronously on the extension host, and nothing + * cached its results. Every request re-tokenised the entire conversation from + * scratch, so turn N paid for all N-1 previous turns again. Measured at ctx + * 288768, a 20-turn session with 128KB tool outputs spent ~4.5s in + * `compileChatMessages` before a single byte reached the model - the host was + * blocked the whole time, which VS Code reports as an unresponsive extension. + * + * Keyed on content rather than object identity: `compileChatMessages` rebuilds + * every message (`msgs.map((m) => ({ ...m }))`) and messages cross the + * messenger boundary as JSON, so a `WeakMap` keyed on the object would never + * hit. Token counts are a pure function of (model, message), so a content key + * is exact - not an approximation. + */ + +// Keys are fixed-size digests, so this entry cap really does bound worst-case +// memory. That is the reason for hashing: an earlier version embedded message +// content in the key, where 4096 entries of large tool outputs could retain +// gigabytes long after the conversation itself was released. +const MAX_ENTRIES = 4096; + +const cache = new Map(); +let hits = 0; +let misses = 0; + +/** + * Builds the cache key: a SHA-256 digest over the fields that affect the count. + * + * Hashing keeps keys fixed-size, which is what makes the entry cap a real + * memory bound, and avoids retaining raw prompt or tool-output text in a + * long-lived map. The digest is cheap relative to the work being cached - + * ~0.66ms for 1MB versus ~3187ms to tokenize the same text - so it does not + * erode the win. + * + * SHA-256 collisions are not a practical concern at this cache size, and a + * collision would only mis-count tokens, not corrupt output. + * + * Only the fields `countChatMessageTokens` actually counts are included. + */ +function cacheKey(modelName: string, message: ChatMessage): string { + const parts: string[] = [modelName, message.role]; + + const content = message.content; + if (typeof content === "string") { + parts.push(content); + } else if (Array.isArray(content)) { + // Image parts contribute a flat token count, so their presence matters but + // their payload does not - avoid keying on base64 blobs. + for (const part of content) { + parts.push(part.type === "text" ? `t:${part.text}` : `i:${part.type}`); + } + } + + if ("toolCalls" in message && message.toolCalls) { + for (const call of message.toolCalls) { + parts.push(JSON.stringify(call)); + } + } + + if (message.role === "thinking") { + if (message.redactedThinking) parts.push(message.redactedThinking); + if (message.signature) parts.push(message.signature); + } + + if (message.role === "tool" && message.toolCallId) { + parts.push(message.toolCallId); + } + + // Length-prefix each part before hashing: any delimiter can also occur + // inside message content, which would let one message forge another's key + // and return a wrong token count. + const hash = createHash("sha256"); + for (const part of parts) { + hash.update(`${part.length}:`); + hash.update(part); + } + return hash.digest("base64"); +} + +/** + * Returns the cached token count for `message`, or computes and stores it. + * + * `compute` must be a pure function of the same (modelName, message) pair. + */ +export function withCachedMessageTokens( + modelName: string, + message: ChatMessage, + compute: () => number, +): number { + const key = cacheKey(modelName, message); + + const cached = cache.get(key); + if (cached !== undefined) { + hits++; + // Refresh recency: re-inserting moves the key to the end of Map iteration + // order, so eviction below drops genuinely cold entries rather than merely + // old ones. + cache.delete(key); + cache.set(key, cached); + return cached; + } + + misses++; + const value = compute(); + cache.set(key, value); + + if (cache.size > MAX_ENTRIES) { + // Map preserves insertion order, so the first key is the least recently + // used. Evict in a loop: a single delete is not enough if the cap is + // lowered or several entries are added before the next check. + for (const oldest of cache.keys()) { + cache.delete(oldest); + if (cache.size <= MAX_ENTRIES) break; + } + } + + return value; +} + +export function getTokenCountCacheStats(): { + size: number; + hits: number; + misses: number; + maxEntries: number; +} { + return { size: cache.size, hits, misses, maxEntries: MAX_ENTRIES }; +} + +export function getTokenCountCacheKeysForTests(): string[] { + return [...cache.keys()]; +} + +export function __resetTokenCountCacheForTests(): void { + cache.clear(); + hits = 0; + misses = 0; +} From 7d8d4e9fa6f736586a56a0b2bb86e6f54173de1a Mon Sep 17 00:00:00 2001 From: "ScrewTSW (public-projects)" Date: Thu, 27 Aug 2026 17:55:20 +0200 Subject: [PATCH 2/3] fix(core): normalize absent text-part text in cache key `stripImages` collects text parts with `.join("\n")`, which renders an absent `text` as "" - so a part with no text tokenizes identically to one with empty text. The cache key interpolated `part.text` instead, yielding "undefined", which both collided with a part whose text is literally "undefined" and split it from the empty-text case it should share. Either way a message could be served another message's token count. Push the type marker as its own key part rather than interpolating it, so it picks up the same length prefix as the content and cannot be forged. Both regression tests verified RED against the previous key. Co-Authored-By: Claude Opus 5 --- core/llm/tokenCountCache.test.ts | 47 ++++++++++++++++++++++++++++++++ core/llm/tokenCountCache.ts | 14 ++++++++-- 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/core/llm/tokenCountCache.test.ts b/core/llm/tokenCountCache.test.ts index cedc5eb9537..ab4dd5a9cde 100644 --- a/core/llm/tokenCountCache.test.ts +++ b/core/llm/tokenCountCache.test.ts @@ -108,6 +108,53 @@ describe("tokenCountCache", () => { // (a 1MB message x 4096 is ~4 GiB) long after the conversation is released. // Keys are fixed-size digests so worst-case memory is a function of the cap // alone, and raw prompt/tool text is not retained by the cache. + // `stripImages` joins text parts with `.join("\n")`, which renders an absent + // `text` as "". A key that interpolates `part.text` instead produces + // "undefined", so a part with no text and a part whose text is literally + // "undefined" share a key - and one is served the other's count. + it("separates a text part with absent text from the literal string 'undefined'", () => { + const part = (text?: string): ChatMessage => + ({ + role: "user", + content: [ + text === undefined ? { type: "text" } : { type: "text", text }, + ], + }) as unknown as ChatMessage; + + expect(withCachedMessageTokens("m", part(undefined), () => 1)).toBe(1); + expect(withCachedMessageTokens("m", part("undefined"), () => 2)).toBe(2); + + // And each keeps its own count on the way back out. + expect(withCachedMessageTokens("m", part(undefined), () => 99)).toBe(1); + expect(withCachedMessageTokens("m", part("undefined"), () => 99)).toBe(2); + }); + + // Absent text and empty-string text DO normalize together, matching + // `stripImages` - they tokenize identically, so sharing a key is correct. + it("treats absent text and empty text as the same message", () => { + const absent = { + role: "user", + content: [{ type: "text" }], + } as unknown as ChatMessage; + const empty = { + role: "user", + content: [{ type: "text", text: "" }], + } as unknown as ChatMessage; + + let calls = 0; + withCachedMessageTokens("m", absent, () => { + calls++; + return 5; + }); + expect( + withCachedMessageTokens("m", empty, () => { + calls++; + return 6; + }), + ).toBe(5); + expect(calls).toBe(1); + }); + it("stores fixed-size keys regardless of message size", () => { const small = msg("x"); const huge = msg("y".repeat(2 * 1024 * 1024)); diff --git a/core/llm/tokenCountCache.ts b/core/llm/tokenCountCache.ts index c03d81bb600..610c6cf9c54 100644 --- a/core/llm/tokenCountCache.ts +++ b/core/llm/tokenCountCache.ts @@ -51,10 +51,18 @@ function cacheKey(modelName: string, message: ChatMessage): string { if (typeof content === "string") { parts.push(content); } else if (Array.isArray(content)) { - // Image parts contribute a flat token count, so their presence matters but - // their payload does not - avoid keying on base64 blobs. for (const part of content) { - parts.push(part.type === "text" ? `t:${part.text}` : `i:${part.type}`); + // `stripImages` collects text parts with `.join("\n")`, which renders an + // absent `text` as "" - so the key must too. Interpolating it instead + // would produce "undefined" and collide with a part whose text is + // literally "undefined", serving one the other's count. + if (part.type === "text") { + parts.push("t:", part.text ?? ""); + } else { + // Image parts contribute a flat token count, so their presence matters + // but their payload does not - avoid keying on base64 blobs. + parts.push("i:", part.type); + } } } From 2061a5c8274dbee64005d9f4e8d1246e01be73a5 Mon Sep 17 00:00:00 2001 From: "ScrewTSW (public-projects)" Date: Thu, 27 Aug 2026 18:22:47 +0200 Subject: [PATCH 3/3] docs(core): don't call a hash collision harmless The docstring claimed a collision would "only mis-count tokens, not corrupt output". A wrong count feeds `compileChatMessages`: it drives `currentTotal` in the pruning loop, so it can drop a message that would have fit or let an over-long prompt through, and can trip the not-enough-context throw. The collision argument rests on probability, not on the consequence being benign. Say that instead. Co-Authored-By: Claude Opus 5 --- core/llm/tokenCountCache.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/core/llm/tokenCountCache.ts b/core/llm/tokenCountCache.ts index 610c6cf9c54..b026ab5dee0 100644 --- a/core/llm/tokenCountCache.ts +++ b/core/llm/tokenCountCache.ts @@ -39,8 +39,11 @@ let misses = 0; * ~0.66ms for 1MB versus ~3187ms to tokenize the same text - so it does not * erode the win. * - * SHA-256 collisions are not a practical concern at this cache size, and a - * collision would only mis-count tokens, not corrupt output. + * SHA-256 collisions are not a practical concern at this cache size. They are + * not harmless, though: a wrong count feeds the pruning loop in + * `compileChatMessages`, so it can drop a message that would have fit or let an + * over-long prompt through. The argument is that the probability is negligible, + * not that the consequence is. * * Only the fields `countChatMessageTokens` actually counts are included. */