tricache 1.0.1 → 2.0.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.
Files changed (127) hide show
  1. package/README.md +89 -93
  2. package/dashboards/tricache-alerts.yaml +80 -4
  3. package/dashboards/tricache-grafana.json +54 -1
  4. package/dashboards/tricache-inventory.rules.yml +21 -0
  5. package/dist/cache-service-BV5T8-20.d.cts +1064 -0
  6. package/dist/cache-service-UZXOQGEY.js +14 -0
  7. package/dist/{cache-service-CREOp7MM.d.ts → cache-service-tpyrXvlH.d.ts} +157 -24
  8. package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
  9. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  10. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  11. package/dist/{chunk-2AJKEQMZ.js → chunk-KV7KISK2.js} +54 -5
  12. package/dist/{chunk-JYQFQJNJ.js → chunk-MB3DMVWN.js} +3424 -1022
  13. package/dist/chunk-RBJRTGFK.js +94 -0
  14. package/dist/chunk-S5N65I45.js +17 -0
  15. package/dist/cli.cjs +3694 -1070
  16. package/dist/cli.d.cts +12 -0
  17. package/dist/cli.js +210 -14
  18. package/dist/dashboard/index.cjs +111 -29
  19. package/dist/dashboard/index.d.cts +185 -0
  20. package/dist/dashboard/index.d.ts +5 -3
  21. package/dist/dashboard/index.js +1 -1
  22. package/dist/drizzle/index.cjs +3578 -1068
  23. package/dist/drizzle/index.d.cts +46 -0
  24. package/dist/drizzle/index.d.ts +2 -2
  25. package/dist/drizzle/index.js +6 -2
  26. package/dist/edge/index.cjs +368 -162
  27. package/dist/edge/index.d.cts +134 -0
  28. package/dist/edge/index.d.ts +11 -4
  29. package/dist/edge/index.js +314 -155
  30. package/dist/hono/index.cjs +3614 -1087
  31. package/dist/hono/index.d.cts +93 -0
  32. package/dist/hono/index.d.ts +7 -5
  33. package/dist/hono/index.js +16 -9
  34. package/dist/hono-CMv2VdQ6.d.cts +404 -0
  35. package/dist/{hono-DSV2ve66.d.ts → hono-Dvq04kX9.d.ts} +33 -7
  36. package/dist/http/index.cjs +3712 -1124
  37. package/dist/http/index.d.cts +103 -0
  38. package/dist/http/index.d.ts +13 -5
  39. package/dist/http/index.js +92 -43
  40. package/dist/index.cjs +4067 -1252
  41. package/dist/index.d.cts +1071 -0
  42. package/dist/index.d.ts +123 -27
  43. package/dist/index.js +878 -21
  44. package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.cts} +1 -0
  45. package/dist/murmur3-DF8BFRnu.d.ts +99 -0
  46. package/dist/nestjs/index.cjs +3635 -1112
  47. package/dist/nestjs/index.d.cts +299 -0
  48. package/dist/nestjs/index.d.ts +120 -33
  49. package/dist/nestjs/index.js +132 -43
  50. package/dist/next/index.cjs +3704 -1175
  51. package/dist/next/index.d.cts +238 -0
  52. package/dist/next/index.d.ts +39 -11
  53. package/dist/next/index.js +202 -102
  54. package/dist/prisma/index.cjs +29 -18
  55. package/dist/prisma/index.d.cts +62 -0
  56. package/dist/prisma/index.d.ts +2 -2
  57. package/dist/prisma/index.js +17 -18
  58. package/dist/serialize-worker.cjs +162 -39
  59. package/dist/serialize-worker.d.cts +2 -0
  60. package/dist/serialize-worker.js +9 -7
  61. package/dist/{types-Dyip5wAl.d.ts → types-F8vRWMrE.d.cts} +186 -54
  62. package/dist/types-F8vRWMrE.d.ts +1636 -0
  63. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  64. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  65. package/package.json +116 -37
  66. package/src/adapters/auto-pipeliner.ts +150 -26
  67. package/src/adapters/node-redis.ts +106 -27
  68. package/src/cache-service.ts +2215 -793
  69. package/src/cli.ts +25 -14
  70. package/src/codec.ts +3 -3
  71. package/src/compression.ts +39 -16
  72. package/src/cross-region.ts +22 -4
  73. package/src/dashboard/handler.ts +26 -6
  74. package/src/dashboard/html.ts +35 -10
  75. package/src/dashboard/index.ts +35 -13
  76. package/src/dashboard/types.ts +3 -1
  77. package/src/disk-tier.ts +448 -102
  78. package/src/drizzle/index.ts +2 -1
  79. package/src/edge/adapters/cloudflare-do.ts +25 -10
  80. package/src/edge/adapters/cloudflare-kv.ts +12 -9
  81. package/src/edge/adapters/upstash.ts +27 -11
  82. package/src/edge/cache.ts +200 -110
  83. package/src/edge/hono.ts +23 -6
  84. package/src/edge/types.ts +17 -5
  85. package/src/encryption.ts +50 -18
  86. package/src/env.d.ts +1 -1
  87. package/src/errors.ts +12 -0
  88. package/src/hono/index.ts +19 -9
  89. package/src/http/express.ts +62 -17
  90. package/src/http/fastify.ts +35 -21
  91. package/src/http/utils.ts +60 -20
  92. package/src/index.ts +6 -0
  93. package/src/ipc-telemetry.ts +35 -9
  94. package/src/latency-watchdog.ts +5 -1
  95. package/src/nestjs/decorators.ts +11 -6
  96. package/src/nestjs/index.ts +2 -0
  97. package/src/nestjs/keyv-adapter.ts +68 -0
  98. package/src/nestjs/tricache.module.ts +15 -12
  99. package/src/nestjs/tricache.store.ts +69 -26
  100. package/src/nestjs/types.ts +30 -16
  101. package/src/next/cache-handler.ts +151 -53
  102. package/src/next/index.ts +1 -0
  103. package/src/next/types.ts +25 -0
  104. package/src/origin-capacity.ts +134 -0
  105. package/src/prisma/index.ts +17 -24
  106. package/src/remote-snapshot.ts +37 -27
  107. package/src/serialize-worker.ts +8 -5
  108. package/src/sigv4-snapshot-adapter.ts +37 -27
  109. package/src/smart-memory-cache.ts +121 -44
  110. package/src/types.ts +117 -37
  111. package/src/utils/cgroup.ts +12 -0
  112. package/src/utils/config-comparison.ts +29 -0
  113. package/src/utils/deadline.ts +14 -0
  114. package/src/utils/diagnostics.ts +27 -0
  115. package/src/utils/lz4-size.ts +74 -0
  116. package/src/utils/namespace-key.ts +48 -0
  117. package/src/utils/query-key.ts +13 -0
  118. package/src/utils/redis-slot.ts +13 -0
  119. package/src/utils/snapshot-transfer.ts +83 -0
  120. package/src/utils/work-limits.ts +73 -0
  121. package/src/utils/write-revision.ts +4 -0
  122. package/src/wasm/bloom-filter-wasm.ts +25 -5
  123. package/src/worker-pool.ts +44 -15
  124. package/src/wtiny-lfu.ts +82 -20
  125. package/dist/cache-service-MG7PN6MX.js +0 -12
  126. package/dist/chunk-3I5L7K6I.js +0 -704
  127. package/dist/chunk-BQRURGGD.js +0 -60
