Repository navigation
perf(core): cache per-message token counts #19
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,201 @@ | ||
| 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. | ||
| // `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)); | ||
|
|
||
| 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); | ||
| }); | ||
| }); |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| 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<string, number>(); | ||
| 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 | ||
|
ScrewTSW marked this conversation as resolved.
Resolved
|
||
| * 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. 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. | ||
| */ | ||
| 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)) { | ||
| for (const part of content) { | ||
| // `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); | ||
| } | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| } | ||
|
|
||
| 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; | ||
| } | ||
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.