tricache 1.0.1 → 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 (96) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-CREOp7MM.d.ts → cache-service-B108FzER.d.ts} +36 -4
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-MG7PN6MX.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-3I5L7K6I.js → chunk-VNRDL5RA.js} +102 -140
  10. package/dist/{chunk-JYQFQJNJ.js → chunk-WYF7NOAT.js} +1443 -609
  11. package/dist/cli.cjs +1367 -625
  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 +1370 -624
  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 +227 -123
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +201 -117
  26. package/dist/hono/index.cjs +1418 -644
  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-DSV2ve66.d.ts → hono-3rDMYVtY.d.ts} +16 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1514 -679
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +92 -43
  36. package/dist/index.cjs +1671 -790
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +39 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1454 -649
  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 +1512 -718
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +172 -99
  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-Dyip5wAl.d.ts → types-BA4pz1A0.d.cts} +24 -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 +106 -27
  61. package/src/cache-service.ts +802 -502
  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 +145 -97
  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 +62 -17
  74. package/src/http/fastify.ts +35 -21
  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 +131 -53
  84. package/src/next/index.ts +1 -0
  85. package/src/next/types.ts +21 -0
  86. package/src/prisma/index.ts +12 -1
  87. package/src/smart-memory-cache.ts +63 -26
  88. package/src/types.ts +25 -2
  89. package/src/utils/cgroup.ts +12 -0
  90. package/src/utils/deadline.ts +14 -0
  91. package/src/utils/diagnostics.ts +27 -0
  92. package/src/utils/redis-slot.ts +13 -0
  93. package/src/wasm/bloom-filter-wasm.ts +9 -4
  94. package/src/worker-pool.ts +17 -8
  95. package/src/wtiny-lfu.ts +20 -6
  96. 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,6 +46,7 @@ import {
45
46
  LockOptions,
46
47
  ICacheMeter,
47
48
  ICacheCounter,
49
+ ICacheBatchObservableCallback,
48
50
  IRedisDriver,
49
51
  WTinyLfuStats,
50
52
  CachePresetType,
@@ -56,8 +58,11 @@ import { CacheEncryption, EnvelopeEncryption, type EncryptionMode } from './encr
56
58
  import { SmartMemoryCache } from './smart-memory-cache';
57
59
  import { DiskTier, resolveDefaultDiskDir } from './disk-tier';
58
60
  import { TierLatencyWatchdog } from './latency-watchdog';
59
- import { resolveAutonomousL1MaxBytes, readCgroupMemoryLimit } from './utils/cgroup';
60
- 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';
61
66
  import { IpcTelemetryServer } from './ipc-telemetry.js';
62
67
  import {
63
68
  compressBuffer,
@@ -85,6 +90,52 @@ end
85
90
  return 0
86
91
  `;
87
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
+
88
139
  // ─── Snapshot constants ───────────────────────────────────────────────────────
89
140
 
90
141
  const SNAPSHOT_VERSION = 1;
@@ -562,7 +613,8 @@ export class CacheService {
562
613
  /** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
563
614
  private readonly keyTags = new Map<string, { tags: string[]; expiresAt: number }>();
564
615
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
565
- 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;
566
618
  /**
567
619
  * Dependency index: source glob pattern → Set of namespaced dependent keys.
568
620
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
@@ -593,9 +645,17 @@ export class CacheService {
593
645
  private subClient: AnyRedisClient | null = null;
594
646
  private streamClient: AnyRedisClient | null = null;
595
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> = [];
596
653
  private _destroyed = false;
597
654
  private readonly _pendingDiskDeletes = new Set<string>();
598
655
  private _globalEpoch = 0;
656
+ private _pendingSpillCount = 0;
657
+ private _suppressSpills = false;
658
+ private _diskCleanupScheduled = false;
599
659
  private readonly _keyMutationEpochs = new Map<string, number>();
600
660
  /**
601
661
  * Pattern tombstones for disk tier.
@@ -603,23 +663,27 @@ export class CacheService {
603
663
  * Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
604
664
  * pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
605
665
  */
606
- private readonly _patternTombstones: Array<{ prefix: string; createdAt: number }> = [];
666
+ private readonly _patternTombstones: Array<{ pattern: string; createdAt: number }> = [];
667
+ private _diskInvalidatedBefore = 0;
607
668
 
608
- private _addPatternTombstone(prefix: string): void {
669
+ private _addPatternTombstone(pattern: string): void {
609
670
  const now = Date.now();
610
671
  while (this._patternTombstones.length > 0 && (now - this._patternTombstones[0].createdAt > 3_600_000)) {
611
- this._patternTombstones.shift();
672
+ const forgotten = this._patternTombstones.shift()!;
673
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
612
674
  }
613
675
  if (this._patternTombstones.length >= 2_000) {
614
- this._patternTombstones.shift();
676
+ const forgotten = this._patternTombstones.shift()!;
677
+ this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, forgotten.createdAt);
615
678
  }
616
- this._patternTombstones.push({ prefix, createdAt: now });
679
+ this._patternTombstones.push({ pattern, createdAt: now });
617
680
  }
618
681
 
619
- private _isTombstonedByPattern(namespacedKey: string): boolean {
682
+ private _isTombstonedByPattern(namespacedKey: string, setAt = 0): boolean {
683
+ if (this._diskInvalidatedBefore > 0 && setAt <= this._diskInvalidatedBefore) return true;
620
684
  if (this._patternTombstones.length === 0) return false;
621
685
  for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
622
- if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
686
+ if (setAt <= this._patternTombstones[i].createdAt && this._matchesGlob(namespacedKey, this._patternTombstones[i].pattern)) {
623
687
  return true;
624
688
  }
625
689
  }
@@ -636,14 +700,94 @@ export class CacheService {
636
700
  const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
637
701
  this._keyMutationEpochs.set(namespacedKey, next);
638
702
  if (this._keyMutationEpochs.size > 50_000) {
639
- const oldest = this._keyMutationEpochs.keys().next().value;
640
- 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);
641
708
  }
642
709
  return next;
643
710
  }
644
711
 
645
- private _getKeyMutationEpoch(namespacedKey: string): number {
646
- 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);
647
791
  }
648
792
 
649
793
  private _removeKeyTags(namespacedKey: string): void {
@@ -680,7 +824,7 @@ export class CacheService {
680
824
  }
681
825
 
682
826
  private _handleL1Eviction(namespacedKey: string, reason: EvictionReason): void {
683
- const spilledToDisk = !this._diskDisabled && (
827
+ const spilledToDisk = !this._diskDisabled && !this._suppressSpills && (
684
828
  reason === 'capacity' ||
685
829
  reason === 'category' ||
686
830
  reason === 'rebalance' ||
@@ -692,15 +836,15 @@ export class CacheService {
692
836
  }
693
837
  }
694
838
 
695
- private _removePrefixFromIndices(prefix: string): void {
839
+ private _removePatternFromIndices(pattern: string): void {
696
840
  for (const k of Array.from(this.keyTags.keys())) {
697
- if (k.startsWith(prefix)) this._removeKeyTags(k);
841
+ if (this._matchesGlob(k, pattern)) this._removeKeyTags(k);
698
842
  }
699
843
  for (const k of Array.from(this.keyDependencies.keys())) {
700
- if (k.startsWith(prefix)) this._removeKeyDependencies(k);
844
+ if (this._matchesGlob(k, pattern)) this._removeKeyDependencies(k);
701
845
  }
702
846
  for (const k of Array.from(this._l1Counters.keys())) {
703
- if (k.startsWith(prefix)) this._l1Counters.delete(k);
847
+ if (this._matchesGlob(k, pattern)) this._l1Counters.delete(k);
704
848
  }
705
849
  }
706
850
 
@@ -721,11 +865,14 @@ export class CacheService {
721
865
  const heap = v8.getHeapStatistics();
722
866
  const heapUsed = heap.used_heap_size / heap.heap_size_limit;
723
867
  const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0
724
- ? process.memoryUsage().rss / this._cgroupMemoryLimit
868
+ ? (readCgroupMemoryUsage() ?? process.memoryUsage().rss) / this._cgroupMemoryLimit
725
869
  : 0;
726
870
  const used = Math.max(heapUsed, cgroupUsed);
727
871
  if (used >= this.opts.oomHeapThreshold) {
728
- const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
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; }
729
876
  this.counters.oomEvictions++;
730
877
  this.counters.oomLastAt = Date.now();
731
878
  this.logger.warn('tricache OOM guard: emergency L1 eviction', {
@@ -994,12 +1141,18 @@ export class CacheService {
994
1141
  admissionPolicy: this.opts.l1AdmissionPolicy,
995
1142
  codec: this.codec,
996
1143
  diskSpill: (key: string, entry: SmartCacheEntry) => {
997
- 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++;
998
1148
  // Defer disk.save() entirely to the next event-loop tick so the synchronous
999
1149
  // preamble inside save() (SHA-256 keyToPath + msgpackr pack) does not block
1000
1150
  // the l1.set() → smartEvict → diskSpill call chain. Mirrors what the
1001
1151
  // backplane handler already does for remote invalidations.
1002
- 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
+ });
1003
1156
  },
1004
1157
  onEviction: (key: string, reason: EvictionReason) => {
1005
1158
  this._handleL1Eviction(key, reason);
@@ -1095,7 +1248,8 @@ export class CacheService {
1095
1248
  this.instanceId = crypto.randomBytes(8).toString('hex');
1096
1249
  this.backplaneChannel = `tricache:inv${ns ? ':' + ns : ''}`;
1097
1250
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || 'default'}}`;
1098
- 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 }));
1099
1253
 
1100
1254
  // Auto-warm from remote snapshot or L2 if configured; ready() waits for completion.
1101
1255
  const startupPromises: Promise<void>[] = [];
@@ -1108,9 +1262,11 @@ export class CacheService {
1108
1262
  if (this.opts.warmKeys) {
1109
1263
  startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => undefined));
1110
1264
  }
1111
- if (startupPromises.length > 0) {
1112
- this._readyPromise = Promise.all(startupPromises).then(() => undefined);
1113
- }
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);
1114
1270
 
1115
1271
  // Native OpenTelemetry metrics integration
