tricache 0.5.1 → 0.6.0

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