@@ -17,7 +17,9 @@ type TraceCacheEntry = {
1717}
1818
1919const MAX_TRACE_CACHE_ENTRIES = 10_000
20+ const MAX_TRACE_CACHE_MESSAGE_HASHES = 250_000
2021const traceCache = new Map < string , TraceCacheEntry > ( )
22+ let traceCacheMessageHashCount = 0
2123
2224type ScheduleTraceWrite = ( task : ( ) => Promise < void > ) => void
2325
@@ -47,17 +49,28 @@ function countCommonPrefix(left: string[], right: string[]) {
4749
4850function 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+
6174function buildChatCompletionTraceRecord ( params : {
6275 body : ChatCompletionRequestBody
6376 userId : string
@@ -245,4 +258,5 @@ export function recordChatCompletionTrace(params: {
245258
246259export function resetChatCompletionTraceCacheForTests ( ) {
247260 traceCache . clear ( )
261+ traceCacheMessageHashCount = 0
248262}
0 commit comments