@@ -13,8 +13,10 @@
13
13
  */
14
14
 
15
15
  import { CacheCodec, defaultCodec } from './codec.js';
16
+ import { randomUUID } from 'node:crypto';
16
17
  import type { CacheHit, CachePriority, CategoryLimit, SmartCacheEntry, ILogger, EvictionReason, WTinyLfuStats } from './types';
17
18
  import { WTinyLfuPolicy } from './wtiny-lfu.js';
19
+ import { isWriteRevision } from './utils/write-revision.js';
18
20
 
19
21
  /**
20
22
  * Packed-byte threshold above which the live JS object is NOT stored alongside the
@@ -119,8 +121,9 @@ type AnyBloomFilter = JsBloomFilter | WasmBloomFilter;
119
121
  function createBloomFilter(logger: ILogger, maxEntries: number): AnyBloomFilter {
120
122
  // Compute optimal bit-count for p = 1 % and the requested entry ceiling.
121
123
  const LN2_SQ = Math.LN2 * Math.LN2; // (ln 2)² ≈ 0.4804
122
- const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
123
- const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
124
+ const capacity = Math.max(1, maxEntries);
125
+ const optimalBits = Math.ceil(-capacity * Math.log(0.01) / LN2_SQ);
126
+ const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / capacity)));
124
127
 
125
128
  try {
126
129
  const wasm = new WasmBloomFilter();
@@ -253,6 +256,8 @@ export interface SmartMemoryCacheOptions {
253
256
  maxBytes: number;
254
257
  maxEntries: number;
255
258
  categories: Record<string, CategoryLimit>;
259
+ /** Storage-key prefix to skip when matching logical category prefixes. */
260
+ keyPrefixLength?: number;
256
261
  diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
