tricache 0.2.0 → 0.3.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.
package/README.md CHANGED
@@ -19,7 +19,8 @@ tricache is an extremely fast three-tier Node.js cache library. It serves warm r
19
19
 
20
20
  | Feature | Detail |
21
21
  |---|---|
22
- | **Adaptive eviction** | LFU × LRU × priority score; reservoir-sampled O(1) hot path; category limits prevent any prefix monopolising RAM |
22
+ | **Adaptive eviction** | LFU × LRU × priority score + Count-Min Sketch cross-eviction frequency; reservoir-sampled O(1) hot path; category limits prevent any prefix monopolising RAM |
23
+ | **Count-Min Sketch** | 4 × 512 `Uint16Array` (4 KB) tracks historical access frequency across eviction boundaries — same-priority burst keys cannot displace long-resident entries; **78 % survival rate** in benchmark flood tests |
23
24
  | **WASM Bloom filter** | 562-byte binary inlined as Base64 — O(k=7) guaranteed-miss detection, no filesystem access, pure-JS fallback |
24
25
  | **msgpackr serialization** | All entries packed with msgpackr — uniform binary format, no JSON at any payload size |
25
26
  | **Stale-While-Revalidate** | Serve stale instantly, revalidate in background — zero added latency on cache hit |
@@ -371,6 +372,32 @@ process.on('SIGTERM', async () => {
371
372
  });
