tricache 0.6.7 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1428 -970
  3. package/bin/tricache.js +8 -0
  4. package/dist/cache-service-5GATUYAK.js +7 -0
  5. package/dist/cache-service-D8tIXmzb.d.ts +1498 -0
  6. package/dist/chunk-EUGYR7KR.js +4629 -0
  7. package/dist/chunk-UBSR5UYA.js +0 -0
  8. package/dist/{chunk-FKY5R3CE.js → chunk-X5AXHPVD.js} +139 -6
  9. package/dist/cli.cjs +5238 -0
  10. package/dist/cli.d.ts +11 -0
  11. package/dist/cli.js +130 -0
  12. package/dist/drizzle/index.cjs +5218 -0
  13. package/dist/drizzle/index.d.ts +44 -0
  14. package/dist/drizzle/index.js +46 -0
  15. package/dist/http/index.cjs +5374 -0
  16. package/dist/http/index.d.ts +33 -0
  17. package/dist/http/index.js +200 -0
  18. package/dist/index.cjs +1245 -209
  19. package/dist/index.d.ts +15 -1230
  20. package/dist/index.js +11 -3705
  21. package/dist/nestjs/index.cjs +5362 -0
  22. package/dist/nestjs/index.d.ts +210 -0
  23. package/dist/nestjs/index.js +250 -0
  24. package/dist/next/index.cjs +5407 -0
  25. package/dist/next/index.d.ts +208 -0
  26. package/dist/next/index.js +297 -0
  27. package/dist/prisma/index.cjs +123 -0
  28. package/dist/prisma/index.d.ts +60 -0
  29. package/dist/prisma/index.js +87 -0
  30. package/dist/serialize-worker.cjs +190 -15
  31. package/dist/serialize-worker.js +63 -12
  32. package/package.json +71 -21
  33. package/src/cache-service.ts +3294 -2429
  34. package/src/cli.ts +143 -0
  35. package/src/compression.ts +56 -0
  36. package/src/disk-tier.ts +821 -757
  37. package/src/drizzle/index.ts +86 -0
  38. package/src/encryption.ts +513 -442
  39. package/src/http/index.ts +265 -0
  40. package/src/index.ts +7 -0
  41. package/src/nestjs/decorators.ts +161 -0
  42. package/src/nestjs/index.ts +23 -0
  43. package/src/nestjs/tricache.module.ts +104 -0
  44. package/src/nestjs/tricache.store.ts +97 -0
  45. package/src/nestjs/types.ts +79 -0
  46. package/src/next/cache-handler.ts +268 -0
  47. package/src/next/index.ts +37 -0
  48. package/src/next/isr-handler.ts +105 -0
  49. package/src/next/types.ts +130 -0
  50. package/src/prisma/index.ts +154 -0
  51. package/src/serialize-worker.ts +77 -13
  52. package/src/smart-memory-cache.ts +1026 -1010
  53. package/src/types.ts +911 -732
  54. package/src/wasm/bloom-filter-wasm.ts +3 -2
  55. package/src/worker-pool.ts +156 -42
