tricache 1.0.0 → 1.0.1

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 (43) hide show
  1. package/README.md +1 -1
  2. package/dist/{cache-service-pJ-nFcVj.d.ts → cache-service-CREOp7MM.d.ts} +29 -1
  3. package/dist/{cache-service-26GCO3UU.js → cache-service-MG7PN6MX.js} +1 -1
  4. package/dist/{chunk-VXFTFZ5N.js → chunk-3I5L7K6I.js} +17 -0
  5. package/dist/{chunk-7SZSQS55.js → chunk-JYQFQJNJ.js} +533 -295
  6. package/dist/cli.cjs +534 -296
  7. package/dist/cli.js +2 -2
  8. package/dist/dashboard/index.d.ts +2 -2
  9. package/dist/drizzle/index.cjs +533 -295
  10. package/dist/drizzle/index.d.ts +2 -2
  11. package/dist/drizzle/index.js +1 -1
  12. package/dist/edge/index.cjs +55 -32
  13. package/dist/edge/index.d.ts +3 -3
  14. package/dist/edge/index.js +55 -32
  15. package/dist/hono/index.cjs +533 -295
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +1 -1
  18. package/dist/{hono-DuNvciyq.d.ts → hono-DSV2ve66.d.ts} +8 -1
  19. package/dist/http/index.cjs +585 -316
  20. package/dist/http/index.d.ts +3 -3
  21. package/dist/http/index.js +55 -24
  22. package/dist/index.cjs +550 -295
  23. package/dist/index.d.ts +5 -4
  24. package/dist/index.js +2 -2
  25. package/dist/nestjs/index.cjs +533 -295
  26. package/dist/nestjs/index.d.ts +2 -2
  27. package/dist/nestjs/index.js +2 -2
  28. package/dist/next/index.cjs +535 -303
  29. package/dist/next/index.d.ts +2 -2
  30. package/dist/next/index.js +3 -9
  31. package/dist/prisma/index.d.ts +2 -2
  32. package/dist/{types-5HXqBfAf.d.ts → types-Dyip5wAl.d.ts} +2 -0
  33. package/package.json +1 -1
  34. package/src/adapters/node-redis.ts +19 -0
  35. package/src/cache-service.ts +599 -320
  36. package/src/cli.ts +1 -1
  37. package/src/edge/cache.ts +60 -35
  38. package/src/http/express.ts +55 -16
  39. package/src/http/fastify.ts +3 -7
  40. package/src/next/cache-handler.ts +1 -4
  41. package/src/next/isr-handler.ts +1 -4
  42. package/src/smart-memory-cache.ts +3 -2
  43. package/src/types.ts +2 -0
@@ -50,12 +50,13 @@ import {
50
50
  CachePresetType,
51
51
  CacheHealthStatus,
52
52
  InvalidateTagOptions,
53
+ EvictionReason,
53
54
  } from './types';
54
55
  import { CacheEncryption, EnvelopeEncryption, type EncryptionMode } from './encryption';
55
56
  import { SmartMemoryCache } from './smart-memory-cache';
56
57
  import { DiskTier, resolveDefaultDiskDir } from './disk-tier';
57
58
  import { TierLatencyWatchdog } from './latency-watchdog';
58
- import { resolveAutonomousL1MaxBytes } from './utils/cgroup';
59
+ import { resolveAutonomousL1MaxBytes, readCgroupMemoryLimit } from './utils/cgroup';
59
60
  import { AutoPipeliner } from './adapters/auto-pipeliner';
60
61
  import { IpcTelemetryServer } from './ipc-telemetry.js';
