tricache 1.0.0 → 1.0.2

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 (97) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-pJ-nFcVj.d.ts → cache-service-B108FzER.d.ts} +63 -3
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-26GCO3UU.js → cache-service-GYPZFB7O.js} +2 -2
  5. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  6. package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
  7. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  8. package/dist/chunk-OYDU3SMI.js +89 -0
  9. package/dist/{chunk-VXFTFZ5N.js → chunk-VNRDL5RA.js} +117 -138
  10. package/dist/{chunk-7SZSQS55.js → chunk-WYF7NOAT.js} +1831 -759
  11. package/dist/cli.cjs +1757 -777
  12. package/dist/cli.d.cts +12 -0
  13. package/dist/cli.js +27 -6
  14. package/dist/dashboard/index.cjs +111 -29
  15. package/dist/dashboard/index.d.cts +185 -0
  16. package/dist/dashboard/index.d.ts +5 -3
  17. package/dist/dashboard/index.js +1 -1
  18. package/dist/drizzle/index.cjs +1757 -773
  19. package/dist/drizzle/index.d.cts +46 -0
  20. package/dist/drizzle/index.d.ts +2 -2
  21. package/dist/drizzle/index.js +1 -1
  22. package/dist/edge/index.cjs +280 -153
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +254 -147
  26. package/dist/hono/index.cjs +1805 -793
  27. package/dist/hono/index.d.cts +93 -0
  28. package/dist/hono/index.d.ts +7 -5
  29. package/dist/hono/index.js +16 -9
  30. package/dist/{hono-DuNvciyq.d.ts → hono-3rDMYVtY.d.ts} +23 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1946 -842
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +137 -57
  36. package/dist/index.cjs +2073 -937
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +40 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1849 -806
  42. package/dist/nestjs/index.d.cts +285 -0
  43. package/dist/nestjs/index.d.ts +103 -30
  44. package/dist/nestjs/index.js +115 -32
  45. package/dist/next/index.cjs +1913 -887
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +174 -107
  49. package/dist/prisma/index.cjs +11 -1
  50. package/dist/prisma/index.d.cts +62 -0
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +11 -1
  53. package/dist/serialize-worker.d.cts +2 -0
  54. package/dist/{types-5HXqBfAf.d.ts → types-BA4pz1A0.d.cts} +26 -9
  55. package/dist/types-BA4pz1A0.d.ts +1519 -0
  56. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  57. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  58. package/package.json +96 -36
  59. package/src/adapters/auto-pipeliner.ts +107 -24
  60. package/src/adapters/node-redis.ts +123 -25
  61. package/src/cache-service.ts +1238 -659
  62. package/src/cli.ts +24 -6
  63. package/src/cross-region.ts +21 -3
  64. package/src/dashboard/handler.ts +26 -6
  65. package/src/dashboard/html.ts +35 -10
  66. package/src/dashboard/index.ts +35 -13
  67. package/src/dashboard/types.ts +3 -1
  68. package/src/disk-tier.ts +171 -65
  69. package/src/edge/cache.ts +202 -129
  70. package/src/edge/hono.ts +23 -6
  71. package/src/edge/types.ts +2 -0
  72. package/src/hono/index.ts +19 -9
  73. package/src/http/express.ts +110 -26
  74. package/src/http/fastify.ts +38 -28
  75. package/src/http/utils.ts +54 -20
  76. package/src/ipc-telemetry.ts +35 -9
  77. package/src/nestjs/decorators.ts +1 -1
  78. package/src/nestjs/index.ts +2 -0
  79. package/src/nestjs/keyv-adapter.ts +68 -0
  80. package/src/nestjs/tricache.module.ts +13 -11
  81. package/src/nestjs/tricache.store.ts +51 -20
  82. package/src/nestjs/types.ts +29 -15
  83. package/src/next/cache-handler.ts +132 -57
  84. package/src/next/index.ts +1 -0
  85. package/src/next/isr-handler.ts +1 -4
  86. package/src/next/types.ts +21 -0
  87. package/src/prisma/index.ts +12 -1
  88. package/src/smart-memory-cache.ts +65 -27
  89. package/src/types.ts +27 -2
  90. package/src/utils/cgroup.ts +12 -0
  91. package/src/utils/deadline.ts +14 -0
  92. package/src/utils/diagnostics.ts +27 -0
  93. package/src/utils/redis-slot.ts +13 -0
  94. package/src/wasm/bloom-filter-wasm.ts +9 -4
  95. package/src/worker-pool.ts +17 -8
  96. package/src/wtiny-lfu.ts +20 -6
  97. package/dist/chunk-BQRURGGD.js +0 -60
@@ -20,6 +20,7 @@ import { Redis as RedisClient, Cluster as RedisCluster } from 'ioredis';
20
20
  import { CacheCodec } from './codec.js';
21
21
  import type { RemoteSnapshotOptions } from './remote-snapshot.js';
22
22
  import type { CrossRegionRelayOptions, CrossRegionInvalidationEvent } from './cross-region.js';
23
+ import { isCrossRegionInvalidationEvent } from './cross-region.js';
23
24
  import crypto from 'crypto';
24
25
  import os from 'os';
25
26
  import { WorkerPool } from './worker-pool.js';
@@ -45,18 +46,23 @@ import {
45
46
  LockOptions,
46
47
  ICacheMeter,
47
48
  ICacheCounter,
49
+ ICacheBatchObservableCallback,
48
50
  IRedisDriver,
49
51
  WTinyLfuStats,
50
52
  CachePresetType,
51
53
  CacheHealthStatus,
52
54
  InvalidateTagOptions,
55
+ EvictionReason,
53
56
  } from './types';
54
57
  import { CacheEncryption, EnvelopeEncryption, type EncryptionMode } from './encryption';
55
58
  import { SmartMemoryCache } from './smart-memory-cache';
56
59
  import { DiskTier, resolveDefaultDiskDir } from './disk-tier';
57
60
  import { TierLatencyWatchdog } from './latency-watchdog';
58
- import { resolveAutonomousL1MaxBytes } from './utils/cgroup';
59
- import { AutoPipeliner } from './adapters/auto-pipeliner';
61
+ import { resolveAutonomousL1MaxBytes, readCgroupMemoryLimit, readCgroupMemoryUsage } from './utils/cgroup';
62
+ import { redactDiagnostics } from './utils/diagnostics';
63
+ import { redisHashSlot } from './utils/redis-slot';
64
+ import { withDeadline } from './utils/deadline';
65
+ import { AutoPipeliner, readRedisValue } from './adapters/auto-pipeliner';
60
66
  import { IpcTelemetryServer } from './ipc-telemetry.js';
61
67
  import {
62
68
  compressBuffer,
@@ -84,6 +90,52 @@ end
84
90
  return 0
85
91
  `;
86
92
 
93
+ const LUA_READ_CACHE_ENTRY = `
94
+ local kind = redis.call('TYPE', KEYS[1]).ok
95
+ if kind == 'string' then
96
+ return { kind, redis.call('GET', KEYS[1]), redis.call('PTTL', KEYS[1]) }
97
+ elseif kind == 'hash' then
98
+ return { kind, redis.call('HGETALL', KEYS[1]), redis.call('PTTL', KEYS[1]) }
99
+ end
100
+ return { 'none', false, -2 }
101
+ `;
102
+
103
+ const LUA_MAX_TAG_VERSION = `
104
+ local current = tonumber(redis.call('GET', KEYS[1]) or '0')
105
+ local floor = tonumber(ARGV[1])
106
+ if current < floor then redis.call('SET', KEYS[1], floor) return floor end
107
+ return current
108
+ `;
109
+
110
+ const LUA_RECEIVE_TAG_VERSION = `
111
+ local current = tonumber(redis.call('GET', KEYS[1]) or '0')
112
+ local next = math.max(current + 1, tonumber(ARGV[1]))
113
+ redis.call('SET', KEYS[1], next)
114
+ return next
115
+ `;
116
+
117
+ const LUA_TOUCH_CACHE_ENTRY = `
118
+ local kind = redis.call('TYPE', KEYS[1]).ok
119
+ if kind == 'hash' then
120
+ if redis.call('HGET', KEYS[1], 't') ~= ARGV[1] then return 0 end
121
+ redis.call('HSET', KEYS[1], 'e', ARGV[2])
122
+ elseif kind ~= 'string' then
123
+ return 0
124
+ end
125
+ return redis.call('PEXPIRE', KEYS[1], ARGV[3])
126
+ `;
127
+
128
+ interface RedisCacheEntry<T> {
129
+ value?: T;
130
+ tagVersions?: Record<string, number>;
131
+ tags?: string[];
132
+ dependsOn?: string[];
133
+ setAt?: number;
134
+ expiresAt?: number;
135
+ staleAt?: number;
136
+ stale: boolean;
137
+ }
138
+
87
139
  // ─── Snapshot constants ───────────────────────────────────────────────────────
88
140
 
89
141
  const SNAPSHOT_VERSION = 1;
@@ -558,13 +610,19 @@ export class CacheService {
558
610
  private readonly _l1Counters = new Map<string, { value: number; expiresAt: number }>();
559
611
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
560
612
  private readonly tagIndex = new Map<string, Set<string>>();
613
+ /** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
614
+ private readonly keyTags = new Map<string, { tags: string[]; expiresAt: number }>();
561
615
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
562
- private readonly tagVersions = new Map<string, { version: number; lastSyncedAt: number }>();
616
+ private readonly tagVersions = new Map<string, { version: number; lastSyncedAt: number; refreshEpoch?: number }>();
617
+ private _tagRefreshEpoch = 0;
563
618
  /**
564
619
  * Dependency index: source glob pattern → Set of namespaced dependent keys.
565
620
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
566
621
  */
567
622
  private readonly dependencyIndex = new Map<string, Set<string>>();
623
+ /** Reverse index of namespaced dependent key → source glob patterns */
624
+ private readonly keyDependencies = new Map<string, string[]>();
625
+ private readonly _cgroupMemoryLimit: number;
568
626
  private redis: AnyRedisClient | null = null;
569
627
  private redisConnecting: Promise<AnyRedisClient> | null = null;
570
628
  private readonly cb: L2CircuitBreaker;
@@ -587,9 +645,17 @@ export class CacheService {
587
645
  private subClient: AnyRedisClient | null = null;
588
646
  private streamClient: AnyRedisClient | null = null;
589
647
  private _lastStreamId = '$';
648
+ private _restoredSnapshot = false;
649
+ private _backplaneAvailable = false;
650
+ private _otelCleanup: (() => void) | null = null;
651
+ private _streamRecovering = false;
652
+ private readonly _backplaneDisposers: Array<() => void> = [];
590
653
  private _destroyed = false;
591
654
  private readonly _pendingDiskDeletes = new Set<string>();
592
655
  private _globalEpoch = 0;
656
+ private _pendingSpillCount = 0;
657
+ private _suppressSpills = false;
658
+ private _diskCleanupScheduled = false;
593
659
  private readonly _keyMutationEpochs = new Map<string, number>();
594
660
  /**
595
661
  * Pattern tombstones for disk tier.
@@ -597,23 +663,27 @@ export class CacheService {
597
663
  * Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
598
664
  * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
599
665
  */
600
- private readonly _patternTombstones: Array<{ prefix: string; createdAt: number }> = [];
666
+ private readonly _patternTombstones: Array<{ pattern: string; createdAt: number }> = [];
667
+ private _diskInvalidatedBefore = 0;
601
668
 
602
- private _addPatternTombstone(prefix: string): void {
669
+ private _addPatternTombstone(pattern: string): void {
603
670
  const now = Date.now();
604
671
  while (this._patternTombstones.length > 0 && (now - this._patternTombstones[0].createdAt > 3_600_000)) {
605
- this._patternTombstones.shift();
672
+ const forgotten = this._patternTombstones.shift()!;
673
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
606
674
  }
607
675
  if (this._patternTombstones.length >= 2_000) {
608
- this._patternTombstones.shift();
676
+ const forgotten = this._patternTombstones.shift()!;
677
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
609
678
  }
610
- this._patternTombstones.push({ prefix, createdAt: now });
679
+ this._patternTombstones.push({ pattern, createdAt: now });
611
680
  }
612
681
 
613
- private _isTombstonedByPattern(namespacedKey: string): boolean {
682
+ private _isTombstonedByPattern(namespacedKey: string, setAt = 0): boolean {
683
+ if (this._diskInvalidatedBefore > 0 && setAt <= this._diskInvalidatedBefore) return true;
614
684
  if (this._patternTombstones.length === 0) return false;
615
685
  for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
616
- if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
686
+ if (setAt <= this._patternTombstones[i].createdAt && this._matchesGlob(namespacedKey, this._patternTombstones[i].pattern)) {
617
687
  return true;
618
688
  }
619
689
  }
@@ -630,14 +700,188 @@ export class CacheService {
630
700
  const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
631
701
  this._keyMutationEpochs.set(namespacedKey, next);
632
702
  if (this._keyMutationEpochs.size > 50_000) {
633
- const oldest = this._keyMutationEpochs.keys().next().value;
634
- if (oldest !== undefined) this._keyMutationEpochs.delete(oldest);
703
+ // Rotate a bounded fence era, rather than cancelling unrelated work on
704
+ // every subsequent write once the map reaches capacity.
705
+ this._globalEpoch++;
706
+ this._keyMutationEpochs.clear();
707
+ this._keyMutationEpochs.set(namespacedKey, next);
635
708
  }
636
709
  return next;
637
710
  }
638
711
 
639
- private _getKeyMutationEpoch(namespacedKey: string): number {
640
- return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
712
+ private _getKeyMutationEpoch(namespacedKey: string): string {
713
+ return `${this._globalEpoch}:${this._keyMutationEpochs.get(namespacedKey) ?? 0}`;
714
+ }
715
+
716
+ /** Capture a commit fence before asynchronous computation outside the cache. */
717
+ captureMutationFence(cacheKey: string): () => boolean {
718
+ this._assertActive('captureMutationFence');
719
+ const key = this.nk(cacheKey);
720
+ const epoch = this._getKeyMutationEpoch(key);
721
+ return () => !this._destroyed && this._getKeyMutationEpoch(key) === epoch;
722
+ }
723
+
724
+ /** Force tag re-sync without forgetting locally observed monotonic generations. */
725
+ refreshTagVersions(): void {
726
+ this._assertActive('refreshTagVersions');
727
+ this._tagRefreshEpoch++;
728
+ }
729
+
730
+ private _fenceInvalidation(): void {
731
+ this._globalEpoch++;
732
+ this.inflight.clear();
733
+ }
734
+
735
+ private _invalidateDiskKey(key: string): void {
736
+ if (this._diskDisabled) return;
737
+ this.disk.invalidate(key);
738
+ this._pendingDiskDeletes.add(key);
739
+ this._scheduleDiskCleanup();
740
+ }
741
+
742
+ private _scheduleDiskCleanup(): void {
743
+ if (this._diskCleanupScheduled || this._pendingDiskDeletes.size === 0) return;
744
+ this._diskCleanupScheduled = true;
745
+ setImmediate(() => {
746
+ this._diskCleanupScheduled = false;
747
+ if (this._destroyed) return;
748
+ let processed = 0;
749
+ for (const key of this._pendingDiskDeletes) {
750
+ try { this.disk.delete(key, true); }
751
+ finally { this._pendingDiskDeletes.delete(key); }
752
+ if (++processed >= 16) break;
753
+ }
754
+ this._scheduleDiskCleanup();
755
+ });
756
+ }
757
+
758
+ private _registerDependencies(key: string, patterns?: string[]): void {
759
+ this._removeKeyDependencies(key);
760
+ if (!patterns?.length) return;
761
+ const namespaced = [...new Set(patterns.map(pattern => this.nk(pattern)))];
762
+ for (const pattern of namespaced) {
763
+ const dependents = this.dependencyIndex.get(pattern) ?? new Set<string>();
764
+ dependents.add(key);
765
+ this.dependencyIndex.set(pattern, dependents);
766
+ }
767
+ this.keyDependencies.set(key, namespaced);
768
+ }
769
+
770
+ private _rememberTags(key: string, tags: string[], expiresAt: number): void {
771
+ this._removeKeyTags(key);
772
+ if (!tags.length) return;
773
+ if (this.keyTags.size >= 100_000) {
774
+ this._sweepExpiredMetadata();
775
+ const oldest = this.keyTags.keys().next().value;
776
+ if (this.keyTags.size >= 100_000 && oldest !== undefined) this._removeKeyTags(oldest);
777
+ }
778
+ const unique = [...new Set(tags)];
779
+ for (const tag of unique) {
780
+ const tagKey = this.nk(`_tag_:${tag}`);
781
+ const members = this.tagIndex.get(tagKey) ?? new Set<string>();
782
+ members.add(key);
783
+ this.tagIndex.set(tagKey, members);
784
+ }
785
+ this.keyTags.set(key, { tags: unique, expiresAt });
786
+ }
787
+
788
+ private _restoreEntryMetadata(key: string, entry: { tags?: string[]; dependsOn?: string[]; expiresAt: number }): void {
789
+ if (entry.tags?.length) this._rememberTags(key, entry.tags, entry.expiresAt);
790
+ if (entry.dependsOn?.length) this._registerDependencies(key, entry.dependsOn);
791
+ }
792
+
793
+ private _removeKeyTags(namespacedKey: string): void {
794
+ const entry = this.keyTags.get(namespacedKey);
795
+ if (!entry) return;
796
+ for (const tag of entry.tags) {
797
+ const tagKey = this.nk(`_tag_:${tag}`);
798
+ const members = this.tagIndex.get(tagKey);
799
+ if (members) {
800
+ members.delete(namespacedKey);
801
+ if (members.size === 0) this.tagIndex.delete(tagKey);
802
+ }
803
+ }
804
+ this.keyTags.delete(namespacedKey);
805
+ }
806
+
807
+ private _removeKeyDependencies(namespacedKey: string): void {
808
+ const patterns = this.keyDependencies.get(namespacedKey);
809
+ if (patterns) {
810
+ for (const pat of patterns) {
811
+ const deps = this.dependencyIndex.get(pat);
812
+ if (deps) {
813
+ deps.delete(namespacedKey);
814
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
815
+ }
816
+ }
817
+ this.keyDependencies.delete(namespacedKey);
818
+ } else if (this.dependencyIndex.size > 0) {
819
+ for (const [pat, deps] of this.dependencyIndex) {
820
+ deps.delete(namespacedKey);
821
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
822
+ }
823
+ }
824
+ }
825
+
826
+ private _handleL1Eviction(namespacedKey: string, reason: EvictionReason): void {
827
+ const spilledToDisk = !this._diskDisabled && !this._suppressSpills && (
828
+ reason === 'capacity' ||
829
+ reason === 'category' ||
830
+ reason === 'rebalance' ||
831
+ reason === 'oom'
832
+ );
833
+ if (!spilledToDisk) {
834
+ this._removeKeyTags(namespacedKey);
835
+ this._removeKeyDependencies(namespacedKey);
836
+ }
837
+ }
838
+
839
+ private _removePatternFromIndices(pattern: string): void {
840
+ for (const k of Array.from(this.keyTags.keys())) {
841
+ if (this._matchesGlob(k, pattern)) this._removeKeyTags(k);
842
+ }
843
+ for (const k of Array.from(this.keyDependencies.keys())) {
844
+ if (this._matchesGlob(k, pattern)) this._removeKeyDependencies(k);
845
+ }
846
+ for (const k of Array.from(this._l1Counters.keys())) {
847
+ if (this._matchesGlob(k, pattern)) this._l1Counters.delete(k);
848
+ }
849
+ }
850
+
851
+ private _sweepExpiredMetadata(): void {
852
+ const now = Date.now();
853
+ for (const [k, c] of this._l1Counters) {
854
+ if (c.expiresAt <= now) this._l1Counters.delete(k);
855
+ }
856
+ for (const [k, meta] of this.keyTags) {
857
+ if (meta.expiresAt <= now && !this.l1.has(k)) {
858
+ this._removeKeyTags(k);
859
+ this._removeKeyDependencies(k);
860
+ }
861
+ }
862
+ }
863
+
864
+ private _runOomCheck(): void {
865
+ const heap = v8.getHeapStatistics();
866
+ const heapUsed = heap.used_heap_size / heap.heap_size_limit;
867
+ const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0
868
+ ? (readCgroupMemoryUsage() ?? process.memoryUsage().rss) / this._cgroupMemoryLimit
869
+ : 0;
870
+ const used = Math.max(heapUsed, cgroupUsed);
871
+ if (used >= this.opts.oomHeapThreshold) {
872
+ this._suppressSpills = cgroupUsed >= this.opts.oomHeapThreshold;
873
+ let evicted: number;
874
+ try { evicted = this.l1.evictPercentage(this.opts.oomEvictPercent); }
875
+ finally { this._suppressSpills = false; }
876
+ this.counters.oomEvictions++;
877
+ this.counters.oomLastAt = Date.now();
878
+ this.logger.warn('tricache OOM guard: emergency L1 eviction', {
879
+ heapUsedPct: Math.round(heapUsed * 100),
880
+ cgroupUsedPct: cgroupUsed > 0 ? Math.round(cgroupUsed * 100) : undefined,
881
+ threshold: Math.round(this.opts.oomHeapThreshold * 100),
882
+ evicted,
883
+ });
884
+ }
641
885
  }
642
886
  private _ipcServer?: IpcTelemetryServer;
643
887
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
@@ -688,6 +932,7 @@ export class CacheService {
688
932
  constructor(options: CacheOptions = {}) {
689
933
  const logger = options.logger ?? consoleLogger;
690
934
  this.logger = logger;
935
+ this._cgroupMemoryLimit = readCgroupMemoryLimit();
691
936
 
692
937
  // Resolve namespace: trim whitespace, default to empty string
693
938
  const ns = options.namespace?.trim() ?? '';
@@ -896,14 +1141,23 @@ export class CacheService {
896
1141
  admissionPolicy: this.opts.l1AdmissionPolicy,
897
1142
  codec: this.codec,
898
1143
  diskSpill: (key: string, entry: SmartCacheEntry) => {
899
- if (this._diskDisabled) return; // Fix 3: skip spill in serverless environments
1144
+ if (this._diskDisabled || this._suppressSpills) return;
1145
+ if (this._pendingSpillCount >= (this.opts.diskMaxPendingWrites ?? 512)) return;
1146
+ const epoch = this._getKeyMutationEpoch(key);
1147
+ this._pendingSpillCount++;
900
1148
  // Defer disk.save() entirely to the next event-loop tick so the synchronous
901
1149
  // preamble inside save() (SHA-256 keyToPath + msgpackr pack) does not block
902
1150
  // the l1.set() → smartEvict → diskSpill call chain. Mirrors what the
903
1151
  // backplane handler already does for remote invalidations.
904
- setImmediate(() => { void this.disk.save(key, entry as unknown as DiskCacheEntry); });
1152
+ setImmediate(() => {
1153
+ this._pendingSpillCount--;
1154
+ if (!this._destroyed && this._getKeyMutationEpoch(key) === epoch) void this.disk.save(key, entry as unknown as DiskCacheEntry);
1155
+ });
1156
+ },
1157
+ onEviction: (key: string, reason: EvictionReason) => {
1158
+ this._handleL1Eviction(key, reason);
1159
+ options.onEviction?.(key, reason);
905
1160
  },
906
- onEviction: options.onEviction,
907
1161
  logger,
908
1162
  });
909
1163
 
@@ -952,6 +1206,7 @@ export class CacheService {
952
1206
  // here to avoid a synchronous O(fileCount) event-loop stall at scale.
953
1207
  this.cleanupInterval = setInterval(() => {
954
1208
  const cleaned = this.l1.cleanup();
1209
+ this._sweepExpiredMetadata();
955
1210
  if (cleaned > 0) this.logger.debug('Periodic L1 cleanup', { cleaned });
956
1211
  }, 5 * 60 * 1000);
957
1212
  if (this.cleanupInterval.unref) this.cleanupInterval.unref(); // don't block process exit
@@ -965,21 +1220,10 @@ export class CacheService {
965
1220
  if (this.diskJanitorInterval.unref) this.diskJanitorInterval.unref();
966
1221
  }
967
1222
 
968
- // OOM protection: evict coldest L1 entries when heap pressure rises
1223
+ // OOM protection: evict coldest L1 entries when heap or container RSS pressure rises
969
1224
  if (this.opts.oomProtection) {
970
1225
  this.oomInterval = setInterval(() => {
971
- const heap = v8.getHeapStatistics();
972
- const used = heap.used_heap_size / heap.heap_size_limit;
973
- if (used >= this.opts.oomHeapThreshold) {
974
- const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
975
- this.counters.oomEvictions++;
976
- this.counters.oomLastAt = Date.now();
977
- this.logger.warn('tricache OOM guard: emergency L1 eviction', {
978
- heapUsedPct: Math.round(used * 100),
979
- threshold: Math.round(this.opts.oomHeapThreshold * 100),
980
- evicted,
981
- });
982
- }
1226
+ this._runOomCheck();
983
1227
  }, this.opts.oomCheckIntervalMs);
984
1228
  if (this.oomInterval.unref) this.oomInterval.unref();
985
1229
  }
@@ -1004,7 +1248,8 @@ export class CacheService {
1004
1248
  this.instanceId = crypto.randomBytes(8).toString('hex');
1005
1249
  this.backplaneChannel = `tricache:inv${ns ? ':' + ns : ''}`;
1006
1250
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || 'default'}}`;
1007
- this.initBackplane();
1251
+ const startBackplane = () => withDeadline(this.initBackplane(), this.opts.redisCommandTimeoutMs ?? 2500, 'Backplane initialization')
1252
+ .catch(error => this.logger.warn('Backplane initialization failed; continuing with local degradation', { error: (error as Error).message }));
1008
1253
 
1009
1254
  // Auto-warm from remote snapshot or L2 if configured; ready() waits for completion.
1010
1255
  const startupPromises: Promise<void>[] = [];
@@ -1017,9 +1262,11 @@ export class CacheService {
1017
1262
  if (this.opts.warmKeys) {
1018
1263
  startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => undefined));
1019
1264
  }
