Skip to content

Commit 7f4c925

Browse files
committed
Bound trace cache by message hashes
1 parent 3d4c4af commit 7f4c925

1 file changed

Lines changed: 17 additions & 3 deletions

File tree

web/src/llm-api/chat-completion-trace.ts

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@ type TraceCacheEntry = {
1717
}
1818

1919
const MAX_TRACE_CACHE_ENTRIES = 10_000
20+
const MAX_TRACE_CACHE_MESSAGE_HASHES = 250_000
2021
const traceCache = new Map<string, TraceCacheEntry>()
22+
let traceCacheMessageHashCount = 0
2123

2224
type ScheduleTraceWrite = (task: () => Promise<void>) => void
2325

@@ -47,17 +49,28 @@ function countCommonPrefix(left: string[], right: string[]) {
4749

4850
function rememberTraceCacheEntry(key: string, entry: TraceCacheEntry) {
4951
if (traceCache.has(key)) {
50-
traceCache.delete(key)
52+
forgetTraceCacheEntry(key)
5153
}
5254
traceCache.set(key, entry)
55+
traceCacheMessageHashCount += entry.messageHashes.length
5356

54-
while (traceCache.size > MAX_TRACE_CACHE_ENTRIES) {
57+
while (
58+
traceCache.size > MAX_TRACE_CACHE_ENTRIES ||
59+
traceCacheMessageHashCount > MAX_TRACE_CACHE_MESSAGE_HASHES
60+
) {
5561
const oldestKey = traceCache.keys().next().value
5662
if (!oldestKey) break
57-
traceCache.delete(oldestKey)
63+
forgetTraceCacheEntry(oldestKey)
5864
}
5965
}
6066

67+
function forgetTraceCacheEntry(key: string) {
68+
const entry = traceCache.get(key)
69+
if (!entry) return
70+
traceCache.delete(key)
71+
traceCacheMessageHashCount -= entry.messageHashes.length
72+
}
73+
6174
function buildChatCompletionTraceRecord(params: {
6275
body: ChatCompletionRequestBody
6376
userId: string
@@ -245,4 +258,5 @@ export function recordChatCompletionTrace(params: {
245258

246259
export function resetChatCompletionTraceCacheForTests() {
247260
traceCache.clear()
261+
traceCacheMessageHashCount = 0
248262
}

0 commit comments

Comments
 (0)