@@ -1,1010 +1,1026 @@
1
- /**
2
- * SmartMemoryCache — L1 in-process cache with adaptive LFU/LRU hybrid eviction.
3
- *
4
- * Features:
5
- * - WASM Bloom filter for O(k) guaranteed-miss detection (pure-JS fallback)
6
- * - msgpackr compression for entries ≥ 512 bytes
7
- * - Category-aware capacity limits (prevents any single key prefix from monopolising RAM)
8
- * - Priority-weighted adaptive eviction (LFU × LRU × priority score)
9
- * - Stale-While-Revalidate soft-expiry support (isStale flag on get())
10
- * - L1.5 disk-spill on eviction — evicted entries are sent to DiskTier before deletion
11
- * - Periodic cleanup of hard-expired entries + bloom filter rebuild
12
- * - Process-level singleton via globalThis (survives Next.js hot reloads)
13
- */
14
-
15
- import { pack, unpack } from 'msgpackr';
16
- import type { CacheHit, CachePriority, CategoryLimit, SmartCacheEntry, ILogger, EvictionReason } from './types';
17
-
18
- // Reusable return object for get() — eliminates one heap allocation per hot read.
19
- // Safe because JS is single-threaded: callers consume all fields before the next get().
20
- const _hit: CacheHit = { value: undefined, isStale: false, expiresAt: 0, ttlMs: undefined, delta: undefined, fetchedAt: 0 };
21
-
22
- /**
23
- * Packed-byte threshold above which the live JS object is NOT stored alongside the
24
- * serialised buffer. For entries above this size, the double-heap overhead (both the
25
- * msgpackr Buffer and the deserialized object resident simultaneously) outweighs the
26
- * latency saved by skipping unpack on read. Below the threshold the live object is
27
- * stored so hot reads skip deserialization entirely.
28
- *
29
- * 16 KiB is a conservative default: msgpackr unpacks a 16 KiB buffer in ~0.03 ms,
30
- * while storing the deserialized form of a 16 KiB payload typically costs 32–64 KiB
31
- * of additional heap depending on object shape.
32
- */
33
- const LARGE_VALUE_BYTES = 16_384;
34
- import { WasmBloomFilter } from './wasm/bloom-filter-wasm';
35
-
36
-
37
-
38
- /** Fraction of candidates evicted in one pass when a limit is exceeded */
39
- const EVICTION_BATCH_PERCENT = 0.2;
40
- /** Reservoir sample window for smartEvict() — Redis-style. */
41
- const EVICTION_SAMPLE = 16;
42
- /** Number of lowest-scored candidates evicted per smartEvict() call. */
43
- const EVICT_COUNT = Math.max(1, Math.ceil(EVICTION_SAMPLE * EVICTION_BATCH_PERCENT)); // 4
44
-
45
- // ─── Pure-JS Bloom filter fallback ───────────────────────────────────────────
46
-
47
- class JsBloomFilter {
48
- private bits: Buffer;
49
- private readonly numBits: number;
50
- private readonly k: number;
51
- /** Pre-computed — numBits and k are constant, no need to recalculate on every probe. */
52
- private readonly _maxCapacity: number;
53
- /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
54
- private _insertionCount = 0;
55
-
56
- constructor(numBits = 100_000, k = 7) {
57
- this.numBits = numBits;
58
- this.k = k;
59
- this.bits = Buffer.alloc(Math.ceil(numBits / 8), 0);
60
- const p = 0.01;
61
- this._maxCapacity = Math.floor(-numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
62
- }
63
-
64
- private fnv1a32(s: string): number {
65
- let h = 0x811c9dc5;
66
- for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; }
67
- return h >>> 0;
68
- }
69
-
70
- private djb2(s: string): number {
71
- let h = 5381;
72
- for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0;
73
- return h >>> 0;
74
- }
75
-
76
- private setBit(i: number) { this.bits[i >>> 3] |= 1 << (i & 7); }
77
- private getBit(i: number): boolean { return (this.bits[i >>> 3] & (1 << (i & 7))) !== 0; }
78
-
79
- add(key: string): void {
80
- const h1 = this.fnv1a32(key), h2 = this.djb2(key);
81
- for (let i = 0; i < this.k; i++) this.setBit(((h1 + i * h2) >>> 0) % this.numBits);
82
- this._insertionCount++;
83
- }
84
-
85
- mightContain(key: string): boolean {
86
- const h1 = this.fnv1a32(key), h2 = this.djb2(key);
87
- for (let i = 0; i < this.k; i++) if (!this.getBit(((h1 + i * h2) >>> 0) % this.numBits)) return false;
88
- return true;
89
- }
90
-
91
- reset() { this.bits.fill(0); this._insertionCount = 0; }
92
- rebuild(keys: Iterable<string>) { this.bits.fill(0); this._insertionCount = 0; for (const k of keys) this.add(k); }
93
-
94
- /** Number of add() calls since last reset/rebuild. */
95
- get insertions(): number { return this._insertionCount; }
96
-
97
- /**
98
- * Maximum safe insertions before false-positive rate exceeds ~1 %.
99
- * Exact formula for the configured k and target p=1 %:
100
- * n_max = -m * ln(1 - p^(1/k)) / k
101
- */
102
- get maxCapacity(): number { return this._maxCapacity; }
103
-
104
- get stats(): { bitsSet: number; fillFactor: number } {
105
- let bitsSet = 0;
106
- for (const byte of this.bits) { let b = byte; while (b) { bitsSet++; b &= b - 1; } }
107
- return { bitsSet, fillFactor: bitsSet / this.numBits };
108
- }
109
- }
110
-
111
- type AnyBloomFilter = JsBloomFilter | WasmBloomFilter;
112
-
113
- /**
114
- * Return a bloom filter sized for `maxEntries` at a ~1 % false-positive target.
115
- *
116
- * The WASM filter is hardcoded at 100 K bits (k = 7), which holds ≈ 10 400 entries
117
- * at 1 % FP. For larger caches the filter saturates quickly, producing high FP rates
118
- * that force wasted Map.get() calls on every definite miss. When `maxEntries` exceeds
119
- * the WASM filter's rated capacity, we instantiate a JS filter sized via the optimal
120
- * formula: m = ⌈–n · ln p / (ln 2)²⌉ with k = round(ln 2 · m / n) clamped to [4, 10].
121
- */
122
- function createBloomFilter(logger: ILogger, maxEntries: number): AnyBloomFilter {
123
- // Compute optimal bit-count for p = 1 % and the requested entry ceiling.
124
- const LN2_SQ = Math.LN2 * Math.LN2; // (ln 2)² ≈ 0.4804
125
- const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
126
- const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
127
-
128
- try {
129
- const wasm = new WasmBloomFilter();
130
- if (wasm.maxCapacity >= maxEntries) {
131
- logger.debug('SmartMemoryCache: WASM BloomFilter active');
132
- return wasm;
133
- }
134
- // WASM filter is undersized for this cache — fall through to right-sized JS filter.
135
- logger.debug('SmartMemoryCache: WASM BloomFilter capacity too small, using sized JS BloomFilter', {
136
- wasmCapacity: wasm.maxCapacity, maxEntries, optimalBits,
137
- });
138
- } catch (err) {
139
- logger.debug('SmartMemoryCache: WASM unavailable — using pure-JS BloomFilter', { reason: (err as Error).message });
140
- }
141
- return new JsBloomFilter(optimalBits, optimalK);
142
- }
143
-
144
- // ─── Count-Min Sketch ─────────────────────────────────────────────────────────
145
- //
146
- // Estimates historical access frequency across eviction boundaries — a per-entry
147
- // `hits` counter resets to 1 whenever a key is re-admitted after eviction, but
148
- // the sketch remembers the key's frequency in a fixed-size typed array that
149
- // survives evictions. This closes the same-priority burst-flood gap: a key that
150
- // has been accessed 80 times over the last hour but was evicted 5 minutes ago
151
- // will score far above a brand-new burst key whose hits = 1.
152
- //
153
- // Dimensions: 4 rows × 512 counters (Uint16Array) — 4 KB total, fits in L1d.
154
- // Hash: four independent Murmur3-fragment mixes of the key's FNV-1a digest.
155
- // Decay: all counters halved when total insertions cross SKETCH_DECAY_THRESHOLD
156
- // (frequency-ageing prevents indefinitely growing hot-key counts).
157
-
158
- const SKETCH_ROWS = 4;
159
- const SKETCH_WIDTH = 512; // must be power of two
160
- const SKETCH_MASK = SKETCH_WIDTH - 1;
161
- const SKETCH_DECAY_THRESHOLD = 100_000;
162
-
163
- class CountMinSketch {
164
- private readonly table = new Uint16Array(SKETCH_ROWS * SKETCH_WIDTH);
165
- private inserts = 0;
166
-
167
- /** Inline FNV-1a for a string key → 32-bit unsigned integer. */
168
- private fnv32(key: string): number {
169
- let h = 0x811c9dc5;
170
- for (let i = 0; i < key.length; i++) {
171
- h ^= key.charCodeAt(i);
172
- h = (Math.imul(h, 0x01000193) >>> 0);
173
- }
174
- return h;
175
- }
176
-
177
- /** Record one access. Decays all counters when the insertion threshold is crossed. */
178
- increment(key: string): void {
179
- const h = this.fnv32(key);
180
- const h1 = (h ^ (h >>> 16)) >>> 0;
181
- const h2 = (Math.imul(h1, 0x45d9f3b) ^ (h1 >>> 16)) >>> 0;
182
- const h3 = (Math.imul(h2, 0x7fb9b7a1) ^ (h2 >>> 16)) >>> 0;
183
- const h4 = (Math.imul(h3, 0x1b873593) ^ (h3 >>> 16)) >>> 0;
184
- const t = this.table;
185
- const i0 = h1 & SKETCH_MASK;
186
- const i1 = SKETCH_WIDTH + (h2 & SKETCH_MASK);
187
- const i2 = 2 * SKETCH_WIDTH + (h3 & SKETCH_MASK);
188
- const i3 = 3 * SKETCH_WIDTH + (h4 & SKETCH_MASK);
189
- if (t[i0] < 0xffff) t[i0]++;
190
- if (t[i1] < 0xffff) t[i1]++;
191
- if (t[i2] < 0xffff) t[i2]++;
192
- if (t[i3] < 0xffff) t[i3]++;
193
- if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
194
- }
195
-
196
- /** Minimum-across-rows frequency estimate. */
197
- estimate(key: string): number {
198
- const h = this.fnv32(key);
199
- const h1 = (h ^ (h >>> 16)) >>> 0;
200
- const h2 = (Math.imul(h1, 0x45d9f3b) ^ (h1 >>> 16)) >>> 0;
201
- const h3 = (Math.imul(h2, 0x7fb9b7a1) ^ (h2 >>> 16)) >>> 0;
202
- const h4 = (Math.imul(h3, 0x1b873593) ^ (h3 >>> 16)) >>> 0;
203
- const t = this.table;
204
- return Math.min(
205
- t[h1 & SKETCH_MASK],
206
- t[SKETCH_WIDTH + (h2 & SKETCH_MASK)],
207
- t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
208
- t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)],
209
- );
210
- }
211
-
212
- /** Halve all counters — ages out old frequency so bursts don't hold indefinitely. */
213
- private decay(): void {
214
- for (let i = 0; i < this.table.length; i++) this.table[i] >>>= 1;
215
- this.inserts = 0;
216
- }
217
- }
218
-
219
- // ─── Glob matcher ───────────────────────────────────────────────────────────────
220
-
221
- /**
222
- * Pure-string glob matcher — replaces RegExp on the deletePattern hot path.
223
- * Supports only '*' wildcards (any sequence, including empty).
224
- * No NFA/DFA state machine, no backtracking.
225
- *
226
- * Two-layer design to avoid per-key allocation in the inner loop:
227
- * globMatch() — public entry point; splits the pattern once.
228
- * globMatchParts() — hot inner loop; receives the pre-split segments.
229
- *
230
- * Algorithm:
231
- * 1. First segment anchors the prefix (startsWith, O(|first|)).
232
- * 2. Last segment anchors the suffix (endsWith, O(|last|)).
233
- * 3. Middle segments are located left-to-right with indexOf (O(N) total, no re-scan).
234
- */
235
- function globMatchParts(parts: string[], first: string, last: string, key: string): boolean {
236
- if (first.length > 0 && !key.startsWith(first)) return false;
237
- if (last.length > 0 && !key.endsWith(last)) return false;
238
- if (first.length + last.length > key.length) return false; // anchors overlap
239
-
240
- // Walk any middle segments left-to-right — indexOf never backtracks.
241
- let pos = first.length;
242
- const end = key.length - last.length;
243
- for (let i = 1; i < parts.length - 1; i++) {
244
- const seg = parts[i];
245
- if (seg.length === 0) continue; // consecutive '*' — skip
246
- const idx = key.indexOf(seg, pos);
247
- if (idx === -1 || idx + seg.length > end) return false;
248
- pos = idx + seg.length;
249
- }
250
- return true;
251
- }
252
-
253
- function globMatch(pattern: string, key: string): boolean {
254
- const parts = pattern.split('*');
255
- if (parts.length === 1) return pattern === key; // no wildcard — exact match
256
- return globMatchParts(parts, parts[0], parts[parts.length - 1], key);
257
- }
258
-
259
- // ─── SmartMemoryCache ─────────────────────────────────────────────────────────
260
-
261
- export interface SmartMemoryCacheOptions {
262
- maxBytes: number;
263
- maxEntries: number;
264
- categories: Record<string, CategoryLimit>;
265
- diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
266
- onEviction?: (key: string, reason: EvictionReason) => void;
267
- logger: ILogger;
268
- /** Fraction of maxEntries / maxBytes at which proactive eviction fires (default 0.9). */
269
- evictionWatermark?: number;
270
- }
271
-
272
- export class SmartMemoryCache {
273
- private readonly cache = new Map<string, SmartCacheEntry>();
274
- private readonly opts: SmartMemoryCacheOptions;
275
- private bloom: AnyBloomFilter;
276
- /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
277
- private readonly categoryPrefixes: string[];
278
- /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
279
- private readonly sketch = new CountMinSketch();
280
- private totalSize = 0;
281
- private categoryCount = new Map<string, number>();
282
- private categorySize = new Map<string, number>();
283
- /** Per-category key sets — enables O(catSize) Phase-1 reservoir sampling without an O(N) scan. */
284
- private categoryKeys = new Map<string, Set<string>>();
285
-
286
- // ── Observability counters ──────────────────────────────────────────────────────
287
- private bloomChecks = 0;
288
- private bloomFalsePos = 0;
289
- private compressions = 0; private categoryHits = new Map<string, number>();
290
- /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
291
- private _bloomDirtyCount = 0;
292
-
293
- /**
294
- * Pre-allocated eviction candidate pools — reused across every smartEvict() call to
295
- * eliminate per-call heap pressure. Each slot holds a mutable {key, score} record
296
- * that is overwritten in-place rather than replaced with a new object literal.
297
- * Safe because JS is single-threaded: smartEvict() completes synchronously before
298
- * any other code can observe the pool state.
299
- */
300
- private readonly _evictPool: Array<{ key: string; score: number }> =
301
- Array.from({ length: EVICTION_SAMPLE }, () => ({ key: '', score: 0 }));
302
- private readonly _evictGPool: Array<{ key: string; score: number }> =
303
- Array.from({ length: EVICTION_SAMPLE }, () => ({ key: '', score: 0 }));
304
-
305
- constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>) {
306
- this.opts = opts;
307
- this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
308
- this.categoryPrefixes = Object.keys(opts.categories).filter(k => k !== 'default');
309
-
310
- if (existing) {
311
- for (const [k, v] of existing) this.cache.set(k, v);
312
- this.recalculateStats();
313
- for (const key of this.cache.keys()) this.bloom.add(key);
314
- }
315
- }
316
-
317
- // ── Internal helpers ──────────────────────────────────────────────────────
318
-
319
- private recalculateStats(): void {
320
- this.totalSize = 0;
321
- this.categoryCount.clear();
322
- this.categorySize.clear();
323
- this.categoryKeys.clear();
324
- for (const [key, entry] of this.cache) {
325
- this.totalSize += entry.size;
326
- const cat = this.getCategory(key);
327
- this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
328
- this.categorySize.set(cat, (this.categorySize.get(cat) ?? 0) + entry.size);
329
- let ks = this.categoryKeys.get(cat);
330
- if (!ks) { ks = new Set(); this.categoryKeys.set(cat, ks); }
331
- ks.add(key);
332
- }
333
- }
334
-
335
- private getCategory(key: string): string {
336
- for (const prefix of this.categoryPrefixes) {
337
- if (key.startsWith(prefix)) return prefix;
338
- }
339
- return 'default';
340
- }
341
-
342
- private getCategoryLimit(cat: string): CategoryLimit {
343
- return this.opts.categories[cat] ?? this.opts.categories['default'] ?? { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 };
344
- }
345
-
346
- private _delete(key: string, reason: EvictionReason = 'manual'): boolean {
347
- const entry = this.cache.get(key);
348
- if (!entry) return false;
349
- const cat = this.getCategory(key);
350
- this.totalSize -= entry.size;
351
- this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
352
- this.categorySize.set(cat, (this.categorySize.get(cat) ?? entry.size) - entry.size);
353
- this.categoryKeys.get(cat)?.delete(key);
354
- this._bloomDirtyCount++;
355
- const deleted = this.cache.delete(key);
356
- if (deleted && this.opts.onEviction) {
357
- try { this.opts.onEviction(key, reason); } catch { /* never crash cache */ }
358
- }
359
- return deleted;
360
- }
361
-
362
- private ensureCapacity(category: string, neededSize: number): void {
363
- const lim = this.getCategoryLimit(category);
364
- const catCnt = this.categoryCount.get(category) ?? 0;
365
- const catSz = this.categorySize.get(category) ?? 0;
366
- let catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
367
- let glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
368
- if (!catOvf && !glbOvf) {
369
- // Proactive watermark: when either the global entry count OR total byte
370
- // usage crosses 90 % of its configured ceiling while there is still
371
- // headroom, run one eviction pass now — during the cheap headroom path —
372
- // so the hard cliffs at 100 % are rarely reached and writes at full
373
- // capacity become uncommon. Both dimensions are guarded so that
374
- // large-payload workloads (where maxBytes is the binding constraint)
375
- // benefit equally alongside entry-count-bound workloads.
376
- const wm = this.opts.evictionWatermark ?? 0.9;
377
- const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * wm);
378
- const byteWatermark = this.totalSize + neededSize >= Math.floor(this.opts.maxBytes * wm);
379
- if (entryWatermark || byteWatermark) {
380
- this.smartEvict(category, false);
381
- }
382
- return;
383
- }
384
- // Hard overflow: evict until back under BOTH the category and global limits.
385
- // A single smartEvict() pass removes at most EVICT_COUNT entries, which is not
386
- // enough when one set() pushes the cache far past its ceiling (e.g. a large
387
- // entry that itself dominates the byte budget). Loop until the overflow clears,
388
- // bounded by MAX_EVICT_PASSES so a pathological key (larger than the limit
389
- // cannot be evicted to fit itself) cannot spin forever.
390
- const MAX_EVICT_PASSES = 64;
391
- let passes = 0;
392
- do {
393
- this.smartEvict(category, catOvf);
394
- const lim2 = this.getCategoryLimit(category);
395
- const catCnt2 = this.categoryCount.get(category) ?? 0;
396
- const catSz2 = this.categorySize.get(category) ?? 0;
397
- catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
398
- glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
399
- passes++;
400
- } while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
401
- }
402
-
403
- private score(entry: SmartCacheEntry, catBonus: number, now: number, key: string): number {
404
- const age = now - entry.lastAccess;
405
- const ttl = Math.max(0, entry.expiresAt - now);
406
- // Use the sketch's cross-eviction frequency estimate when it exceeds the
407
- // entry's current-tenure hit count — protects long-resident keys that were
408
- // recently re-admitted (hits reset to 1) from same-priority burst floods.
409
- const freq = Math.min(Math.max(entry.hits, this.sketch.estimate(key)), 100);
410
- return entry.priority * 1000 + freq * 10 + ttl / 60000 - age / 60000 - catBonus;
411
- }
412
-
413
- /**
414
- * Rebuild the bloom filter when phantom bits from deleted/expired keys have
415
- * saturated the filter past its ~1 % FP capacity.
416
- *
417
- * Trigger: (insertions − live entries) > maxCapacity
418
- *
419
- * Using the phantom count (insertions − cache.size) instead of raw insertions
420
- * prevents an O(cache.size) rebuild from re-firing on every set() when the
421
- * cache holds more entries than the filter's rated capacity — which would
422
- * stall the write path entirely.
423
- *
424
- * After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
425
- */
426
- private maybeRebuildBloom(): void {
427
- // Two independent triggers — whichever fires first:
428
- // 1. Phantom count (insertions of dead keys since last rebuild)
429
- // 2. Deletion count (ANY _delete() call — expiry, eviction, or explicit)
430
- //
431
- // Dirty-count cap: bloom.maxCapacity grows proportionally with filter size, but
432
- // we want rebuild frequency to stay proportional to cache ENTRY count, not bit
433
- // count. Without the cap a JS filter sized for 50 K entries allows ~12 500 ghost
434
- // entries before a rebuild — 5× longer than the old WASM filter, which let phantom
435
- // bits accumulate and raised the measured FP rate. The cap restores the original
436
- // rebuild cadence: rebuild after ~5 % of maxEntries are deleted, with a 256 floor.
437
- const dirtyThreshold = Math.max(256, Math.min(this.bloom.maxCapacity >>> 2, Math.ceil(this.opts.maxEntries * 0.05)));
438
- if (this._bloomDirtyCount > dirtyThreshold ||
439
- this.bloom.insertions - this.cache.size > this.bloom.maxCapacity) {
440
- this.bloom.rebuild(this.cache.keys());
441
- this._bloomDirtyCount = 0;
442
- }
443
- }
444
-
445
- private smartEvict(targetCat: string, catOvf: boolean): void {
446
- const now = Date.now();
447
- const pool = this._evictPool;
448
- const gPool = this._evictGPool;
449
- let poolLen = 0;
450
-
451
- if (catOvf) {
452
- // Phase 1 — O(catSize) category-local reservoir sample.
453
- // Uses the categoryKeys index to iterate only the overflowing category's keys,
454
- // avoiding an O(N) scan of the entire cache. Guarantees at least
455
- // min(catSize, EVICT_COUNT) entries from the overflowing category in the pool so
456
- // the priority score ordering is always deterministic in practice.
457
- const catKeySet = this.categoryKeys.get(targetCat);
458
- if (catKeySet) {
459
- let catSeen = 0;
460
- for (const key of catKeySet) {
461
- const entry = this.cache.get(key);
462
- if (!entry || (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now)) continue;
463
- catSeen++;
464
- const s = this.score(entry, 100, now, key);
465
- if (poolLen < EVICT_COUNT) {
466
- pool[poolLen].key = key; pool[poolLen].score = s; poolLen++;
467
- } else {
468
- const j = Math.floor(Math.random() * catSeen);
469
- if (j < EVICT_COUNT) { pool[j].key = key; pool[j].score = s; }
470
- }
471
- }
472
- }
473
- }
474
-
475
- // Phase 2 — global reservoir sample fills remaining EVICTION_SAMPLE-poolLen slots.
476
- // Skipped entirely when Phase 1 already collected a full EVICT_COUNT-sized pool
477
- // (the common catOvf case — overflowing categories always have ≥ EVICT_COUNT entries).
478
- // Also the sole phase when !catOvf (global over-capacity, no preferred category).
479
- if (poolLen < EVICT_COUNT) {
480
- const remaining = EVICTION_SAMPLE - poolLen;
481
- let globalSeen = 0;
482
- let gLen = 0;
483
- for (const [key, entry] of this.cache) {
484
- if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
485
- if (catOvf && this.getCategory(key) === targetCat) continue; // already sampled above
486
- globalSeen++;
487
- const s = this.score(entry, 0, now, key);
488
- if (gLen < remaining) {
489
- gPool[gLen].key = key; gPool[gLen].score = s; gLen++;
490
- } else {
491
- const j = Math.floor(Math.random() * globalSeen);
492
- if (j < remaining) { gPool[j].key = key; gPool[j].score = s; }
493
- }
494
- }
495
- // Manual merge — no spread, no new array
496
- for (let i = 0; i < gLen; i++) {
497
- pool[poolLen].key = gPool[i].key; pool[poolLen].score = gPool[i].score; poolLen++;
498
- }
499
- }
500
-
501
- if (poolLen === 0) return;
502
-
503
- // Insertion sort — O(poolLen²) but poolLen ≤ EVICTION_SAMPLE=16 (max 256 comparisons).
504
- // Faster than Array.sort() at this scale: no comparator closure call overhead,
505
- // no timsort startup, no allocation. Sorts in-place within the pre-allocated pool.
506
- for (let i = 1; i < poolLen; i++) {
507
- const sk = pool[i].key, ss = pool[i].score;
508
- let j = i - 1;
509
- while (j >= 0 && pool[j].score > ss) {
510
- pool[j + 1].key = pool[j].key; pool[j + 1].score = pool[j].score; j--;
511
- }
512
- pool[j + 1].key = sk; pool[j + 1].score = ss;
513
- }
514
-
515
- const toEvict = Math.min(EVICT_COUNT, poolLen);
516
- for (let i = 0; i < toEvict; i++) {
517
- const key = pool[i].key;
518
- const entry = this.cache.get(key);
519
- if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry); // L1.5 spill
520
- this._delete(key, 'capacity');
521
- }
522
- }
523
-
524
- // ── Public API ────────────────────────────────────────────────────────────
525
-
526
- get(key: string): CacheHit | null {
527
- this.bloomChecks++;
528
- if (!this.bloom.mightContain(key)) return null;
529
- const entry = this.cache.get(key);
530
- if (!entry) { this.bloomFalsePos++; return null; }
531
- const now = Date.now();
532
- if (entry.expiresAt < now) { this._delete(key, 'ttl'); return null; }
533
- entry.hits++;
534
- entry.lastAccess = now;
535
- // Sample sketch at 25 % — eviction scoring only needs relative frequency, not exact counts.
536
- if ((entry.hits & 3) === 0) this.sketch.increment(key);
537
- // value is cached at write time — hot reads return the live object directly,
538
- // skipping unpack. Falls back to decode for entries restored from disk/snapshot.
539
- const value = entry.value !== undefined ? entry.value : unpack(entry.data as Buffer);
540
- _hit.value = value;
541
- _hit.isStale = entry.staleAt !== undefined && now > entry.staleAt;
542
- _hit.expiresAt = entry.expiresAt;
543
- _hit.ttlMs = entry.ttlMs;
544
- _hit.delta = entry.delta;
545
- _hit.fetchedAt = now;
546
- return _hit;
547
- }
548
-
549
- set(
550
- key: string,
551
- data: unknown,
552
- ttlMs: number,
553
- priority: CachePriority = 2 /* NORMAL */,
554
- staleAt?: number,
555
- delta?: number,
556
- ): void {
557
- // Single serialization pass — always msgpackr. Eliminates the prior JSON.stringify
558
- // "size probe" that was discarded for large payloads (the double-pass).
559
- const packed = pack(data);
560
- const size = packed.byteLength;
561
- this.compressions++;
562
- this.sketch.increment(key);
563
-
564
- const cat = this.getCategory(key);
565
- const lim = this.getCategoryLimit(cat);
566
-
567
- if (size > lim.maxSizeBytes * 0.5) {
568
- this.opts.logger.debug('SmartMemoryCache: entry too large, skipping', { key, sizeBytes: size });
569
- return;
570
- }
571
-
572
- // Single Map.get replaces Map.has + _delete's Map.get (saves one lookup on overwrite).
573
- const existingEntry = this.cache.get(key);
574
- if (existingEntry) {
575
- this.totalSize -= existingEntry.size;
576
- this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
577
- this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
578
- this.cache.delete(key);
579
- }
580
- this.ensureCapacity(cat, size);
581
-
582
- const now = Date.now();
583
- // Only cache the live object for small entries — large entries would store the packed
584
- // buffer AND a potentially much-larger deserialized object simultaneously (double-heap).
585
- // For large entries, get() falls back to the unpack() path transparently.
586
- const liveValue = size <= LARGE_VALUE_BYTES ? data : undefined;
587
- this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now });
588
- // Only add new keys to the bloom — overwrites already have their bits set.
589
- // Re-adding inflates the insertions counter, delaying trigger-2 phantom detection.
590
- if (!existingEntry) this.bloom.add(key);
591
- this.maybeRebuildBloom();
592
- this.totalSize += size;
593
- this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
594
- this.categorySize.set(cat, (this.categorySize.get(cat) ?? 0) + size);
595
- let ks = this.categoryKeys.get(cat);
596
- if (!ks) { ks = new Set(); this.categoryKeys.set(cat, ks); }
597
- ks.add(key);
598
- }
599
-
600
- delete(key: string): boolean {
601
- const deleted = this._delete(key, 'manual');
602
- if (deleted) this.maybeRebuildBloom();
603
- return deleted;
604
- }
605
-
606
- private keysMatchingPattern(pattern: string): string[] {
607
- if (!pattern.includes('*')) return this.cache.has(pattern) ? [pattern] : [];
608
-
609
- // Fast path: trailing-only wildcard whose prefix exactly matches a configured
610
- // category (e.g. deletePattern('user:*') when 'user:' is a category).
611
- // categoryKeys already indexes all live keys per category prefix in O(1),
612
- // so we skip the O(N) Map scan and regex evaluation entirely.
613
- // We snapshot via Array.from() before returning so _delete() mutations to
614
- // the Set during the subsequent iteration are safe.
615
- if (pattern.endsWith('*') && pattern.indexOf('*') === pattern.length - 1) {
616
- const prefix = pattern.slice(0, -1);
617
- const catKeys = this.categoryKeys.get(prefix);
618
- if (catKeys !== undefined) return Array.from(catKeys);
619
- }
620
-
621
- // Fast path: exactly one '*' that is NOT at the end (e.g. "user:*:profile").
622
- // AOT detection lets us avoid globMatchParts dispatch and its empty middle-
623
- // segment loop — keys only need startsWith + endsWith + length checks inline.
624
- const firstStar = pattern.indexOf('*');
625
- if (firstStar === pattern.lastIndexOf('*')) {
626
- const prefix = pattern.slice(0, firstStar);
627
- const suffix = pattern.slice(firstStar + 1); // empty when star is last char
628
- const minLen = prefix.length + suffix.length;
629
- const out: string[] = [];
630
- for (const k of this.cache.keys()) {
631
- if (k.length >= minLen && k.startsWith(prefix) && k.endsWith(suffix)) out.push(k);
632
- }
633
- return out;
634
- }
635
-
636
- // General case: multiple '*' wildcards — split once, then scan.
637
- const parts = pattern.split('*');
638
- const first = parts[0];
639
- const last = parts[parts.length - 1];
640
- const out: string[] = [];
641
- for (const k of this.cache.keys()) if (globMatchParts(parts, first, last, k)) out.push(k);
642
- return out;
643
- }
644
-
645
- deletePattern(pattern: string): number {
646
- let n = 0;
647
- for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key, 'manual')) n++;
648
- if (n > 0) this.maybeRebuildBloom();
649
- return n;
650
- }
651
-
652
- /** Flush all entries, or only those whose key starts with `prefix`. */
653
- clear(prefix?: string): number {
654
- if (prefix) {
655
- const pattern = prefix.includes('*') ? prefix : `${prefix}*`;
656
- return this.deletePattern(pattern);
657
- }
658
- const count = this.cache.size;
659
- this.cache.clear();
660
- this.totalSize = 0;
661
- this.categoryCount.clear();
662
- this.categorySize.clear();
663
- this.categoryKeys.clear();
664
- this.categoryHits.clear();
665
- this.bloom.reset();
666
- this._bloomDirtyCount = 0;
667
- return count;
668
- }
669
-
670
- /**
671
- * Evict entries that violate current category or global limits.
672
- * Returns the number of entries evicted.
673
- */
674
- rebalance(): number {
675
- const now = Date.now();
676
- let evicted = 0;
677
-
678
- for (const [cat, limit] of Object.entries(this.opts.categories)) {
679
- const catKeys = this.categoryKeys.get(cat);
680
- if (!catKeys || catKeys.size === 0) continue;
681
-
682
- let catCnt = this.categoryCount.get(cat) ?? 0;
683
- let catSz = this.categorySize.get(cat) ?? 0;
684
- if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) continue;
685
-
686
- const candidates: Array<{ key: string; score: number }> = [];
687
- for (const key of catKeys) {
688
- const entry = this.cache.get(key);
689
- if (!entry) continue;
690
- if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
691
- candidates.push({ key, score: this.score(entry, 0, now, key) });
692
- }
693
- candidates.sort((a, b) => a.score - b.score);
694
-
695
- for (const { key } of candidates) {
696
- catCnt = this.categoryCount.get(cat) ?? 0;
697
- catSz = this.categorySize.get(cat) ?? 0;
698
- if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) break;
699
- const entry = this.cache.get(key);
700
- if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
701
- this._delete(key, 'rebalance');
702
- evicted++;
703
- }
704
- }
705
-
706
- // Global limits
707
- while (this.cache.size > this.opts.maxEntries || this.totalSize > this.opts.maxBytes) {
708
- const before = this.cache.size;
709
- this.smartEvict('default', false);
710
- if (this.cache.size >= before) break; // only CRITICAL entries remain
711
- evicted += before - this.cache.size;
712
- }
713
-
714
- if (evicted > 0) this.maybeRebuildBloom();
715
- return evicted;
716
- }
717
-
718
- /**
719
- * Return remaining TTL in seconds for a key in L1, or null if absent/expired.
720
- * Only reflects L1 state — does not query Redis or disk.
721
- */
722
- ttl(key: string): number | null {
723
- const entry = this.cache.get(key);
724
- if (!entry) return null;
725
- const remaining = entry.expiresAt - Date.now();
726
- return remaining > 0 ? Math.ceil(remaining / 1000) : null;
727
- }
728
-
729
- /**
730
- * Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
731
- * spilling each to L1.5 disk. Called by the OOM guard when heap pressure
732
- * exceeds the configured threshold.
733
- *
734
- * @param pct - Fraction to evict (0–1), e.g. 0.2 = 20 %
735
- * @returns Number of entries evicted
736
- */
737
- evictPercentage(pct: number): number {
738
- if (pct <= 0 || this.cache.size === 0) return 0;
739
- const now = Date.now();
740
- const candidates: Array<{ key: string; score: number }> = [];
741
- for (const [key, entry] of this.cache) {
742
- if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
743
- candidates.push({ key, score: this.score(entry, 0, now, key) });
744
- }
745
- candidates.sort((a, b) => a.score - b.score);
746
- const count = Math.max(1, Math.ceil(candidates.length * pct));
747
- let evicted = 0;
748
- for (const { key } of candidates.slice(0, count)) {
749
- const entry = this.cache.get(key);
750
- if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
751
- this._delete(key, 'oom');
752
- evicted++;
753
- }
754
- return evicted;
755
- }
756
-
757
- cleanup(): number {
758
- const now = Date.now();
759
- let cleaned = 0;
760
- for (const [key, entry] of this.cache) if (entry.expiresAt < now) { this._delete(key, 'ttl'); cleaned++; }
761
- if (cleaned > 0) { this.bloom.rebuild(this.cache.keys()); this._bloomDirtyCount = 0; }
762
- return cleaned;
763
- }
764
-
765
- /**
766
- * Evict all non-CRITICAL L1 entries that were written before `cutoffMs`.
767
- *
768
- * Called by the backplane staleness fence when the Pub/Sub subscriber
769
- * reconnects after a disconnect gap that exceeded `backplaneMaxStalenessMs`.
770
- * Entries written before the disconnect started may have been invalidated by
771
- * peers while the backplane was down; evicting them forces a controlled
772
- * cold-start re-fetch from L2 rather than serving silently stale data.
773
- *
774
- * Write-time is read from `entry.setAt` (set by `SmartMemoryCache.set()` since v0.7.0).
775
- * Older snapshot entries without `setAt` fall back to approximating via `expiresAt - ttlMs`;
776
- * entries with neither field are treated as potentially stale and evicted conservatively.
777
- *
778
- * @param cutoffMs - Unix timestamp in milliseconds; entries written before
779
- * this time are evicted.
780
- * @returns Number of entries evicted.
781
- */
782
- evictSetBefore(cutoffMs: number): number {
783
- let evicted = 0;
784
- for (const [key, entry] of this.cache) {
785
- // Never evict live CRITICAL entries — auth tokens, active sessions, etc.
786
- if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > Date.now()) continue;
787
-
788
- // Prefer the explicit setAt timestamp; fall back to approximation for older entries.
789
- const setAt = entry.setAt ?? (entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0);
790
-
791
- if (setAt < cutoffMs) {
792
- this._delete(key, 'manual');
793
- evicted++;
794
- }
795
- }
796
- if (evicted > 0) {
797
- this.bloom.rebuild(this.cache.keys());
798
- this._bloomDirtyCount = 0;
799
- }
800
- return evicted;
801
- }
802
-
803
-
804
-
805
- exportEntries(forbiddenPrefixes: readonly string[]): Array<{ key: string; entry: SmartCacheEntry }> {
806
- const now = Date.now();
807
- const out: Array<{ key: string; entry: SmartCacheEntry }> = [];
808
- for (const [key, entry] of this.cache) {
809
- if (entry.expiresAt <= now) continue;
810
- if (entry.priority === 4 /* CRITICAL */) continue;
811
- if (forbiddenPrefixes.some(p => key.startsWith(p))) continue;
812
- out.push({ key, entry: { ...entry } });
813
- }
814
- return out;
815
- }
816
-
817
- importEntries(entries: Array<{ key: string; entry: SmartCacheEntry }>, forbiddenPrefixes: readonly string[]): number {
818
- const now = Date.now();
819
- let loaded = 0;
820
- for (const { key, entry } of entries) {
821
- if (entry.expiresAt <= now) continue;
822
- if (forbiddenPrefixes.some(p => key.startsWith(p))) continue;
823
- if (this.cache.has(key)) continue;
824
- const rawData = entry.data;
825
- // Handle both legacy (isCompressed=false, data=JSON string) and current (data=Buffer) formats.
826
- const data: Buffer = !entry.isCompressed
827
- ? pack(JSON.parse(rawData as unknown as string)) // legacy: re-encode JSON → msgpackr
828
- : rawData instanceof Uint8Array
829
- ? Buffer.from(rawData) // msgpackr Uint8Array → Buffer
830
- : rawData as Buffer; // already a Buffer
831
- // Cache the live object for small entries only — large entries skip double-heap storage.
832
- const value = entry.size <= LARGE_VALUE_BYTES ? unpack(data) : undefined;
833
- this.cache.set(key, { ...entry, data, value, isCompressed: true });
834
- this.bloom.add(key);
835
- loaded++;
836
- }
837
- this.recalculateStats();
838
- return loaded;
839
- }
840
-
841
- // ── Iterators ─────────────────────────────────────────────────────────────
842
-
843
- /**
844
- * Lazily yields every [key, entry] pair whose TTL has not yet expired.
845
- * Expired entries that are still in the Map (awaiting background cleanup)
846
- * are silently skipped.
847
- */
848
- *liveEntries(): Generator<[string, SmartCacheEntry]> {
849
- const now = Date.now();
850
- for (const [key, entry] of this.cache) {
851
- if (entry.expiresAt > now) yield [key, entry];
852
- }
853
- }
854
-
855
- /**
856
- * Non-generator bulk scan over all live entries.
857
- *
858
- * Faster than the generator-based iterators for bulk operations because:
859
- * - No generator state-machine overhead (no yield/resume suspend points).
860
- * - No per-entry tuple allocation (compare `liveEntries()` which yields `[key, entry]`).
861
- * - The same Map call-site is used by a single plain `for` loop instead of being
862
- * shared across three competing generator functions, giving V8's IC a cleaner
863
- * monomorphic profile for this path.
864
- *
865
- * The callback receives the raw (namespaced) key and a `prefixLen` offset so the
866
- * caller can call `key.slice(prefixLen)` only when it actually needs the stripped
867
- * key, avoiding the allocation entirely for callers that don't.
868
- *
869
- * @param fn Called once per live entry.
870
- * @param prefixLen Number of bytes to skip to reach the un-namespaced portion of the key.
871
- * Pass 0 when no namespace is configured.
872
- */
873
- scan(fn: (key: string, entry: SmartCacheEntry, prefixLen: number) => void, prefixLen: number): void {
874
- const now = Date.now();
875
- for (const [key, entry] of this.cache) {
876
- if (entry.expiresAt > now) fn(key, entry, prefixLen);
877
- }
878
- }
879
-
880
- /**
881
- * Yields only the keys of live entries — no intermediate tuple allocation.
882
- * Use this instead of liveEntries() when you only need keys.
883
- */
884
- *liveKeys(): Generator<string> {
885
- const now = Date.now();
886
- for (const [key, entry] of this.cache) {
887
- if (entry.expiresAt > now) yield key;
888
- }
889
- }
890
-
891
- /**
892
- * Yields only the resolved values of live entries.
893
- * Iterates Map.values() so the key is never loaded into the yielded path.
894
- * Returns the deserialized value — identical semantics to get() but without bloom/hit tracking.
895
- */
896
- *liveValues(): Generator<unknown> {
897
- const now = Date.now();
898
- for (const entry of this.cache.values()) {
899
- if (entry.expiresAt > now)
900
- yield this.resolveValue(entry);
901
- }
902
- }
903
-
904
- /**
905
- * Returns the deserialized value for an entry, unpacking from the msgpackr buffer
906
- * if the live object was not cached (large-entry optimisation or disk-restored entry).
907
- */
908
- resolveValue(entry: SmartCacheEntry): unknown {
909
- return entry.value !== undefined ? entry.value : unpack(entry.data as Buffer);
910
- }
911
-
912
- // ── Stats ─────────────────────────────────────────────────────────────────
913
-
914
- get size(): number { return this.cache.size; }
915
- get memoryUsage(): number { return this.totalSize; }
916
-
917
- getStats() {
918
- const categories: Record<string, { entries: number; hits: number }> = {};
919
- for (const [cat, cnt] of this.categoryCount) {
920
- categories[cat] = { entries: cnt, hits: this.categoryHits.get(cat) ?? 0 };
921
- }
922
- return {
923
- entries: this.cache.size,
924
- sizeBytes: this.totalSize,
925
- sizeKB: Math.round(this.totalSize / 1024),
926
- categories,
927
- bloom: {
928
- checks: this.bloomChecks,
929
- falsePositives: this.bloomFalsePos,
930
- },
931
- compression: {
932
- compressed: this.compressions,
933
- uncompressed: 0, // all entries are now msgpackr-packed
934
- bytesSaved: 0, // no longer tracked (unified format removes the split path)
935
- },
936
- };
937
- }
938
-
939
- /**
940
- * Return the raw cache entry for a key, or `undefined` if absent/expired.
941
- * Does NOT count as a hit or perform SWR logic.
942
- */
943
- getEntry(key: string): SmartCacheEntry | undefined {
944
- const entry = this.cache.get(key);
945
- if (!entry) return undefined;
946
- if (entry.expiresAt <= Date.now()) return undefined;
947
- return entry;
948
- }
949
-
950
- /**
951
- * Return true if the key exists in L1 and has not expired.
952
- * Uses the bloom filter as a fast negative check.
953
- */
954
- has(key: string): boolean {
955
- if (!this.bloom.mightContain(key)) return false;
956
- const entry = this.cache.get(key);
957
- if (!entry) return false;
958
- if (entry.expiresAt <= Date.now()) {
959
- this._delete(key, 'ttl');
960
- return false;
961
- }
962
- return true;
963
- }
964
-
965
- /**
966
- * Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
967
- * @param newTtlMs - New TTL from now, in milliseconds.
968
- */
969
- touch(key: string, newTtlMs: number): boolean {
970
- const entry = this.cache.get(key);
971
- if (!entry) return false;
972
- const now = Date.now();
973
- if (entry.expiresAt <= now) { this._delete(key, 'ttl'); return false; }
974
- entry.expiresAt = now + newTtlMs;
975
- return true;
976
- }
977
-
978
- /**
979
- * Add additional milliseconds to a key's existing expiry (for stale-if-error).
980
- * Returns `false` if the key is absent or already expired.
981
- */
982
- bumpExpiry(key: string, additionalMs: number): boolean {
983
- const entry = this.cache.get(key);
984
- if (!entry) return false;
985
- if (entry.expiresAt <= Date.now()) return false;
986
- entry.expiresAt += additionalMs;
987
- return true;
988
- }
989
-
990
- bloomMightContain(key: string): boolean { return this.bloom.mightContain(key); }
991
- bloomStats() { return this.bloom.stats; }
992
-
993
- /**
994
- * Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
995
- * Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
996
- * Useful for diagnosing which keys are driving cache pressure.
997
- *
998
- * @param n - Maximum number of entries to return. Default: 10.
999
- */
1000
- hotKeys(n: number): Array<{ key: string; hits: number; sizeBytes: number }> {
1001
- const now = Date.now();
1002
- const out: Array<{ key: string; hits: number; sizeBytes: number }> = [];
1003
- for (const [key, entry] of this.cache) {
1004
- if (entry.expiresAt <= now) continue;
1005
- out.push({ key, hits: this.sketch.estimate(key), sizeBytes: entry.size });
1006
- }
1007
- out.sort((a, b) => b.hits - a.hits);
1008
- return out.slice(0, n);
1009
- }
1010
- }
1
+ /**
2
+ * SmartMemoryCache — L1 in-process cache with adaptive LFU/LRU hybrid eviction.
3
+ *
4
+ * Features:
5
+ * - WASM Bloom filter for O(k) guaranteed-miss detection (pure-JS fallback)
6
+ * - msgpackr compression for entries ≥ 512 bytes
7
+ * - Category-aware capacity limits (prevents any single key prefix from monopolising RAM)
8
+ * - Priority-weighted adaptive eviction (LFU × LRU × priority score)
9
+ * - Stale-While-Revalidate soft-expiry support (isStale flag on get())
10
+ * - L1.5 disk-spill on eviction — evicted entries are sent to DiskTier before deletion
11
+ * - Periodic cleanup of hard-expired entries + bloom filter rebuild
12
+ * - Process-level singleton via globalThis (survives Next.js hot reloads)
13
+ */
14
+
15
+ import { pack, unpack } from 'msgpackr';
16
+ import type { CacheHit, CachePriority, CategoryLimit, SmartCacheEntry, ILogger, EvictionReason } from './types';
17
+
18
+ /**
19
+ * Packed-byte threshold above which the live JS object is NOT stored alongside the
20
+ * serialised buffer. For entries above this size, the double-heap overhead (both the
21
+ * msgpackr Buffer and the deserialized object resident simultaneously) outweighs the
22
+ * latency saved by skipping unpack on read. Below the threshold the live object is
23
+ * stored so hot reads skip deserialization entirely.
24
+ *
25
+ * 16 KiB is a conservative default: msgpackr unpacks a 16 KiB buffer in ~0.03 ms,
26
+ * while storing the deserialized form of a 16 KiB payload typically costs 32–64 KiB
27
+ * of additional heap depending on object shape.
28
+ */
29
+ const LARGE_VALUE_BYTES = 16_384;
30
+ import { WasmBloomFilter } from './wasm/bloom-filter-wasm';
31
+
32
+
33
+
34
+ /** Fraction of candidates evicted in one pass when a limit is exceeded */
35
+ const EVICTION_BATCH_PERCENT = 0.2;
36
+ /** Reservoir sample window for smartEvict() — Redis-style. */
37
+ const EVICTION_SAMPLE = 16;
38
+ /** Number of lowest-scored candidates evicted per smartEvict() call. */
39
+ const EVICT_COUNT = Math.max(1, Math.ceil(EVICTION_SAMPLE * EVICTION_BATCH_PERCENT)); // 4
40
+
41
+ // ─── Pure-JS Bloom filter fallback ───────────────────────────────────────────
42
+
43
+ class JsBloomFilter {
44
+ private bits: Buffer;
45
+ private readonly numBits: number;
46
+ private readonly k: number;
47
+ /** Pre-computed — numBits and k are constant, no need to recalculate on every probe. */
48
+ private readonly _maxCapacity: number;
49
+ /** Tracks total add() calls so we know when phantom bits have saturated the filter. */
50
+ private _insertionCount = 0;
51
+
52
+ constructor(numBits = 100_000, k = 7) {
53
+ this.numBits = numBits;
54
+ this.k = k;
55
+ this.bits = Buffer.alloc(Math.ceil(numBits / 8), 0);
56
+ const p = 0.01;
57
+ this._maxCapacity = Math.floor(-numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
58
+ }
59
+
60
+ private fnv1a32(s: string): number {
61
+ let h = 0x811c9dc5;
62
+ for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; }
63
+ return h >>> 0;
64
+ }
65
+
66
+ private djb2(s: string): number {
67
+ let h = 5381;
68
+ for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0;
69
+ return h >>> 0;
70
+ }
71
+
72
+ private setBit(i: number) { this.bits[i >>> 3] |= 1 << (i & 7); }
73
+ private getBit(i: number): boolean { return (this.bits[i >>> 3] & (1 << (i & 7))) !== 0; }
74
+
75
+ add(key: string): void {
76
+ const h1 = this.fnv1a32(key), h2 = this.djb2(key);
77
+ for (let i = 0; i < this.k; i++) this.setBit(((h1 + i * h2) >>> 0) % this.numBits);
78
+ this._insertionCount++;
79
+ }
80
+
81
+ mightContain(key: string): boolean {
82
+ const h1 = this.fnv1a32(key), h2 = this.djb2(key);
83
+ for (let i = 0; i < this.k; i++) if (!this.getBit(((h1 + i * h2) >>> 0) % this.numBits)) return false;
84
+ return true;
85
+ }
86
+
87
+ reset() { this.bits.fill(0); this._insertionCount = 0; }
88
+ rebuild(keys: Iterable<string>) { this.bits.fill(0); this._insertionCount = 0; for (const k of keys) this.add(k); }
89
+
90
+ /** Number of add() calls since last reset/rebuild. */
91
+ get insertions(): number { return this._insertionCount; }
92
+
93
+ /**
94
+ * Maximum safe insertions before false-positive rate exceeds ~1 %.
95
+ * Exact formula for the configured k and target p=1 %:
96
+ * n_max = -m * ln(1 - p^(1/k)) / k
97
+ */
98
+ get maxCapacity(): number { return this._maxCapacity; }
99
+
100
+ get stats(): { bitsSet: number; fillFactor: number } {
101
+ let bitsSet = 0;
102
+ for (const byte of this.bits) { let b = byte; while (b) { bitsSet++; b &= b - 1; } }
103
+ return { bitsSet, fillFactor: bitsSet / this.numBits };
104
+ }
105
+ }
106
+
107
+ type AnyBloomFilter = JsBloomFilter | WasmBloomFilter;
108
+
109
+ /**
110
+ * Return a bloom filter sized for `maxEntries` at a ~1 % false-positive target.
111
+ *
112
+ * The WASM filter is hardcoded at 100 K bits (k = 7), which holds ≈ 10 400 entries
113
+ * at 1 % FP. For larger caches the filter saturates quickly, producing high FP rates
114
+ * that force wasted Map.get() calls on every definite miss. When `maxEntries` exceeds
115
+ * the WASM filter's rated capacity, we instantiate a JS filter sized via the optimal
116
+ * formula: m = ⌈–n · ln p / (ln 2)²⌉ with k = round(ln 2 · m / n) clamped to [4, 10].
117
+ */
118
+ function createBloomFilter(logger: ILogger, maxEntries: number): AnyBloomFilter {
119
+ // Compute optimal bit-count for p = 1 % and the requested entry ceiling.
120
+ const LN2_SQ = Math.LN2 * Math.LN2; // (ln 2)² ≈ 0.4804
121
+ const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
122
+ const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
123
+
124
+ try {
125
+ const wasm = new WasmBloomFilter();
126
+ if (wasm.maxCapacity >= maxEntries) {
127
+ logger.debug('SmartMemoryCache: WASM BloomFilter active');
128
+ return wasm;
129
+ }
130
+ // WASM filter is undersized for this cache — fall through to right-sized JS filter.
131
+ logger.debug('SmartMemoryCache: WASM BloomFilter capacity too small, using sized JS BloomFilter', {
132
+ wasmCapacity: wasm.maxCapacity, maxEntries, optimalBits,
133
+ });
134
+ } catch (err) {
135
+ logger.debug('SmartMemoryCache: WASM unavailable — using pure-JS BloomFilter', { reason: (err as Error).message });
136
+ }
137
+ return new JsBloomFilter(optimalBits, optimalK);
138
+ }
139
+
140
+ // ─── Count-Min Sketch ─────────────────────────────────────────────────────────
141
+ //
142
+ // Estimates historical access frequency across eviction boundaries — a per-entry
143
+ // `hits` counter resets to 1 whenever a key is re-admitted after eviction, but
144
+ // the sketch remembers the key's frequency in a fixed-size typed array that
145
+ // survives evictions. This closes the same-priority burst-flood gap: a key that
146
+ // has been accessed 80 times over the last hour but was evicted 5 minutes ago
147
+ // will score far above a brand-new burst key whose hits = 1.
148
+ //
149
+ // Dimensions: 4 rows × 512 counters (Uint16Array) — 4 KB total, fits in L1d.
150
+ // Hash: four independent Murmur3-fragment mixes of the key's FNV-1a digest.
151
+ // Decay: all counters halved when total insertions cross SKETCH_DECAY_THRESHOLD
152
+ // (frequency-ageing prevents indefinitely growing hot-key counts).
153
+
154
+ const SKETCH_ROWS = 4;
155
+ const SKETCH_WIDTH = 512; // must be power of two
156
+ const SKETCH_MASK = SKETCH_WIDTH - 1;
157
+ const SKETCH_DECAY_THRESHOLD = 100_000;
158
+
159
+ class CountMinSketch {
160
+ private readonly table = new Uint16Array(SKETCH_ROWS * SKETCH_WIDTH);
161
+ private inserts = 0;
162
+
163
+ /** Inline FNV-1a for a string key → 32-bit unsigned integer. */
164
+ private fnv32(key: string): number {
165
+ let h = 0x811c9dc5;
166
+ for (let i = 0; i < key.length; i++) {
167
+ h ^= key.charCodeAt(i);
168
+ h = (Math.imul(h, 0x01000193) >>> 0);
169
+ }
170
+ return h;
171
+ }
172
+
173
+ /** Record one access. Decays all counters when the insertion threshold is crossed. */
174
+ increment(key: string): void {
175
+ const h = this.fnv32(key);
176
+ const h1 = (h ^ (h >>> 16)) >>> 0;
177
+ const h2 = (Math.imul(h1, 0x45d9f3b) ^ (h1 >>> 16)) >>> 0;
178
+ const h3 = (Math.imul(h2, 0x7fb9b7a1) ^ (h2 >>> 16)) >>> 0;
179
+ const h4 = (Math.imul(h3, 0x1b873593) ^ (h3 >>> 16)) >>> 0;
180
+ const t = this.table;
181
+ const i0 = h1 & SKETCH_MASK;
182
+ const i1 = SKETCH_WIDTH + (h2 & SKETCH_MASK);
183
+ const i2 = 2 * SKETCH_WIDTH + (h3 & SKETCH_MASK);
184
+ const i3 = 3 * SKETCH_WIDTH + (h4 & SKETCH_MASK);
185
+ if (t[i0] < 0xffff) t[i0]++;
186
+ if (t[i1] < 0xffff) t[i1]++;
187
+ if (t[i2] < 0xffff) t[i2]++;
188
+ if (t[i3] < 0xffff) t[i3]++;
189
+ if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
190
+ }
191
+
192
+ /** Minimum-across-rows frequency estimate. */
193
+ estimate(key: string): number {
194
+ const h = this.fnv32(key);
195
+ const h1 = (h ^ (h >>> 16)) >>> 0;
196
+ const h2 = (Math.imul(h1, 0x45d9f3b) ^ (h1 >>> 16)) >>> 0;
197
+ const h3 = (Math.imul(h2, 0x7fb9b7a1) ^ (h2 >>> 16)) >>> 0;
198
+ const h4 = (Math.imul(h3, 0x1b873593) ^ (h3 >>> 16)) >>> 0;
199
+ const t = this.table;
200
+ return Math.min(
201
+ t[h1 & SKETCH_MASK],
202
+ t[SKETCH_WIDTH + (h2 & SKETCH_MASK)],
203
+ t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
204
+ t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)],
205
+ );
206
+ }
207
+
208
+ /** Halve all counters — ages out old frequency so bursts don't hold indefinitely. */
209
+ private decay(): void {
210
+ for (let i = 0; i < this.table.length; i++) this.table[i] >>>= 1;
211
+ this.inserts = 0;
212
+ }
213
+ }
214
+
215
+ // ─── Glob matcher ───────────────────────────────────────────────────────────────
216
+
217
+ /**
218
+ * Pure-string glob matcher — replaces RegExp on the deletePattern hot path.
219
+ * Supports only '*' wildcards (any sequence, including empty).
220
+ * No NFA/DFA state machine, no backtracking.
221
+ *
222
+ * Two-layer design to avoid per-key allocation in the inner loop:
223
+ * globMatch() — public entry point; splits the pattern once.
224
+ * globMatchParts() — hot inner loop; receives the pre-split segments.
225
+ *
226
+ * Algorithm:
227
+ * 1. First segment anchors the prefix (startsWith, O(|first|)).
228
+ * 2. Last segment anchors the suffix (endsWith, O(|last|)).
229
+ * 3. Middle segments are located left-to-right with indexOf (O(N) total, no re-scan).
230
+ */
231
+ function globMatchParts(parts: string[], first: string, last: string, key: string): boolean {
232
+ if (first.length > 0 && !key.startsWith(first)) return false;
233
+ if (last.length > 0 && !key.endsWith(last)) return false;
234
+ if (first.length + last.length > key.length) return false; // anchors overlap
235
+
236
+ // Walk any middle segments left-to-right — indexOf never backtracks.
237
+ let pos = first.length;
238
+ const end = key.length - last.length;
239
+ for (let i = 1; i < parts.length - 1; i++) {
240
+ const seg = parts[i];
241
+ if (seg.length === 0) continue; // consecutive '*' — skip
242
+ const idx = key.indexOf(seg, pos);
243
+ if (idx === -1 || idx + seg.length > end) return false;
244
+ pos = idx + seg.length;
245
+ }
246
+ return true;
247
+ }
248
+
249
+ // ─── SmartMemoryCache ─────────────────────────────────────────────────────────
250
+
251
+ export interface SmartMemoryCacheOptions {
252
+ maxBytes: number;
253
+ maxEntries: number;
254
+ categories: Record<string, CategoryLimit>;
255
+ diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
256
+ onEviction?: (key: string, reason: EvictionReason) => void;
257
+ logger: ILogger;
258
+ /** Fraction of maxEntries / maxBytes at which proactive eviction fires (default 0.9). */
259
+ evictionWatermark?: number;
260
+ }
261
+
262
+ export class SmartMemoryCache {
263
+ private readonly cache = new Map<string, SmartCacheEntry>();
264
+ private readonly opts: SmartMemoryCacheOptions;
265
+ private bloom: AnyBloomFilter;
266
+ /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
267
+ private readonly categoryPrefixes: string[];
268
+ /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
269
+ private readonly sketch = new CountMinSketch();
270
+ private totalSize = 0;
271
+ private categoryCount = new Map<string, number>();
272
+ private categorySize = new Map<string, number>();
273
+ /** Per-category key sets — enables O(catSize) Phase-1 reservoir sampling without an O(N) scan. */
274
+ private categoryKeys = new Map<string, Set<string>>();
275
+
276
+ // ── Observability counters ──────────────────────────────────────────────────────
277
+ private bloomChecks = 0;
278
+ private bloomFalsePos = 0;
279
+ private compressions = 0; private categoryHits = new Map<string, number>();
280
+ /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
281
+ private _bloomDirtyCount = 0;
282
+
283
+ /**
284
+ * Pre-allocated eviction candidate pools — reused across every smartEvict() call to
285
+ * eliminate per-call heap pressure. Each slot holds a mutable {key, score} record
286
+ * that is overwritten in-place rather than replaced with a new object literal.
287
+ * Safe because JS is single-threaded: smartEvict() completes synchronously before
288
+ * any other code can observe the pool state.
289
+ */
290
+ private readonly _evictPool: Array<{ key: string; score: number }> =
291
+ Array.from({ length: EVICTION_SAMPLE }, () => ({ key: '', score: 0 }));
292
+ private readonly _evictGPool: Array<{ key: string; score: number }> =
293
+ Array.from({ length: EVICTION_SAMPLE }, () => ({ key: '', score: 0 }));
294
+
295
+ constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>) {
296
+ this.opts = opts;
297
+ this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
298
+ this.categoryPrefixes = Object.keys(opts.categories).filter(k => k !== 'default');
299
+
300
+ if (existing) {
301
+ for (const [k, v] of existing) this.cache.set(k, v);
302
+ this.recalculateStats();
303
+ for (const key of this.cache.keys()) this.bloom.add(key);
304
+ }
305
+ }
306
+
307
+ // ── Internal helpers ──────────────────────────────────────────────────────
308
+
309
+ private recalculateStats(): void {
310
+ this.totalSize = 0;
311
+ this.categoryCount.clear();
312
+ this.categorySize.clear();
313
+ this.categoryKeys.clear();
314
+ for (const [key, entry] of this.cache) {
315
+ this.totalSize += entry.size;
316
+ const cat = this.getCategory(key);
317
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
318
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? 0) + entry.size);
319
+ let ks = this.categoryKeys.get(cat);
320
+ if (!ks) { ks = new Set(); this.categoryKeys.set(cat, ks); }
321
+ ks.add(key);
322
+ }
323
+ }
324
+
325
+ private getCategory(key: string): string {
326
+ for (const prefix of this.categoryPrefixes) {
327
+ if (key.startsWith(prefix)) return prefix;
328
+ }
329
+ return 'default';
330
+ }
331
+
332
+ private getCategoryLimit(cat: string): CategoryLimit {
333
+ return this.opts.categories[cat] ?? this.opts.categories['default'] ?? { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 };
334
+ }
335
+
336
+ private _delete(key: string, reason: EvictionReason = 'manual'): boolean {
337
+ const entry = this.cache.get(key);
338
+ if (!entry) return false;
339
+ const cat = this.getCategory(key);
340
+ this.totalSize -= entry.size;
341
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
342
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? entry.size) - entry.size);
343
+ this.categoryKeys.get(cat)?.delete(key);
344
+ this._bloomDirtyCount++;
345
+ const deleted = this.cache.delete(key);
346
+ if (deleted && this.opts.onEviction) {
347
+ try { this.opts.onEviction(key, reason); } catch { /* never crash cache */ }
348
+ }
349
+ return deleted;
350
+ }
351
+
352
+ private ensureCapacity(category: string, neededSize: number): void {
353
+ const lim = this.getCategoryLimit(category);
354
+ const catCnt = this.categoryCount.get(category) ?? 0;
355
+ const catSz = this.categorySize.get(category) ?? 0;
356
+ let catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
357
+ let glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
358
+ if (!catOvf && !glbOvf) {
359
+ // Proactive watermark: when either the global entry count OR total byte
360
+ // usage crosses 90 % of its configured ceiling while there is still
361
+ // headroom, run one eviction pass now — during the cheap headroom path —
362
+ // so the hard cliffs at 100 % are rarely reached and writes at full
363
+ // capacity become uncommon. Both dimensions are guarded so that
364
+ // large-payload workloads (where maxBytes is the binding constraint)
365
+ // benefit equally alongside entry-count-bound workloads.
366
+ const wm = this.opts.evictionWatermark ?? 0.9;
367
+ const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * wm);
368
+ const byteWatermark = this.totalSize + neededSize >= Math.floor(this.opts.maxBytes * wm);
369
+ if (entryWatermark || byteWatermark) {
370
+ this.smartEvict(category, false);
371
+ }
372
+ return;
373
+ }
374
+ // Hard overflow: evict until back under BOTH the category and global limits.
375
+ // A single smartEvict() pass removes at most EVICT_COUNT entries, which is not
376
+ // enough when one set() pushes the cache far past its ceiling (e.g. a large
377
+ // entry that itself dominates the byte budget). Loop until the overflow clears,
378
+ // bounded by MAX_EVICT_PASSES so a pathological key (larger than the limit
379
+ // cannot be evicted to fit itself) cannot spin forever.
380
+ const MAX_EVICT_PASSES = 64;
381
+ let passes = 0;
382
+ do {
383
+ this.smartEvict(category, catOvf);
384
+ const lim2 = this.getCategoryLimit(category);
385
+ const catCnt2 = this.categoryCount.get(category) ?? 0;
386
+ const catSz2 = this.categorySize.get(category) ?? 0;
387
+ catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
388
+ glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
389
+ passes++;
390
+ } while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
391
+ }
392
+
393
+ private score(entry: SmartCacheEntry, catBonus: number, now: number, key: string): number {
394
+ const age = now - entry.lastAccess;
395
+ const ttl = Math.max(0, entry.expiresAt - now);
396
+ // Use the sketch's cross-eviction frequency estimate when it exceeds the
397
+ // entry's current-tenure hit count — protects long-resident keys that were
398
+ // recently re-admitted (hits reset to 1) from same-priority burst floods.
399
+ const freq = Math.min(Math.max(entry.hits, this.sketch.estimate(key)), 100);
400
+ return entry.priority * 1000 + freq * 10 + ttl / 60000 - age / 60000 - catBonus;
401
+ }
402
+
403
+ /**
404
+ * Rebuild the bloom filter when phantom bits from deleted/expired keys have
405
+ * saturated the filter past its ~1 % FP capacity.
406
+ *
407
+ * Trigger: (insertions − live entries) > maxCapacity
408
+ *
409
+ * Using the phantom count (insertions − cache.size) instead of raw insertions
410
+ * prevents an O(cache.size) rebuild from re-firing on every set() when the
411
+ * cache holds more entries than the filter's rated capacity — which would
412
+ * stall the write path entirely.
413
+ *
414
+ * After rebuild: insertions = cache.size → phantoms = 0 → no immediate re-trigger.
415
+ */
416
+ private maybeRebuildBloom(): void {
417
+ // Two independent triggers — whichever fires first:
418
+ // 1. Phantom count (insertions of dead keys since last rebuild)
419
+ // 2. Deletion count (ANY _delete() call — expiry, eviction, or explicit)
420
+ //
421
+ // Dirty-count cap: bloom.maxCapacity grows proportionally with filter size, but
422
+ // we want rebuild frequency to stay proportional to cache ENTRY count, not bit
423
+ // count. Without the cap a JS filter sized for 50 K entries allows ~12 500 ghost
424
+ // entries before a rebuild — 5× longer than the old WASM filter, which let phantom
425
+ // bits accumulate and raised the measured FP rate. The cap restores the original
426
+ // rebuild cadence: rebuild after ~5 % of maxEntries are deleted, with a 256 floor.
427
+ const dirtyThreshold = Math.max(256, Math.min(this.bloom.maxCapacity >>> 2, Math.ceil(this.opts.maxEntries * 0.05)));
428
+ if (this._bloomDirtyCount > dirtyThreshold ||
429
+ this.bloom.insertions - this.cache.size > this.bloom.maxCapacity) {
430
+ this.bloom.rebuild(this.cache.keys());
431
+ this._bloomDirtyCount = 0;
432
+ }
433
+ }
434
+
435
+ private smartEvict(targetCat: string, catOvf: boolean): void {
436
+ const now = Date.now();
437
+ const pool = this._evictPool;
438
+ const gPool = this._evictGPool;
439
+ let poolLen = 0;
440
+
441
+ if (catOvf) {
442
+ // Phase 1 — O(catSize) category-local reservoir sample.
443
+ // Uses the categoryKeys index to iterate only the overflowing category's keys,
444
+ // avoiding an O(N) scan of the entire cache. Guarantees at least
445
+ // min(catSize, EVICT_COUNT) entries from the overflowing category in the pool so
446
+ // the priority score ordering is always deterministic in practice.
447
+ const catKeySet = this.categoryKeys.get(targetCat);
448
+ if (catKeySet) {
449
+ let catSeen = 0;
450
+ for (const key of catKeySet) {
451
+ const entry = this.cache.get(key);
452
+ if (!entry || (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now)) continue;
453
+ catSeen++;
454
+ const s = this.score(entry, 100, now, key);
455
+ if (poolLen < EVICT_COUNT) {
456
+ pool[poolLen].key = key; pool[poolLen].score = s; poolLen++;
457
+ } else {
458
+ const j = Math.floor(Math.random() * catSeen);
459
+ if (j < EVICT_COUNT) { pool[j].key = key; pool[j].score = s; }
460
+ }
461
+ }
462
+ }
463
+ }
464
+
465
+ // Phase 2 — global reservoir sample fills remaining EVICTION_SAMPLE-poolLen slots.
466
+ // Skipped entirely when Phase 1 already collected a full EVICT_COUNT-sized pool
467
+ // (the common catOvf case — overflowing categories always have ≥ EVICT_COUNT entries).
468
+ // Also the sole phase when !catOvf (global over-capacity, no preferred category).
469
+ if (poolLen < EVICT_COUNT) {
470
+ const remaining = EVICTION_SAMPLE - poolLen;
471
+ let globalSeen = 0;
472
+ let gLen = 0;
473
+ for (const [key, entry] of this.cache) {
474
+ if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
475
+ if (catOvf && this.getCategory(key) === targetCat) continue; // already sampled above
476
+ globalSeen++;
477
+ const s = this.score(entry, 0, now, key);
478
+ if (gLen < remaining) {
479
+ gPool[gLen].key = key; gPool[gLen].score = s; gLen++;
480
+ } else {
481
+ const j = Math.floor(Math.random() * globalSeen);
482
+ if (j < remaining) { gPool[j].key = key; gPool[j].score = s; }
483
+ }
484
+ }
485
+ // Manual merge — no spread, no new array
486
+ for (let i = 0; i < gLen; i++) {
487
+ pool[poolLen].key = gPool[i].key; pool[poolLen].score = gPool[i].score; poolLen++;
488
+ }
489
+ }
490
+
491
+ if (poolLen === 0) return;
492
+
493
+ // Insertion sort — O(poolLen²) but poolLen ≤ EVICTION_SAMPLE=16 (max 256 comparisons).
494
+ // Faster than Array.sort() at this scale: no comparator closure call overhead,
495
+ // no timsort startup, no allocation. Sorts in-place within the pre-allocated pool.
496
+ for (let i = 1; i < poolLen; i++) {
497
+ const sk = pool[i].key, ss = pool[i].score;
498
+ let j = i - 1;
499
+ while (j >= 0 && pool[j].score > ss) {
500
+ pool[j + 1].key = pool[j].key; pool[j + 1].score = pool[j].score; j--;
501
+ }
502
+ pool[j + 1].key = sk; pool[j + 1].score = ss;
503
+ }
504
+
505
+ const toEvict = Math.min(EVICT_COUNT, poolLen);
506
+ for (let i = 0; i < toEvict; i++) {
507
+ const key = pool[i].key;
508
+ const entry = this.cache.get(key);
509
+ if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry); // L1.5 spill
510
+ this._delete(key, 'capacity');
511
+ }
512
+ }
513
+
514
+ // ── Public API ────────────────────────────────────────────────────────────
515
+
516
+ get(key: string): CacheHit | null {
517
+ this.bloomChecks++;
518
+ if (!this.bloom.mightContain(key)) return null;
519
+ const entry = this.cache.get(key);
520
+ if (!entry) { this.bloomFalsePos++; return null; }
521
+ const now = Date.now();
522
+ if (entry.expiresAt < now) { this._delete(key, 'ttl'); return null; }
523
+ entry.hits++;
524
+ entry.lastAccess = now;
525
+ // Sample sketch at 25 % — eviction scoring only needs relative frequency, not exact counts.
526
+ if ((entry.hits & 3) === 0) this.sketch.increment(key);
527
+ // value is cached at write time — hot reads return the live object directly,
528
+ // skipping unpack. Falls back to decode for entries restored from disk/snapshot.
529
+ const value = entry.value !== undefined ? entry.value : unpack(entry.data as Buffer);
530
+ // Fresh object per call — never a shared/reusable one. Callers hold this result
531
+ // across await boundaries (CacheService.get() awaits tag-version checks between
532
+ // the L1 hit and the return); a shared object would let a concurrent get()
533
+ // repurpose those fields for another key (silent cross-key data corruption).
534
+ const hit: CacheHit = {
535
+ value,
536
+ isStale: entry.staleAt !== undefined && now > entry.staleAt,
537
+ expiresAt: entry.expiresAt,
538
+ ttlMs: entry.ttlMs,
539
+ delta: entry.delta,
540
+ fetchedAt: now,
541
+ tagVersions: entry.tagVersions,
542
+ setAt: entry.setAt,
543
+ };
544
+ return hit;
545
+ }
546
+
547
+ set(
548
+ key: string,
549
+ data: unknown,
550
+ ttlMs: number,
551
+ priority: CachePriority = 2 /* NORMAL */,
552
+ staleAt?: number,
553
+ delta?: number,
554
+ tagVersions?: Record<string, number>,
555
+ ): void {
556
+ // Single serialization pass — always msgpackr. Eliminates the prior JSON.stringify
557
+ // "size probe" that was discarded for large payloads (the double-pass).
558
+ const packed = pack(data);
559
+ const size = packed.byteLength;
560
+ this.compressions++;
561
+ this.sketch.increment(key);
562
+
563
+ const cat = this.getCategory(key);
564
+ const lim = this.getCategoryLimit(cat);
565
+
566
+ if (size > lim.maxSizeBytes * 0.5) {
567
+ this.opts.logger.debug('SmartMemoryCache: entry too large, skipping', { key, sizeBytes: size });
568
+ return;
569
+ }
570
+
571
+ // Single Map.get replaces Map.has + _delete's Map.get (saves one lookup on overwrite).
572
+ const existingEntry = this.cache.get(key);
573
+ if (existingEntry) {
574
+ this.totalSize -= existingEntry.size;
575
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
576
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
577
+ this.cache.delete(key);
578
+ }
579
+ this.ensureCapacity(cat, size);
580
+
581
+ const now = Date.now();
582
+ // Only cache the live object for small entries — large entries would store the packed
583
+ // buffer AND a potentially much-larger deserialized object simultaneously (double-heap).
584
+ // For large entries, get() falls back to the unpack() path transparently.
585
+ const liveValue = size <= LARGE_VALUE_BYTES ? data : undefined;
586
+ this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now, tagVersions });
587
+ // Only add new keys to the bloom — overwrites already have their bits set.
588
+ // Re-adding inflates the insertions counter, delaying trigger-2 phantom detection.
589
+ if (!existingEntry) this.bloom.add(key);
590
+ this.maybeRebuildBloom();
591
+ this.totalSize += size;
592
+ this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 0) + 1);
593
+ this.categorySize.set(cat, (this.categorySize.get(cat) ?? 0) + size);
594
+ let ks = this.categoryKeys.get(cat);
595
+ if (!ks) { ks = new Set(); this.categoryKeys.set(cat, ks); }
596
+ ks.add(key);
597
+ }
598
+
599
+ delete(key: string): boolean {
600
+ const deleted = this._delete(key, 'manual');
601
+ if (deleted) this.maybeRebuildBloom();
602
+ return deleted;
603
+ }
604
+
605
+ private keysMatchingPattern(pattern: string): string[] {
606
+ if (!pattern.includes('*')) return this.cache.has(pattern) ? [pattern] : [];
607
+
608
+ // Fast path: trailing-only wildcard whose prefix exactly matches a configured
609
+ // category (e.g. deletePattern('user:*') when 'user:' is a category).
610
+ // categoryKeys already indexes all live keys per category prefix in O(1),
611
+ // so we skip the O(N) Map scan and regex evaluation entirely.
612
+ // We snapshot via Array.from() before returning so _delete() mutations to
613
+ // the Set during the subsequent iteration are safe.
614
+ if (pattern.endsWith('*') && pattern.indexOf('*') === pattern.length - 1) {
615
+ const prefix = pattern.slice(0, -1);
616
+ const catKeys = this.categoryKeys.get(prefix);
617
+ if (catKeys !== undefined) return Array.from(catKeys);
618
+ }
619
+
620
+ // Fast path: exactly one '*' that is NOT at the end (e.g. "user:*:profile").
621
+ // AOT detection lets us avoid globMatchParts dispatch and its empty middle-
622
+ // segment loop — keys only need startsWith + endsWith + length checks inline.
623
+ const firstStar = pattern.indexOf('*');
624
+ if (firstStar === pattern.lastIndexOf('*')) {
625
+ const prefix = pattern.slice(0, firstStar);
626
+ const suffix = pattern.slice(firstStar + 1); // empty when star is last char
627
+ const minLen = prefix.length + suffix.length;
628
+ const out: string[] = [];
629
+ for (const k of this.cache.keys()) {
630
+ if (k.length >= minLen && k.startsWith(prefix) && k.endsWith(suffix)) out.push(k);
631
+ }
632
+ return out;
633
+ }
634
+
635
+ // General case: multiple '*' wildcards — split once, then scan.
636
+ const parts = pattern.split('*');
637
+ const first = parts[0];
638
+ const last = parts[parts.length - 1];
639
+ const out: string[] = [];
640
+ for (const k of this.cache.keys()) if (globMatchParts(parts, first, last, k)) out.push(k);
641
+ return out;
642
+ }
643
+
644
+ deletePattern(pattern: string): number {
645
+ let n = 0;
646
+ for (const key of this.keysMatchingPattern(pattern)) if (this._delete(key, 'manual')) n++;
647
+ if (n > 0) this.maybeRebuildBloom();
648
+ return n;
649
+ }
650
+
651
+ /** Flush all entries, or only those whose key starts with `prefix`. */
652
+ clear(prefix?: string): number {
653
+ if (prefix) {
654
+ const pattern = prefix.includes('*') ? prefix : `${prefix}*`;
655
+ return this.deletePattern(pattern);
656
+ }
657
+ const count = this.cache.size;
658
+ this.cache.clear();
659
+ this.totalSize = 0;
660
+ this.categoryCount.clear();
661
+ this.categorySize.clear();
662
+ this.categoryKeys.clear();
663
+ this.categoryHits.clear();
664
+ this.bloom.reset();
665
+ this._bloomDirtyCount = 0;
666
+ return count;
667
+ }
668
+
669
+ /**
670
+ * Evict entries that violate current category or global limits.
671
+ * Returns the number of entries evicted.
672
+ */
673
+ rebalance(): number {
674
+ const now = Date.now();
675
+ let evicted = 0;
676
+
677
+ for (const [cat, limit] of Object.entries(this.opts.categories)) {
678
+ const catKeys = this.categoryKeys.get(cat);
679
+ if (!catKeys || catKeys.size === 0) continue;
680
+
681
+ let catCnt = this.categoryCount.get(cat) ?? 0;
682
+ let catSz = this.categorySize.get(cat) ?? 0;
683
+ if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) continue;
684
+
685
+ const candidates: Array<{ key: string; score: number }> = [];
686
+ for (const key of catKeys) {
687
+ const entry = this.cache.get(key);
688
+ if (!entry) continue;
689
+ if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
690
+ candidates.push({ key, score: this.score(entry, 0, now, key) });
691
+ }
692
+ candidates.sort((a, b) => a.score - b.score);
693
+
694
+ for (const { key } of candidates) {
695
+ catCnt = this.categoryCount.get(cat) ?? 0;
696
+ catSz = this.categorySize.get(cat) ?? 0;
697
+ if (catCnt <= limit.maxEntries && catSz <= limit.maxSizeBytes) break;
698
+ const entry = this.cache.get(key);
699
+ if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
700
+ this._delete(key, 'rebalance');
701
+ evicted++;
702
+ }
703
+ }
704
+
705
+ // Global limits
706
+ while (this.cache.size > this.opts.maxEntries || this.totalSize > this.opts.maxBytes) {
707
+ const before = this.cache.size;
708
+ this.smartEvict('default', false);
709
+ if (this.cache.size >= before) break; // only CRITICAL entries remain
710
+ evicted += before - this.cache.size;
711
+ }
712
+
713
+ if (evicted > 0) this.maybeRebuildBloom();
714
+ return evicted;
715
+ }
716
+
717
+ /**
718
+ * Return remaining TTL in seconds for a key in L1, or null if absent/expired.
719
+ * Only reflects L1 state — does not query Redis or disk.
720
+ */
721
+ ttl(key: string): number | null {
722
+ const entry = this.cache.get(key);
723
+ if (!entry) return null;
724
+ const remaining = entry.expiresAt - Date.now();
725
+ return remaining > 0 ? Math.ceil(remaining / 1000) : null;
726
+ }
727
+
728
+ /**
729
+ * Forcibly evict the coldest `pct` fraction of non-CRITICAL L1 entries,
730
+ * spilling each to L1.5 disk. Called by the OOM guard when heap pressure
731
+ * exceeds the configured threshold.
732
+ *
733
+ * @param pct - Fraction to evict (0–1), e.g. 0.2 = 20 %
734
+ * @returns Number of entries evicted
735
+ */
736
+ evictPercentage(pct: number): number {
737
+ if (pct <= 0 || this.cache.size === 0) return 0;
738
+ const now = Date.now();
739
+ const candidates: Array<{ key: string; score: number }> = [];
740
+ for (const [key, entry] of this.cache) {
741
+ if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
742
+ candidates.push({ key, score: this.score(entry, 0, now, key) });
743
+ }
744
+ candidates.sort((a, b) => a.score - b.score);
745
+ const count = Math.max(1, Math.ceil(candidates.length * pct));
746
+ let evicted = 0;
747
+ for (const { key } of candidates.slice(0, count)) {
748
+ const entry = this.cache.get(key);
749
+ if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry);
750
+ this._delete(key, 'oom');
751
+ evicted++;
752
+ }
753
+ return evicted;
754
+ }
755
+
756
+ cleanup(): number {
757
+ const now = Date.now();
758
+ let cleaned = 0;
759
+ for (const [key, entry] of this.cache) if (entry.expiresAt < now) { this._delete(key, 'ttl'); cleaned++; }
760
+ if (cleaned > 0) { this.bloom.rebuild(this.cache.keys()); this._bloomDirtyCount = 0; }
761
+ return cleaned;
762
+ }
763
+
764
+ /**
765
+ * Evict all non-CRITICAL L1 entries that were written before `cutoffMs`.
766
+ *
767
+ * Called by the backplane staleness fence when the Pub/Sub subscriber
768
+ * reconnects after a disconnect gap that exceeded `backplaneMaxStalenessMs`.
769
+ * Entries written before the disconnect started may have been invalidated by
770
+ * peers while the backplane was down; evicting them forces a controlled
771
+ * cold-start re-fetch from L2 rather than serving silently stale data.
772
+ *
773
+ * Write-time is read from `entry.setAt` (set by `SmartMemoryCache.set()` since v0.7.0).
774
+ * Older snapshot entries without `setAt` fall back to approximating via `expiresAt - ttlMs`;
775
+ * entries with neither field are treated as potentially stale and evicted conservatively.
776
+ *
777
+ * @param cutoffMs - Unix timestamp in milliseconds; entries written before
778
+ * this time are evicted.
779
+ * @returns Number of entries evicted.
780
+ */
781
+ evictSetBefore(cutoffMs: number): number {
782
+ let evicted = 0;
783
+ for (const [key, entry] of this.cache) {
784
+ // Never evict live CRITICAL entries — auth tokens, active sessions, etc.
785
+ if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > Date.now()) continue;
786
+
787
+ // Prefer the explicit setAt timestamp; fall back to approximation for older entries.
788
+ const setAt = entry.setAt ?? (entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0);
789
+
790
+ if (setAt < cutoffMs) {
791
+ this._delete(key, 'manual');
792
+ evicted++;
793
+ }
794
+ }
795
+ if (evicted > 0) {
796
+ this.bloom.rebuild(this.cache.keys());
797
+ this._bloomDirtyCount = 0;
798
+ }
799
+ return evicted;
800
+ }
801
+
802
+ /**
803
+ * Delete a key only if its write timestamp (`setAt`) is <= `cutoffMs`.
804
+ * Used for concurrency-safe compare-and-delete on stale generational reads,
805
+ * guaranteeing that a newer value written by a concurrent revalidation is never wiped out.
806
+ */
807
+ deleteIfSetBefore(key: string, cutoffMs: number): boolean {
808
+ const entry = this.cache.get(key);
809
+ if (!entry) return false;
810
+ const setAt = entry.setAt ?? (entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0);
811
+ if (setAt <= cutoffMs) {
812
+ const deleted = this._delete(key, 'manual');
813
+ if (deleted) this.maybeRebuildBloom();
814
+ return deleted;
815
+ }
816
+ return false;
817
+ }
818
+
819
+
820
+
821
+ exportEntries(forbiddenPrefixes: readonly string[]): Array<{ key: string; entry: SmartCacheEntry }> {
822
+ const now = Date.now();
823
+ const out: Array<{ key: string; entry: SmartCacheEntry }> = [];
824
+ for (const [key, entry] of this.cache) {
825
+ if (entry.expiresAt <= now) continue;
826
+ if (entry.priority === 4 /* CRITICAL */) continue;
827
+ if (forbiddenPrefixes.some(p => key.startsWith(p))) continue;
828
+ out.push({ key, entry: { ...entry } });
829
+ }
830
+ return out;
831
+ }
832
+
833
+ importEntries(entries: Array<{ key: string; entry: SmartCacheEntry }>, forbiddenPrefixes: readonly string[]): number {
834
+ const now = Date.now();
835
+ let loaded = 0;
836
+ for (const { key, entry } of entries) {
837
+ if (entry.expiresAt <= now) continue;
838
+ if (forbiddenPrefixes.some(p => key.startsWith(p))) continue;
839
+ if (this.cache.has(key)) continue;
840
+ const rawData = entry.data;
841
+ // Handle both legacy (isCompressed=false, data=JSON string) and current (data=Buffer) formats.
842
+ const data: Buffer = !entry.isCompressed
843
+ ? pack(JSON.parse(rawData as unknown as string)) // legacy: re-encode JSON → msgpackr
844
+ : rawData instanceof Uint8Array
845
+ ? Buffer.from(rawData) // msgpackr Uint8Array → Buffer
846
+ : rawData as Buffer; // already a Buffer
847
+ // Cache the live object for small entries only — large entries skip double-heap storage.
848
+ const value = entry.size <= LARGE_VALUE_BYTES ? unpack(data) : undefined;
849
+ this.cache.set(key, { ...entry, data, value, isCompressed: true });
850
+ this.bloom.add(key);
851
+ loaded++;
852
+ }
853
+ this.recalculateStats();
854
+ return loaded;
855
+ }
856
+
857
+ // ── Iterators ─────────────────────────────────────────────────────────────
858
+
859
+ /**
860
+ * Lazily yields every [key, entry] pair whose TTL has not yet expired.
861
+ * Expired entries that are still in the Map (awaiting background cleanup)
862
+ * are silently skipped.
863
+ */
864
+ *liveEntries(): Generator<[string, SmartCacheEntry]> {
865
+ const now = Date.now();
866
+ for (const [key, entry] of this.cache) {
867
+ if (entry.expiresAt > now) yield [key, entry];
868
+ }
869
+ }
870
+
871
+ /**
872
+ * Non-generator bulk scan over all live entries.
873
+ *
874
+ * Faster than the generator-based iterators for bulk operations because:
875
+ * - No generator state-machine overhead (no yield/resume suspend points).
876
+ * - No per-entry tuple allocation (compare `liveEntries()` which yields `[key, entry]`).
877
+ * - The same Map call-site is used by a single plain `for` loop instead of being
878
+ * shared across three competing generator functions, giving V8's IC a cleaner
879
+ * monomorphic profile for this path.
880
+ *
881
+ * The callback receives the raw (namespaced) key and a `prefixLen` offset so the
882
+ * caller can call `key.slice(prefixLen)` only when it actually needs the stripped
883
+ * key, avoiding the allocation entirely for callers that don't.
884
+ *
885
+ * @param fn Called once per live entry.
886
+ * @param prefixLen Number of bytes to skip to reach the un-namespaced portion of the key.
887
+ * Pass 0 when no namespace is configured.
888
+ */
889
+ scan(fn: (key: string, entry: SmartCacheEntry, prefixLen: number) => void, prefixLen: number): void {
890
+ const now = Date.now();
891
+ for (const [key, entry] of this.cache) {
892
+ if (entry.expiresAt > now) fn(key, entry, prefixLen);
893
+ }
894
+ }
895
+
896
+ /**
897
+ * Yields only the keys of live entries — no intermediate tuple allocation.
898
+ * Use this instead of liveEntries() when you only need keys.
899
+ */
900
+ *liveKeys(): Generator<string> {
901
+ const now = Date.now();
902
+ for (const [key, entry] of this.cache) {
903
+ if (entry.expiresAt > now) yield key;
904
+ }
905
+ }
906
+
907
+ /**
908
+ * Yields only the resolved values of live entries.
909
+ * Iterates Map.values() so the key is never loaded into the yielded path.
910
+ * Returns the deserialized value — identical semantics to get() but without bloom/hit tracking.
911
+ */
912
+ *liveValues(): Generator<unknown> {
913
+ const now = Date.now();
914
+ for (const entry of this.cache.values()) {
915
+ if (entry.expiresAt > now)
916
+ yield this.resolveValue(entry);
917
+ }
918
+ }
919
+
920
+ /**
921
+ * Returns the deserialized value for an entry, unpacking from the msgpackr buffer
922
+ * if the live object was not cached (large-entry optimisation or disk-restored entry).
923
+ */
924
+ resolveValue(entry: SmartCacheEntry): unknown {
925
+ return entry.value !== undefined ? entry.value : unpack(entry.data as Buffer);
926
+ }
927
+
928
+ // ── Stats ─────────────────────────────────────────────────────────────────
929
+
930
+ get size(): number { return this.cache.size; }
931
+ get memoryUsage(): number { return this.totalSize; }
932
+
933
+ getStats() {
934
+ const categories: Record<string, { entries: number; hits: number }> = {};
935
+ for (const [cat, cnt] of this.categoryCount) {
936
+ categories[cat] = { entries: cnt, hits: this.categoryHits.get(cat) ?? 0 };
937
+ }
938
+ return {
939
+ entries: this.cache.size,
940
+ sizeBytes: this.totalSize,
941
+ sizeKB: Math.round(this.totalSize / 1024),
942
+ categories,
943
+ bloom: {
944
+ checks: this.bloomChecks,
945
+ falsePositives: this.bloomFalsePos,
946
+ },
947
+ compression: {
948
+ compressed: this.compressions,
949
+ uncompressed: 0, // all entries are now msgpackr-packed
950
+ bytesSaved: 0, // no longer tracked (unified format removes the split path)
951
+ },
952
+ };
953
+ }
954
+
955
+ /**
956
+ * Return the raw cache entry for a key, or `undefined` if absent/expired.
957
+ * Does NOT count as a hit or perform SWR logic.
958
+ */
959
+ getEntry(key: string): SmartCacheEntry | undefined {
960
+ const entry = this.cache.get(key);
961
+ if (!entry) return undefined;
962
+ if (entry.expiresAt <= Date.now()) return undefined;
963
+ return entry;
964
+ }
965
+
966
+ /**
967
+ * Return true if the key exists in L1 and has not expired.
968
+ * Uses the bloom filter as a fast negative check.
969
+ */
970
+ has(key: string): boolean {
971
+ if (!this.bloom.mightContain(key)) return false;
972
+ const entry = this.cache.get(key);
973
+ if (!entry) return false;
974
+ if (entry.expiresAt <= Date.now()) {
975
+ this._delete(key, 'ttl');
976
+ return false;
977
+ }
978
+ return true;
979
+ }
980
+
981
+ /**
982
+ * Extend the TTL of an existing key. Returns `false` if the key is absent or expired.
983
+ * @param newTtlMs - New TTL from now, in milliseconds.
984
+ */
985
+ touch(key: string, newTtlMs: number): boolean {
986
+ const entry = this.cache.get(key);
987
+ if (!entry) return false;
988
+ const now = Date.now();
989
+ if (entry.expiresAt <= now) { this._delete(key, 'ttl'); return false; }
990
+ entry.expiresAt = now + newTtlMs;
991
+ return true;
992
+ }
993
+
994
+ /**
995
+ * Add additional milliseconds to a key's existing expiry (for stale-if-error).
996
+ * Returns `false` if the key is absent or already expired.
997
+ */
998
+ bumpExpiry(key: string, additionalMs: number): boolean {
999
+ const entry = this.cache.get(key);
1000
+ if (!entry) return false;
1001
+ if (entry.expiresAt <= Date.now()) return false;
1002
+ entry.expiresAt += additionalMs;
1003
+ return true;
1004
+ }
1005
+
1006
+ bloomMightContain(key: string): boolean { return this.bloom.mightContain(key); }
1007
+ bloomStats() { return this.bloom.stats; }
1008
+
1009
+ /**
1010
+ * Return the top-N live L1 keys by historical access frequency (Count-Min Sketch estimate).
1011
+ * Includes evicted-then-readmitted keys whose sketch frequency exceeds their current hit count.
1012
+ * Useful for diagnosing which keys are driving cache pressure.
1013
+ *
1014
+ * @param n - Maximum number of entries to return. Default: 10.
1015
+ */
1016
+ hotKeys(n: number): Array<{ key: string; hits: number; sizeBytes: number }> {
1017
+ const now = Date.now();
1018
+ const out: Array<{ key: string; hits: number; sizeBytes: number }> = [];
1019
+ for (const [key, entry] of this.cache) {
1020
+ if (entry.expiresAt <= now) continue;
1021
+ out.push({ key, hits: this.sketch.estimate(key), sizeBytes: entry.size });
1022
+ }
1023
+ out.sort((a, b) => b.hits - a.hits);
1024
+ return out.slice(0, n);
1025
+ }
1026
+ }