1116
1272
  if (this.opts.meter) {
@@ -1126,7 +1282,7 @@ export class CacheService {
1126
1282
  if (typeof prop === 'string' && typeof value === 'number' && typeof oldVal === 'number') {
1127
1283
  const diff = value - oldVal;
1128
1284
  if (diff > 0 && otel[prop]) {
1129
- otel[prop]!.add(diff, nsAttr);
1285
+ try { otel[prop]!.add(diff, nsAttr); } catch { /* Telemetry must never fail a cache operation. */ }
1130
1286
  }
1131
1287
  }
1132
1288
  return ok;
@@ -1227,7 +1383,7 @@ export class CacheService {
1227
1383
 
1228
1384
  // Singleton already exists for this namespace — detect & surface divergence.
1229
1385
  const existing = g[key] as CacheService;
1230
- const diff = CacheService.optionsDiff(options ?? {}, existing.options);
1386
+ const diff = CacheService.optionsDiff(options ?? {}, existing.opts);
1231
1387
  if (diff.length > 0) {
1232
1388
  existing.bumpSingletonDivergence();
1233
1389
  const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || '(default)'}' — ignoring divergent options: ${diff.join(', ')}`;
@@ -1249,10 +1405,11 @@ export class CacheService {
1249
1405
  'redisClusterNodes', 'redisSentinel', 'encryptionKey', 'encryptionMode',
1250
1406
  'l1MaxBytes', 'l1MaxEntries', 'namespace', 'frozen', 'adaptiveTtl',
1251
1407
  'l2WriteMode', 'instanceName', 'invalidationBackplane', 'awaitInvalidationBackplane', 'lockFailClosed',
1408
+ 'tagStrategy', 'cloneStrategy', 'compression', 'backplaneMode', 'redisProtocol', 'failClosed',
1252
1409
  ];
1253
1410
 
1254
1411
  /** Returns the names of options that differ between `a` and the live `b`. */
1255
- private static optionsDiff(a: CacheOptions, b: CacheOptions): string[] {
1412
+ private static optionsDiff(a: CacheOptions, b: Record<string, unknown>): string[] {
1256
1413
  const out: string[] = [];
1257
1414
  for (const k of CacheService.DIVERGENT_KEYS) {
1258
1415
  const av = a[k];
@@ -1272,12 +1429,12 @@ export class CacheService {
1272
1429
  this.counters.singletonDivergences++;
1273
1430
  }
1274
1431
 
1275
- /** Read-only view of the options the singleton was constructed with. */
1432
+ /** Sanitized diagnostic view; retain the original options/adapters to reuse configuration. */
1276
1433
  get options(): CacheOptions {
1277
1434
  const o = this.opts;
1278
1435
  return {
1279
1436
  namespace: o.namespace,
1280
- 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) },
1281
1438
  l1MaxBytes: o.l1MaxBytes,
1282
1439
  l1MaxEntries: o.l1MaxEntries,
1283
1440
  redisHost: o.redisHost,
@@ -1298,8 +1455,8 @@ export class CacheService {
1298
1455
  awaitInvalidationBackplane: o.awaitInvalidationBackplane,
1299
1456
  lockFailClosed: o.lockFailClosed,
1300
1457
  strictSingleton: o.strictSingleton,
1301
- remoteSnapshot: o.remoteSnapshot,
1302
- crossRegion: o.crossRegion,
1458
+ remoteSnapshot: redactDiagnostics(o.remoteSnapshot),
1459
+ crossRegion: redactDiagnostics(o.crossRegion),
1303
1460
  } as CacheOptions;
1304
1461
  }
1305
1462
 
@@ -1385,11 +1542,15 @@ export class CacheService {
1385
1542
  if (this.opts.redisClient && typeof this.opts.redisClient.duplicate === 'function') {
1386
1543
  return this.opts.redisClient.duplicate();
1387
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
+ }
1388
1548
  if (this.opts.redisClusterNodes?.length) {
1389
1549
  return new RedisCluster(this.opts.redisClusterNodes, {
1390
1550
  redisOptions: {
1391
1551
  tls: this.opts.redisTls ? {} : undefined,
1392
1552
  connectTimeout: 10_000,
1553
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
1393
1554
  maxRetriesPerRequest: null as unknown as number,
1394
1555
  ...(this.opts.redisProtocol && { protocol: this.opts.redisProtocol }),
1395
1556
  },
@@ -1400,6 +1561,7 @@ export class CacheService {
1400
1561
  name: this.opts.redisSentinel.name,
1401
1562
  tls: this.opts.redisTls ? {} : undefined,
1402
1563
  connectTimeout: 10_000,
1564
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
1403
1565
  lazyConnect: true,
1404
1566
  maxRetriesPerRequest: null as unknown as number,
1405
1567
  enableAutoPipelining: false,
@@ -1412,6 +1574,7 @@ export class CacheService {
1412
1574
  port: this.opts.redisPort,
1413
1575
  tls: this.opts.redisTls ? {} : undefined,
1414
1576
  connectTimeout: 10_000,
1577
+ commandTimeout: Math.max(this.opts.redisCommandTimeoutMs ?? 2500, this.opts.backplaneStreamBlockMs + 500),
1415
1578
  lazyConnect: true,
1416
1579
  maxRetriesPerRequest: null as unknown as number,
1417
1580
  enableAutoPipelining: false,
@@ -1422,33 +1585,40 @@ export class CacheService {
1422
1585
  }
1423
1586
  }
1424
1587
 
1425
- 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> {
1426
1594
  if (!this.opts.invalidationBackplane || this._redisDisabled) return;
1427
1595
 
1428
1596
  if (this.opts.backplaneMode === 'stream') {
1429
1597
  if (this.streamClient) return;
1430
- void this._startStreamConsumer();
1598
+ await this._startStreamConsumer();
1431
1599
  return;
1432
1600
  }
1433
1601
 
1434
1602
  if (this.subClient) return;
1435
1603
 
1436
1604
  const sub = this.createDedicatedRedisClient();
1605
+ this.subClient = sub;
1437
1606
 
1438
- sub.on('error', (e: Error) => {
1607
+ this._listenBackplane(sub, 'error', (e: Error) => {
1439
1608
  this._checkAndLogResp3Hint(e);
1440
1609
  this.logger.debug('Backplane subscriber error', { error: e.message });
1441
1610
  });
1442
1611
 
1443
1612
  // ── Staleness fence — track disconnect time ──────────────────────
1444
- sub.on('close', () => {
1613
+ this._listenBackplane(sub, 'close', () => {
1614
+ this._backplaneAvailable = false;
1445
1615
  if (this._subDisconnectedAt === null) {
1446
1616
  this._subDisconnectedAt = Date.now();
1447
1617
  this.logger.debug('Backplane: subscriber disconnected', { at: this._subDisconnectedAt });
1448
1618
  }
1449
1619
  });
1450
1620
 
1451
- sub.on('ready', () => {
1621
+ this._listenBackplane(sub, 'ready', () => {
1452
1622
  if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
1453
1623
  const gapMs = Date.now() - this._subDisconnectedAt;
1454
1624
  if (gapMs > this.opts.backplaneMaxStalenessMs) {
@@ -1460,54 +1630,70 @@ export class CacheService {
1460
1630
  }
1461
1631
  this._subDisconnectedAt = null;
1462
1632
  }
1633
+ if (!this._destroyed) this._backplaneAvailable = true;
1463
1634
  });
1464
1635
 
1465
1636
  const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
1466
1637
 
1467
1638
  if (isClusterSharded) {
1468
- sub.on('smessage', (_channel: string, message: string) => {
1639
+ this._listenBackplane(sub, 'smessage', (_channel: string, message: string) => {
1469
1640
  this._handleBackplaneMessage(message);
1470
1641
  });
1471
- (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> })
1472
1644
  .ssubscribe(this.backplaneChannel)
1473
1645
  .then(() => this.logger.info('Backplane: sharded subscribed', {
1474
1646
  channel: this.backplaneChannel, instanceId: this.instanceId,
1475
- }))
1476
- .catch((err: Error) => this.logger.warn('Backplane: sharded subscribe failed', {
1477
- error: err.message,
1478
1647
  }));
1479
1648
  } else {
1480
- sub.on('message', (_channel: string, message: string) => {
1649
+ this._listenBackplane(sub, 'message', (_channel: string, message: string) => {
1481
1650
  this._handleBackplaneMessage(message);
1482
1651
  });
1483
- 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)
1484
1655
  .then(() => this.logger.info('Backplane: subscribed', {
1485
1656
  channel: this.backplaneChannel, instanceId: this.instanceId,
1486
- }))
1487
- .catch((err: Error) => this.logger.warn('Backplane: subscribe failed', {
1488
- error: err.message,
1489
1657
  }));
1490
1658
  }
1491
1659
 
1492
- 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';
1493
1675
  }
1494
1676
 
1495
1677
  private async _startStreamConsumer(): Promise<void> {
1678
+ this._streamRecovering ||= this._lastStreamId !== '$' && this._lastStreamId !== '0-0';
1496
1679
  const sub = this.streamClient ?? this.createDedicatedRedisClient();
1497
1680
  this.streamClient = sub;
1681
+ if (typeof sub.xread !== 'function') throw new Error('backplaneMode: stream requires a driver supporting XREAD');
1498
1682
 
1499
1683
  if (typeof (sub as any).on === 'function') {
1500
- sub.on('error', (e: Error) =>
1684
+ this._listenBackplane(sub, 'error', (e: Error) =>
1501
1685
  this.logger.debug('Backplane stream consumer error', { error: e.message }));
1502
1686
 
1503
- sub.on('close', () => {
1687
+ this._listenBackplane(sub, 'close', () => {
1688
+ this._streamRecovering = true;
1689
+ this._backplaneAvailable = false;
1504
1690
  if (this._subDisconnectedAt === null) {
1505
1691
  this._subDisconnectedAt = Date.now();
1506
1692
  this.logger.debug('Backplane stream: consumer disconnected', { at: this._subDisconnectedAt });
1507
1693
  }
1508
1694
  });
1509
1695
 
1510
- sub.on('ready', () => {
1696
+ this._listenBackplane(sub, 'ready', () => {
1511
1697
  if (this._subDisconnectedAt !== null) {
1512
1698
  this.logger.debug('Backplane stream: consumer reconnected, resuming stream read', { lastId: this._lastStreamId });
1513
1699
  this._subDisconnectedAt = null;
@@ -1515,31 +1701,71 @@ export class CacheService {
1515
1701
  });
1516
1702
  }
1517
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
+
1518
1751
  // Continuous async worker loop
1519
1752
  const runLoop = async () => {
1520
1753
  while (!this._destroyed && !this._redisDisabled) {
1521
1754
  try {
1755
+ if (!initialized) await initialize();
1756
+ if (this._destroyed) break;
1757
+ await checkGap();
1522
1758
  const res = await (sub as any).xread(
1523
1759
  'BLOCK', this.opts.backplaneStreamBlockMs,
1524
1760
  'STREAMS', this.backplaneStreamKey, this._lastStreamId,
1525
1761
  ) as Array<[string, Array<[string, string[]]>]> | null;
1526
1762
 
1527
1763
  if (this._destroyed) break;
1764
+ this._backplaneAvailable = true;
1528
1765
 
1529
1766
  if (res && res.length > 0) {
1530
- for (const [, entries] of res) {
1531
- if (entries.length > 0) {
1532
- if (this._lastStreamId !== '$') {
1533
- this.counters.streamReplays++;
1534
- }
1535
-
1536
- for (const [id, fields] of entries) {
1537
- this._lastStreamId = id;
1538
- this.counters.streamEntriesReceived++;
1539
- this._processStreamEntry(fields);
1540
- }
1541
- }
1542
- }
1767
+ apply(res);
1768
+ this._backplaneAvailable = true;
1543
1769
  } else {
1544
1770
  // Idle timeout without messages — yield briefly before next long-poll
1545
1771
  await new Promise(resolve => setTimeout(resolve, 10));
@@ -1548,10 +1774,9 @@ export class CacheService {
1548
1774
  if (this._destroyed) break;
1549
1775
  const msg = (err as Error).message ?? '';
1550
1776
  if (msg.includes('NOGROUP') || msg.includes('smaller than') || msg.includes('trimmed')) {
1551
- this.counters.streamGaps++;
1552
- this.l1.clear();
1553
- this._lastStreamId = '$';
1777
+ this._resetAfterStreamGap();
1554
1778
  }
1779
+ this._backplaneAvailable = false;
1555
1780
  await new Promise(resolve => setTimeout(resolve, 200));
1556
1781
  }
1557
1782
  }
@@ -1589,7 +1814,8 @@ export class CacheService {
1589
1814
  op === 'tag_incr' ||
1590
1815
  op === 'tag_pattern_incr' ||
1591
1816
  op === 'tag_pattern_del';
1592
- if (!validOp || typeof key !== 'string' || !key || typeof src !== 'string') {
1817
+ if (!validOp || typeof key !== 'string' || !key || typeof src !== 'string' || !src ||
1818
+ ((op === 'del' || op === 'del-glob') && this._namespace && !key.startsWith(`${this._namespace}:`))) {
1593
1819
  this.logger.warn('Backplane: rejected invalid stream entry', {
1594
1820
  op: String(op).slice(0, 40),
1595
1821
  key: typeof key === 'string' ? key.slice(0, 100).replace(/[\r\n\t]/g, ' ') : String(key),
@@ -1597,11 +1823,11 @@ export class CacheService {
1597
1823
  return;
1598
1824
  }
1599
1825
 
1600
- // parseInt('12abc34') → NaN — reject instead of poisoning the version map.
1826
+ // Reject partial numeric strings rather than truncating them with parseInt().
1601
1827
  let tagVersion: number | undefined;
1602
1828
  if (tagVersionRaw !== undefined) {
1603
- const parsed = parseInt(tagVersionRaw, 10);
1604
- if (!Number.isFinite(parsed)) {
1829
+ const parsed = Number(tagVersionRaw);
1830
+ if (!Number.isSafeInteger(parsed) || parsed < 0) {
1605
1831
  this.logger.warn('Backplane: rejected stream entry with non-numeric tagVersion', { key });
1606
1832
  return;
1607
1833
  }
@@ -1622,16 +1848,10 @@ export class CacheService {
1622
1848
  this.l1.delete(key);
1623
1849
  this._bumpKeyMutation(key);
1624
1850
  this.inflight.delete(key);
1625
- this._pendingDiskDeletes.add(key);
1626
- setImmediate(() => {
1627
- try {
1628
- if (!this._diskDisabled) this.disk.delete(key);
1629
- } finally {
1630
- this._pendingDiskDeletes.delete(key);
1631
- }
1632
- });
1851
+ this._invalidateDiskKey(key);
1633
1852
  this._cascadeDependencies(key);
1634
1853
  } else if (op === 'del-glob') {
1854
+ this._fenceInvalidation();
1635
1855
  this.l1.deletePattern(key);
1636
1856
  const pfx = key.endsWith('*') ? key.slice(0, -1) : key;
1637
1857
  for (const liveKey of this.l1.liveKeys()) {
@@ -1645,12 +1865,22 @@ export class CacheService {
1645
1865
  this.inflight.delete(inflightKey);
1646
1866
  }
1647
1867
  }
1648
- 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
+ }
1649
1877
  } else if (op === 'tag_incr') {
1878
+ this._fenceInvalidation();
1650
1879
  const tag = key;
1651
1880
  const ver = typeof tagVersion === 'number' ? tagVersion : ((this.tagVersions.get(tag)?.version ?? 0) + 1);
1652
1881
  this._setLocalTagVersion(tag, ver, performance.now());
1653
1882
  } else if (op === 'tag_pattern_incr') {
1883
+ this._fenceInvalidation();
1654
1884
  const pattern = key;
1655
1885
  const now = performance.now();
1656
1886
  for (const [tag, info] of this.tagVersions) {
@@ -1670,6 +1900,7 @@ export class CacheService {
1670
1900
  }
1671
1901
  }, 0);
1672
1902
  } else if (op === 'tag_pattern_del') {
1903
+ this._fenceInvalidation();
1673
1904
  const pattern = key;
1674
1905
  const matchedTagKeys: string[] = [];
1675
1906
  const prefix = this.nk('_tag_:');
@@ -1680,14 +1911,7 @@ export class CacheService {
1680
1911
  for (const k of members) {
1681
1912
  this.l1.delete(k);
1682
1913
  this._bumpKeyMutation(k);
1683
- this._pendingDiskDeletes.add(k);
1684
- setImmediate(() => {
1685
- try {
1686
- if (!this._diskDisabled) this.disk.delete(k);
1687
- } finally {
1688
- this._pendingDiskDeletes.delete(k);
1689
- }
1690
- });
1914
+ this._invalidateDiskKey(k);
1691
1915
  }
1692
1916
  }
1693
1917
  }
@@ -1733,6 +1957,7 @@ export class CacheService {
1733
1957
  isCrossRegionRelay = false,
1734
1958
  isExplicitInvalidation = false,
1735
1959
  ): Promise<void> {
1960
+ if (this.opts.l2WriteMode === 'read-only') return;
1736
1961
  if (!isCrossRegionRelay && this.opts.crossRegion) {
1737
1962
  const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
1738
1963
  if (shouldBroadcast) {
@@ -1819,13 +2044,13 @@ export class CacheService {
1819
2044
  timestamp: Date.now(),
1820
2045
  namespace: this._namespace || undefined,
1821
2046
  };
1822
- this.counters.crossRegionSent++;
1823
2047
  await cr.relay.broadcast(event);
2048
+ this.counters.crossRegionSent++;
1824
2049
  this.logger.debug('Cross-region invalidation broadcast', { op, key, region: cr.currentRegion });
1825
2050
  } catch (err) {
1826
- this.counters.crossRegionSent = Math.max(0, this.counters.crossRegionSent - 1);
1827
2051
  this.counters.crossRegionErrors++;
1828
2052
  this.logger.warn('Cross-region invalidation broadcast failed', { error: (err as Error).message });
2053
+ if (this.opts.awaitInvalidationBackplane) throw err;
1829
2054
  }
1830
2055
  }
1831
2056
 
@@ -1837,13 +2062,14 @@ export class CacheService {
1837
2062
  * Returns true if the event was accepted and applied, or false if ignored/deduplicated.
1838
2063
  */
1839
2064
  async receiveCrossRegionInvalidation(event: CrossRegionInvalidationEvent): Promise<boolean> {
2065
+ this._assertActive('receiveCrossRegionInvalidation');
1840
2066
  const cr = this.opts.crossRegion;
1841
2067
  if (!cr) return false;
1842
2068
 
1843
2069
  // Reject malformed event
1844
- if (!event || typeof event !== 'object' || !event.id || !event.originRegion || !event.op || !event.key) {
2070
+ if (!isCrossRegionInvalidationEvent(event)) {
1845
2071
  this.counters.crossRegionErrors++;
1846
- this.logger.warn('Cross-region: rejected invalid event payload', { event });
2072
+ this.logger.warn('Cross-region: rejected invalid event payload');
1847
2073
  return false;
1848
2074
  }
1849
2075
 
@@ -1858,21 +2084,56 @@ export class CacheService {
1858
2084
  this.counters.crossRegionDeduplicated++;
1859
2085
  return false;
1860
2086
  }
1861
- this._markCrossRegionEventSeen(event.id);
1862
2087
 
1863
2088
  // If namespaces don't match, ignore
1864
2089
  if (event.namespace !== undefined && event.namespace !== (this._namespace || undefined)) {
1865
2090
  return false;
1866
2091
  }
2092
+ if ((event.op === 'del' || event.op === 'del-glob') && this._namespace && !event.key.startsWith(`${this._namespace}:`)) return false;
2093
+ this._markCrossRegionEventSeen(event.id);
1867
2094
 
1868
2095
  this.counters.crossRegionReceived++;
1869
2096
 
1870
- // 1. Apply to local L1 and disk
1871
- this._applyInvalidationEvent(event.op, event.key, event.tagVersion);
1872
-
1873
- // 2. Propagate to local Redis backplane so other instances in THIS region also invalidate,
1874
- // passing isCrossRegionRelay = true to prevent re-broadcasting cross-region
1875
- 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
+ }
1876
2137
 
1877
2138
  this.logger.info('Cross-region invalidation applied', {
1878
2139
  op: event.op,
@@ -1889,11 +2150,11 @@ export class CacheService {
1889
2150
  const oldestKey = this.tagVersions.keys().next().value;
1890
2151
  if (oldestKey !== undefined) this.tagVersions.delete(oldestKey);
1891
2152
  }
1892
- this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
2153
+ this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now, refreshEpoch: this._tagRefreshEpoch });
1893
2154
  }
1894
2155
 
1895
2156
  private async _isGenerationalEntryStale(tagVersions?: Record<string, number>): Promise<boolean> {
1896
- if (this.opts.tagStrategy !== 'generational' || !tagVersions) return false;
2157
+ if (!tagVersions) return false;
1897
2158
  const tags = Object.keys(tagVersions);
1898
2159
  if (tags.length === 0) return false;
1899
2160
  const currentVers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
@@ -1907,12 +2168,22 @@ export class CacheService {
1907
2168
  if (keys.length === 0) return;
1908
2169
  const CHUNK_SIZE = 1_000;
1909
2170
  if (client instanceof RedisCluster) {
1910
- for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
1911
- const chunk = keys.slice(i, i + CHUNK_SIZE);
1912
- const pl = client.pipeline();
1913
- for (const k of chunk) pl.del(k);
1914
- await pl.exec();
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);
1915
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
+ }));
1916
2187
  return;
1917
2188
  }
1918
2189
  for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
@@ -1924,11 +2195,16 @@ export class CacheService {
1924
2195
  private async _parseGenerationalRedisHash<T>(
1925
2196
  k: string,
1926
2197
  hashData: Record<string, string>,
1927
- ): Promise<{ value?: T; tagVersions?: Record<string, number>; stale: boolean } | null> {
2198
+ ): Promise<RedisCacheEntry<T> | null> {
1928
2199
  if (!hashData || !hashData.d) return null;
1929
2200
  let storedTagVersions: Record<string, number> = {};
1930
2201
  if (hashData.tv) {
1931
- try { storedTagVersions = JSON.parse(hashData.tv); } catch { /* ignore */ }
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; }
1932
2208
  }
1933
2209
  if (await this._isGenerationalEntryStale(storedTagVersions)) {
1934
2210
  const setAtMs = parseInt(hashData.t, 10) || 0;
@@ -1936,23 +2212,46 @@ export class CacheService {
1936
2212
  return { stale: true };
1937
2213
  }
1938
2214
  const value = await this._decryptAndDeserialize<T>(hashData.d);
1939
- return { value, tagVersions: storedTagVersions, stale: false };
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 };
1940
2228
  }
1941
2229
 
1942
2230
  private async _readRedisEntry<T>(
1943
2231
  client: AnyRedisClient,
1944
2232
  k: string,
1945
2233
  allowAutoPipeline = false,
1946
- ): Promise<{ value?: T; tagVersions?: Record<string, number>; stale: boolean } | null> {
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
+ };
1947
2246
  if (this.opts.tagStrategy === 'generational' && typeof (client as any).hgetall === 'function') {
1948
2247
  try {
1949
- const hashData = await client.hgetall(k);
2248
+ const { raw: hashData, ttlMs } = await read(true);
1950
2249
  if (typeof hashData === 'string') {
1951
2250
  const value = await this._decryptAndDeserialize<T>(hashData);
1952
- return { value, stale: false };
2251
+ return withExpiry({ value, stale: false }, ttlMs);
1953
2252
  }
1954
2253
  if (hashData && hashData.d) {
1955
- return await this._parseGenerationalRedisHash<T>(k, hashData);
2254
+ return withExpiry(await this._parseGenerationalRedisHash<T>(k, hashData), ttlMs);
1956
2255
  }
1957
2256
  return null;
1958
2257
  } catch (err) {
@@ -1962,32 +2261,168 @@ export class CacheService {
1962
2261
  }
1963
2262
  }
1964
2263
 
1965
- const raw = (allowAutoPipeline && this.opts.autoPipeline && this.pipeliner)
1966
- ? await this.pipeliner.get(k)
1967
- : await client.get(k);
2264
+ const { raw, ttlMs } = await read(false);
1968
2265
  if (raw == null) return null;
2266
+ if (typeof raw !== 'string') return null;
1969
2267
  const value = await this._decryptAndDeserialize<T>(raw);
1970
- return { value, stale: false };
2268
+ return withExpiry({ value, stale: false }, ttlMs);
1971
2269
  }
1972
2270
 
1973
2271
  private async _getTagVersion(tag: string): Promise<number> {
1974
2272
  const now = performance.now();
1975
2273
  const local = this.tagVersions.get(tag);
1976
- if (local && (now - local.lastSyncedAt < this.opts.tagVersionTtlMs)) {
2274
+ if (local && (local.refreshEpoch ?? 0) === this._tagRefreshEpoch && (now - local.lastSyncedAt < this.opts.tagVersionTtlMs)) {
1977
2275
  return local.version;
1978
2276
  }
1979
2277
  if (!this._redisDisabled) {
1980
2278
  try {
1981
2279
  const client = await this.getRedis();
1982
2280
  const raw = await client.get(this.nk(`tag_ver:${tag}`));
1983
- 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
+ }
1984
2288
  this._setLocalTagVersion(tag, version, now);
2289
+ this.cb.onSuccess();
1985
2290
  return version;
1986
2291
  } catch {
1987
2292
  /* fallback to local */
1988
2293
  }
1989
2294
  }
1990
- 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();
1991
2426
  }
1992
2427
 
1993
2428
  private _deleteIfStale(k: string, setAtMs: number): void {
@@ -2042,7 +2477,7 @@ export class CacheService {
2042
2477
  } else {
2043
2478
  plain = raw;
2044
2479
  }
2045
- return JSON.parse(plain) as T;
2480
+ return plain === 'undefined' ? undefined as T : JSON.parse(plain) as T;
2046
2481
  }
2047
2482
 
2048
2483
  /**
@@ -2263,7 +2698,8 @@ export class CacheService {
2263
2698
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
2264
2699
  if (entries.length === 0) return;
2265
2700
 
2266
- 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 };
2267
2703
  const packed = this.codec.encode(payload);
2268
2704
  const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
2269
2705
  const dest = altPath ?? this.opts.snapshotPath;
@@ -2308,6 +2744,7 @@ export class CacheService {
2308
2744
  const snapshot = this.codec.decode(buf) as {
2309
2745
  version?: number; writtenAt?: number;
2310
2746
  entries?: Array<{ key: string; entry: SmartCacheEntry }>;
2747
+ streamId?: string;
2311
2748
  };
2312
2749
 
2313
2750
  if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
@@ -2337,6 +2774,9 @@ export class CacheService {
2337
2774
  }
2338
2775
 
2339
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);
2340
2780
  this.logger.info('Cache snapshot loaded (L1 is warm)', {
2341
2781
  loaded, total: snapshot.entries.length,
2342
2782
  sizeKB: this.l1.getStats().sizeKB,
@@ -2360,7 +2800,8 @@ export class CacheService {
2360
2800
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
2361
2801
  if (entries.length === 0) return false;
2362
2802
 
2363
- 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 };
2364
2805
  const packed = this.codec.encode(payload);
2365
2806
  let final: Buffer;
2366
2807
  if (this.opts.remoteSnapshot.envelope) {
@@ -2393,14 +2834,17 @@ export class CacheService {
2393
2834
  async loadRemoteSnapshot(): Promise<number> {
2394
2835
  if (!this.opts.remoteSnapshot) return 0;
2395
2836
  const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
2837
+ const epoch = this._globalEpoch;
2396
2838
  try {
2397
2839
  const raw = await this.opts.remoteSnapshot.adapter.get();
2840
+ if (this._destroyed || this._globalEpoch !== epoch) return 0;
2398
2841
  if (!raw || raw.length === 0) {
2399
2842
  this.logger.debug('Remote snapshot not found or empty — starting cold');
2400
2843
  return 0;
2401
2844
  }
2402
2845
 
2403
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');
2404
2848
  let buf: Buffer;
2405
2849
  try {
2406
2850
  if (EnvelopeEncryption.isEnvelope(rawBuf)) {
@@ -2421,6 +2865,7 @@ export class CacheService {
2421
2865
  version?: number;
2422
2866
  writtenAt?: number;
2423
2867
  entries?: Array<{ key: string; entry: SmartCacheEntry }>;
2868
+ streamId?: string;
2424
2869
  };
2425
2870
 
2426
2871
  if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
@@ -2453,7 +2898,12 @@ export class CacheService {
2453
2898
  return 0;
2454
2899
  }
2455
2900
 
2456
- 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);
2457
2907
  this.counters.remoteSnapshotDownloads++;
2458
2908
  this.counters.remoteSnapshotLastDownloadedAt = Date.now();
2459
2909
  this.logger.info('Remote cache snapshot loaded (L1 hydrated)', {
@@ -2507,6 +2957,8 @@ export class CacheService {
2507
2957
  * On an L1/L2 hit the tags are already registered — this field is a no-op for hits.
2508
2958
  */
2509
2959
  tags?: string[];
2960
+ /** Dependency patterns registered when a miss populates the entry. */
2961
+ dependsOn?: string[];
2510
2962
  } = {},
2511
2963
  ): Promise<T> {
2512
2964
  this._assertActive('get');
@@ -2536,7 +2988,7 @@ export class CacheService {
2536
2988
 
2537
2989
  if (isGenerationalStale) {
2538
2990
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
2539
- } else {
2991
+ } else if (!l1Hit.isStale || optSwr > 0) {
2540
2992
  if (l1Hit.isStale) {
2541
2993
  const swrGraceMs = optSwr * 1_000;
2542
2994
  if (swrGraceMs > 0 && !this.revalidating.has(k)) {
@@ -2618,55 +3070,26 @@ export class CacheService {
2618
3070
  span.setAttribute('cache.hit', true)
2619
3071
  .setAttribute('cache.stampede_coalesced', true)
2620
3072
  .end();
2621
- return existing as Promise<T>;
3073
+ return this._prepareReadValue(await existing as T);
2622
3074
  }
2623
3075
 
2624
3076
  const mutationEpochAtStart = this._getKeyMutationEpoch(k);
2625
- const executionPromise: Promise<T> = (async () => {
3077
+ const executionPromise: Promise<T> = Promise.resolve().then(async () => {
2626
3078
  try {
2627
3079
  // ── Tier 1.5: disk tier (evicted L1 entries) — protected by latency watchdog ──
2628
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
2629
- if (this._isTombstonedByPattern(k)) {
2630
- try { this.disk.delete(k); } catch { /* ok */ }
2631
- } else {
2632
- const isDiskAllowed = this.watchdog.isDiskAllowed();
2633
- if (isDiskAllowed) {
2634
- const diskStart = performance.now();
2635
- const diskHit = this.disk.load(k);
2636
- const diskElapsed = performance.now() - diskStart;
2637
- this.watchdog.recordDisk(diskElapsed);
2638
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
2639
-
2640
- if (diskHit !== null) {
2641
- const isDiskStale = await this._isGenerationalEntryStale(diskHit.tagVersions);
2642
-
2643
- if (isDiskStale) {
2644
- this.disk.delete(k);
2645
- } else {
2646
- const promoted = this.l1.importEntries(
2647
- [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
2648
- this.opts.forbiddenSnapshotPrefixes,
2649
- );
2650
- if (promoted > 0) {
2651
- const l1Check = this.l1.get(k);
2652
- if (l1Check !== null) {
2653
- this.counters.diskHits++;
2654
- this.opts.onHit?.(cacheKey, 'disk');
2655
- this.logger.debug('L1.5 hit (disk → L1)', { cacheKey });
2656
- span.setAttribute('cache.hit', true)
2657
- .setAttribute('cache.item.tier', 'disk')
2658
- .setAttribute('cache.hit_tier', 'disk');
2659
- if (this.opts.frozen) deepFreeze(l1Check.value);
2660
- return (this.opts.cloneStrategy === 'structuredClone' && l1Check.value != null && typeof l1Check.value === 'object')
2661
- ? structuredClone(l1Check.value) as T
2662
- : l1Check.value as T;
2663
- }
2664
- }
2665
- }
2666
- }
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])));
2667
3090
  }
3091
+ return diskHit.value;
2668
3092
  }
2669
- }
2670
3093
 
2671
3094
  // ── Tier 2: Redis (distributed, production-only by default) ──
2672
3095
  if (!this._redisDisabled) {
@@ -2677,31 +3100,30 @@ export class CacheService {
2677
3100
  const redisElapsed = performance.now() - redisStart;
2678
3101
  this.watchdog.recordRedis(redisElapsed);
2679
3102
  this.cb.onSuccess();
2680
- if (redisHit && !redisHit.stale && redisHit.value !== undefined) {
3103
+ if (redisHit && !redisHit.stale && (redisHit.staleAt === undefined || redisHit.staleAt > Date.now() || optSwr > 0)) {
2681
3104
  const parsed = redisHit.value;
2682
3105
  if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
2683
3106
  this.logger.debug('Aborting L2 promotion — key was mutated or deleted during Redis read', { cacheKey });
2684
3107
  span.setAttribute('cache.aborted_mutation_race', true);
2685
3108
  const current = this.l1.get(k);
2686
- const liveVal = (current && !current.isStale && current.value !== undefined)
3109
+ const liveVal = (current && !current.isStale)
2687
3110
  ? current.value as T
2688
3111
  : parsed;
2689
- if (this.opts.frozen) deepFreeze(liveVal);
2690
- return (this.opts.cloneStrategy === 'structuredClone' && liveVal != null && typeof liveVal === 'object')
2691
- ? structuredClone(liveVal) as T
2692
- : liveVal;
3112
+ return liveVal as T;
2693
3113
  }
2694
- this.l1.set(k, parsed, ttlMs, priority, undefined, undefined, redisHit.tagVersions);
3114
+ if (!this._promoteRedisEntry(k, redisHit, ttlMs, priority)) throw new Error('Redis entry expired during promotion');
2695
3115
  this.counters.l2Hits++;
2696
3116
  this.opts.onHit?.(cacheKey, 'l2');
2697
3117
  this.logger.debug(redisHit.tagVersions ? 'L2 hit (Redis hash)' : 'L2 hit (Redis)', { cacheKey });
2698
3118
  span.setAttribute('cache.hit', true)
2699
3119
  .setAttribute('cache.item.tier', 'remote')
2700
3120
  .setAttribute('cache.hit_tier', 'l2');
2701
- if (this.opts.frozen) deepFreeze(parsed);
2702
- return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
2703
- ? structuredClone(parsed)
2704
- : parsed;
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);
3125
+ }
3126
+ return parsed as T;
2705
3127
  }
2706
3128
  } catch (err) {
2707
3129
  this.cb.onFailure();
@@ -2714,6 +3136,11 @@ export class CacheService {
2714
3136
  this.opts.onMiss?.(cacheKey);
2715
3137
 
2716
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;
2717
3144
  const fetchStart = Date.now();
2718
3145
  let data: T;
2719
3146
  try {
@@ -2747,16 +3174,12 @@ export class CacheService {
2747
3174
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : undefined;
2748
3175
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
2749
3176
 
2750
- let activeTagVersions: Record<string, number> | undefined;
3177
+ const activeTagVersions = tagSnapshot;
2751
3178
  if (optTags?.length) {
2752
3179
  if (this.opts.tagStrategy === 'generational') {
2753
- const vers = await Promise.all(optTags.map(tag => this._getTagVersion(tag)));
2754
- activeTagVersions = {};
2755
- for (let i = 0; i < optTags.length; i++) {
2756
- activeTagVersions[optTags[i]] = vers[i];
2757
- }
3180
+ if (await this._isGenerationalEntryStale(tagSnapshot)) return data;
2758
3181
  } else {
2759
- await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1_000));
3182
+ await this._registerTags(k, optTags, Math.ceil(storeTtl / 1_000));
2760
3183
  }
2761
3184
  }
2762
3185
 
@@ -2764,40 +3187,22 @@ export class CacheService {
2764
3187
  this.logger.debug('Aborting in-flight cache commit — key was mutated or deleted during fetch', { cacheKey });
2765
3188
  span.setAttribute('cache.aborted_mutation_race', true);
2766
3189
  const current = this.l1.get(k);
2767
- if (current && !current.isStale && current.value !== undefined) {
3190
+ if (current && !current.isStale) {
2768
3191
  const freshVal = current.value as T;
2769
- if (this.opts.frozen) deepFreeze(freshVal);
2770
- return (this.opts.cloneStrategy === 'structuredClone' && freshVal != null && typeof freshVal === 'object')
2771
- ? structuredClone(freshVal)
2772
- : freshVal;
3192
+ return freshVal;
2773
3193
  }
2774
- if (this.opts.frozen) deepFreeze(data);
2775
- return (this.opts.cloneStrategy === 'structuredClone' && data != null && typeof data === 'object')
2776
- ? structuredClone(data)
2777
- : data;
3194
+ return data;
2778
3195
  }
2779
3196
 
2780
3197
  const writeTs = Date.now();
2781
- this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs);
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 });
2782
3201
 
2783
- if (!this._redisDisabled) {
3202
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2784
3203
  try {
2785
- const client = await this.getRedis();
2786
- const serialized = JSON.stringify(data);
2787
- const toStore = await this._serializeAndEncrypt(serialized);
2788
- const ttlSec = Math.ceil(effectiveTtl / 1_000);
2789
- if (this.opts.tagStrategy === 'generational' && (activeTagVersions || (!this.opts.autoPipeline && typeof (client as any).hgetall === 'function'))) {
2790
- const tx = client.multi();
2791
- tx.hset(k, {
2792
- d: toStore,
2793
- t: String(writeTs),
2794
- tv: JSON.stringify(activeTagVersions ?? {}),
2795
- });
2796
- tx.expire(k, ttlSec);
2797
- await tx.exec();
2798
- } else {
2799
- await client.setex(k, ttlSec, toStore);
2800
- }
3204
+ await this._writeRedisEntry(k, data, writeTs + storeTtl, writeTs, activeTagVersions, staleAt, optTags, opts.dependsOn,
3205
+ () => this._getKeyMutationEpoch(k) === mutationEpochAtStart);
2801
3206
  this.cb.onSuccess();
2802
3207
  this.logger.debug('Cached L1+L2', { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
2803
3208
  } catch {
@@ -2808,18 +3213,15 @@ export class CacheService {
2808
3213
  this.logger.debug('Cached L1', { cacheKey });
2809
3214
  }
2810
3215
 
2811
- if (this.opts.frozen) deepFreeze(data);
2812
- return (this.opts.cloneStrategy === 'structuredClone' && data != null && typeof data === 'object')
2813
- ? structuredClone(data)
2814
- : data;
3216
+ return data;
2815
3217
  } finally {
2816
- this.inflight.delete(k);
3218
+ if (this.inflight.get(k) === executionPromise) this.inflight.delete(k);
2817
3219
  span.end();
2818
3220
  }
2819
- })();
3221
+ });
2820
3222
 
2821
3223
  this.inflight.set(k, executionPromise);
2822
- return executionPromise;
3224
+ return this._prepareReadValue(await executionPromise);
2823
3225
  }
2824
3226
 
2825
3227
  /**
@@ -2915,6 +3317,9 @@ export class CacheService {
2915
3317
  knownTagVersions?: Record<string, number>,
2916
3318
  ): Promise<void> {
2917
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;
2918
3323
  try {
2919
3324
  const fetchStart = Date.now();
2920
3325
  const data = await fetchFn();
@@ -2956,31 +3361,19 @@ export class CacheService {
2956
3361
  }
2957
3362
 
2958
3363
  const writeTs = Date.now();
2959
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs);
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 });
2960
3367
 
2961
3368
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2962
3369
  try {
2963
- const client = await this.getRedis();
2964
- const s = JSON.stringify(data);
2965
- const stored = await this._serializeAndEncrypt(s);
2966
- const ttlSec = Math.ceil(ttlMs / 1_000);
2967
- if (this.opts.tagStrategy === 'generational' && (activeTagVersions || (!this.opts.autoPipeline && typeof (client as any).hgetall === 'function'))) {
2968
- const tx = client.multi();
2969
- tx.hset(cacheKey, {
2970
- d: stored,
2971
- t: String(writeTs),
2972
- tv: JSON.stringify(activeTagVersions ?? {}),
2973
- });
2974
- tx.expire(cacheKey, ttlSec);
2975
- await tx.exec();
2976
- } else {
2977
- await client.setex(cacheKey, ttlSec, stored);
2978
- }
3370
+ await this._writeRedisEntry(cacheKey, data, writeTs + ttlMs + swrGraceMs, writeTs, activeTagVersions, staleAt, tags, dependencies,
3371
+ () => this._getKeyMutationEpoch(cacheKey) === startEpoch);
2979
3372
  } catch { /* ok */ }
2980
3373
  }
2981
3374
  this.logger.debug('SWR: revalidation complete', { cacheKey });
2982
3375
  } catch (err) {
2983
- if (this.opts.staleIfError > 0) {
3376
+ if (this.opts.staleIfError > 0 && this._getKeyMutationEpoch(cacheKey) === startEpoch) {
2984
3377
  const additionalMs = this.opts.staleIfError * 1_000;
2985
3378
  this.l1.bumpExpiry(cacheKey, additionalMs);
2986
3379
  this.logger.debug('SWR: revalidation failed, stale-if-error extending expiry', {
@@ -3012,14 +3405,18 @@ export class CacheService {
3012
3405
  const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1_000);
3013
3406
  const p = priority ?? inferPriority(cacheKey);
3014
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;
3015
3411
  this._bumpKeyMutation(k);
3412
+ const epoch = this._getKeyMutationEpoch(k);
3016
3413
  this.inflight.delete(k);
3017
- this._pendingDiskDeletes.delete(k);
3414
+ this._invalidateDiskKey(k);
3018
3415
  this.counters.sets++;
3019
3416
 
3020
3417
  let activeTagVersions: Record<string, number> | undefined;
3021
- const tagsToRegister = opts?.tags?.length
3022
- ? (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)
3023
3420
  : undefined;
3024
3421
 
3025
3422
  if (tagsToRegister?.length) {
@@ -3030,52 +3427,23 @@ export class CacheService {
3030
3427
  activeTagVersions[tagsToRegister[i]] = vers[i];
3031
3428
  }
3032
3429
  } else {
3033
- await this._registerTags(k, tagsToRegister, ttlSeconds);
3430
+ await this._registerTags(k, tagsToRegister, effectiveTtlSeconds);
3034
3431
  }
3035
3432
  }
3036
3433
 
3434
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return;
3037
3435
  const writeTs = Date.now();
3038
- this.l1.set(k, data, ttlMs, p, undefined, undefined, activeTagVersions, writeTs);
3436
+ this.l1.set(k, data, ttlMs, p, undefined, undefined, activeTagVersions, writeTs, tagsToRegister, requestedDependencies);
3437
+ this._rememberTags(k, tagsToRegister ?? [], writeTs + ttlMs);
3039
3438
 
3040
3439
  // Register dependency patterns: when any key matching a pattern is deleted,
3041
3440
  // this key (k) is automatically cascaded.
3042
- if (opts?.dependsOn !== undefined) {
3043
- this._removeKeyDependencies(k);
3044
- if (opts.dependsOn.length > 0) {
3045
- const nsPatterns: string[] = [];
3046
- for (const pattern of opts.dependsOn) {
3047
- const nsPattern = this.nk(pattern);
3048
- nsPatterns.push(nsPattern);
3049
- let deps = this.dependencyIndex.get(nsPattern);
3050
- if (!deps) { deps = new Set(); this.dependencyIndex.set(nsPattern, deps); }
3051
- deps.add(k);
3052
- }
3053
- this.keyDependencies.set(k, nsPatterns);
3054
- }
3055
- }
3441
+ this._registerDependencies(k, requestedDependencies);
3056
3442
 
3057
3443
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
3058
3444
  try {
3059
- const client = await this.getRedis();
3060
- const s = JSON.stringify(data);
3061
- const stored = await this._serializeAndEncrypt(s);
3062
- const ttlSec = Math.ceil(ttlMs / 1_000);
3063
- if (this.opts.tagStrategy === 'generational' && (activeTagVersions || (!this.opts.autoPipeline && typeof (client as any).hgetall === 'function'))) {
3064
- const tx = client.multi();
3065
- tx.hset(k, {
3066
- d: stored,
3067
- t: String(writeTs),
3068
- tv: JSON.stringify(activeTagVersions ?? {}),
3069
- });
3070
- tx.expire(k, ttlSec);
3071
- await tx.exec();
3072
- } else {
3073
- if (this.opts.autoPipeline && this.pipeliner) {
3074
- await this.pipeliner.setex(k, ttlSec, stored);
3075
- } else {
3076
- await client.setex(k, ttlSec, stored);
3077
- }
3078
- }
3445
+ await this._writeRedisEntry(k, data, writeTs + ttlMs, writeTs, activeTagVersions, undefined, tagsToRegister, requestedDependencies,
3446
+ () => this._getKeyMutationEpoch(k) === epoch);
3079
3447
  this.cb.onSuccess();
3080
3448
  } catch (err) {
3081
3449
  this.cb.onFailure();
@@ -3102,24 +3470,10 @@ export class CacheService {
3102
3470
  * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
3103
3471
  */
3104
3472
  private async _registerTags(k: string, tags: string[], ttlSeconds: number): Promise<void> {
3105
- this._removeKeyTags(k);
3106
3473
  const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
3107
3474
  const expiresAt = Date.now() + effectiveTtl * 1_000;
3108
- if (this.keyTags.size >= 100_000 && !this.keyTags.has(k)) {
3109
- this._sweepExpiredMetadata();
3110
- if (this.keyTags.size >= 100_000) {
3111
- const oldestKey = this.keyTags.keys().next().value;
3112
- if (oldestKey !== undefined) this._removeKeyTags(oldestKey);
3113
- }
3114
- }
3115
3475
  const uniqueTags = Array.from(new Set(tags));
3116
- for (const tag of uniqueTags) {
3117
- const tagKey = this.nk(`_tag_:${tag}`);
3118
- let members = this.tagIndex.get(tagKey);
3119
- if (!members) { members = new Set(); this.tagIndex.set(tagKey, members); }
3120
- members.add(k);
3121
- }
3122
- this.keyTags.set(k, { tags: uniqueTags, expiresAt });
3476
+ this._rememberTags(k, uniqueTags, expiresAt);
3123
3477
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
3124
3478
  try {
3125
3479
  const client = await this.getRedis();
@@ -3152,6 +3506,7 @@ export class CacheService {
3152
3506
  this.counters.deletes++;
3153
3507
 
3154
3508
  if (isPattern) {
3509
+ this._fenceInvalidation();
3155
3510
  const pfx = k.endsWith('*') ? k.slice(0, -1) : k;
3156
3511
  for (const liveKey of this.l1.liveKeys()) {
3157
3512
  if (liveKey.startsWith(pfx)) {
@@ -3164,9 +3519,9 @@ export class CacheService {
3164
3519
  this.inflight.delete(inflightKey);
3165
3520
  }
3166
3521
  }
3167
- this._addPatternTombstone(pfx);
3522
+ this._addPatternTombstone(k);
3168
3523
  this.l1.deletePattern(k);
3169
- this._removePrefixFromIndices(pfx);
3524
+ this._removePatternFromIndices(k);
3170
3525
  for (const ktKey of Array.from(this.keyTags.keys())) {
3171
3526
  if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
3172
3527
  }
@@ -3177,14 +3532,7 @@ export class CacheService {
3177
3532
  this._bumpKeyMutation(k);
3178
3533
  this.inflight.delete(k);
3179
3534
  this.l1.delete(k);
3180
- this._pendingDiskDeletes.add(k);
3181
- setImmediate(() => {
3182
- try {
3183
- if (!this._diskDisabled) this.disk.delete(k);
3184
- } finally {
3185
- this._pendingDiskDeletes.delete(k);
3186
- }
3187
- });
3535
+ this._invalidateDiskKey(k);
3188
3536
  this._removeKeyTags(k);
3189
3537
  // Cascade: invalidate any key that declared it depends on this exact key's pattern
3190
3538
  this._cascadeDependencies(k);
@@ -3248,7 +3596,7 @@ export class CacheService {
3248
3596
  this._assertActive('increment');
3249
3597
  const k = this.nk(cacheKey);
3250
3598
 
3251
- if (this._redisDisabled) {
3599
+ if (this._redisDisabled || this.opts.l2WriteMode === 'read-only') {
3252
3600
  if (!this._incrementFallbackWarned) {
3253
3601
  this._incrementFallbackWarned = true;
3254
3602
  this.logger.warn(
@@ -3310,6 +3658,7 @@ export class CacheService {
3310
3658
  : undefined;
3311
3659
 
3312
3660
  if (k) {
3661
+ this._fenceInvalidation();
3313
3662
  const pfx = k.endsWith('*') ? k.slice(0, -1) : k;
3314
3663
  for (const liveKey of this.l1.liveKeys()) {
3315
3664
  if (liveKey.startsWith(pfx)) {
@@ -3322,9 +3671,9 @@ export class CacheService {
3322
3671
  this.inflight.delete(inflightKey);
3323
3672
  }
3324
3673
  }
3325
- this._addPatternTombstone(pfx);
3674
+ this._addPatternTombstone(k);
3326
3675
  this.l1.deletePattern(k);
3327
- this._removePrefixFromIndices(pfx);
3676
+ this._removePatternFromIndices(k);
3328
3677
  } else {
3329
3678
  this._globalEpoch++;
3330
3679
  this.inflight.clear();
@@ -3476,29 +3825,35 @@ export class CacheService {
3476
3825
  this._assertActive('scan');
3477
3826
  const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
3478
3827
  this.l1.scan((key, entry, pfx) => {
3479
- const value = (entry.value !== undefined ? entry.value : entry.data) as T;
3480
- fn(key, value, pfx);
3828
+ fn(key, this._prepareReadValue(this.l1.resolveValue(entry) as T), pfx);
3481
3829
  }, prefixLen);
3482
3830
  }
3483
3831
 
3484
3832
  /**
3485
- * 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.
3486
3834
  * Returns `false` if the key is absent or already expired.
3487
3835
  *
3488
3836
  * @param newTtlSeconds - The new TTL from now, in seconds.
3489
3837
  */
3490
3838
  async touch(cacheKey: string, newTtlSeconds: number): Promise<boolean> {
3491
3839
  this._assertActive('touch');
3840
+ if (!Number.isFinite(newTtlSeconds) || newTtlSeconds <= 0) throw new Error('touch TTL must be finite and positive');
3492
3841
  const k = this.nk(cacheKey);
3842
+ const epoch = this._getKeyMutationEpoch(k);
3493
3843
  const hit = this.l1.touch(k, newTtlSeconds * 1_000);
3844
+ const entry = this.l1.getEntry(k);
3494
3845
  if (hit) {
3495
3846
  const kt = this.keyTags.get(k);
3496
3847
  if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1_000;
3497
3848
  }
3498
- if (hit && !this._redisDisabled) {
3849
+ if (hit && !this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
3499
3850
  try {
3500
3851
  const client = await this.getRedis();
3501
- 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();
3502
3857
  } catch { /* ok */ }
3503
3858
  }
3504
3859
  return hit;
@@ -3520,7 +3875,8 @@ export class CacheService {
3520
3875
  const now = Date.now();
3521
3876
  if (entry.expiresAt <= now) return null; // expired
3522
3877
  if (entry.staleAt !== undefined && entry.staleAt < now) return null; // in SWR grace
3523
- 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);
3524
3880
  }
3525
3881
 
3526
3882
  private _prepareReadValue<T>(val: T): T {
@@ -3541,6 +3897,8 @@ export class CacheService {
3541
3897
  async peek<T = unknown>(cacheKey: string): Promise<T | null> {
3542
3898
  this._assertActive('peek');
3543
3899
  const k = this.nk(cacheKey);
3900
+ const epoch = this._getKeyMutationEpoch(k);
3901
+ this.counters.gets++;
3544
3902
 
3545
3903
  // 1. L1 RAM
3546
3904
  const l1Hit = this.l1.get(k);
@@ -3548,46 +3906,20 @@ export class CacheService {
3548
3906
  if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
3549
3907
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
3550
3908
  } else {
3551
- this.counters.gets++;
3552
3909
  this.counters.l1Hits++;
3553
3910
  return this._prepareReadValue(l1Hit.value as T);
3554
3911
  }
3555
3912
  }
3556
3913
 
3557
3914
  // 2. L1.5 Disk
3558
- if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
3559
- if (this._isTombstonedByPattern(k)) {
3560
- try { this.disk.delete(k); } catch { /* ok */ }
3561
- } else if (this.watchdog.isDiskAllowed()) {
3562
- const diskStart = performance.now();
3563
- const diskHit = this.disk.load(k);
3564
- const diskElapsed = performance.now() - diskStart;
3565
- this.watchdog.recordDisk(diskElapsed);
3566
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
3567
-
3568
- if (diskHit !== null) {
3569
- if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
3570
- this.disk.delete(k);
3571
- } else {
3572
- const promoted = this.l1.importEntries(
3573
- [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
3574
- this.opts.forbiddenSnapshotPrefixes,
3575
- );
3576
- if (promoted > 0) {
3577
- const l1Check = this.l1.get(k);
3578
- if (l1Check !== null) {
3579
- this.counters.gets++;
3580
- this.counters.diskHits++;
3581
- return this._prepareReadValue(l1Check.value as T);
3582
- }
3583
- }
3584
- }
3585
- }
3586
- }
3915
+ const diskHit = await this._readDiskEntry<T>(k, epoch);
3916
+ if (diskHit) {
3917
+ this.counters.diskHits++;
3918
+ return this._prepareReadValue(diskHit.value);
3587
3919
  }
3588
3920
 
3589
3921
  // 3. L2 Redis
3590
- if (!this._redisDisabled && !this.cb.isOpen) {
3922
+ if (!this._redisDisabled) {
3591
3923
  try {
3592
3924
  const client = await this.getRedis();
3593
3925
  const redisStart = performance.now();
@@ -3595,12 +3927,12 @@ export class CacheService {
3595
3927
  const redisElapsed = performance.now() - redisStart;
3596
3928
  this.watchdog.recordRedis(redisElapsed);
3597
3929
  this.cb.onSuccess();
3598
- if (redisHit && !redisHit.stale && redisHit.value !== undefined) {
3930
+ if (redisHit && !redisHit.stale) {
3599
3931
  const parsed = redisHit.value;
3600
- this.l1.set(k, parsed, 60_000, inferPriority(cacheKey), undefined, undefined, redisHit.tagVersions);
3601
- this.counters.gets++;
3932
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return null;
3933
+ if (!this._promoteRedisEntry(k, redisHit, 60_000, inferPriority(cacheKey))) return null;
3602
3934
  this.counters.l2Hits++;
3603
- return this._prepareReadValue(parsed);
3935
+ return this._prepareReadValue(parsed as T);
3604
3936
  }
3605
3937
  } catch (err) {
3606
3938
  this.cb.onFailure();
@@ -3627,6 +3959,8 @@ export class CacheService {
3627
3959
  priority?: CachePriority,
3628
3960
  ): Promise<(T | undefined)[]> {
3629
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))]));
3630
3964
  const span = this._startSpan('tricache.mget');
3631
3965
  if (this.opts.tracer) {
3632
3966
  span.setAttribute('cache.batch.size', keys.length);
@@ -3641,7 +3975,7 @@ export class CacheService {
3641
3975
  for (let i = 0; i < keys.length; i++) {
3642
3976
  const k = this.nk(keys[i]);
3643
3977
  const entry = this.l1.getEntry(k);
3644
- if (entry && entry.expiresAt > now) {
3978
+ if (entry && entry.expiresAt > now && (entry.staleAt === undefined || entry.staleAt > now)) {
3645
3979
  if (await this._isGenerationalEntryStale(entry.tagVersions)) {
3646
3980
  this._deleteIfStale(k, entry.setAt ?? 0);
3647
3981
  missIndexes.push(i);
@@ -3673,69 +4007,27 @@ export class CacheService {
3673
4007
  try {
3674
4008
  const client = await this.getRedis();
3675
4009
  const nsKeys = missKeys.map(k => this.nk(k));
3676
- const pipeline = client.multi();
3677
- const useHashPipeline = this.opts.tagStrategy === 'generational' && typeof (pipeline as any).hgetall === 'function';
3678
- for (const nk of nsKeys) {
3679
- if (useHashPipeline) {
3680
- (pipeline as any).hgetall(nk);
3681
- } else {
3682
- pipeline.get(nk);
3683
- }
3684
- }
3685
- const redisStart = performance.now();
3686
- const raws = await pipeline.exec() as Array<[Error | null, any] | null>;
3687
- const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
3688
- this.watchdog.recordRedis(redisElapsed);
3689
- this.cb.onSuccess();
4010
+ const remoteEntries = await this._readRedisBatch<T>(client, nsKeys);
3690
4011
 
3691
4012
  for (let j = 0; j < missKeys.length; j++) {
3692
- const tuple = raws[j];
3693
- const err = tuple ? tuple[0] : null;
3694
- const rawVal = tuple ? tuple[1] : null;
3695
4013
  const idx = missIndexes[j];
3696
4014
  const k = nsKeys[j];
3697
-
3698
- let parsed: T | undefined;
3699
- let tagVersions: Record<string, number> | undefined;
3700
- let hit = false;
3701
-
3702
- if (useHashPipeline) {
3703
- if (err && err.message?.includes('WRONGTYPE')) {
3704
- const fallbackRaw = await client.get(k);
3705
- if (fallbackRaw) {
3706
- parsed = await this._decryptAndDeserialize<T>(fallbackRaw);
3707
- hit = true;
3708
- }
3709
- } else if (!err && typeof rawVal === 'string') {
3710
- parsed = await this._decryptAndDeserialize<T>(rawVal);
3711
- hit = true;
3712
- } else if (!err && rawVal && typeof rawVal === 'object' && rawVal.d) {
3713
- const hashHit = await this._parseGenerationalRedisHash<T>(k, rawVal);
3714
- if (hashHit && !hashHit.stale && hashHit.value !== undefined) {
3715
- parsed = hashHit.value;
3716
- tagVersions = hashHit.tagVersions;
3717
- hit = true;
3718
- }
3719
- }
3720
- } else if (!err && rawVal) {
3721
- parsed = await this._decryptAndDeserialize<T>(rawVal);
3722
- hit = true;
3723
- }
3724
-
3725
- if (hit && parsed !== undefined) {
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)) {
3726
4018
  const p = priority ?? inferPriority(missKeys[j]);
3727
4019
  const ttlVal = typeof ttl === 'function' ? ttl(missKeys[j]) : ttl;
3728
- this.l1.set(k, parsed, this._jitterTtl(ttlVal * 1_000), p, undefined, undefined, tagVersions);
4020
+ if (!this._promoteRedisEntry(k, entry, this._jitterTtl(ttlVal * 1_000), p)) continue;
3729
4021
  this.counters.l2Hits++;
3730
4022
  l2HitCount++;
3731
- result[idx] = this._prepareReadValue(parsed);
4023
+ result[idx] = this._prepareReadValue(entry.value as T);
3732
4024
  missIndexes[j] = -1;
3733
4025
  missKeys[j] = '';
3734
4026
  }
3735
4027
  }
3736
4028
  // Compact the still-missing arrays.
3737
4029
  const remainingIdx = missIndexes.filter(i => i >= 0);
3738
- const remainingKeys = missKeys.filter(k => k !== '');
4030
+ const remainingKeys = missKeys.filter((_key, index) => missIndexes[index] >= 0);
3739
4031
  missIndexes.length = 0; missKeys.length = 0;
3740
4032
  missIndexes.push(...remainingIdx);
3741
4033
  missKeys.push(...remainingKeys);
@@ -3749,62 +4041,62 @@ export class CacheService {
3749
4041
  if (!this._diskDisabled && missKeys.length > 0) {
3750
4042
  for (let j = missKeys.length - 1; j >= 0; j--) {
3751
4043
  const k = this.nk(missKeys[j]);
3752
- if (this._pendingDiskDeletes.has(k)) continue;
3753
- if (this._isTombstonedByPattern(k)) {
3754
- try { this.disk.delete(k); } catch { /* ok */ }
3755
- continue;
3756
- }
3757
- if (!this.watchdog.isDiskAllowed()) continue;
3758
- const diskStart = performance.now();
3759
- const diskHit = this.disk.load(k);
3760
- const diskElapsed = performance.now() - diskStart;
3761
- this.watchdog.recordDisk(diskElapsed);
3762
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
3763
- if (diskHit !== null) {
3764
- if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
3765
- this.disk.delete(k);
3766
- continue;
3767
- }
3768
- const promoted = this.l1.importEntries(
3769
- [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
3770
- this.opts.forbiddenSnapshotPrefixes,
3771
- );
3772
- if (promoted > 0) {
3773
- const l1Check = this.l1.get(k);
3774
- if (l1Check !== null) {
3775
- this.counters.diskHits++;
3776
- result[missIndexes[j]] = this._prepareReadValue(l1Check.value as T);
3777
- missIndexes.splice(j, 1);
3778
- missKeys.splice(j, 1);
3779
- }
3780
- }
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);
3781
4050
  }
3782
4051
  }
3783
4052
  }
3784
4053
 
3785
4054
  // ── Tier 3: fetchFn for whatever still missed ──
3786
4055
  if (missKeys.length > 0 && fetchFn) {
3787
- this.counters.fetches++;
3788
- const fetched = await fetchFn(missKeys);
3789
- const isMap = fetched instanceof Map;
3790
- 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>[] = [];
3791
4058
  for (let j = 0; j < missKeys.length; j++) {
3792
- const k = missKeys[j];
3793
- const v = isMap ? (fetched as Map<string, T>).get(k) : (fetched as Record<string, T>)[k];
3794
- result[missIndexes[j]] = v;
3795
- if (v !== undefined && v !== null) {
3796
- const resolvedTtl = typeof ttl === 'function' ? ttl(k) : ttl;
3797
- setPromises.push(this.set(k, v, resolvedTtl, priority));
3798
- } else if (v == null && this.opts.notFoundTtl > 0) {
3799
- // Negative caching: cache null/missing records with notFoundTtl to protect origin DB
3800
- setPromises.push(this.set(k, null as unknown as T, this.opts.notFoundTtl, priority));
3801
- } else if (v === null) {
3802
- const resolvedTtl = typeof ttl === 'function' ? ttl(k) : ttl;
3803
- 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++;
3804
4070
  }
4071
+ const index = missIndexes[j];
4072
+ waiting.push(promise.then(value => { result[index] = this._prepareReadValue(value as T | undefined); }));
3805
4073
  }
3806
- if (setPromises.length > 0) {
3807
- 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
+ }
3808
4100
  }
3809
4101
  }
3810
4102
 
@@ -3863,7 +4155,7 @@ export class CacheService {
3863
4155
  try {
3864
4156
  await Promise.all(keys.map(key => {
3865
4157
  const { value, ttl = 300, priority, tags, dependsOn } = entries[key];
3866
- const hasOpts = tags?.length || dependsOn?.length;
4158
+ const hasOpts = tags !== undefined || dependsOn !== undefined;
3867
4159
  return this.set(key, value, ttl, priority, hasOpts ? { tags, dependsOn } : undefined);
3868
4160
  }));
3869
4161
  } catch (err) {
@@ -3919,7 +4211,10 @@ export class CacheService {
3919
4211
  const nsPattern = this.nk(pattern);
3920
4212
 
3921
4213
  // Collect all matching keys via SCAN (handles single-node and Cluster)
3922
- 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
+ });
3923
4218
 
3924
4219
  if (matchedKeys.length === 0) {
3925
4220
  this.cb.onSuccess();
@@ -3927,23 +4222,13 @@ export class CacheService {
3927
4222
  }
3928
4223
 
3929
4224
  // Fetch values in a pipeline and load into L1
3930
- const pl = client.pipeline();
3931
- for (const k of matchedKeys) pl.get(k);
3932
- const results = await pl.exec() as Array<[Error | null, string | null]>;
3933
- this.cb.onSuccess();
3934
-
4225
+ const epochs = new Map(matchedKeys.map(key => [key, this._getKeyMutationEpoch(key)]));
4226
+ const results = await this._readRedisBatch<unknown>(client, matchedKeys);
3935
4227
  let loaded = 0;
3936
- for (let i = 0; i < matchedKeys.length; i++) {
3937
- const [err, raw] = results[i];
3938
- if (err || raw == null) continue;
3939
- try {
3940
- const parsed = await this._decryptAndDeserialize<unknown>(raw);
3941
- // Use a 10-minute TTL as a reasonable default; the real TTL is not
3942
- // returned by GET (use PTTL to be precise, but that doubles round-trips).
3943
- const remainingMs = 10 * 60 * 1_000;
3944
- this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
3945
- loaded++;
3946
- } 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++;
3947
4232
  }
3948
4233
 
3949
4234
  this.logger.info('warmFromL2 complete', {
@@ -4033,7 +4318,7 @@ export class CacheService {
4033
4318
  }
4034
4319
 
4035
4320
  private async _publishTagInvalidation(
4036
- op: 'tag_incr' | 'tag_pattern_incr' | 'tag_pattern_del',
4321
+ op: 'del' | 'tag_incr' | 'tag_pattern_incr' | 'tag_pattern_del',
4037
4322
  key: string,
4038
4323
  tagVersion?: number,
4039
4324
  ): Promise<void> {
@@ -4051,14 +4336,7 @@ export class CacheService {
4051
4336
  this._bumpKeyMutation(k);
4052
4337
  this._removeKeyTags(k);
4053
4338
  this._removeKeyDependencies(k);
4054
- this._pendingDiskDeletes.add(k);
4055
- setImmediate(() => {
4056
- try {
4057
- if (!this._diskDisabled) this.disk.delete(k);
4058
- } finally {
4059
- this._pendingDiskDeletes.delete(k);
4060
- }
4061
- });
4339
+ this._invalidateDiskKey(k);
4062
4340
  }
4063
4341
  }
4064
4342
 
@@ -4067,9 +4345,10 @@ export class CacheService {
4067
4345
  * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
4068
4346
  */
4069
4347
  private async _invalidateConcreteTag(tag: string): Promise<void> {
4348
+ this._fenceInvalidation();
4070
4349
  if (this.opts.tagStrategy === 'generational') {
4071
4350
  let newVer = 1;
4072
- if (!this._redisDisabled) {
4351
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
4073
4352
  try {
4074
4353
  const client = await this.getRedis();
4075
4354
  newVer = await client.incr(this.nk(`tag_ver:${tag}`));
@@ -4088,21 +4367,25 @@ export class CacheService {
4088
4367
  }
4089
4368
 
4090
4369
  const tagKey = this.nk(`_tag_:${tag}`);
4091
- const members = Array.from(this.tagIndex.get(tagKey) ?? []);
4370
+ const members = new Set(this.tagIndex.get(tagKey) ?? []);
4092
4371
 
4093
4372
  this.tagIndex.delete(tagKey);
4094
4373
  this._removeTagMembersLocal(members);
4095
4374
 
4096
- if (!this._redisDisabled) {
4375
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
4097
4376
  try {
4098
4377
  const client = await this.getRedis();
4099
4378
  const redisMembers: string[] = await client.smembers(tagKey);
4379
+ for (const key of redisMembers) members.add(key);
4380
+ this._removeTagMembersLocal(redisMembers);
4100
4381
  const toDelete = [...new Set([...members, ...redisMembers, tagKey])];
4101
4382
  await this._deleteRedisKeys(client, toDelete);
4102
4383
  } catch (err) {
4103
4384
  this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
4104
4385
  }
4105
4386
  }
4387
+ await Promise.all([...members].map(key => this._publishTagInvalidation('del', key)));
4388
+ await this._publishTagInvalidation('tag_pattern_del', tag);
4106
4389
  }
4107
4390
 
4108
4391
  /**
@@ -4115,10 +4398,11 @@ export class CacheService {
4115
4398
  await this._invalidateConcreteTag(tags[0]);
4116
4399
  return;
4117
4400
  }
4401
+ this._fenceInvalidation();
4118
4402
 
4119
4403
  if (this.opts.tagStrategy === 'generational') {
4120
4404
  const now = performance.now();
4121
- if (!this._redisDisabled) {
4405
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
4122
4406
  try {
4123
4407
  const client = await this.getRedis();
4124
4408
  const pl = client.pipeline();
@@ -4155,7 +4439,7 @@ export class CacheService {
4155
4439
  }
4156
4440
  this._removeTagMembersLocal(allMembers);
4157
4441
 
4158
- if (!this._redisDisabled) {
4442
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
4159
4443
  try {
4160
4444
  const client = await this.getRedis();
4161
4445
  // Single round-trip: pipeline SMEMBERS for all tag keys
@@ -4167,16 +4451,19 @@ export class CacheService {
4167
4451
  const toDelete: string[] = [...allMembers];
4168
4452
  for (const [err, redisMembers] of smResults) {
4169
4453
  if (!err && redisMembers) {
4170
- for (const k of redisMembers) { if (!allMembers.has(k)) toDelete.push(k); }
4454
+ for (const k of redisMembers) { if (!allMembers.has(k)) toDelete.push(k); allMembers.add(k); }
4171
4455
  }
4172
4456
  }
4173
4457
  // Chunk/cluster-safe DEL for all member keys + tag keys
4174
4458
  const keysToRemove = [...toDelete, ...tagKeys];
4175
4459
  await this._deleteRedisKeys(client, keysToRemove);
4460
+ this._removeTagMembersLocal(allMembers);
4176
4461
  } catch (err) {
4177
4462
  this.logger.debug('invalidateTags: Redis unavailable', { tags, error: (err as Error).message });
4178
4463
  }
4179
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);
4180
4467
  }
4181
4468
 
4182
4469
  /**
@@ -4352,21 +4639,25 @@ export class CacheService {
4352
4639
  const circuitOpen = this.cb.isOpen;
4353
4640
  const latencyBypass = watchdogTel.bypassActive;
4354
4641
 
4355
- const degraded = circuitOpen || latencyBypass || diskPruning || diskLowSpace;
4356
- 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);
4357
4645
 
4358
4646
  const reasons: string[] = [];
4359
4647
  if (circuitOpen) reasons.push('redis_circuit_breaker_open');
4360
4648
  if (latencyBypass) reasons.push(`disk_latency_bypass_stage_${watchdogTel.bypassStage}`);
4361
4649
  if (diskPruning) reasons.push('disk_quota_watermark_pruning_active');
4362
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');
4363
4653
 
4364
4654
  return {
4365
4655
  healthy,
4366
4656
  degraded,
4367
4657
  reasons,
4368
4658
  details: {
4369
- redisConnected: !circuitOpen && !this._redisDisabled,
4659
+ redisConnected: !this._destroyed && !circuitOpen && !!this.redis && (this.redis.status === 'ready' || this.redis.isOpen === true),
4660
+ backplaneReady: this._backplaneAvailable,
4370
4661
  circuitBreakerState: this.cb.currentState,
4371
4662
  diskPruningActive: diskPruning,
4372
4663
  diskHostVolumeLowSpace: diskLowSpace,
@@ -4390,24 +4681,19 @@ export class CacheService {
4390
4681
  */
4391
4682
  async drainToL2(): Promise<number> {
4392
4683
  this._assertActive('drainToL2');
4393
- if (this._redisDisabled) return 0;
4684
+ if (this._redisDisabled || this.opts.l2WriteMode === 'read-only') return 0;
4394
4685
  try {
4395
- const client = await this.getRedis();
4396
4686
  const entries = this.l1.exportEntries([]);
4397
- const now = Date.now();
4398
4687
  if (entries.length === 0) return 0;
4399
-
4400
- const pl = client.pipeline();
4401
- for (const { key, entry } of entries) {
4402
- const remainingMs = entry.expiresAt - now;
4403
- if (remainingMs <= 0) continue;
4404
- const ttlSecs = Math.max(1, Math.ceil(remainingMs / 1_000));
4405
- const s = JSON.stringify(entry.value);
4406
- const stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
4407
- pl.setex(key, ttlSecs, stored);
4408
- }
4409
- await pl.exec();
4410
- 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;
4411
4697
  } catch (err) {
4412
4698
  this.logger.debug('drainToL2: Redis unavailable', { error: (err as Error).message });
4413
4699
  return 0;
@@ -4444,7 +4730,7 @@ export class CacheService {
4444
4730
  // Fast path: L1 check (process-local, no network hop)
4445
4731
  if (this.l1.has(k)) return false;
4446
4732
 
4447
- if (!this._redisDisabled) {
4733
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
4448
4734
  try {
4449
4735
  const client = await this.getRedis();
4450
4736
  const serialized = JSON.stringify(value);
@@ -4464,7 +4750,7 @@ export class CacheService {
4464
4750
  const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
4465
4751
  const p = priority ?? inferPriority(cacheKey);
4466
4752
  this._bumpKeyMutation(k);
4467
- this._pendingDiskDeletes.delete(k);
4753
+ this._invalidateDiskKey(k);
4468
4754
  this.l1.set(k, value, ttlMs, p);
4469
4755
  this.counters.sets++;
4470
4756
  return true;
@@ -4500,7 +4786,7 @@ export class CacheService {
4500
4786
 
4501
4787
  let acquired = false;
4502
4788
 
4503
- if (!this._redisDisabled) {
4789
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
4504
4790
  // ── Acquire phase ONLY. Redis-side failures here may fall back to the
4505
4791
  // in-process mutex below. fn() is deliberately NOT inside this try: a
4506
4792
  // business exception must propagate to the caller exactly once — the old
@@ -4610,7 +4896,9 @@ export class CacheService {
4610
4896
  const gDiskBytes = meter.createObservableGauge('tricache.disk.bytes', { description: 'Current L1.5 disk size in bytes' });
4611
4897
  const gBloomFpr = meter.createObservableGauge('tricache.bloom.fpr', { description: 'Bloom filter false-positive rate' });
4612
4898
 
4613
- meter.addBatchObservableCallback((observableResult) => {
4899
+ const observables = [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr];
4900
+ const callback: ICacheBatchObservableCallback = (observableResult) => {
4901
+ if (this._destroyed) return;
4614
4902
  const stats = this.stats();
4615
4903
  const l1 = stats.l1;
4616
4904
  const disk = stats.disk;
@@ -4624,7 +4912,9 @@ export class CacheService {
4624
4912
  observableResult.observe(gDiskFiles, disk.files, attrs);
4625
4913
  observableResult.observe(gDiskBytes, disk.sizeKB * 1024, attrs);
4626
4914
  observableResult.observe(gBloomFpr, fpr, attrs);
4627
- }, [gL1Entries, gL1Bytes, gDiskFiles, gDiskBytes, gBloomFpr]);
4915
+ };
4916
+ meter.addBatchObservableCallback(callback, observables);
4917
+ this._otelCleanup = () => meter.removeBatchObservableCallback?.(callback, observables);
4628
4918
  } catch (err) {
4629
4919
  this.logger.warn('Failed to initialize OpenTelemetry metrics meter', { error: (err as Error).message });
4630
4920
  }
@@ -4914,6 +5204,13 @@ export class CacheService {
4914
5204
  /** Close Redis connections and stop all background timers. */
4915
5205
  async destroy(): Promise<void> {
4916
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();
4917
5214
  this._pendingDiskDeletes.clear();
4918
5215
  this._keyMutationEpochs.clear();
4919
5216
  this.inflight.clear();
@@ -4943,13 +5240,16 @@ export class CacheService {
4943
5240
  this._workerPool = null;
4944
5241
  }
4945
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
+ }
4946
5246
  if (!this.opts.redisSubClient) {
4947
5247
  try { this.subClient.disconnect(); } catch { /* ok */ }
4948
5248
  }
4949
5249
  this.subClient = null;
4950
5250
  }
4951
5251
  if (this.streamClient) {
4952
- try { this.streamClient.disconnect(); } catch { /* ok */ }
5252
+ if (!this.opts.redisSubClient) try { this.streamClient.disconnect(); } catch { /* ok */ }
4953
5253
  this.streamClient = null;
4954
5254
  }
4955
5255
  if (this.redis) {
@@ -4980,4 +5280,4 @@ export class CacheService {
4980
5280
  return this.l1.getWTinyLfuStats();
4981
5281
  }
4982
5282
 
4983
- }
5283
+ }