-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathSemanticCache.ts
More file actions
1579 lines (1403 loc) · 55.9 KB
/
Copy pathSemanticCache.ts
File metadata and controls
1579 lines (1403 loc) · 55.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { randomUUID } from 'node:crypto';
import { createHash } from 'node:crypto';
import { SpanStatusCode, type Span } from '@opentelemetry/api';
import type {
SemanticCacheOptions,
CacheCheckOptions,
CacheStoreOptions,
CacheCheckResult,
CacheConfidence,
CacheStats,
IndexInfo,
InvalidateResult,
Valkey,
EmbedFn,
ModelCost,
ConfigRefreshOptions,
} from './types';
import {
SemanticCacheUsageError,
EmbeddingError,
ValkeyCommandError,
} from './errors';
import { createTelemetry, type Telemetry } from './telemetry';
import {
encodeFloat32,
escapeTag,
parseFtSearchResponse,
extractText,
extractBinaryRefs,
type ContentBlock,
type TextBlock,
} from './utils';
import { DEFAULT_COST_TABLE } from './defaultCostTable';
import { clusterScan } from './cluster';
import { createAnalytics, NOOP_ANALYTICS, type Analytics } from './analytics';
import {
DiscoveryManager,
buildSemanticMetadata,
type DiscoveryOptions,
} from './discovery';
const INVALIDATE_BATCH_SIZE = 1000;
const PACKAGE_VERSION = (require('../package.json') as { version: string }).version;
function errMsg(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
export class SemanticCache {
private readonly client: Valkey;
private readonly embedFn: EmbedFn;
private readonly name: string;
private readonly indexName: string;
private readonly entryPrefix: string;
private readonly statsKey: string;
private readonly similarityWindowKey: string;
private readonly configKey: string;
private defaultThreshold: number;
private readonly defaultTtl: number | undefined;
private categoryThresholds: Record<string, number>;
private readonly uncertaintyBand: number;
private readonly telemetry: Telemetry;
private readonly costTable: Record<string, ModelCost> | undefined;
private readonly embeddingCacheEnabled: boolean;
private readonly embeddingCacheTtl: number;
private readonly embedKeyPrefix: string;
private readonly discoveryOptions: DiscoveryOptions;
private readonly _initialDefaultThreshold: number;
private readonly _initialCategoryThresholds: Record<string, number>;
private readonly configRefreshOptions: Required<ConfigRefreshOptions>;
private configRefreshTimer: ReturnType<typeof setInterval> | undefined;
private discovery: DiscoveryManager | null = null;
private _initialized = false;
private _dimension = 0;
private _hasBinaryRefs = false;
private _initPromise: Promise<void> | null = null;
private _initGeneration = 0;
private readonly analyticsOpts: SemanticCacheOptions['analytics'];
private readonly usesDefaultCostTable: boolean;
private analytics: Analytics = NOOP_ANALYTICS;
private statsTimer: ReturnType<typeof setInterval> | undefined;
private shutdownCalled = false;
private analyticsInitiated = false;
/**
* Creates a new SemanticCache instance.
*
* The caller owns the iovalkey client lifecycle. SemanticCache does not
* close or disconnect the client when it is done. Call client.quit() or
* client.disconnect() yourself when the application shuts down.
*
* Call initialize() before using check() or store().
*/
constructor(options: SemanticCacheOptions) {
this.client = options.client;
this.embedFn = options.embedFn;
this.name = options.name ?? 'betterdb_scache';
this.indexName = `${this.name}:idx`;
this.entryPrefix = `${this.name}:entry:`;
this.statsKey = `${this.name}:__stats`;
this.similarityWindowKey = `${this.name}:__similarity_window`;
this.configKey = `${this.name}:__config`;
this.embedKeyPrefix = `${this.name}:embed:`;
this.defaultThreshold = options.defaultThreshold ?? 0.1;
this.defaultTtl = options.defaultTtl;
this.categoryThresholds = options.categoryThresholds ?? {};
this.uncertaintyBand = options.uncertaintyBand ?? 0.05;
// Build effective cost table
const useDefault = options.useDefaultCostTable ?? true;
if (!useDefault && !options.costTable) {
this.costTable = undefined;
} else if (!useDefault) {
this.costTable = options.costTable;
} else {
this.costTable = { ...DEFAULT_COST_TABLE, ...(options.costTable ?? {}) };
}
// Embedding cache config
this.embeddingCacheEnabled = options.embeddingCache?.enabled ?? true;
this.embeddingCacheTtl = options.embeddingCache?.ttl ?? 86400;
this.telemetry = createTelemetry({
prefix: options.telemetry?.metricsPrefix ?? 'semantic_cache',
tracerName: options.telemetry?.tracerName ?? '@betterdb/semantic-cache',
registry: options.telemetry?.registry,
});
this.analyticsOpts = options.analytics;
this.usesDefaultCostTable = useDefault;
this.discoveryOptions = options.discovery ?? {};
// Capture constructor values as fallback when __config fields are absent
this._initialDefaultThreshold = this.defaultThreshold;
this._initialCategoryThresholds = { ...this.categoryThresholds };
// Refresh options
const refresh = options.configRefresh ?? {};
this.configRefreshOptions = {
enabled: refresh.enabled ?? true,
intervalMs: Math.max(1000, refresh.intervalMs ?? 30_000),
};
}
// -- Lifecycle --
async initialize(): Promise<void> {
if (!this._initPromise) {
this._initPromise = this._doInitialize().catch((err) => {
this._initPromise = null;
throw err;
});
}
return this._initPromise;
}
async flush(): Promise<void> {
// Mark uninitialized immediately so concurrent check()/store() calls get
// a clear SemanticCacheUsageError instead of cryptic Valkey errors.
this._initialized = false;
this._initPromise = null;
this._initGeneration++;
// Capture and null the discovery ref synchronously, before any await,
// so a concurrent _doInitialize() (started after _initGeneration++) can't
// race in and have its new manager overwritten by this flush.
const discoveryToStop = this.discovery;
this.discovery = null;
if (discoveryToStop) {
await discoveryToStop.stop({ deleteHeartbeat: true });
}
// Valkey Search 1.2 does not support the DD (Delete Documents) flag on
// FT.DROPINDEX. Drop the index first, then clean up keys separately.
try {
await this.client.call('FT.DROPINDEX', this.indexName);
} catch (err: unknown) {
if (!this.isIndexNotFoundError(err)) {
throw new ValkeyCommandError('FT.DROPINDEX', err);
}
}
// Cluster-aware SCAN for entry keys and embed cache keys
const patterns = [
`${this.name}:entry:*`,
`${this.name}:embed:*`,
];
for (const pattern of patterns) {
await clusterScan(this.client, pattern, async (keys, nodeClient) => {
await nodeClient.del(keys);
});
}
await this.client.del(this.statsKey);
await this.client.del(this.similarityWindowKey);
this.analytics.capture('cache_flush');
}
/**
* Shut down the analytics client, cancel the stats timer, and stop the
* discovery heartbeat. Safe to call multiple times.
*/
async shutdown(): Promise<void> {
this.shutdownCalled = true;
if (this.configRefreshTimer) {
clearInterval(this.configRefreshTimer);
this.configRefreshTimer = undefined;
}
if (this.statsTimer) {
clearInterval(this.statsTimer);
this.statsTimer = undefined;
}
await this.analytics.shutdown();
await this.dispose();
}
/**
* Graceful shutdown of the discovery layer — stops the heartbeat and
* deletes this instance's heartbeat key so Monitor marks the cache offline
* immediately. Does NOT touch the registry hash, the FT index, or any
* entries. Safe to call multiple times.
*/
async dispose(): Promise<void> {
if (this.configRefreshTimer) {
clearInterval(this.configRefreshTimer);
this.configRefreshTimer = undefined;
}
if (this._initPromise) {
await this._initPromise.catch(() => {});
}
if (this.discovery) {
await this.discovery.stop({ deleteHeartbeat: true });
this.discovery = null;
}
}
// -- Public operations --
async check(prompt: string | ContentBlock[], options?: CacheCheckOptions): Promise<CacheCheckResult> {
this.assertInitialized('check');
return this.traced('check', async (span) => {
const category = options?.category ?? '';
const threshold =
options?.threshold ??
(category && this.categoryThresholds[category] !== undefined
? this.categoryThresholds[category]
: this.defaultThreshold);
// Resolve text and binary refs from prompt
const { text: promptText, binaryRefs } = await this.resolvePrompt(prompt);
// Stale model detection
const checkStale = (options?.staleAfterModelChange ?? false) && !!options?.currentModel;
// Rerank option
const rerankOpts = options?.rerank;
const k = rerankOpts ? rerankOpts.k : (options?.k ?? 1);
const { vector: embedding, durationSec: embedSec } = await this.embed(promptText);
this.assertDimension(embedding);
// Build filter
const userFilter = options?.filter;
// AND semantics: each ref must be present — chain separate TAG clauses.
const binaryFilter =
binaryRefs.length > 0 && this._hasBinaryRefs
? (binaryRefs.length === 1
? `@binary_refs:{${escapeTag(binaryRefs[0])}}`
: binaryRefs.map((r) => `@binary_refs:{${escapeTag(r)}}`).join(' '))
: null;
const combinedFilter = [userFilter, binaryFilter].filter(Boolean).join(' ');
const filterExpr = combinedFilter ? `(${combinedFilter})` : '*';
const query = `${filterExpr}=>[KNN ${k} @embedding $vec AS __score]`;
const searchStart = performance.now();
let rawResult: unknown;
try {
rawResult = await this.client.call(
'FT.SEARCH', this.indexName, query,
'PARAMS', '2', 'vec', encodeFloat32(embedding),
'LIMIT', '0', String(k),
'DIALECT', '2',
);
} catch (err) {
throw new ValkeyCommandError('FT.SEARCH', err);
}
const searchMs = performance.now() - searchStart;
const parsed = parseFtSearchResponse(rawResult);
const categoryLabel = category || 'none';
const timingAttrs = { 'embedding_latency_ms': embedSec * 1000, 'search_latency_ms': searchMs };
// No candidates at all
if (parsed.length === 0) {
await this.recordStat('misses');
this.telemetry.metrics.requestsTotal
.labels({ cache_name: this.name, result: 'miss', category: categoryLabel }).inc();
span.setAttributes({
'cache.hit': false, 'cache.name': this.name,
'cache.category': categoryLabel, ...timingAttrs,
});
return { hit: false, confidence: 'miss' as const };
}
const scoreStr = parsed[0].fields['__score'];
const score = scoreStr !== undefined ? parseFloat(scoreStr) : NaN;
if (!isNaN(score)) {
this.telemetry.metrics.similarityScore
.labels({ cache_name: this.name, category: categoryLabel }).observe(score);
}
// Miss (no usable score, or score exceeds threshold)
if (isNaN(score) || score > threshold) {
if (!isNaN(score)) {
await this.recordSimilarityWindow(score, 'miss', category);
}
await this.recordStat('misses');
this.telemetry.metrics.requestsTotal
.labels({ cache_name: this.name, result: 'miss', category: categoryLabel }).inc();
span.setAttributes({
'cache.hit': false, 'cache.name': this.name,
'cache.category': categoryLabel, ...timingAttrs,
...(isNaN(score) ? {} : { 'cache.similarity': score, 'cache.threshold': threshold }),
});
const result: CacheCheckResult = { hit: false, confidence: 'miss' as const };
if (!isNaN(score)) {
result.similarity = score;
result.nearestMiss = { similarity: score, deltaToThreshold: score - threshold };
}
return result;
}
// Rerank: apply rerankFn to all candidates above threshold
let winnerParsedIndex = 0;
if (rerankOpts && parsed.length > 0) {
// Preserve the original parsed[] index alongside each candidate so we
// can map back even when NaN-scored entries are filtered out.
const indexedCandidates = parsed
.map((r, i) => ({ i, s: parseFloat(r.fields['__score'] ?? 'NaN') }))
.filter(({ s }) => !isNaN(s))
.map(({ i, s }) => ({
origIdx: i,
candidate: { response: parsed[i].fields['response'] ?? '', similarity: s },
}));
const picked = await rerankOpts.rerankFn(
promptText, indexedCandidates.map((x) => x.candidate),
);
// Explicit bounds check: -1 means "reject all"; out-of-range is a caller bug
// treated as a miss rather than silently falling back to the top candidate.
if (picked === -1 || picked < 0 || picked >= indexedCandidates.length) {
await this.recordSimilarityWindow(score, 'miss', category);
await this.recordStat('misses');
this.telemetry.metrics.requestsTotal
.labels({ cache_name: this.name, result: 'miss', category: categoryLabel }).inc();
span.setAttributes({ 'cache.hit': false, 'cache.name': this.name, 'cache.reranked': true });
return { hit: false, confidence: 'miss' as const };
}
// Map back to the original parsed[] index (not the candidates[] index)
winnerParsedIndex = indexedCandidates[picked].origIdx;
}
const winner = parsed[winnerParsedIndex] ?? parsed[0];
const winnerScore = parseFloat(winner.fields['__score'] ?? String(score));
// Stale model check: if winner's model differs from currentModel, evict and treat as miss
if (checkStale) {
const storedModel = winner.fields['model'] ?? '';
if (storedModel && storedModel !== options!.currentModel) {
// Evict stale entry
try {
await this.client.del(winner.key);
} catch { /* best effort */ }
await this.recordSimilarityWindow(winnerScore, 'miss', category);
this.telemetry.metrics.staleModelEvictions.labels({ cache_name: this.name }).inc();
await this.recordStat('misses');
this.telemetry.metrics.requestsTotal
.labels({ cache_name: this.name, result: 'miss', category: categoryLabel }).inc();
span.setAttributes({ 'cache.hit': false, 'cache.stale_evicted': true });
return { hit: false, confidence: 'miss' as const };
}
}
// All checks passed — compute confidence (recordSimilarityWindow moves to after judge)
let confidence: CacheConfidence =
winnerScore >= threshold - this.uncertaintyBand ? 'uncertain' : 'high';
const matchedKey = winner.key;
// --- LLM-as-judge for borderline hits ---
if (options?.judge && confidence === 'uncertain') {
const judgeStart = performance.now();
const timeoutMs = options.judge.timeoutMs ?? 2000;
const onError = options.judge.onError ?? 'accept';
type JudgeDecision =
| 'accept' | 'reject'
| 'error_accept' | 'error_reject'
| 'timeout_accept' | 'timeout_reject';
let decision: JudgeDecision;
const judgeController = new AbortController();
try {
const accepted = await raceWithTimeout(
options.judge.judgeFn({
prompt: promptText,
response: winner.fields['response'] ?? '',
similarity: winnerScore,
threshold,
category: category || undefined,
signal: judgeController.signal,
}),
timeoutMs,
() => judgeController.abort(),
);
decision = accepted ? 'accept' : 'reject';
} catch (err) {
// raceWithTimeout already aborted the controller on the timeout path.
const isTimeout = err instanceof JudgeTimeoutError;
if (onError === 'accept') {
decision = isTimeout ? 'timeout_accept' : 'error_accept';
} else {
decision = isTimeout ? 'timeout_reject' : 'error_reject';
}
}
const judgeSec = (performance.now() - judgeStart) / 1000;
this.telemetry.metrics.judgeDecisions
.labels({ cache_name: this.name, category: categoryLabel, decision })
.inc();
this.telemetry.metrics.judgeDuration
.labels({ cache_name: this.name, category: categoryLabel, decision })
.observe(judgeSec);
span.setAttributes({
'cache.judge.invoked': true,
'cache.judge.decision': decision,
'cache.judge.latency_ms': judgeSec * 1000,
});
if (decision === 'accept') {
confidence = 'high';
// Fall through to hit-return path
} else if (decision === 'error_accept' || decision === 'timeout_accept') {
// Preserve 'uncertain'; fall through to hit-return path
} else {
// reject / error_reject / timeout_reject → treat as miss
await this.recordSimilarityWindow(winnerScore, 'miss', category);
await this.recordStat('misses');
this.telemetry.metrics.requestsTotal
.labels({ cache_name: this.name, result: 'miss', category: categoryLabel })
.inc();
span.setAttributes({
'cache.hit': false,
'cache.name': this.name,
'cache.category': categoryLabel,
});
return {
hit: false,
confidence: 'miss' as const,
similarity: winnerScore,
nearestMiss: {
similarity: winnerScore,
threshold,
deltaToThreshold: winnerScore - threshold,
matchedKey,
},
};
}
}
// --- End judge ---
// Record as genuine hit (moved here from before the judge block)
await this.recordSimilarityWindow(winnerScore, 'hit', category);
await this.recordStat('hits');
const metricResult = confidence === 'uncertain' ? 'uncertain_hit' : 'hit';
this.telemetry.metrics.requestsTotal
.labels({ cache_name: this.name, result: metricResult, category: categoryLabel }).inc();
if (this.defaultTtl !== undefined && matchedKey) {
await this.client.expire(matchedKey, this.defaultTtl);
}
// Cost saved
let costSaved: number | undefined;
const costMicrosStr = winner.fields['cost_micros'];
if (costMicrosStr) {
const costMicros = parseInt(costMicrosStr, 10);
if (!isNaN(costMicros) && costMicros > 0) {
costSaved = costMicros / 1_000_000;
// Atomically increment cost_saved_micros in stats
await this.client.hincrby(this.statsKey, 'cost_saved_micros', costMicros);
this.telemetry.metrics.costSavedTotal
.labels({ cache_name: this.name, category: categoryLabel }).inc(costSaved);
}
}
// Content blocks
let contentBlocks: import('./utils').ContentBlock[] | undefined;
const contentBlocksStr = winner.fields['content_blocks'];
if (contentBlocksStr) {
try {
contentBlocks = JSON.parse(contentBlocksStr);
} catch { /* ignore parse errors */ }
}
span.setAttributes({
'cache.hit': true, 'cache.similarity': winnerScore, 'cache.threshold': threshold,
'cache.confidence': confidence, 'cache.matched_key': matchedKey,
'cache.category': categoryLabel, ...timingAttrs,
});
const result: CacheCheckResult = {
hit: true, response: winner.fields['response'],
similarity: winnerScore, confidence, matchedKey,
};
if (costSaved !== undefined) result.costSaved = costSaved;
if (contentBlocks) result.contentBlocks = contentBlocks;
return result;
});
}
async store(prompt: string | ContentBlock[], response: string, options?: CacheStoreOptions): Promise<string> {
this.assertInitialized('store');
return this.traced('store', async (span) => {
const { text: promptText, binaryRefs } = await this.resolvePrompt(prompt);
const { vector: embedding, durationSec: embedSec } = await this.embed(promptText);
this.assertDimension(embedding);
const entryKey = `${this.entryPrefix}${randomUUID()}`;
const category = options?.category ?? '';
const model = options?.model ?? '';
// Compute cost if tokens and model provided
let costMicros: number | undefined;
if (
options?.model &&
options?.inputTokens !== undefined &&
options?.outputTokens !== undefined &&
this.costTable
) {
const pricing = this.costTable[options.model];
if (pricing) {
costMicros = Math.round(
(options.inputTokens * pricing.inputPer1k / 1000 +
options.outputTokens * pricing.outputPer1k / 1000) * 1_000_000
);
}
}
const hashFields: Record<string, string | Buffer> = {
prompt: promptText,
response,
model,
category,
inserted_at: Date.now().toString(),
metadata: JSON.stringify(options?.metadata ?? {}),
embedding: encodeFloat32(embedding),
};
if (binaryRefs.length > 0) {
hashFields['binary_refs'] = binaryRefs.join(',');
}
if (costMicros !== undefined && costMicros > 0) {
hashFields['cost_micros'] = String(costMicros);
}
if (options?.temperature !== undefined) {
hashFields['temperature'] = String(options.temperature);
}
if (options?.topP !== undefined) {
hashFields['top_p'] = String(options.topP);
}
if (options?.seed !== undefined) {
hashFields['seed'] = String(options.seed);
}
try {
await this.client.hset(entryKey, hashFields);
} catch (err) {
throw new ValkeyCommandError('HSET', err);
}
const ttl = options?.ttl ?? this.defaultTtl;
if (ttl !== undefined) await this.client.expire(entryKey, ttl);
span.setAttributes({
'cache.name': this.name, 'cache.key': entryKey, 'cache.ttl': ttl ?? -1,
'cache.category': category || 'none', 'cache.model': model || 'none',
'embedding_latency_ms': embedSec * 1000,
});
return entryKey;
});
}
/**
* Store structured content blocks as the cached response.
* Populates both the response field (from TextBlock text) and content_blocks (full JSON).
*/
async storeMultipart(
prompt: string | ContentBlock[],
blocks: ContentBlock[],
options?: CacheStoreOptions,
): Promise<string> {
this.assertInitialized('storeMultipart');
return this.traced('storeMultipart', async (span) => {
const { text: promptText, binaryRefs } = await this.resolvePrompt(prompt);
const { vector: embedding, durationSec: embedSec } = await this.embed(promptText);
this.assertDimension(embedding);
// Derive text response from blocks for backward compat
const textResponse = extractText(blocks);
const entryKey = `${this.entryPrefix}${randomUUID()}`;
const category = options?.category ?? '';
const model = options?.model ?? '';
let costMicros: number | undefined;
if (options?.model && options?.inputTokens !== undefined && options?.outputTokens !== undefined && this.costTable) {
const pricing = this.costTable[options.model];
if (pricing) {
costMicros = Math.round(
(options.inputTokens * pricing.inputPer1k / 1000 +
options.outputTokens * pricing.outputPer1k / 1000) * 1_000_000
);
}
}
const hashFields: Record<string, string | Buffer> = {
prompt: promptText,
response: textResponse,
model,
category,
inserted_at: Date.now().toString(),
metadata: JSON.stringify(options?.metadata ?? {}),
embedding: encodeFloat32(embedding),
content_blocks: JSON.stringify(blocks),
};
if (binaryRefs.length > 0) {
hashFields['binary_refs'] = binaryRefs.join(',');
}
if (costMicros !== undefined && costMicros > 0) {
hashFields['cost_micros'] = String(costMicros);
}
if (options?.temperature !== undefined) hashFields['temperature'] = String(options.temperature);
if (options?.topP !== undefined) hashFields['top_p'] = String(options.topP);
if (options?.seed !== undefined) hashFields['seed'] = String(options.seed);
try {
await this.client.hset(entryKey, hashFields);
} catch (err) {
throw new ValkeyCommandError('HSET', err);
}
const ttl = options?.ttl ?? this.defaultTtl;
if (ttl !== undefined) await this.client.expire(entryKey, ttl);
span.setAttributes({
'cache.name': this.name, 'cache.key': entryKey, 'cache.ttl': ttl ?? -1,
'cache.category': category || 'none', 'cache.model': model || 'none',
'embedding_latency_ms': embedSec * 1000,
});
return entryKey;
});
}
/**
* Check multiple prompts in parallel, using pipelined FT.SEARCH calls.
* Returns results in input order.
*/
async checkBatch(
prompts: (string | ContentBlock[])[],
options?: CacheCheckOptions,
): Promise<CacheCheckResult[]> {
this.assertInitialized('checkBatch');
if (prompts.length === 0) return [];
if (options?.rerank) {
throw new SemanticCacheUsageError(
"checkBatch() does not support the 'rerank' option. Use check() for reranking individual prompts.",
);
}
if (options?.staleAfterModelChange) {
throw new SemanticCacheUsageError(
"checkBatch() does not support 'staleAfterModelChange'. Use check() for stale-model eviction.",
);
}
if (options?.judge) {
throw new SemanticCacheUsageError(
"checkBatch() does not support the 'judge' option. Use check() for LLM-as-judge adjudication.",
);
}
return this.traced('checkBatch', async (span) => {
// Resolve all prompts and embed in parallel
const resolved = await Promise.all(prompts.map((p) => this.resolvePrompt(p)));
const embeddings = await Promise.all(resolved.map(({ text }) => this.embed(text)));
const category = options?.category ?? '';
const threshold =
options?.threshold ??
(category && this.categoryThresholds[category] !== undefined
? this.categoryThresholds[category]
: this.defaultThreshold);
const k = options?.k ?? 1;
const userFilter = options?.filter;
// Pipeline all FT.SEARCH calls
const pipeline = this.client.pipeline();
for (let i = 0; i < prompts.length; i++) {
const { binaryRefs } = resolved[i];
const { vector: embedding } = embeddings[i];
const binaryFilter =
binaryRefs.length > 0 && this._hasBinaryRefs
? (binaryRefs.length === 1
? `@binary_refs:{${escapeTag(binaryRefs[0])}}`
: binaryRefs.map((r) => `@binary_refs:{${escapeTag(r)}}`).join(' '))
: null;
const combinedFilter = [userFilter, binaryFilter].filter(Boolean).join(' ');
const filterExpr = combinedFilter ? `(${combinedFilter})` : '*';
const query = `${filterExpr}=>[KNN ${k} @embedding $vec AS __score]`;
pipeline.call(
'FT.SEARCH', this.indexName, query,
'PARAMS', '2', 'vec', encodeFloat32(embedding),
'LIMIT', '0', String(k),
'DIALECT', '2',
);
}
const pipelineResults = await pipeline.exec();
span.setAttributes({ 'cache.batch_size': prompts.length, 'cache.name': this.name });
const results: CacheCheckResult[] = [];
const categoryLabel = category || 'none';
for (let i = 0; i < prompts.length; i++) {
const pipelineEntry = pipelineResults?.[i];
const err = pipelineEntry?.[0];
const rawResult = pipelineEntry?.[1];
if (err) {
await this.recordStat('misses');
this.telemetry.metrics.requestsTotal
.labels({ cache_name: this.name, result: 'miss', category: categoryLabel }).inc();
results.push({ hit: false, confidence: 'miss' as const });
continue;
}
const parsed = parseFtSearchResponse(rawResult);
if (parsed.length === 0) {
await this.recordStat('misses');
this.telemetry.metrics.requestsTotal
.labels({ cache_name: this.name, result: 'miss', category: categoryLabel }).inc();
results.push({ hit: false, confidence: 'miss' as const });
continue;
}
const scoreStr = parsed[0].fields['__score'];
const score = scoreStr !== undefined ? parseFloat(scoreStr) : NaN;
if (isNaN(score) || score > threshold) {
if (!isNaN(score)) {
await this.recordSimilarityWindow(score, 'miss', category);
}
await this.recordStat('misses');
this.telemetry.metrics.requestsTotal
.labels({ cache_name: this.name, result: 'miss', category: categoryLabel }).inc();
const result: CacheCheckResult = { hit: false, confidence: 'miss' as const };
if (!isNaN(score)) {
result.similarity = score;
result.nearestMiss = { similarity: score, deltaToThreshold: score - threshold };
}
results.push(result);
continue;
}
await this.recordSimilarityWindow(score, 'hit', category);
const confidence: CacheConfidence =
score >= threshold - this.uncertaintyBand ? 'uncertain' : 'high';
await this.recordStat('hits');
const metricResult = confidence === 'uncertain' ? 'uncertain_hit' : 'hit';
this.telemetry.metrics.requestsTotal
.labels({ cache_name: this.name, result: metricResult, category: categoryLabel }).inc();
const matchedKey = parsed[0].key;
if (this.defaultTtl !== undefined && matchedKey) {
await this.client.expire(matchedKey, this.defaultTtl);
}
let costSaved: number | undefined;
const costMicrosStr = parsed[0].fields['cost_micros'];
if (costMicrosStr) {
const costMicros = parseInt(costMicrosStr, 10);
if (!isNaN(costMicros) && costMicros > 0) {
costSaved = costMicros / 1_000_000;
await this.client.hincrby(this.statsKey, 'cost_saved_micros', costMicros);
this.telemetry.metrics.costSavedTotal
.labels({ cache_name: this.name, category: categoryLabel }).inc(costSaved);
}
}
let contentBlocks: import('./utils').ContentBlock[] | undefined;
const contentBlocksStr = parsed[0].fields['content_blocks'];
if (contentBlocksStr) {
try { contentBlocks = JSON.parse(contentBlocksStr); } catch { /* ignore */ }
}
const result: CacheCheckResult = {
hit: true, response: parsed[0].fields['response'],
similarity: score, confidence, matchedKey,
};
if (costSaved !== undefined) result.costSaved = costSaved;
if (contentBlocks) result.contentBlocks = contentBlocks;
results.push(result);
}
return results;
});
}
/**
* Deletes all entries matching a valkey-search filter expression.
*
* **Security note:** `filter` is passed directly to FT.SEARCH. Only pass
* trusted, programmatically-constructed expressions - never unsanitised
* user input.
*/
async invalidate(filter: string): Promise<InvalidateResult> {
this.assertInitialized('invalidate');
return this.traced('invalidate', async (span) => {
let rawResult: unknown;
try {
rawResult = await this.client.call(
'FT.SEARCH', this.indexName, filter,
'RETURN', '0',
'LIMIT', '0', String(INVALIDATE_BATCH_SIZE),
'DIALECT', '2',
);
} catch (err) {
throw new ValkeyCommandError('FT.SEARCH', err);
}
const parsed = parseFtSearchResponse(rawResult);
if (parsed.length === 0) {
span.setAttributes({
'cache.name': this.name, 'cache.filter': filter,
'cache.deleted_count': 0, 'cache.truncated': false,
});
return { deleted: 0, truncated: false };
}
const keys = parsed.map((r) => r.key);
const truncated = keys.length === INVALIDATE_BATCH_SIZE;
try {
await this.client.del(keys);
} catch (err) {
throw new ValkeyCommandError('DEL', err);
}
span.setAttributes({
'cache.name': this.name, 'cache.filter': filter,
'cache.deleted_count': keys.length, 'cache.truncated': truncated,
});
return { deleted: keys.length, truncated };
});
}
/** Delete all entries tagged with the given model name. */
async invalidateByModel(model: string): Promise<number> {
let total = 0;
let result: InvalidateResult;
do {
result = await this.invalidate(`@model:{${escapeTag(model)}}`);
total += result.deleted;
} while (result.truncated);
return total;
}
/** Delete all entries tagged with the given category. */
async invalidateByCategory(category: string): Promise<number> {
let total = 0;
let result: InvalidateResult;
do {
result = await this.invalidate(`@category:{${escapeTag(category)}}`);
total += result.deleted;
} while (result.truncated);
return total;
}
async stats(): Promise<CacheStats> {
this.assertInitialized('stats');
const raw = await this.client.hgetall(this.statsKey);
const hits = parseInt(raw?.hits ?? '0', 10);
const misses = parseInt(raw?.misses ?? '0', 10);
const total = parseInt(raw?.total ?? '0', 10);
const costSavedMicros = parseInt(raw?.cost_saved_micros ?? '0', 10);
return { hits, misses, total, hitRate: total === 0 ? 0 : hits / total, costSavedMicros };
}
async indexInfo(): Promise<IndexInfo> {
this.assertInitialized('indexInfo');
let raw: unknown;
try {
raw = await this.client.call('FT.INFO', this.indexName);
} catch (err) {
throw new ValkeyCommandError('FT.INFO', err);
}
const info = raw as unknown[];
let numDocs = 0;
let indexingState = 'unknown';
for (let i = 0; i < info.length - 1; i += 2) {
const key = String(info[i]);
if (key === 'num_docs') numDocs = parseInt(String(info[i + 1]), 10) || 0;
else if (key === 'indexing') indexingState = String(info[i + 1]);
}
return { name: this.indexName, numDocs, dimension: this._dimension, indexingState };
}
/**
* Analyze the rolling similarity score window and recommend threshold adjustments.
*/
async thresholdEffectiveness(options?: {
category?: string;
minSamples?: number;
}): Promise<ThresholdEffectivenessResult> {
this.assertInitialized('thresholdEffectiveness');
const minSamples = options?.minSamples ?? 100;
const category = options?.category;
const threshold = category && this.categoryThresholds[category] !== undefined
? this.categoryThresholds[category]
: this.defaultThreshold;
// Read all window entries
let rawEntries: string[];
try {
rawEntries = (await this.client.zrange(this.similarityWindowKey, '0', '-1')) as string[];
} catch {
rawEntries = [];
}
// Parse and optionally filter by category
const entries: Array<{ score: number; result: 'hit' | 'miss'; category: string }> = [];
for (const raw of rawEntries) {
try {
const entry = JSON.parse(String(raw));
if (
typeof entry.score === 'number' &&
(entry.result === 'hit' || entry.result === 'miss')
) {
if (!category || entry.category === category) {
entries.push(entry);
}
}
} catch { /* skip corrupt entries */ }
}
const sampleCount = entries.length;
const categoryLabel = category ?? 'all';
if (sampleCount < minSamples) {
return {
category: categoryLabel,
sampleCount,
currentThreshold: threshold,
hitRate: 0,
uncertainHitRate: 0,
nearMissRate: 0,
avgHitSimilarity: 0,
avgMissSimilarity: 0,
recommendation: 'insufficient_data',
reasoning: `Only ${sampleCount} samples collected; ${minSamples} required for a reliable recommendation.`,
};
}
const hits = entries.filter((e) => e.result === 'hit');
const misses = entries.filter((e) => e.result === 'miss');
const hitRate = hits.length / sampleCount;
const uncertainHits = hits.filter((e) => e.score >= threshold - this.uncertaintyBand);
const uncertainHitRate = hits.length > 0 ? uncertainHits.length / hits.length : 0;