372
373
  ```
373
374
 
375
+ ### `cache.keys()` → `Generator<string>`
376
+
377
+ Lazily yields the key for every live (non-expired) L1 entry. Namespace prefix is stripped automatically. Uses a dedicated generator that skips intermediate tuple allocation.
378
+
379
+ ```typescript
380
+ for (const key of cache.keys()) console.log(key);
381
+ ```
382
+
383
+ ### `cache.values<T>()` → `Generator<T>`
384
+
385
+ Lazily yields the cached value for every live L1 entry. Returns the live deserialized object (same reference semantics as `get()`). Uses `yield*` delegation — no intermediate generator frame.
386
+
387
+ ```typescript
388
+ for (const session of cache.values<Session>()) evict(session);
389
+ ```
390
+
391
+ ### `cache.entries<T>()` → `Generator<[string, T]>`
392
+
393
+ Lazily yields `[key, value]` pairs for every live L1 entry. Key has namespace prefix stripped.
394
+
395
+ ```typescript
396
+ for (const [key, user] of cache.entries<User>()) sync(key, user);
397
+ ```
398
+
399
+ > **JIT note:** all three generators iterate `SmartMemoryCache.cache` (a single `Map`). V8 maintains per-call-site type feedback; having three generator functions share the same Map means no single one gets the full monomorphic specialization budget. In practice the throughput impact is ≤5 % relative to each running in isolation. See [BENCHMARKS.md](BENCHMARKS.md) for numbers.
400
+
374
401
  ### `cache.destroy()` → `Promise<void>`
375
402
 
376
403
  Closes the Redis connection, unsubscribes the backplane, and stops all background timers.
@@ -520,14 +547,24 @@ Measured on a single Node.js thread (no `await` on synchronous paths):
520
547
 
521
548
  | Operation | Throughput | Latency | Notes |
522
549
  |---|---|---|---|
523
- | `get` — hot hit (8K entries) | **2.65 M/s** | 377 ns | bloom → Map lookup → return cached value |
524
- | `get` — cold miss | **6.77 M/s** | 148 ns | bloom gates → early return |
550
+ | `get` — hot hit (8K entries) | **2.19 M/s** | 457 ns | bloom → Map lookup → return cached value |
551
+ | `get` — cold miss | **5.81 M/s** | 172 ns | bloom gates → early return |
525
552
  | `set` — tiny payload | 915 K/s | 1.09 µs | pack() + Map.set + bloom.add |
526
553
  | `set` — small payload (≈ 512 B) | 562 K/s | 1.78 µs | pack() same unified path, larger payload |
527
554
  | `set` — large payload (≥ 512 B) | 213.6 K/s | 4.68 µs | pack() larger payload |
528
555
  | `set` — CRITICAL priority | 489.7 K/s | 2.04 µs | same set path; skipped in eviction sort |
529
556
  | `delete` — exact key | **4.40 M/s** | 227 ns | Map.delete |
530
557
  | `deletePattern` — glob wildcard | 7.1 K/s | 141 µs | O(n) Map scan |
558
+ | Count-Min Sketch estimate | **3.04 M/s** | 329 ns | 4 row lookups — called on every `get()` hit and `set()` |
559
+
560
+ **Iterator interface (L1 live entries, 500 entries)**
561
+
562
+ | Method | Throughput | Latency | Notes |
563
+ |---|---|---|---|
564
+ | `cache.keys()` | 34.5 K/s | 29 µs | no `[key,entry]` tuple allocation — +19 % vs v0.2.0 |
565
+ | `cache.values()` | 35 K/s | 29 µs | `yield*` delegation — +4 % vs v0.2.0 |
566
+ | `cache.entries()` | 28 K/s | 35 µs | `[strippedKey, value]` pairs |
567
+ | raw `Map` iteration (baseline) | 338 K/s | 3 µs | no expiry check, no generator overhead |
531
568
 
532
569
  **CacheService (end-to-end)**
533
570
 
package/dist/index.cjs CHANGED
@@ -537,12 +537,66 @@ function createBloomFilter(logger) {
537
537
  return new JsBloomFilter();
538
538
  }
539
539
  }
540
+ var SKETCH_ROWS = 4;
541
+ var SKETCH_WIDTH = 512;
542
+ var SKETCH_MASK = SKETCH_WIDTH - 1;
543
+ var SKETCH_DECAY_THRESHOLD = 1e5;
544
+ var CountMinSketch = class {
545
+ table = new Uint16Array(SKETCH_ROWS * SKETCH_WIDTH);
546
+ inserts = 0;
547
+ /** Inline FNV-1a for a string key → 32-bit unsigned integer. */
548
+ fnv32(key) {
549
+ let h = 2166136261;
550
+ for (let i = 0; i < key.length; i++) {
551
+ h ^= key.charCodeAt(i);
552
+ h = Math.imul(h, 16777619) >>> 0;
553
+ }
554
+ return h;
555
+ }
556
+ /** Four independent bit-mixes from one FNV-1a seed. */
557
+ hashes(key) {
558
+ const h = this.fnv32(key);
559
+ const h1 = (h ^ h >>> 16) >>> 0;
560
+ const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
561
+ const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
562
+ const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
563
+ return [h1, h2, h3, h4];
564
+ }
565
+ /** Record one access. Decays all counters when the insertion threshold is crossed. */
566
+ increment(key) {
567
+ const [h1, h2, h3, h4] = this.hashes(key);
568
+ const t = this.table;
569
+ t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] = Math.min(65535, t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] + 1);
570
+ t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] = Math.min(65535, t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] + 1);
571
+ t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] = Math.min(65535, t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] + 1);
572
+ t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] = Math.min(65535, t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] + 1);
573
+ if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
574
+ }
575
+ /** Minimum-across-rows frequency estimate. */
576
+ estimate(key) {
577
+ const [h1, h2, h3, h4] = this.hashes(key);
578
+ const t = this.table;
579
+ return Math.min(
580
+ t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)],
581
+ t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)],
582
+ t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
583
+ t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)]
584
+ );
585
+ }
586
+ /** Halve all counters — ages out old frequency so bursts don't hold indefinitely. */
587
+ decay() {
588
+ for (let i = 0; i < this.table.length; i++) this.table[i] >>>= 1;
589
+ this.inserts = 0;
590
+ }
591
+ };
540
592
  var SmartMemoryCache = class {
541
593
  cache = /* @__PURE__ */ new Map();
542
594
  opts;
543
595
  bloom;
544
596
  /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
545
597
  categoryPrefixes;
598
+ /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
599
+ sketch = new CountMinSketch();
546
600
  totalSize = 0;
547
601
  categoryCount = /* @__PURE__ */ new Map();
548
602
  categorySize = /* @__PURE__ */ new Map();
@@ -620,10 +674,10 @@ var SmartMemoryCache = class {
620
674
  if (!catOvf && !glbOvf) return;
621
675
  this.smartEvict(category, catOvf);
622
676
  }
623
- score(entry, catBonus, now) {
677
+ score(entry, catBonus, now, key) {
624
678
  const age = now - entry.lastAccess;
625
679
  const ttl = Math.max(0, entry.expiresAt - now);
626
- const freq = Math.min(entry.hits, 100);
680
+ const freq = Math.min(Math.max(entry.hits, this.sketch.estimate(key)), 100);
627
681
  return entry.priority * 1e3 + freq * 10 + ttl / 6e4 - age / 6e4 - catBonus;
628
682
  }
629
683
  /**
@@ -658,7 +712,7 @@ var SmartMemoryCache = class {
658
712
  const entry = this.cache.get(key);
659
713
  if (!entry || entry.priority === 4 && entry.expiresAt > now) continue;
660
714
  catSeen++;
661
- const s = this.score(entry, 100, now);
715
+ const s = this.score(entry, 100, now, key);
662
716
  if (pool.length < EVICT) {
663
717
  pool.push({ key, score: s });
664
718
  } else {
@@ -676,7 +730,7 @@ var SmartMemoryCache = class {
676
730
  if (entry.priority === 4 && entry.expiresAt > now) continue;
677
731
  if (catOvf && this.getCategory(key) === targetCat) continue;
678
732
  globalSeen++;
679
- const s = this.score(entry, 0, now);
733
+ const s = this.score(entry, 0, now, key);
680
734
  if (globalPool.length < remaining) {
681
735
  globalPool.push({ key, score: s });
682
736
  } else {
@@ -710,6 +764,7 @@ var SmartMemoryCache = class {
710
764
  }
711
765
  entry.hits++;
712
766
  entry.lastAccess = now;
767
+ this.sketch.increment(key);
713
768
  const cat = this.getCategory(key);
714
769
  this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
715
770
  const value = entry.value !== void 0 ? entry.value : (0, import_msgpackr.unpack)(entry.data);
@@ -720,6 +775,7 @@ var SmartMemoryCache = class {
720
775
  const packed = (0, import_msgpackr.pack)(data);
721
776
  const size = packed.byteLength;
722
777
  this.compressions++;
778
+ this.sketch.increment(key);
723
779
  const cat = this.getCategory(key);
724
780
  const lim = this.getCategoryLimit(cat);
725
781
  if (size > lim.maxSizeBytes * 0.5) {
@@ -801,7 +857,7 @@ var SmartMemoryCache = class {
801
857
  const entry = this.cache.get(key);
802
858
  if (!entry) continue;
803
859
  if (entry.priority === 4 && entry.expiresAt > now) continue;
804
- candidates.push({ key, score: this.score(entry, 0, now) });
860
+ candidates.push({ key, score: this.score(entry, 0, now, key) });
805
861
  }
806
862
  candidates.sort((a, b) => a.score - b.score);
807
863
  for (const { key } of candidates) {
@@ -847,7 +903,7 @@ var SmartMemoryCache = class {
847
903
  const candidates = [];
848
904
  for (const [key, entry] of this.cache) {
849
905
  if (entry.priority === 4 && entry.expiresAt > now) continue;
850
- candidates.push({ key, score: this.score(entry, 0, now) });
906
+ candidates.push({ key, score: this.score(entry, 0, now, key) });
851
907
  }
852
908
  candidates.sort((a, b) => a.score - b.score);
853
909
  const count = Math.max(1, Math.ceil(candidates.length * pct));
@@ -902,6 +958,41 @@ var SmartMemoryCache = class {
902
958
  this.recalculateStats();
903
959
  return loaded;
904
960
  }
961
+ // ── Iterators ─────────────────────────────────────────────────────────────
962
+ /**
963
+ * Lazily yields every [key, entry] pair whose TTL has not yet expired.
964
+ * Expired entries that are still in the Map (awaiting background cleanup)
965
+ * are silently skipped.
966
+ */
967
+ *liveEntries() {
968
+ const now = Date.now();
969
+ for (const [key, entry] of this.cache) {
970
+ if (entry.expiresAt > now) yield [key, entry];
971
+ }
972
+ }
973
+ /**
974
+ * Yields only the keys of live entries — no intermediate tuple allocation.
975
+ * Use this instead of liveEntries() when you only need keys.
976
+ */
977
+ *liveKeys() {
978
+ const now = Date.now();
979
+ for (const [key, entry] of this.cache) {
980
+ if (entry.expiresAt > now) yield key;
981
+ }
982
+ }
983
+ /**
984
+ * Yields only the resolved values of live entries.
985
+ * Iterates Map.values() so the key is never loaded into the yielded path.
986
+ * Returns the cached deserialized object when available (entry.value), otherwise
987
+ * the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
988
+ */
989
+ *liveValues() {
990
+ const now = Date.now();
991
+ for (const entry of this.cache.values()) {
992
+ if (entry.expiresAt > now)
993
+ yield entry.value !== void 0 ? entry.value : entry.data;
994
+ }
995
+ }
905
996
  // ── Stats ─────────────────────────────────────────────────────────────────
906
997
  get size() {
907
998
  return this.cache.size;
@@ -1511,25 +1602,7 @@ var CacheService = class _CacheService {
1511
1602
  });
1512
1603
  sub.on("error", (e) => this.logger.debug("Backplane subscriber error", { error: e.message }));
1513
1604
  sub.on("message", (_channel, message) => {
1514
- try {
1515
- const msg = JSON.parse(message);
1516
- if (msg.src === this.instanceId) {
1517
- this.counters.invSkipped++;
1518
- return;
1519
- }
1520
- this.counters.invReceived++;
1521
- if (msg.op === "del") {
1522
- this.l1.delete(msg.key);
1523
- this.disk.delete(msg.key);
1524
- } else if (msg.op === "del-glob") {
1525
- this.l1.deletePattern(msg.key);
1526
- }
1527
- this.logger.debug("Backplane: peer invalidation applied", {
1528
- op: msg.op,
1529
- key: msg.key.slice(0, 60)
1530
- });
1531
- } catch {
1532
- }
1605
+ this._handleBackplaneMessage(message);
1533
1606
  });
1534
1607
  sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
1535
1608
  channel: this.backplaneChannel,
@@ -1539,6 +1612,28 @@ var CacheService = class _CacheService {
1539
1612
  }));
1540
1613
  this.subClient = sub;
1541
1614
  }
1615
+ /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
1616
+ _handleBackplaneMessage(message) {
1617
+ try {
1618
+ const msg = JSON.parse(message);
1619
+ if (msg.src === this.instanceId) {
1620
+ this.counters.invSkipped++;
1621
+ return;
1622
+ }
1623
+ this.counters.invReceived++;
1624
+ if (msg.op === "del") {
1625
+ this.l1.delete(msg.key);
1626
+ setImmediate(() => this.disk.delete(msg.key));
1627
+ } else if (msg.op === "del-glob") {
1628
+ this.l1.deletePattern(msg.key);
1629
+ }
1630
+ this.logger.debug("Backplane: peer invalidation applied", {
1631
+ op: msg.op,
1632
+ key: msg.key.slice(0, 60)
1633
+ });
1634
+ } catch {
1635
+ }
1636
+ }
1542
1637
  async publishInvalidation(op, key) {
1543
1638
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
1544
1639
  try {
@@ -1958,6 +2053,43 @@ var CacheService = class _CacheService {
1958
2053
  has(cacheKey) {
1959
2054
  return this.l1.has(this.nk(cacheKey));
1960
2055
  }
2056
+ // ── Iteration ─────────────────────────────────────────────────────────────
2057
+ /**
2058
+ * Lazily yield every non-expired L1 key, stripped of its namespace prefix.
2059
+ *
2060
+ * @example
2061
+ * for (const key of cache.keys()) console.log(key);
2062
+ */
2063
+ *keys() {
2064
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2065
+ for (const key of this.l1.liveKeys()) {
2066
+ yield prefixLen > 0 ? key.slice(prefixLen) : key;
2067
+ }
2068
+ }
2069
+ /**
2070
+ * Lazily yield every non-expired L1 value.
2071
+ * Each value is the cached (pre-deserialized) JS object — no unpack overhead.
2072
+ *
2073
+ * @example
2074
+ * for (const val of cache.values<User>()) console.log(val.id);
2075
+ */
2076
+ *values() {
2077
+ yield* this.l1.liveValues();
2078
+ }
2079
+ /**
2080
+ * Lazily yield every non-expired L1 [key, value] pair.
2081
+ * Keys are stripped of their namespace prefix.
2082
+ *
2083
+ * @example
2084
+ * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
2085
+ */
2086
+ *entries() {
2087
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2088
+ for (const [key, entry] of this.l1.liveEntries()) {
2089
+ const k = prefixLen > 0 ? key.slice(prefixLen) : key;
2090
+ yield [k, entry.value !== void 0 ? entry.value : entry.data];
2091
+ }
2092
+ }
1961
2093
  /**
1962
2094
  * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
1963
2095
  * Returns `false` if the key is absent or already expired.
package/dist/index.d.cts CHANGED
@@ -420,6 +420,8 @@ declare class CacheService {
420
420
  */
421
421
  private nk;
422
422
  private initBackplane;
423
+ /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
424
+ _handleBackplaneMessage(message: string): void;
423
425
  private publishInvalidation;
424
426
  private getRedis;
425
427
  writeSnapshot(altPath?: string): void;
@@ -482,6 +484,29 @@ declare class CacheService {
482
484
  * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
483
485
  */
484
486
  has(cacheKey: string): boolean;
487
+ /**
488
+ * Lazily yield every non-expired L1 key, stripped of its namespace prefix.
489
+ *
490
+ * @example
491
+ * for (const key of cache.keys()) console.log(key);
492
+ */
493
+ keys(): Generator<string>;
494
+ /**
495
+ * Lazily yield every non-expired L1 value.
496
+ * Each value is the cached (pre-deserialized) JS object — no unpack overhead.
497
+ *
498
+ * @example
499
+ * for (const val of cache.values<User>()) console.log(val.id);
500
+ */
501
+ values<T = unknown>(): Generator<T>;
502
+ /**
503
+ * Lazily yield every non-expired L1 [key, value] pair.
504
+ * Keys are stripped of their namespace prefix.
505
+ *
506
+ * @example
507
+ * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
508
+ */
509
+ entries<T = unknown>(): Generator<[string, T]>;
485
510
  /**
486
511
  * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
487
512
  * Returns `false` if the key is absent or already expired.
@@ -685,6 +710,8 @@ declare class SmartMemoryCache {
685
710
  private bloom;
686
711
  /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
687
712
  private readonly categoryPrefixes;
713
+ /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
714
+ private readonly sketch;
688
715
  private totalSize;
689
716
  private categoryCount;
690
717
  private categorySize;
@@ -753,6 +780,24 @@ declare class SmartMemoryCache {
753
780
  key: string;
754
781
  entry: SmartCacheEntry;
755
782
  }>, forbiddenPrefixes: readonly string[]): number;
783
+ /**
784
+ * Lazily yields every [key, entry] pair whose TTL has not yet expired.
785
+ * Expired entries that are still in the Map (awaiting background cleanup)
786
+ * are silently skipped.
787
+ */
788
+ liveEntries(): Generator<[string, SmartCacheEntry]>;
789
+ /**
790
+ * Yields only the keys of live entries — no intermediate tuple allocation.
791
+ * Use this instead of liveEntries() when you only need keys.
792
+ */
793
+ liveKeys(): Generator<string>;
794
+ /**
795
+ * Yields only the resolved values of live entries.
796
+ * Iterates Map.values() so the key is never loaded into the yielded path.
797
+ * Returns the cached deserialized object when available (entry.value), otherwise
798
+ * the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
799
+ */
800
+ liveValues(): Generator<unknown>;
756
801
  get size(): number;
757
802
  get memoryUsage(): number;
758
803
  getStats(): {
package/dist/index.d.ts CHANGED
@@ -420,6 +420,8 @@ declare class CacheService {
420
420
  */
421
421
  private nk;
422
422
  private initBackplane;
423
+ /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
424
+ _handleBackplaneMessage(message: string): void;
423
425
  private publishInvalidation;
424
426
  private getRedis;
425
427
  writeSnapshot(altPath?: string): void;
@@ -482,6 +484,29 @@ declare class CacheService {
482
484
  * Bloom-filter fast path — no fetch, no disk or Redis round-trip.
483
485
  */
484
486
  has(cacheKey: string): boolean;
487
+ /**
488
+ * Lazily yield every non-expired L1 key, stripped of its namespace prefix.
489
+ *
490
+ * @example
491
+ * for (const key of cache.keys()) console.log(key);
492
+ */
493
+ keys(): Generator<string>;
494
+ /**
495
+ * Lazily yield every non-expired L1 value.
496
+ * Each value is the cached (pre-deserialized) JS object — no unpack overhead.
497
+ *
498
+ * @example
499
+ * for (const val of cache.values<User>()) console.log(val.id);
500
+ */
501
+ values<T = unknown>(): Generator<T>;
502
+ /**
503
+ * Lazily yield every non-expired L1 [key, value] pair.
504
+ * Keys are stripped of their namespace prefix.
505
+ *
506
+ * @example
507
+ * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
508
+ */
509
+ entries<T = unknown>(): Generator<[string, T]>;
485
510
  /**
486
511
  * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
487
512
  * Returns `false` if the key is absent or already expired.
@@ -685,6 +710,8 @@ declare class SmartMemoryCache {
685
710
  private bloom;
686
711
  /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
687
712
  private readonly categoryPrefixes;
713
+ /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
714
+ private readonly sketch;
688
715
  private totalSize;
689
716
  private categoryCount;
690
717
  private categorySize;
@@ -753,6 +780,24 @@ declare class SmartMemoryCache {
753
780
  key: string;
754
781
  entry: SmartCacheEntry;
755
782
  }>, forbiddenPrefixes: readonly string[]): number;
783
+ /**
784
+ * Lazily yields every [key, entry] pair whose TTL has not yet expired.
785
+ * Expired entries that are still in the Map (awaiting background cleanup)
786
+ * are silently skipped.
787
+ */
788
+ liveEntries(): Generator<[string, SmartCacheEntry]>;
789
+ /**
790
+ * Yields only the keys of live entries — no intermediate tuple allocation.
791
+ * Use this instead of liveEntries() when you only need keys.
792
+ */
793
+ liveKeys(): Generator<string>;
794
+ /**
795
+ * Yields only the resolved values of live entries.
796
+ * Iterates Map.values() so the key is never loaded into the yielded path.
797
+ * Returns the cached deserialized object when available (entry.value), otherwise
798
+ * the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
799
+ */
800
+ liveValues(): Generator<unknown>;
756
801
  get size(): number;
757
802
  get memoryUsage(): number;
758
803
  getStats(): {
package/dist/index.js CHANGED
@@ -495,12 +495,66 @@ function createBloomFilter(logger) {
495
495
  return new JsBloomFilter();
496
496
  }
497
497
  }
498
+ var SKETCH_ROWS = 4;
499
+ var SKETCH_WIDTH = 512;
500
+ var SKETCH_MASK = SKETCH_WIDTH - 1;
501
+ var SKETCH_DECAY_THRESHOLD = 1e5;
502
+ var CountMinSketch = class {
503
+ table = new Uint16Array(SKETCH_ROWS * SKETCH_WIDTH);
504
+ inserts = 0;
505
+ /** Inline FNV-1a for a string key → 32-bit unsigned integer. */
506
+ fnv32(key) {
507
+ let h = 2166136261;
508
+ for (let i = 0; i < key.length; i++) {
509
+ h ^= key.charCodeAt(i);
510
+ h = Math.imul(h, 16777619) >>> 0;
511
+ }
512
+ return h;
513
+ }
514
+ /** Four independent bit-mixes from one FNV-1a seed. */
515
+ hashes(key) {
516
+ const h = this.fnv32(key);
517
+ const h1 = (h ^ h >>> 16) >>> 0;
518
+ const h2 = (Math.imul(h1, 73244475) ^ h1 >>> 16) >>> 0;
519
+ const h3 = (Math.imul(h2, 2142877601) ^ h2 >>> 16) >>> 0;
520
+ const h4 = (Math.imul(h3, 461845907) ^ h3 >>> 16) >>> 0;
521
+ return [h1, h2, h3, h4];
522
+ }
523
+ /** Record one access. Decays all counters when the insertion threshold is crossed. */
524
+ increment(key) {
525
+ const [h1, h2, h3, h4] = this.hashes(key);
526
+ const t = this.table;
527
+ t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] = Math.min(65535, t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] + 1);
528
+ t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] = Math.min(65535, t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] + 1);
529
+ t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] = Math.min(65535, t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] + 1);
530
+ t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] = Math.min(65535, t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] + 1);
531
+ if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
532
+ }
533
+ /** Minimum-across-rows frequency estimate. */
534
+ estimate(key) {
535
+ const [h1, h2, h3, h4] = this.hashes(key);
536
+ const t = this.table;
537
+ return Math.min(
538
+ t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)],
539
+ t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)],
540
+ t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
541
+ t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)]
542
+ );
543
+ }
544
+ /** Halve all counters — ages out old frequency so bursts don't hold indefinitely. */
545
+ decay() {
546
+ for (let i = 0; i < this.table.length; i++) this.table[i] >>>= 1;
547
+ this.inserts = 0;
548
+ }
549
+ };
498
550
  var SmartMemoryCache = class {
499
551
  cache = /* @__PURE__ */ new Map();
500
552
  opts;
501
553
  bloom;
502
554
  /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
503
555
  categoryPrefixes;
556
+ /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
557
+ sketch = new CountMinSketch();
504
558
  totalSize = 0;
505
559
  categoryCount = /* @__PURE__ */ new Map();
506
560
  categorySize = /* @__PURE__ */ new Map();
@@ -578,10 +632,10 @@ var SmartMemoryCache = class {
578
632
  if (!catOvf && !glbOvf) return;
579
633
  this.smartEvict(category, catOvf);
580
634
  }
581
- score(entry, catBonus, now) {
635
+ score(entry, catBonus, now, key) {
582
636
  const age = now - entry.lastAccess;
583
637
  const ttl = Math.max(0, entry.expiresAt - now);
584
- const freq = Math.min(entry.hits, 100);
638
+ const freq = Math.min(Math.max(entry.hits, this.sketch.estimate(key)), 100);
585
639
  return entry.priority * 1e3 + freq * 10 + ttl / 6e4 - age / 6e4 - catBonus;
586
640
  }
587
641
  /**
@@ -616,7 +670,7 @@ var SmartMemoryCache = class {
616
670
  const entry = this.cache.get(key);
617
671
  if (!entry || entry.priority === 4 && entry.expiresAt > now) continue;
618
672
  catSeen++;
619
- const s = this.score(entry, 100, now);
673
+ const s = this.score(entry, 100, now, key);
620
674
  if (pool.length < EVICT) {
621
675
  pool.push({ key, score: s });
622
676
  } else {
@@ -634,7 +688,7 @@ var SmartMemoryCache = class {
634
688
  if (entry.priority === 4 && entry.expiresAt > now) continue;
635
689
  if (catOvf && this.getCategory(key) === targetCat) continue;
636
690
  globalSeen++;
637
- const s = this.score(entry, 0, now);
691
+ const s = this.score(entry, 0, now, key);
638
692
  if (globalPool.length < remaining) {
639
693
  globalPool.push({ key, score: s });
640
694
  } else {
@@ -668,6 +722,7 @@ var SmartMemoryCache = class {
668
722
  }
669
723
  entry.hits++;
670
724
  entry.lastAccess = now;
725
+ this.sketch.increment(key);
671
726
  const cat = this.getCategory(key);
672
727
  this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
673
728
  const value = entry.value !== void 0 ? entry.value : unpack(entry.data);
@@ -678,6 +733,7 @@ var SmartMemoryCache = class {
678
733
  const packed = pack(data);
679
734
  const size = packed.byteLength;
680
735
  this.compressions++;
736
+ this.sketch.increment(key);
681
737
  const cat = this.getCategory(key);
682
738
  const lim = this.getCategoryLimit(cat);
683
739
  if (size > lim.maxSizeBytes * 0.5) {
@@ -759,7 +815,7 @@ var SmartMemoryCache = class {
759
815
  const entry = this.cache.get(key);
760
816
  if (!entry) continue;
761
817
  if (entry.priority === 4 && entry.expiresAt > now) continue;
762
- candidates.push({ key, score: this.score(entry, 0, now) });
818
+ candidates.push({ key, score: this.score(entry, 0, now, key) });
763
819
  }
764
820
  candidates.sort((a, b) => a.score - b.score);
765
821
  for (const { key } of candidates) {
@@ -805,7 +861,7 @@ var SmartMemoryCache = class {
805
861
  const candidates = [];
806
862
  for (const [key, entry] of this.cache) {
807
863
  if (entry.priority === 4 && entry.expiresAt > now) continue;
808
- candidates.push({ key, score: this.score(entry, 0, now) });
864
+ candidates.push({ key, score: this.score(entry, 0, now, key) });
809
865
  }
810
866
  candidates.sort((a, b) => a.score - b.score);
811
867
  const count = Math.max(1, Math.ceil(candidates.length * pct));
@@ -860,6 +916,41 @@ var SmartMemoryCache = class {
860
916
  this.recalculateStats();
861
917
  return loaded;
862
918
  }
919
+ // ── Iterators ─────────────────────────────────────────────────────────────
920
+ /**
921
+ * Lazily yields every [key, entry] pair whose TTL has not yet expired.
922
+ * Expired entries that are still in the Map (awaiting background cleanup)
923
+ * are silently skipped.
924
+ */
925
+ *liveEntries() {
926
+ const now = Date.now();
927
+ for (const [key, entry] of this.cache) {
928
+ if (entry.expiresAt > now) yield [key, entry];
929
+ }
930
+ }
931
+ /**
932
+ * Yields only the keys of live entries — no intermediate tuple allocation.
933
+ * Use this instead of liveEntries() when you only need keys.
934
+ */
935
+ *liveKeys() {
936
+ const now = Date.now();
937
+ for (const [key, entry] of this.cache) {
938
+ if (entry.expiresAt > now) yield key;
939
+ }
940
+ }
941
+ /**
942
+ * Yields only the resolved values of live entries.
943
+ * Iterates Map.values() so the key is never loaded into the yielded path.
944
+ * Returns the cached deserialized object when available (entry.value), otherwise
945
+ * the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
946
+ */
947
+ *liveValues() {
948
+ const now = Date.now();
949
+ for (const entry of this.cache.values()) {
950
+ if (entry.expiresAt > now)
951
+ yield entry.value !== void 0 ? entry.value : entry.data;
952
+ }
953
+ }
863
954
  // ── Stats ─────────────────────────────────────────────────────────────────
864
955
  get size() {
865
956
  return this.cache.size;
@@ -1469,25 +1560,7 @@ var CacheService = class _CacheService {
1469
1560
  });
1470
1561
  sub.on("error", (e) => this.logger.debug("Backplane subscriber error", { error: e.message }));
1471
1562
  sub.on("message", (_channel, message) => {
1472
- try {
1473
- const msg = JSON.parse(message);
1474
- if (msg.src === this.instanceId) {
1475
- this.counters.invSkipped++;
1476
- return;
1477
- }
1478
- this.counters.invReceived++;
1479
- if (msg.op === "del") {
1480
- this.l1.delete(msg.key);
1481
- this.disk.delete(msg.key);
1482
- } else if (msg.op === "del-glob") {
1483
- this.l1.deletePattern(msg.key);
1484
- }
1485
- this.logger.debug("Backplane: peer invalidation applied", {
1486
- op: msg.op,
1487
- key: msg.key.slice(0, 60)
1488
- });
1489
- } catch {
1490
- }
1563
+ this._handleBackplaneMessage(message);
1491
1564
  });
1492
1565
  sub.subscribe(this.backplaneChannel).then(() => this.logger.info("Backplane: subscribed", {
1493
1566
  channel: this.backplaneChannel,
@@ -1497,6 +1570,28 @@ var CacheService = class _CacheService {
1497
1570
  }));
1498
1571
  this.subClient = sub;
1499
1572
  }
1573
+ /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
1574
+ _handleBackplaneMessage(message) {
1575
+ try {
1576
+ const msg = JSON.parse(message);
1577
+ if (msg.src === this.instanceId) {
1578
+ this.counters.invSkipped++;
1579
+ return;
1580
+ }
1581
+ this.counters.invReceived++;
1582
+ if (msg.op === "del") {
1583
+ this.l1.delete(msg.key);
1584
+ setImmediate(() => this.disk.delete(msg.key));
1585
+ } else if (msg.op === "del-glob") {
1586
+ this.l1.deletePattern(msg.key);
1587
+ }
1588
+ this.logger.debug("Backplane: peer invalidation applied", {
1589
+ op: msg.op,
1590
+ key: msg.key.slice(0, 60)
1591
+ });
1592
+ } catch {
1593
+ }
1594
+ }
1500
1595
  async publishInvalidation(op, key) {
1501
1596
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
1502
1597
  try {
@@ -1916,6 +2011,43 @@ var CacheService = class _CacheService {
1916
2011
  has(cacheKey) {
1917
2012
  return this.l1.has(this.nk(cacheKey));
1918
2013
  }
2014
+ // ── Iteration ─────────────────────────────────────────────────────────────
2015
+ /**
2016
+ * Lazily yield every non-expired L1 key, stripped of its namespace prefix.
2017
+ *
2018
+ * @example
2019
+ * for (const key of cache.keys()) console.log(key);
2020
+ */
2021
+ *keys() {
2022
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2023
+ for (const key of this.l1.liveKeys()) {
2024
+ yield prefixLen > 0 ? key.slice(prefixLen) : key;
2025
+ }
2026
+ }
2027
+ /**
2028
+ * Lazily yield every non-expired L1 value.
2029
+ * Each value is the cached (pre-deserialized) JS object — no unpack overhead.
2030
+ *
2031
+ * @example
2032
+ * for (const val of cache.values<User>()) console.log(val.id);
2033
+ */
2034
+ *values() {
2035
+ yield* this.l1.liveValues();
2036
+ }
2037
+ /**
2038
+ * Lazily yield every non-expired L1 [key, value] pair.
2039
+ * Keys are stripped of their namespace prefix.
2040
+ *
2041
+ * @example
2042
+ * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
2043
+ */
2044
+ *entries() {
2045
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
2046
+ for (const [key, entry] of this.l1.liveEntries()) {
2047
+ const k = prefixLen > 0 ? key.slice(prefixLen) : key;
2048
+ yield [k, entry.value !== void 0 ? entry.value : entry.data];
2049
+ }
2050
+ }
1919
2051
  /**
1920
2052
  * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
1921
2053
  * Returns `false` if the key is absent or already expired.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tricache",
3
- "version": "0.2.0",
4
- "description": "Three-tier Node.js cache: L1 smart RAM (adaptive LFU/LRU) → L1.5 NVMe disk spill → L2 Redis/Valkey. Includes AES-256-GCM at-rest encryption, WASM Bloom filter, Stale-While-Revalidate, and thundering-herd prevention.",
3
+ "version": "0.3.0",
4
+ "description": "Three-tier Node.js cache: L1 smart RAM (adaptive LFU/LRU + Count-Min Sketch) → L1.5 NVMe disk spill → L2 Redis/Valkey. Includes AES-256-GCM at-rest encryption, WASM Bloom filter, Stale-While-Revalidate, and thundering-herd prevention.",
5
5
  "keywords": [
6
6
  "cache",
7
7
  "redis",
@@ -9,6 +9,7 @@
9
9
  "lru",
10
10
  "lfu",
11
11
  "bloom-filter",
12
+ "count-min-sketch",
12
13
  "swr",
13
14
  "stale-while-revalidate",
14
15
  "msgpack",
@@ -17,7 +18,6 @@
17
18
  "nodejs"
18
19
  ],
19
20
  "license": "MIT",
20
- "packageManager": "pnpm@11.0.9",
21
21
  "type": "module",
22
22
  "main": "./dist/index.js",
23
23
  "module": "./dist/index.js",
@@ -35,14 +35,6 @@
35
35
  "README.md",
36
36
  "LICENSE"
37
37
  ],
38
- "scripts": {
39
- "build": "tsup src/index.ts --format esm,cjs --dts --clean",
40
- "dev": "tsup src/index.ts --format esm,cjs --dts --watch",
41
- "typecheck": "tsc --noEmit",
42
- "test": "vitest run",
43
- "test:watch": "vitest",
44
- "bench": "node --import tsx/esm bench/benchmark.ts"
45
- },
46
38
  "dependencies": {
47
39
  "ioredis": "^5.3.2",
48
40
  "msgpackr": "^2.0.1"
@@ -61,5 +53,13 @@
61
53
  "repository": {
62
54
  "type": "git",
63
55
  "url": "git+https://github.com/Kareem411/TriCache.git"
56
+ },
57
+ "scripts": {
58
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
59
+ "dev": "tsup src/index.ts --format esm,cjs --dts --watch",
60
+ "typecheck": "tsc --noEmit",
61
+ "test": "vitest run",
62
+ "test:watch": "vitest",
63
+ "bench": "node --import tsx/esm bench/benchmark.ts"
64
64
  }
65
- }
65
+ }
@@ -348,23 +348,7 @@ export class CacheService {
348
348
  this.logger.debug('Backplane subscriber error', { error: e.message }));
349
349
 
350
350
  sub.on('message', (_channel: string, message: string) => {
351
- try {
352
- const msg = JSON.parse(message) as { op: 'del' | 'del-glob'; key: string; src: string };
353
- if (msg.src === this.instanceId) {
354
- this.counters.invSkipped++;
355
- return; // own message — our L1 is already current
356
- }
357
- this.counters.invReceived++;
358
- if (msg.op === 'del') {
359
- this.l1.delete(msg.key);
360
- this.disk.delete(msg.key);
361
- } else if (msg.op === 'del-glob') {
362
- this.l1.deletePattern(msg.key);
363
- }
364
- this.logger.debug('Backplane: peer invalidation applied', {
365
- op: msg.op, key: msg.key.slice(0, 60),
366
- });
367
- } catch { /* malformed message — ignore */ }
351
+ this._handleBackplaneMessage(message);
368
352
  });
369
353
 
370
354
  sub.subscribe(this.backplaneChannel)
@@ -378,6 +362,32 @@ export class CacheService {
378
362
  this.subClient = sub;
379
363
  }
380
364
 
365
+ /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
366
+ _handleBackplaneMessage(message: string): void {
367
+ try {
368
+ const msg = JSON.parse(message) as { op: 'del' | 'del-glob'; key: string; src: string };
369
+ if (msg.src === this.instanceId) {
370
+ this.counters.invSkipped++;
371
+ return; // own message — our L1 is already current
372
+ }
373
+ this.counters.invReceived++;
374
+ if (msg.op === 'del') {
375
+ // L1 eviction is synchronous and O(1); disk delete is deferred via
376
+ // setImmediate so the event-loop tick that processes this pub/sub
377
+ // message returns immediately without blocking hot get() calls.
378
+ this.l1.delete(msg.key);
379
+ setImmediate(() => this.disk.delete(msg.key));
380
+ } else if (msg.op === 'del-glob') {
381
+ // Glob patterns clean L1 only — disk entries expire naturally via
382
+ // the background purge timer or are bypassed on the next L1 miss.
383
+ this.l1.deletePattern(msg.key);
384
+ }
385
+ this.logger.debug('Backplane: peer invalidation applied', {
386
+ op: msg.op, key: msg.key.slice(0, 60),
387
+ });
388
+ } catch { /* malformed message — ignore */ }
389
+ }
390
+
381
391
  private async publishInvalidation(op: 'del' | 'del-glob', key: string): Promise<void> {
382
392
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
383
393
  try {
@@ -862,6 +872,48 @@ export class CacheService {
862
872
  return this.l1.has(this.nk(cacheKey));
863
873
  }
864
874
 
875
+ // ── Iteration ─────────────────────────────────────────────────────────────
876
+
877
+ /**
878
+ * Lazily yield every non-expired L1 key, stripped of its namespace prefix.
879
+ *
880
+ * @example
881
+ * for (const key of cache.keys()) console.log(key);
882
+ */
883
+ *keys(): Generator<string> {
884
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
885
+ for (const key of this.l1.liveKeys()) {
886
+ yield prefixLen > 0 ? key.slice(prefixLen) : key;
887
+ }
888
+ }
889
+
890
+ /**
891
+ * Lazily yield every non-expired L1 value.
892
+ * Each value is the cached (pre-deserialized) JS object — no unpack overhead.
893
+ *
894
+ * @example
895
+ * for (const val of cache.values<User>()) console.log(val.id);
896
+ */
897
+ *values<T = unknown>(): Generator<T> {
898
+ // yield* delegates directly into liveValues(), collapsing one generator frame.
899
+ yield* this.l1.liveValues() as Generator<T>;
900
+ }
901
+
902
+ /**
903
+ * Lazily yield every non-expired L1 [key, value] pair.
904
+ * Keys are stripped of their namespace prefix.
905
+ *
906
+ * @example
907
+ * for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
908
+ */
909
+ *entries<T = unknown>(): Generator<[string, T]> {
910
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
911
+ for (const [key, entry] of this.l1.liveEntries()) {
912
+ const k = prefixLen > 0 ? key.slice(prefixLen) : key;
913
+ yield [k, (entry.value !== undefined ? entry.value : entry.data) as T];
914
+ }
915
+ }
916
+
865
917
  /**
866
918
  * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
867
919
  * Returns `false` if the key is absent or already expired.
@@ -100,6 +100,79 @@ function createBloomFilter(logger: ILogger): AnyBloomFilter {
100
100
  }
101
101
  }
102
102
 
103
+ // ─── Count-Min Sketch ─────────────────────────────────────────────────────────
104
+ //
105
+ // Estimates historical access frequency across eviction boundaries — a per-entry
106
+ // `hits` counter resets to 1 whenever a key is re-admitted after eviction, but
107
+ // the sketch remembers the key's frequency in a fixed-size typed array that
108
+ // survives evictions. This closes the same-priority burst-flood gap: a key that
109
+ // has been accessed 80 times over the last hour but was evicted 5 minutes ago
110
+ // will score far above a brand-new burst key whose hits = 1.
111
+ //
112
+ // Dimensions: 4 rows × 512 counters (Uint16Array) — 4 KB total, fits in L1d.
113
+ // Hash: four independent Murmur3-fragment mixes of the key's FNV-1a digest.
114
+ // Decay: all counters halved when total insertions cross SKETCH_DECAY_THRESHOLD
115
+ // (frequency-ageing prevents indefinitely growing hot-key counts).
116
+
117
+ const SKETCH_ROWS = 4;
118
+ const SKETCH_WIDTH = 512; // must be power of two
119
+ const SKETCH_MASK = SKETCH_WIDTH - 1;
120
+ const SKETCH_DECAY_THRESHOLD = 100_000;
121
+
122
+ class CountMinSketch {
123
+ private readonly table = new Uint16Array(SKETCH_ROWS * SKETCH_WIDTH);
124
+ private inserts = 0;
125
+
126
+ /** Inline FNV-1a for a string key → 32-bit unsigned integer. */
127
+ private fnv32(key: string): number {
128
+ let h = 0x811c9dc5;
129
+ for (let i = 0; i < key.length; i++) {
130
+ h ^= key.charCodeAt(i);
131
+ h = (Math.imul(h, 0x01000193) >>> 0);
132
+ }
133
+ return h;
134
+ }
135
+
136
+ /** Four independent bit-mixes from one FNV-1a seed. */
137
+ private hashes(key: string): [number, number, number, number] {
138
+ const h = this.fnv32(key);
139
+ const h1 = (h ^ (h >>> 16)) >>> 0;
140
+ const h2 = (Math.imul(h1, 0x45d9f3b) ^ (h1 >>> 16)) >>> 0;
141
+ const h3 = (Math.imul(h2, 0x7fb9b7a1) ^ (h2 >>> 16)) >>> 0;
142
+ const h4 = (Math.imul(h3, 0x1b873593) ^ (h3 >>> 16)) >>> 0;
143
+ return [h1, h2, h3, h4];
144
+ }
145
+
146
+ /** Record one access. Decays all counters when the insertion threshold is crossed. */
147
+ increment(key: string): void {
148
+ const [h1, h2, h3, h4] = this.hashes(key);
149
+ const t = this.table;
150
+ t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] = Math.min(0xffff, (t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] + 1));
151
+ t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] = Math.min(0xffff, (t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] + 1));
152
+ t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] = Math.min(0xffff, (t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] + 1));
153
+ t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] = Math.min(0xffff, (t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] + 1));
154
+ if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
155
+ }
156
+
157
+ /** Minimum-across-rows frequency estimate. */
158
+ estimate(key: string): number {
159
+ const [h1, h2, h3, h4] = this.hashes(key);
160
+ const t = this.table;
161
+ return Math.min(
162
+ t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)],
163
+ t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)],
164
+ t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
165
+ t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)],
166
+ );
167
+ }
168
+
169
+ /** Halve all counters — ages out old frequency so bursts don't hold indefinitely. */
170
+ private decay(): void {
171
+ for (let i = 0; i < this.table.length; i++) this.table[i] >>>= 1;
172
+ this.inserts = 0;
173
+ }
174
+ }
175
+
103
176
  // ─── SmartMemoryCache ─────────────────────────────────────────────────────────
104
177
 
105
178
  export interface SmartMemoryCacheOptions {
@@ -117,6 +190,8 @@ export class SmartMemoryCache {
117
190
  private bloom: AnyBloomFilter;
118
191
  /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
119
192
  private readonly categoryPrefixes: string[];
193
+ /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
194
+ private readonly sketch = new CountMinSketch();
120
195
  private totalSize = 0;
121
196
  private categoryCount = new Map<string, number>();
122
197
  private categorySize = new Map<string, number>();
@@ -197,10 +272,13 @@ export class SmartMemoryCache {
197
272
  this.smartEvict(category, catOvf);
198
273
  }
199
274
 
200
- private score(entry: SmartCacheEntry, catBonus: number, now: number): number {
275
+ private score(entry: SmartCacheEntry, catBonus: number, now: number, key: string): number {
201
276
  const age = now - entry.lastAccess;
202
277
  const ttl = Math.max(0, entry.expiresAt - now);
203
- const freq = Math.min(entry.hits, 100);
278
+ // Use the sketch's cross-eviction frequency estimate when it exceeds the
279
+ // entry's current-tenure hit count — protects long-resident keys that were
280
+ // recently re-admitted (hits reset to 1) from same-priority burst floods.
281
+ const freq = Math.min(Math.max(entry.hits, this.sketch.estimate(key)), 100);
204
282
  return entry.priority * 1000 + freq * 10 + ttl / 60000 - age / 60000 - catBonus;
205
283
  }
206
284
 
@@ -250,7 +328,7 @@ export class SmartMemoryCache {
250
328
  const entry = this.cache.get(key);
251
329
  if (!entry || (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now)) continue;
252
330
  catSeen++;
253
- const s = this.score(entry, 100, now);
331
+ const s = this.score(entry, 100, now, key);
254
332
  if (pool.length < EVICT) {
255
333
  pool.push({ key, score: s });
256
334
  } else {
@@ -273,7 +351,7 @@ export class SmartMemoryCache {
273
351
  if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
274
352
  if (catOvf && this.getCategory(key) === targetCat) continue; // already sampled above
275
353
  globalSeen++;
276
- const s = this.score(entry, 0, now);
354
+ const s = this.score(entry, 0, now, key);
277
355
  if (globalPool.length < remaining) {
278
356
  globalPool.push({ key, score: s });
279
357
  } else {
@@ -306,6 +384,7 @@ export class SmartMemoryCache {
306
384
  if (entry.expiresAt < now) { this._delete(key, 'ttl'); return null; }
307
385
  entry.hits++;
308
386
  entry.lastAccess = now;
387
+ this.sketch.increment(key);
309
388
  const cat = this.getCategory(key);
310
389
  this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
311
390
  // value is cached at write time — hot reads return the live object directly,
@@ -327,6 +406,7 @@ export class SmartMemoryCache {
327
406
  const packed = pack(data);
328
407
  const size = packed.byteLength;
329
408
  this.compressions++;
409
+ this.sketch.increment(key);
330
410
 
331
411
  const cat = this.getCategory(key);
332
412
  const lim = this.getCategoryLimit(cat);
@@ -418,7 +498,7 @@ export class SmartMemoryCache {
418
498
  const entry = this.cache.get(key);
419
499
  if (!entry) continue;
420
500
  if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
421
- candidates.push({ key, score: this.score(entry, 0, now) });
501
+ candidates.push({ key, score: this.score(entry, 0, now, key) });
422
502
  }
423
503
  candidates.sort((a, b) => a.score - b.score);
424
504
 
@@ -470,7 +550,7 @@ export class SmartMemoryCache {
470
550
  const candidates: Array<{ key: string; score: number }> = [];
471
551
  for (const [key, entry] of this.cache) {
472
552
  if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
473
- candidates.push({ key, score: this.score(entry, 0, now) });
553
+ candidates.push({ key, score: this.score(entry, 0, now, key) });
474
554
  }
475
555
  candidates.sort((a, b) => a.score - b.score);
476
556
  const count = Math.max(1, Math.ceil(candidates.length * pct));
@@ -530,6 +610,45 @@ export class SmartMemoryCache {
530
610
  return loaded;
531
611
  }
532
612
 
613
+ // ── Iterators ─────────────────────────────────────────────────────────────
614
+
615
+ /**
616
+ * Lazily yields every [key, entry] pair whose TTL has not yet expired.
617
+ * Expired entries that are still in the Map (awaiting background cleanup)
618
+ * are silently skipped.
619
+ */
620
+ *liveEntries(): Generator<[string, SmartCacheEntry]> {
621
+ const now = Date.now();
622
+ for (const [key, entry] of this.cache) {
623
+ if (entry.expiresAt > now) yield [key, entry];
624
+ }
625
+ }
626
+
627
+ /**
628
+ * Yields only the keys of live entries — no intermediate tuple allocation.
629
+ * Use this instead of liveEntries() when you only need keys.
630
+ */
631
+ *liveKeys(): Generator<string> {
632
+ const now = Date.now();
633
+ for (const [key, entry] of this.cache) {
634
+ if (entry.expiresAt > now) yield key;
635
+ }
636
+ }
637
+
638
+ /**
639
+ * Yields only the resolved values of live entries.
640
+ * Iterates Map.values() so the key is never loaded into the yielded path.
641
+ * Returns the cached deserialized object when available (entry.value), otherwise
642
+ * the raw msgpackr Buffer — identical semantics to get() but without bloom/hit tracking.
643
+ */
644
+ *liveValues(): Generator<unknown> {
645
+ const now = Date.now();
646
+ for (const entry of this.cache.values()) {
647
+ if (entry.expiresAt > now)
648
+ yield entry.value !== undefined ? entry.value : entry.data;
649
+ }
650
+ }
651
+
533
652
  // ── Stats ─────────────────────────────────────────────────────────────────
534
653
 
535
654
  get size(): number { return this.cache.size; }