61
62
  import {
@@ -558,6 +559,8 @@ export class CacheService {
558
559
  private readonly _l1Counters = new Map<string, { value: number; expiresAt: number }>();
559
560
  /** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
560
561
  private readonly tagIndex = new Map<string, Set<string>>();
562
+ /** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
563
+ private readonly keyTags = new Map<string, { tags: string[]; expiresAt: number }>();
561
564
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
562
565
  private readonly tagVersions = new Map<string, { version: number; lastSyncedAt: number }>();
563
566
  /**
@@ -565,6 +568,9 @@ export class CacheService {
565
568
  * When an exact-key delete matches a registered pattern, all dependents are cascaded.
566
569
  */
567
570
  private readonly dependencyIndex = new Map<string, Set<string>>();
571
+ /** Reverse index of namespaced dependent key → source glob patterns */
572
+ private readonly keyDependencies = new Map<string, string[]>();
573
+ private readonly _cgroupMemoryLimit: number;
568
574
  private redis: AnyRedisClient | null = null;
569
575
  private redisConnecting: Promise<AnyRedisClient> | null = null;
570
576
  private readonly cb: L2CircuitBreaker;
@@ -639,6 +645,97 @@ export class CacheService {
639
645
  private _getKeyMutationEpoch(namespacedKey: string): number {
640
646
  return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
641
647
  }
648
+
649
+ private _removeKeyTags(namespacedKey: string): void {
650
+ const entry = this.keyTags.get(namespacedKey);
651
+ if (!entry) return;
652
+ for (const tag of entry.tags) {
653
+ const tagKey = this.nk(`_tag_:${tag}`);
654
+ const members = this.tagIndex.get(tagKey);
655
+ if (members) {
656
+ members.delete(namespacedKey);
657
+ if (members.size === 0) this.tagIndex.delete(tagKey);
658
+ }
659
+ }
660
+ this.keyTags.delete(namespacedKey);
661
+ }
662
+
663
+ private _removeKeyDependencies(namespacedKey: string): void {
664
+ const patterns = this.keyDependencies.get(namespacedKey);
665
+ if (patterns) {
666
+ for (const pat of patterns) {
667
+ const deps = this.dependencyIndex.get(pat);
668
+ if (deps) {
669
+ deps.delete(namespacedKey);
670
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
671
+ }
672
+ }
673
+ this.keyDependencies.delete(namespacedKey);
674
+ } else if (this.dependencyIndex.size > 0) {
675
+ for (const [pat, deps] of this.dependencyIndex) {
676
+ deps.delete(namespacedKey);
677
+ if (deps.size === 0) this.dependencyIndex.delete(pat);
678
+ }
679
+ }
680
+ }
681
+
682
+ private _handleL1Eviction(namespacedKey: string, reason: EvictionReason): void {
683
+ const spilledToDisk = !this._diskDisabled && (
684
+ reason === 'capacity' ||
685
+ reason === 'category' ||
686
+ reason === 'rebalance' ||
687
+ reason === 'oom'
688
+ );
689
+ if (!spilledToDisk) {
690
+ this._removeKeyTags(namespacedKey);
691
+ this._removeKeyDependencies(namespacedKey);
692
+ }
693
+ }
694
+
695
+ private _removePrefixFromIndices(prefix: string): void {
696
+ for (const k of Array.from(this.keyTags.keys())) {
697
+ if (k.startsWith(prefix)) this._removeKeyTags(k);
698
+ }
699
+ for (const k of Array.from(this.keyDependencies.keys())) {
700
+ if (k.startsWith(prefix)) this._removeKeyDependencies(k);
701
+ }
702
+ for (const k of Array.from(this._l1Counters.keys())) {
703
+ if (k.startsWith(prefix)) this._l1Counters.delete(k);
704
+ }
705
+ }
706
+
707
+ private _sweepExpiredMetadata(): void {
708
+ const now = Date.now();
709
+ for (const [k, c] of this._l1Counters) {
710
+ if (c.expiresAt <= now) this._l1Counters.delete(k);
711
+ }
712
+ for (const [k, meta] of this.keyTags) {
713
+ if (meta.expiresAt <= now && !this.l1.has(k)) {
714
+ this._removeKeyTags(k);
715
+ this._removeKeyDependencies(k);
716
+ }
717
+ }
718
+ }
719
+
720
+ private _runOomCheck(): void {
721
+ const heap = v8.getHeapStatistics();
722
+ const heapUsed = heap.used_heap_size / heap.heap_size_limit;
723
+ const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0
724
+ ? process.memoryUsage().rss / this._cgroupMemoryLimit
725
+ : 0;
726
+ const used = Math.max(heapUsed, cgroupUsed);
727
+ if (used >= this.opts.oomHeapThreshold) {
728
+ const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
729
+ this.counters.oomEvictions++;
730
+ this.counters.oomLastAt = Date.now();
731
+ this.logger.warn('tricache OOM guard: emergency L1 eviction', {
732
+ heapUsedPct: Math.round(heapUsed * 100),
733
+ cgroupUsedPct: cgroupUsed > 0 ? Math.round(cgroupUsed * 100) : undefined,
734
+ threshold: Math.round(this.opts.oomHeapThreshold * 100),
735
+ evicted,
736
+ });
737
+ }
738
+ }
642
739
  private _ipcServer?: IpcTelemetryServer;
643
740
  /** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
644
741
  private _subDisconnectedAt: number | null = null;
@@ -688,6 +785,7 @@ export class CacheService {
688
785
  constructor(options: CacheOptions = {}) {
689
786
  const logger = options.logger ?? consoleLogger;
690
787
  this.logger = logger;
788
+ this._cgroupMemoryLimit = readCgroupMemoryLimit();
691
789
 
692
790
  // Resolve namespace: trim whitespace, default to empty string
693
791
  const ns = options.namespace?.trim() ?? '';
@@ -903,7 +1001,10 @@ export class CacheService {
903
1001
  // backplane handler already does for remote invalidations.
904
1002
  setImmediate(() => { void this.disk.save(key, entry as unknown as DiskCacheEntry); });
905
1003
  },
906
- onEviction: options.onEviction,
1004
+ onEviction: (key: string, reason: EvictionReason) => {
1005
+ this._handleL1Eviction(key, reason);
1006
+ options.onEviction?.(key, reason);
1007
+ },
907
1008
  logger,
908
1009
  });
909
1010
 
@@ -952,6 +1053,7 @@ export class CacheService {
952
1053
  // here to avoid a synchronous O(fileCount) event-loop stall at scale.
953
1054
  this.cleanupInterval = setInterval(() => {
954
1055
  const cleaned = this.l1.cleanup();
1056
+ this._sweepExpiredMetadata();
955
1057
  if (cleaned > 0) this.logger.debug('Periodic L1 cleanup', { cleaned });
956
1058
  }, 5 * 60 * 1000);
957
1059
  if (this.cleanupInterval.unref) this.cleanupInterval.unref(); // don't block process exit
@@ -965,21 +1067,10 @@ export class CacheService {
965
1067
  if (this.diskJanitorInterval.unref) this.diskJanitorInterval.unref();
966
1068
  }
967
1069
 
968
- // OOM protection: evict coldest L1 entries when heap pressure rises
1070
+ // OOM protection: evict coldest L1 entries when heap or container RSS pressure rises
969
1071
  if (this.opts.oomProtection) {
970
1072
  this.oomInterval = setInterval(() => {
971
- const heap = v8.getHeapStatistics();
972
- const used = heap.used_heap_size / heap.heap_size_limit;
973
- if (used >= this.opts.oomHeapThreshold) {
974
- const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
975
- this.counters.oomEvictions++;
976
- this.counters.oomLastAt = Date.now();
977
- this.logger.warn('tricache OOM guard: emergency L1 eviction', {
978
- heapUsedPct: Math.round(used * 100),
979
- threshold: Math.round(this.opts.oomHeapThreshold * 100),
980
- evicted,
981
- });
982
- }
1073
+ this._runOomCheck();
983
1074
  }, this.opts.oomCheckIntervalMs);
984
1075
  if (this.oomInterval.unref) this.oomInterval.unref();
985
1076
  }
@@ -1492,7 +1583,12 @@ export class CacheService {
1492
1583
  else if (f === 'tagVersion') tagVersionRaw = v;
1493
1584
  }
1494
1585
 
1495
- const validOp = op === 'del' || op === 'del-glob' || op === 'tag_incr';
1586
+ const validOp =
1587
+ op === 'del' ||
1588
+ op === 'del-glob' ||
1589
+ op === 'tag_incr' ||
1590
+ op === 'tag_pattern_incr' ||
1591
+ op === 'tag_pattern_del';
1496
1592
  if (!validOp || typeof key !== 'string' || !key || typeof src !== 'string') {
1497
1593
  this.logger.warn('Backplane: rejected invalid stream entry', {
1498
1594
  op: String(op).slice(0, 40),
@@ -1796,6 +1892,84 @@ export class CacheService {
1796
1892
  this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
1797
1893
  }
1798
1894
 
1895
+ private async _isGenerationalEntryStale(tagVersions?: Record<string, number>): Promise<boolean> {
1896
+ if (this.opts.tagStrategy !== 'generational' || !tagVersions) return false;
1897
+ const tags = Object.keys(tagVersions);
1898
+ if (tags.length === 0) return false;
1899
+ const currentVers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
1900
+ for (let i = 0; i < tags.length; i++) {
1901
+ if (currentVers[i] > tagVersions[tags[i]]) return true;
1902
+ }
1903
+ return false;
1904
+ }
1905
+
1906
+ private async _deleteRedisKeys(client: AnyRedisClient, keys: string[]): Promise<void> {
1907
+ if (keys.length === 0) return;
1908
+ const CHUNK_SIZE = 1_000;
1909
+ 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();
1915
+ }
1916
+ return;
1917
+ }
1918
+ for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
1919
+ const chunk = keys.slice(i, i + CHUNK_SIZE);
1920
+ await client.del(...chunk);
1921
+ }
1922
+ }
1923
+
1924
+ private async _parseGenerationalRedisHash<T>(
1925
+ k: string,
1926
+ hashData: Record<string, string>,
1927
+ ): Promise<{ value?: T; tagVersions?: Record<string, number>; stale: boolean } | null> {
1928
+ if (!hashData || !hashData.d) return null;
1929
+ let storedTagVersions: Record<string, number> = {};
1930
+ if (hashData.tv) {
1931
+ try { storedTagVersions = JSON.parse(hashData.tv); } catch { /* ignore */ }
1932
+ }
1933
+ if (await this._isGenerationalEntryStale(storedTagVersions)) {
1934
+ const setAtMs = parseInt(hashData.t, 10) || 0;
1935
+ this._deleteIfStale(k, setAtMs);
1936
+ return { stale: true };
1937
+ }
1938
+ const value = await this._decryptAndDeserialize<T>(hashData.d);
1939
+ return { value, tagVersions: storedTagVersions, stale: false };
1940
+ }
1941
+
1942
+ private async _readRedisEntry<T>(
1943
+ client: AnyRedisClient,
1944
+ k: string,
1945
+ allowAutoPipeline = false,
1946
+ ): Promise<{ value?: T; tagVersions?: Record<string, number>; stale: boolean } | null> {
1947
+ if (this.opts.tagStrategy === 'generational' && typeof (client as any).hgetall === 'function') {
1948
+ try {
1949
+ const hashData = await client.hgetall(k);
1950
+ if (typeof hashData === 'string') {
1951
+ const value = await this._decryptAndDeserialize<T>(hashData);
1952
+ return { value, stale: false };
1953
+ }
1954
+ if (hashData && hashData.d) {
1955
+ return await this._parseGenerationalRedisHash<T>(k, hashData);
1956
+ }
1957
+ return null;
1958
+ } catch (err) {
1959
+ const msg = err instanceof Error ? err.message : String(err);
1960
+ if (!msg.includes('WRONGTYPE')) throw err;
1961
+ // Fall through to GET if key was stored as a plain string without tags
1962
+ }
1963
+ }
1964
+
1965
+ const raw = (allowAutoPipeline && this.opts.autoPipeline && this.pipeliner)
1966
+ ? await this.pipeliner.get(k)
1967
+ : await client.get(k);
1968
+ if (raw == null) return null;
1969
+ const value = await this._decryptAndDeserialize<T>(raw);
1970
+ return { value, stale: false };
1971
+ }
1972
+
1799
1973
  private async _getTagVersion(tag: string): Promise<number> {
1800
1974
  const now = performance.now();
1801
1975
  const local = this.tagVersions.get(tag);
@@ -1948,10 +2122,9 @@ export class CacheService {
1948
2122
  }
1949
2123
 
1950
2124
  this.redisConnecting = (async () => {
2125
+ let client: AnyRedisClient | null = null;
1951
2126
  try {
1952
2127
  // ── Fix 4: Cluster / Sentinel / single-node connection factory ──────
1953
- let client: AnyRedisClient;
1954
-
1955
2128
  if (this.opts.redisClusterNodes?.length) {
1956
2129
  // Redis Cluster — ioredis handles slot routing and multi-node pooling.
1957
2130
  client = new RedisCluster(this.opts.redisClusterNodes, {
@@ -2018,15 +2191,45 @@ export class CacheService {
2018
2191
  client.on('reconnecting', () => this.logger.debug('Redis reconnecting'));
2019
2192
  }
2020
2193
 
2194
+ const pendingClient = client;
2021
2195
  await new Promise<void>((resolve, reject) => {
2022
- client.once('ready', resolve);
2023
- client.once('error', (e: Error) => {
2196
+ let settled = false;
2197
+ const cleanupListeners = () => {
2198
+ pendingClient.removeListener?.('ready', onReady);
2199
+ pendingClient.removeListener?.('error', onError);
2200
+ };
2201
+ const onReady = () => {
2202
+ if (settled) return;
2203
+ settled = true;
2204
+ clearTimeout(timer);
2205
+ cleanupListeners();
2206
+ resolve();
2207
+ };
2208
+ const onError = (e: Error) => {
2209
+ if (settled) return;
2210
+ settled = true;
2211
+ clearTimeout(timer);
2212
+ cleanupListeners();
2024
2213
  this._checkAndLogResp3Hint(e);
2025
2214
  reject(e);
2026
- });
2027
- setTimeout(() => reject(new Error('Redis connection timeout')), 15_000);
2215
+ };
2216
+ const timer = setTimeout(() => {
2217
+ if (settled) return;
2218
+ settled = true;
2219
+ cleanupListeners();
2220
+ reject(new Error('Redis connection timeout'));
2221
+ }, 15_000);
2222
+ if (timer.unref) timer.unref();
2223
+
2224
+ pendingClient.once('ready', onReady);
2225
+ pendingClient.once('error', onError);
2028
2226
  });
2029
2227
 
2228
+ if (this._destroyed) {
2229
+ try { client.disconnect(); } catch { /* ok */ }
2230
+ this._assertActive('getRedis');
2231
+ }
2232
+
2030
2233
  this.cb.onSuccess();
2031
2234
  this.redis = client;
2032
2235
  this.pipeliner = new AutoPipeliner(client, {
@@ -2036,6 +2239,7 @@ export class CacheService {
2036
2239
  this.redisConnecting = null;
2037
2240
  return client;
2038
2241
  } catch (err) {
2242
+ try { client?.disconnect(); } catch { /* ok */ }
2039
2243
  this.cb.onFailure();
2040
2244
  this.redisConnecting = null; // allow retry on next call — fixes the cached-rejection bug
2041
2245
  this._checkAndLogResp3Hint(err as Error);
@@ -2328,17 +2532,7 @@ export class CacheService {
2328
2532
  // L1: in-memory (fastest path)
2329
2533
  const l1Hit = this.l1.get(k);
2330
2534
  if (l1Hit !== null) {
2331
- let isGenerationalStale = false;
2332
- if (this.opts.tagStrategy === 'generational' && l1Hit.tagVersions) {
2333
- const tags = Object.keys(l1Hit.tagVersions);
2334
- const currentVers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
2335
- for (let i = 0; i < tags.length; i++) {
2336
- if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
2337
- isGenerationalStale = true;
2338
- break;
2339
- }
2340
- }
2341
- }
2535
+ const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
2342
2536
 
2343
2537
  if (isGenerationalStale) {
2344
2538
  this._deleteIfStale(k, l1Hit.setAt ?? 0);
@@ -2444,17 +2638,7 @@ export class CacheService {
2444
2638
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
2445
2639
 
2446
2640
  if (diskHit !== null) {
2447
- let isDiskStale = false;
2448
- if (this.opts.tagStrategy === 'generational' && diskHit.tagVersions) {
2449
- const tags = Object.keys(diskHit.tagVersions);
2450
- const currentVers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
2451
- for (let i = 0; i < tags.length; i++) {
2452
- if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
2453
- isDiskStale = true;
2454
- break;
2455
- }
2456
- }
2457
- }
2641
+ const isDiskStale = await this._isGenerationalEntryStale(diskHit.tagVersions);
2458
2642
 
2459
2643
  if (isDiskStale) {
2460
2644
  this.disk.delete(k);
@@ -2489,64 +2673,35 @@ export class CacheService {
2489
2673
  try {
2490
2674
  const client = await this.getRedis();
2491
2675
  const redisStart = performance.now();
2492
- if (this.opts.tagStrategy === 'generational') {
2493
- const hashData = await client.hgetall(k);
2494
- const redisElapsed = performance.now() - redisStart;
2495
- this.watchdog.recordRedis(redisElapsed);
2496
- this.cb.onSuccess();
2497
- if (hashData && hashData.d) {
2498
- let isStale = false;
2499
- let storedTagVersions: Record<string, number> = {};
2500
- if (hashData.tv) {
2501
- try { storedTagVersions = JSON.parse(hashData.tv); } catch { /* ignore */ }
2502
- }
2503
- const tags = Object.keys(storedTagVersions);
2504
- const currentVers = await Promise.all(tags.map(tag => this._getTagVersion(tag)));
2505
- for (let i = 0; i < tags.length; i++) {
2506
- if (currentVers[i] > storedTagVersions[tags[i]]) {
2507
- isStale = true;
2508
- break;
2509
- }
2510
- }
2511
- if (isStale) {
2512
- const setAtMs = parseInt(hashData.t, 10) || 0;
2513
- this._deleteIfStale(k, setAtMs);
2514
- } else {
2515
- const parsed = await this._decryptAndDeserialize<T>(hashData.d);
2516
- this.l1.set(k, parsed, ttlMs, priority, undefined, undefined, storedTagVersions);
2517
- this.counters.l2Hits++;
2518
- this.opts.onHit?.(cacheKey, 'l2');
2519
- this.logger.debug('L2 hit (Redis hash)', { cacheKey });
2520
- span.setAttribute('cache.hit', true)
2521
- .setAttribute('cache.item.tier', 'remote')
2522
- .setAttribute('cache.hit_tier', 'l2');
2523
- if (this.opts.frozen) deepFreeze(parsed);
2524
- return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
2525
- ? structuredClone(parsed)
2526
- : parsed;
2527
- }
2528
- }
2529
- } else {
2530
- const raw = (this.opts.autoPipeline && this.pipeliner)
2531
- ? await this.pipeliner.get(k)
2532
- : await client.get(k);
2533
- const redisElapsed = performance.now() - redisStart;
2534
- this.watchdog.recordRedis(redisElapsed);
2535
- this.cb.onSuccess();
2536
- if (raw) {
2537
- const parsed = await this._decryptAndDeserialize<T>(raw);
2538
- this.l1.set(k, parsed, ttlMs, priority);
2539
- this.counters.l2Hits++;
2540
- this.opts.onHit?.(cacheKey, 'l2');
2541
- this.logger.debug('L2 hit (Redis)', { cacheKey });
2542
- span.setAttribute('cache.hit', true)
2543
- .setAttribute('cache.item.tier', 'remote')
2544
- .setAttribute('cache.hit_tier', 'l2');
2545
- if (this.opts.frozen) deepFreeze(parsed);
2546
- return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
2547
- ? structuredClone(parsed)
2676
+ const redisHit = await this._readRedisEntry<T>(client, k, true);
2677
+ const redisElapsed = performance.now() - redisStart;
2678
+ this.watchdog.recordRedis(redisElapsed);
2679
+ this.cb.onSuccess();
2680
+ if (redisHit && !redisHit.stale && redisHit.value !== undefined) {
2681
+ const parsed = redisHit.value;
2682
+ if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
2683
+ this.logger.debug('Aborting L2 promotion — key was mutated or deleted during Redis read', { cacheKey });
2684
+ span.setAttribute('cache.aborted_mutation_race', true);
2685
+ const current = this.l1.get(k);
2686
+ const liveVal = (current && !current.isStale && current.value !== undefined)
2687
+ ? current.value as T
2548
2688
  : 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;
2549
2693
  }
2694
+ this.l1.set(k, parsed, ttlMs, priority, undefined, undefined, redisHit.tagVersions);
2695
+ this.counters.l2Hits++;
2696
+ this.opts.onHit?.(cacheKey, 'l2');
2697
+ this.logger.debug(redisHit.tagVersions ? 'L2 hit (Redis hash)' : 'L2 hit (Redis)', { cacheKey });
2698
+ span.setAttribute('cache.hit', true)
2699
+ .setAttribute('cache.item.tier', 'remote')
2700
+ .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;
2550
2705
  }
2551
2706
  } catch (err) {
2552
2707
  this.cb.onFailure();
@@ -2622,7 +2777,8 @@ export class CacheService {
2622
2777
  : data;
2623
2778
  }
2624
2779
 
2625
- this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
2780
+ const writeTs = Date.now();
2781
+ this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs);
2626
2782
 
2627
2783
  if (!this._redisDisabled) {
2628
2784
  try {
@@ -2630,13 +2786,12 @@ export class CacheService {
2630
2786
  const serialized = JSON.stringify(data);
2631
2787
  const toStore = await this._serializeAndEncrypt(serialized);
2632
2788
  const ttlSec = Math.ceil(effectiveTtl / 1_000);
2633
- if (this.opts.tagStrategy === 'generational' && activeTagVersions) {
2634
- const now = Date.now();
2789
+ if (this.opts.tagStrategy === 'generational' && (activeTagVersions || (!this.opts.autoPipeline && typeof (client as any).hgetall === 'function'))) {
2635
2790
  const tx = client.multi();
2636
2791
  tx.hset(k, {
2637
2792
  d: toStore,
2638
- t: String(now),
2639
- tv: JSON.stringify(activeTagVersions),
2793
+ t: String(writeTs),
2794
+ tv: JSON.stringify(activeTagVersions ?? {}),
2640
2795
  });
2641
2796
  tx.expire(k, ttlSec);
2642
2797
  await tx.exec();
@@ -2800,7 +2955,8 @@ export class CacheService {
2800
2955
  return;
2801
2956
  }
2802
2957
 
2803
- this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
2958
+ const writeTs = Date.now();
2959
+ this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs);
2804
2960
 
2805
2961
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2806
2962
  try {
@@ -2808,13 +2964,12 @@ export class CacheService {
2808
2964
  const s = JSON.stringify(data);
2809
2965
  const stored = await this._serializeAndEncrypt(s);
2810
2966
  const ttlSec = Math.ceil(ttlMs / 1_000);
2811
- if (this.opts.tagStrategy === 'generational' && activeTagVersions) {
2812
- const now = Date.now();
2967
+ if (this.opts.tagStrategy === 'generational' && (activeTagVersions || (!this.opts.autoPipeline && typeof (client as any).hgetall === 'function'))) {
2813
2968
  const tx = client.multi();
2814
2969
  tx.hset(cacheKey, {
2815
2970
  d: stored,
2816
- t: String(now),
2817
- tv: JSON.stringify(activeTagVersions),
2971
+ t: String(writeTs),
2972
+ tv: JSON.stringify(activeTagVersions ?? {}),
2818
2973
  });
2819
2974
  tx.expire(cacheKey, ttlSec);
2820
2975
  await tx.exec();
@@ -2879,16 +3034,23 @@ export class CacheService {
2879
3034
  }
2880
3035
  }
2881
3036
 
2882
- this.l1.set(k, data, ttlMs, p, undefined, undefined, activeTagVersions);
3037
+ const writeTs = Date.now();
3038
+ this.l1.set(k, data, ttlMs, p, undefined, undefined, activeTagVersions, writeTs);
2883
3039
 
2884
3040
  // Register dependency patterns: when any key matching a pattern is deleted,
2885
3041
  // this key (k) is automatically cascaded.
2886
- if (opts?.dependsOn?.length) {
2887
- for (const pattern of opts.dependsOn) {
2888
- const nsPattern = this.nk(pattern);
2889
- let deps = this.dependencyIndex.get(nsPattern);
2890
- if (!deps) { deps = new Set(); this.dependencyIndex.set(nsPattern, deps); }
2891
- deps.add(k);
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);
2892
3054
  }
2893
3055
  }
2894
3056
 
@@ -2898,13 +3060,12 @@ export class CacheService {
2898
3060
  const s = JSON.stringify(data);
2899
3061
  const stored = await this._serializeAndEncrypt(s);
2900
3062
  const ttlSec = Math.ceil(ttlMs / 1_000);
2901
- if (this.opts.tagStrategy === 'generational' && activeTagVersions) {
2902
- const now = Date.now();
3063
+ if (this.opts.tagStrategy === 'generational' && (activeTagVersions || (!this.opts.autoPipeline && typeof (client as any).hgetall === 'function'))) {
2903
3064
  const tx = client.multi();
2904
3065
  tx.hset(k, {
2905
3066
  d: stored,
2906
- t: String(now),
2907
- tv: JSON.stringify(activeTagVersions),
3067
+ t: String(writeTs),
3068
+ tv: JSON.stringify(activeTagVersions ?? {}),
2908
3069
  });
2909
3070
  tx.expire(k, ttlSec);
2910
3071
  await tx.exec();
@@ -2941,20 +3102,32 @@ export class CacheService {
2941
3102
  * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
2942
3103
  */
2943
3104
  private async _registerTags(k: string, tags: string[], ttlSeconds: number): Promise<void> {
2944
- for (const tag of tags) {
3105
+ this._removeKeyTags(k);
3106
+ const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
3107
+ 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
+ const uniqueTags = Array.from(new Set(tags));
3116
+ for (const tag of uniqueTags) {
2945
3117
  const tagKey = this.nk(`_tag_:${tag}`);
2946
3118
  let members = this.tagIndex.get(tagKey);
2947
3119
  if (!members) { members = new Set(); this.tagIndex.set(tagKey, members); }
2948
3120
  members.add(k);
2949
3121
  }
3122
+ this.keyTags.set(k, { tags: uniqueTags, expiresAt });
2950
3123
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2951
3124
  try {
2952
3125
  const client = await this.getRedis();
2953
3126
  const pl = client.pipeline();
2954
- for (const tag of tags) {
3127
+ for (const tag of uniqueTags) {
2955
3128
  const tagKey = this.nk(`_tag_:${tag}`);
2956
3129
  pl.sadd(tagKey, k);
2957
- pl.expire(tagKey, ttlSeconds + 3_600);
3130
+ pl.expire(tagKey, effectiveTtl + 3_600);
2958
3131
  }
2959
3132
  await pl.exec();
2960
3133
  this.cb.onSuccess();
@@ -2993,6 +3166,13 @@ export class CacheService {
2993
3166
  }
2994
3167
  this._addPatternTombstone(pfx);
2995
3168
  this.l1.deletePattern(k);
3169
+ this._removePrefixFromIndices(pfx);
3170
+ for (const ktKey of Array.from(this.keyTags.keys())) {
3171
+ if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
3172
+ }
3173
+ for (const kdKey of Array.from(this.keyDependencies.keys())) {
3174
+ if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
3175
+ }
2996
3176
  } else {
2997
3177
  this._bumpKeyMutation(k);
2998
3178
  this.inflight.delete(k);
@@ -3005,10 +3185,11 @@ export class CacheService {
3005
3185
  this._pendingDiskDeletes.delete(k);
3006
3186
  }
3007
3187
  });
3188
+ this._removeKeyTags(k);
3008
3189
  // Cascade: invalidate any key that declared it depends on this exact key's pattern
3009
3190
  this._cascadeDependencies(k);
3010
3191
  // Clean up: remove k from all dependency registrations (it is gone)
3011
- for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
3192
+ this._removeKeyDependencies(k);
3012
3193
  }
3013
3194
 
3014
3195
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
@@ -3016,7 +3197,7 @@ export class CacheService {
3016
3197
  const client = await this.getRedis();
3017
3198
  if (isPattern) {
3018
3199
  const keys = await this._scanKeys(client, k);
3019
- if (keys.length > 0) await client.del(...keys);
3200
+ await this._deleteRedisKeys(client, keys);
3020
3201
  } else {
3021
3202
  if (this.opts.autoPipeline && this.pipeliner) {
3022
3203
  await this.pipeliner.del(k);
@@ -3082,6 +3263,15 @@ export class CacheService {
3082
3263
  entry.value++;
3083
3264
  return entry.value;
3084
3265
  }
3266
+ if (this._l1Counters.size >= 50_000 && !this._l1Counters.has(k)) {
3267
+ for (const [ck, cv] of this._l1Counters) {
3268
+ if (cv.expiresAt <= now) this._l1Counters.delete(ck);
3269
+ }
3270
+ if (this._l1Counters.size >= 50_000) {
3271
+ const oldest = this._l1Counters.keys().next().value;
3272
+ if (oldest !== undefined) this._l1Counters.delete(oldest);
3273
+ }
3274
+ }
3085
3275
  this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
3086
3276
  return 1;
3087
3277
  }
@@ -3134,6 +3324,7 @@ export class CacheService {
3134
3324
  }
3135
3325
  this._addPatternTombstone(pfx);
3136
3326
  this.l1.deletePattern(k);
3327
+ this._removePrefixFromIndices(pfx);
3137
3328
  } else {
3138
3329
  this._globalEpoch++;
3139
3330
  this.inflight.clear();
@@ -3142,7 +3333,10 @@ export class CacheService {
3142
3333
  if (!this._diskDisabled) this.disk.clear();
3143
3334
  this._l1Counters.clear();
3144
3335
  this.tagIndex.clear();
3336
+ this.keyTags.clear();
3145
3337
  this.tagVersions.clear();
3338
+ this.dependencyIndex.clear();
3339
+ this.keyDependencies.clear();
3146
3340
  this._pendingDiskDeletes.clear();
3147
3341
  this._keyMutationEpochs.clear();
3148
3342
  }
@@ -3152,7 +3346,7 @@ export class CacheService {
3152
3346
  const client = await this.getRedis();
3153
3347
  const pattern = k ?? (this._namespace ? `${this._namespace}:*` : '*');
3154
3348
  const keys = await this._scanKeys(client, pattern);
3155
- if (keys.length > 0) await client.del(...keys);
3349
+ await this._deleteRedisKeys(client, keys);
3156
3350
  } catch (err) {
3157
3351
  this.logger.debug('clear: Redis unavailable', { error: (err as Error).message });
3158
3352
  }
@@ -3297,6 +3491,10 @@ export class CacheService {
3297
3491
  this._assertActive('touch');
3298
3492
  const k = this.nk(cacheKey);
3299
3493
  const hit = this.l1.touch(k, newTtlSeconds * 1_000);
3494
+ if (hit) {
3495
+ const kt = this.keyTags.get(k);
3496
+ if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1_000;
3497
+ }
3300
3498
  if (hit && !this._redisDisabled) {
3301
3499
  try {
3302
3500
  const client = await this.getRedis();
@@ -3325,6 +3523,13 @@ export class CacheService {
3325
3523
  return (entry.value !== undefined ? entry.value : this.codec.decode(entry.data)) as T;
3326
3524
  }
3327
3525
 
3526
+ private _prepareReadValue<T>(val: T): T {
3527
+ if (this.opts.frozen) deepFreeze(val);
3528
+ return (this.opts.cloneStrategy === 'structuredClone' && val != null && typeof val === 'object')
3529
+ ? structuredClone(val)
3530
+ : val;
3531
+ }
3532
+
3328
3533
  /**
3329
3534
  * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
3330
3535
  * Returns the cached value if found and valid, or `null` if absent / expired.
@@ -3340,13 +3545,13 @@ export class CacheService {
3340
3545
  // 1. L1 RAM
3341
3546
  const l1Hit = this.l1.get(k);
3342
3547
  if (l1Hit !== null) {
3343
- this.counters.gets++;
3344
- this.counters.l1Hits++;
3345
- const val = l1Hit.value as T;
3346
- if (this.opts.frozen) deepFreeze(val);
3347
- return (this.opts.cloneStrategy === 'structuredClone' && val != null && typeof val === 'object')
3348
- ? structuredClone(val)
3349
- : val;
3548
+ if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
3549
+ this._deleteIfStale(k, l1Hit.setAt ?? 0);
3550
+ } else {
3551
+ this.counters.gets++;
3552
+ this.counters.l1Hits++;
3553
+ return this._prepareReadValue(l1Hit.value as T);
3554
+ }
3350
3555
  }
3351
3556
 
3352
3557
  // 2. L1.5 Disk
@@ -3354,51 +3559,48 @@ export class CacheService {
3354
3559
  if (this._isTombstonedByPattern(k)) {
3355
3560
  try { this.disk.delete(k); } catch { /* ok */ }
3356
3561
  } else if (this.watchdog.isDiskAllowed()) {
3357
- const diskStart = performance.now();
3358
- const diskHit = this.disk.load(k);
3359
- const diskElapsed = performance.now() - diskStart;
3360
- this.watchdog.recordDisk(diskElapsed);
3361
- this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
3362
-
3363
- if (diskHit !== null) {
3364
- const promoted = this.l1.importEntries(
3365
- [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
3366
- this.opts.forbiddenSnapshotPrefixes,
3367
- );
3368
- if (promoted > 0) {
3369
- const l1Check = this.l1.get(k);
3370
- if (l1Check !== null) {
3371
- this.counters.gets++;
3372
- this.counters.diskHits++;
3373
- const val = l1Check.value as T;
3374
- if (this.opts.frozen) deepFreeze(val);
3375
- return (this.opts.cloneStrategy === 'structuredClone' && val != null && typeof val === 'object')
3376
- ? structuredClone(val)
3377
- : val;
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
+ }
3378
3584
  }
3379
3585
  }
3380
3586
  }
3381
3587
  }
3382
- }
3383
3588
 
3384
3589
  // 3. L2 Redis
3385
3590
  if (!this._redisDisabled && !this.cb.isOpen) {
3386
3591
  try {
3387
3592
  const client = await this.getRedis();
3388
3593
  const redisStart = performance.now();
3389
- const raw = await client.get(k);
3594
+ const redisHit = await this._readRedisEntry<T>(client, k);
3390
3595
  const redisElapsed = performance.now() - redisStart;
3391
3596
  this.watchdog.recordRedis(redisElapsed);
3392
- if (raw !== null) {
3393
- const parsed = await this._decryptAndDeserialize<T>(raw);
3394
- this.l1.set(k, parsed, 60_000, inferPriority(cacheKey));
3597
+ this.cb.onSuccess();
3598
+ if (redisHit && !redisHit.stale && redisHit.value !== undefined) {
3599
+ const parsed = redisHit.value;
3600
+ this.l1.set(k, parsed, 60_000, inferPriority(cacheKey), undefined, undefined, redisHit.tagVersions);
3395
3601
  this.counters.gets++;
3396
3602
  this.counters.l2Hits++;
3397
- this.cb.onSuccess();
3398
- if (this.opts.frozen) deepFreeze(parsed);
3399
- return (this.opts.cloneStrategy === 'structuredClone' && parsed != null && typeof parsed === 'object')
3400
- ? structuredClone(parsed)
3401
- : parsed;
3603
+ return this._prepareReadValue(parsed);
3402
3604
  }
3403
3605
  } catch (err) {
3404
3606
  this.cb.onFailure();
@@ -3435,12 +3637,20 @@ export class CacheService {
3435
3637
  const missKeys: string[] = [];
3436
3638
 
3437
3639
  // ── Tier 1: L1 (in-memory) ──
3640
+ const now = Date.now();
3438
3641
  for (let i = 0; i < keys.length; i++) {
3439
3642
  const k = this.nk(keys[i]);
3440
3643
  const entry = this.l1.getEntry(k);
3441
- if (entry && entry.expiresAt > Date.now()) {
3442
- result[i] = (entry.value !== undefined ? entry.value : this.codec.decode(entry.data)) as T;
3443
- this.counters.l1Hits++;
3644
+ if (entry && entry.expiresAt > now) {
3645
+ if (await this._isGenerationalEntryStale(entry.tagVersions)) {
3646
+ this._deleteIfStale(k, entry.setAt ?? 0);
3647
+ missIndexes.push(i);
3648
+ missKeys.push(keys[i]);
3649
+ } else {
3650
+ const val = (entry.value !== undefined ? entry.value : this.codec.decode(entry.data)) as T;
3651
+ result[i] = this._prepareReadValue(val);
3652
+ this.counters.l1Hits++;
3653
+ }
3444
3654
  } else {
3445
3655
  missIndexes.push(i);
3446
3656
  missKeys.push(keys[i]);
@@ -3464,23 +3674,61 @@ export class CacheService {
3464
3674
  const client = await this.getRedis();
3465
3675
  const nsKeys = missKeys.map(k => this.nk(k));
3466
3676
  const pipeline = client.multi();
3467
- for (const nk of nsKeys) pipeline.get(nk);
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
+ }
3468
3685
  const redisStart = performance.now();
3469
- const raws = await pipeline.exec() as Array<[Error | null, string | null] | null>;
3686
+ const raws = await pipeline.exec() as Array<[Error | null, any] | null>;
3470
3687
  const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
3471
3688
  this.watchdog.recordRedis(redisElapsed);
3472
3689
  this.cb.onSuccess();
3690
+
3473
3691
  for (let j = 0; j < missKeys.length; j++) {
3474
- const raw = raws[j] ? (raws[j] as [Error | null, string | null])[1] : null;
3692
+ const tuple = raws[j];
3693
+ const err = tuple ? tuple[0] : null;
3694
+ const rawVal = tuple ? tuple[1] : null;
3475
3695
  const idx = missIndexes[j];
3476
- if (raw) {
3477
- const parsed = await this._decryptAndDeserialize<T>(raw);
3478
- const k = nsKeys[j];
3696
+ 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) {
3479
3726
  const p = priority ?? inferPriority(missKeys[j]);
3480
- this.l1.set(k, parsed, this._jitterTtl((typeof ttl === 'function' ? ttl(missKeys[j]) : ttl) * 1_000), p);
3727
+ const ttlVal = typeof ttl === 'function' ? ttl(missKeys[j]) : ttl;
3728
+ this.l1.set(k, parsed, this._jitterTtl(ttlVal * 1_000), p, undefined, undefined, tagVersions);
3481
3729
  this.counters.l2Hits++;
3482
3730
  l2HitCount++;
3483
- result[idx] = parsed;
3731
+ result[idx] = this._prepareReadValue(parsed);
3484
3732
  missIndexes[j] = -1;
3485
3733
  missKeys[j] = '';
3486
3734
  }
@@ -3513,6 +3761,10 @@ export class CacheService {
3513
3761
  this.watchdog.recordDisk(diskElapsed);
3514
3762
  this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
3515
3763
  if (diskHit !== null) {
3764
+ if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
3765
+ this.disk.delete(k);
3766
+ continue;
3767
+ }
3516
3768
  const promoted = this.l1.importEntries(
3517
3769
  [{ key: k, entry: diskHit as unknown as SmartCacheEntry }],
3518
3770
  this.opts.forbiddenSnapshotPrefixes,
@@ -3521,7 +3773,7 @@ export class CacheService {
3521
3773
  const l1Check = this.l1.get(k);
3522
3774
  if (l1Check !== null) {
3523
3775
  this.counters.diskHits++;
3524
- result[missIndexes[j]] = l1Check.value as T;
3776
+ result[missIndexes[j]] = this._prepareReadValue(l1Check.value as T);
3525
3777
  missIndexes.splice(j, 1);
3526
3778
  missKeys.splice(j, 1);
3527
3779
  }
@@ -3780,6 +4032,153 @@ export class CacheService {
3780
4032
  return matched;
3781
4033
  }
3782
4034
 
4035
+ private async _publishTagInvalidation(
4036
+ op: 'tag_incr' | 'tag_pattern_incr' | 'tag_pattern_del',
4037
+ key: string,
4038
+ tagVersion?: number,
4039
+ ): Promise<void> {
4040
+ if (this.opts.awaitInvalidationBackplane) {
4041
+ await this.publishInvalidation(op, key, tagVersion, false, true);
4042
+ } else {
4043
+ void this.publishInvalidation(op, key, tagVersion, false, true);
4044
+ }
4045
+ }
4046
+
4047
+ private _removeTagMembersLocal(keys: Iterable<string>): void {
4048
+ const keyList = Array.isArray(keys) ? keys : Array.from(keys);
4049
+ for (const k of keyList) {
4050
+ this.l1.delete(k);
4051
+ this._bumpKeyMutation(k);
4052
+ this._removeKeyTags(k);
4053
+ 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
+ });
4062
+ }
4063
+ }
4064
+
4065
+ /**
4066
+ * Executes invalidation for a single already-resolved concrete tag without
4067
+ * wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
4068
+ */
4069
+ private async _invalidateConcreteTag(tag: string): Promise<void> {
4070
+ if (this.opts.tagStrategy === 'generational') {
4071
+ let newVer = 1;
4072
+ if (!this._redisDisabled) {
4073
+ try {
4074
+ const client = await this.getRedis();
4075
+ newVer = await client.incr(this.nk(`tag_ver:${tag}`));
4076
+ } catch (err) {
4077
+ this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
4078
+ const current = this.tagVersions.get(tag)?.version ?? 0;
4079
+ newVer = current + 1;
4080
+ }
4081
+ } else {
4082
+ const current = this.tagVersions.get(tag)?.version ?? 0;
4083
+ newVer = current + 1;
4084
+ }
4085
+ this._setLocalTagVersion(tag, newVer, performance.now());
4086
+ await this._publishTagInvalidation('tag_incr', tag, newVer);
4087
+ return;
4088
+ }
4089
+
4090
+ const tagKey = this.nk(`_tag_:${tag}`);
4091
+ const members = Array.from(this.tagIndex.get(tagKey) ?? []);
4092
+
4093
+ this.tagIndex.delete(tagKey);
4094
+ this._removeTagMembersLocal(members);
4095
+
4096
+ if (!this._redisDisabled) {
4097
+ try {
4098
+ const client = await this.getRedis();
4099
+ const redisMembers: string[] = await client.smembers(tagKey);
4100
+ const toDelete = [...new Set([...members, ...redisMembers, tagKey])];
4101
+ await this._deleteRedisKeys(client, toDelete);
4102
+ } catch (err) {
4103
+ this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
4104
+ }
4105
+ }
4106
+ }
4107
+
4108
+ /**
4109
+ * Executes invalidation for an array of already-resolved concrete tags
4110
+ * without re-entering wildcard/cascade resolution or invalidateTag().
4111
+ */
4112
+ private async _invalidateConcreteTags(tags: string[]): Promise<void> {
4113
+ if (tags.length === 0) return;
4114
+ if (tags.length === 1) {
4115
+ await this._invalidateConcreteTag(tags[0]);
4116
+ return;
4117
+ }
4118
+
4119
+ if (this.opts.tagStrategy === 'generational') {
4120
+ const now = performance.now();
4121
+ if (!this._redisDisabled) {
4122
+ try {
4123
+ const client = await this.getRedis();
4124
+ const pl = client.pipeline();
4125
+ for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
4126
+ const results = await pl.exec() as Array<[Error | null, number]>;
4127
+ for (let i = 0; i < tags.length; i++) {
4128
+ const [err, newVer] = results[i] ?? [null, null];
4129
+ const ver = (!err && typeof newVer === 'number') ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
4130
+ this._setLocalTagVersion(tags[i], ver, now);
4131
+ await this._publishTagInvalidation('tag_incr', tags[i], ver);
4132
+ }
4133
+ return;
4134
+ } catch (err) {
4135
+ this.logger.debug('invalidateTags: Redis unavailable', { tags, error: (err as Error).message });
4136
+ }
4137
+ }
4138
+ for (const tag of tags) {
4139
+ const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
4140
+ this._setLocalTagVersion(tag, ver, now);
4141
+ await this._publishTagInvalidation('tag_incr', tag, ver);
4142
+ }
4143
+ return;
4144
+ }
4145
+
4146
+ // In-process: collect all member keys across all tags and remove from L1 + disk
4147
+ const tagKeys: string[] = [];
4148
+ const allMembers = new Set<string>();
4149
+ for (const tag of tags) {
4150
+ const tagKey = this.nk(`_tag_:${tag}`);
4151
+ tagKeys.push(tagKey);
4152
+ const members = this.tagIndex.get(tagKey) ?? new Set<string>();
4153
+ for (const k of members) allMembers.add(k);
4154
+ this.tagIndex.delete(tagKey);
4155
+ }
4156
+ this._removeTagMembersLocal(allMembers);
4157
+
4158
+ if (!this._redisDisabled) {
4159
+ try {
4160
+ const client = await this.getRedis();
4161
+ // Single round-trip: pipeline SMEMBERS for all tag keys
4162
+ const pl = client.pipeline();
4163
+ for (const tagKey of tagKeys) pl.smembers(tagKey);
4164
+ const smResults = await pl.exec() as Array<[Error | null, string[] | null]>;
4165
+
4166
+ // Merge Redis members into the master delete set
4167
+ const toDelete: string[] = [...allMembers];
4168
+ for (const [err, redisMembers] of smResults) {
4169
+ if (!err && redisMembers) {
4170
+ for (const k of redisMembers) { if (!allMembers.has(k)) toDelete.push(k); }
4171
+ }
4172
+ }
4173
+ // Chunk/cluster-safe DEL for all member keys + tag keys
4174
+ const keysToRemove = [...toDelete, ...tagKeys];
4175
+ await this._deleteRedisKeys(client, keysToRemove);
4176
+ } catch (err) {
4177
+ this.logger.debug('invalidateTags: Redis unavailable', { tags, error: (err as Error).message });
4178
+ }
4179
+ }
4180
+ }
4181
+
3783
4182
  /**
3784
4183
  * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
3785
4184
  * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
@@ -3817,76 +4216,17 @@ export class CacheService {
3817
4216
  const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
3818
4217
 
3819
4218
  if (matchedTags.size > 0) {
3820
- await this.invalidateTags(Array.from(matchedTags));
4219
+ await this._invalidateConcreteTags(Array.from(matchedTags));
3821
4220
  }
3822
4221
 
3823
4222
  // Broadcast wildcard invalidation across backplane and cross-region
3824
4223
  const op = this.opts.tagStrategy === 'generational' ? 'tag_pattern_incr' : 'tag_pattern_del';
3825
- if (this.opts.awaitInvalidationBackplane) {
3826
- await this.publishInvalidation(op, broadcastPattern, undefined, false, true);
3827
- } else {
3828
- void this.publishInvalidation(op, broadcastPattern, undefined, false, true);
3829
- }
4224
+ await this._publishTagInvalidation(op, broadcastPattern);
3830
4225
  return;
3831
4226
  }
3832
4227
 
3833
4228
  // Fast-path: single discrete tag
3834
- if (this.opts.tagStrategy === 'generational') {
3835
- let newVer = 1;
3836
- if (!this._redisDisabled) {
3837
- try {
3838
- const client = await this.getRedis();
3839
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
3840
- } catch (err) {
3841
- this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
3842
- const current = this.tagVersions.get(tag)?.version ?? 0;
3843
- newVer = current + 1;
3844
- }
3845
- } else {
3846
- const current = this.tagVersions.get(tag)?.version ?? 0;
3847
- newVer = current + 1;
3848
- }
3849
- this._setLocalTagVersion(tag, newVer, performance.now());
3850
- if (this.opts.awaitInvalidationBackplane) {
3851
- await this.publishInvalidation('tag_incr', tag, newVer, false, true);
3852
- } else {
3853
- void this.publishInvalidation('tag_incr', tag, newVer, false, true);
3854
- }
3855
- return;
3856
- }
3857
-
3858
- const tagKey = this.nk(`_tag_:${tag}`);
3859
- const members = this.tagIndex.get(tagKey) ?? new Set<string>();
3860
-
3861
- // Remove from L1 + disk
3862
- for (const k of members) {
3863
- this.l1.delete(k);
3864
- this._bumpKeyMutation(k);
3865
- this._pendingDiskDeletes.add(k);
3866
- setImmediate(() => {
3867
- try {
3868
- if (!this._diskDisabled) this.disk.delete(k);
3869
- } finally {
3870
- this._pendingDiskDeletes.delete(k);
3871
- }
3872
- });
3873
- }
3874
- this.tagIndex.delete(tagKey);
3875
-
3876
- if (!this._redisDisabled) {
3877
- try {
3878
- const client = await this.getRedis();
3879
- const redisMembers: string[] = await client.smembers(tagKey);
3880
- const toDelete = [...new Set([...members, ...redisMembers])];
3881
- if (toDelete.length > 0) {
3882
- await client.del(...toDelete, tagKey);
3883
- } else {
3884
- await client.del(tagKey);
3885
- }
3886
- } catch (err) {
3887
- this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
3888
- }
3889
- }
4229
+ await this._invalidateConcreteTag(tag);
3890
4230
  } catch (err) {
3891
4231
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
3892
4232
  span.recordException?.(err);
@@ -3916,100 +4256,32 @@ export class CacheService {
3916
4256
 
3917
4257
  if (hasWildcards || shouldCascade) {
3918
4258
  const allResolvedTags = new Set<string>();
4259
+ const broadcastPatterns = new Set<string>();
4260
+ const delim = this.opts.tagHierarchyDelimiter;
4261
+
3919
4262
  for (const t of tags) {
3920
- if (isWildcardTag(t) || shouldCascade) {
4263
+ const tIsPattern = isWildcardTag(t);
4264
+ if (tIsPattern || shouldCascade) {
4265
+ broadcastPatterns.add(tIsPattern ? t : `${t}${delim}*`);
3921
4266
  const resolved = await this._resolveMatchingTags(t, shouldCascade);
3922
4267
  for (const rt of resolved) allResolvedTags.add(rt);
3923
4268
  } else {
3924
4269
  allResolvedTags.add(t);
3925
4270
  }
3926
4271
  }
3927
- if (allResolvedTags.size === 0) return;
3928
- tags = Array.from(allResolvedTags);
3929
- }
3930
-
3931
- if (tags.length === 1) { await this.invalidateTag(tags[0], opts); return; }
3932
4272
 
3933
- if (this.opts.tagStrategy === 'generational') {
3934
- const now = performance.now();
3935
- if (!this._redisDisabled) {
3936
- try {
3937
- const client = await this.getRedis();
3938
- const pl = client.pipeline();
3939
- for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
3940
- const results = await pl.exec() as Array<[Error | null, number]>;
3941
- for (let i = 0; i < tags.length; i++) {
3942
- const [err, newVer] = results[i] ?? [null, null];
3943
- const ver = (!err && typeof newVer === 'number') ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
3944
- this._setLocalTagVersion(tags[i], ver, now);
3945
- if (this.opts.awaitInvalidationBackplane) {
3946
- await this.publishInvalidation('tag_incr', tags[i], ver, false, true);
3947
- } else {
3948
- void this.publishInvalidation('tag_incr', tags[i], ver, false, true);
3949
- }
3950
- }
3951
- return;
3952
- } catch (err) {
3953
- this.logger.debug('invalidateTags: Redis unavailable', { tags, error: (err as Error).message });
3954
- }
4273
+ if (allResolvedTags.size > 0) {
4274
+ await this._invalidateConcreteTags(Array.from(allResolvedTags));
3955
4275
  }
3956
- for (const tag of tags) {
3957
- const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
3958
- this._setLocalTagVersion(tag, ver, now);
3959
- if (this.opts.awaitInvalidationBackplane) {
3960
- await this.publishInvalidation('tag_incr', tag, ver, false, true);
3961
- } else {
3962
- void this.publishInvalidation('tag_incr', tag, ver, false, true);
3963
- }
4276
+
4277
+ const op = this.opts.tagStrategy === 'generational' ? 'tag_pattern_incr' : 'tag_pattern_del';
4278
+ for (const pattern of broadcastPatterns) {
4279
+ await this._publishTagInvalidation(op, pattern);
3964
4280
  }
3965
4281
  return;
3966
4282
  }
3967
4283
 
3968
- // In-process: collect all member keys across all tags and remove from L1 + disk
3969
- const tagKeys: string[] = [];
3970
- const allMembers = new Set<string>();
3971
- for (const tag of tags) {
3972
- const tagKey = this.nk(`_tag_:${tag}`);
3973
- tagKeys.push(tagKey);
3974
- const members = this.tagIndex.get(tagKey) ?? new Set<string>();
3975
- for (const k of members) allMembers.add(k);
3976
- this.tagIndex.delete(tagKey);
3977
- }
3978
- for (const k of allMembers) {
3979
- this.l1.delete(k);
3980
- this._bumpKeyMutation(k);
3981
- this._pendingDiskDeletes.add(k);
3982
- setImmediate(() => {
3983
- try {
3984
- if (!this._diskDisabled) this.disk.delete(k);
3985
- } finally {
3986
- this._pendingDiskDeletes.delete(k);
3987
- }
3988
- });
3989
- }
3990
-
3991
- if (!this._redisDisabled) {
3992
- try {
3993
- const client = await this.getRedis();
3994
- // Single round-trip: pipeline SMEMBERS for all tag keys
3995
- const pl = client.pipeline();
3996
- for (const tagKey of tagKeys) pl.smembers(tagKey);
3997
- const smResults = await pl.exec() as Array<[Error | null, string[] | null]>;
3998
-
3999
- // Merge Redis members into the master delete set
4000
- const toDelete: string[] = [...allMembers];
4001
- for (const [err, redisMembers] of smResults) {
4002
- if (!err && redisMembers) {
4003
- for (const k of redisMembers) { if (!allMembers.has(k)) toDelete.push(k); }
4004
- }
4005
- }
4006
- // Single DEL for all member keys + tag keys
4007
- const keysToRemove = [...toDelete, ...tagKeys];
4008
- if (keysToRemove.length > 0) await client.del(...keysToRemove);
4009
- } catch (err) {
4010
- this.logger.debug('invalidateTags: Redis unavailable', { tags, error: (err as Error).message });
4011
- }
4012
- }
4284
+ await this._invalidateConcreteTags(Array.from(new Set(tags)));
4013
4285
  }
4014
4286
 
4015
4287
  /**
@@ -4644,6 +4916,13 @@ export class CacheService {
4644
4916
  this._destroyed = true;
4645
4917
  this._pendingDiskDeletes.clear();
4646
4918
  this._keyMutationEpochs.clear();
4919
+ this.inflight.clear();
4920
+ this.revalidating.clear();
4921
+ this._l1Counters.clear();
4922
+ this.tagIndex.clear();
4923
+ this.keyTags.clear();
4924
+ this.dependencyIndex.clear();
4925
+ this.keyDependencies.clear();
4647
4926
  const g = globalThis as Record<string, unknown>;
4648
4927
  const key = CacheService.globalKey(this.opts);
4649
4928
  if (g[key] === this) {