257
262
  onEviction?: (key: string, reason: EvictionReason) => void;
258
263
  logger: ILogger;
@@ -288,6 +293,7 @@ export class SmartMemoryCache {
288
293
  // ── Observability counters ──────────────────────────────────────────────────────
289
294
  private bloomChecks = 0;
290
295
  private bloomFalsePos = 0;
296
+ private bloomAbsentChecks = 0;
291
297
  private compressions = 0; private categoryHits = new Map<string, number>();
292
298
  /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
293
299
  private _bloomDirtyCount = 0;
@@ -310,7 +316,10 @@ export class SmartMemoryCache {
310
316
  this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
311
317
  this.categoryPrefixes = Object.keys(opts.categories).filter(k => k !== 'default');
312
318
  if (opts.admissionPolicy === 'wtinylfu') {
313
- this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch);
319
+ this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch, 0.01, 0.80, key => {
320
+ const entry = this.cache.get(key);
321
+ return !entry || entry.priority !== 4 || entry.expiresAt <= Date.now();
322
+ });
314
323
  }
315
324
 
316
325
  if (existing) {
@@ -346,7 +355,7 @@ export class SmartMemoryCache {
346
355
 
347
356
  private getCategory(key: string): string {
348
357
  for (const prefix of this.categoryPrefixes) {
349
- if (key.startsWith(prefix)) return prefix;
358
+ if (key.startsWith(prefix, this.opts.keyPrefixLength ?? 0)) return prefix;
350
359
  }
351
360
  return 'default';
352
361
  }
@@ -367,7 +376,7 @@ export class SmartMemoryCache {
367
376
  this._bloomDirtyCount++;
368
377
  const deleted = this.cache.delete(key);
369
378
  if (deleted && this.opts.onEviction) {
370
- try { this.opts.onEviction(key, reason); } catch { /* never crash cache */ }
379
+ try { void Promise.resolve(this.opts.onEviction(key, reason)).catch(() => {}); } catch { /* never crash cache */ }
371
380
  }
372
381
  return deleted;
373
382
  }
@@ -403,6 +412,7 @@ export class SmartMemoryCache {
403
412
  const MAX_EVICT_PASSES = 64;
404
413
  let passes = 0;
405
414
  do {
415
+ const before = this.cache.size;
406
416
  this.smartEvict(category, catOvf);
407
417
  const lim2 = this.getCategoryLimit(category);
408
418
  const catCnt2 = this.categoryCount.get(category) ?? 0;
@@ -410,6 +420,7 @@ export class SmartMemoryCache {
410
420
  catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
411
421
  glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
412
422
  passes++;
423
+ if (this.cache.size === before) break; // Only protected entries remain.
413
424
  } while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
414
425
  }
415
426
 
@@ -538,16 +549,12 @@ export class SmartMemoryCache {
538
549
 
539
550
  get(key: string): CacheHit | null {
540
551
  this.bloomChecks++;
541
- if (!this.bloom.mightContain(key)) return null;
552
+ if (!this.bloom.mightContain(key)) { this.bloomAbsentChecks++; return null; }
542
553
  const entry = this.cache.get(key);
543
- if (!entry) { this.bloomFalsePos++; return null; }
554
+ if (!entry) { this.bloomFalsePos++; this.bloomAbsentChecks++; return null; }
544
555
  const now = Date.now();
545
556
  if (entry.expiresAt < now) { this._delete(key, 'ttl'); return null; }
546
- entry.hits++;
547
- entry.lastAccess = now;
548
- // Sample sketch at 25 % — eviction scoring only needs relative frequency, not exact counts.
549
- if ((entry.hits & 3) === 0) this.sketch.increment(key);
550
- this.wtinyPolicy?.onAccess(key);
557
+ this.recordAccess(key, entry, now);
551
558
  // value is cached at write time — hot reads return the live object directly,
552
559
  // skipping unpack. Falls back to decode for entries restored from disk/snapshot.
553
560
  const value = entry.value !== undefined ? entry.value : this.codec.decode(entry.data as Buffer);
@@ -564,10 +571,22 @@ export class SmartMemoryCache {
564
571
  fetchedAt: now,
565
572
  tagVersions: entry.tagVersions,
566
573
  setAt: entry.setAt,
574
+ revision: entry.revision,
575
+ tags: entry.tags,
576
+ dependsOn: entry.dependsOn,
567
577
  };
568
578
  return hit;
569
579
  }
570
580
 
581
+ /** Shared policy accounting for scalar and batch reads. */
582
+ recordAccess(key: string, entry: SmartCacheEntry, now = Date.now()): void {
583
+ if (this.cache.get(key) !== entry) return;
584
+ entry.hits++;
585
+ entry.lastAccess = now;
586
+ if ((entry.hits & 3) === 0) this.sketch.increment(key);
587
+ this.wtinyPolicy?.onAccess(key);
588
+ }
589
+
571
590
  set(
572
591
  key: string,
573
592
  data: unknown,
@@ -577,10 +596,42 @@ export class SmartMemoryCache {
577
596
  delta?: number,
578
597
  tagVersions?: Record<string, number>,
579
598
  setAt?: number,
580
- ): void {
599
+ tags?: string[],
600
+ dependsOn?: string[],
601
+ revision: string = randomUUID(),
602
+ ): boolean {
581
603
  // Single serialization pass — always msgpackr. Eliminates the prior JSON.stringify
582
604
  // "size probe" that was discarded for large payloads (the double-pass).
583
- const packed = this.codec.encode(data);
605
+ return this.setPacked(key, this.codec.encode(data), data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn, revision);
606
+ }
607
+
608
+ /**
609
+ * Store a value when its codec representation is already available.
610
+ * CacheService uses this to share one MessagePack encoding between L1 and
611
+ * Redis/disk writes on an origin fill. The buffer is treated as immutable.
612
+ */
613
+ setPacked(
614
+ key: string,
615
+ packed: Buffer,
616
+ data: unknown,
617
+ ttlMs: number,
618
+ priority: CachePriority = 2 /* NORMAL */,
619
+ staleAt?: number,
620
+ delta?: number,
621
+ tagVersions?: Record<string, number>,
622
+ setAt?: number,
623
+ tags?: string[],
624
+ dependsOn?: string[],
625
+ revision: string = randomUUID(),
626
+ ): boolean {
627
+ return this.storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn, revision);
628
+ }
629
+
630
+ private storePacked(
631
+ key: string, packed: Buffer, data: unknown, ttlMs: number, priority: CachePriority,
632
+ staleAt?: number, delta?: number, tagVersions?: Record<string, number>, setAt?: number,
633
+ tags?: string[], dependsOn?: string[], revision?: string,
634
+ ): boolean {
584
635
  const size = packed.byteLength;
585
636
  this.compressions++;
586
637
  this.sketch.increment(key);
@@ -588,9 +639,11 @@ export class SmartMemoryCache {
588
639
  const cat = this.getCategory(key);
589
640
  const lim = this.getCategoryLimit(cat);
590
641
 
591
- if (size > lim.maxSizeBytes * 0.5) {
642
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0 || this.opts.maxEntries <= 0 || lim.maxEntries <= 0 ||
643
+ size > this.opts.maxBytes || size > lim.maxSizeBytes * 0.5) {
644
+ this.delete(key); // An oversized replacement must not leave the old value readable.
592
645
  this.opts.logger.debug('SmartMemoryCache: entry too large, skipping', { key, sizeBytes: size });
593
- return;
646
+ return false;
594
647
  }
595
648
 
596
649
  // Single Map.get replaces Map.has + _delete's Map.get (saves one lookup on overwrite).
@@ -623,10 +676,13 @@ export class SmartMemoryCache {
623
676
  ttlMs,
624
677
  delta,
625
678
  setAt: setAt ?? now,
679
+ revision,
626
680
  tagVersions,
681
+ tags,
682
+ dependsOn,
627
683
  });
628
684
  }
629
- return;
685
+ return false;
630
686
  } else if (decision.candidateKey) {
631
687
  // An older window candidate was rejected to make room for key
632
688
  const candEntry = this.cache.get(decision.candidateKey);
@@ -644,21 +700,28 @@ export class SmartMemoryCache {
644
700
  this._delete(decision.evictKey, 'capacity');
645
701
  }
646
702
 
647
- // Check category byte limit or total byte limit
703
+ // Count and byte limits apply to TinyLFU too, including category quotas.
648
704
  const catSz = this.categorySize.get(cat) ?? 0;
649
- if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
705
+ if ((this.categoryCount.get(cat) ?? 0) >= lim.maxEntries || this.cache.size >= this.opts.maxEntries ||
706
+ catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
650
707
  this.ensureCapacity(cat, size);
651
708
  }
652
709
  } else {
653
710
  this.ensureCapacity(cat, size);
654
711
  }
655
712
 
713
+ if (this.cache.size >= this.opts.maxEntries || (this.categoryCount.get(cat) ?? 0) >= lim.maxEntries ||
714
+ this.totalSize + size > this.opts.maxBytes || (this.categorySize.get(cat) ?? 0) + size > lim.maxSizeBytes) {
715
+ this.wtinyPolicy?.onDelete(key);
716
+ return false;
717
+ }
718
+
656
719
  const now = Date.now();
657
720
  // Only cache the live object for small entries — large entries would store the packed
658
721
  // buffer AND a potentially much-larger deserialized object simultaneously (double-heap).
659
722
  // For large entries, get() falls back to the unpack() path transparently.
660
723
  const liveValue = size <= LARGE_VALUE_BYTES ? data : undefined;
661
- this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: setAt ?? now, tagVersions });
724
+ this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: setAt ?? now, revision, tagVersions, tags, dependsOn });
662
725
  // Only add new keys to the bloom — overwrites already have their bits set.