1020
- if (startupPromises.length > 0) {
1021
- this._readyPromise = Promise.all(startupPromises).then(() => undefined);
1022
- }
1265
+ // Hydrate before replaying a snapshot's stream cursor; otherwise replay could
1266
+ // run first and a late snapshot download could restore already-invalidated data.
1267
+ const backplaneReady = this.opts.remoteSnapshot || this.opts.warmKeys
1268
+ ? Promise.all(startupPromises).then(startBackplane) : startBackplane();
1269
+ this._readyPromise = Promise.all([...startupPromises, backplaneReady]).then(() => undefined);
1023
1270
 
1024
1271
  // Native OpenTelemetry metrics integration
1025
1272
  if (this.opts.meter) {
@@ -1035,7 +1282,7 @@ export class CacheService {
1035
1282
  if (typeof prop === 'string' && typeof value === 'number' && typeof oldVal === 'number') {
1036
1283
  const diff = value - oldVal;
1037
1284
  if (diff > 0 && otel[prop]) {
1038
- otel[prop]!.add(diff, nsAttr);
1285
+ try { otel[prop]!.add(diff, nsAttr); } catch { /* Telemetry must never fail a cache operation. */ }
1039
1286
  }
1040
1287
  }
1041
1288
  return ok;
@@ -1136,7 +1383,7 @@ export class CacheService {
1136
1383
 
1137
1384
  // Singleton already exists for this namespace — detect & surface divergence.
1138
1385
  const existing = g[key] as CacheService;
1139
- const diff = CacheService.optionsDiff(options ?? {}, existing.options);
1386
+ const diff = CacheService.optionsDiff(options ?? {}, existing.opts);
1140
1387
  if (diff.length > 0) {
1141
1388
  existing.bumpSingletonDivergence();
1142
1389
  const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || '(default)'}' — ignoring divergent options: ${diff.join(', ')}`;
@@ -1158,10 +1405,11 @@ export class CacheService {
1158
1405
  'redisClusterNodes', 'redisSentinel', 'encryptionKey', 'encryptionMode',
1159
1406
  'l1MaxBytes', 'l1MaxEntries', 'namespace', 'frozen', 'adaptiveTtl',
1160
1407
  'l2WriteMode', 'instanceName', 'invalidationBackplane', 'awaitInvalidationBackplane', 'lockFailClosed',
1408
+ 'tagStrategy', 'cloneStrategy', 'compression', 'backplaneMode', 'redisProtocol', 'failClosed',
1161
1409
  ];
1162
1410
 
1163
1411
  /** Returns the names of options that differ between `a` and the live `b`. */
1164
- private static optionsDiff(a: CacheOptions, b: CacheOptions): string[] {
1412
+ private static optionsDiff(a: CacheOptions, b: Record<string, unknown>): string[] {
1165
1413
  const out: string[] = [];
1166
1414
  for (const k of CacheService.DIVERGENT_KEYS) {
1167
1415
  const av = a[k];
@@ -1181,12 +1429,12 @@ export class CacheService {
1181
1429
  this.counters.singletonDivergences++;
1182
1430
  }
1183
1431
 
1184
- /** Read-only view of the options the singleton was constructed with. */
1432
+ /** Sanitized diagnostic view; retain the original options/adapters to reuse configuration. */
1185
1433
  get options(): CacheOptions {
1186
1434
  const o = this.opts;
1187
1435
  return {
1188
1436
  namespace: o.namespace,
1189
- logger: o.logger,
1437
+ logger: { debug: o.logger.debug.bind(o.logger), info: o.logger.info.bind(o.logger), warn: o.logger.warn.bind(o.logger), error: o.logger.error.bind(o.logger) },
1190
1438
  l1MaxBytes: o.l1MaxBytes,
1191
1439
  l1MaxEntries: o.l1MaxEntries,
1192
1440
  redisHost: o.redisHost,
@@ -1207,8 +1455,8 @@ export class CacheService {
1207
1455
  awaitInvalidationBackplane: o.awaitInvalidationBackplane,
1208
1456
  lockFailClosed: o.lockFailClosed,
1209
1457
  strictSingleton: o.strictSingleton,
1210
- remoteSnapshot: o.remoteSnapshot,
1211
- crossRegion: o.crossRegion,
1458
+ remoteSnapshot: redactDiagnostics(o.remoteSnapshot),
1459
+ crossRegion: redactDiagnostics(o.crossRegion),
1212
1460
  } as CacheOptions;
1213
1461
  }
1214
1462
 
@@ -1294,11 +1542,15 @@ export class CacheService {
1294
1542
  if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === 'function') {
1295
1543
  return this.opts.redisClient.duplicate();
1296
1544
  }
1545
+ if (this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel) {
1546
+ throw new Error('Invalidation backplane requires redisSubClient or a driver supporting duplicate()');
1547
+ }
1297
1548
  if (this.opts.redisClusterNodes?.length) {
1298
1549
  return new RedisCluster(this.opts.redisClusterNodes, {
1299
1550
  redisOptions: {
1300
1551
  tls: this.opts.redisTls ? {} : undefined,
1301
1552
  connectTimeout: 10_000,
1553
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
1302
1554
  maxRetriesPerRequest: null as unknown as number,
1303
1555
  ...(this.opts.redisProtocol && { protocol: this.opts.redisProtocol }),
1304
1556
  },
@@ -1309,6 +1561,7 @@ export class CacheService {
1309
1561
  name: this.opts.redisSentinel.name,
1310
1562
  tls: this.opts.redisTls ? {} : undefined,
1311
1563
  connectTimeout: 10_000,
1564
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
1312
1565
  lazyConnect: true,
1313
1566
  maxRetriesPerRequest: null as unknown as number,
1314
1567
  enableAutoPipelining: false,
@@ -1321,6 +1574,7 @@ export class CacheService {
1321
1574
  port: this.opts.redisPort,
1322
1575
  tls: this.opts.redisTls ? {} : undefined,
1323
1576
  connectTimeout: 10_000,
1577
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
1324
1578
  lazyConnect: true,
1325
1579
  maxRetriesPerRequest: null as unknown as number,
1326
1580
  enableAutoPipelining: false,
@@ -1331,33 +1585,40 @@ export class CacheService {
1331
1585
  }
1332
1586
  }
1333
1587
 
1334
- private initBackplane(): void {
1588
+ private _listenBackplane(client: AnyRedisClient, event: string, listener: (...args: any[]) => void): void {
1589
+ client.on?.(event, listener);
1590
+ this._backplaneDisposers.push(() => client.removeListener?.(event, listener));
1591
+ }
1592
+
1593
+ private async initBackplane(): Promise<void> {
1335
1594
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
1336
1595
 
1337
1596
  if (this.opts.backplaneMode === 'stream') {
1338
1597
  if (this.streamClient) return;
1339
- void this._startStreamConsumer();
1598
+ await this._startStreamConsumer();
1340
1599
  return;
1341
1600
  }
1342
1601
 
1343
1602
  if (this.subClient) return;
1344
1603
 
1345
1604
  const sub = this.createDedicatedRedisClient();
1605
+ this.subClient = sub;
1346
1606
 
1347
- sub.on('error', (e: Error) => {
1607
+ this._listenBackplane(sub, 'error', (e: Error) => {
1348
1608
  this._checkAndLogResp3Hint(e);
1349
1609
  this.logger.debug('Backplane subscriber error', { error: e.message });
1350
1610
  });
1351
1611
 
1352
1612
  // ── Staleness fence — track disconnect time ──────────────────────
1353
- sub.on('close', () => {
1613
+ this._listenBackplane(sub, 'close', () => {
1614
+ this._backplaneAvailable = false;
1354
1615
  if (this._subDisconnectedAt === null) {
1355
1616
  this._subDisconnectedAt = Date.now();
1356
1617
  this.logger.debug('Backplane: subscriber disconnected', { at: this._subDisconnectedAt });
1357
1618
  }
1358
1619
  });
1359
1620
 
1360
- sub.on('ready', () => {
1621
+ this._listenBackplane(sub, 'ready', () => {
1361
1622
  if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
1362
1623
  const gapMs = Date.now() - this._subDisconnectedAt;
1363
1624
  if (gapMs > this.opts.backplaneMaxStalenessMs) {
@@ -1369,54 +1630,70 @@ export class CacheService {
1369
1630
  }
1370
1631
  this._subDisconnectedAt = null;
1371
1632
  }
1633
+ if (!this._destroyed) this._backplaneAvailable = true;
1372
1634
  });
1373
1635
 
1374
1636
  const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
1375
1637
 
1376
1638
  if (isClusterSharded) {
1377
- sub.on('smessage', (_channel: string, message: string) => {
1639
+ this._listenBackplane(sub, 'smessage', (_channel: string, message: string) => {
1378
1640
  this._handleBackplaneMessage(message);
1379
1641
  });
1380
- (sub as unknown as { ssubscribe: (c: string) => Promise<unknown> })
1642
+ if (typeof sub.connect === 'function' && (sub.isOpen === false || sub.status === 'wait')) await sub.connect();
1643
+ await (sub as unknown as { ssubscribe: (c: string) => Promise<unknown> })
1381
1644
  .ssubscribe(this.backplaneChannel)
1382
1645
  .then(() => this.logger.info('Backplane: sharded subscribed', {
1383
1646
  channel: this.backplaneChannel, instanceId: this.instanceId,
1384
- }))
1385
- .catch((err: Error) => this.logger.warn('Backplane: sharded subscribe failed', {
1386
- error: err.message,
1387
1647
  }));
1388
1648
  } else {
1389
- sub.on('message', (_channel: string, message: string) => {
1649
+ this._listenBackplane(sub, 'message', (_channel: string, message: string) => {
1390
1650
  this._handleBackplaneMessage(message);
1391
1651
  });
1392
- sub.subscribe(this.backplaneChannel)
1652
+ if (typeof sub.connect === 'function' && (sub.isOpen === false || sub.status === 'wait')) await sub.connect();
1653
+ if (this._destroyed) return;
1654
+ await sub.subscribe(this.backplaneChannel)
1393
1655
  .then(() => this.logger.info('Backplane: subscribed', {
1394
1656
  channel: this.backplaneChannel, instanceId: this.instanceId,
1395
- }))
1396
- .catch((err: Error) => this.logger.warn('Backplane: subscribe failed', {
1397
- error: err.message,
1398
1657
  }));
1399
1658
  }
1400
1659
 
1401
- this.subClient = sub;
1660
+ if (!this._destroyed) this._backplaneAvailable = true;
1661
+ }
1662
+
1663
+ private _resetAfterStreamGap(): void {
1664
+ this.counters.streamGaps++;
1665
+ this._fenceInvalidation();
1666
+ this.l1.clear();
1667
+ this.tagIndex.clear();
1668
+ this.keyTags.clear();
1669
+ this.tagVersions.clear();
1670
+ this.dependencyIndex.clear();
1671
+ this.keyDependencies.clear();
1672
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, Date.now());
1673
+ this._addPatternTombstone(this.nk('*'));
1674
+ this._lastStreamId = '0-0';
1402
1675
  }
1403
1676
 
1404
1677
  private async _startStreamConsumer(): Promise<void> {
1678
+ this._streamRecovering ||= this._lastStreamId !== '$' && this._lastStreamId !== '0-0';
1405
1679
  const sub = this.streamClient ?? this.createDedicatedRedisClient();
1406
1680
  this.streamClient = sub;
1681
+ if (typeof sub.xread !== 'function') throw new Error('backplaneMode: stream requires a driver supporting XREAD');
1407
1682
 
1408
1683
  if (typeof (sub as any).on === 'function') {
1409
- sub.on('error', (e: Error) =>
1684
+ this._listenBackplane(sub, 'error', (e: Error) =>
1410
1685
  this.logger.debug('Backplane stream consumer error', { error: e.message }));
1411
1686
 
1412
- sub.on('close', () => {
1687
+ this._listenBackplane(sub, 'close', () => {
1688
+ this._streamRecovering = true;
1689
+ this._backplaneAvailable = false;
1413
1690
  if (this._subDisconnectedAt === null) {
1414
1691
  this._subDisconnectedAt = Date.now();
1415
1692
  this.logger.debug('Backplane stream: consumer disconnected', { at: this._subDisconnectedAt });
1416
1693
  }
1417
1694
  });
1418
1695
 
1419
- sub.on('ready', () => {
1696
+ this._listenBackplane(sub, 'ready', () => {
1420
1697
  if (this._subDisconnectedAt !== null) {
1421
1698
  this.logger.debug('Backplane stream: consumer reconnected, resuming stream read', { lastId: this._lastStreamId });
1422
1699
  this._subDisconnectedAt = null;
@@ -1424,31 +1701,71 @@ export class CacheService {
1424
1701
  });
1425
1702
  }
1426
1703
 
1704
+ const checkGap = async () => {
1705
+ if (this._lastStreamId === '$' || this._lastStreamId === '0-0' || typeof sub.xrange !== 'function') return;
1706
+ const first = await sub.xrange(this.backplaneStreamKey, '-', '+', 'COUNT', 1);
1707
+ const firstId = first?.[0]?.[0] as string | undefined;
1708
+ if (!firstId) return;
1709
+ const [firstMs, firstSequence] = firstId.split('-').map(BigInt);
1710
+ const [lastMs, lastSequence] = this._lastStreamId.split('-').map(BigInt);
1711
+ if (firstMs > lastMs || (firstMs === lastMs && firstSequence > lastSequence)) this._resetAfterStreamGap();
1712
+ };
1713
+ const apply = (response: Array<[string, Array<[string, string[]]>]> | null) => {
1714
+ if (this._destroyed || !response) return;
1715
+ if (this._streamRecovering && response.some(([, entries]) => entries.length > 0)) {
1716
+ this.counters.streamReplays++;
1717
+ this._streamRecovering = false;
1718
+ }
1719
+ for (const [, entries] of response) {
1720
+ for (const [id, fields] of entries) {
1721
+ this._lastStreamId = id;
1722
+ this.counters.streamEntriesReceived++;
1723
+ this._processStreamEntry(fields);
1724
+ }
1725
+ }
1726
+ };
1727
+ let initialized = false;
1728
+ const initialize = async () => {
1729
+ if (typeof sub.connect === 'function' && (sub.isOpen === false || sub.status === 'wait')) await sub.connect();
1730
+ if (this._destroyed) return;
1731
+ if (this._lastStreamId === '$') {
1732
+ if (this._restoredSnapshot) this._resetAfterStreamGap(); // Legacy snapshot without a replay cursor.
1733
+ else if (typeof sub.xrevrange === 'function') {
1734
+ const latest = await sub.xrevrange(this.backplaneStreamKey, '+', '-', 'COUNT', 1);
1735
+ this._lastStreamId = latest?.[0]?.[0] ?? '0-0';
1736
+ } else this._lastStreamId = '0-0'; // Never repeatedly use the moving '$' cursor.
1737
+ }
1738
+ if (typeof sub.xrange === 'function') {
1739
+ await checkGap();
1740
+ apply(await sub.xread('STREAMS', this.backplaneStreamKey, this._lastStreamId));
1741
+ }
1742
+ initialized = true;
1743
+ this._backplaneAvailable = true;
1744
+ };
1745
+ try { await initialize(); }
1746
+ catch (error) {
1747
+ this._backplaneAvailable = false;
1748
+ this.logger.warn('Backplane stream initialization failed; retrying in consumer loop', { error: (error as Error).message });
1749
+ }
1750
+
1427
1751
  // Continuous async worker loop
1428
1752
  const runLoop = async () => {
1429
1753
  while (!this._destroyed && !this._redisDisabled) {
1430
1754
  try {
1755
+ if (!initialized) await initialize();
1756
+ if (this._destroyed) break;
1757
+ await checkGap();
1431
1758
  const res = await (sub as any).xread(
1432
1759
  'BLOCK', this.opts.backplaneStreamBlockMs,
1433
1760
  'STREAMS', this.backplaneStreamKey, this._lastStreamId,
1434
1761
  ) as Array<[string, Array<[string, string[]]>]> | null;
1435
1762
 
1436
1763
  if (this._destroyed) break;
1764
+ this._backplaneAvailable = true;
1437
1765
 
1438
1766
  if (res && res.length > 0) {
1439
- for (const [, entries] of res) {
1440
- if (entries.length > 0) {
1441
- if (this._lastStreamId !== '$') {
1442
- this.counters.streamReplays++;
1443
- }
1444
-
1445
- for (const [id, fields] of entries) {
1446
- this._lastStreamId = id;
1447
- this.counters.streamEntriesReceived++;
1448
- this._processStreamEntry(fields);
1449
- }
1450
- }
1451
- }
1767
+ apply(res);
1768
+ this._backplaneAvailable = true;
1452
1769
  } else {
1453
1770
  // Idle timeout without messages — yield briefly before next long-poll
1454
1771
  await new Promise(resolve => setTimeout(resolve, 10));
@@ -1457,10 +1774,9 @@ export class CacheService {
1457
1774
  if (this._destroyed) break;
1458
1775
  const msg = (err as Error).message ?? '';
1459
1776
  if (msg.includes('NOGROUP') || msg.includes('smaller than') || msg.includes('trimmed')) {
1460
- this.counters.streamGaps++;
1461
- this.l1.clear();
1462
- this._lastStreamId = '$';
1777
+ this._resetAfterStreamGap();
1463
1778
  }
1779
+ this._backplaneAvailable = false;
1464
1780
  await new Promise(resolve => setTimeout(resolve, 200));
1465
1781
  }
1466
1782
  }
@@ -1492,8 +1808,14 @@ export class CacheService {
1492
1808
  else if (f === 'tagVersion') tagVersionRaw = v;
1493
1809
  }
1494
1810
 
1495
- const validOp = op === 'del' || op === 'del-glob' || op === 'tag_incr';
1496
- if (!validOp || typeof key !== 'string' || !key || typeof src !== 'string') {
1811
+ const validOp =
1812
+ op === 'del' ||
1813
+ op === 'del-glob' ||
1814
+ op === 'tag_incr' ||
1815
+ op === 'tag_pattern_incr' ||
1816
+ op === 'tag_pattern_del';
1817
+ if (!validOp || typeof key !== 'string' || !key || typeof src !== 'string' || !src ||
1818
+ ((op === 'del' || op === 'del-glob') && this._namespace && !key.startsWith(`${this._namespace}:`))) {
1497
1819
  this.logger.warn('Backplane: rejected invalid stream entry', {
1498
1820
  op: String(op).slice(0, 40),
1499
1821
  key: typeof key === 'string' ? key.slice(0, 100).replace(/[\r\n\t]/g, ' ') : String(key),
@@ -1501,11 +1823,11 @@ export class CacheService {
1501
1823
  return;
1502
1824
  }
1503
1825
 
1504
- // parseInt('12abc34') → NaN — reject instead of poisoning the version map.
1826
+ // Reject partial numeric strings rather than truncating them with parseInt().
1505
1827
  let tagVersion: number | undefined;
1506
1828
  if (tagVersionRaw !== undefined) {
1507
- const parsed = parseInt(tagVersionRaw, 10);
1508
- if (!Number.isFinite(parsed)) {
1829
+ const parsed = Number(tagVersionRaw);
1830
+ if (!Number.isSafeInteger(parsed) || parsed < 0) {
1509
1831
  this.logger.warn('Backplane: rejected stream entry with non-numeric tagVersion', { key });
1510
1832
  return;
1511
1833
  }
@@ -1526,16 +1848,10 @@ export class CacheService {
1526
1848
  this.l1.delete(key);
1527
1849
  this._bumpKeyMutation(key);
1528
1850
  this.inflight.delete(key);
1529
- this._pendingDiskDeletes.add(key);
1530
- setImmediate(() => {
1531
- try {
1532
- if (!this._diskDisabled) this.disk.delete(key);
1533
- } finally {
1534
- this._pendingDiskDeletes.delete(key);
1535
- }
1536
- });
1851
+ this._invalidateDiskKey(key);
1537
1852
  this._cascadeDependencies(key);
1538
1853
  } else if (op === 'del-glob') {
1854
+ this._fenceInvalidation();
1539
1855
  this.l1.deletePattern(key);
1540
1856
  const pfx = key.endsWith('*') ? key.slice(0, -1) : key;
1541
1857
  for (const liveKey of this.l1.liveKeys()) {
@@ -1549,12 +1865,22 @@ export class CacheService {
1549
1865
  this.inflight.delete(inflightKey);
1550
1866
  }
1551
1867
  }
1552
- this._addPatternTombstone(pfx);
1868
+ this._addPatternTombstone(key);
1869
+ this._removePatternFromIndices(key);
1870
+ if (key === this.nk('*')) {
1871
+ this.tagIndex.clear();
1872
+ this.keyTags.clear();
1873
+ this.tagVersions.clear();
1874
+ this.dependencyIndex.clear();
1875
+ this.keyDependencies.clear();
1876
+ }
1553
1877
  } else if (op === 'tag_incr') {
1878
+ this._fenceInvalidation();
1554
1879
  const tag = key;
1555
1880
  const ver = typeof tagVersion === 'number' ? tagVersion : ((this.tagVersions.get(tag)?.version ?? 0) + 1);
1556
1881
  this._setLocalTagVersion(tag, ver, performance.now());
1557
1882
  } else if (op === 'tag_pattern_incr') {
1883
+ this._fenceInvalidation();
1558
1884
  const pattern = key;
1559
1885
  const now = performance.now();
1560
1886
  for (const [tag, info] of this.tagVersions) {
@@ -1574,6 +1900,7 @@ export class CacheService {
1574
1900
  }
1575
1901
  }, 0);
1576
1902
  } else if (op === 'tag_pattern_del') {
1903
+ this._fenceInvalidation();
1577
1904
  const pattern = key;
1578
1905
  const matchedTagKeys: string[] = [];
1579
1906
  const prefix = this.nk('_tag_:');
@@ -1584,14 +1911,7 @@ export class CacheService {
1584
1911
  for (const k of members) {
1585
1912
  this.l1.delete(k);
1586
1913
  this._bumpKeyMutation(k);
1587
- this._pendingDiskDeletes.add(k);
1588
- setImmediate(() => {
1589
- try {
1590
- if (!this._diskDisabled) this.disk.delete(k);
1591
- } finally {
1592
- this._pendingDiskDeletes.delete(k);
1593
- }
1594
- });
1914
+ this._invalidateDiskKey(k);
1595
1915
  }
1596
1916
  }
1597
1917
  }
@@ -1637,6 +1957,7 @@ export class CacheService {
1637
1957
  isCrossRegionRelay = false,
1638
1958
  isExplicitInvalidation = false,
1639
1959
  ): Promise<void> {
1960
+ if (this.opts.l2WriteMode === 'read-only') return;
1640
1961
  if (!isCrossRegionRelay && this.opts.crossRegion) {
1641
1962
  const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
1642
1963
  if (shouldBroadcast) {
@@ -1723,13 +2044,13 @@ export class CacheService {
1723
2044
  timestamp: Date.now(),
1724
2045
  namespace: this._namespace || undefined,
1725
2046
  };
1726
- this.counters.crossRegionSent++;
1727
2047
  await cr.relay.broadcast(event);
2048
+ this.counters.crossRegionSent++;
1728
2049
  this.logger.debug('Cross-region invalidation broadcast', { op, key, region: cr.currentRegion });
1729
2050
  } catch (err) {
1730
- this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
1731
2051
  this.counters.crossRegionErrors++;
1732
2052
  this.logger.warn('Cross-region invalidation broadcast failed', { error: (err as Error).message });
2053
+ if (this.opts.awaitInvalidationBackplane) throw err;
1733
2054
  }
1734
2055
  }
1735
2056
 
@@ -1741,13 +2062,14 @@ export class CacheService {
1741
2062
  * Returns true if the event was accepted and applied, or false if ignored/deduplicated.
1742
2063
  */
1743
2064
  async receiveCrossRegionInvalidation(event: CrossRegionInvalidationEvent): Promise<boolean> {
2065
+ this._assertActive('receiveCrossRegionInvalidation');
1744
2066
  const cr = this.opts.crossRegion;
1745
2067
  if (!cr) return false;
1746
2068
 
1747
2069
  // Reject malformed event
1748
- if (!event || typeof event !== 'object' || !event.id || !event.originRegion || !event.op || !event.key) {
2070
+ if (!isCrossRegionInvalidationEvent(event)) {
1749
2071
  this.counters.crossRegionErrors++;
1750
- this.logger.warn('Cross-region: rejected invalid event payload', { event });
2072
+ this.logger.warn('Cross-region: rejected invalid event payload');
1751
2073
  return false;
1752
2074
  }
1753
2075
 
@@ -1762,21 +2084,56 @@ export class CacheService {
1762
2084
  this.counters.crossRegionDeduplicated++;
1763
2085
  return false;
1764
2086
  }
1765
- this._markCrossRegionEventSeen(event.id);
1766
2087
 
1767
2088
  // If namespaces don't match, ignore
1768
2089
  if (event.namespace !== undefined && event.namespace !== (this._namespace || undefined)) {
1769
2090
  return false;
1770
2091
  }
2092
+ if ((event.op === 'del' || event.op === 'del-glob') && this._namespace && !event.key.startsWith(`${this._namespace}:`)) return false;
2093
+ this._markCrossRegionEventSeen(event.id);
1771
2094
 
1772
2095
  this.counters.crossRegionReceived++;
1773
2096
 
1774
- // 1. Apply to local L1 and disk
1775
- this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
1776
-
1777
- // 2. Propagate to local Redis backplane so other instances in THIS region also invalidate,
1778
- // passing isCrossRegionRelay = true to prevent re-broadcasting cross-region
1779
- void this.publishInvalidation(event.op, event.key, event.tagVersion, true);
2097
+ const localTags = new Set([...this.tagVersions.keys(), ...[...this.tagIndex.keys()].map(key => this.unnk(key).replace(/^_tag_:/, ''))]);
2098
+ let version = event.tagVersion;
2099
+ if (event.op === 'tag_incr') version = Math.max((this.tagVersions.get(event.key)?.version ?? 0) + 1, version ?? 0);
2100
+ this._applyInvalidationEvent(event.op, event.key, version);
2101
+ try {
2102
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2103
+ const client = await this.getRedis();
2104
+ if (event.op === 'del' || event.op === 'del-glob') {
2105
+ await this._deleteRedisKeys(client, event.op === 'del' ? [event.key] : await this._scanKeys(client, event.key));
2106
+ } else if (event.op === 'tag_incr') {
2107
+ version = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.nk(`tag_ver:${event.key}`), String(version)));
2108
+ this._setLocalTagVersion(event.key, version);
2109
+ } else {
2110
+ const matched = await this._resolveMatchingTags(event.key, false);
2111
+ for (const tag of localTags) if (matchesTagPattern(event.key, tag)) matched.add(tag);
2112
+ for (const tag of matched) {
2113
+ if (event.op === 'tag_pattern_incr') {
2114
+ const floor = this.tagVersions.get(tag)?.version ?? 1;
2115
+ const next = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.nk(`tag_ver:${tag}`), String(floor)));
2116
+ this._setLocalTagVersion(tag, next);
2117
+ await this.publishInvalidation('tag_incr', tag, next, true);
2118
+ } else {
2119
+ const tagKey = this.nk(`_tag_:${tag}`);
2120
+ const members = await client.smembers(tagKey) as string[];
2121
+ this._removeTagMembersLocal(members);
2122
+ await this._deleteRedisKeys(client, [...members, tagKey]);
2123
+ await Promise.all(members.map(key => this.publishInvalidation('del', key, undefined, true)));
2124
+ }
2125
+ }
2126
+ }
2127
+ this.cb.onSuccess();
2128
+ }
2129
+ await this.publishInvalidation(event.op, event.key, version, true);
2130
+ } catch (error) {
2131
+ this._seenCrossRegionEvents.delete(event.id);
2132
+ this.counters.crossRegionErrors++;
2133
+ this.logger.warn('Cross-region regional invalidation failed', { error: (error as Error).message });
2134
+ if (this.opts.awaitInvalidationBackplane) throw error;
2135
+ return false;
2136
+ }
1780
2137
 
1781
2138
  this.logger.info('Cross-region invalidation applied', {
1782
2139
  op: event.op,
@@ -1793,27 +2150,279 @@ export class CacheService {
1793
2150
  const oldestKey = this.tagVersions.keys().next().value;
1794
2151
  if (oldestKey !== undefined) this.tagVersions.delete(oldestKey);
1795
2152
  }
1796
- this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
2153
+ this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now, refreshEpoch: this._tagRefreshEpoch });
2154
+ }
2155
+
2156
+ private async _isGenerationalEntryStale(tagVersions?: Record<string, number>): Promise<boolean> {
2157
+ if (!tagVersions) return false;
2158
+ const tags = Object.keys(tagVersions);
2159
+ if (tags.length === 0) return false;
2160
+ const currentVers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
2161
+ for (let i = 0; i < tags.length; i++) {
2162
+ if (currentVers[i] > tagVersions[tags[i]]) return true;
2163
+ }
2164
+ return false;
2165
+ }
2166
+
2167
+ private async _deleteRedisKeys(client: AnyRedisClient, keys: string[]): Promise<void> {
2168
+ if (keys.length === 0) return;
2169
+ const CHUNK_SIZE = 1_000;
2170
+ if (client instanceof RedisCluster) {
2171
+ const groups = new Map<string, string[]>();
2172
+ for (const key of keys) {
2173
+ const slot = redisHashSlot(key);
2174
+ const master = client.slots?.[slot]?.[0] ?? String(slot);
2175
+ const members = groups.get(master) ?? [];
2176
+ members.push(key);
2177
+ groups.set(master, members);
2178
+ }
2179
+ await Promise.all([...groups.values()].map(async members => {
2180
+ for (let offset = 0; offset < members.length; offset += CHUNK_SIZE) {
2181
+ const pipeline = client.pipeline();
2182
+ for (const key of members.slice(offset, offset + CHUNK_SIZE)) pipeline.del(key);
2183
+ const result = await pipeline.exec();
2184
+ if (!result || result.some(([error]) => error)) throw new Error('Redis Cluster delete failed');
2185
+ }
2186
+ }));
2187
+ return;
2188
+ }
2189
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
2190
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
2191
+ await client.del(...chunk);
2192
+ }
2193
+ }
2194
+
2195
+ private async _parseGenerationalRedisHash<T>(
2196
+ k: string,
2197
+ hashData: Record<string, string>,
2198
+ ): Promise<RedisCacheEntry<T> | null> {
2199
+ if (!hashData || !hashData.d) return null;
2200
+ let storedTagVersions: Record<string, number> = {};
2201
+ if (hashData.tv) {
2202
+ try {
2203
+ const parsed = JSON.parse(hashData.tv);
2204
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) ||
2205
+ Object.values(parsed).some(version => !Number.isSafeInteger(version) || Number(version) < 0)) return null;
2206
+ storedTagVersions = parsed;
2207
+ } catch { return null; }
2208
+ }
2209
+ if (await this._isGenerationalEntryStale(storedTagVersions)) {
2210
+ const setAtMs = parseInt(hashData.t, 10) || 0;
2211
+ this._deleteIfStale(k, setAtMs);
2212
+ return { stale: true };
2213
+ }
2214
+ const value = await this._decryptAndDeserialize<T>(hashData.d);
2215
+ const expiresAt = Number(hashData.e);
2216
+ const staleAt = Number(hashData.s);
2217
+ let tags: string[] | undefined;
2218
+ let dependsOn: string[] | undefined;
2219
+ try {
2220
+ const parsedTags = hashData.tags ? JSON.parse(hashData.tags) : Object.keys(storedTagVersions);
2221
+ const parsedDependencies = hashData.deps ? JSON.parse(hashData.deps) : undefined;
2222
+ if (Array.isArray(parsedTags) && parsedTags.every(tag => typeof tag === 'string')) tags = parsedTags;
2223
+ if (Array.isArray(parsedDependencies) && parsedDependencies.every(pattern => typeof pattern === 'string')) dependsOn = parsedDependencies;
2224
+ } catch { return null; }
2225
+ return { value, tagVersions: storedTagVersions, stale: false, tags, dependsOn, setAt: Number(hashData.t) || undefined,
2226
+ expiresAt: Number.isFinite(expiresAt) && expiresAt > 0 ? expiresAt : undefined,
2227
+ staleAt: Number.isFinite(staleAt) && staleAt > 0 ? staleAt : undefined };
2228
+ }
2229
+
2230
+ private async _readRedisEntry<T>(
2231
+ client: AnyRedisClient,
2232
+ k: string,
2233
+ allowAutoPipeline = false,
2234
+ ): Promise<RedisCacheEntry<T> | null> {
2235
+ const readStartedAt = Date.now();
2236
+ const read = async (hash: boolean) => allowAutoPipeline && this.opts.autoPipeline && this.pipeliner
2237
+ ? this.pipeliner.read(k, hash)
2238
+ : readRedisValue(client, k, hash);
2239
+ const withExpiry = (entry: RedisCacheEntry<T> | null, ttlMs?: number): RedisCacheEntry<T> | null => {
2240
+ if (!entry || ttlMs === -2 || ttlMs === 0) return null;
2241
+ if (ttlMs !== undefined && Number.isFinite(ttlMs) && ttlMs > 0) {
2242
+ entry.expiresAt = Math.min(entry.expiresAt ?? Infinity, readStartedAt + ttlMs);
2243
+ }
2244
+ return entry.expiresAt !== undefined && entry.expiresAt <= Date.now() ? null : entry;
2245
+ };
2246
+ if (this.opts.tagStrategy === 'generational' && typeof (client as any).hgetall === 'function') {
2247
+ try {
2248
+ const { raw: hashData, ttlMs } = await read(true);
2249
+ if (typeof hashData === 'string') {
2250
+ const value = await this._decryptAndDeserialize<T>(hashData);
2251
+ return withExpiry({ value, stale: false }, ttlMs);
2252
+ }
2253
+ if (hashData && hashData.d) {
2254
+ return withExpiry(await this._parseGenerationalRedisHash<T>(k, hashData), ttlMs);
2255
+ }
2256
+ return null;
2257
+ } catch (err) {
2258
+ const msg = err instanceof Error ? err.message : String(err);
2259
+ if (!msg.includes('WRONGTYPE')) throw err;
2260
+ // Fall through to GET if key was stored as a plain string without tags
2261
+ }
2262
+ }
2263
+
2264
+ const { raw, ttlMs } = await read(false);
2265
+ if (raw == null) return null;
2266
+ if (typeof raw !== 'string') return null;
2267
+ const value = await this._decryptAndDeserialize<T>(raw);
2268
+ return withExpiry({ value, stale: false }, ttlMs);
1797
2269
  }
1798
2270
 
1799
2271
  private async _getTagVersion(tag: string): Promise<number> {
1800
2272
  const now = performance.now();
1801
2273
  const local = this.tagVersions.get(tag);
1802
- if (local && (now - local.lastSyncedAt < this.opts.tagVersionTtlMs)) {
2274
+ if (local && (local.refreshEpoch ?? 0) === this._tagRefreshEpoch && (now - local.lastSyncedAt < this.opts.tagVersionTtlMs)) {
1803
2275
  return local.version;
1804
2276
  }
1805
2277
  if (!this._redisDisabled) {
1806
2278
  try {
1807
2279
  const client = await this.getRedis();
1808
2280
  const raw = await client.get(this.nk(`tag_ver:${tag}`));
1809
- const version = raw ? parseInt(raw, 10) : 0;
2281
+ const parsed = raw ? Number(raw) : 0;
2282
+ if (!Number.isSafeInteger(parsed) || parsed < 0) throw new Error('Invalid Redis tag generation');
2283
+ const version = Math.max(this.tagVersions.get(tag)?.version ?? 0, parsed);
2284
+ if (this.opts.l2WriteMode === 'read-write') {
2285
+ if (raw === null) await client.set(this.nk(`tag_ver:${tag}`), String(version), 'NX');
2286
+ else if (version > parsed) await client.eval(LUA_MAX_TAG_VERSION, 1, this.nk(`tag_ver:${tag}`), String(version));
2287
+ }
1810
2288
  this._setLocalTagVersion(tag, version, now);
2289
+ this.cb.onSuccess();
1811
2290
  return version;
1812
2291
  } catch {
1813
2292
  /* fallback to local */
1814
2293
  }
1815
2294
  }
1816
- return local?.version ?? 0;
2295
+ const version = this.tagVersions.get(tag)?.version ?? local?.version ?? 0;
2296
+ if (this._redisDisabled) this._setLocalTagVersion(tag, version, now);
2297
+ return version;
2298
+ }
2299
+
2300
+ private async _readRedisBatch<T>(client: AnyRedisClient, keys: string[]): Promise<Map<string, RedisCacheEntry<T>>> {
2301
+ const entries = new Map<string, RedisCacheEntry<T>>();
2302
+ const groups = new Map<string, string[]>();
2303
+ for (const key of new Set(keys)) {
2304
+ const group = client instanceof RedisCluster ? client.slots[redisHashSlot(key)]?.[0] ?? String(redisHashSlot(key)) : 'single';
2305
+ const members = groups.get(group) ?? [];
2306
+ members.push(key);
2307
+ groups.set(group, members);
2308
+ }
2309
+ await Promise.all([...groups.values()].map(async members => {
2310
+ for (let offset = 0; offset < members.length; offset += 1000) {
2311
+ const chunk = members.slice(offset, offset + 1000);
2312
+ const pipeline = typeof client.pipeline === 'function' ? client.pipeline() : client.multi();
2313
+ const timedScripts = typeof pipeline.eval === 'function';
2314
+ const hashes = this.opts.tagStrategy === 'generational' && typeof pipeline.hgetall === 'function';
2315
+ for (const key of chunk) {
2316
+ if (timedScripts) pipeline.eval(LUA_READ_CACHE_ENTRY, 1, key);
2317
+ else if (hashes) pipeline.hgetall(key);
2318
+ else pipeline.get(key);
2319
+ }
2320
+ const startedAt = Date.now();
2321
+ const start = performance.now();
2322
+ const results = await pipeline.exec() as Array<[Error | null, unknown]> | null;
2323
+ this.watchdog.recordRedis(performance.now() - start);
2324
+ if (!results) throw new Error('Redis batch read aborted');
2325
+ for (let index = 0; index < chunk.length; index++) {
2326
+ try {
2327
+ const tuple = results[index];
2328
+ if (!tuple) continue;
2329
+ let [error, raw] = tuple;
2330
+ let ttl: number | undefined;
2331
+ if (error?.message?.includes('WRONGTYPE')) {
2332
+ const fallback = await this._readRedisEntry<T>(client, chunk[index]);
2333
+ if (fallback && !fallback.stale) entries.set(chunk[index], fallback);
2334
+ continue;
2335
+ }
2336
+ if (error) continue;
2337
+ if (timedScripts) {
2338
+ if (!Array.isArray(raw) || raw[0] === 'none') continue;
2339
+ const kind = raw[0];
2340
+ ttl = Number(raw[2]);
2341
+ const payload = raw[1];
2342
+ if (kind === 'hash') {
2343
+ if (!Array.isArray(payload) || payload.length % 2 !== 0) continue;
2344
+ raw = Object.fromEntries(Array.from({ length: payload.length / 2 }, (_unused, i) => [String(payload[i * 2]), String(payload[i * 2 + 1])]));
2345
+ } else if (kind === 'string') raw = payload;
2346
+ else continue;
2347
+ if (ttl === -2 || ttl === 0) continue;
2348
+ }
2349
+ const entry = typeof raw === 'string'
2350
+ ? { value: await this._decryptAndDeserialize<T>(raw), stale: false } as RedisCacheEntry<T>
2351
+ : raw && typeof raw === 'object' && 'd' in raw
2352
+ ? await this._parseGenerationalRedisHash<T>(chunk[index], raw as Record<string, string>) : null;
2353
+ if (!entry || entry.stale) continue;
2354
+ if (ttl !== undefined && ttl > 0) entry.expiresAt = Math.min(entry.expiresAt ?? Infinity, startedAt + ttl);
2355
+ if (entry.expiresAt !== undefined && entry.expiresAt <= Date.now()) continue;
2356
+ entries.set(chunk[index], entry);
2357
+ } catch (error) {
2358
+ this.logger.debug('mget: skipping invalid remote entry', { key: chunk[index], error: (error as Error).message });
2359
+ }
2360
+ }
2361
+ }
2362
+ }));
2363
+ this.cb.onSuccess();
2364
+ return entries;
2365
+ }
2366
+
2367
+ private _promoteRedisEntry<T>(key: string, entry: RedisCacheEntry<T>, fallbackTtlMs: number, priority: CachePriority): boolean {
2368
+ const expiresAt = entry.expiresAt ?? Date.now() + fallbackTtlMs;
2369
+ if (expiresAt <= Date.now()) return false;
2370
+ const admitted = this.l1.set(key, entry.value, expiresAt - Date.now(), priority, entry.staleAt, undefined,
2371
+ entry.tagVersions, entry.setAt, entry.tags, entry.dependsOn);
2372
+ if (admitted) this._restoreEntryMetadata(key, { ...entry, expiresAt });
2373
+ return true;
2374
+ }
2375
+
2376
+ private async _readDiskEntry<T>(key: string, epoch: string): Promise<{ value: T; entry: DiskCacheEntry } | null> {
2377
+ if (this._diskDisabled || this._pendingDiskDeletes.has(key) || !this.watchdog.isDiskAllowed()) return null;
2378
+ const start = performance.now();
2379
+ const entry = this.disk.load(key);
2380
+ const elapsed = performance.now() - start;
2381
+ this.watchdog.recordDisk(elapsed);
2382
+ this.watchdog.onCanaryResult(entry !== null, elapsed);
2383
+ if (!entry || this._isTombstonedByPattern(key, entry.setAt ?? 0) || await this._isGenerationalEntryStale(entry.tagVersions) ||
2384
+ this._destroyed || this._getKeyMutationEpoch(key) !== epoch || entry.expiresAt <= Date.now()) return null;
2385
+ this.l1.importEntries([{ key, entry: entry as SmartCacheEntry }], this.opts.forbiddenSnapshotPrefixes);
2386
+ const hit = this.l1.get(key);
2387
+ const value = hit ? hit.value as T : entry.isCompressed
2388
+ ? this.codec.decode<T>(entry.data as Buffer) : JSON.parse(entry.data as string) as T;
2389
+ this._restoreEntryMetadata(key, entry);
2390
+ return { value, entry };
2391
+ }
2392
+
2393
+ /** Common write policy and metadata across get/set/revalidation/draining. */
2394
+ private async _writeRedisEntry(
2395
+ key: string, data: unknown, expiresAt: number, setAt: number, tagVersions?: Record<string, number>,
2396
+ staleAt?: number, tags?: string[], dependsOn?: string[], canCommit: () => boolean = () => true,
2397
+ ): Promise<void> {
2398
+ if (this._redisDisabled || this.opts.l2WriteMode !== 'read-write' || !canCommit() || this._destroyed) return;
2399
+ const client = await this.getRedis();
2400
+ const stored = await this._serializeAndEncrypt(JSON.stringify(data) ?? 'undefined');
2401
+ if (!canCommit() || this._destroyed) return;
2402
+ const useHash = this.opts.tagStrategy === 'generational' && (tagVersions || (!this.opts.autoPipeline && typeof client.hgetall === 'function'));
2403
+ // Plain legacy Redis strings cannot carry SWR metadata: expire them at soft TTL.
2404
+ const remaining = (useHash ? expiresAt : staleAt ?? expiresAt) - Date.now();
2405
+ if (remaining <= 0) return;
2406
+ const ttl = Math.max(1, Math.ceil(remaining / 1000));
2407
+ if (useHash) {
2408
+ const transaction = client.multi();
2409
+ transaction.del(key); // Safely migrate legacy string values into a hash.
2410
+ const hash: Record<string, string> = { d: stored, t: String(setAt), tv: JSON.stringify(tagVersions ?? {}), e: String(expiresAt) };
2411
+ if (staleAt !== undefined) hash.s = String(staleAt);
2412
+ if (tags?.length) hash.tags = JSON.stringify(tags);
2413
+ if (dependsOn?.length) hash.deps = JSON.stringify(dependsOn);
2414
+ transaction.hset(key, hash);
2415
+ transaction.expire(key, ttl);
2416
+ const result = await transaction.exec();
2417
+ if (!result || result.some(([error]: [Error | null, unknown]) => error)) throw new Error('Redis cache write transaction failed');
2418
+ } else if (this.opts.autoPipeline && this.pipeliner) {
2419
+ if (typeof client.pttl === 'function' && typeof client.set === 'function') await this.pipeliner.setpx(key, Math.ceil(remaining), stored);
2420
+ else await this.pipeliner.setex(key, ttl, stored);
2421
+ } else {
2422
+ if (typeof client.pttl === 'function' && typeof client.set === 'function') await client.set(key, stored, 'PX', Math.ceil(remaining));
2423
+ else await client.setex(key, ttl, stored);
2424
+ }
2425
+ this.cb.onSuccess();
1817
2426
  }
1818
2427
 
1819
2428
  private _deleteIfStale(k: string, setAtMs: number): void {
@@ -1868,7 +2477,7 @@ export class CacheService {
1868
2477
  } else {
1869
2478
  plain = raw;
1870
2479
  }
1871
- return JSON.parse(plain) as T;
2480
+ return plain === 'undefined' ? undefined as T : JSON.parse(plain) as T;
1872
2481
  }
1873
2482
 
1874
2483
  /**
@@ -1948,10 +2557,9 @@ export class CacheService {
1948
2557
  }
1949
2558
 
1950
2559
  this.redisConnecting = (async () => {
2560
+ let client: AnyRedisClient | null = null;
1951
2561
  try {
1952
2562
  // ── Fix 4: Cluster / Sentinel / single-node connection factory ──────
1953
- let client: AnyRedisClient;
1954
-
1955
2563
  if (this.opts.redisClusterNodes?.length) {
1956
2564
  // Redis Cluster — ioredis handles slot routing and multi-node pooling.
1957
2565
  client = new RedisCluster(this.opts.redisClusterNodes, {
@@ -2018,15 +2626,45 @@ export class CacheService {
2018
2626
  client.on('reconnecting', () => this.logger.debug('Redis reconnecting'));
2019
2627
  }
2020
2628
 
2629
+ const pendingClient = client;
2021
2630
  await new Promise<void>((resolve, reject) => {
2022
- client.once('ready', resolve);
2023
- client.once('error', (e: Error) => {
2631
+ let settled = false;
2632
+ const cleanupListeners = () => {
2633
+ pendingClient.removeListener?.('ready', onReady);
2634
+ pendingClient.removeListener?.('error', onError);
2635
+ };
2636
+ const onReady = () => {
2637
+ if (settled) return;
2638
+ settled = true;
2639
+ clearTimeout(timer);
2640
+ cleanupListeners();
2641
+ resolve();
2642
+ };
2643
+ const onError = (e: Error) => {
2644
+ if (settled) return;
2645
+ settled = true;
2646
+ clearTimeout(timer);
2647
+ cleanupListeners();
2024
2648
  this._checkAndLogResp3Hint(e);
2025
2649
  reject(e);
2026
- });
2027
- setTimeout(() => reject(new Error('Redis connection timeout')), 15_000);
2650
+ };
2651
+ const timer = setTimeout(() => {
2652
+ if (settled) return;
2653
+ settled = true;
2654
+ cleanupListeners();
2655
+ reject(new Error('Redis connection timeout'));
2656
+ }, 15_000);
2657
+ if (timer.unref) timer.unref();
2658
+
2659
+ pendingClient.once('ready', onReady);
2660
+ pendingClient.once('error', onError);
2028
2661
  });
2029
2662
 
2663
+ if (this._destroyed) {
2664
+ try { client.disconnect(); } catch { /* ok */ }
2665
+ this._assertActive('getRedis');
2666
+ }
2667
+
2030
2668
  this.cb.onSuccess();
2031
2669
  this.redis = client;
2032
2670
  this.pipeliner = new AutoPipeliner(client, {
@@ -2036,6 +2674,7 @@ export class CacheService {
2036
2674
  this.redisConnecting = null;
2037
2675
  return client;
2038
2676
  } catch (err) {
2677
+ try { client?.disconnect(); } catch { /* ok */ }
2039
2678
  this.cb.onFailure();
2040
2679
  this.redisConnecting = null; // allow retry on next call — fixes the cached-rejection bug
2041
2680
  this._checkAndLogResp3Hint(err as Error);
@@ -2059,7 +2698,8 @@ export class CacheService {
2059
2698
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
2060
2699
  if (entries.length === 0) return;
2061
2700
 
2062
- const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
2701
+ const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries,
2702
+ streamId: this.opts.backplaneMode === 'stream' && this._lastStreamId !== '$' ? this._lastStreamId : undefined };
2063
2703
  const packed = this.codec.encode(payload);
2064
2704
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
2065
2705
  const dest = altPath ?? this.opts.snapshotPath;
@@ -2104,6 +2744,7 @@ export class CacheService {
2104
2744
  const snapshot = this.codec.decode(buf) as {
2105
2745
  version?: number; writtenAt?: number;
2106
2746
  entries?: Array<{ key: string; entry: SmartCacheEntry }>;
2747
+ streamId?: string;
2107
2748
  };
2108
2749
 
2109
2750
  if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
@@ -2133,6 +2774,9 @@ export class CacheService {
2133
2774
  }
2134
2775
 
2135
2776
  const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
2777
+ this._restoredSnapshot ||= loaded > 0;
2778
+ if (typeof snapshot.streamId === 'string' && /^\d{1,20}-\d{1,20}$/.test(snapshot.streamId)) this._lastStreamId = snapshot.streamId;
2779
+ for (const { key, entry } of snapshot.entries) if (this.l1.has(key)) this._restoreEntryMetadata(key, entry);
2136
2780
  this.logger.info('Cache snapshot loaded (L1 is warm)', {
2137
2781
  loaded, total: snapshot.entries.length,
2138
2782
  sizeKB: this.l1.getStats().sizeKB,
@@ -2156,7 +2800,8 @@ export class CacheService {
2156
2800
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
2157
2801
  if (entries.length === 0) return false;
2158
2802
 
2159
- const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries };
2803
+ const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries,
2804
+ streamId: this.opts.backplaneMode === 'stream' && this._lastStreamId !== '$' ? this._lastStreamId : undefined };
2160
2805
  const packed = this.codec.encode(payload);
2161
2806
  let final: Buffer;
2162
2807
  if (this.opts.remoteSnapshot.envelope) {
@@ -2189,14 +2834,17 @@ export class CacheService {
2189
2834
  async loadRemoteSnapshot(): Promise<number> {
2190
2835
  if (!this.opts.remoteSnapshot) return 0;
2191
2836
  const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
2837
+ const epoch = this._globalEpoch;
2192
2838
  try {
2193
2839
  const raw = await this.opts.remoteSnapshot.adapter.get();
2840
+ if (this._destroyed || this._globalEpoch !== epoch) return 0;
2194
2841
  if (!raw || raw.length === 0) {
2195
2842
  this.logger.debug('Remote snapshot not found or empty — starting cold');
2196
2843
  return 0;
2197
2844
  }
2198
2845
 
2199
2846
  const rawBuf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
2847
+ if (rawBuf.length > SNAPSHOT_MAX_FILE_BYTES) throw new Error('Remote snapshot exceeds size limit');
2200
2848
  let buf: Buffer;
2201
2849
  try {
2202
2850
  if (EnvelopeEncryption.isEnvelope(rawBuf)) {
@@ -2217,6 +2865,7 @@ export class CacheService {
2217
2865
  version?: number;
2218
2866
  writtenAt?: number;
2219
2867
  entries?: Array<{ key: string; entry: SmartCacheEntry }>;
2868
+ streamId?: string;
2220
2869
  };
2221
2870
 
2222
2871
  if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
@@ -2249,7 +2898,12 @@ export class CacheService {
2249
2898
  return 0;
2250
2899
  }
2251
2900
 
2252
- const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
2901
+ if (this._destroyed || this._globalEpoch !== epoch) return 0;
2902
+ const eligible = snapshot.entries.filter(item => item && !this._keyMutationEpochs.has(item.key));
2903
+ const loaded = this.l1.importEntries(eligible, this.opts.forbiddenSnapshotPrefixes);
2904
+ this._restoredSnapshot ||= loaded > 0;
2905
+ if (typeof snapshot.streamId === 'string' && /^\d{1,20}-\d{1,20}$/.test(snapshot.streamId)) this._lastStreamId = snapshot.streamId;
2906
+ for (const { key, entry } of eligible) if (this.l1.has(key)) this._restoreEntryMetadata(key, entry);
2253
2907
  this.counters.remoteSnapshotDownloads++;
2254
2908
  this.counters.remoteSnapshotLastDownloadedAt = Date.now();
2255
2909
  this.logger.info('Remote cache snapshot loaded (L1 hydrated)', {
@@ -2303,6 +2957,8 @@ export class CacheService {
2303
2957
  * On an L1/L2 hit the tags are already registered — this field is a no-op for hits.
2304
2958
  */
2305
2959
  tags?: string[];
2960
+ /** Dependency patterns registered when a miss populates the entry. */
2961
+ dependsOn?: string[];
2306
2962
  } = {},
2307
2963
  ): Promise<T> {
2308
2964
  this._assertActive('get');
@@ -2328,21 +2984,11 @@ export class CacheService {
2328
2984
  // L1: in-memory (fastest path)
2329
2985
  const l1Hit = this.l1.get(k);
2330
2986
  if (l1Hit !== null) {
2331
- let isGenerationalStale = false;
2332
- if (this.opts.tagStrategy === 'generational' && l1Hit.tagVersions) {
2333
- const tags = Object.keys(l1Hit.tagVersions);
2334
- const currentVers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
2335
- for (let i = 0; i < tags.length; i++) {
2336
- if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
2337
- isGenerationalStale = true;
2338
- break;
2339
- }
2340
- }
2341
- }
2987
+ const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
2342
2988
 
2343
2989
  if (isGenerationalStale) {
2344
2990
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
2345
- } else {
2991
+ } else if (!l1Hit.isStale || optSwr > 0) {
2346
2992
  if (l1Hit.isStale) {
2347
2993
  const swrGraceMs = optSwr * 1_000;
2348
2994
  if (swrGraceMs > 0 && !this.revalidating.has(k)) {
@@ -2424,129 +3070,60 @@ export class CacheService {
2424
3070
  span.setAttribute('cache.hit', true)
2425
3071
  .setAttribute('cache.stampede_coalesced', true)
2426
3072
  .end();
2427
- return existing as Promise<T>;
3073
+ return this._prepareReadValue(await existing as T);
2428
3074
  }
2429
3075
 
2430
3076
  const mutationEpochAtStart = this._getKeyMutationEpoch(k);
2431
- const executionPromise: Promise<T> = (async () => {
3077
+ const executionPromise: Promise<T> = Promise.resolve().then(async () => {
2432
3078
  try {
2433
3079
  // ── Tier 1.5: disk tier (evicted L1 entries) — protected by latency watchdog ──
2434
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
2435
- if (this._isTombstonedByPattern(k)) {
2436
- try { this.disk.delete(k); } catch { /* ok */ }
2437
- } else {
2438
- const isDiskAllowed = this.watchdog.isDiskAllowed();
2439
- if (isDiskAllowed) {
2440
- const diskStart = performance.now();
2441
- const diskHit = this.disk.load(k);
2442
- const diskElapsed = performance.now() - diskStart;
2443
- this.watchdog.recordDisk(diskElapsed);
2444
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
2445
-
2446
- if (diskHit !== null) {
2447
- let isDiskStale = false;
2448
- if (this.opts.tagStrategy === 'generational' && diskHit.tagVersions) {
2449
- const tags = Object.keys(diskHit.tagVersions);
2450
- const currentVers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
2451
- for (let i = 0; i < tags.length; i++) {
2452
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
2453
- isDiskStale = true;
2454
- break;
2455
- }
2456
- }
2457
- }
2458
-
2459
- if (isDiskStale) {
2460
- this.disk.delete(k);
2461
- } else {
2462
- const promoted = this.l1.importEntries(
2463
- [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
2464
- this.opts.forbiddenSnapshotPrefixes,
2465
- );
2466
- if (promoted > 0) {
2467
- const l1Check = this.l1.get(k);
2468
- if (l1Check !== null) {
2469
- this.counters.diskHits++;
2470
- this.opts.onHit?.(cacheKey, 'disk');
2471
- this.logger.debug('L1.5 hit (disk → L1)', { cacheKey });
2472
- span.setAttribute('cache.hit', true)
2473
- .setAttribute('cache.item.tier', 'disk')
2474
- .setAttribute('cache.hit_tier', 'disk');
2475
- if (this.opts.frozen) deepFreeze(l1Check.value);
2476
- return (this.opts.cloneStrategy === 'structuredClone' && l1Check.value != null && typeof l1Check.value === 'object')
2477
- ? structuredClone(l1Check.value) as T
2478
- : l1Check.value as T;
2479
- }
2480
- }
2481
- }
2482
- }
3080
+ const diskHit = await this._readDiskEntry<T>(k, mutationEpochAtStart);
3081
+ if (diskHit && (diskHit.entry.staleAt === undefined || diskHit.entry.staleAt > Date.now() || optSwr > 0)) {
3082
+ this.counters.diskHits++;
3083
+ this.opts.onHit?.(cacheKey, 'disk');
3084
+ span.setAttribute('cache.hit', true).setAttribute('cache.item.tier', 'disk').setAttribute('cache.hit_tier', 'disk');
3085
+ if (diskHit.entry.staleAt !== undefined && diskHit.entry.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
3086
+ this.revalidating.add(k);
3087
+ this.counters.swrRevalidations++;
3088
+ void this._revalidate(k, fetchFn, ttlMs, swrGraceMs, priority,
3089
+ diskHit.entry.tagVersions ?? Object.fromEntries((diskHit.entry.tags ?? []).map(tag => [tag, 0])));
2483
3090
  }
3091
+ return diskHit.value;
2484
3092
  }
2485
- }
2486
3093
 
2487
3094
  // ── Tier 2: Redis (distributed, production-only by default) ──
2488
3095
  if (!this._redisDisabled) {
2489
3096
  try {
2490
3097
  const client = await this.getRedis();
2491
3098
  const redisStart = performance.now();
2492
- if (this.opts.tagStrategy === 'generational') {
2493
- const hashData = await client.hgetall(k);
2494
- const redisElapsed = performance.now() - redisStart;
2495
- this.watchdog.recordRedis(redisElapsed);
2496
- this.cb.onSuccess();
2497
- if (hashData && hashData.d) {
2498
- let isStale = false;
2499
- let storedTagVersions: Record<string, number> = {};
2500
- if (hashData.tv) {
2501
- try { storedTagVersions = JSON.parse(hashData.tv); } catch { /* ignore */ }
2502
- }
2503
- const tags = Object.keys(storedTagVersions);
2504
- const currentVers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
2505
- for (let i = 0; i < tags.length; i++) {
2506
- if (currentVers[i] > storedTagVersions[tags[i]]) {
2507
- isStale = true;
2508
- break;
2509
- }
2510
- }
2511
- if (isStale) {
2512
- const setAtMs = parseInt(hashData.t, 10) || 0;
2513
- this._deleteIfStale(k, setAtMs);
2514
- } else {
2515
- const parsed = await this._decryptAndDeserialize<T>(hashData.d);
2516
- this.l1.set(k, parsed, ttlMs, priority, undefined, undefined, storedTagVersions);
2517
- this.counters.l2Hits++;
2518
- this.opts.onHit?.(cacheKey, 'l2');
2519
- this.logger.debug('L2 hit (Redis hash)', { cacheKey });
2520
- span.setAttribute('cache.hit', true)
2521
- .setAttribute('cache.item.tier', 'remote')
2522
- .setAttribute('cache.hit_tier', 'l2');
2523
- if (this.opts.frozen) deepFreeze(parsed);
2524
- return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
2525
- ? structuredClone(parsed)
2526
- : parsed;
2527
- }
2528
- }
2529
- } else {
2530
- const raw = (this.opts.autoPipeline && this.pipeliner)
2531
- ? await this.pipeliner.get(k)
2532
- : await client.get(k);
2533
- const redisElapsed = performance.now() - redisStart;
2534
- this.watchdog.recordRedis(redisElapsed);
2535
- this.cb.onSuccess();
2536
- if (raw) {
2537
- const parsed = await this._decryptAndDeserialize<T>(raw);
2538
- this.l1.set(k, parsed, ttlMs, priority);
2539
- this.counters.l2Hits++;
2540
- this.opts.onHit?.(cacheKey, 'l2');
2541
- this.logger.debug('L2 hit (Redis)', { cacheKey });
2542
- span.setAttribute('cache.hit', true)
2543
- .setAttribute('cache.item.tier', 'remote')
2544
- .setAttribute('cache.hit_tier', 'l2');
2545
- if (this.opts.frozen) deepFreeze(parsed);
2546
- return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
2547
- ? structuredClone(parsed)
3099
+ const redisHit = await this._readRedisEntry<T>(client, k, true);
3100
+ const redisElapsed = performance.now() - redisStart;
3101
+ this.watchdog.recordRedis(redisElapsed);
3102
+ this.cb.onSuccess();
3103
+ if (redisHit && !redisHit.stale && (redisHit.staleAt === undefined || redisHit.staleAt > Date.now() || optSwr > 0)) {
3104
+ const parsed = redisHit.value;
3105
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
3106
+ this.logger.debug('Aborting L2 promotion — key was mutated or deleted during Redis read', { cacheKey });
3107
+ span.setAttribute('cache.aborted_mutation_race', true);
3108
+ const current = this.l1.get(k);
3109
+ const liveVal = (current && !current.isStale)
3110
+ ? current.value as T
2548
3111
  : parsed;
3112
+ return liveVal as T;
3113
+ }
3114
+ if (!this._promoteRedisEntry(k, redisHit, ttlMs, priority)) throw new Error('Redis entry expired during promotion');
3115
+ this.counters.l2Hits++;
3116
+ this.opts.onHit?.(cacheKey, 'l2');
3117
+ this.logger.debug(redisHit.tagVersions ? 'L2 hit (Redis hash)' : 'L2 hit (Redis)', { cacheKey });
3118
+ span.setAttribute('cache.hit', true)
3119
+ .setAttribute('cache.item.tier', 'remote')
3120
+ .setAttribute('cache.hit_tier', 'l2');
3121
+ if (redisHit.staleAt !== undefined && redisHit.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
3122
+ this.revalidating.add(k);
3123
+ this.counters.swrRevalidations++;
3124
+ void this._revalidate(k, fetchFn, ttlMs, swrGraceMs, priority, redisHit.tagVersions);
2549
3125
  }
3126
+ return parsed as T;
2550
3127
  }
2551
3128
  } catch (err) {
2552
3129
  this.cb.onFailure();
@@ -2559,6 +3136,11 @@ export class CacheService {
2559
3136
  this.opts.onMiss?.(cacheKey);
2560
3137
 
2561
3138
  this.counters.fetches++;
3139
+ // Capture generations before origin work, never stamp an old result with
3140
+ // versions discovered only after the fetch has completed.
3141
+ const tagSnapshot = this.opts.tagStrategy === 'generational' && optTags?.length
3142
+ ? Object.fromEntries(await Promise.all(optTags.map(async tag => [tag, await this._getTagVersion(tag)])))
3143
+ : undefined;
2562
3144
  const fetchStart = Date.now();
2563
3145
  let data: T;
2564
3146
  try {
@@ -2592,16 +3174,12 @@ export class CacheService {
2592
3174
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : undefined;
2593
3175
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
2594
3176
 
2595
- let activeTagVersions: Record<string, number> | undefined;
3177
+ const activeTagVersions = tagSnapshot;
2596
3178
  if (optTags?.length) {
2597
3179
  if (this.opts.tagStrategy === 'generational') {
2598
- const vers = await Promise.all(optTags.map(tag => this._getTagVersion(tag)));
2599
- activeTagVersions = {};
2600
- for (let i = 0; i < optTags.length; i++) {
2601
- activeTagVersions[optTags[i]] = vers[i];
2602
- }
3180
+ if (await this._isGenerationalEntryStale(tagSnapshot)) return data;
2603
3181
  } else {
2604
- await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1_000));
3182
+ await this._registerTags(k, optTags, Math.ceil(storeTtl / 1_000));
2605
3183
  }
2606
3184
  }
2607
3185
 
@@ -2609,40 +3187,22 @@ export class CacheService {
2609
3187
  this.logger.debug('Aborting in-flight cache commit — key was mutated or deleted during fetch', { cacheKey });
2610
3188
  span.setAttribute('cache.aborted_mutation_race', true);
2611
3189
  const current = this.l1.get(k);
2612
- if (current && !current.isStale && current.value !== undefined) {
3190
+ if (current && !current.isStale) {
2613
3191
  const freshVal = current.value as T;
2614
- if (this.opts.frozen) deepFreeze(freshVal);
2615
- return (this.opts.cloneStrategy === 'structuredClone' && freshVal != null && typeof freshVal === 'object')
2616
- ? structuredClone(freshVal)
2617
- : freshVal;
3192
+ return freshVal;
2618
3193
  }
2619
- if (this.opts.frozen) deepFreeze(data);
2620
- return (this.opts.cloneStrategy === 'structuredClone' && data != null && typeof data === 'object')
2621
- ? structuredClone(data)
2622
- : data;
3194
+ return data;
2623
3195
  }
2624
3196
 
2625
- this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
3197
+ const writeTs = Date.now();
3198
+ this._invalidateDiskKey(k);
3199
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs, optTags, opts.dependsOn);
3200
+ this._restoreEntryMetadata(k, { tags: optTags, dependsOn: opts.dependsOn, expiresAt: writeTs + storeTtl });
2626
3201
 
2627
- if (!this._redisDisabled) {
3202
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2628
3203
  try {
2629
- const client = await this.getRedis();
2630
- const serialized = JSON.stringify(data);
2631
- const toStore = await this._serializeAndEncrypt(serialized);
2632
- const ttlSec = Math.ceil(effectiveTtl / 1_000);
2633
- if (this.opts.tagStrategy === 'generational' && activeTagVersions) {
2634
- const now = Date.now();
2635
- const tx = client.multi();
2636
- tx.hset(k, {
2637
- d: toStore,
2638
- t: String(now),
2639
- tv: JSON.stringify(activeTagVersions),
2640
- });
2641
- tx.expire(k, ttlSec);
2642
- await tx.exec();
2643
- } else {
2644
- await client.setex(k, ttlSec, toStore);
2645
- }
3204
+ await this._writeRedisEntry(k, data, writeTs + storeTtl, writeTs, activeTagVersions, staleAt, optTags, opts.dependsOn,
3205
+ () => this._getKeyMutationEpoch(k) === mutationEpochAtStart);
2646
3206
  this.cb.onSuccess();
2647
3207
  this.logger.debug('Cached L1+L2', { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
2648
3208
  } catch {
@@ -2653,18 +3213,15 @@ export class CacheService {
2653
3213
  this.logger.debug('Cached L1', { cacheKey });
2654
3214
  }
2655
3215
 
2656
- if (this.opts.frozen) deepFreeze(data);
2657
- return (this.opts.cloneStrategy === 'structuredClone' && data != null && typeof data === 'object')
2658
- ? structuredClone(data)
2659
- : data;
3216
+ return data;
2660
3217
  } finally {
2661
- this.inflight.delete(k);
3218
+ if (this.inflight.get(k) === executionPromise) this.inflight.delete(k);
2662
3219
  span.end();
2663
3220
  }
2664
- })();
3221
+ });
2665
3222
 
2666
3223
  this.inflight.set(k, executionPromise);
2667
- return executionPromise;
3224
+ return this._prepareReadValue(await executionPromise);
2668
3225
  }
2669
3226
 
2670
3227
  /**
@@ -2760,6 +3317,9 @@ export class CacheService {
2760
3317
  knownTagVersions?: Record<string, number>,
2761
3318
  ): Promise<void> {
2762
3319
  const startEpoch = this._getKeyMutationEpoch(cacheKey);
3320
+ const previous = this.l1.getEntry(cacheKey);
3321
+ const tags = previous?.tags ?? Object.keys(knownTagVersions ?? {});
3322
+ const dependencies = previous?.dependsOn;
2763
3323
  try {
2764
3324
  const fetchStart = Date.now();
2765
3325
  const data = await fetchFn();
@@ -2800,32 +3360,20 @@ export class CacheService {
2800
3360
  return;
2801
3361
  }
2802
3362
 
2803
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
3363
+ const writeTs = Date.now();
3364
+ this._invalidateDiskKey(cacheKey);
3365
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs, tags, dependencies);
3366
+ this._restoreEntryMetadata(cacheKey, { tags, dependsOn: dependencies, expiresAt: writeTs + ttlMs + swrGraceMs });
2804
3367
 
2805
3368
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2806
3369
  try {
2807
- const client = await this.getRedis();
2808
- const s = JSON.stringify(data);
2809
- const stored = await this._serializeAndEncrypt(s);
2810
- const ttlSec = Math.ceil(ttlMs / 1_000);
2811
- if (this.opts.tagStrategy === 'generational' && activeTagVersions) {
2812
- const now = Date.now();
2813
- const tx = client.multi();
2814
- tx.hset(cacheKey, {
2815
- d: stored,
2816
- t: String(now),
2817
- tv: JSON.stringify(activeTagVersions),
2818
- });
2819
- tx.expire(cacheKey, ttlSec);
2820
- await tx.exec();
2821
- } else {
2822
- await client.setex(cacheKey, ttlSec, stored);
2823
- }
3370
+ await this._writeRedisEntry(cacheKey, data, writeTs + ttlMs + swrGraceMs, writeTs, activeTagVersions, staleAt, tags, dependencies,
3371
+ () => this._getKeyMutationEpoch(cacheKey) === startEpoch);
2824
3372
  } catch { /* ok */ }
2825
3373
  }
2826
3374
  this.logger.debug('SWR: revalidation complete', { cacheKey });
2827
3375
  } catch (err) {
2828
- if (this.opts.staleIfError > 0) {
3376
+ if (this.opts.staleIfError > 0 && this._getKeyMutationEpoch(cacheKey) === startEpoch) {
2829
3377
  const additionalMs = this.opts.staleIfError * 1_000;
2830
3378
  this.l1.bumpExpiry(cacheKey, additionalMs);
2831
3379
  this.logger.debug('SWR: revalidation failed, stale-if-error extending expiry', {
@@ -2857,14 +3405,18 @@ export class CacheService {
2857
3405
  const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1_000);
2858
3406
  const p = priority ?? inferPriority(cacheKey);
2859
3407
  const k = this.nk(cacheKey);
3408
+ const existingEntry = this.l1.getEntry(k);
3409
+ const requestedTags = opts?.tags ?? existingEntry?.tags ?? this.keyTags.get(k)?.tags;
3410
+ const requestedDependencies = opts?.dependsOn ?? existingEntry?.dependsOn;
2860
3411
  this._bumpKeyMutation(k);
3412
+ const epoch = this._getKeyMutationEpoch(k);
2861
3413
  this.inflight.delete(k);
2862
- this._pendingDiskDeletes.delete(k);
3414
+ this._invalidateDiskKey(k);
2863
3415
  this.counters.sets++;
2864
3416
 
2865
3417
  let activeTagVersions: Record<string, number> | undefined;
2866
- const tagsToRegister = opts?.tags?.length
2867
- ? (this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags)
3418
+ const tagsToRegister = requestedTags?.length
3419
+ ? (this.opts.hierarchicalTags ? expandHierarchicalTags(requestedTags, this.opts.tagHierarchyDelimiter) : requestedTags)
2868
3420
  : undefined;
2869
3421
 
2870
3422
  if (tagsToRegister?.length) {
@@ -2875,46 +3427,23 @@ export class CacheService {
2875
3427
  activeTagVersions[tagsToRegister[i]] = vers[i];
2876
3428
  }
2877
3429
  } else {
2878
- await this._registerTags(k, tagsToRegister, ttlSeconds);
3430
+ await this._registerTags(k, tagsToRegister, effectiveTtlSeconds);
2879
3431
  }
2880
3432
  }
2881
3433
 
2882
- this.l1.set(k, data, ttlMs, p, undefined, undefined, activeTagVersions);
3434
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return;
3435
+ const writeTs = Date.now();
3436
+ this.l1.set(k, data, ttlMs, p, undefined, undefined, activeTagVersions, writeTs, tagsToRegister, requestedDependencies);
3437
+ this._rememberTags(k, tagsToRegister ?? [], writeTs + ttlMs);
2883
3438
 
2884
3439
  // Register dependency patterns: when any key matching a pattern is deleted,
2885
3440
  // this key (k) is automatically cascaded.
2886
- if (opts?.dependsOn?.length) {
2887
- for (const pattern of opts.dependsOn) {
2888
- const nsPattern = this.nk(pattern);
2889
- let deps = this.dependencyIndex.get(nsPattern);
2890
- if (!deps) { deps = new Set(); this.dependencyIndex.set(nsPattern, deps); }
2891
- deps.add(k);
2892
- }
2893
- }
3441
+ this._registerDependencies(k, requestedDependencies);
2894
3442
 
2895
3443
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2896
3444
  try {
2897
- const client = await this.getRedis();
2898
- const s = JSON.stringify(data);
2899
- const stored = await this._serializeAndEncrypt(s);
2900
- const ttlSec = Math.ceil(ttlMs / 1_000);
2901
- if (this.opts.tagStrategy === 'generational' && activeTagVersions) {
2902
- const now = Date.now();
2903
- const tx = client.multi();
2904
- tx.hset(k, {
2905
- d: stored,
2906
- t: String(now),
2907
- tv: JSON.stringify(activeTagVersions),
2908
- });
2909
- tx.expire(k, ttlSec);
2910
- await tx.exec();
2911
- } else {
2912
- if (this.opts.autoPipeline && this.pipeliner) {
2913
- await this.pipeliner.setex(k, ttlSec, stored);
2914
- } else {
2915
- await client.setex(k, ttlSec, stored);
2916
- }
2917
- }
3445
+ await this._writeRedisEntry(k, data, writeTs + ttlMs, writeTs, activeTagVersions, undefined, tagsToRegister, requestedDependencies,
3446
+ () => this._getKeyMutationEpoch(k) === epoch);
2918
3447
  this.cb.onSuccess();
2919
3448
  } catch (err) {
2920
3449
  this.cb.onFailure();
@@ -2941,20 +3470,18 @@ export class CacheService {
2941
3470
  * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
2942
3471
  */
2943
3472
  private async _registerTags(k: string, tags: string[], ttlSeconds: number): Promise<void> {
2944
- for (const tag of tags) {
2945
- const tagKey = this.nk(`_tag_:${tag}`);
2946
- let members = this.tagIndex.get(tagKey);
2947
- if (!members) { members = new Set(); this.tagIndex.set(tagKey, members); }
2948
- members.add(k);
2949
- }
3473
+ const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
3474
+ const expiresAt = Date.now() + effectiveTtl * 1_000;
3475
+ const uniqueTags = Array.from(new Set(tags));
3476
+ this._rememberTags(k, uniqueTags, expiresAt);
2950
3477
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2951
3478
  try {
2952
3479
  const client = await this.getRedis();
2953
3480
  const pl = client.pipeline();
2954
- for (const tag of tags) {
3481
+ for (const tag of uniqueTags) {
2955
3482
  const tagKey = this.nk(`_tag_:${tag}`);
2956
3483
  pl.sadd(tagKey, k);
2957
- pl.expire(tagKey, ttlSeconds + 3_600);
3484
+ pl.expire(tagKey, effectiveTtl + 3_600);
2958
3485
  }
2959
3486
  await pl.exec();
2960
3487
  this.cb.onSuccess();
@@ -2979,6 +3506,7 @@ export class CacheService {
2979
3506
  this.counters.deletes++;
2980
3507
 
2981
3508
  if (isPattern) {
3509
+ this._fenceInvalidation();
2982
3510
  const pfx = k.endsWith('*') ? k.slice(0, -1) : k;
2983
3511
  for (const liveKey of this.l1.liveKeys()) {
2984
3512
  if (liveKey.startsWith(pfx)) {
@@ -2991,24 +3519,25 @@ export class CacheService {
2991
3519
  this.inflight.delete(inflightKey);
2992
3520
  }
2993
3521
  }
2994
- this._addPatternTombstone(pfx);
3522
+ this._addPatternTombstone(k);
2995
3523
  this.l1.deletePattern(k);
3524
+ this._removePatternFromIndices(k);
3525
+ for (const ktKey of Array.from(this.keyTags.keys())) {
3526
+ if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
3527
+ }
3528
+ for (const kdKey of Array.from(this.keyDependencies.keys())) {
3529
+ if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
3530
+ }
2996
3531
  } else {
2997
3532
  this._bumpKeyMutation(k);
2998
3533
  this.inflight.delete(k);
2999
3534
  this.l1.delete(k);
3000
- this._pendingDiskDeletes.add(k);
3001
- setImmediate(() => {
3002
- try {
3003
- if (!this._diskDisabled) this.disk.delete(k);
3004
- } finally {
3005
- this._pendingDiskDeletes.delete(k);
3006
- }
3007
- });
3535
+ this._invalidateDiskKey(k);
3536
+ this._removeKeyTags(k);
3008
3537
  // Cascade: invalidate any key that declared it depends on this exact key's pattern
3009
3538
  this._cascadeDependencies(k);
3010
3539
  // Clean up: remove k from all dependency registrations (it is gone)
3011
- for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
3540
+ this._removeKeyDependencies(k);
3012
3541
  }
3013
3542
 
3014
3543
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
@@ -3016,7 +3545,7 @@ export class CacheService {
3016
3545
  const client = await this.getRedis();
3017
3546
  if (isPattern) {
3018
3547
  const keys = await this._scanKeys(client, k);
3019
- if (keys.length > 0) await client.del(...keys);
3548
+ await this._deleteRedisKeys(client, keys);
3020
3549
  } else {
3021
3550
  if (this.opts.autoPipeline && this.pipeliner) {
3022
3551
  await this.pipeliner.del(k);
@@ -3067,7 +3596,7 @@ export class CacheService {
3067
3596
  this._assertActive('increment');
3068
3597
  const k = this.nk(cacheKey);
3069
3598
 
3070
- if (this._redisDisabled) {
3599
+ if (this._redisDisabled || this.opts.l2WriteMode === 'read-only') {
3071
3600
  if (!this._incrementFallbackWarned) {
3072
3601
  this._incrementFallbackWarned = true;
3073
3602
  this.logger.warn(
@@ -3082,6 +3611,15 @@ export class CacheService {
3082
3611
  entry.value++;
3083
3612
  return entry.value;
3084
3613
  }
3614
+ if (this._l1Counters.size >= 50_000 && !this._l1Counters.has(k)) {
3615
+ for (const [ck, cv] of this._l1Counters) {
3616
+ if (cv.expiresAt <= now) this._l1Counters.delete(ck);
3617
+ }
3618
+ if (this._l1Counters.size >= 50_000) {
3619
+ const oldest = this._l1Counters.keys().next().value;
3620
+ if (oldest !== undefined) this._l1Counters.delete(oldest);
3621
+ }
3622
+ }
3085
3623
  this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
3086
3624
  return 1;
3087
3625
  }
@@ -3120,6 +3658,7 @@ export class CacheService {
3120
3658
  : undefined;
3121
3659
 
3122
3660
  if (k) {
3661
+ this._fenceInvalidation();
3123
3662
  const pfx = k.endsWith('*') ? k.slice(0, -1) : k;
3124
3663
  for (const liveKey of this.l1.liveKeys()) {
3125
3664
  if (liveKey.startsWith(pfx)) {
@@ -3132,8 +3671,9 @@ export class CacheService {
3132
3671
  this.inflight.delete(inflightKey);
3133
3672
  }
3134
3673
  }
3135
- this._addPatternTombstone(pfx);
3674
+ this._addPatternTombstone(k);
3136
3675
  this.l1.deletePattern(k);
3676
+ this._removePatternFromIndices(k);
3137
3677
  } else {
3138
3678
  this._globalEpoch++;
3139
3679
  this.inflight.clear();
@@ -3142,7 +3682,10 @@ export class CacheService {
3142
3682
  if (!this._diskDisabled) this.disk.clear();
3143
3683
  this._l1Counters.clear();
3144
3684
  this.tagIndex.clear();
3685
+ this.keyTags.clear();
3145
3686
  this.tagVersions.clear();
3687
+ this.dependencyIndex.clear();
3688
+ this.keyDependencies.clear();
3146
3689
  this._pendingDiskDeletes.clear();
3147
3690
  this._keyMutationEpochs.clear();
3148
3691
  }
@@ -3152,7 +3695,7 @@ export class CacheService {
3152
3695
  const client = await this.getRedis();
3153
3696
  const pattern = k ?? (this._namespace ? `${this._namespace}:*` : '*');
3154
3697
  const keys = await this._scanKeys(client, pattern);
3155
- if (keys.length > 0) await client.del(...keys);
3698
+ await this._deleteRedisKeys(client, keys);
3156
3699
  } catch (err) {
3157
3700
  this.logger.debug('clear: Redis unavailable', { error: (err as Error).message });
3158
3701
  }
@@ -3282,25 +3825,35 @@ export class CacheService {
3282
3825
  this._assertActive('scan');
3283
3826
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
3284
3827
  this.l1.scan((key, entry, pfx) => {
3285
- const value = (entry.value !== undefined ? entry.value : entry.data) as T;
3286
- fn(key, value, pfx);
3828
+ fn(key, this._prepareReadValue(this.l1.resolveValue(entry) as T), pfx);
3287
3829
  }, prefixLen);
3288
3830
  }
3289
3831
 
3290
3832
  /**
3291
- * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
3833
+ * Extend the TTL of a key in L1 and Redis without fetching.
3292
3834
  * Returns `false` if the key is absent or already expired.
3293
3835
  *
3294
3836
  * @param newTtlSeconds - The new TTL from now, in seconds.
3295
3837
  */
3296
3838
  async touch(cacheKey: string, newTtlSeconds: number): Promise<boolean> {
3297
3839
  this._assertActive('touch');
3840
+ if (!Number.isFinite(newTtlSeconds) || newTtlSeconds <= 0) throw new Error('touch TTL must be finite and positive');
3298
3841
  const k = this.nk(cacheKey);
3842
+ const epoch = this._getKeyMutationEpoch(k);
3299
3843
  const hit = this.l1.touch(k, newTtlSeconds * 1_000);
3300
- if (hit && !this._redisDisabled) {
3844
+ const entry = this.l1.getEntry(k);
3845
+ if (hit) {
3846
+ const kt = this.keyTags.get(k);
3847
+ if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1_000;
3848
+ }
3849
+ if (hit && !this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
3301
3850
  try {
3302
3851
  const client = await this.getRedis();
3303
- void client.expire(k, newTtlSeconds); // fire-and-forget
3852
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return hit;
3853
+ if (entry && typeof client.pttl === 'function' && typeof client.eval === 'function') {
3854
+ await client.eval(LUA_TOUCH_CACHE_ENTRY, 1, k, String(entry.setAt ?? 0), String(entry.expiresAt), String(Math.ceil(newTtlSeconds * 1000)));
3855
+ } else await client.expire(k, Math.ceil(newTtlSeconds));
3856
+ this.cb.onSuccess();
3304
3857
  } catch { /* ok */ }
3305
3858
  }
3306
3859
  return hit;
@@ -3322,7 +3875,15 @@ export class CacheService {
3322
3875
  const now = Date.now();
3323
3876
  if (entry.expiresAt <= now) return null; // expired
3324
3877
  if (entry.staleAt !== undefined && entry.staleAt < now) return null; // in SWR grace
3325
- return (entry.value !== undefined ? entry.value : this.codec.decode(entry.data)) as T;
3878
+ if (entry.tagVersions && Object.entries(entry.tagVersions).some(([tag, version]) => (this.tagVersions.get(tag)?.version ?? 0) > version)) return null;
3879
+ return this._prepareReadValue((entry.value !== undefined ? entry.value : this.codec.decode(entry.data)) as T);
3880
+ }
3881
+
3882
+ private _prepareReadValue<T>(val: T): T {
3883
+ if (this.opts.frozen) deepFreeze(val);
3884
+ return (this.opts.cloneStrategy === 'structuredClone' && val != null && typeof val === 'object')
3885
+ ? structuredClone(val)
3886
+ : val;
3326
3887
  }
3327
3888
 
3328
3889
  /**
@@ -3336,69 +3897,42 @@ export class CacheService {
3336
3897
  async peek<T = unknown>(cacheKey: string): Promise<T | null> {
3337
3898
  this._assertActive('peek');
3338
3899
  const k = this.nk(cacheKey);
3900
+ const epoch = this._getKeyMutationEpoch(k);
3901
+ this.counters.gets++;
3339
3902
 
3340
3903
  // 1. L1 RAM
3341
3904
  const l1Hit = this.l1.get(k);
3342
3905
  if (l1Hit !== null) {
3343
- this.counters.gets++;
3344
- this.counters.l1Hits++;
3345
- const val = l1Hit.value as T;
3346
- if (this.opts.frozen) deepFreeze(val);
3347
- return (this.opts.cloneStrategy === 'structuredClone' && val != null && typeof val === 'object')
3348
- ? structuredClone(val)
3349
- : val;
3906
+ if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
3907
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
3908
+ } else {
3909
+ this.counters.l1Hits++;
3910
+ return this._prepareReadValue(l1Hit.value as T);
3911
+ }
3350
3912
  }
3351
3913
 
3352
3914
  // 2. L1.5 Disk
3353
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
3354
- if (this._isTombstonedByPattern(k)) {
3355
- try { this.disk.delete(k); } catch { /* ok */ }
3356
- } else if (this.watchdog.isDiskAllowed()) {
3357
- const diskStart = performance.now();
3358
- const diskHit = this.disk.load(k);
3359
- const diskElapsed = performance.now() - diskStart;
3360
- this.watchdog.recordDisk(diskElapsed);
3361
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
3362
-
3363
- if (diskHit !== null) {
3364
- const promoted = this.l1.importEntries(
3365
- [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
3366
- this.opts.forbiddenSnapshotPrefixes,
3367
- );
3368
- if (promoted > 0) {
3369
- const l1Check = this.l1.get(k);
3370
- if (l1Check !== null) {
3371
- this.counters.gets++;
3372
- this.counters.diskHits++;
3373
- const val = l1Check.value as T;
3374
- if (this.opts.frozen) deepFreeze(val);
3375
- return (this.opts.cloneStrategy === 'structuredClone' && val != null && typeof val === 'object')
3376
- ? structuredClone(val)
3377
- : val;
3378
- }
3379
- }
3380
- }
3915
+ const diskHit = await this._readDiskEntry<T>(k, epoch);
3916
+ if (diskHit) {
3917
+ this.counters.diskHits++;
3918
+ return this._prepareReadValue(diskHit.value);
3381
3919
  }
3382
- }
3383
3920
 
3384
3921
  // 3. L2 Redis
3385
- if (!this._redisDisabled && !this.cb.isOpen) {
3922
+ if (!this._redisDisabled) {
3386
3923
  try {
3387
3924
  const client = await this.getRedis();
3388
3925
  const redisStart = performance.now();
3389
- const raw = await client.get(k);
3926
+ const redisHit = await this._readRedisEntry<T>(client, k);
3390
3927
  const redisElapsed = performance.now() - redisStart;
3391
3928
  this.watchdog.recordRedis(redisElapsed);
3392
- if (raw !== null) {
3393
- const parsed = await this._decryptAndDeserialize<T>(raw);
3394
- this.l1.set(k, parsed, 60_000, inferPriority(cacheKey));
3395
- this.counters.gets++;
3929
+ this.cb.onSuccess();
3930
+ if (redisHit && !redisHit.stale) {
3931
+ const parsed = redisHit.value;
3932
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return null;
3933
+ if (!this._promoteRedisEntry(k, redisHit, 60_000, inferPriority(cacheKey))) return null;
3396
3934
  this.counters.l2Hits++;
3397
- this.cb.onSuccess();
3398
- if (this.opts.frozen) deepFreeze(parsed);
3399
- return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
3400
- ? structuredClone(parsed)
3401
- : parsed;
3935
+ return this._prepareReadValue(parsed as T);
3402
3936
  }
3403
3937
  } catch (err) {
3404
3938
  this.cb.onFailure();
@@ -3425,6 +3959,8 @@ export class CacheService {
3425
3959
  priority?: CachePriority,
3426
3960
  ): Promise<(T | undefined)[]> {
3427
3961
  this._assertActive('mget');
3962
+ this.counters.gets += keys.length;
3963
+ const epochs = new Map(keys.map(key => [this.nk(key), this._getKeyMutationEpoch(this.nk(key))]));
3428
3964
  const span = this._startSpan('tricache.mget');
3429
3965
  if (this.opts.tracer) {
3430
3966
  span.setAttribute('cache.batch.size', keys.length);
@@ -3435,12 +3971,20 @@ export class CacheService {
3435
3971
  const missKeys: string[] = [];
3436
3972
 
3437
3973
  // ── Tier 1: L1 (in-memory) ──
3974
+ const now = Date.now();
3438
3975
  for (let i = 0; i < keys.length; i++) {
3439
3976
  const k = this.nk(keys[i]);
3440
3977
  const entry = this.l1.getEntry(k);
3441
- if (entry && entry.expiresAt > Date.now()) {
3442
- result[i] = (entry.value !== undefined ? entry.value : this.codec.decode(entry.data)) as T;
3443
- this.counters.l1Hits++;
3978
+ if (entry && entry.expiresAt > now && (entry.staleAt === undefined || entry.staleAt > now)) {
3979
+ if (await this._isGenerationalEntryStale(entry.tagVersions)) {
3980
+ this._deleteIfStale(k, entry.setAt ?? 0);
3981
+ missIndexes.push(i);
3982
+ missKeys.push(keys[i]);
3983
+ } else {
3984
+ const val = (entry.value !== undefined ? entry.value : this.codec.decode(entry.data)) as T;
3985
+ result[i] = this._prepareReadValue(val);
3986
+ this.counters.l1Hits++;
3987
+ }
3444
3988
  } else {
3445
3989
  missIndexes.push(i);
3446
3990
  missKeys.push(keys[i]);
@@ -3463,31 +4007,27 @@ export class CacheService {
3463
4007
  try {
3464
4008
  const client = await this.getRedis();
3465
4009
  const nsKeys = missKeys.map(k => this.nk(k));
3466
- const pipeline = client.multi();
3467
- for (const nk of nsKeys) pipeline.get(nk);
3468
- const redisStart = performance.now();
3469
- const raws = await pipeline.exec() as Array<[Error | null, string | null] | null>;
3470
- const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
3471
- this.watchdog.recordRedis(redisElapsed);
3472
- this.cb.onSuccess();
4010
+ const remoteEntries = await this._readRedisBatch<T>(client, nsKeys);
4011
+
3473
4012
  for (let j = 0; j < missKeys.length; j++) {
3474
- const raw = raws[j] ? (raws[j] as [Error | null, string | null])[1] : null;
3475
4013
  const idx = missIndexes[j];
3476
- if (raw) {
3477
- const parsed = await this._decryptAndDeserialize<T>(raw);
3478
- const k = nsKeys[j];
4014
+ const k = nsKeys[j];
4015
+ const entry = remoteEntries.get(k);
4016
+ if (entry && (entry.staleAt === undefined || entry.staleAt > Date.now()) &&
4017
+ !this._destroyed && this._getKeyMutationEpoch(k) === epochs.get(k)) {
3479
4018
  const p = priority ?? inferPriority(missKeys[j]);
3480
- this.l1.set(k, parsed, this._jitterTtl((typeof ttl === 'function' ? ttl(missKeys[j]) : ttl) * 1_000), p);
4019
+ const ttlVal = typeof ttl === 'function' ? ttl(missKeys[j]) : ttl;
4020
+ if (!this._promoteRedisEntry(k, entry, this._jitterTtl(ttlVal * 1_000), p)) continue;
3481
4021
  this.counters.l2Hits++;
3482
4022
  l2HitCount++;
3483
- result[idx] = parsed;
4023
+ result[idx] = this._prepareReadValue(entry.value as T);
3484
4024
  missIndexes[j] = -1;
3485
4025
  missKeys[j] = '';
3486
4026
  }
3487
4027
  }
3488
4028
  // Compact the still-missing arrays.
3489
4029
  const remainingIdx = missIndexes.filter(i => i >= 0);
3490
- const remainingKeys = missKeys.filter(k => k !== '');
4030
+ const remainingKeys = missKeys.filter((_key, index) => missIndexes[index] >= 0);
3491
4031
  missIndexes.length = 0; missKeys.length = 0;
3492
4032
  missIndexes.push(...remainingIdx);
3493
4033
  missKeys.push(...remainingKeys);
@@ -3501,58 +4041,62 @@ export class CacheService {
3501
4041
  if (!this._diskDisabled && missKeys.length > 0) {
3502
4042
  for (let j = missKeys.length - 1; j >= 0; j--) {
3503
4043
  const k = this.nk(missKeys[j]);
3504
- if (this._pendingDiskDeletes.has(k)) continue;
3505
- if (this._isTombstonedByPattern(k)) {
3506
- try { this.disk.delete(k); } catch { /* ok */ }
3507
- continue;
3508
- }
3509
- if (!this.watchdog.isDiskAllowed()) continue;
3510
- const diskStart = performance.now();
3511
- const diskHit = this.disk.load(k);
3512
- const diskElapsed = performance.now() - diskStart;
3513
- this.watchdog.recordDisk(diskElapsed);
3514
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
3515
- if (diskHit !== null) {
3516
- const promoted = this.l1.importEntries(
3517
- [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
3518
- this.opts.forbiddenSnapshotPrefixes,
3519
- );
3520
- if (promoted > 0) {
3521
- const l1Check = this.l1.get(k);
3522
- if (l1Check !== null) {
3523
- this.counters.diskHits++;
3524
- result[missIndexes[j]] = l1Check.value as T;
3525
- missIndexes.splice(j, 1);
3526
- missKeys.splice(j, 1);
3527
- }
3528
- }
4044
+ const diskHit = await this._readDiskEntry<T>(k, epochs.get(k)!);
4045
+ if (diskHit && (diskHit.entry.staleAt === undefined || diskHit.entry.staleAt > Date.now())) {
4046
+ this.counters.diskHits++;
4047
+ result[missIndexes[j]] = this._prepareReadValue(diskHit.value);
4048
+ missIndexes.splice(j, 1);
4049
+ missKeys.splice(j, 1);
3529
4050
  }
3530
4051
  }
3531
4052
  }
3532
4053
 
3533
4054
  // ── Tier 3: fetchFn for whatever still missed ──
3534
4055
  if (missKeys.length > 0 && fetchFn) {
3535
- this.counters.fetches++;
3536
- const fetched = await fetchFn(missKeys);
3537
- const isMap = fetched instanceof Map;
3538
- const setPromises: Promise<void>[] = [];
4056
+ const owned = new Map<string, { promise: Promise<unknown>; resolve(value: T | undefined): void; reject(error: unknown): void }>();
4057
+ const waiting: Promise<void>[] = [];
3539
4058
  for (let j = 0; j < missKeys.length; j++) {
3540
- const k = missKeys[j];
3541
- const v = isMap ? (fetched as Map<string, T>).get(k) : (fetched as Record<string, T>)[k];
3542
- result[missIndexes[j]] = v;
3543
- if (v !== undefined && v !== null) {
3544
- const resolvedTtl = typeof ttl === 'function' ? ttl(k) : ttl;
3545
- setPromises.push(this.set(k, v, resolvedTtl, priority));
3546
- } else if (v == null && this.opts.notFoundTtl > 0) {
3547
- // Negative caching: cache null/missing records with notFoundTtl to protect origin DB
3548
- setPromises.push(this.set(k, null as unknown as T, this.opts.notFoundTtl, priority));
3549
- } else if (v === null) {
3550
- const resolvedTtl = typeof ttl === 'function' ? ttl(k) : ttl;
3551
- setPromises.push(this.set(k, null as unknown as T, resolvedTtl, priority));
4059
+ const key = missKeys[j];
4060
+ const namespaced = this.nk(key);
4061
+ let promise = this.inflight.get(namespaced);
4062
+ if (!promise) {
4063
+ let resolve!: (value: T | undefined) => void;
4064
+ let reject!: (error: unknown) => void;
4065
+ promise = new Promise<T | undefined>((yes, no) => { resolve = yes; reject = no; });
4066
+ owned.set(key, { promise, resolve, reject });
4067
+ this.inflight.set(namespaced, promise);
4068
+ } else {
4069
+ this.counters.stampedes++;
3552
4070
  }
4071
+ const index = missIndexes[j];
4072
+ waiting.push(promise.then(value => { result[index] = this._prepareReadValue(value as T | undefined); }));
3553
4073
  }
3554
- if (setPromises.length > 0) {
3555
- await Promise.all(setPromises);
4074
+ // Observe coalesced failures immediately while the originating batch is still running.
4075
+ const settled = Promise.allSettled(waiting);
4076
+ try {
4077
+ if (owned.size > 0) {
4078
+ this.counters.fetches++;
4079
+ const fetched = await fetchFn([...owned.keys()]);
4080
+ await Promise.all([...owned].map(async ([key, entry]) => {
4081
+ const value = fetched instanceof Map ? fetched.get(key) : Object.hasOwn(fetched, key) ? fetched[key] : undefined;
4082
+ if (!this._destroyed && this._getKeyMutationEpoch(this.nk(key)) === epochs.get(this.nk(key))) {
4083
+ const resolvedTtl = value == null && this.opts.notFoundTtl > 0 ? this.opts.notFoundTtl : typeof ttl === 'function' ? ttl(key) : ttl;
4084
+ if (value !== undefined || this.opts.notFoundTtl > 0) await this.set(key, value === undefined && this.opts.notFoundTtl > 0 ? null : value, resolvedTtl, priority);
4085
+ }
4086
+ entry.resolve(value);
4087
+ }));
4088
+ }
4089
+ const outcomes = await settled;
4090
+ const failed = outcomes.find(outcome => outcome.status === 'rejected');
4091
+ if (failed?.status === 'rejected') throw failed.reason;
4092
+ } catch (error) {
4093
+ for (const entry of owned.values()) entry.reject(error);
4094
+ throw error;
4095
+ } finally {
4096
+ for (const [key, entry] of owned) {
4097
+ const namespaced = this.nk(key);
4098
+ if (this.inflight.get(namespaced) === entry.promise) this.inflight.delete(namespaced);
4099
+ }
3556
4100
  }
3557
4101
  }
3558
4102
 
@@ -3611,7 +4155,7 @@ export class CacheService {
3611
4155
  try {
3612
4156
  await Promise.all(keys.map(key => {
3613
4157
  const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
3614
- const hasOpts = tags?.length || dependsOn?.length;
4158
+ const hasOpts = tags !== undefined || dependsOn !== undefined;
3615
4159
  return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : undefined);
3616
4160
  }));
3617
4161
  } catch (err) {
@@ -3667,7 +4211,10 @@ export class CacheService {
3667
4211
  const nsPattern = this.nk(pattern);
3668
4212
 
3669
4213
  // Collect all matching keys via SCAN (handles single-node and Cluster)
3670
- const matchedKeys = await this._scanKeys(client, nsPattern);
4214
+ const matchedKeys = (await this._scanKeys(client, nsPattern)).filter(key => {
4215
+ const raw = this.unnk(key);
4216
+ return !raw.startsWith('_tag_:') && !raw.startsWith('tag_ver:') && !raw.startsWith('lock:') && key !== this.backplaneStreamKey;
4217
+ });
3671
4218
 
3672
4219
  if (matchedKeys.length === 0) {
3673
4220
  this.cb.onSuccess();
@@ -3675,23 +4222,13 @@ export class CacheService {
3675
4222
  }
3676
4223
 
3677
4224
  // Fetch values in a pipeline and load into L1
3678
- const pl = client.pipeline();
3679
- for (const k of matchedKeys) pl.get(k);
3680
- const results = await pl.exec() as Array<[Error | null, string | null]>;
3681
- this.cb.onSuccess();
3682
-
4225
+ const epochs = new Map(matchedKeys.map(key => [key, this._getKeyMutationEpoch(key)]));
4226
+ const results = await this._readRedisBatch<unknown>(client, matchedKeys);
3683
4227
  let loaded = 0;
3684
- for (let i = 0; i < matchedKeys.length; i++) {
3685
- const [err, raw] = results[i];
3686
- if (err || raw == null) continue;
3687
- try {
3688
- const parsed = await this._decryptAndDeserialize<unknown>(raw);
3689
- // Use a 10-minute TTL as a reasonable default; the real TTL is not
3690
- // returned by GET (use PTTL to be precise, but that doubles round-trips).
3691
- const remainingMs = 10 * 60 * 1_000;
3692
- this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
3693
- loaded++;
3694
- } catch { /* skip malformed entries */ }
4228
+ for (const key of matchedKeys) {
4229
+ const entry = results.get(key);
4230
+ if (!entry || this._destroyed || this._getKeyMutationEpoch(key) !== epochs.get(key)) continue;
4231
+ if (this._promoteRedisEntry(key, entry, 10 * 60 * 1000, opts?.priority ?? inferPriority(this.unnk(key))) && this.l1.has(key)) loaded++;
3695
4232
  }
3696
4233
 
3697
4234
  this.logger.info('warmFromL2 complete', {
@@ -3780,6 +4317,155 @@ export class CacheService {
3780
4317
  return matched;
3781
4318
  }
3782
4319
 
4320
+ private async _publishTagInvalidation(
4321
+ op: 'del' | 'tag_incr' | 'tag_pattern_incr' | 'tag_pattern_del',
4322
+ key: string,
4323
+ tagVersion?: number,
4324
+ ): Promise<void> {
4325
+ if (this.opts.awaitInvalidationBackplane) {
4326
+ await this.publishInvalidation(op, key, tagVersion, false, true);
4327
+ } else {
4328
+ void this.publishInvalidation(op, key, tagVersion, false, true);
4329
+ }
4330
+ }
4331
+
4332
+ private _removeTagMembersLocal(keys: Iterable<string>): void {
4333
+ const keyList = Array.isArray(keys) ? keys : Array.from(keys);
4334
+ for (const k of keyList) {
4335
+ this.l1.delete(k);
4336
+ this._bumpKeyMutation(k);
4337
+ this._removeKeyTags(k);
4338
+ this._removeKeyDependencies(k);
4339
+ this._invalidateDiskKey(k);
4340
+ }
4341
+ }
4342
+
4343
+ /**
4344
+ * Executes invalidation for a single already-resolved concrete tag without
4345
+ * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
4346
+ */
4347
+ private async _invalidateConcreteTag(tag: string): Promise<void> {
4348
+ this._fenceInvalidation();
4349
+ if (this.opts.tagStrategy === 'generational') {
4350
+ let newVer = 1;
4351
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
4352
+ try {
4353
+ const client = await this.getRedis();
4354
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
4355
+ } catch (err) {
4356
+ this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
4357
+ const current = this.tagVersions.get(tag)?.version ?? 0;
4358
+ newVer = current + 1;
4359
+ }
4360
+ } else {
4361
+ const current = this.tagVersions.get(tag)?.version ?? 0;
4362
+ newVer = current + 1;
4363
+ }
4364
+ this._setLocalTagVersion(tag, newVer, performance.now());
4365
+ await this._publishTagInvalidation('tag_incr', tag, newVer);
4366
+ return;
4367
+ }
4368
+
4369
+ const tagKey = this.nk(`_tag_:${tag}`);
4370
+ const members = new Set(this.tagIndex.get(tagKey) ?? []);
4371
+
4372
+ this.tagIndex.delete(tagKey);
4373
+ this._removeTagMembersLocal(members);
4374
+
4375
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
4376
+ try {
4377
+ const client = await this.getRedis();
4378
+ const redisMembers: string[] = await client.smembers(tagKey);
4379
+ for (const key of redisMembers) members.add(key);
4380
+ this._removeTagMembersLocal(redisMembers);
4381
+ const toDelete = [...new Set([...members, ...redisMembers, tagKey])];
4382
+ await this._deleteRedisKeys(client, toDelete);
4383
+ } catch (err) {
4384
+ this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
4385
+ }
4386
+ }
4387
+ await Promise.all([...members].map(key => this._publishTagInvalidation('del', key)));
4388
+ await this._publishTagInvalidation('tag_pattern_del', tag);
4389
+ }
4390
+
4391
+ /**
4392
+ * Executes invalidation for an array of already-resolved concrete tags
4393
+ * without re-entering wildcard/cascade resolution or invalidateTag().
4394
+ */
4395
+ private async _invalidateConcreteTags(tags: string[]): Promise<void> {
4396
+ if (tags.length === 0) return;
4397
+ if (tags.length === 1) {
4398
+ await this._invalidateConcreteTag(tags[0]);
4399
+ return;
4400
+ }
4401
+ this._fenceInvalidation();
4402
+
4403
+ if (this.opts.tagStrategy === 'generational') {
4404
+ const now = performance.now();
4405
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
4406
+ try {
4407
+ const client = await this.getRedis();
4408
+ const pl = client.pipeline();
4409
+ for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
4410
+ const results = await pl.exec() as Array<[Error | null, number]>;
4411
+ for (let i = 0; i < tags.length; i++) {
4412
+ const [err, newVer] = results[i] ?? [null, null];
4413
+ const ver = (!err && typeof newVer === 'number') ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
4414
+ this._setLocalTagVersion(tags[i], ver, now);
4415
+ await this._publishTagInvalidation('tag_incr', tags[i], ver);
4416
+ }
4417
+ return;
4418
+ } catch (err) {
4419
+ this.logger.debug('invalidateTags: Redis unavailable', { tags, error: (err as Error).message });
4420
+ }
4421
+ }
4422
+ for (const tag of tags) {
4423
+ const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
4424
+ this._setLocalTagVersion(tag, ver, now);
4425
+ await this._publishTagInvalidation('tag_incr', tag, ver);
4426
+ }
4427
+ return;
4428
+ }
4429
+
4430
+ // In-process: collect all member keys across all tags and remove from L1 + disk
4431
+ const tagKeys: string[] = [];
4432
+ const allMembers = new Set<string>();
4433
+ for (const tag of tags) {
4434
+ const tagKey = this.nk(`_tag_:${tag}`);
4435
+ tagKeys.push(tagKey);
4436
+ const members = this.tagIndex.get(tagKey) ?? new Set<string>();
4437
+ for (const k of members) allMembers.add(k);
4438
+ this.tagIndex.delete(tagKey);
4439
+ }
4440
+ this._removeTagMembersLocal(allMembers);
4441
+
4442
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
4443
+ try {
4444
+ const client = await this.getRedis();
4445
+ // Single round-trip: pipeline SMEMBERS for all tag keys
4446
+ const pl = client.pipeline();
4447
+ for (const tagKey of tagKeys) pl.smembers(tagKey);
4448
+ const smResults = await pl.exec() as Array<[Error | null, string[] | null]>;
4449
+
4450
+ // Merge Redis members into the master delete set
4451
+ const toDelete: string[] = [...allMembers];
4452
+ for (const [err, redisMembers] of smResults) {
4453
+ if (!err && redisMembers) {
4454
+ for (const k of redisMembers) { if (!allMembers.has(k)) toDelete.push(k); allMembers.add(k); }
4455
+ }
4456
+ }
4457
+ // Chunk/cluster-safe DEL for all member keys + tag keys
4458
+ const keysToRemove = [...toDelete, ...tagKeys];
4459
+ await this._deleteRedisKeys(client, keysToRemove);
4460
+ this._removeTagMembersLocal(allMembers);
4461
+ } catch (err) {
4462
+ this.logger.debug('invalidateTags: Redis unavailable', { tags, error: (err as Error).message });
4463
+ }
4464
+ }
4465
+ await Promise.all([...allMembers].map(key => this._publishTagInvalidation('del', key)));
4466
+ for (const tag of tags) await this._publishTagInvalidation('tag_pattern_del', tag);
4467
+ }
4468
+
3783
4469
  /**
3784
4470
  * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
3785
4471
  * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
@@ -3817,76 +4503,17 @@ export class CacheService {
3817
4503
  const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
3818
4504
 
3819
4505
  if (matchedTags.size > 0) {
3820
- await this.invalidateTags(Array.from(matchedTags));
4506
+ await this._invalidateConcreteTags(Array.from(matchedTags));
3821
4507
  }
3822
4508
 
3823
4509
  // Broadcast wildcard invalidation across backplane and cross-region
3824
4510
  const op = this.opts.tagStrategy === 'generational' ? 'tag_pattern_incr' : 'tag_pattern_del';
3825
- if (this.opts.awaitInvalidationBackplane) {
3826
- await this.publishInvalidation(op, broadcastPattern, undefined, false, true);
3827
- } else {
3828
- void this.publishInvalidation(op, broadcastPattern, undefined, false, true);
3829
- }
4511
+ await this._publishTagInvalidation(op, broadcastPattern);
3830
4512
  return;
3831
4513
  }
3832
4514
 
3833
4515
  // Fast-path: single discrete tag
3834
- if (this.opts.tagStrategy === 'generational') {
3835
- let newVer = 1;
3836
- if (!this._redisDisabled) {
3837
- try {
3838
- const client = await this.getRedis();
3839
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
3840
- } catch (err) {
3841
- this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
3842
- const current = this.tagVersions.get(tag)?.version ?? 0;
3843
- newVer = current + 1;
3844
- }
3845
- } else {
3846
- const current = this.tagVersions.get(tag)?.version ?? 0;
3847
- newVer = current + 1;
3848
- }
3849
- this._setLocalTagVersion(tag, newVer, performance.now());
3850
- if (this.opts.awaitInvalidationBackplane) {
3851
- await this.publishInvalidation('tag_incr', tag, newVer, false, true);
3852
- } else {
3853
- void this.publishInvalidation('tag_incr', tag, newVer, false, true);
3854
- }
3855
- return;
3856
- }
3857
-
3858
- const tagKey = this.nk(`_tag_:${tag}`);
3859
- const members = this.tagIndex.get(tagKey) ?? new Set<string>();
3860
-
3861
- // Remove from L1 + disk
3862
- for (const k of members) {
3863
- this.l1.delete(k);
3864
- this._bumpKeyMutation(k);
3865
- this._pendingDiskDeletes.add(k);
3866
- setImmediate(() => {
3867
- try {
3868
- if (!this._diskDisabled) this.disk.delete(k);
3869
- } finally {
3870
- this._pendingDiskDeletes.delete(k);
3871
- }
3872
- });
3873
- }
3874
- this.tagIndex.delete(tagKey);
3875
-
3876
- if (!this._redisDisabled) {
3877
- try {
3878
- const client = await this.getRedis();
3879
- const redisMembers: string[] = await client.smembers(tagKey);
3880
- const toDelete = [...new Set([...members, ...redisMembers])];
3881
- if (toDelete.length > 0) {
3882
- await client.del(...toDelete, tagKey);
3883
- } else {
3884
- await client.del(tagKey);
3885
- }
3886
- } catch (err) {
3887
- this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
3888
- }
3889
- }
4516
+ await this._invalidateConcreteTag(tag);
3890
4517
  } catch (err) {
3891
4518
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
3892
4519
  span.recordException?.(err);
@@ -3916,100 +4543,32 @@ export class CacheService {
3916
4543
 
3917
4544
  if (hasWildcards || shouldCascade) {
3918
4545
  const allResolvedTags = new Set<string>();
4546
+ const broadcastPatterns = new Set<string>();
4547
+ const delim = this.opts.tagHierarchyDelimiter;
4548
+
3919
4549
  for (const t of tags) {
3920
- if (isWildcardTag(t) || shouldCascade) {
4550
+ const tIsPattern = isWildcardTag(t);
4551
+ if (tIsPattern || shouldCascade) {
4552
+ broadcastPatterns.add(tIsPattern ? t : `${t}${delim}*`);
3921
4553
  const resolved = await this._resolveMatchingTags(t, shouldCascade);
3922
4554
  for (const rt of resolved) allResolvedTags.add(rt);
3923
4555
  } else {
3924
4556
  allResolvedTags.add(t);
3925
4557
  }
3926
4558
  }
3927
- if (allResolvedTags.size === 0) return;
3928
- tags = Array.from(allResolvedTags);
3929
- }
3930
-
3931
- if (tags.length === 1) { await this.invalidateTag(tags[0], opts); return; }
3932
4559
 
3933
- if (this.opts.tagStrategy === 'generational') {
3934
- const now = performance.now();
3935
- if (!this._redisDisabled) {
3936
- try {
3937
- const client = await this.getRedis();
3938
- const pl = client.pipeline();
3939
- for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
3940
- const results = await pl.exec() as Array<[Error | null, number]>;
3941
- for (let i = 0; i < tags.length; i++) {
3942
- const [err, newVer] = results[i] ?? [null, null];
3943
- const ver = (!err && typeof newVer === 'number') ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
3944
- this._setLocalTagVersion(tags[i], ver, now);
3945
- if (this.opts.awaitInvalidationBackplane) {
3946
- await this.publishInvalidation('tag_incr', tags[i], ver, false, true);
3947
- } else {
3948
- void this.publishInvalidation('tag_incr', tags[i], ver, false, true);
3949
- }
3950
- }
3951
- return;
3952
- } catch (err) {
3953
- this.logger.debug('invalidateTags: Redis unavailable', { tags, error: (err as Error).message });
3954
- }
4560
+ if (allResolvedTags.size > 0) {
4561
+ await this._invalidateConcreteTags(Array.from(allResolvedTags));
3955
4562
  }
3956
- for (const tag of tags) {
3957
- const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
3958
- this._setLocalTagVersion(tag, ver, now);
3959
- if (this.opts.awaitInvalidationBackplane) {
3960
- await this.publishInvalidation('tag_incr', tag, ver, false, true);
3961
- } else {
3962
- void this.publishInvalidation('tag_incr', tag, ver, false, true);
3963
- }
4563
+
4564
+ const op = this.opts.tagStrategy === 'generational' ? 'tag_pattern_incr' : 'tag_pattern_del';
4565
+ for (const pattern of broadcastPatterns) {
4566
+ await this._publishTagInvalidation(op, pattern);
3964
4567
  }
3965
4568
  return;
3966
4569
  }
3967
4570
 
3968
- // In-process: collect all member keys across all tags and remove from L1 + disk
3969
- const tagKeys: string[] = [];
3970
- const allMembers = new Set<string>();
3971
- for (const tag of tags) {
3972
- const tagKey = this.nk(`_tag_:${tag}`);
3973
- tagKeys.push(tagKey);
3974
- const members = this.tagIndex.get(tagKey) ?? new Set<string>();
3975
- for (const k of members) allMembers.add(k);
3976
- this.tagIndex.delete(tagKey);
3977
- }
3978
- for (const k of allMembers) {
3979
- this.l1.delete(k);
3980
- this._bumpKeyMutation(k);
3981
- this._pendingDiskDeletes.add(k);
3982
- setImmediate(() => {
3983
- try {
3984
- if (!this._diskDisabled) this.disk.delete(k);
3985
- } finally {
3986
- this._pendingDiskDeletes.delete(k);
3987
- }
3988
- });
3989
- }
3990
-
3991
- if (!this._redisDisabled) {
3992
- try {
3993
- const client = await this.getRedis();
3994
- // Single round-trip: pipeline SMEMBERS for all tag keys
3995
- const pl = client.pipeline();
3996
- for (const tagKey of tagKeys) pl.smembers(tagKey);
3997
- const smResults = await pl.exec() as Array<[Error | null, string[] | null]>;
3998
-
3999
- // Merge Redis members into the master delete set
4000
- const toDelete: string[] = [...allMembers];
4001
- for (const [err, redisMembers] of smResults) {
4002
- if (!err && redisMembers) {
4003
- for (const k of redisMembers) { if (!allMembers.has(k)) toDelete.push(k); }
4004
- }
4005
- }
4006
- // Single DEL for all member keys + tag keys
4007
- const keysToRemove = [...toDelete, ...tagKeys];
4008
- if (keysToRemove.length > 0) await client.del(...keysToRemove);
4009
- } catch (err) {
4010
- this.logger.debug('invalidateTags: Redis unavailable', { tags, error: (err as Error).message });
4011
- }
4012
- }
4571
+ await this._invalidateConcreteTags(Array.from(new Set(tags)));
4013
4572
  }
4014
4573
 
4015
4574
  /**
@@ -4080,21 +4639,25 @@ export class CacheService {
4080
4639
  const circuitOpen = this.cb.isOpen;
4081
4640
  const latencyBypass = watchdogTel.bypassActive;
4082
4641
 
4083
- const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
4084
- const healthy = this.opts.failReadinessOnDegraded ? !degraded : true;
4642
+ const backplaneUnavailable = this.opts.invalidationBackplane && !this._redisDisabled && !this._backplaneAvailable;
4643
+ const degraded = this._destroyed || circuitOpen || latencyBypass || diskPruning || diskLowSpace || backplaneUnavailable;
4644
+ const healthy = !this._destroyed && (this.opts.failReadinessOnDegraded ? !degraded : true);
4085
4645
 
4086
4646
  const reasons: string[] = [];
4087
4647
  if (circuitOpen) reasons.push('redis_circuit_breaker_open');
4088
4648
  if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
4089
4649
  if (diskPruning) reasons.push('disk_quota_watermark_pruning_active');
4090
4650
  if (diskLowSpace) reasons.push('disk_host_volume_low_space');
4651
+ if (backplaneUnavailable) reasons.push('invalidation_backplane_unavailable');
4652
+ if (this._destroyed) reasons.push('cache_destroyed');
4091
4653
 
4092
4654
  return {
4093
4655
  healthy,
4094
4656
  degraded,
4095
4657
  reasons,
4096
4658
  details: {
4097
- redisConnected: !circuitOpen && !this._redisDisabled,
4659
+ redisConnected: !this._destroyed && !circuitOpen && !!this.redis && (this.redis.status === 'ready' || this.redis.isOpen === true),
4660
+ backplaneReady: this._backplaneAvailable,
4098
4661
  circuitBreakerState: this.cb.currentState,
4099
4662
  diskPruningActive: diskPruning,
4100
4663
  diskHostVolumeLowSpace: diskLowSpace,
@@ -4118,24 +4681,19 @@ export class CacheService {
4118
4681
  */
4119
4682
  async drainToL2(): Promise<number> {
4120
4683
  this._assertActive('drainToL2');
4121
- if (this._redisDisabled) return 0;
4684
+ if (this._redisDisabled || this.opts.l2WriteMode === 'read-only') return 0;
4122
4685
  try {
4123
- const client = await this.getRedis();
4124
4686
  const entries = this.l1.exportEntries([]);
4125
- const now = Date.now();
4126
4687
  if (entries.length === 0) return 0;
4127
-
4128
- const pl = client.pipeline();
4129
- for (const { key, entry } of entries) {
4130
- const remainingMs = entry.expiresAt - now;
4131
- if (remainingMs <= 0) continue;
4132
- const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1_000));
4133
- const s = JSON.stringify(entry.value);
4134
- const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
4135
- pl.setex(key, ttlSecs, stored);
4136
- }
4137
- await pl.exec();
4138
- return entries.length;
4688
+ let written = 0;
4689
+ await Promise.all(entries.map(async ({ key, entry }) => {
4690
+ const epoch = this._getKeyMutationEpoch(key);
4691
+ if (entry.expiresAt <= Date.now()) return;
4692
+ await this._writeRedisEntry(key, this.l1.resolveValue(entry), entry.expiresAt, entry.setAt ?? Date.now(),
4693
+ entry.tagVersions, entry.staleAt, entry.tags, entry.dependsOn, () => this._getKeyMutationEpoch(key) === epoch);
4694
+ written++;
4695
+ }));
4696
+ return written;
4139
4697
  } catch (err) {
4140
4698
  this.logger.debug('drainToL2: Redis unavailable', { error: (err as Error).message });
4141
4699
  return 0;
@@ -4172,7 +4730,7 @@ export class CacheService {
4172
4730
  // Fast path: L1 check (process-local, no network hop)
4173
4731
  if (this.l1.has(k)) return false;
4174
4732
 
4175
- if (!this._redisDisabled) {
4733
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
4176
4734
  try {
4177
4735
  const client = await this.getRedis();
4178
4736
  const serialized = JSON.stringify(value);
@@ -4192,7 +4750,7 @@ export class CacheService {
4192
4750
  const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
4193
4751
  const p = priority ?? inferPriority(cacheKey);
4194
4752
  this._bumpKeyMutation(k);
4195
- this._pendingDiskDeletes.delete(k);
4753
+ this._invalidateDiskKey(k);
4196
4754
  this.l1.set(k, value, ttlMs, p);
4197
4755
  this.counters.sets++;
4198
4756
  return true;
@@ -4228,7 +4786,7 @@ export class CacheService {
4228
4786
 
4229
4787
  let acquired = false;
4230
4788
 
4231
- if (!this._redisDisabled) {
4789
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
4232
4790
  // ── Acquire phase ONLY. Redis-side failures here may fall back to the
4233
4791
  // in-process mutex below. fn() is deliberately NOT inside this try: a
4234
4792
  // business exception must propagate to the caller exactly once — the old
@@ -4338,7 +4896,9 @@ export class CacheService {
4338
4896
  const gDiskBytes = meter.createObservableGauge('tricache.disk.bytes', { description: 'Current L1.5 disk size in bytes' });
4339
4897
  const gBloomFpr = meter.createObservableGauge('tricache.bloom.fpr', { description: 'Bloom filter false-positive rate' });
4340
4898
 
4341
- meter.addBatchObservableCallback((observableResult) => {
4899
+ const observables = [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr];
4900
+ const callback: ICacheBatchObservableCallback = (observableResult) => {
4901
+ if (this._destroyed) return;
4342
4902
  const stats = this.stats();
4343
4903
  const l1 = stats.l1;
4344
4904
  const disk = stats.disk;
@@ -4352,7 +4912,9 @@ export class CacheService {
4352
4912
  observableResult.observe(gDiskFiles, disk.files, attrs);
4353
4913
  observableResult.observe(gDiskBytes, disk.sizeKB * 1024, attrs);
4354
4914
  observableResult.observe(gBloomFpr, fpr, attrs);
4355
- }, [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr]);
4915
+ };
4916
+ meter.addBatchObservableCallback(callback, observables);
4917
+ this._otelCleanup = () => meter.removeBatchObservableCallback?.(callback, observables);
4356
4918
  } catch (err) {
4357
4919
  this.logger.warn('Failed to initialize OpenTelemetry metrics meter', { error: (err as Error).message });
4358
4920
  }
@@ -4642,8 +5204,22 @@ export class CacheService {
4642
5204
  /** Close Redis connections and stop all background timers. */
4643
5205
  async destroy(): Promise<void> {
4644
5206
  this._destroyed = true;
5207
+ this._fenceInvalidation();
5208
+ this._backplaneAvailable = false;
5209
+ this.l1.clear();
5210
+ try { this._otelCleanup?.(); } catch { /* fail-soft telemetry teardown */ }
5211
+ this._otelCleanup = null;
5212
+ this.tagVersions.clear();
5213
+ for (const dispose of this._backplaneDisposers.splice(0)) dispose();
4645
5214
  this._pendingDiskDeletes.clear();
4646
5215
  this._keyMutationEpochs.clear();
5216
+ this.inflight.clear();
5217
+ this.revalidating.clear();
5218
+ this._l1Counters.clear();
5219
+ this.tagIndex.clear();
5220
+ this.keyTags.clear();
5221
+ this.dependencyIndex.clear();
5222
+ this.keyDependencies.clear();
4647
5223
  const g = globalThis as Record<string, unknown>;
4648
5224
  const key = CacheService.globalKey(this.opts);
4649
5225
  if (g[key] === this) {
@@ -4664,13 +5240,16 @@ export class CacheService {
4664
5240
  this._workerPool = null;
4665
5241
  }
4666
5242
  if (this.subClient) {
5243
+ if (this.opts.redisSubClient) {
5244
+ try { await this.subClient.unsubscribe?.(this.backplaneChannel); } catch { /* caller connection remains owned by caller */ }
5245
+ }
4667
5246
  if (!this.opts.redisSubClient) {
4668
5247
  try { this.subClient.disconnect(); } catch { /* ok */ }
4669
5248
  }
4670
5249
  this.subClient = null;
4671
5250
  }
4672
5251
  if (this.streamClient) {
4673
- try { this.streamClient.disconnect(); } catch { /* ok */ }
5252
+ if (!this.opts.redisSubClient) try { this.streamClient.disconnect(); } catch { /* ok */ }
4674
5253
  this.streamClient = null;
4675
5254
  }
4676
5255
  if (this.redis) {
@@ -4701,4 +5280,4 @@ export class CacheService {
4701
5280
  return this.l1.getWTinyLfuStats();
4702
5281
  }
4703
5282
 
4704
- }
5283
+ }