663
726
  // Re-adding inflates the insertions counter, delaying trigger-2 phantom detection.
664
727
  if (!existingEntry) this.bloom.add(key);
@@ -669,6 +732,7 @@ export class SmartMemoryCache {
669
732
  let ks = this.categoryKeys.get(cat);
670
733
  if (!ks) { ks = new Set(); this.categoryKeys.set(cat, ks); }
671
734
  ks.add(key);
735
+ return true;
672
736
  }
673
737
 
674
738
  delete(key: string): boolean {
@@ -688,7 +752,7 @@ export class SmartMemoryCache {
688
752
  // the Set during the subsequent iteration are safe.
689
753
  if (pattern.endsWith('*') && pattern.indexOf('*') === pattern.length - 1) {
690
754
  const prefix = pattern.slice(0, -1);
691
- const catKeys = this.categoryKeys.get(prefix);
755
+ const catKeys = this.categoryKeys.get(prefix.slice(this.opts.keyPrefixLength ?? 0));
692
756
  if (catKeys !== undefined) return Array.from(catKeys);
693
757
  }
694
758
 
@@ -838,7 +902,7 @@ export class SmartMemoryCache {
838
902
  }
839
903
 
840
904
  /**
841
- * Evict all non-CRITICAL L1 entries that were written before `cutoffMs`.
905
+ * Evict all L1 entries that were written before `cutoffMs`, at every priority.
842
906
  *
843
907
  * Called by the backplane staleness fence when the Pub/Sub subscriber
844
908
  * reconnects after a disconnect gap that exceeded `backplaneMaxStalenessMs`.
@@ -858,8 +922,6 @@ export class SmartMemoryCache {
858
922
  let evicted = 0;
859
923
  for (const [key, entry] of this.cache) {
860
924
  // Never evict live CRITICAL entries — auth tokens, active sessions, etc.
861
- if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > Date.now()) continue;
862
-
863
925
  // Prefer the explicit setAt timestamp; fall back to approximation for older entries.
864
926
  const setAt = entry.setAt ?? (entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0);
865
927
 
@@ -877,8 +939,7 @@ export class SmartMemoryCache {
877
939
 
878
940
  /**
879
941
  * Delete a key only if its write timestamp (`setAt`) is <= `cutoffMs`.
880
- * Used for concurrency-safe compare-and-delete on stale generational reads,
881
- * guaranteeing that a newer value written by a concurrent revalidation is never wiped out.
942
+ * This is a time-based eviction policy; use deleteIfRevision for write identity.
882
943
  */
883
944
  deleteIfSetBefore(key: string, cutoffMs: number): boolean {
884
945
  const entry = this.cache.get(key);
@@ -892,6 +953,11 @@ export class SmartMemoryCache {
892
953
  return false;
893
954
  }
894
955
 
956
+ /** Remove exactly the observed write, even when another write shares its timestamp. */
957
+ deleteIfRevision(key: string, revision: string): boolean {
958
+ if (!isWriteRevision(revision) || this.cache.get(key)?.revision !== revision) return false;
959
+ return this.delete(key);
960
+ }
895
961
 
896
962
 
897
963
  exportEntries(forbiddenPrefixes: readonly string[]): Array<{ key: string; entry: SmartCacheEntry }> {
@@ -901,7 +967,8 @@ export class SmartMemoryCache {
901
967
  if (entry.expiresAt <= now) continue;
902
968
  if (entry.priority === 4 /* CRITICAL */) continue;
903
969
  if (forbiddenPrefixes.some(p => key.startsWith(p))) continue;
904
- out.push({ key, entry: { ...entry } });
970
+ const { value: _value, ...stored } = entry;
971
+ out.push({ key, entry: { ...stored } });
905
972
  }
906
973
  return out;
907
974
  }
@@ -909,24 +976,31 @@ export class SmartMemoryCache {
909
976
  importEntries(entries: Array<{ key: string; entry: SmartCacheEntry }>, forbiddenPrefixes: readonly string[]): number {
910
977
  const now = Date.now();
911
978
  let loaded = 0;
912
- for (const { key, entry } of entries) {
913
- if (entry.expiresAt <= now) continue;
979
+ for (const item of entries) {
980
+ if (!item || typeof item.key !== 'string' || !item.entry) continue;
981
+ const { key, entry } = item;
982
+ if (entry.revision !== undefined && !isWriteRevision(entry.revision)) continue;
983
+ if (!Number.isFinite(entry.expiresAt) || entry.expiresAt <= now) continue;
914
984
  if (forbiddenPrefixes.some(p => key.startsWith(p))) continue;
915
985
  if (this.cache.has(key)) continue;
916
- const rawData = entry.data;
917
- // Handle both legacy (isCompressed=false, data=JSON string) and current (data=Buffer) formats.
918
- const data: Buffer = !entry.isCompressed
919
- ? this.codec.encode(JSON.parse(rawData as unknown as string)) // legacy: re-encode JSON → msgpackr
920
- : rawData instanceof Uint8Array
921
- ? Buffer.from(rawData) // msgpackr Uint8Array → Buffer
922
- : rawData as Buffer; // already a Buffer
923
- // Cache the live object for small entries only — large entries skip double-heap storage.
924
- const value = entry.size <= LARGE_VALUE_BYTES ? this.codec.decode(data) : undefined;
925
- this.cache.set(key, { ...entry, data, value, isCompressed: true });
926
- this.bloom.add(key);
927
- loaded++;
986
+ try {
987
+ const rawData = entry.data;
988
+ const data = !entry.isCompressed
989
+ ? this.codec.encode(JSON.parse(rawData as unknown as string))
990
+ : rawData instanceof Uint8Array ? Buffer.from(rawData) : null;
991
+ if (!data) continue;
992
+ const value = data.length <= LARGE_VALUE_BYTES ? this.codec.decode(data) : undefined;
993
+ if (this.storePacked(key, data, value, entry.expiresAt - now, entry.priority, entry.staleAt,
994
+ entry.delta, entry.tagVersions, entry.setAt, entry.tags, entry.dependsOn, entry.revision)) {
995
+ const restored = this.cache.get(key)!;
996
+ restored.expiresAt = entry.expiresAt;
997
+ restored.ttlMs = entry.ttlMs ?? entry.expiresAt - now;
998
+ restored.hits = Number.isFinite(entry.hits) ? Math.max(1, entry.hits) : 1;
999
+ restored.lastAccess = Number.isFinite(entry.lastAccess) ? entry.lastAccess : now;
1000
+ loaded++;
1001
+ }
1002
+ } catch { /* One corrupt snapshot entry must not discard the healthy entries. */ }
928
1003
  }
929
- this.recalculateStats();
930
1004
  return loaded;
931
1005
  }
932
1006
 
@@ -1019,6 +1093,7 @@ export class SmartMemoryCache {
1019
1093
  bloom: {
1020
1094
  checks: this.bloomChecks,
1021
1095
  falsePositives: this.bloomFalsePos,
1096
+ absentChecks: this.bloomAbsentChecks,
1022
1097
  },
1023
1098
  compression: {
1024
1099
  compressed: this.compressions,
@@ -1071,11 +1146,13 @@ export class SmartMemoryCache {
1071
1146
  * Add additional milliseconds to a key's existing expiry (for stale-if-error).
1072
1147
  * Returns `false` if the key is absent or already expired.
1073
1148
  */
1074
- bumpExpiry(key: string, additionalMs: number): boolean {
1149
+ bumpExpiry(key: string, additionalMs: number, maximumExpiry = Infinity): boolean {
1075
1150
  const entry = this.cache.get(key);
1076
1151
  if (!entry) return false;
1077
1152
  if (entry.expiresAt <= Date.now()) return false;
1078
- entry.expiresAt += additionalMs;
1153
+ const next = Math.min(entry.expiresAt + additionalMs, maximumExpiry);
1154
+ if (next <= entry.expiresAt) return false;
1155
+ entry.expiresAt = next;
1079
1156
  return true;
1080
1157
  }
1081
1158