tricache 1.0.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +78 -90
  2. package/dashboards/tricache-alerts.yaml +80 -4
  3. package/dashboards/tricache-grafana.json +54 -1
  4. package/dashboards/tricache-inventory.rules.yml +21 -0
  5. package/dist/{cache-service-CWI4jkS7.d.cts → cache-service-BV5T8-20.d.cts} +122 -21
  6. package/dist/cache-service-UZXOQGEY.js +14 -0
  7. package/dist/{cache-service-B108FzER.d.ts → cache-service-tpyrXvlH.d.ts} +122 -21
  8. package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
  9. package/dist/{chunk-H4GFLQ26.js → chunk-KV7KISK2.js} +47 -1
  10. package/dist/{chunk-WYF7NOAT.js → chunk-MB3DMVWN.js} +2111 -543
  11. package/dist/{chunk-OYDU3SMI.js → chunk-RBJRTGFK.js} +5 -0
  12. package/dist/chunk-S5N65I45.js +17 -0
  13. package/dist/cli.cjs +2454 -572
  14. package/dist/cli.js +186 -11
  15. package/dist/dashboard/index.d.cts +2 -2
  16. package/dist/dashboard/index.d.ts +2 -2
  17. package/dist/drizzle/index.cjs +2335 -571
  18. package/dist/drizzle/index.d.cts +2 -2
  19. package/dist/drizzle/index.d.ts +2 -2
  20. package/dist/drizzle/index.js +6 -2
  21. package/dist/edge/index.cjs +145 -43
  22. package/dist/edge/index.d.cts +11 -4
  23. package/dist/edge/index.d.ts +11 -4
  24. package/dist/edge/index.js +118 -43
  25. package/dist/hono/index.cjs +2322 -569
  26. package/dist/hono/index.d.cts +2 -2
  27. package/dist/hono/index.d.ts +2 -2
  28. package/dist/hono/index.js +2 -2
  29. package/dist/{hono-C886ok3X.d.cts → hono-CMv2VdQ6.d.cts} +18 -5
  30. package/dist/{hono-3rDMYVtY.d.ts → hono-Dvq04kX9.d.ts} +18 -5
  31. package/dist/http/index.cjs +2323 -570
  32. package/dist/http/index.d.cts +3 -3
  33. package/dist/http/index.d.ts +3 -3
  34. package/dist/http/index.js +4 -4
  35. package/dist/index.cjs +2554 -620
  36. package/dist/index.d.cts +88 -23
  37. package/dist/index.d.ts +88 -23
  38. package/dist/index.js +873 -16
  39. package/dist/{murmur3-CMGw9PbV.d.cts → murmur3-DF8BFRnu.d.cts} +1 -0
  40. package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.ts} +1 -0
  41. package/dist/nestjs/index.cjs +2292 -574
  42. package/dist/nestjs/index.d.cts +19 -5
  43. package/dist/nestjs/index.d.ts +19 -5
  44. package/dist/nestjs/index.js +25 -19
  45. package/dist/next/index.cjs +2306 -571
  46. package/dist/next/index.d.cts +8 -2
  47. package/dist/next/index.d.ts +8 -2
  48. package/dist/next/index.js +36 -9
  49. package/dist/prisma/index.cjs +26 -25
  50. package/dist/prisma/index.d.cts +2 -2
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +14 -25
  53. package/dist/serialize-worker.cjs +162 -39
  54. package/dist/serialize-worker.js +9 -7
  55. package/dist/{types-BA4pz1A0.d.cts → types-F8vRWMrE.d.cts} +162 -45
  56. package/dist/{types-BA4pz1A0.d.ts → types-F8vRWMrE.d.ts} +162 -45
  57. package/package.json +21 -2
  58. package/src/adapters/auto-pipeliner.ts +52 -11
  59. package/src/cache-service.ts +1537 -415
  60. package/src/cli.ts +2 -9
  61. package/src/codec.ts +3 -3
  62. package/src/compression.ts +39 -16
  63. package/src/cross-region.ts +1 -1
  64. package/src/disk-tier.ts +283 -43
  65. package/src/drizzle/index.ts +2 -1
  66. package/src/edge/adapters/cloudflare-do.ts +25 -10
  67. package/src/edge/adapters/cloudflare-kv.ts +12 -9
  68. package/src/edge/adapters/upstash.ts +27 -11
  69. package/src/edge/cache.ts +59 -17
  70. package/src/edge/types.ts +15 -5
  71. package/src/encryption.ts +50 -18
  72. package/src/env.d.ts +1 -1
  73. package/src/errors.ts +12 -0
  74. package/src/http/utils.ts +6 -0
  75. package/src/index.ts +6 -0
  76. package/src/latency-watchdog.ts +5 -1
  77. package/src/nestjs/decorators.ts +11 -6
  78. package/src/nestjs/tricache.module.ts +2 -1
  79. package/src/nestjs/tricache.store.ts +21 -9
  80. package/src/nestjs/types.ts +1 -1
  81. package/src/next/cache-handler.ts +24 -4
  82. package/src/next/types.ts +4 -0
  83. package/src/origin-capacity.ts +134 -0
  84. package/src/prisma/index.ts +14 -32
  85. package/src/remote-snapshot.ts +37 -27
  86. package/src/serialize-worker.ts +8 -5
  87. package/src/sigv4-snapshot-adapter.ts +37 -27
  88. package/src/smart-memory-cache.ts +62 -22
  89. package/src/types.ts +92 -35
  90. package/src/utils/config-comparison.ts +29 -0
  91. package/src/utils/lz4-size.ts +74 -0
  92. package/src/utils/namespace-key.ts +48 -0
  93. package/src/utils/query-key.ts +13 -0
  94. package/src/utils/snapshot-transfer.ts +83 -0
  95. package/src/utils/work-limits.ts +73 -0
  96. package/src/utils/write-revision.ts +4 -0
  97. package/src/wasm/bloom-filter-wasm.ts +16 -1
  98. package/src/worker-pool.ts +28 -8
  99. package/src/wtiny-lfu.ts +62 -14
  100. package/dist/cache-service-GYPZFB7O.js +0 -12
  101. package/dist/chunk-VNRDL5RA.js +0 -666
@@ -61,6 +61,12 @@ import { TierLatencyWatchdog } from './latency-watchdog';
61
61
  import { resolveAutonomousL1MaxBytes, readCgroupMemoryLimit, readCgroupMemoryUsage } from './utils/cgroup';
62
62
  import { redactDiagnostics } from './utils/diagnostics';
63
63
  import { redisHashSlot } from './utils/redis-slot';
64
+ import { isWriteRevision } from './utils/write-revision.js';
65
+ import { CacheCapacityError, DependencyBudget, positiveLimit, WorkLimit } from './utils/work-limits.js';
66
+ import { CacheInvalidationUnavailableError } from './errors.js';
67
+ import { OriginCapacityLimiter } from './origin-capacity.js';
68
+ import { captureConfiguration, sameConfiguration } from './utils/config-comparison.js';
69
+ import { encodeNamespaceSegment, namespaceBackplaneChannel, namespaceDomainPrefix, namespaceKeyPrefix, namespaceSingletonKey, namespaceStreamKey } from './utils/namespace-key.js';
64
70
  import { withDeadline } from './utils/deadline';
65
71
  import { AutoPipeliner, readRedisValue } from './adapters/auto-pipeliner';
66
72
  import { IpcTelemetryServer } from './ipc-telemetry.js';
@@ -83,8 +89,9 @@ import {
83
89
  // ─── Lua scripts ─────────────────────────────────────────────────────────────
84
90
 
85
91
  const LUA_COMPARE_AND_DELETE = `
86
- local currentTs = redis.call('HGET', KEYS[1], 't')
87
- if currentTs and currentTs == ARGV[1] then
92
+ if redis.call('TYPE', KEYS[1]).ok ~= 'hash' then return 0 end
93
+ local currentRevision = redis.call('HGET', KEYS[1], 'r')
94
+ if currentRevision and currentRevision == ARGV[1] then
88
95
  return redis.call('DEL', KEYS[1])
89
96
  end
90
97
  return 0
@@ -114,35 +121,73 @@ redis.call('SET', KEYS[1], next)
114
121
  return next
115
122
  `;
116
123
 
124
+ // One tag key per script keeps registration safe for Redis Cluster slots.
125
+ const LUA_REGISTER_TAG = `
126
+ local existed = redis.call('EXISTS', KEYS[1])
127
+ redis.call('SADD', KEYS[1], ARGV[1])
128
+ local ttl = redis.call('PTTL', KEYS[1])
129
+ local clock = redis.call('TIME')
130
+ local now = tonumber(clock[1]) * 1000 + math.floor(tonumber(clock[2]) / 1000)
131
+ local deadline = tonumber(ARGV[2])
132
+ if existed == 0 or (ttl >= 0 and now + ttl < deadline) then
133
+ redis.call('PEXPIREAT', KEYS[1], deadline)
134
+ end
135
+ return 1
136
+ `;
137
+
117
138
  const LUA_TOUCH_CACHE_ENTRY = `
118
139
  local kind = redis.call('TYPE', KEYS[1]).ok
119
140
  if kind == 'hash' then
120
- if redis.call('HGET', KEYS[1], 't') ~= ARGV[1] then return 0 end
141
+ if redis.call('HGET', KEYS[1], 'r') ~= ARGV[1] then return 0 end
121
142
  redis.call('HSET', KEYS[1], 'e', ARGV[2])
143
+ if ARGV[4] and ARGV[4] ~= '' then redis.call('HSET', KEYS[1], 'd', ARGV[4]) end
122
144
  elseif kind ~= 'string' then
123
145
  return 0
124
146
  end
125
147
  return redis.call('PEXPIRE', KEYS[1], ARGV[3])
126
148
  `;
127
149
 
150
+ // Positive TTL requests a fixed window, including repair of persistent counters.
151
+ // A zero TTL leaves existing expiry untouched and creates permanent counters.
152
+ const LUA_INCREMENT_COUNTER = `
153
+ local count = redis.call('INCR', KEYS[1])
154
+ local ttlMs = tonumber(ARGV[1])
155
+ if ttlMs > 0 and redis.call('PTTL', KEYS[1]) == -1 then
156
+ redis.call('PEXPIRE', KEYS[1], ARGV[1])
157
+ end
158
+ return count
159
+ `;
160
+
128
161
  interface RedisCacheEntry<T> {
129
162
  value?: T;
130
163
  tagVersions?: Record<string, number>;
131
164
  tags?: string[];
132
165
  dependsOn?: string[];
133
166
  setAt?: number;
167
+ revision?: string;
134
168
  expiresAt?: number;
135
169
  staleAt?: number;
136
170
  stale: boolean;
137
171
  }
138
172
 
173
+ interface DependencyCascade {
174
+ keys: string[];
175
+ finish: () => void;
176
+ }
177
+
139
178
  // ─── Snapshot constants ───────────────────────────────────────────────────────
140
179
 
141
- const SNAPSHOT_VERSION = 1;
180
+ const SNAPSHOT_VERSION = 3;
142
181
  const DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1000; // 2 hours
143
182
  /** ttl 0 ("indefinite", per the NestJS store contract) maps to a 1-year expiry. */
144
- const INDEFINITE_TTL_SECONDS = 31_536_000;
183
+ export const INDEFINITE_TTL_SECONDS = 31_536_000;
184
+ /** Keep discovery metadata beyond the latest known hard entry deadline. */
185
+ const TAG_REGISTRY_GRACE_MS = 3_600_000;
186
+ /** Versioned Redis plaintext envelope, inside optional compression/encryption. */
187
+ const PREFIX_MSGPACK = 'mpk:v1:';
145
188
  const SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024; // 220 MB guard
189
+ /** Sentinel for an invalid tag-version payload shared by Pub/Sub and Streams. */
190
+ const INVALID_TAG_VERSION = Symbol('invalid-tag-version');
146
191
 
147
192
  // ─── Default category limits ──────────────────────────────────────────────────
148
193
 
@@ -154,9 +199,6 @@ const DEFAULT_CATEGORY_LIMITS: Record<string, CategoryLimit> = {
154
199
 
155
200
  const DEFAULT_FORBIDDEN_PREFIXES = ['auth:', 'session:', 'mfa:', 'rate_limit:'] as const;
156
201
 
157
- // ─── Default counter TTL ──────────────────────────────────────────────────────
158
- const DEFAULT_COUNTER_TTL_SECONDS = 60;
159
-
160
202
  // ─── Glob regex cache (bounded LRU, max 256 compiled patterns) ───────────────
161
203
  const GLOB_REGEX_CACHE_MAX = 256;
162
204
  const globRegexCache = new Map<string, RegExp>();
@@ -189,6 +231,9 @@ function getGlobRegex(pattern: string): RegExp {
189
231
  // ─────────────────────────────────────────────────────────────────────────────
190
232
 
191
233
  const enum CBState { CLOSED, OPEN, HALF_OPEN }
234
+ class RedisCircuitOpenError extends Error {
235
+ constructor() { super('tricache: L2 circuit breaker is open'); }
236
+ }
192
237
 
193
238
  class L2CircuitBreaker {
194
239
  private state = CBState.CLOSED;
@@ -196,6 +241,7 @@ class L2CircuitBreaker {
196
241
  private openedAt = performance.now();
197
242
  /** True while the single permitted HALF_OPEN probe is in flight. */
198
243
  private probing = false;
244
+ private probeSequence = 0;
199
245
  constructor(
200
246
  private readonly threshold: number,
201
247
  private readonly cooldownMs: number,
@@ -212,6 +258,7 @@ class L2CircuitBreaker {
212
258
  if (this.state === CBState.HALF_OPEN) {
213
259
  if (this.probing) return false; // a probe is already in flight
214
260
  this.probing = true;
261
+ this.probeSequence++;
215
262
  return true; // this caller is the one permitted probe
216
263
  }
217
264
  // OPEN: check if cooldown elapsed using monotonic clock (immune to NTP drift / leap seconds).
@@ -220,11 +267,21 @@ class L2CircuitBreaker {
220
267
  if (now - this.openedAt >= this.cooldownMs) {
221
268
  this.state = CBState.HALF_OPEN;
222
269
  this.probing = true;
270
+ this.probeSequence++;
223
271
  return true; // probe
224
272
  }
225
273
  return false;
226
274
  }
227
275
 
276
+ get probeToken(): number | null {
277
+ return this.state === CBState.HALF_OPEN && this.probing ? this.probeSequence : null;
278
+ }
279
+
280
+ /** A cancelled publisher may release only the probe it actually acquired. */
281
+ releaseProbe(token: number | null): void {
282
+ if (token !== null && token === this.probeToken) this.probing = false;
283
+ }
284
+
228
285
  /** Call on Redis success. */
229
286
  onSuccess(): void {
230
287
  this.failures = 0;
@@ -233,7 +290,11 @@ class L2CircuitBreaker {
233
290
  }
234
291
 
235
292
  /** Call on Redis failure. */
236
- onFailure(): void {
293
+ onFailure(error?: unknown): void {
294
+ if (error instanceof RedisCircuitOpenError) return;
295
+ // An open circuit already rejected work. Rejections (and late failures from
296
+ // older requests) must not postpone its next recovery opportunity.
297
+ if (this.state === CBState.OPEN) return;
237
298
  this.failures++;
238
299
  this.probing = false;
239
300
  if (this.state === CBState.HALF_OPEN || this.failures >= this.threshold) {
@@ -292,6 +353,11 @@ interface LatencyMeta {
292
353
  dirty: boolean; // true when a new sample was written since last p95 computation
293
354
  }
294
355
 
356
+ /** Fetch durations and internal TTL bounds are milliseconds; the multiplier is dimensionless. */
357
+ function resolveAdaptiveTtlMs(p95Ms: number, multiplier: number, minMs: number, maxMs: number): number {
358
+ return Math.max(minMs, Math.min(maxMs, Math.round(p95Ms * multiplier)));
359
+ }
360
+
295
361
  class LatencyTracker {
296
362
  private readonly samples: number;
297
363
  private readonly maxKeys: number;
@@ -329,7 +395,7 @@ class LatencyTracker {
329
395
 
330
396
  /**
331
397
  * Recomputes the p95 for the given key into `m.p95` and clears `m.dirty`.
332
- * Uses the shared scratch buffer — no heap allocation.
398
+ * Reuses the scratch storage; subarray views still allocate small wrapper objects.
333
399
  */
334
400
  private _computeP95(buf: Float64Array, m: LatencyMeta): void {
335
401
  const n = m.count;
@@ -360,12 +426,12 @@ class LatencyTracker {
360
426
  * Keys with < 5 samples are excluded (not enough data for a reliable p95).
361
427
  *
362
428
  * Only dirty keys (those with new samples since the last call) pay the sort
363
- * cost. Keys whose p95 is already cached are O(1) reads — so repeated
364
- * metrics() calls with no intervening fetches are essentially free.
429
+ * cost. Cached p95 reads are O(1), but the snapshot still allocates, scans
430
+ * tracked keys, and sorts the rankings.
365
431
  */
366
432
  snapshot(
367
433
  prefixLen: number,
368
- multiplierSec: number,
434
+ multiplier: number,
369
435
  minMs: number,
370
436
  maxMs: number,
371
437
  ): Array<{ key: string; p95Ms: number; adaptedTtlSec: number }> {
@@ -375,7 +441,7 @@ class LatencyTracker {
375
441
  if (m.count < 5) continue;
376
442
  if (m.dirty) this._computeP95(buf, m); // sort only when new sample arrived
377
443
  const p95 = m.p95;
378
- const adaptedMs = Math.max(minMs, Math.min(maxMs, Math.round(p95 * multiplierSec * 1_000)));
444
+ const adaptedMs = resolveAdaptiveTtlMs(p95, multiplier, minMs, maxMs);
379
445
  out.push({
380
446
  key: prefixLen > 0 ? key.slice(prefixLen) : key,
381
447
  p95Ms: Math.round(p95),
@@ -386,6 +452,19 @@ class LatencyTracker {
386
452
  }
387
453
  }
388
454
 
455
+ /**
456
+ * Escape a Prometheus label value per the text exposition format:
457
+ * backslash, double quote, and newline are escaped; other characters pass through.
458
+ * @see https://prometheus.io/docs/instrumenting/exposition_formats/
459
+ */
460
+ function isGlobLineTerminator(value: string): boolean {
461
+ return value === '\n' || value === '\r' || value === '\u2028' || value === '\u2029';
462
+ }
463
+
464
+ function escapePrometheusLabel(value: string): string {
465
+ return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
466
+ }
467
+
389
468
  function inferPriority(cacheKey: string): CachePriority {
390
469
  if (cacheKey.includes('auth:') || cacheKey.includes('session:')) return CachePriority.CRITICAL;
391
470
  if (cacheKey.includes('user:') || cacheKey.includes('org:') || cacheKey.includes('profile:')) return CachePriority.HIGH;
@@ -397,9 +476,6 @@ function inferPriority(cacheKey: string): CachePriority {
397
476
  // CacheService
398
477
  // ─────────────────────────────────────────────────────────────────────────────
399
478
 
400
- // globalThis key — allows reuse across hot reloads (Next.js, ts-node watch, etc.)
401
- const GLOBAL_KEY = '__tricache_instance__';
402
-
403
479
  // ── Union type for single-node, Cluster, Sentinel, and pluggable Redis drivers ──
404
480
  type AnyRedisClient = RedisClient | RedisCluster | IRedisDriver | any;
405
481
 
@@ -512,6 +588,14 @@ export function deepMergeOptions(base: CacheOptions, overrides?: Partial<CacheOp
512
588
  }
513
589
 
514
590
  export class CacheService {
591
+ private readonly _originWork: WorkLimit;
592
+ private readonly _backgroundWork: WorkLimit;
593
+ private readonly _originCapacityLimiter: OriginCapacityLimiter | undefined;
594
+ private readonly _dependencyBudget: DependencyBudget;
595
+ private readonly _dependencyReleases = new Map<string, () => void>();
596
+ private readonly _dependencyExpirations = new Map<string, number>();
597
+ private readonly _lifecycle = new AbortController();
598
+ private readonly _singletonConfig: Record<string, unknown>;
515
599
  private readonly logger: ILogger;
516
600
  private readonly enc: CacheEncryption;
517
601
  private readonly codec: CacheCodec;
@@ -522,6 +606,12 @@ export class CacheService {
522
606
  /** Worker pool for off-main-thread AES-GCM (null when workerThreads is false or unavailable). */
523
607
  private _workerPool: WorkerPool | null = null;
524
608
  private readonly opts: {
609
+ originCapacityLimiter: OriginCapacityLimiter | undefined;
610
+ maxConcurrentFetches: number;
611
+ maxBackgroundRefreshes: number;
612
+ maxDependencyEdges: number;
613
+ workerMaxPendingTasks: number;
614
+ workerMaxPendingBytes: number;
525
615
  namespace: string;
526
616
  logger: ILogger; l1MaxBytes: number; l1MaxEntries: number;
527
617
  categoryLimits: Record<string, CategoryLimit>;
@@ -531,6 +621,7 @@ export class CacheService {
531
621
  encryptionKey: string | undefined; encryptionMode: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor' | undefined; snapshotPath: string; snapshotMaxAgeMs: number;
532
622
  invalidationBackplane: boolean;
533
623
  awaitInvalidationBackplane: boolean;
624
+ rejectCachedReadsOnInvalidationLoss: boolean;
534
625
  lockFailClosed: boolean;
535
626
  oomProtection: boolean; oomHeapThreshold: number;
536
627
  oomCheckIntervalMs: number; oomEvictPercent: number;
@@ -600,6 +691,11 @@ export class CacheService {
600
691
  };
601
692
  /** Pre-computed once — opts.namespace never changes after construction. */
602
693
  private readonly _namespace: string;
694
+ private readonly _namespacePrefix: string;
695
+ private readonly _dataPrefix: string;
696
+ private readonly _tagSetPrefix: string;
697
+ private readonly _tagVersionPrefix: string;
698
+ private readonly _lockPrefix: string;
603
699
  private readonly prefixLen: number;
604
700
  /** Pre-computed once — disableRedis and redisHost never change after construction. */
605
701
  private readonly _redisDisabled: boolean;
@@ -614,6 +710,8 @@ export class CacheService {
614
710
  private readonly keyTags = new Map<string, { tags: string[]; expiresAt: number }>();
615
711
  /** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
616
712
  private readonly tagVersions = new Map<string, { version: number; lastSyncedAt: number; refreshEpoch?: number }>();
713
+ /** Share active generation reads only; retain at most the tag-cache ceiling. */
714
+ private readonly _tagVersionRefreshes = new Map<string, { epoch: number; fence: number; startedAt: number; promise: Promise<number> }>();
617
715
  private _tagRefreshEpoch = 0;
618
716
  /**
619
717
  * Dependency index: source glob pattern → Set of namespaced dependent keys.
@@ -622,6 +720,8 @@ export class CacheService {
622
720
  private readonly dependencyIndex = new Map<string, Set<string>>();
623
721
  /** Reverse index of namespaced dependent key → source glob patterns */
624
722
  private readonly keyDependencies = new Map<string, string[]>();
723
+ /** Active writers retain their dependency edges even before admission or after eviction. */
724
+ private readonly _pendingDependencies = new Set<{ key: string; patterns: string[]; epoch: string }>();
625
725
  private readonly _cgroupMemoryLimit: number;
626
726
  private redis: AnyRedisClient | null = null;
627
727
  private redisConnecting: Promise<AnyRedisClient> | null = null;
@@ -647,13 +747,30 @@ export class CacheService {
647
747
  private _lastStreamId = '$';
648
748
  private _restoredSnapshot = false;
649
749
  private _backplaneAvailable = false;
750
+ private _backplaneUnavailableReason = 'initializing';
751
+ private _backplaneUnavailableSince: number | null = Date.now();
752
+ private _backplaneStateSince = performance.now();
753
+ private _lastBackplaneHeartbeatAt = 0;
754
+ private _backplaneHeartbeatInterval: ReturnType<typeof setInterval> | null = null;
755
+ private _backplaneHeartbeat: { nonce: string; epoch: number; sentAt: number } | null = null;
756
+ private _heartbeatPublishInFlight = false;
757
+ private _backplaneSubscriptionReady = false;
758
+ private _backplaneTransportEpoch = 0;
759
+ private _retryBackplaneSubscription: (() => Promise<void>) | null = null;
760
+ private _preparedBackplaneClient: AnyRedisClient | null = null;
761
+ private _invalidationReadEpoch = 0;
650
762
  private _otelCleanup: (() => void) | null = null;
651
763
  private _streamRecovering = false;
652
764
  private readonly _backplaneDisposers: Array<() => void> = [];
653
765
  private _destroyed = false;
654
766
  private readonly _pendingDiskDeletes = new Set<string>();
767
+ /** Active invalidations fence cold Redis reads until their asynchronous deletion settles. */
768
+ private readonly _pendingRedisInvalidations = new Set<{ key: string; isPattern: boolean }>();
655
769
  private _globalEpoch = 0;
656
770
  private _pendingSpillCount = 0;
771
+ private readonly _pendingSpills = new Set<{ key: string; revision?: string; cancelled: boolean }>();
772
+ /** Strict reads trust only revisions spilled in this consumer epoch; bounded independently of disk size. */
773
+ private readonly _protectedSpillRevisions = new Map<string, string>();
657
774
  private _suppressSpills = false;
658
775
  private _diskCleanupScheduled = false;
659
776
  private readonly _keyMutationEpochs = new Map<string, number>();
@@ -696,6 +813,21 @@ export class CacheService {
696
813
  }
697
814
  }
698
815
 
816
+ private _beginRedisInvalidation(key: string, isPattern: boolean): () => void {
817
+ if (this._redisDisabled || this.opts.l2WriteMode !== 'read-write') return () => {};
818
+ const invalidation = { key, isPattern };
819
+ this._pendingRedisInvalidations.add(invalidation);
820
+ // Distinct tokens keep overlapping invalidations fenced until every operation settles.
821
+ return () => { this._pendingRedisInvalidations.delete(invalidation); };
822
+ }
823
+
824
+ private _isRedisReadInvalidated(key: string): boolean {
825
+ for (const invalidation of this._pendingRedisInvalidations) {
826
+ if (invalidation.isPattern ? this._matchesGlob(key, invalidation.key) : key === invalidation.key) return true;
827
+ }
828
+ return false;
829
+ }
830
+
699
831
  private _bumpKeyMutation(namespacedKey: string): number {
700
832
  const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
701
833
  this._keyMutationEpochs.set(namespacedKey, next);
@@ -725,6 +857,7 @@ export class CacheService {
725
857
  refreshTagVersions(): void {
726
858
  this._assertActive('refreshTagVersions');
727
859
  this._tagRefreshEpoch++;
860
+ this._tagVersionRefreshes.clear();
728
861
  }
729
862
 
730
863
  private _fenceInvalidation(): void {
@@ -733,6 +866,7 @@ export class CacheService {
733
866
  }
734
867
 
735
868
  private _invalidateDiskKey(key: string): void {
869
+ this._protectedSpillRevisions.delete(key);
736
870
  if (this._diskDisabled) return;
737
871
  this.disk.invalidate(key);
738
872
  this._pendingDiskDeletes.add(key);
@@ -755,9 +889,21 @@ export class CacheService {
755
889
  });
756
890
  }
757
891
 
758
- private _registerDependencies(key: string, patterns?: string[]): void {
892
+ private _reserveDependencies(key: string, patterns: string[]): () => void {
893
+ try { return this._dependencyBudget.reserve(key, patterns); }
894
+ catch (error) {
895
+ if (!(error instanceof CacheCapacityError)) throw error;
896
+ this._sweepExpiredMetadata();
897
+ return this._dependencyBudget.reserve(key, patterns);
898
+ }
899
+ }
900
+
901
+ private _registerDependencies(key: string, patterns?: string[], expiresAt = Infinity): void {
902
+ const release = this._reserveDependencies(key, patterns ?? []);
759
903
  this._removeKeyDependencies(key);
760
- if (!patterns?.length) return;
904
+ if (!patterns?.length) { release(); return; }
905
+ this._dependencyReleases.set(key, release);
906
+ this._dependencyExpirations.set(key, expiresAt);
761
907
  const namespaced = [...new Set(patterns.map(pattern => this.nk(pattern)))];
762
908
  for (const pattern of namespaced) {
763
909
  const dependents = this.dependencyIndex.get(pattern) ?? new Set<string>();
@@ -767,6 +913,19 @@ export class CacheService {
767
913
  this.keyDependencies.set(key, namespaced);
768
914
  }
769
915
 
916
+ private _trackPendingDependencies(key: string, patterns?: string[], bumpMutation = false): () => void {
917
+ if (!patterns?.length) {
918
+ if (bumpMutation) this._bumpKeyMutation(key);
919
+ return () => {};
920
+ }
921
+ const release = this._reserveDependencies(key, patterns);
922
+ if (bumpMutation) this._bumpKeyMutation(key);
923
+ const registration = { key, patterns: [...new Set(patterns.map(pattern => this.nk(pattern)))],
924
+ epoch: this._getKeyMutationEpoch(key) };
925
+ this._pendingDependencies.add(registration);
926
+ return () => { this._pendingDependencies.delete(registration); release(); };
927
+ }
928
+
770
929
  private _rememberTags(key: string, tags: string[], expiresAt: number): void {
771
930
  this._removeKeyTags(key);
772
931
  if (!tags.length) return;
@@ -777,7 +936,7 @@ export class CacheService {
777
936
  }
778
937
  const unique = [...new Set(tags)];
779
938
  for (const tag of unique) {
780
- const tagKey = this.nk(`_tag_:${tag}`);
939
+ const tagKey = this.tagIndexKey(tag);
781
940
  const members = this.tagIndex.get(tagKey) ?? new Set<string>();
782
941
  members.add(key);
783
942
  this.tagIndex.set(tagKey, members);
@@ -785,16 +944,23 @@ export class CacheService {
785
944
  this.keyTags.set(key, { tags: unique, expiresAt });
786
945
  }
787
946
 
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);
947
+ private _restoreEntryMetadata(key: string, entry: { tags?: string[]; dependsOn?: string[]; expiresAt: number }): boolean {
948
+ try {
949
+ if (entry.dependsOn?.length) this._registerDependencies(key, entry.dependsOn, entry.expiresAt);
950
+ if (entry.tags?.length) this._rememberTags(key, entry.tags, entry.expiresAt);
951
+ return true;
952
+ } catch (error) {
953
+ this.l1.delete(key);
954
+ if (!(error instanceof CacheCapacityError)) throw error;
955
+ return false;
956
+ }
791
957
  }
792
958
 
793
959
  private _removeKeyTags(namespacedKey: string): void {
794
960
  const entry = this.keyTags.get(namespacedKey);
795
961
  if (!entry) return;
796
962
  for (const tag of entry.tags) {
797
- const tagKey = this.nk(`_tag_:${tag}`);
963
+ const tagKey = this.tagIndexKey(tag);
798
964
  const members = this.tagIndex.get(tagKey);
799
965
  if (members) {
800
966
  members.delete(namespacedKey);
@@ -805,6 +971,9 @@ export class CacheService {
805
971
  }
806
972
 
807
973
  private _removeKeyDependencies(namespacedKey: string): void {
974
+ this._dependencyReleases.get(namespacedKey)?.();
975
+ this._dependencyReleases.delete(namespacedKey);
976
+ this._dependencyExpirations.delete(namespacedKey);
808
977
  const patterns = this.keyDependencies.get(namespacedKey);
809
978
  if (patterns) {
810
979
  for (const pat of patterns) {
@@ -823,6 +992,49 @@ export class CacheService {
823
992
  }
824
993
  }
825
994
 
995
+ private _clearDependencyMetadata(): void {
996
+ for (const release of this._dependencyReleases.values()) release();
997
+ this._dependencyReleases.clear();
998
+ this._dependencyExpirations.clear();
999
+ this.dependencyIndex.clear();
1000
+ this.keyDependencies.clear();
1001
+ }
1002
+
1003
+ private _notifyReadObserver(key: string, tier?: 'l1' | 'disk' | 'l2'): void {
1004
+ try {
1005
+ const result = tier ? this.opts.onHit?.(key, tier) : this.opts.onMiss?.(key);
1006
+ void Promise.resolve(result).catch(() => {});
1007
+ } catch { /* observers cannot change read results */ }
1008
+ }
1009
+
1010
+ private async _runOrigin<T>(fetch: (signal?: AbortSignal) => Promise<T>, weight = 1): Promise<T> {
1011
+ this._assertActive('origin fetch');
1012
+ const release = this._originWork.acquire(weight);
1013
+ const limiter = this._originCapacityLimiter;
1014
+ if (!limiter) {
1015
+ try { return await fetch(); }
1016
+ finally { release(); }
1017
+ }
1018
+
1019
+ let started = false;
1020
+ try {
1021
+ return await limiter.run(signal => {
1022
+ started = true;
1023
+ let physical: Promise<T>;
1024
+ try { physical = fetch(signal); }
1025
+ catch (error) { release(); throw error; }
1026
+ // Caller cancellation (including cache destruction) stops waiting, but
1027
+ // local and shared physical-work accounting release only on settlement.
1028
+ return Promise.resolve(physical).finally(release);
1029
+ }, { signal: this._lifecycle.signal, weight });
1030
+ } catch (error) {
1031
+ // A shared-budget rejection occurs before invoking the loader. If the
1032
+ // loader started, its physical promise owns the local reservation now.
1033
+ if (!started) release();
1034
+ throw error;
1035
+ }
1036
+ }
1037
+
826
1038
  private _handleL1Eviction(namespacedKey: string, reason: EvictionReason): void {
827
1039
  const spilledToDisk = !this._diskDisabled && !this._suppressSpills && (
828
1040
  reason === 'capacity' ||
@@ -850,6 +1062,9 @@ export class CacheService {
850
1062
 
851
1063
  private _sweepExpiredMetadata(): void {
852
1064
  const now = Date.now();
1065
+ for (const [key, expiresAt] of this._dependencyExpirations) {
1066
+ if (expiresAt <= now) this._removeKeyDependencies(key);
1067
+ }
853
1068
  for (const [k, c] of this._l1Counters) {
854
1069
  if (c.expiresAt <= now) this._l1Counters.delete(k);
855
1070
  }
@@ -904,6 +1119,7 @@ export class CacheService {
904
1119
  streamEntriesReceived: 0,
905
1120
  streamReplays: 0,
906
1121
  streamGaps: 0,
1122
+ invalidationReadRejections: 0,
907
1123
  oomEvictions: 0,
908
1124
  oomLastAt: null as number | null,
909
1125
  /** Times `increment()` hit a Redis error (fail-open by default, or fail-closed re-throw). */
@@ -930,6 +1146,41 @@ export class CacheService {
930
1146
  // ── Constructor (use CacheService.create() for the recommended singleton) ──
931
1147
 
932
1148
  constructor(options: CacheOptions = {}) {
1149
+ // Validate strict custom drivers before creating disk/worker/timer resources.
1150
+ if (options.rejectCachedReadsOnInvalidationLoss) {
1151
+ const deadline = options.backplaneMaxStalenessMs ?? 5_000;
1152
+ if (!Number.isFinite(deadline) || deadline <= 0) {
1153
+ throw new TypeError('rejectCachedReadsOnInvalidationLoss requires a finite positive backplaneMaxStalenessMs');
1154
+ }
1155
+ const explicitRedis = Boolean(options.redisClient || options.redisHost || options.redisClusterNodes?.length || options.redisSentinel);
1156
+ const redisDisabled = options.disableRedis ?? (!explicitRedis && process.env.NODE_ENV !== 'production');
1157
+ const redisConfigured = Boolean(options.redisClient || (options.redisHost ?? process.env.REDIS_HOST) || options.redisClusterNodes?.length || options.redisSentinel);
1158
+ if (redisDisabled || !redisConfigured || options.invalidationBackplane === false) {
1159
+ throw new TypeError('rejectCachedReadsOnInvalidationLoss requires active Redis and an invalidation backplane');
1160
+ }
1161
+ const sharded = Boolean(options.useShardedPubSub && options.redisClusterNodes?.length);
1162
+ const publisher = options.redisClient;
1163
+ const publish = options.backplaneMode === 'stream' ? 'xadd' : sharded ? 'spublish' : 'publish';
1164
+ if (publisher && typeof publisher[publish] !== 'function') {
1165
+ throw new TypeError(`rejectCachedReadsOnInvalidationLoss requires a Redis driver supporting ${publish}`);
1166
+ }
1167
+ if (publisher || options.redisSubClient) {
1168
+ const sub = options.redisSubClient ?? publisher?.duplicate?.();
1169
+ const methods = ['on', 'removeListener', 'disconnect', ...(options.backplaneMode === 'stream'
1170
+ ? ['xread', 'xrange', 'xrevrange'] : [sharded ? 'ssubscribe' : 'subscribe'])];
1171
+ if (!sub || sub === publisher || methods.some(method => typeof sub[method] !== 'function')) {
1172
+ if (sub && sub !== publisher && !options.redisSubClient) sub.disconnect?.();
1173
+ throw new TypeError(`rejectCachedReadsOnInvalidationLoss requires a distinct invalidation subscriber supporting ${methods.join(', ')}`);
1174
+ }
1175
+ this._preparedBackplaneClient = sub;
1176
+ }
1177
+ }
1178
+ positiveLimit(options.workerMaxPendingTasks, 256, 'workerMaxPendingTasks');
1179
+ positiveLimit(options.workerMaxPendingBytes, 64 * 1024 * 1024, 'workerMaxPendingBytes');
1180
+ this._originCapacityLimiter = options.originCapacityLimiter;
1181
+ this._originWork = new WorkLimit(positiveLimit(options.maxConcurrentFetches, 1024, 'maxConcurrentFetches'), 'origin work');
1182
+ this._backgroundWork = new WorkLimit(positiveLimit(options.maxBackgroundRefreshes, 64, 'maxBackgroundRefreshes'), 'background refreshes');
1183
+ this._dependencyBudget = new DependencyBudget(positiveLimit(options.maxDependencyEdges, 100_000, 'maxDependencyEdges'));
933
1184
  const logger = options.logger ?? consoleLogger;
934
1185
  this.logger = logger;
935
1186
  this._cgroupMemoryLimit = readCgroupMemoryLimit();
@@ -945,18 +1196,26 @@ export class CacheService {
945
1196
  options.encryptionMode,
946
1197
  options.previousEncryptionKey,
947
1198
  options.previousEncryptionMode,
948
- { strictKeyValidation: options.strictKeyValidation ?? false },
1199
+ { strictKeyValidation: options.strictKeyValidation ?? true,
1200
+ allowLegacyPlaintextRead: options.allowLegacyPlaintextRead ?? false },
949
1201
  );
950
1202
 
951
- // When a namespace is active, scope the forbidden prefixes so that
952
- // auth/session keys like `org_abc:auth:token` are still protected.
1203
+ const namespacePrefix = namespaceKeyPrefix(ns);
1204
+ const dataPrefix = namespaceDomainPrefix(ns, 'data');
1205
+
1206
+ // Snapshot policies operate on stored keys, so scope bare prefixes to the
1207
+ // same collision-free namespace keyspace used by all storage tiers.
953
1208
  const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
954
- const forbiddenPrefixes = ns
955
- ? rawForbidden.map(p => `${ns}:${p}`)
956
- : rawForbidden;
1209
+ const forbiddenPrefixes = rawForbidden.map(prefix => `${dataPrefix}${prefix}`);
957
1210
 
958
1211
  // Normalised options with defaults
959
1212
  this.opts = {
1213
+ originCapacityLimiter: options.originCapacityLimiter,
1214
+ maxConcurrentFetches: this._originWork.maximum,
1215
+ maxBackgroundRefreshes: this._backgroundWork.maximum,
1216
+ maxDependencyEdges: options.maxDependencyEdges ?? 100_000,
1217
+ workerMaxPendingTasks: options.workerMaxPendingTasks ?? 256,
1218
+ workerMaxPendingBytes: options.workerMaxPendingBytes ?? 64 * 1024 * 1024,
960
1219
  namespace: ns,
961
1220
  logger,
962
1221
  l1MaxBytes: options.l1MaxBytes ?? resolveAutonomousL1MaxBytes(),
@@ -987,10 +1246,11 @@ export class CacheService {
987
1246
  encryptionKey: encKeyRaw,
988
1247
  encryptionMode: options.encryptionMode,
989
1248
  snapshotPath: options.snapshotPath ?? path.join(
990
- os.tmpdir(), ns ? `tricache-snapshot-${ns}.msgpack` : 'tricache-snapshot.msgpack'),
1249
+ os.tmpdir(), `tricache-snapshot-v3-${encodeNamespaceSegment(ns)}.msgpack`),
991
1250
  snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
992
1251
  invalidationBackplane: options.invalidationBackplane ?? true,
993
1252
  awaitInvalidationBackplane: options.awaitInvalidationBackplane ?? false,
1253
+ rejectCachedReadsOnInvalidationLoss: options.rejectCachedReadsOnInvalidationLoss ?? false,
994
1254
  lockFailClosed: options.lockFailClosed ?? false,
995
1255
  oomProtection: options.oomProtection ?? true,
996
1256
  oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
@@ -1048,14 +1308,16 @@ export class CacheService {
1048
1308
  diskCircuitBreakerThreshold: options.diskCircuitBreakerThreshold,
1049
1309
  diskCircuitBreakerCooldownMs: options.diskCircuitBreakerCooldownMs,
1050
1310
  redisCommandTimeoutMs: options.redisCommandTimeoutMs,
1051
- clockSkewToleranceMs: options.clockSkewToleranceMs ?? 250,
1311
+ clockSkewToleranceMs: Number.isFinite(options.clockSkewToleranceMs)
1312
+ ? Math.max(0, options.clockSkewToleranceMs as number)
1313
+ : 250,
1052
1314
  l1AdmissionPolicy: options.l1AdmissionPolicy,
1053
1315
  diskLatencyWatchdog: options.diskLatencyWatchdog ?? true,
1054
1316
  diskLatencyBypassRatio: options.diskLatencyBypassRatio ?? 1.5,
1055
1317
  diskLatencyBypassMinMs: options.diskLatencyBypassMinMs ?? 10,
1056
1318
  diskLatencyBypassCooldownMs: options.diskLatencyBypassCooldownMs ?? 30_000,
1057
1319
  failReadinessOnDegraded: options.failReadinessOnDegraded ?? false,
1058
- autoPipeline: options.autoPipeline ?? false,
1320
+ autoPipeline: options.autoPipeline ?? true,
1059
1321
  maxPipelineBatchSize: options.maxPipelineBatchSize ?? 100,
1060
1322
  enableIpc: options.enableIpc ?? false,
1061
1323
  ipcSocketPath: options.ipcSocketPath,
@@ -1096,6 +1358,28 @@ export class CacheService {
1096
1358
  }
1097
1359
  this._diskDisabled = diskDisabled;
1098
1360
 
1361
+ this._singletonConfig = captureConfiguration({
1362
+ ...options, ...this.opts,
1363
+ disableDisk: diskDisabled, disableRedis: this.opts.disableRedis,
1364
+ forbiddenSnapshotPrefixes: rawForbidden,
1365
+ encryptionMode: options.encryptionMode ?? 'aes-256-gcm',
1366
+ strictKeyValidation: options.strictKeyValidation ?? true,
1367
+ allowLegacyPlaintextRead: options.allowLegacyPlaintextRead ?? false,
1368
+ l1AdmissionPolicy: options.l1AdmissionPolicy ?? 'adaptive',
1369
+ l2CircuitBreakerThreshold: cbThreshold, l2CircuitBreakerCooldownMs: cbCooldownMs,
1370
+ adaptiveTtlMin: this.opts.adaptiveTtlMinMs / 1000,
1371
+ adaptiveTtlMax: this.opts.adaptiveTtlMaxMs / 1000,
1372
+ adaptiveTtlSamples: options.adaptiveTtlSamples ?? 32,
1373
+ adaptiveTtlMaxKeys: options.adaptiveTtlMaxKeys ?? 5_000,
1374
+ redisProtocol: options.redisProtocol ?? 3,
1375
+ redisCommandTimeoutMs: options.redisCommandTimeoutMs ?? 2500,
1376
+ diskMaxConcurrentWrites: options.diskMaxConcurrentWrites ?? Math.min(4, Math.max(1, Math.floor((os.availableParallelism?.() ?? 4) / 4))),
1377
+ diskMaxPendingWrites: options.diskMaxPendingWrites ?? 512,
1378
+ diskWriteTimeoutMs: options.diskWriteTimeoutMs ?? 500,
1379
+ diskCircuitBreakerThreshold: options.diskCircuitBreakerThreshold ?? 5,
1380
+ diskCircuitBreakerCooldownMs: options.diskCircuitBreakerCooldownMs ?? 5000,
1381
+ });
1382
+
1099
1383
  // L1.5 disk tier (always constructed for metrics shape; ops are no-ops when disabled)
1100
1384
  this.disk = new DiskTier({
1101
1385
  dir: this.opts.diskCacheDir,
@@ -1115,7 +1399,12 @@ export class CacheService {
1115
1399
  });
1116
1400
 
1117
1401
  this._namespace = ns;
1118
- this.prefixLen = ns ? ns.length + 1 : 0;
1402
+ this._namespacePrefix = namespacePrefix;
1403
+ this._dataPrefix = dataPrefix;
1404
+ this._tagSetPrefix = namespaceDomainPrefix(ns, 'tag-set');
1405
+ this._tagVersionPrefix = namespaceDomainPrefix(ns, 'tag-version');
1406
+ this._lockPrefix = namespaceDomainPrefix(ns, 'lock');
1407
+ this.prefixLen = this._dataPrefix.length;
1119
1408
  // disableRedis takes unconditional precedence; otherwise, L2 is active when
1120
1409
  // at least one of host / cluster nodes / sentinel is configured.
1121
1410
  this._redisDisabled = this.opts.disableRedis
@@ -1137,13 +1426,16 @@ export class CacheService {
1137
1426
  maxBytes: this.opts.l1MaxBytes,
1138
1427
  maxEntries: this.opts.l1MaxEntries,
1139
1428
  categories: this.opts.categoryLimits,
1429
+ keyPrefixLength: this.prefixLen,
1140
1430
  evictionWatermark: this.opts.l1EvictionWatermark,
1141
1431
  admissionPolicy: this.opts.l1AdmissionPolicy,
1142
1432
  codec: this.codec,
1143
1433
  diskSpill: (key: string, entry: SmartCacheEntry) => {
1144
- if (this._diskDisabled || this._suppressSpills) return;
1434
+ if (this._diskDisabled || this._suppressSpills || !this._cachedReadAllowed()) return;
1145
1435
  if (this._pendingSpillCount >= (this.opts.diskMaxPendingWrites ?? 512)) return;
1146
1436
  const epoch = this._getKeyMutationEpoch(key);
1437
+ const spill = { key, revision: entry.revision, cancelled: false };
1438
+ this._pendingSpills.add(spill);
1147
1439
  this._pendingSpillCount++;
1148
1440
  // Defer disk.save() entirely to the next event-loop tick so the synchronous
1149
1441
  // preamble inside save() (SHA-256 keyToPath + msgpackr pack) does not block
@@ -1151,17 +1443,29 @@ export class CacheService {
1151
1443
  // backplane handler already does for remote invalidations.
1152
1444
  setImmediate(() => {
1153
1445
  this._pendingSpillCount--;
1154
- if (!this._destroyed && this._getKeyMutationEpoch(key) === epoch) void this.disk.save(key, entry as unknown as DiskCacheEntry);
1446
+ this._pendingSpills.delete(spill);
1447
+ if (!spill.cancelled && !this._destroyed && this._cachedReadAllowed() && this._getKeyMutationEpoch(key) === epoch) {
1448
+ if (this._strictInvalidationReadProtectionEnabled()) {
1449
+ if (!entry.revision) return;
1450
+ this._protectedSpillRevisions.delete(key);
1451
+ if (this._protectedSpillRevisions.size >= 50_000) {
1452
+ this._protectedSpillRevisions.delete(this._protectedSpillRevisions.keys().next().value!);
1453
+ }
1454
+ this._protectedSpillRevisions.set(key, entry.revision);
1455
+ }
1456
+ void this.disk.save(key, entry as unknown as DiskCacheEntry);
1457
+ }
1155
1458
  });
1156
1459
  },
1157
1460
  onEviction: (key: string, reason: EvictionReason) => {
1158
1461
  this._handleL1Eviction(key, reason);
1159
- options.onEviction?.(key, reason);
1462
+ try { void Promise.resolve(options.onEviction?.(key, reason)).catch(() => {}); } catch { /* observers cannot break eviction */ }
1160
1463
  },
1161
1464
  logger,
1162
1465
  });
1163
1466
 
1164
1467
  // Load snapshot once per process
1468
+ if (this._strictInvalidationReadProtectionEnabled() && !this._diskDisabled) this.disk.clear();
1165
1469
  if (!this.snapshotLoaded) {
1166
1470
  this.snapshotLoaded = true;
1167
1471
  if (!this._diskDisabled) this.loadSnapshot(); // Fix 3: skip in ephemeral environments
@@ -1183,9 +1487,12 @@ export class CacheService {
1183
1487
  mode: encRef.mode as never,
1184
1488
  prevKeyBase64: encRef.prevKeyBase64,
1185
1489
  prevMode: encRef.prevMode as never,
1490
+ allowLegacyPlaintextRead: encRef.allowLegacyPlaintextRead,
1186
1491
  compression: this.opts.compression,
1187
1492
  compressionThresholdBytes: this.opts.compressionThresholdBytes,
1188
1493
  size: this.opts.workerPoolSize || undefined,
1494
+ maxPendingTasks: options.workerMaxPendingTasks,
1495
+ maxPendingBytes: this.opts.workerMaxPendingBytes,
1189
1496
  });
1190
1497
  if (this._workerPool.isAvailable) {
1191
1498
  logger.info('tricache: worker-thread encryption pool active', {
@@ -1231,7 +1538,7 @@ export class CacheService {
1231
1538
  // Metrics callback
1232
1539
  if (this.opts.onMetrics && this.opts.metricsIntervalMs > 0) {
1233
1540
  this.metricsInterval = setInterval(() => {
1234
- try { this.opts.onMetrics!(this.metrics()); } catch { /* never crash process */ }
1541
+ try { void Promise.resolve(this.opts.onMetrics!(this.metrics())).catch(() => {}); } catch { /* never crash process */ }
1235
1542
  }, this.opts.metricsIntervalMs);
1236
1543
  if (this.metricsInterval.unref) this.metricsInterval.unref();
1237
1544
  }
@@ -1246,10 +1553,14 @@ export class CacheService {
1246
1553
 
1247
1554
  // Backplane: assign instance ID + channel + streamKey, then subscribe
1248
1555
  this.instanceId = crypto.randomBytes(8).toString('hex');
1249
- this.backplaneChannel = `tricache:inv${ns ? ':' + ns : ''}`;
1250
- this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || 'default'}}`;
1556
+ this.backplaneChannel = namespaceBackplaneChannel(ns);
1557
+ this.backplaneStreamKey = namespaceStreamKey(ns, options.backplaneStreamKey);
1251
1558
  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 }));
1559
+ .catch(error => {
1560
+ if (this._destroyed) return;
1561
+ this._setBackplaneUnavailable('initialization_failed');
1562
+ this.logger.warn('Backplane initialization failed; continuing with local degradation', { error: (error as Error).message });
1563
+ });
1253
1564
 
1254
1565
  // Auto-warm from remote snapshot or L2 if configured; ready() waits for completion.
1255
1566
  const startupPromises: Promise<void>[] = [];
@@ -1259,14 +1570,18 @@ export class CacheService {
1259
1570
  if (this.opts.remoteSnapshot) {
1260
1571
  startupPromises.push(this.loadRemoteSnapshot().then(() => undefined));
1261
1572
  }
1262
- if (this.opts.warmKeys) {
1573
+ if (this.opts.warmKeys && !this._strictInvalidationReadProtectionEnabled()) {
1263
1574
  startupPromises.push(this.warmFromL2(this.opts.warmKeys).then(() => undefined));
1264
1575
  }
1265
1576
  // Hydrate before replaying a snapshot's stream cursor; otherwise replay could
1266
1577
  // run first and a late snapshot download could restore already-invalidated data.
1267
1578
  const backplaneReady = this.opts.remoteSnapshot || this.opts.warmKeys
1268
1579
  ? Promise.all(startupPromises).then(startBackplane) : startBackplane();
1269
- this._readyPromise = Promise.all([...startupPromises, backplaneReady]).then(() => undefined);
1580
+ this._readyPromise = Promise.all([...startupPromises, backplaneReady]).then(async () => {
1581
+ if (this.opts.warmKeys && this._strictInvalidationReadProtectionEnabled() && this._cachedReadAllowed()) {
1582
+ await this.warmFromL2(this.opts.warmKeys);
1583
+ }
1584
+ });
1270
1585
 
1271
1586
  // Native OpenTelemetry metrics integration
1272
1587
  if (this.opts.meter) {
@@ -1346,6 +1661,8 @@ export class CacheService {
1346
1661
  tagStrategy: 'generational',
1347
1662
  backplaneMode: 'stream',
1348
1663
  strictSingleton: true,
1664
+ strictKeyValidation: true,
1665
+ lockFailClosed: true,
1349
1666
  failClosed: true,
1350
1667
  oomProtection: true,
1351
1668
  oomHeapThreshold: 0.80,
@@ -1383,7 +1700,7 @@ export class CacheService {
1383
1700
 
1384
1701
  // Singleton already exists for this namespace — detect & surface divergence.
1385
1702
  const existing = g[key] as CacheService;
1386
- const diff = CacheService.optionsDiff(options ?? {}, existing.opts);
1703
+ const diff = CacheService.optionsDiff(options ?? {}, existing._singletonConfig);
1387
1704
  if (diff.length > 0) {
1388
1705
  existing.bumpSingletonDivergence();
1389
1706
  const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || '(default)'}' — ignoring divergent options: ${diff.join(', ')}`;
@@ -1400,26 +1717,16 @@ export class CacheService {
1400
1717
  * meaningful configuration divergence worth flagging (security/correctness
1401
1718
  * relevant — not cosmetic, e.g. log level).
1402
1719
  */
1403
- private static readonly DIVERGENT_KEYS: Array<keyof CacheOptions> = [
1404
- 'redisHost', 'redisPort', 'redisTls', 'disableRedis',
1405
- 'redisClusterNodes', 'redisSentinel', 'encryptionKey', 'encryptionMode',
1406
- 'l1MaxBytes', 'l1MaxEntries', 'namespace', 'frozen', 'adaptiveTtl',
1407
- 'l2WriteMode', 'instanceName', 'invalidationBackplane', 'awaitInvalidationBackplane', 'lockFailClosed',
1408
- 'tagStrategy', 'cloneStrategy', 'compression', 'backplaneMode', 'redisProtocol', 'failClosed',
1409
- ];
1410
-
1411
1720
  /** Returns the names of options that differ between `a` and the live `b`. */
1412
1721
  private static optionsDiff(a: CacheOptions, b: Record<string, unknown>): string[] {
1413
1722
  const out: string[] = [];
1414
- for (const k of CacheService.DIVERGENT_KEYS) {
1415
- const av = a[k];
1723
+ for (const k of Object.keys(a) as Array<keyof CacheOptions>) {
1724
+ let av = a[k];
1416
1725
  const bv = (b as Record<string, unknown>)[k as string];
1417
1726
  // Treat undefined (not passed) as "no opinion" — only flag explicit conflicts.
1418
1727
  if (av === undefined) continue;
1419
- const same =
1420
- JSON.stringify(av) === JSON.stringify(bv) ||
1421
- (k === 'encryptionKey' && av === bv);
1422
- if (!same) out.push(String(k));
1728
+ if (k === 'namespace' && typeof av === 'string') av = av.trim();
1729
+ if (!sameConfiguration(av, bv, k)) out.push(String(k));
1423
1730
  }
1424
1731
  return out;
1425
1732
  }
@@ -1437,6 +1744,12 @@ export class CacheService {
1437
1744
  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) },
1438
1745
  l1MaxBytes: o.l1MaxBytes,
1439
1746
  l1MaxEntries: o.l1MaxEntries,
1747
+ maxConcurrentFetches: o.maxConcurrentFetches,
1748
+ maxBackgroundRefreshes: o.maxBackgroundRefreshes,
1749
+ originCapacityLimiter: o.originCapacityLimiter,
1750
+ maxDependencyEdges: o.maxDependencyEdges,
1751
+ workerMaxPendingTasks: o.workerMaxPendingTasks,
1752
+ workerMaxPendingBytes: o.workerMaxPendingBytes,
1440
1753
  redisHost: o.redisHost,
1441
1754
  redisPort: o.redisPort,
1442
1755
  redisTls: o.redisTls,
@@ -1455,6 +1768,9 @@ export class CacheService {
1455
1768
  awaitInvalidationBackplane: o.awaitInvalidationBackplane,
1456
1769
  lockFailClosed: o.lockFailClosed,
1457
1770
  strictSingleton: o.strictSingleton,
1771
+ // Nonsecret timing configuration. Framework adapters read the effective
1772
+ // value here instead of re-deriving defaults from their own inputs.
1773
+ clockSkewToleranceMs: o.clockSkewToleranceMs,
1458
1774
  remoteSnapshot: redactDiagnostics(o.remoteSnapshot),
1459
1775
  crossRegion: redactDiagnostics(o.crossRegion),
1460
1776
  } as CacheOptions;
@@ -1485,25 +1801,59 @@ export class CacheService {
1485
1801
  /** Derive the globalThis key for a given set of options. */
1486
1802
  private static globalKey(options?: { namespace?: string }): string {
1487
1803
  const ns = options?.namespace?.trim() ?? '';
1488
- return ns ? `__tricache_${ns}__` : GLOBAL_KEY;
1804
+ return namespaceSingletonKey(ns);
1489
1805
  }
1490
1806
 
1491
1807
  // ── Redis connection ──────────────────────────────────────────────────────
1492
1808
 
1493
1809
  /**
1494
- * Prepend the configured namespace to a raw cache key.
1495
- * Returns the key unchanged when namespace is empty.
1810
+ * Encode the namespace, data domain, and raw key as an unambiguous v3 key.
1496
1811
  *
1497
- * This is the only place the namespace prefix is applied — callers always
1498
- * receive and provide un-prefixed keys in the public API.
1812
+ * Callers always receive and provide logical keys in the public API.
1499
1813
  */
1500
1814
  private nk(key: string): string {
1501
- return this._namespace ? `${this._namespace}:${key}` : key;
1815
+ return `${this._dataPrefix}${key}`;
1816
+ }
1817
+
1818
+ private tagIndexKey(tag: string): string {
1819
+ return `${this._tagSetPrefix}${tag}`;
1820
+ }
1821
+
1822
+ private tagIndexPrefix(): string {
1823
+ return this._tagSetPrefix;
1824
+ }
1825
+
1826
+ private tagVersionKey(tag: string): string {
1827
+ return `${this._tagVersionPrefix}${tag}`;
1828
+ }
1829
+
1830
+ private tagVersionPrefix(): string {
1831
+ return this._tagVersionPrefix;
1502
1832
  }
1503
1833
 
1504
- /** Strip the instance namespace prefix from a namespaced key (inverse of `nk`). */
1505
- private unnk(key: string): string {
1506
- return this._namespace ? key.slice(this._namespace.length + 1) : key;
1834
+ private lockKey(key: string): string {
1835
+ return `${this._lockPrefix}${key}`;
1836
+ }
1837
+
1838
+ private undk(key: string): string {
1839
+ return key.startsWith(this._dataPrefix) ? key.slice(this._dataPrefix.length) : key;
1840
+ }
1841
+
1842
+ /**
1843
+ * Validate a snapshot write timestamp before age/skew arithmetic.
1844
+ *
1845
+ * NaN and non-numeric values previously made every comparison false, so a
1846
+ * malformed timestamp skipped both the future-skew and maximum-age gates.
1847
+ * Missing or invalid values are rejected outright rather than treated as 0.
1848
+ */
1849
+ private _snapshotWrittenAt(value: unknown, label: string): number | null {
1850
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
1851
+ this.logger.warn(`${label} rejected: writtenAt is not a finite non-negative number`, {
1852
+ writtenAtType: typeof value,
1853
+ });
1854
+ return null;
1855
+ }
1856
+ return value;
1507
1857
  }
1508
1858
 
1509
1859
  /** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
@@ -1536,6 +1886,7 @@ export class CacheService {
1536
1886
  }
1537
1887
 
1538
1888
  private createDedicatedRedisClient(): AnyRedisClient {
1889
+ if (this._preparedBackplaneClient) return this._preparedBackplaneClient;
1539
1890
  if (this.opts.redisSubClient) {
1540
1891
  return this.opts.redisSubClient;
1541
1892
  }
@@ -1586,12 +1937,197 @@ export class CacheService {
1586
1937
  }
1587
1938
 
1588
1939
  private _listenBackplane(client: AnyRedisClient, event: string, listener: (...args: any[]) => void): void {
1940
+ if (this._destroyed) return;
1589
1941
  client.on?.(event, listener);
1590
1942
  this._backplaneDisposers.push(() => client.removeListener?.(event, listener));
1591
1943
  }
1592
1944
 
1945
+ private _strictInvalidationReadProtectionEnabled(): boolean {
1946
+ return this.opts.rejectCachedReadsOnInvalidationLoss && this.opts.invalidationBackplane && !this._redisDisabled;
1947
+ }
1948
+
1949
+ private _setBackplaneUnavailable(reason: string): void {
1950
+ if (this._destroyed && reason !== 'destroyed') return;
1951
+ const wasAvailable = this._backplaneAvailable;
1952
+ this._backplaneAvailable = false;
1953
+ this._backplaneUnavailableReason = reason;
1954
+ this._backplaneHeartbeat = null;
1955
+ if (this._backplaneUnavailableSince === null) {
1956
+ this._backplaneUnavailableSince = Date.now();
1957
+ this._backplaneStateSince = performance.now();
1958
+ }
1959
+ if (this._strictInvalidationReadProtectionEnabled() && wasAvailable) {
1960
+ this._invalidationReadEpoch++;
1961
+ this._flushLocalCacheAfterInvalidationRecovery();
1962
+ }
1963
+ }
1964
+
1965
+ private _flushLocalCacheAfterInvalidationRecovery(): void {
1966
+ this._fenceInvalidation();
1967
+ for (const spill of this._pendingSpills) spill.cancelled = true;
1968
+ this._protectedSpillRevisions.clear();
1969
+ this._suppressSpills = true;
1970
+ try { this.l1.clear(); }
1971
+ finally { this._suppressSpills = false; }
1972
+ if (!this._diskDisabled) {
1973
+ try { this.disk.clear(); }
1974
+ catch (error) { this.logger.debug('Backplane recovery: disk cleanup failed', { error: (error as Error).message }); }
1975
+ }
1976
+ this.tagIndex.clear();
1977
+ this.keyTags.clear();
1978
+ this.tagVersions.clear();
1979
+ this._tagRefreshEpoch++;
1980
+ this._tagVersionRefreshes.clear();
1981
+ this._l1Counters.clear();
1982
+ this._clearDependencyMetadata();
1983
+ this._pendingDiskDeletes.clear();
1984
+ this._patternTombstones.length = 0;
1985
+ this._diskInvalidatedBefore = Date.now();
1986
+ }
1987
+
1988
+ private _setBackplaneAvailable(): void {
1989
+ if (this._destroyed) return;
1990
+ if (this._strictInvalidationReadProtectionEnabled() && !this._backplaneAvailable) {
1991
+ this._flushLocalCacheAfterInvalidationRecovery();
1992
+ }
1993
+ this._backplaneAvailable = true;
1994
+ this._backplaneUnavailableReason = '';
1995
+ this._backplaneUnavailableSince = null;
1996
+ this._backplaneStateSince = performance.now();
1997
+ }
1998
+
1999
+ private _rejectCachedRead(): never {
2000
+ this.counters.invalidationReadRejections++;
2001
+ throw new CacheInvalidationUnavailableError(
2002
+ this._backplaneUnavailableReason || 'read_crossed_invalidation_loss',
2003
+ this._backplaneUnavailableSince,
2004
+ );
2005
+ }
2006
+
2007
+ private _ensureCachedReadAllowed(epoch?: number): void {
2008
+ if (!this._strictInvalidationReadProtectionEnabled()) return;
2009
+ if (!this._cachedReadAllowed(epoch)) this._rejectCachedRead();
2010
+ }
2011
+
2012
+ /** Shared admission/commit/response fence. Health checks must also evaluate elapsed deadlines. */
2013
+ private _cachedReadAllowed(epoch?: number): boolean {
2014
+ if (!this._strictInvalidationReadProtectionEnabled()) return true;
2015
+ this._checkBackplaneDeadline();
2016
+ return !this._destroyed && this._backplaneAvailable && (epoch === undefined || epoch === this._invalidationReadEpoch);
2017
+ }
2018
+
2019
+ private _checkBackplaneDeadline(): void {
2020
+ if (this._strictInvalidationReadProtectionEnabled() && this._backplaneAvailable &&
2021
+ performance.now() - this._lastBackplaneHeartbeatAt >= this.opts.backplaneMaxStalenessMs) {
2022
+ this._setBackplaneUnavailable('heartbeat_timeout');
2023
+ }
2024
+ }
2025
+
2026
+ private _startBackplaneHeartbeat(): void {
2027
+ if (this._destroyed || !this._strictInvalidationReadProtectionEnabled() || this._backplaneHeartbeatInterval) return;
2028
+ const deadline = this.opts.backplaneMaxStalenessMs;
2029
+ const interval = Math.max(1, Math.min(1_000, Math.floor(deadline / 3)));
2030
+ this._backplaneHeartbeatInterval = setInterval(() => {
2031
+ if (this._destroyed) return;
2032
+ this._checkBackplaneDeadline();
2033
+ if (!this._backplaneSubscriptionReady) void this._retryBackplaneSubscription?.();
2034
+ void this._publishBackplaneHeartbeat();
2035
+ }, interval);
2036
+ if (this._backplaneHeartbeatInterval.unref) this._backplaneHeartbeatInterval.unref();
2037
+ }
2038
+
2039
+ private async _publishBackplaneHeartbeat(): Promise<void> {
2040
+ if (this._destroyed || !this._strictInvalidationReadProtectionEnabled() || !this._backplaneSubscriptionReady || this._heartbeatPublishInFlight) return;
2041
+ const now = performance.now();
2042
+ if (this._backplaneHeartbeat && now - this._backplaneHeartbeat.sentAt < this.opts.backplaneMaxStalenessMs) return;
2043
+ const probe = { nonce: crypto.randomUUID(), epoch: this._invalidationReadEpoch, sentAt: now };
2044
+ this._backplaneHeartbeat = probe;
2045
+ this._heartbeatPublishInFlight = true;
2046
+ let probeToken: number | null = null;
2047
+ try {
2048
+ const client = await this.getRedis(token => { probeToken = token; });
2049
+ if (this._destroyed || this._backplaneHeartbeat !== probe) {
2050
+ this.cb.releaseProbe(probeToken);
2051
+ return;
2052
+ }
2053
+ if (this.opts.backplaneMode === 'stream') {
2054
+ await (client as any).xadd(this.backplaneStreamKey, 'MAXLEN', '~', String(this.opts.backplaneStreamMaxLen), '*',
2055
+ 'op', 'heartbeat', 'key', '', 'src', this.instanceId, 'nonce', probe.nonce);
2056
+ } else {
2057
+ const payload = JSON.stringify({ op: 'heartbeat', key: '', src: this.instanceId, nonce: probe.nonce });
2058
+ const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
2059
+ if (isClusterSharded && typeof (client as any).spublish === 'function') await (client as any).spublish(this.backplaneChannel, payload);
2060
+ else await client.publish(this.backplaneChannel, payload);
2061
+ }
2062
+ this.cb.onSuccess();
2063
+ } catch (error) {
2064
+ this.cb.onFailure(error);
2065
+ if (!this._destroyed && this._backplaneHeartbeat === probe) this._setBackplaneUnavailable('heartbeat_publish_failed');
2066
+ this.logger.debug('Backplane heartbeat failed', { error: (error as Error).message });
2067
+ } finally {
2068
+ this._heartbeatPublishInFlight = false;
2069
+ }
2070
+ }
2071
+
2072
+ private _acceptBackplaneHeartbeat(src: unknown, nonce: unknown): void {
2073
+ if (!this._strictInvalidationReadProtectionEnabled() || this._destroyed || !this._backplaneSubscriptionReady) return;
2074
+ // Evaluate expiry before accepting a delayed callback after an event-loop pause.
2075
+ this._checkBackplaneDeadline();
2076
+ const probe = this._backplaneHeartbeat;
2077
+ if (src !== this.instanceId || !probe || nonce !== probe.nonce || probe.epoch !== this._invalidationReadEpoch ||
2078
+ performance.now() - probe.sentAt >= this.opts.backplaneMaxStalenessMs) return;
2079
+ this._backplaneHeartbeat = null;
2080
+ this._lastBackplaneHeartbeatAt = probe.sentAt;
2081
+ this._setBackplaneAvailable();
2082
+ }
2083
+
2084
+ private _protectedConsumerDisconnected(reason: string): void {
2085
+ this._backplaneTransportEpoch++;
2086
+ this._backplaneSubscriptionReady = false;
2087
+ this._setBackplaneUnavailable(reason);
2088
+ }
2089
+
2090
+ private async _initProtectedPubSub(sub: AnyRedisClient): Promise<void> {
2091
+ const sharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
2092
+ let subscribing: Promise<void> | null = null;
2093
+ const subscribe = (): Promise<void> => {
2094
+ if (this._destroyed || this._backplaneSubscriptionReady) return Promise.resolve();
2095
+ if (subscribing) return subscribing;
2096
+ const epoch = this._backplaneTransportEpoch;
2097
+ const work = Promise.resolve().then(async () => {
2098
+ if (typeof sub.connect === 'function' && (sub.isOpen === false || sub.status === 'wait')) await sub.connect();
2099
+ if (this._destroyed || epoch !== this._backplaneTransportEpoch) return;
2100
+ if (sharded) await (sub as any).ssubscribe(this.backplaneChannel);
2101
+ else await sub.subscribe(this.backplaneChannel);
2102
+ if (this._destroyed || epoch !== this._backplaneTransportEpoch) return;
2103
+ this._backplaneSubscriptionReady = true;
2104
+ await this._publishBackplaneHeartbeat();
2105
+ }).catch(error => {
2106
+ if (!this._destroyed && epoch === this._backplaneTransportEpoch) this._setBackplaneUnavailable('subscription_failed');
2107
+ this.logger.debug('Backplane subscription failed', { error: (error as Error).message });
2108
+ }).finally(() => { if (subscribing === work) subscribing = null; });
2109
+ subscribing = work;
2110
+ return work;
2111
+ };
2112
+ for (const event of ['close', 'end', 'reconnecting']) {
2113
+ this._listenBackplane(sub, event, () => this._protectedConsumerDisconnected('subscriber_disconnected'));
2114
+ }
2115
+ this._listenBackplane(sub, 'error', () => this._protectedConsumerDisconnected('subscriber_error'));
2116
+ this._listenBackplane(sub, 'ready', () => {
2117
+ // A new ready event can precede automatic resubscription in Redis drivers.
2118
+ if (this._backplaneSubscriptionReady) this._protectedConsumerDisconnected('subscriber_reconnecting');
2119
+ void subscribe();
2120
+ });
2121
+ this._listenBackplane(sub, sharded ? 'smessage' : 'message', (channel: string, message: string) => {
2122
+ if (channel === this.backplaneChannel && this._backplaneSubscriptionReady && !this._destroyed) this._handleBackplaneMessage(message);
2123
+ });
2124
+ this._retryBackplaneSubscription = subscribe;
2125
+ this._startBackplaneHeartbeat();
2126
+ await subscribe();
2127
+ }
2128
+
1593
2129
  private async initBackplane(): Promise<void> {
1594
- if (!this.opts.invalidationBackplane || this._redisDisabled) return;
2130
+ if (this._destroyed || !this.opts.invalidationBackplane || this._redisDisabled) return;
1595
2131
 
1596
2132
  if (this.opts.backplaneMode === 'stream') {
1597
2133
  if (this.streamClient) return;
@@ -1603,6 +2139,10 @@ export class CacheService {
1603
2139
 
1604
2140
  const sub = this.createDedicatedRedisClient();
1605
2141
  this.subClient = sub;
2142
+ if (this._strictInvalidationReadProtectionEnabled()) {
2143
+ await this._initProtectedPubSub(sub);
2144
+ return;
2145
+ }
1606
2146
 
1607
2147
  this._listenBackplane(sub, 'error', (e: Error) => {
1608
2148
  this._checkAndLogResp3Hint(e);
@@ -1611,7 +2151,7 @@ export class CacheService {
1611
2151
 
1612
2152
  // ── Staleness fence — track disconnect time ──────────────────────
1613
2153
  this._listenBackplane(sub, 'close', () => {
1614
- this._backplaneAvailable = false;
2154
+ this._setBackplaneUnavailable('subscriber_disconnected');
1615
2155
  if (this._subDisconnectedAt === null) {
1616
2156
  this._subDisconnectedAt = Date.now();
1617
2157
  this.logger.debug('Backplane: subscriber disconnected', { at: this._subDisconnectedAt });
@@ -1630,7 +2170,7 @@ export class CacheService {
1630
2170
  }
1631
2171
  this._subDisconnectedAt = null;
1632
2172
  }
1633
- if (!this._destroyed) this._backplaneAvailable = true;
2173
+ this._setBackplaneAvailable();
1634
2174
  });
1635
2175
 
1636
2176
  const isClusterSharded = Boolean(this.opts.useShardedPubSub && this.opts.redisClusterNodes?.length);
@@ -1657,42 +2197,56 @@ export class CacheService {
1657
2197
  }));
1658
2198
  }
1659
2199
 
1660
- if (!this._destroyed) this._backplaneAvailable = true;
2200
+ this._setBackplaneAvailable();
1661
2201
  }
1662
2202
 
1663
2203
  private _resetAfterStreamGap(): void {
1664
2204
  this.counters.streamGaps++;
2205
+ this._setBackplaneUnavailable('stream_gap');
1665
2206
  this._fenceInvalidation();
1666
2207
  this.l1.clear();
1667
2208
  this.tagIndex.clear();
1668
2209
  this.keyTags.clear();
1669
2210
  this.tagVersions.clear();
1670
- this.dependencyIndex.clear();
1671
- this.keyDependencies.clear();
2211
+ this._clearDependencyMetadata();
1672
2212
  this._diskInvalidatedBefore = Math.max(this._diskInvalidatedBefore, Date.now());
1673
2213
  this._addPatternTombstone(this.nk('*'));
1674
2214
  this._lastStreamId = '0-0';
1675
2215
  }
1676
2216
 
1677
2217
  private async _startStreamConsumer(): Promise<void> {
2218
+ if (this._destroyed) return;
2219
+ const strict = this._strictInvalidationReadProtectionEnabled();
2220
+ let initialized = false;
1678
2221
  this._streamRecovering ||= this._lastStreamId !== '$' && this._lastStreamId !== '0-0';
1679
2222
  const sub = this.streamClient ?? this.createDedicatedRedisClient();
1680
2223
  this.streamClient = sub;
1681
2224
  if (typeof sub.xread !== 'function') throw new Error('backplaneMode: stream requires a driver supporting XREAD');
1682
2225
 
1683
2226
  if (typeof (sub as any).on === 'function') {
1684
- this._listenBackplane(sub, 'error', (e: Error) =>
1685
- this.logger.debug('Backplane stream consumer error', { error: e.message }));
2227
+ this._listenBackplane(sub, 'error', (e: Error) => {
2228
+ if (strict) { initialized = false; this._protectedConsumerDisconnected('subscriber_error'); }
2229
+ this.logger.debug('Backplane stream consumer error', { error: e.message });
2230
+ });
1686
2231
 
1687
2232
  this._listenBackplane(sub, 'close', () => {
2233
+ if (strict) { initialized = false; this._protectedConsumerDisconnected('subscriber_disconnected'); }
1688
2234
  this._streamRecovering = true;
1689
- this._backplaneAvailable = false;
2235
+ if (!strict) this._setBackplaneUnavailable('subscriber_disconnected');
1690
2236
  if (this._subDisconnectedAt === null) {
1691
2237
  this._subDisconnectedAt = Date.now();
1692
2238
  this.logger.debug('Backplane stream: consumer disconnected', { at: this._subDisconnectedAt });
1693
2239
  }
1694
2240
  });
1695
2241
 
2242
+ if (strict) for (const event of ['end', 'reconnecting']) {
2243
+ this._listenBackplane(sub, event, () => {
2244
+ initialized = false;
2245
+ this._streamRecovering = true;
2246
+ this._protectedConsumerDisconnected('subscriber_disconnected');
2247
+ });
2248
+ }
2249
+
1696
2250
  this._listenBackplane(sub, 'ready', () => {
1697
2251
  if (this._subDisconnectedAt !== null) {
1698
2252
  this.logger.debug('Backplane stream: consumer reconnected, resuming stream read', { lastId: this._lastStreamId });
@@ -1705,13 +2259,22 @@ export class CacheService {
1705
2259
  if (this._lastStreamId === '$' || this._lastStreamId === '0-0' || typeof sub.xrange !== 'function') return;
1706
2260
  const first = await sub.xrange(this.backplaneStreamKey, '-', '+', 'COUNT', 1);
1707
2261
  const firstId = first?.[0]?.[0] as string | undefined;
1708
- if (!firstId) return;
2262
+ if (!firstId) { if (strict) this._resetAfterStreamGap(); return; }
1709
2263
  const [firstMs, firstSequence] = firstId.split('-').map(BigInt);
1710
2264
  const [lastMs, lastSequence] = this._lastStreamId.split('-').map(BigInt);
1711
- if (firstMs > lastMs || (firstMs === lastMs && firstSequence > lastSequence)) this._resetAfterStreamGap();
2265
+ if (firstMs > lastMs || (firstMs === lastMs && firstSequence > lastSequence)) {
2266
+ this._resetAfterStreamGap();
2267
+ return;
2268
+ }
2269
+ if (strict) {
2270
+ const latest = await sub.xrevrange(this.backplaneStreamKey, '+', '-', 'COUNT', 1);
2271
+ const [latestMs, latestSequence] = (latest?.[0]?.[0] ?? '0-0').split('-').map(BigInt);
2272
+ if (latestMs < lastMs || (latestMs === lastMs && latestSequence < lastSequence)) this._resetAfterStreamGap();
2273
+ }
1712
2274
  };
1713
2275
  const apply = (response: Array<[string, Array<[string, string[]]>]> | null) => {
1714
2276
  if (this._destroyed || !response) return;
2277
+ const heartbeats: Array<[unknown, unknown]> = [];
1715
2278
  if (this._streamRecovering && response.some(([, entries]) => entries.length > 0)) {
1716
2279
  this.counters.streamReplays++;
1717
2280
  this._streamRecovering = false;
@@ -1720,12 +2283,14 @@ export class CacheService {
1720
2283
  for (const [id, fields] of entries) {
1721
2284
  this._lastStreamId = id;
1722
2285
  this.counters.streamEntriesReceived++;
1723
- this._processStreamEntry(fields);
2286
+ this._processStreamEntry(fields, (src, nonce) => heartbeats.push([src, nonce]));
1724
2287
  }
1725
2288
  }
2289
+ // Replay must finish applying the entire response before any proof reopens reads.
2290
+ for (const [src, nonce] of heartbeats) this._acceptBackplaneHeartbeat(src, nonce);
1726
2291
  };
1727
- let initialized = false;
1728
2292
  const initialize = async () => {
2293
+ const transportEpoch = this._backplaneTransportEpoch;
1729
2294
  if (typeof sub.connect === 'function' && (sub.isOpen === false || sub.status === 'wait')) await sub.connect();
1730
2295
  if (this._destroyed) return;
1731
2296
  if (this._lastStreamId === '$') {
@@ -1737,14 +2302,22 @@ export class CacheService {
1737
2302
  }
1738
2303
  if (typeof sub.xrange === 'function') {
1739
2304
  await checkGap();
1740
- apply(await sub.xread('STREAMS', this.backplaneStreamKey, this._lastStreamId));
2305
+ const response = await sub.xread('STREAMS', this.backplaneStreamKey, this._lastStreamId);
2306
+ if (this._destroyed || (strict && transportEpoch !== this._backplaneTransportEpoch)) return;
2307
+ this._backplaneSubscriptionReady = true;
2308
+ apply(response);
1741
2309
  }
1742
2310
  initialized = true;
1743
- this._backplaneAvailable = true;
2311
+ if (strict) {
2312
+ this._backplaneSubscriptionReady = true;
2313
+ this._startBackplaneHeartbeat();
2314
+ void this._publishBackplaneHeartbeat();
2315
+ } else this._setBackplaneAvailable();
1744
2316
  };
1745
2317
  try { await initialize(); }
1746
2318
  catch (error) {
1747
- this._backplaneAvailable = false;
2319
+ if (this._destroyed) return;
2320
+ this._setBackplaneUnavailable('initialization_failed');
1748
2321
  this.logger.warn('Backplane stream initialization failed; retrying in consumer loop', { error: (error as Error).message });
1749
2322
  }
1750
2323
 
@@ -1754,6 +2327,8 @@ export class CacheService {
1754
2327
  try {
1755
2328
  if (!initialized) await initialize();
1756
2329
  if (this._destroyed) break;
2330
+ if (!initialized) continue;
2331
+ const transportEpoch = this._backplaneTransportEpoch;
1757
2332
  await checkGap();
1758
2333
  const res = await (sub as any).xread(
1759
2334
  'BLOCK', this.opts.backplaneStreamBlockMs,
@@ -1761,11 +2336,15 @@ export class CacheService {
1761
2336
  ) as Array<[string, Array<[string, string[]]>]> | null;
1762
2337
 
1763
2338
  if (this._destroyed) break;
1764
- this._backplaneAvailable = true;
2339
+ if (strict) {
2340
+ if (transportEpoch !== this._backplaneTransportEpoch) continue;
2341
+ await checkGap();
2342
+ if (this._destroyed || transportEpoch !== this._backplaneTransportEpoch) continue;
2343
+ } else this._setBackplaneAvailable();
1765
2344
 
1766
2345
  if (res && res.length > 0) {
1767
2346
  apply(res);
1768
- this._backplaneAvailable = true;
2347
+ if (!strict) this._setBackplaneAvailable();
1769
2348
  } else {
1770
2349
  // Idle timeout without messages — yield briefly before next long-poll
1771
2350
  await new Promise(resolve => setTimeout(resolve, 10));
@@ -1776,7 +2355,8 @@ export class CacheService {
1776
2355
  if (msg.includes('NOGROUP') || msg.includes('smaller than') || msg.includes('trimmed')) {
1777
2356
  this._resetAfterStreamGap();
1778
2357
  }
1779
- this._backplaneAvailable = false;
2358
+ if (strict) { initialized = false; this._protectedConsumerDisconnected('consumer_error'); }
2359
+ else this._setBackplaneUnavailable('consumer_error');
1780
2360
  await new Promise(resolve => setTimeout(resolve, 200));
1781
2361
  }
1782
2362
  }
@@ -1793,11 +2373,12 @@ export class CacheService {
1793
2373
  * number. Invalid entries are logged and dropped — never applied.
1794
2374
  */
1795
2375
  /** @internal Exposed for testing. */
1796
- _processStreamEntry(fields: string[]): void {
2376
+ _processStreamEntry(fields: string[], deferHeartbeat?: (src: unknown, nonce: unknown) => void): void {
1797
2377
  let op = '';
1798
2378
  let key = '';
1799
2379
  let src = '';
1800
2380
  let tagVersionRaw: string | undefined;
2381
+ let nonce: string | undefined;
1801
2382
 
1802
2383
  for (let i = 0; i + 1 < fields.length; i += 2) {
1803
2384
  const f = fields[i];
@@ -1806,6 +2387,13 @@ export class CacheService {
1806
2387
  else if (f === 'key') key = v;
1807
2388
  else if (f === 'src') src = v;
1808
2389
  else if (f === 'tagVersion') tagVersionRaw = v;
2390
+ else if (f === 'nonce') nonce = v;
2391
+ }
2392
+
2393
+ if (op === 'heartbeat') {
2394
+ if (deferHeartbeat) deferHeartbeat(src, nonce);
2395
+ else this._acceptBackplaneHeartbeat(src, nonce);
2396
+ return;
1809
2397
  }
1810
2398
 
1811
2399
  const validOp =
@@ -1815,7 +2403,7 @@ export class CacheService {
1815
2403
  op === 'tag_pattern_incr' ||
1816
2404
  op === 'tag_pattern_del';
1817
2405
  if (!validOp || typeof key !== 'string' || !key || typeof src !== 'string' || !src ||
1818
- ((op === 'del' || op === 'del-glob') && this._namespace && !key.startsWith(`${this._namespace}:`))) {
2406
+ ((op === 'del' || op === 'del-glob') && !key.startsWith(this._dataPrefix))) {
1819
2407
  this.logger.warn('Backplane: rejected invalid stream entry', {
1820
2408
  op: String(op).slice(0, 40),
1821
2409
  key: typeof key === 'string' ? key.slice(0, 100).replace(/[\r\n\t]/g, ' ') : String(key),
@@ -1824,15 +2412,8 @@ export class CacheService {
1824
2412
  }
1825
2413
 
1826
2414
  // Reject partial numeric strings rather than truncating them with parseInt().
1827
- let tagVersion: number | undefined;
1828
- if (tagVersionRaw !== undefined) {
1829
- const parsed = Number(tagVersionRaw);
1830
- if (!Number.isSafeInteger(parsed) || parsed < 0) {
1831
- this.logger.warn('Backplane: rejected stream entry with non-numeric tagVersion', { key });
1832
- return;
1833
- }
1834
- tagVersion = parsed;
1835
- }
2415
+ const tagVersion = this._parseTagVersion(tagVersionRaw, key, 'stream entry');
2416
+ if (tagVersion === INVALID_TAG_VERSION) return;
1836
2417
 
1837
2418
  if (src === this.instanceId) {
1838
2419
  this.counters.invSkipped++;
@@ -1840,17 +2421,23 @@ export class CacheService {
1840
2421
  }
1841
2422
 
1842
2423
  this.counters.invReceived++;
1843
- this._applyInvalidationEvent(op, key, tagVersion);
2424
+ this._completeBackplaneCascade(this._applyInvalidationEvent(op, key, tagVersion));
1844
2425
  }
1845
2426
 
1846
- private _applyInvalidationEvent(op: string, key: string, tagVersion?: number): void {
2427
+ private _applyInvalidationEvent(op: string, key: string, tagVersion?: number): DependencyCascade | undefined {
1847
2428
  if (op === 'del') {
1848
- this.l1.delete(key);
2429
+ const cascade = this._cascadeDependencies(key);
1849
2430
  this._bumpKeyMutation(key);
1850
2431
  this.inflight.delete(key);
1851
2432
  this._invalidateDiskKey(key);
1852
- this._cascadeDependencies(key);
2433
+ this.l1.delete(key);
2434
+ this._removeKeyTags(key);
2435
+ this._removeKeyDependencies(key);
2436
+ this._l1Counters.delete(key);
2437
+ this.logger.debug('Backplane: invalidation applied', { op, key: key.slice(0, 60) });
2438
+ return cascade;
1853
2439
  } else if (op === 'del-glob') {
2440
+ const cascade = this._cascadeDependenciesForPattern(key);
1854
2441
  this._fenceInvalidation();
1855
2442
  this.l1.deletePattern(key);
1856
2443
  const pfx = key.endsWith('*') ? key.slice(0, -1) : key;
@@ -1871,9 +2458,9 @@ export class CacheService {
1871
2458
  this.tagIndex.clear();
1872
2459
  this.keyTags.clear();
1873
2460
  this.tagVersions.clear();
1874
- this.dependencyIndex.clear();
1875
- this.keyDependencies.clear();
2461
+ this._clearDependencyMetadata();
1876
2462
  }
2463
+ return cascade;
1877
2464
  } else if (op === 'tag_incr') {
1878
2465
  this._fenceInvalidation();
1879
2466
  const tag = key;
@@ -1903,7 +2490,7 @@ export class CacheService {
1903
2490
  this._fenceInvalidation();
1904
2491
  const pattern = key;
1905
2492
  const matchedTagKeys: string[] = [];
1906
- const prefix = this.nk('_tag_:');
2493
+ const prefix = this.tagIndexPrefix();
1907
2494
  for (const [tagKey, members] of this.tagIndex) {
1908
2495
  const tag = tagKey.startsWith(prefix) ? tagKey.slice(prefix.length) : tagKey;
1909
2496
  if (matchesTagPattern(pattern, tag)) {
@@ -1922,16 +2509,46 @@ export class CacheService {
1922
2509
  this.logger.debug('Backplane: invalidation applied', { op, key: key.slice(0, 60) });
1923
2510
  }
1924
2511
 
2512
+ /**
2513
+ * Parse an optional tag version from either transport.
2514
+ *
2515
+ * Pub/Sub previously forwarded any numeric value (including `1.5`) while
2516
+ * Streams rejected non-integers, so the two transports disagreed on the same
2517
+ * logical payload. Both now share this validation: absent means "no version",
2518
+ * and anything present must be a non-negative safe integer.
2519
+ */
2520
+ private _parseTagVersion(value: unknown, key: string, source: string): number | undefined | typeof INVALID_TAG_VERSION {
2521
+ if (value === undefined) return undefined;
2522
+ if (typeof value === 'string') {
2523
+ const parsed = Number(value);
2524
+ if (!Number.isSafeInteger(parsed) || parsed < 0) {
2525
+ this.logger.warn(`Backplane: rejected ${source} with non-numeric tagVersion`, { key });
2526
+ return INVALID_TAG_VERSION;
2527
+ }
2528
+ return parsed;
2529
+ }
2530
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {
2531
+ this.logger.warn(`Backplane: rejected ${source} with non-numeric tagVersion`, { key });
2532
+ return INVALID_TAG_VERSION;
2533
+ }
2534
+ return value;
2535
+ }
2536
+
1925
2537
  /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
1926
2538
  _handleBackplaneMessage(message: string): void {
1927
2539
  try {
1928
2540
  const msg = JSON.parse(message);
2541
+ if (msg?.op === 'heartbeat' && typeof msg.src === 'string') {
2542
+ this._acceptBackplaneHeartbeat(msg.src, msg.nonce);
2543
+ return;
2544
+ }
1929
2545
  if (
1930
2546
  !msg ||
1931
2547
  typeof msg !== 'object' ||
1932
2548
  Array.isArray(msg) ||
1933
2549
  typeof msg.src !== 'string' ||
1934
2550
  typeof msg.key !== 'string' ||
2551
+ ((msg.op === 'del' || msg.op === 'del-glob') && !msg.key.startsWith(this._dataPrefix)) ||
1935
2552
  (msg.op !== 'del' && msg.op !== 'del-glob' && msg.op !== 'tag_incr' && msg.op !== 'tag_pattern_incr' && msg.op !== 'tag_pattern_del')
1936
2553
  ) {
1937
2554
  this.logger.warn('Backplane: rejected invalid pubsub message format', {
@@ -1939,12 +2556,14 @@ export class CacheService {
1939
2556
  });
1940
2557
  return;
1941
2558
  }
2559
+ const tagVersion = this._parseTagVersion(msg.tagVersion, msg.key, 'pubsub message');
2560
+ if (tagVersion === INVALID_TAG_VERSION) return;
1942
2561
  if (msg.src === this.instanceId) {
1943
2562
  this.counters.invSkipped++;
1944
2563
  return; // own message — our L1 is already current
1945
2564
  }
1946
2565
  this.counters.invReceived++;
1947
- this._applyInvalidationEvent(msg.op, msg.key, typeof msg.tagVersion === 'number' ? msg.tagVersion : undefined);
2566
+ this._completeBackplaneCascade(this._applyInvalidationEvent(msg.op, msg.key, tagVersion));
1948
2567
  } catch {
1949
2568
  this.logger.warn('Backplane: malformed message JSON parse failed');
1950
2569
  }
@@ -1985,6 +2604,7 @@ export class CacheService {
1985
2604
  args.push('tagVersion', String(tagVersion));
1986
2605
  }
1987
2606
  await (client as any).xadd(...args);
2607
+ this.cb.onSuccess();
1988
2608
  this.counters.invSent++;
1989
2609
  return;
1990
2610
  }
@@ -2002,8 +2622,10 @@ export class CacheService {
2002
2622
  payload,
2003
2623
  );
2004
2624
  }
2625
+ this.cb.onSuccess();
2005
2626
  this.counters.invSent++;
2006
2627
  } catch (err) {
2628
+ this.cb.onFailure(err);
2007
2629
  this.logger.warn('Backplane invalidation publish failed', { op, key, error: (err as Error).message });
2008
2630
  if (this.opts.awaitInvalidationBackplane) {
2009
2631
  throw err;
@@ -2042,7 +2664,7 @@ export class CacheService {
2042
2664
  key,
2043
2665
  tagVersion,
2044
2666
  timestamp: Date.now(),
2045
- namespace: this._namespace || undefined,
2667
+ namespace: this._namespace,
2046
2668
  };
2047
2669
  await cr.relay.broadcast(event);
2048
2670
  this.counters.crossRegionSent++;
@@ -2086,25 +2708,29 @@ export class CacheService {
2086
2708
  }
2087
2709
 
2088
2710
  // If namespaces don't match, ignore
2089
- if (event.namespace !== undefined && event.namespace !== (this._namespace || undefined)) {
2711
+ if ((event.namespace ?? '') !== this._namespace) {
2090
2712
  return false;
2091
2713
  }
2092
- if ((event.op === 'del' || event.op === 'del-glob') && this._namespace && !event.key.startsWith(`${this._namespace}:`)) return false;
2714
+ if ((event.op === 'del' || event.op === 'del-glob') && !event.key.startsWith(this._dataPrefix)) return false;
2093
2715
  this._markCrossRegionEventSeen(event.id);
2094
2716
 
2095
2717
  this.counters.crossRegionReceived++;
2096
2718
 
2097
- const localTags = new Set([...this.tagVersions.keys(), ...[...this.tagIndex.keys()].map(key => this.unnk(key).replace(/^_tag_:/, ''))]);
2719
+ const tagPrefix = this.tagIndexPrefix();
2720
+ const localTags = new Set([...this.tagVersions.keys(), ...[...this.tagIndex.keys()].map(key =>
2721
+ key.startsWith(tagPrefix) ? key.slice(tagPrefix.length) : key,
2722
+ )]);
2098
2723
  let version = event.tagVersion;
2099
2724
  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);
2725
+ const cascade = this._applyInvalidationEvent(event.op, event.key, version);
2101
2726
  try {
2102
2727
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2103
2728
  const client = await this.getRedis();
2104
2729
  if (event.op === 'del' || event.op === 'del-glob') {
2105
- await this._deleteRedisKeys(client, event.op === 'del' ? [event.key] : await this._scanKeys(client, event.key));
2730
+ await this._deleteRedisKeys(client, event.op === 'del'
2731
+ ? [event.key, ...(cascade?.keys ?? [])] : await this._scanKeys(client, event.key));
2106
2732
  } 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)));
2733
+ version = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.tagVersionKey(event.key), String(version)));
2108
2734
  this._setLocalTagVersion(event.key, version);
2109
2735
  } else {
2110
2736
  const matched = await this._resolveMatchingTags(event.key, false);
@@ -2112,11 +2738,11 @@ export class CacheService {
2112
2738
  for (const tag of matched) {
2113
2739
  if (event.op === 'tag_pattern_incr') {
2114
2740
  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)));
2741
+ const next = Number(await client.eval(LUA_RECEIVE_TAG_VERSION, 1, this.tagVersionKey(tag), String(floor)));
2116
2742
  this._setLocalTagVersion(tag, next);
2117
2743
  await this.publishInvalidation('tag_incr', tag, next, true);
2118
2744
  } else {
2119
- const tagKey = this.nk(`_tag_:${tag}`);
2745
+ const tagKey = this.tagIndexKey(tag);
2120
2746
  const members = await client.smembers(tagKey) as string[];
2121
2747
  this._removeTagMembersLocal(members);
2122
2748
  await this._deleteRedisKeys(client, [...members, tagKey]);
@@ -2126,13 +2752,19 @@ export class CacheService {
2126
2752
  }
2127
2753
  this.cb.onSuccess();
2128
2754
  }
2129
- await this.publishInvalidation(event.op, event.key, version, true);
2755
+ if (event.op === 'del') {
2756
+ await this._publishKeyInvalidations([event.key, ...(cascade?.keys ?? [])], true);
2757
+ } else {
2758
+ await this.publishInvalidation(event.op, event.key, version, true);
2759
+ }
2130
2760
  } catch (error) {
2131
2761
  this._seenCrossRegionEvents.delete(event.id);
2132
2762
  this.counters.crossRegionErrors++;
2133
2763
  this.logger.warn('Cross-region regional invalidation failed', { error: (error as Error).message });
2134
2764
  if (this.opts.awaitInvalidationBackplane) throw error;
2135
2765
  return false;
2766
+ } finally {
2767
+ cascade?.finish();
2136
2768
  }
2137
2769
 
2138
2770
  this.logger.info('Cross-region invalidation applied', {
@@ -2192,11 +2824,12 @@ export class CacheService {
2192
2824
  }
2193
2825
  }
2194
2826
 
2195
- private async _parseGenerationalRedisHash<T>(
2827
+ private async _parseRedisHash<T>(
2196
2828
  k: string,
2197
2829
  hashData: Record<string, string>,
2198
2830
  ): Promise<RedisCacheEntry<T> | null> {
2199
2831
  if (!hashData || !hashData.d) return null;
2832
+ const revision = isWriteRevision(hashData.r) ? hashData.r : undefined;
2200
2833
  let storedTagVersions: Record<string, number> = {};
2201
2834
  if (hashData.tv) {
2202
2835
  try {
@@ -2206,12 +2839,11 @@ export class CacheService {
2206
2839
  storedTagVersions = parsed;
2207
2840
  } catch { return null; }
2208
2841
  }
2842
+ const value = await this._decryptAndDeserialize<T>(hashData.d, this._redisContext(k, hashData));
2209
2843
  if (await this._isGenerationalEntryStale(storedTagVersions)) {
2210
- const setAtMs = parseInt(hashData.t, 10) || 0;
2211
- this._deleteIfStale(k, setAtMs);
2844
+ this._deleteIfStale(k, revision);
2212
2845
  return { stale: true };
2213
2846
  }
2214
- const value = await this._decryptAndDeserialize<T>(hashData.d);
2215
2847
  const expiresAt = Number(hashData.e);
2216
2848
  const staleAt = Number(hashData.s);
2217
2849
  let tags: string[] | undefined;
@@ -2222,7 +2854,7 @@ export class CacheService {
2222
2854
  if (Array.isArray(parsedTags) && parsedTags.every(tag => typeof tag === 'string')) tags = parsedTags;
2223
2855
  if (Array.isArray(parsedDependencies) && parsedDependencies.every(pattern => typeof pattern === 'string')) dependsOn = parsedDependencies;
2224
2856
  } catch { return null; }
2225
- return { value, tagVersions: storedTagVersions, stale: false, tags, dependsOn, setAt: Number(hashData.t) || undefined,
2857
+ return { value, tagVersions: storedTagVersions, stale: false, tags, dependsOn, revision, setAt: Number(hashData.t) || undefined,
2226
2858
  expiresAt: Number.isFinite(expiresAt) && expiresAt > 0 ? expiresAt : undefined,
2227
2859
  staleAt: Number.isFinite(staleAt) && staleAt > 0 ? staleAt : undefined };
2228
2860
  }
@@ -2232,6 +2864,7 @@ export class CacheService {
2232
2864
  k: string,
2233
2865
  allowAutoPipeline = false,
2234
2866
  ): Promise<RedisCacheEntry<T> | null> {
2867
+ if (this._isRedisReadInvalidated(k)) return null;
2235
2868
  const readStartedAt = Date.now();
2236
2869
  const read = async (hash: boolean) => allowAutoPipeline && this.opts.autoPipeline && this.pipeliner
2237
2870
  ? this.pipeliner.read(k, hash)
@@ -2243,64 +2876,100 @@ export class CacheService {
2243
2876
  }
2244
2877
  return entry.expiresAt !== undefined && entry.expiresAt <= Date.now() ? null : entry;
2245
2878
  };
2246
- if (this.opts.tagStrategy === 'generational' && typeof (client as any).hgetall === 'function') {
2247
- try {
2248
- const { raw: hashData, ttlMs } = await read(true);
2249
- if (typeof hashData === 'string') {
2250
- const value = await this._decryptAndDeserialize<T>(hashData);
2251
- return withExpiry({ value, stale: false }, ttlMs);
2252
- }
2253
- if (hashData && hashData.d) {
2254
- return withExpiry(await this._parseGenerationalRedisHash<T>(k, hashData), ttlMs);
2255
- }
2256
- return null;
2257
- } catch (err) {
2879
+ const readHash = async (): Promise<RedisCacheEntry<T> | null> => {
2880
+ const { raw: hashData, ttlMs } = await read(true);
2881
+ if (typeof hashData === 'string') {
2882
+ const value = await this._decryptAndDeserialize<T>(hashData, this._redisContext(k));
2883
+ return withExpiry({ value, stale: false }, ttlMs);
2884
+ }
2885
+ return hashData?.d ? withExpiry(await this._parseRedisHash<T>(k, hashData), ttlMs) : null;
2886
+ };
2887
+ const supportsHashes = typeof client.hgetall === 'function';
2888
+ if (this.opts.tagStrategy === 'generational' && supportsHashes) {
2889
+ try { return await readHash(); }
2890
+ catch (err) {
2258
2891
  const msg = err instanceof Error ? err.message : String(err);
2259
2892
  if (!msg.includes('WRONGTYPE')) throw err;
2260
2893
  // Fall through to GET if key was stored as a plain string without tags
2261
2894
  }
2262
2895
  }
2263
2896
 
2264
- const { raw, ttlMs } = await read(false);
2265
- if (raw == null) return null;
2266
- if (typeof raw !== 'string') return null;
2267
- const value = await this._decryptAndDeserialize<T>(raw);
2268
- return withExpiry({ value, stale: false }, ttlMs);
2897
+ try {
2898
+ const { raw, ttlMs } = await read(false);
2899
+ if (typeof raw === 'string') {
2900
+ const value = await this._decryptAndDeserialize<T>(raw, this._redisContext(k));
2901
+ return withExpiry({ value, stale: false }, ttlMs);
2902
+ }
2903
+ // The typed atomic read can discover a hash even when the caller asked
2904
+ // for the ordinary string path. Preserve the old WRONGTYPE fallback
2905
+ // behavior without issuing a second Redis read.
2906
+ return raw?.d ? withExpiry(await this._parseRedisHash<T>(k, raw), ttlMs) : null;
2907
+ } catch (err) {
2908
+ // Set-tagged values carry tags/deadlines in the shared Node hash envelope.
2909
+ // Keep the single GET path for ordinary untagged values.
2910
+ const message = err instanceof Error ? err.message : String(err);
2911
+ if (!supportsHashes || !message.includes('WRONGTYPE')) throw err;
2912
+ return readHash();
2913
+ }
2269
2914
  }
2270
2915
 
2271
- private async _getTagVersion(tag: string): Promise<number> {
2916
+ private _getTagVersion(tag: string): Promise<number> {
2272
2917
  const now = performance.now();
2273
2918
  const local = this.tagVersions.get(tag);
2274
2919
  if (local && (local.refreshEpoch ?? 0) === this._tagRefreshEpoch && (now - local.lastSyncedAt < this.opts.tagVersionTtlMs)) {
2275
- return local.version;
2276
- }
2920
+ return Promise.resolve(local.version);
2921
+ }
2922
+ if (this._redisDisabled) {
2923
+ const version = local?.version ?? 0;
2924
+ this._setLocalTagVersion(tag, version, now);
2925
+ return Promise.resolve(version);
2926
+ }
2927
+
2928
+ const epoch = this._tagRefreshEpoch, fence = this._globalEpoch;
2929
+ // A zero TTL requires a new observation per caller. A positive TTL bounds
2930
+ // the age of shared observations just as it bounds completed metadata.
2931
+ if (this.opts.tagVersionTtlMs <= 0) return this._refreshTagVersion(tag, local?.version ?? 0, now, epoch, fence);
2932
+ const pending = this._tagVersionRefreshes.get(tag);
2933
+ if (pending?.epoch === epoch && pending.fence === fence && now - pending.startedAt < this.opts.tagVersionTtlMs) {
2934
+ return pending.promise.then(version => Math.max(version, this.tagVersions.get(tag)?.version ?? 0));
2935
+ }
2936
+ const refresh = { epoch, fence, startedAt: now, promise: this._refreshTagVersion(tag, local?.version ?? 0, now, epoch, fence) };
2937
+ if (this._tagVersionRefreshes.size < 10_000 || pending) this._tagVersionRefreshes.set(tag, refresh);
2938
+ return refresh.promise.then(version => Math.max(version, this.tagVersions.get(tag)?.version ?? 0)).finally(() => {
2939
+ // An older completion cannot delete a newer refresh after an explicit reset.
2940
+ if (this._tagVersionRefreshes.get(tag) === refresh) this._tagVersionRefreshes.delete(tag);
2941
+ });
2942
+ }
2943
+
2944
+ private async _refreshTagVersion(tag: string, fallback: number, now: number, epoch: number, fence: number): Promise<number> {
2277
2945
  if (!this._redisDisabled) {
2278
2946
  try {
2279
2947
  const client = await this.getRedis();
2280
- const raw = await client.get(this.nk(`tag_ver:${tag}`));
2948
+ const raw = await client.get(this.tagVersionKey(tag));
2281
2949
  const parsed = raw ? Number(raw) : 0;
2282
2950
  if (!Number.isSafeInteger(parsed) || parsed < 0) throw new Error('Invalid Redis tag generation');
2283
2951
  const version = Math.max(this.tagVersions.get(tag)?.version ?? 0, parsed);
2284
2952
  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));
2953
+ if (raw === null) await client.set(this.tagVersionKey(tag), String(version), 'NX');
2954
+ else if (version > parsed) await client.eval(LUA_MAX_TAG_VERSION, 1, this.tagVersionKey(tag), String(version));
2955
+ }
2956
+ if (!this._destroyed && this._tagRefreshEpoch === epoch && this._globalEpoch === fence) {
2957
+ this._setLocalTagVersion(tag, version, now);
2287
2958
  }
2288
- this._setLocalTagVersion(tag, version, now);
2289
2959
  this.cb.onSuccess();
2290
- return version;
2960
+ return Math.max(version, this.tagVersions.get(tag)?.version ?? 0);
2291
2961
  } catch {
2292
2962
  /* fallback to local */
2293
2963
  }
2294
2964
  }
2295
- const version = this.tagVersions.get(tag)?.version ?? local?.version ?? 0;
2296
- if (this._redisDisabled) this._setLocalTagVersion(tag, version, now);
2297
- return version;
2965
+ return Math.max(fallback, this.tagVersions.get(tag)?.version ?? 0);
2298
2966
  }
2299
2967
 
2300
2968
  private async _readRedisBatch<T>(client: AnyRedisClient, keys: string[]): Promise<Map<string, RedisCacheEntry<T>>> {
2301
2969
  const entries = new Map<string, RedisCacheEntry<T>>();
2302
2970
  const groups = new Map<string, string[]>();
2303
2971
  for (const key of new Set(keys)) {
2972
+ if (this._isRedisReadInvalidated(key)) continue;
2304
2973
  const group = client instanceof RedisCluster ? client.slots[redisHashSlot(key)]?.[0] ?? String(redisHashSlot(key)) : 'single';
2305
2974
  const members = groups.get(group) ?? [];
2306
2975
  members.push(key);
@@ -2324,6 +2993,7 @@ export class CacheService {
2324
2993
  if (!results) throw new Error('Redis batch read aborted');
2325
2994
  for (let index = 0; index < chunk.length; index++) {
2326
2995
  try {
2996
+ if (this._isRedisReadInvalidated(chunk[index])) continue;
2327
2997
  const tuple = results[index];
2328
2998
  if (!tuple) continue;
2329
2999
  let [error, raw] = tuple;
@@ -2347,9 +3017,9 @@ export class CacheService {
2347
3017
  if (ttl === -2 || ttl === 0) continue;
2348
3018
  }
2349
3019
  const entry = typeof raw === 'string'
2350
- ? { value: await this._decryptAndDeserialize<T>(raw), stale: false } as RedisCacheEntry<T>
3020
+ ? { value: await this._decryptAndDeserialize<T>(raw, this._redisContext(chunk[index])), stale: false } as RedisCacheEntry<T>
2351
3021
  : raw && typeof raw === 'object' && 'd' in raw
2352
- ? await this._parseGenerationalRedisHash<T>(chunk[index], raw as Record<string, string>) : null;
3022
+ ? await this._parseRedisHash<T>(chunk[index], raw as Record<string, string>) : null;
2353
3023
  if (!entry || entry.stale) continue;
2354
3024
  if (ttl !== undefined && ttl > 0) entry.expiresAt = Math.min(entry.expiresAt ?? Infinity, startedAt + ttl);
2355
3025
  if (entry.expiresAt !== undefined && entry.expiresAt <= Date.now()) continue;
@@ -2364,42 +3034,62 @@ export class CacheService {
2364
3034
  return entries;
2365
3035
  }
2366
3036
 
2367
- private _promoteRedisEntry<T>(key: string, entry: RedisCacheEntry<T>, fallbackTtlMs: number, priority: CachePriority): boolean {
3037
+ private _promoteRedisEntry<T>(key: string, entry: RedisCacheEntry<T>, fallbackTtlMs: number, priority: CachePriority, readEpoch?: number): boolean {
3038
+ this._ensureCachedReadAllowed(readEpoch);
3039
+ if (this._isRedisReadInvalidated(key)) return false;
2368
3040
  const expiresAt = entry.expiresAt ?? Date.now() + fallbackTtlMs;
2369
3041
  if (expiresAt <= Date.now()) return false;
2370
3042
  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 });
3043
+ entry.tagVersions, entry.setAt, entry.tags, entry.dependsOn, entry.revision);
3044
+ if (admitted && !this._restoreEntryMetadata(key, { ...entry, expiresAt })) return false;
2373
3045
  return true;
2374
3046
  }
2375
3047
 
2376
- private async _readDiskEntry<T>(key: string, epoch: string): Promise<{ value: T; entry: DiskCacheEntry } | null> {
3048
+ private async _readDiskEntry<T>(key: string, epoch: string, readEpoch?: number): Promise<{ value: T; entry: DiskCacheEntry } | null> {
3049
+ this._ensureCachedReadAllowed(readEpoch);
2377
3050
  if (this._diskDisabled || this._pendingDiskDeletes.has(key) || !this.watchdog.isDiskAllowed()) return null;
2378
3051
  const start = performance.now();
2379
3052
  const entry = this.disk.load(key);
2380
3053
  const elapsed = performance.now() - start;
2381
3054
  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) ||
3055
+ this.watchdog.onCanaryResult(true, elapsed); // A clean miss also demonstrates responsive I/O.
3056
+ if (!entry || (this._strictInvalidationReadProtectionEnabled() &&
3057
+ (!entry.revision || this._protectedSpillRevisions.get(key) !== entry.revision)) ||
3058
+ this._isTombstonedByPattern(key, entry.setAt ?? 0) || await this._isGenerationalEntryStale(entry.tagVersions) ||
2384
3059
  this._destroyed || this._getKeyMutationEpoch(key) !== epoch || entry.expiresAt <= Date.now()) return null;
3060
+ this._ensureCachedReadAllowed(readEpoch);
2385
3061
  this.l1.importEntries([{ key, entry: entry as SmartCacheEntry }], this.opts.forbiddenSnapshotPrefixes);
2386
3062
  const hit = this.l1.get(key);
2387
3063
  const value = hit ? hit.value as T : entry.isCompressed
2388
3064
  ? this.codec.decode<T>(entry.data as Buffer) : JSON.parse(entry.data as string) as T;
2389
- this._restoreEntryMetadata(key, entry);
3065
+ if (!this._restoreEntryMetadata(key, entry)) return null;
3066
+ this._protectedSpillRevisions.delete(key);
2390
3067
  return { value, entry };
2391
3068
  }
2392
3069
 
2393
3070
  /** Common write policy and metadata across get/set/revalidation/draining. */
2394
3071
  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,
3072
+ key: string, data: unknown, expiresAt: number, setAt: number, revision: string, tagVersions?: Record<string, number>,
3073
+ staleAt?: number, tags?: string[], dependsOn?: string[], canCommit: () => boolean = () => true, packed?: Buffer,
2397
3074
  ): Promise<void> {
2398
3075
  if (this._redisDisabled || this.opts.l2WriteMode !== 'read-write' || !canCommit() || this._destroyed) return;
2399
3076
  const client = await this.getRedis();
2400
- const stored = await this._serializeAndEncrypt(JSON.stringify(data) ?? 'undefined');
3077
+ if (this.opts.tagStrategy === 'set' && tags?.length) {
3078
+ await this._registerTags(key, tags, expiresAt);
3079
+ if (!canCommit() || this._destroyed) return;
3080
+ }
3081
+ const useHash = (this.opts.tagStrategy === 'generational' && (tagVersions || typeof client.hgetall === 'function')) ||
3082
+ (tags?.length && typeof client.hgetall === 'function');
3083
+ const hash: Record<string, string> | undefined = useHash
3084
+ ? { t: String(setAt), r: revision, tv: JSON.stringify(tagVersions ?? {}), e: String(expiresAt) } : undefined;
3085
+ if (hash) {
3086
+ if (staleAt !== undefined) hash.s = String(staleAt);
3087
+ if (tags?.length) hash.tags = JSON.stringify(tags);
3088
+ if (dependsOn?.length) hash.deps = JSON.stringify(dependsOn);
3089
+ }
3090
+ const encoded = packed ?? this.codec.encode(data);
3091
+ const stored = await this._serializeAndEncrypt(PREFIX_MSGPACK + encoded.toString('base64'), this._redisContext(key, hash));
2401
3092
  if (!canCommit() || this._destroyed) return;
2402
- const useHash = this.opts.tagStrategy === 'generational' && (tagVersions || (!this.opts.autoPipeline && typeof client.hgetall === 'function'));
2403
3093
  // Plain legacy Redis strings cannot carry SWR metadata: expire them at soft TTL.
2404
3094
  const remaining = (useHash ? expiresAt : staleAt ?? expiresAt) - Date.now();
2405
3095
  if (remaining <= 0) return;
@@ -2407,11 +3097,7 @@ export class CacheService {
2407
3097
  if (useHash) {
2408
3098
  const transaction = client.multi();
2409
3099
  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);
3100
+ transaction.hset(key, { ...hash!, d: stored });
2415
3101
  transaction.expire(key, ttl);
2416
3102
  const result = await transaction.exec();
2417
3103
  if (!result || result.some(([error]: [Error | null, unknown]) => error)) throw new Error('Redis cache write transaction failed');
@@ -2425,12 +3111,18 @@ export class CacheService {
2425
3111
  this.cb.onSuccess();
2426
3112
  }
2427
3113
 
2428
- private _deleteIfStale(k: string, setAtMs: number): void {
2429
- this.l1.deleteIfSetBefore(k, setAtMs);
2430
- if (!this._diskDisabled) this.disk.delete(k);
3114
+ private _deleteIfStale(k: string, revision: string | undefined): void {
3115
+ // No timestamp fallback: revisionless entries are rejected as stale but left
3116
+ // for expiry/replacement because their write identity was never observed.
3117
+ if (!isWriteRevision(revision)) return;
3118
+ this.l1.deleteIfRevision(k, revision);
3119
+ for (const spill of this._pendingSpills) {
3120
+ if (spill.key === k && spill.revision === revision) spill.cancelled = true;
3121
+ }
3122
+ if (!this._diskDisabled) this.disk.deleteIfRevision(k, revision);
2431
3123
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
2432
3124
  void this.getRedis().then(client => {
2433
- return client.eval(LUA_COMPARE_AND_DELETE, 1, k, String(setAtMs));
3125
+ return client.eval(LUA_COMPARE_AND_DELETE, 1, k, revision);
2434
3126
  }).catch(() => {});
2435
3127
  }
2436
3128
  }
@@ -2439,44 +3131,52 @@ export class CacheService {
2439
3131
  * Serialize payload for L2 Redis storage applying compression and encryption as configured.
2440
3132
  * Offloads to worker thread if pool is active and payload exceeds threshold.
2441
3133
  */
2442
- private async _serializeAndEncrypt(serialized: string): Promise<string> {
3134
+ private _redisContext(key: string, hash?: Record<string, string>): string {
3135
+ return JSON.stringify(hash
3136
+ ? ['tricache-redis-v2', key, 'hash', hash.t, hash.r, hash.tv, hash.e, hash.s, hash.tags, hash.deps]
3137
+ : ['tricache-redis-v2', key, 'string']);
3138
+ }
3139
+
3140
+ private async _serializeAndEncrypt(serialized: string, context?: string): Promise<string> {
2443
3141
  const isCompressed = (this.opts.customCompressor || (this.opts.compression && this.opts.compression !== 'none')) && serialized.length > this.opts.compressionThresholdBytes;
2444
3142
  if (this._workerPool && !this.opts.customCompressor && (this.enc.isEnabled || isCompressed) && serialized.length > this.opts.workerThresholdBytes) {
2445
- return this._workerPool.encrypt(serialized);
3143
+ return this._workerPool.encrypt(serialized, context);
2446
3144
  }
2447
3145
  if (isCompressed) {
2448
3146
  const compressed = compressBuffer(Buffer.from(serialized, 'utf8'), this.opts.compression, this.opts.customCompressor);
2449
3147
  if (this.enc.isEnabled) {
2450
- const encrypted = this.enc.encryptBuffer(compressed);
3148
+ const encrypted = this.enc.encryptBuffer(compressed, context);
2451
3149
  return PREFIX_ENC_COMPRESSED + encrypted.toString('base64');
2452
3150
  }
2453
3151
  return PREFIX_COMPRESSED + compressed.toString('base64');
2454
3152
  }
2455
- return this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
3153
+ return this.enc.isEnabled ? this.enc.encrypt(serialized, context) : serialized;
2456
3154
  }
2457
3155
 
2458
3156
  /**
2459
3157
  * Deserialize raw L2 Redis entry applying decryption and decompression as needed.
2460
3158
  * Offloads to worker thread if pool is active and payload exceeds threshold.
2461
3159
  */
2462
- private async _decryptAndDeserialize<T>(raw: string): Promise<T> {
3160
+ private async _decryptAndDeserialize<T>(raw: string, context?: string): Promise<T> {
3161
+ this.enc.assertReadPolicy(raw, context);
2463
3162
  let plain: string;
2464
3163
  if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
2465
- plain = await this._workerPool.decrypt(raw);
3164
+ plain = await this._workerPool.decrypt(raw, context);
2466
3165
  } else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
2467
3166
  const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), 'base64');
2468
- const decBuf = this.enc.decryptBuffer(encBuf);
3167
+ const decBuf = this.enc.decryptBuffer(encBuf, context);
2469
3168
  const decompressed = decompressBuffer(decBuf, this.opts.compression !== 'none' ? this.opts.compression : 'brotli', this.opts.customCompressor);
2470
3169
  plain = decompressed.toString('utf8');
2471
3170
  } else if (raw.startsWith(PREFIX_COMPRESSED)) {
2472
3171
  const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), 'base64');
2473
3172
  const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== 'none' ? this.opts.compression : 'brotli', this.opts.customCompressor);
2474
3173
  plain = decompressed.toString('utf8');
2475
- } else if (raw.startsWith('enc:v1:') || this.enc.isEnabled) {
2476
- plain = this.enc.decrypt(raw);
3174
+ } else if (/^(?:enc|a128):v[12]:/.test(raw) || this.enc.isEnabled) {
3175
+ plain = this.enc.decrypt(raw, context);
2477
3176
  } else {
2478
3177
  plain = raw;
2479
3178
  }
3179
+ if (plain.startsWith(PREFIX_MSGPACK)) return this.codec.decode<T>(Buffer.from(plain.slice(PREFIX_MSGPACK.length), 'base64'));
2480
3180
  return plain === 'undefined' ? undefined as T : JSON.parse(plain) as T;
2481
3181
  }
2482
3182
 
@@ -2536,9 +3236,10 @@ export class CacheService {
2536
3236
  }
2537
3237
  }
2538
3238
 
2539
- private async getRedis(): Promise<AnyRedisClient> {
3239
+ private async getRedis(onProbe?: (token: number | null) => void): Promise<AnyRedisClient> {
2540
3240
  this._assertActive('getRedis');
2541
- if (!this.cb.isAllowed()) throw new Error('tricache: L2 circuit breaker is open');
3241
+ if (!this.cb.isAllowed()) throw new RedisCircuitOpenError();
3242
+ onProbe?.(this.cb.probeToken);
2542
3243
  if (this.redis) return this.redis;
2543
3244
  if (this.redisConnecting) return this.redisConnecting;
2544
3245
 
@@ -2692,25 +3393,37 @@ export class CacheService {
2692
3393
  * NOTE: fs.writeFileSync is INTENTIONAL here: this method is invoked during SIGTERM/SIGINT
2693
3394
  * process termination hooks where asynchronous I/O would risk the Node.js event loop dying or
2694
3395
  * process.exit() being called before the snapshot is physically written to disk.
3396
+ *
3397
+ * @returns `true` when a snapshot was written (or when there was nothing to write),
3398
+ * `false` when the write failed. Callers that report shutdown success must
3399
+ * check this value.
2695
3400
  */
2696
- writeSnapshot(altPath?: string): void {
3401
+ writeSnapshot(altPath?: string): boolean {
3402
+ let staging: string | undefined;
2697
3403
  try {
2698
3404
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
2699
- if (entries.length === 0) return;
3405
+ if (entries.length === 0) return true;
2700
3406
 
2701
- const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries,
3407
+ const payload = { version: SNAPSHOT_VERSION, namespace: this._namespacePrefix, writtenAt: Date.now(), entries,
2702
3408
  streamId: this.opts.backplaneMode === 'stream' && this._lastStreamId !== '$' ? this._lastStreamId : undefined };
2703
3409
  const packed = this.codec.encode(payload);
2704
- const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
3410
+ const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed, this._namespacePrefix + 'snapshot-v1') : packed;
2705
3411
  const dest = altPath ?? this.opts.snapshotPath;
2706
3412
  fs.mkdirSync(path.dirname(dest), { recursive: true });
2707
- fs.writeFileSync(dest, final, { mode: 0o600 });
3413
+ staging = `${dest}.${process.pid}.${crypto.randomUUID()}.tmp`;
3414
+ fs.writeFileSync(staging, final, { mode: 0o600, flag: 'wx' });
3415
+ fs.renameSync(staging, dest);
3416
+ staging = undefined;
2708
3417
  this.logger.info('Cache snapshot written', {
2709
3418
  path: dest, entries: entries.length,
2710
3419
  sizeKB: Math.round(final.length / 1024), encrypted: this.enc.isEnabled,
2711
3420
  });
3421
+ return true;
2712
3422
  } catch (err) {
2713
3423
  this.logger.warn('Cache snapshot write failed', { error: (err as Error).message });
3424
+ return false;
3425
+ } finally {
3426
+ if (staging) try { fs.unlinkSync(staging); } catch { /* staging may not exist */ }
2714
3427
  }
2715
3428
  }
2716
3429
 
@@ -2721,6 +3434,7 @@ export class CacheService {
2721
3434
  * cache.get() or cache.set() operations run, eliminating cold-start race conditions.
2722
3435
  */
2723
3436
  loadSnapshot(): void {
3437
+ if (this._strictInvalidationReadProtectionEnabled() || this._destroyed) return;
2724
3438
  const snapshotPath = this.opts.snapshotPath;
2725
3439
  try {
2726
3440
  if (!fs.existsSync(snapshotPath)) return;
@@ -2736,24 +3450,27 @@ export class CacheService {
2736
3450
  fs.unlinkSync(snapshotPath); // delete immediately — don't leave cache data on disk
2737
3451
 
2738
3452
  let buf: Buffer;
2739
- try { buf = this.enc.decryptBuffer(raw); } catch (e) {
3453
+ try { buf = this.enc.decryptBuffer(raw, this._namespacePrefix + 'snapshot-v1'); } catch (e) {
2740
3454
  this.logger.warn('Snapshot rejected: decryption failed', { error: (e as Error).message });
2741
3455
  return;
2742
3456
  }
2743
3457
 
2744
3458
  const snapshot = this.codec.decode(buf) as {
2745
- version?: number; writtenAt?: number;
3459
+ version?: number; namespace?: string; writtenAt?: number;
2746
3460
  entries?: Array<{ key: string; entry: SmartCacheEntry }>;
2747
3461
  streamId?: string;
2748
3462
  };
2749
3463
 
2750
- if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
2751
- this.logger.warn('Snapshot rejected: version mismatch', { got: snapshot?.version });
3464
+ if (!snapshot || snapshot.version !== SNAPSHOT_VERSION || snapshot.namespace !== this._namespacePrefix) {
3465
+ this.logger.warn('Snapshot rejected: version or namespace mismatch', {
3466
+ got: snapshot?.version, namespaceMatches: snapshot?.namespace === this._namespacePrefix,
3467
+ });
2752
3468
  return;
2753
3469
  }
2754
3470
 
2755
3471
  const now = Date.now();
2756
- const writtenAt = snapshot.writtenAt ?? 0;
3472
+ const writtenAt = this._snapshotWrittenAt(snapshot.writtenAt, 'Snapshot');
3473
+ if (writtenAt === null) return;
2757
3474
  const tolerance = this.opts.clockSkewToleranceMs ?? 250;
2758
3475
  if (writtenAt - now > tolerance) {
2759
3476
  this.logger.warn('Snapshot rejected: timestamp too far in future (exceeds clock skew tolerance)', {
@@ -2772,6 +3489,10 @@ export class CacheService {
2772
3489
  this.logger.warn('Snapshot rejected: entries is not an array');
2773
3490
  return;
2774
3491
  }
3492
+ if (snapshot.entries.some(item => !item || typeof item.key !== 'string' || !item.key.startsWith(this._dataPrefix))) {
3493
+ this.logger.warn('Snapshot rejected: entry outside namespace');
3494
+ return;
3495
+ }
2775
3496
 
2776
3497
  const loaded = this.l1.importEntries(snapshot.entries, this.opts.forbiddenSnapshotPrefixes);
2777
3498
  this._restoredSnapshot ||= loaded > 0;
@@ -2800,17 +3521,19 @@ export class CacheService {
2800
3521
  const entries = this.l1.exportEntries(this.opts.forbiddenSnapshotPrefixes);
2801
3522
  if (entries.length === 0) return false;
2802
3523
 
2803
- const payload = { version: SNAPSHOT_VERSION, writtenAt: Date.now(), entries,
3524
+ const payload = { version: SNAPSHOT_VERSION, namespace: this._namespacePrefix, writtenAt: Date.now(), entries,
2804
3525
  streamId: this.opts.backplaneMode === 'stream' && this._lastStreamId !== '$' ? this._lastStreamId : undefined };
2805
3526
  const packed = this.codec.encode(payload);
2806
3527
  let final: Buffer;
2807
3528
  if (this.opts.remoteSnapshot.envelope) {
2808
3529
  final = await EnvelopeEncryption.encrypt(packed, this.opts.remoteSnapshot.envelope);
2809
3530
  } else {
2810
- final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
3531
+ final = this.enc.isEnabled ? this.enc.encryptBuffer(packed, this._namespacePrefix + 'snapshot-v1') : packed;
2811
3532
  }
2812
3533
 
2813
- await this.opts.remoteSnapshot.adapter.put(final);
3534
+ if (this._destroyed) return false;
3535
+ await this.opts.remoteSnapshot.adapter.put(final, { signal: this._lifecycle.signal });
3536
+ if (this._destroyed) return false;
2814
3537
  this.counters.remoteSnapshotUploads++;
2815
3538
  this.counters.remoteSnapshotLastUploadedAt = Date.now();
2816
3539
  this.logger.info('Remote cache snapshot uploaded', {
@@ -2832,11 +3555,12 @@ export class CacheService {
2832
3555
  * Returns the number of entries successfully imported.
2833
3556
  */
2834
3557
  async loadRemoteSnapshot(): Promise<number> {
2835
- if (!this.opts.remoteSnapshot) return 0;
3558
+ if (!this.opts.remoteSnapshot || this._strictInvalidationReadProtectionEnabled() || this._destroyed) return 0;
2836
3559
  const maxAgeMs = this.opts.remoteSnapshot.maxAgeMs ?? this.opts.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE;
2837
3560
  const epoch = this._globalEpoch;
2838
3561
  try {
2839
- const raw = await this.opts.remoteSnapshot.adapter.get();
3562
+ const raw = await this.opts.remoteSnapshot.adapter.get({ signal: this._lifecycle.signal });
3563
+ if (this._destroyed) return 0;
2840
3564
  if (this._destroyed || this._globalEpoch !== epoch) return 0;
2841
3565
  if (!raw || raw.length === 0) {
2842
3566
  this.logger.debug('Remote snapshot not found or empty — starting cold');
@@ -2853,7 +3577,7 @@ export class CacheService {
2853
3577
  }
2854
3578
  buf = await EnvelopeEncryption.decrypt(rawBuf, this.opts.remoteSnapshot.envelope);
2855
3579
  } else {
2856
- buf = this.enc.decryptBuffer(rawBuf);
3580
+ buf = this.enc.decryptBuffer(rawBuf, this._namespacePrefix + 'snapshot-v1');
2857
3581
  }
2858
3582
  } catch (e) {
2859
3583
  this.counters.remoteSnapshotErrors++;
@@ -2863,19 +3587,26 @@ export class CacheService {
2863
3587
 
2864
3588
  const snapshot = this.codec.decode(buf) as {
2865
3589
  version?: number;
3590
+ namespace?: string;
2866
3591
  writtenAt?: number;
2867
3592
  entries?: Array<{ key: string; entry: SmartCacheEntry }>;
2868
3593
  streamId?: string;
2869
3594
  };
2870
3595
 
2871
- if (!snapshot || snapshot.version !== SNAPSHOT_VERSION) {
3596
+ if (!snapshot || snapshot.version !== SNAPSHOT_VERSION || snapshot.namespace !== this._namespacePrefix) {
2872
3597
  this.counters.remoteSnapshotErrors++;
2873
- this.logger.warn('Remote snapshot rejected: version mismatch', { got: snapshot?.version });
3598
+ this.logger.warn('Remote snapshot rejected: version or namespace mismatch', {
3599
+ got: snapshot?.version, namespaceMatches: snapshot?.namespace === this._namespacePrefix,
3600
+ });
2874
3601
  return 0;
2875
3602
  }
2876
3603
 
2877
3604
  const now = Date.now();
2878
- const writtenAt = snapshot.writtenAt ?? 0;
3605
+ const writtenAt = this._snapshotWrittenAt(snapshot.writtenAt, 'Remote');
3606
+ if (writtenAt === null) {
3607
+ this.counters.remoteSnapshotErrors++;
3608
+ return 0;
3609
+ }
2879
3610
  const tolerance = this.opts.clockSkewToleranceMs ?? 250;
2880
3611
  if (writtenAt - now > tolerance) {
2881
3612
  this.counters.remoteSnapshotErrors++;
@@ -2897,9 +3628,15 @@ export class CacheService {
2897
3628
  this.logger.warn('Remote snapshot rejected: entries is not an array');
2898
3629
  return 0;
2899
3630
  }
3631
+ if (snapshot.entries.some(item => !item || typeof item.key !== 'string' || !item.key.startsWith(this._dataPrefix))) {
3632
+ this.counters.remoteSnapshotErrors++;
3633
+ this.logger.warn('Remote snapshot rejected: entry outside namespace');
3634
+ return 0;
3635
+ }
2900
3636
 
2901
3637
  if (this._destroyed || this._globalEpoch !== epoch) return 0;
2902
3638
  const eligible = snapshot.entries.filter(item => item && !this._keyMutationEpochs.has(item.key));
3639
+ if (this._destroyed) return 0;
2903
3640
  const loaded = this.l1.importEntries(eligible, this.opts.forbiddenSnapshotPrefixes);
2904
3641
  this._restoredSnapshot ||= loaded > 0;
2905
3642
  if (typeof snapshot.streamId === 'string' && /^\d{1,20}-\d{1,20}$/.test(snapshot.streamId)) this._lastStreamId = snapshot.streamId;
@@ -2942,7 +3679,7 @@ export class CacheService {
2942
3679
  */
2943
3680
  async get<T>(
2944
3681
  cacheKey: string,
2945
- fetchFn: () => Promise<T>,
3682
+ fetchFn: (signal?: AbortSignal) => Promise<T>,
2946
3683
  ttlSeconds: number = 300,
2947
3684
  opts: {
2948
3685
  priority?: CachePriority;
@@ -2962,9 +3699,13 @@ export class CacheService {
2962
3699
  } = {},
2963
3700
  ): Promise<T> {
2964
3701
  this._assertActive('get');
3702
+ this._ensureCachedReadAllowed();
3703
+ const readProtectionEpoch = this._invalidationReadEpoch;
3704
+ if (ttlSeconds === 0) ttlSeconds = INDEFINITE_TTL_SECONDS;
3705
+ if (!Number.isFinite(ttlSeconds) || ttlSeconds < 0) throw new TypeError('Cache TTL must be finite and non-negative');
2965
3706
  const span = this._startSpan('tricache.get');
2966
3707
  if (this.opts.tracer) span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
2967
- const k = this.nk(cacheKey); // namespaced key used for all storage
3708
+ const k = this.nk(cacheKey); // namespaced data key used for all storage
2968
3709
  this.counters.gets++;
2969
3710
 
2970
3711
  // Normalize all opts fields to plain locals once. Every opts.XXX read
@@ -2972,6 +3713,7 @@ export class CacheService {
2972
3713
  // different option shapes: {}, { swr }, { refreshAhead }, { tags }, etc.
2973
3714
  // Reading everything here collapses all downstream accesses to fast
2974
3715
  // monomorphic local-variable reads regardless of call-site variety.
3716
+ const optDependencies = opts.dependsOn ?? this.keyDependencies.get(k)?.map(pattern => this.undk(pattern));
2975
3717
  const optSwr = opts.swr ?? 0;
2976
3718
  const optPriority = opts.priority;
2977
3719
  const optRefreshAhead = opts.refreshAhead;
@@ -2985,13 +3727,14 @@ export class CacheService {
2985
3727
  const l1Hit = this.l1.get(k);
2986
3728
  if (l1Hit !== null) {
2987
3729
  const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
3730
+ this._ensureCachedReadAllowed(readProtectionEpoch);
2988
3731
 
2989
3732
  if (isGenerationalStale) {
2990
- this._deleteIfStale(k, l1Hit.setAt ?? 0);
3733
+ this._deleteIfStale(k, l1Hit.revision);
2991
3734
  } else if (!l1Hit.isStale || optSwr > 0) {
2992
3735
  if (l1Hit.isStale) {
2993
3736
  const swrGraceMs = optSwr * 1_000;
2994
- if (swrGraceMs > 0 && !this.revalidating.has(k)) {
3737
+ if (swrGraceMs > 0 && !this.revalidating.has(k) && this.l1.getEntry(k)?.revision === l1Hit.revision) {
2995
3738
  const priority = optPriority ?? inferPriority(cacheKey);
2996
3739
  this.revalidating.add(k);
2997
3740
  void this._revalidate(
@@ -3001,6 +3744,7 @@ export class CacheService {
3001
3744
  swrGraceMs,
3002
3745
  priority,
3003
3746
  l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map(t => [t, 0])) : undefined),
3747
+ l1Hit.dependsOn,
3004
3748
  );
3005
3749
  this.counters.swrRevalidations++;
3006
3750
  this.logger.debug('SWR: serving stale, revalidating', { cacheKey });
@@ -3023,7 +3767,7 @@ export class CacheService {
3023
3767
  ? remaining <= l1Hit.delta * xb * -Math.log(Math.random())
3024
3768
  : false;
3025
3769
 
3026
- if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
3770
+ if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k) && this.l1.getEntry(k)?.revision === l1Hit.revision) {
3027
3771
  const priority = optPriority ?? inferPriority(cacheKey);
3028
3772
  this.revalidating.add(k);
3029
3773
  void this._revalidate(
@@ -3033,6 +3777,7 @@ export class CacheService {
3033
3777
  optSwr * 1_000,
3034
3778
  priority,
3035
3779
  l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map(t => [t, 0])) : undefined),
3780
+ l1Hit.dependsOn,
3036
3781
  );
3037
3782
  this.counters.swrRevalidations++;
3038
3783
  this.logger.debug(
@@ -3043,15 +3788,14 @@ export class CacheService {
3043
3788
  }
3044
3789
  }
3045
3790
  this.counters.l1Hits++;
3046
- this.opts.onHit?.(cacheKey, 'l1');
3791
+ this._notifyReadObserver(cacheKey, 'l1');
3047
3792
  if (this.opts.frozen) deepFreeze(l1Hit.value);
3048
3793
  span.setAttribute('cache.hit', true)
3049
3794
  .setAttribute('cache.item.tier', 'memory')
3050
3795
  .setAttribute('cache.hit_tier', 'l1')
3051
3796
  .end();
3052
- return (this.opts.cloneStrategy === 'structuredClone' && l1Hit.value != null && typeof l1Hit.value === 'object')
3053
- ? structuredClone(l1Hit.value) as T
3054
- : l1Hit.value as T;
3797
+ this._ensureCachedReadAllowed(readProtectionEpoch);
3798
+ return this._prepareReadValue(l1Hit.value as T, readProtectionEpoch);
3055
3799
  }
3056
3800
  }
3057
3801
 
@@ -3070,24 +3814,30 @@ export class CacheService {
3070
3814
  span.setAttribute('cache.hit', true)
3071
3815
  .setAttribute('cache.stampede_coalesced', true)
3072
3816
  .end();
3073
- return this._prepareReadValue(await existing as T);
3817
+ const value = await existing as T;
3818
+ this._ensureCachedReadAllowed(readProtectionEpoch);
3819
+ return this._prepareReadValue(value, readProtectionEpoch);
3074
3820
  }
3075
3821
 
3076
3822
  const mutationEpochAtStart = this._getKeyMutationEpoch(k);
3823
+ const finishDependencies = this._trackPendingDependencies(k, optDependencies);
3077
3824
  const executionPromise: Promise<T> = Promise.resolve().then(async () => {
3078
3825
  try {
3079
3826
  // ── Tier 1.5: disk tier (evicted L1 entries) — protected by latency watchdog ──
3080
- const diskHit = await this._readDiskEntry<T>(k, mutationEpochAtStart);
3827
+ const diskHit = await this._readDiskEntry<T>(k, mutationEpochAtStart, readProtectionEpoch);
3081
3828
  if (diskHit && (diskHit.entry.staleAt === undefined || diskHit.entry.staleAt > Date.now() || optSwr > 0)) {
3829
+ this._ensureCachedReadAllowed(readProtectionEpoch);
3082
3830
  this.counters.diskHits++;
3083
- this.opts.onHit?.(cacheKey, 'disk');
3831
+ this._notifyReadObserver(cacheKey, 'disk');
3084
3832
  span.setAttribute('cache.hit', true).setAttribute('cache.item.tier', 'disk').setAttribute('cache.hit_tier', 'disk');
3085
3833
  if (diskHit.entry.staleAt !== undefined && diskHit.entry.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
3086
3834
  this.revalidating.add(k);
3087
3835
  this.counters.swrRevalidations++;
3088
3836
  void this._revalidate(k, fetchFn, ttlMs, swrGraceMs, priority,
3089
- diskHit.entry.tagVersions ?? Object.fromEntries((diskHit.entry.tags ?? []).map(tag => [tag, 0])));
3837
+ diskHit.entry.tagVersions ?? Object.fromEntries((diskHit.entry.tags ?? []).map(tag => [tag, 0])),
3838
+ diskHit.entry.dependsOn);
3090
3839
  }
3840
+ this._ensureCachedReadAllowed(readProtectionEpoch);
3091
3841
  return diskHit.value;
3092
3842
  }
3093
3843
 
@@ -3097,6 +3847,7 @@ export class CacheService {
3097
3847
  const client = await this.getRedis();
3098
3848
  const redisStart = performance.now();
3099
3849
  const redisHit = await this._readRedisEntry<T>(client, k, true);
3850
+ this._ensureCachedReadAllowed(readProtectionEpoch);
3100
3851
  const redisElapsed = performance.now() - redisStart;
3101
3852
  this.watchdog.recordRedis(redisElapsed);
3102
3853
  this.cb.onSuccess();
@@ -3111,9 +3862,10 @@ export class CacheService {
3111
3862
  : parsed;
3112
3863
  return liveVal as T;
3113
3864
  }
3114
- if (!this._promoteRedisEntry(k, redisHit, ttlMs, priority)) throw new Error('Redis entry expired during promotion');
3865
+ if (!this._promoteRedisEntry(k, redisHit, ttlMs, priority, readProtectionEpoch)) throw new Error('Redis entry expired during promotion');
3866
+ this._ensureCachedReadAllowed(readProtectionEpoch);
3115
3867
  this.counters.l2Hits++;
3116
- this.opts.onHit?.(cacheKey, 'l2');
3868
+ this._notifyReadObserver(cacheKey, 'l2');
3117
3869
  this.logger.debug(redisHit.tagVersions ? 'L2 hit (Redis hash)' : 'L2 hit (Redis)', { cacheKey });
3118
3870
  span.setAttribute('cache.hit', true)
3119
3871
  .setAttribute('cache.item.tier', 'remote')
@@ -3121,19 +3873,21 @@ export class CacheService {
3121
3873
  if (redisHit.staleAt !== undefined && redisHit.staleAt <= Date.now() && optSwr > 0 && !this.revalidating.has(k)) {
3122
3874
  this.revalidating.add(k);
3123
3875
  this.counters.swrRevalidations++;
3124
- void this._revalidate(k, fetchFn, ttlMs, swrGraceMs, priority, redisHit.tagVersions);
3876
+ void this._revalidate(k, fetchFn, ttlMs, swrGraceMs, priority, redisHit.tagVersions, redisHit.dependsOn);
3125
3877
  }
3126
3878
  return parsed as T;
3127
3879
  }
3128
3880
  } catch (err) {
3129
- this.cb.onFailure();
3881
+ if (err instanceof CacheInvalidationUnavailableError) throw err;
3882
+ this.cb.onFailure(err);
3130
3883
  this.logger.debug('Redis unavailable, continuing to fetch', { cacheKey, error: (err as Error).message });
3131
3884
  }
3132
3885
  }
3133
3886
 
3134
3887
  // Cache MISS across all tiers: fetchFn
3888
+ this._ensureCachedReadAllowed(readProtectionEpoch);
3135
3889
  span.setAttribute('cache.hit', false).setAttribute('cache.hit_tier', 'miss');
3136
- this.opts.onMiss?.(cacheKey);
3890
+ this._notifyReadObserver(cacheKey);
3137
3891
 
3138
3892
  this.counters.fetches++;
3139
3893
  // Capture generations before origin work, never stamp an old result with
@@ -3141,10 +3895,11 @@ export class CacheService {
3141
3895
  const tagSnapshot = this.opts.tagStrategy === 'generational' && optTags?.length
3142
3896
  ? Object.fromEntries(await Promise.all(optTags.map(async tag => [tag, await this._getTagVersion(tag)])))
3143
3897
  : undefined;
3898
+ this._ensureCachedReadAllowed(readProtectionEpoch);
3144
3899
  const fetchStart = Date.now();
3145
3900
  let data: T;
3146
3901
  try {
3147
- data = await fetchFn();
3902
+ data = this._prepareWriteValue(await this._runOrigin(fetchFn));
3148
3903
  } catch (fetchErr) {
3149
3904
  span.setStatus({
3150
3905
  code: 2,
@@ -3154,6 +3909,7 @@ export class CacheService {
3154
3909
  throw fetchErr;
3155
3910
  }
3156
3911
  const delta = Date.now() - fetchStart;
3912
+ this._ensureCachedReadAllowed(readProtectionEpoch);
3157
3913
 
3158
3914
  // Negative caching: null/undefined results get their own (shorter) TTL
3159
3915
  const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1_000;
@@ -3163,11 +3919,12 @@ export class CacheService {
3163
3919
  this.latencyTracker.record(k, delta);
3164
3920
  const p95 = this.latencyTracker.p95(k);
3165
3921
  if (p95 !== null) {
3166
- const adaptedMs = Math.round(p95 * this.opts.adaptiveTtlMultiplier * 1_000);
3167
- effectiveTtl = Math.max(
3922
+ effectiveTtl = Math.min(effectiveTtl, resolveAdaptiveTtlMs(
3923
+ p95,
3924
+ this.opts.adaptiveTtlMultiplier,
3168
3925
  this.opts.adaptiveTtlMinMs,
3169
- Math.min(this.opts.adaptiveTtlMaxMs, adaptedMs),
3170
- );
3926
+ this.opts.adaptiveTtlMaxMs,
3927
+ ));
3171
3928
  }
3172
3929
  }
3173
3930
 
@@ -3175,13 +3932,8 @@ export class CacheService {
3175
3932
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
3176
3933
 
3177
3934
  const activeTagVersions = tagSnapshot;
3178
- if (optTags?.length) {
3179
- if (this.opts.tagStrategy === 'generational') {
3180
- if (await this._isGenerationalEntryStale(tagSnapshot)) return data;
3181
- } else {
3182
- await this._registerTags(k, optTags, Math.ceil(storeTtl / 1_000));
3183
- }
3184
- }
3935
+ if (optTags?.length && this.opts.tagStrategy === 'generational' && await this._isGenerationalEntryStale(tagSnapshot)) return data;
3936
+ this._ensureCachedReadAllowed(readProtectionEpoch);
3185
3937
 
3186
3938
  if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
3187
3939
  this.logger.debug('Aborting in-flight cache commit — key was mutated or deleted during fetch', { cacheKey });
@@ -3195,18 +3947,22 @@ export class CacheService {
3195
3947
  }
3196
3948
 
3197
3949
  const writeTs = Date.now();
3950
+ const revision = crypto.randomUUID();
3198
3951
  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 });
3952
+ const packed = this.codec.encode(data);
3953
+ this.l1.setPacked(k, packed, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs, optTags, optDependencies, revision);
3954
+ const admitted = this.l1.getEntry(k);
3955
+ const expiresAt = admitted?.revision === revision ? admitted.expiresAt : writeTs + storeTtl;
3956
+ this._restoreEntryMetadata(k, { tags: optTags, dependsOn: optDependencies, expiresAt });
3201
3957
 
3202
3958
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
3203
3959
  try {
3204
- await this._writeRedisEntry(k, data, writeTs + storeTtl, writeTs, activeTagVersions, staleAt, optTags, opts.dependsOn,
3205
- () => this._getKeyMutationEpoch(k) === mutationEpochAtStart);
3960
+ await this._writeRedisEntry(k, data, expiresAt, writeTs, revision, activeTagVersions, staleAt, optTags, optDependencies,
3961
+ () => this._cachedReadAllowed(readProtectionEpoch) && this._getKeyMutationEpoch(k) === mutationEpochAtStart, packed);
3206
3962
  this.cb.onSuccess();
3207
3963
  this.logger.debug('Cached L1+L2', { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
3208
- } catch {
3209
- this.cb.onFailure();
3964
+ } catch (err) {
3965
+ this.cb.onFailure(err);
3210
3966
  this.logger.debug('Cached L1 only (Redis unavailable)', { cacheKey });
3211
3967
  }
3212
3968
  } else {
@@ -3215,13 +3971,14 @@ export class CacheService {
3215
3971
 
3216
3972
  return data;
3217
3973
  } finally {
3974
+ finishDependencies();
3218
3975
  if (this.inflight.get(k) === executionPromise) this.inflight.delete(k);
3219
3976
  span.end();
3220
3977
  }
3221
3978
  });
3222
3979
 
3223
3980
  this.inflight.set(k, executionPromise);
3224
- return this._prepareReadValue(await executionPromise);
3981
+ return this._prepareReadValue(await executionPromise, readProtectionEpoch);
3225
3982
  }
3226
3983
 
3227
3984
  /**
@@ -3234,20 +3991,26 @@ export class CacheService {
3234
3991
  * @param timeoutMs Maximum time permitted for snapshot persistence before timing out. Default: 8000ms.
3235
3992
  */
3236
3993
  async flushSnapshotOnShutdown(timeoutMs = 8_000): Promise<boolean> {
3994
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0) throw new Error('Shutdown timeout must be finite and non-negative');
3995
+ const deadline = performance.now() + timeoutMs;
3996
+ let timedOut = false;
3237
3997
  const flusher = async (): Promise<boolean> => {
3238
3998
  let localOk = true;
3239
3999
  let remoteOk = true;
3240
4000
 
3241
4001
  if (!this._diskDisabled) {
3242
- try {
3243
- this.writeSnapshot();
3244
- } catch (err) {
3245
- localOk = false;
3246
- this.logger.warn('flushSnapshotOnShutdown: disk snapshot write failed', { error: (err as Error).message });
3247
- }
4002
+ localOk = await this._drainPendingDiskWork(timeoutMs);
4003
+ if (!localOk) this.logger.warn('flushSnapshotOnShutdown: disk writes did not drain before snapshot deadline');
4004
+ if (!localOk || timedOut || this._destroyed || performance.now() >= deadline) return false;
4005
+ // writeSnapshot() swallows its own error and returns a boolean; the
4006
+ // previous try/catch could never observe a failure and always reported
4007
+ // success even when the destination was unwritable.
4008
+ localOk = this.writeSnapshot();
4009
+ if (!localOk) this.logger.warn('flushSnapshotOnShutdown: disk snapshot write failed');
3248
4010
  }
3249
4011
 
3250
4012
  if (this.opts.remoteSnapshot && this.opts.remoteSnapshot.saveOnShutdown !== false) {
4013
+ if (timedOut || this._destroyed || performance.now() >= deadline) return false;
3251
4014
  try {
3252
4015
  remoteOk = await this.writeRemoteSnapshot();
3253
4016
  } catch (err) {
@@ -3265,6 +4028,7 @@ export class CacheService {
3265
4028
  flusher(),
3266
4029
  new Promise<boolean>((resolve) => {
3267
4030
  timer = setTimeout(() => {
4031
+ timedOut = true;
3268
4032
  this.logger.warn(`flushSnapshotOnShutdown timed out after ${timeoutMs}ms`);
3269
4033
  resolve(false);
3270
4034
  }, timeoutMs);
@@ -3276,6 +4040,23 @@ export class CacheService {
3276
4040
  }
3277
4041
  }
3278
4042
 
4043
+ private async _drainPendingDiskWork(timeoutMs: number): Promise<boolean> {
4044
+ if (this._diskDisabled) return true;
4045
+ const deadline = performance.now() + timeoutMs;
4046
+ while (true) {
4047
+ if (this._pendingSpillCount > 0) {
4048
+ if (performance.now() >= deadline) return false;
4049
+ await new Promise<void>(resolve => setImmediate(resolve));
4050
+ continue;
4051
+ }
4052
+ const remaining = Math.max(0, deadline - performance.now());
4053
+ if (!await this.disk.drain(remaining)) return false;
4054
+ if (this._pendingSpillCount === 0 && this.disk.backpressure.getStats().activeWrites === 0 &&
4055
+ this.disk.backpressure.getStats().pendingWrites === 0) return true;
4056
+ if (performance.now() >= deadline) return false;
4057
+ }
4058
+ }
4059
+
3279
4060
  /**
3280
4061
  * Internal graceful shutdown trigger invoked by ProcessTerminationBus.
3281
4062
  */
@@ -3303,31 +4084,38 @@ export class CacheService {
3303
4084
  * tags: ['users'],
3304
4085
  * });
3305
4086
  */
3306
- wrap<T>(cacheKey: string, fetchFn: () => Promise<T>, options?: WrapOptions): Promise<T> {
4087
+ wrap<T>(cacheKey: string, fetchFn: (signal?: AbortSignal) => Promise<T>, options?: WrapOptions): Promise<T> {
3307
4088
  const ttl = options?.ttl ?? 300;
3308
4089
  return this.get<T>(cacheKey, fetchFn, ttl, options);
3309
4090
  }
3310
4091
 
3311
4092
  private async _revalidate<T>(
3312
4093
  cacheKey: string,
3313
- fetchFn: () => Promise<T>,
4094
+ fetchFn: (signal?: AbortSignal) => Promise<T>,
3314
4095
  ttlMs: number,
3315
4096
  swrGraceMs: number,
3316
4097
  priority: CachePriority,
3317
4098
  knownTagVersions?: Record<string, number>,
4099
+ knownDependencies?: string[],
3318
4100
  ): Promise<void> {
3319
4101
  const startEpoch = this._getKeyMutationEpoch(cacheKey);
4102
+ const readProtectionEpoch = this._invalidationReadEpoch;
3320
4103
  const previous = this.l1.getEntry(cacheKey);
3321
4104
  const tags = previous?.tags ?? Object.keys(knownTagVersions ?? {});
3322
- const dependencies = previous?.dependsOn;
4105
+ const dependencies = previous?.dependsOn ?? knownDependencies;
4106
+ let finishDependencies = () => {};
4107
+ let finishBackground = () => {};
3323
4108
  try {
4109
+ this._ensureCachedReadAllowed(readProtectionEpoch);
4110
+ finishBackground = this._backgroundWork.acquire();
4111
+ finishDependencies = this._trackPendingDependencies(cacheKey, dependencies);
3324
4112
  const fetchStart = Date.now();
3325
- const data = await fetchFn();
4113
+ const data = this._prepareWriteValue(await this._runOrigin(fetchFn));
3326
4114
  const delta = Date.now() - fetchStart;
3327
4115
  const staleAt = Date.now() + ttlMs;
3328
4116
 
3329
4117
  // Invalidation fence: if the key was deleted or mutated while fetchFn was in-flight, abort commit!
3330
- if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
4118
+ if (this._destroyed || !this._cachedReadAllowed(readProtectionEpoch) || this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
3331
4119
  this.logger.debug('SWR: aborting revalidation commit — key was mutated or deleted during fetch', { cacheKey });
3332
4120
  return;
3333
4121
  }
@@ -3355,27 +4143,39 @@ export class CacheService {
3355
4143
  }
3356
4144
  }
3357
4145
 
3358
- if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
4146
+ if (this._destroyed || !this._cachedReadAllowed(readProtectionEpoch) || this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
3359
4147
  this.logger.debug('SWR: aborting revalidation commit — key was mutated or deleted during tag resolution', { cacheKey });
3360
4148
  return;
3361
4149
  }
3362
4150
 
3363
4151
  const writeTs = Date.now();
4152
+ const revision = crypto.randomUUID();
3364
4153
  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 });
4154
+ const packed = this.codec.encode(data);
4155
+ this.l1.setPacked(cacheKey, packed, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs, tags, dependencies, revision);
4156
+ const admitted = this.l1.getEntry(cacheKey);
4157
+ const expiresAt = admitted?.revision === revision ? admitted.expiresAt : writeTs + ttlMs + swrGraceMs;
4158
+ this._restoreEntryMetadata(cacheKey, { tags, dependsOn: dependencies, expiresAt });
3367
4159
 
3368
4160
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
3369
4161
  try {
3370
- await this._writeRedisEntry(cacheKey, data, writeTs + ttlMs + swrGraceMs, writeTs, activeTagVersions, staleAt, tags, dependencies,
3371
- () => this._getKeyMutationEpoch(cacheKey) === startEpoch);
4162
+ await this._writeRedisEntry(cacheKey, data, expiresAt, writeTs, revision, activeTagVersions, staleAt, tags, dependencies,
4163
+ () => this._cachedReadAllowed(readProtectionEpoch) && this._getKeyMutationEpoch(cacheKey) === startEpoch, packed);
3372
4164
  } catch { /* ok */ }
3373
4165
  }
3374
4166
  this.logger.debug('SWR: revalidation complete', { cacheKey });
3375
4167
  } catch (err) {
3376
- if (this.opts.staleIfError > 0 && this._getKeyMutationEpoch(cacheKey) === startEpoch) {
4168
+ if (!(err instanceof CacheCapacityError) && !this._destroyed && this._cachedReadAllowed(readProtectionEpoch) && previous && this.opts.staleIfError > 0 && this._getKeyMutationEpoch(cacheKey) === startEpoch) {
3377
4169
  const additionalMs = this.opts.staleIfError * 1_000;
3378
- this.l1.bumpExpiry(cacheKey, additionalMs);
4170
+ const horizon = (previous.setAt ?? 0) + (previous.ttlMs ?? 0) + additionalMs;
4171
+ if (this.l1.getEntry(cacheKey)?.revision === previous.revision && this.l1.bumpExpiry(cacheKey, additionalMs, horizon)) {
4172
+ const retained = this.l1.getEntry(cacheKey);
4173
+ if (retained?.dependsOn?.length) this._dependencyExpirations.set(cacheKey, retained.expiresAt);
4174
+ if (retained?.tags?.length) {
4175
+ this._rememberTags(cacheKey, retained.tags, retained.expiresAt);
4176
+ if (this.opts.tagStrategy === 'set') await this._registerTags(cacheKey, retained.tags, retained.expiresAt);
4177
+ }
4178
+ }
3379
4179
  this.logger.debug('SWR: revalidation failed, stale-if-error extending expiry', {
3380
4180
  cacheKey, staleIfErrorSecs: this.opts.staleIfError,
3381
4181
  });
@@ -3383,6 +4183,8 @@ export class CacheService {
3383
4183
  this.logger.debug('SWR: revalidation failed', { cacheKey, error: (err as Error).message });
3384
4184
  }
3385
4185
  } finally {
4186
+ finishDependencies();
4187
+ finishBackground();
3386
4188
  this.revalidating.delete(cacheKey);
3387
4189
  }
3388
4190
  }
@@ -3391,12 +4193,20 @@ export class CacheService {
3391
4193
 
3392
4194
  /** Explicitly write a value into L1 (+ L2 in production). */
3393
4195
  async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority, opts?: { tags?: string[]; dependsOn?: string[] }): Promise<void> {
4196
+ return this._set(cacheKey, data, ttlSeconds, priority, opts);
4197
+ }
4198
+
4199
+ private async _set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority,
4200
+ opts?: { tags?: string[]; dependsOn?: string[] }, readEpoch?: number): Promise<void> {
3394
4201
  this._assertActive('set');
4202
+ if (readEpoch !== undefined) this._ensureCachedReadAllowed(readEpoch);
4203
+ data = this._prepareWriteValue(data);
3395
4204
  const span = this._startSpan('tricache.set');
3396
4205
  if (this.opts.tracer) {
3397
4206
  span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
3398
4207
  span.setAttribute('cache.ttl', ttlSeconds);
3399
4208
  }
4209
+ let finishDependencies = () => {};
3400
4210
  try {
3401
4211
  // ttl 0 = indefinite (documented contract, used by the NestJS store): map to
3402
4212
  // a far-future expiry instead of computing expiresAt = now + 0ms, which
@@ -3408,7 +4218,7 @@ export class CacheService {
3408
4218
  const existingEntry = this.l1.getEntry(k);
3409
4219
  const requestedTags = opts?.tags ?? existingEntry?.tags ?? this.keyTags.get(k)?.tags;
3410
4220
  const requestedDependencies = opts?.dependsOn ?? existingEntry?.dependsOn;
3411
- this._bumpKeyMutation(k);
4221
+ finishDependencies = this._trackPendingDependencies(k, requestedDependencies, true);
3412
4222
  const epoch = this._getKeyMutationEpoch(k);
3413
4223
  this.inflight.delete(k);
3414
4224
  this._invalidateDiskKey(k);
@@ -3419,34 +4229,35 @@ export class CacheService {
3419
4229
  ? (this.opts.hierarchicalTags ? expandHierarchicalTags(requestedTags, this.opts.tagHierarchyDelimiter) : requestedTags)
3420
4230
  : undefined;
3421
4231
 
3422
- if (tagsToRegister?.length) {
3423
- if (this.opts.tagStrategy === 'generational') {
3424
- const vers = await Promise.all(tagsToRegister.map(tag => this._getTagVersion(tag)));
3425
- activeTagVersions = {};
3426
- for (let i = 0; i < tagsToRegister.length; i++) {
3427
- activeTagVersions[tagsToRegister[i]] = vers[i];
3428
- }
3429
- } else {
3430
- await this._registerTags(k, tagsToRegister, effectiveTtlSeconds);
4232
+ if (tagsToRegister?.length && this.opts.tagStrategy === 'generational') {
4233
+ const vers = await Promise.all(tagsToRegister.map(tag => this._getTagVersion(tag)));
4234
+ activeTagVersions = {};
4235
+ for (let i = 0; i < tagsToRegister.length; i++) {
4236
+ activeTagVersions[tagsToRegister[i]] = vers[i];
3431
4237
  }
3432
4238
  }
3433
4239
 
4240
+ if (readEpoch !== undefined) this._ensureCachedReadAllowed(readEpoch);
3434
4241
  if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return;
3435
4242
  const writeTs = Date.now();
3436
- this.l1.set(k, data, ttlMs, p, undefined, undefined, activeTagVersions, writeTs, tagsToRegister, requestedDependencies);
3437
- this._rememberTags(k, tagsToRegister ?? [], writeTs + ttlMs);
4243
+ const revision = crypto.randomUUID();
4244
+ const packed = this.codec.encode(data);
4245
+ this.l1.setPacked(k, packed, data, ttlMs, p, undefined, undefined, activeTagVersions, writeTs, tagsToRegister, requestedDependencies, revision);
4246
+ const admitted = this.l1.getEntry(k);
4247
+ const expiresAt = admitted?.revision === revision ? admitted.expiresAt : writeTs + ttlMs;
4248
+ this._rememberTags(k, tagsToRegister ?? [], expiresAt);
3438
4249
 
3439
4250
  // Register dependency patterns: when any key matching a pattern is deleted,
3440
4251
  // this key (k) is automatically cascaded.
3441
- this._registerDependencies(k, requestedDependencies);
4252
+ this._registerDependencies(k, requestedDependencies, expiresAt);
3442
4253
 
3443
4254
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
3444
4255
  try {
3445
- await this._writeRedisEntry(k, data, writeTs + ttlMs, writeTs, activeTagVersions, undefined, tagsToRegister, requestedDependencies,
3446
- () => this._getKeyMutationEpoch(k) === epoch);
4256
+ await this._writeRedisEntry(k, data, expiresAt, writeTs, revision, activeTagVersions, undefined, tagsToRegister, requestedDependencies,
4257
+ () => (readEpoch === undefined || this._cachedReadAllowed(readEpoch)) && this._getKeyMutationEpoch(k) === epoch, packed);
3447
4258
  this.cb.onSuccess();
3448
4259
  } catch (err) {
3449
- this.cb.onFailure();
4260
+ this.cb.onFailure(err);
3450
4261
  this.logger.debug('set: Redis unavailable', { cacheKey, error: (err as Error).message });
3451
4262
  }
3452
4263
  }
@@ -3461,31 +4272,33 @@ export class CacheService {
3461
4272
  span.recordException?.(err);
3462
4273
  throw err;
3463
4274
  } finally {
4275
+ finishDependencies();
3464
4276
  span.end();
3465
4277
  }
3466
4278
  }
3467
4279
 
3468
4280
  /**
3469
- * Register tags for a cache key in the in-process index and (if Redis is enabled) in
3470
- * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
4281
+ * Retain remote discovery through the entry's hard deadline plus cleanup grace.
4282
+ * Each atomic registration initializes new sets and only extends expiring sets;
4283
+ * existing persistent sets retain their unknown member lifetimes. Local metadata
4284
+ * is maintained at admission/retention changes. Redis failure remains best effort.
3471
4285
  */
3472
- private async _registerTags(k: string, tags: string[], ttlSeconds: number): Promise<void> {
3473
- const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
3474
- const expiresAt = Date.now() + effectiveTtl * 1_000;
4286
+ private async _registerTags(k: string, tags: string[], expiresAt: number): Promise<void> {
4287
+ const deadline = Math.ceil(expiresAt) + TAG_REGISTRY_GRACE_MS;
4288
+ if (!Number.isSafeInteger(deadline) || deadline <= 0) return;
3475
4289
  const uniqueTags = Array.from(new Set(tags));
3476
- this._rememberTags(k, uniqueTags, expiresAt);
3477
4290
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
3478
4291
  try {
3479
4292
  const client = await this.getRedis();
3480
- const pl = client.pipeline();
3481
- for (const tag of uniqueTags) {
3482
- const tagKey = this.nk(`_tag_:${tag}`);
3483
- pl.sadd(tagKey, k);
3484
- pl.expire(tagKey, effectiveTtl + 3_600);
3485
- }
3486
- await pl.exec();
4293
+ const results = await Promise.allSettled(uniqueTags.map(tag =>
4294
+ client.eval(LUA_REGISTER_TAG, 1, this.tagIndexKey(tag), k, String(deadline))));
4295
+ const failed = results.find(result => result.status === 'rejected');
4296
+ if (failed?.status === 'rejected') throw failed.reason;
3487
4297
  this.cb.onSuccess();
3488
- } catch { this.cb.onFailure(); /* tags are best-effort */ }
4298
+ } catch (err) {
4299
+ this.cb.onFailure(err);
4300
+ this.logger.debug('Tag registry registration failed', { error: (err as Error).message });
4301
+ }
3489
4302
  }
3490
4303
  }
3491
4304
 
@@ -3500,12 +4313,16 @@ export class CacheService {
3500
4313
  this._assertActive('delete');
3501
4314
  const span = this._startSpan('tricache.delete');
3502
4315
  if (this.opts.tracer) span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
4316
+ let finishInvalidation = () => {};
4317
+ let cascade: DependencyCascade | undefined;
3503
4318
  try {
3504
4319
  const isPattern = cacheKey.includes('*');
3505
4320
  const k = this.nk(cacheKey);
4321
+ finishInvalidation = this._beginRedisInvalidation(k, isPattern);
3506
4322
  this.counters.deletes++;
3507
4323
 
3508
4324
  if (isPattern) {
4325
+ cascade = this._cascadeDependenciesForPattern(k);
3509
4326
  this._fenceInvalidation();
3510
4327
  const pfx = k.endsWith('*') ? k.slice(0, -1) : k;
3511
4328
  for (const liveKey of this.l1.liveKeys()) {
@@ -3529,15 +4346,15 @@ export class CacheService {
3529
4346
  if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
3530
4347
  }
3531
4348
  } else {
4349
+ // Resolve the graph before L1 eviction callbacks remove dependency edges.
4350
+ cascade = this._cascadeDependencies(k);
3532
4351
  this._bumpKeyMutation(k);
3533
4352
  this.inflight.delete(k);
3534
4353
  this.l1.delete(k);
3535
4354
  this._invalidateDiskKey(k);
3536
4355
  this._removeKeyTags(k);
3537
- // Cascade: invalidate any key that declared it depends on this exact key's pattern
3538
- this._cascadeDependencies(k);
3539
- // Clean up: remove k from all dependency registrations (it is gone)
3540
4356
  this._removeKeyDependencies(k);
4357
+ this._l1Counters.delete(k);
3541
4358
  }
3542
4359
 
3543
4360
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
@@ -3545,9 +4362,11 @@ export class CacheService {
3545
4362
  const client = await this.getRedis();
3546
4363
  if (isPattern) {
3547
4364
  const keys = await this._scanKeys(client, k);
3548
- await this._deleteRedisKeys(client, keys);
4365
+ await this._deleteRedisKeys(client, [...new Set([...keys, ...(cascade?.keys ?? [])])]);
3549
4366
  } else {
3550
- if (this.opts.autoPipeline && this.pipeliner) {
4367
+ if (cascade?.keys.length) {
4368
+ await this._deleteRedisKeys(client, [k, ...cascade.keys]);
4369
+ } else if (this.opts.autoPipeline && this.pipeliner) {
3551
4370
  await this.pipeliner.del(k);
3552
4371
  } else {
3553
4372
  await client.del(k);
@@ -3555,21 +4374,23 @@ export class CacheService {
3555
4374
  }
3556
4375
  this.cb.onSuccess();
3557
4376
  } catch (err) {
3558
- this.cb.onFailure();
4377
+ this.cb.onFailure(err);
3559
4378
  this.logger.debug('delete: Redis unavailable', { cacheKey, error: (err as Error).message });
3560
4379
  }
3561
4380
  }
3562
4381
 
3563
- if (this.opts.awaitInvalidationBackplane) {
3564
- await this.publishInvalidation(isPattern ? 'del-glob' : 'del', k, undefined, false, true);
3565
- } else {
3566
- void this.publishInvalidation(isPattern ? 'del-glob' : 'del', k, undefined, false, true);
3567
- }
4382
+ const publication = isPattern
4383
+ ? this._publishPatternAndKeyInvalidations(k, cascade?.keys ?? [])
4384
+ : this._publishKeyInvalidations([k, ...(cascade?.keys ?? [])]);
4385
+ if (this.opts.awaitInvalidationBackplane) await publication;
4386
+ else void publication;
3568
4387
  } catch (err) {
3569
4388
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
3570
4389
  span.recordException?.(err);
3571
4390
  throw err;
3572
4391
  } finally {
4392
+ cascade?.finish();
4393
+ finishInvalidation();
3573
4394
  span.end();
3574
4395
  }
3575
4396
  }
@@ -3579,8 +4400,12 @@ export class CacheService {
3579
4400
  /**
3580
4401
  * Distributed counter.
3581
4402
  *
3582
- * When Redis is active, atomically increments the key via `INCR` and returns
3583
- * the new (fleet-wide) value. On a Redis error it increments `counters.errors`
4403
+ * When Redis is active, one single-key script increments and applies missing
4404
+ * expiry, returning the new fleet-wide value. A positive TTL starts a fixed
4405
+ * window only when no expiry exists; subsequent increments do not extend it.
4406
+ * Omitted/zero TTL creates a permanent counter and preserves existing expiry.
4407
+ * Positive fractional seconds round up to milliseconds. Invalid TTLs reject
4408
+ * before mutation. On a Redis error it increments `counters.errors`
3584
4409
  * and, by default, fails OPEN — returning `0` so a caller's
3585
4410
  * `if (count > LIMIT) reject()` guard does NOT reject during an outage. Set
3586
4411
  * `failClosed: true` to re-throw the error instead, enforcing the limit even
@@ -3594,6 +4419,11 @@ export class CacheService {
3594
4419
  */
3595
4420
  async increment(cacheKey: string, ttlSeconds?: number): Promise<number> {
3596
4421
  this._assertActive('increment');
4422
+ const ttlMs = ttlSeconds === undefined ? 0 : Math.ceil(ttlSeconds * 1_000);
4423
+ if ((ttlSeconds !== undefined && (!Number.isFinite(ttlSeconds) || ttlSeconds < 0)) ||
4424
+ !Number.isSafeInteger(ttlMs) || !Number.isSafeInteger(Date.now() + ttlMs)) {
4425
+ throw new RangeError('Counter TTL must be finite, non-negative, and fit an integer-millisecond deadline');
4426
+ }
3597
4427
  const k = this.nk(cacheKey);
3598
4428
 
3599
4429
  if (this._redisDisabled || this.opts.l2WriteMode === 'read-only') {
@@ -3605,9 +4435,10 @@ export class CacheService {
3605
4435
  );
3606
4436
  }
3607
4437
  const now = Date.now();
3608
- const ttlMs = (ttlSeconds ?? DEFAULT_COUNTER_TTL_SECONDS) * 1_000;
3609
4438
  const entry = this._l1Counters.get(k);
3610
4439
  if (entry && entry.expiresAt > now) {
4440
+ if (!Number.isSafeInteger(entry.value + 1)) throw new RangeError('Counter value exceeds the safe integer range');
4441
+ if (ttlMs > 0 && entry.expiresAt === Infinity) entry.expiresAt = now + ttlMs;
3611
4442
  entry.value++;
3612
4443
  return entry.value;
3613
4444
  }
@@ -3620,18 +4451,21 @@ export class CacheService {
3620
4451
  if (oldest !== undefined) this._l1Counters.delete(oldest);
3621
4452
  }
3622
4453
  }
3623
- this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
4454
+ this._l1Counters.set(k, { value: 1, expiresAt: ttlMs > 0 ? now + ttlMs : Infinity });
3624
4455
  return 1;
3625
4456
  }
3626
4457
 
3627
4458
  try {
3628
4459
  const client = await this.getRedis();
3629
- const count = await client.incr(k);
3630
- if (count === 1 && ttlSeconds) await client.expire(k, ttlSeconds);
4460
+ const result = await client.eval(LUA_INCREMENT_COUNTER, 1, k, String(ttlMs));
4461
+ const count = typeof result === 'number' ? result
4462
+ : typeof result === 'string' && result.trim() !== '' ? Number(result) : NaN;
4463
+ if (!Number.isSafeInteger(count)) throw new Error('Invalid Redis counter result: expected a safe integer');
4464
+ this.cb.onSuccess();
3631
4465
  return count;
3632
4466
  } catch (err) {
3633
4467
  this.counters.counterErrors++;
3634
- this.cb.onFailure();
4468
+ this.cb.onFailure(err);
3635
4469
  this.logger.error('increment: Redis error', { cacheKey }, err as Error);
3636
4470
  if (this.opts.failClosed) throw err;
3637
4471
  return 0;
@@ -3651,13 +4485,17 @@ export class CacheService {
3651
4485
  this._assertActive('clear');
3652
4486
  const span = this._startSpan('tricache.clear');
3653
4487
  if (this.opts.tracer) span.setAttribute('cache.prefix', prefix || '*');
4488
+ let finishInvalidation = () => {};
4489
+ let cascade: DependencyCascade | undefined;
3654
4490
  try {
3655
4491
  this.counters.deletes++;
3656
4492
  const k = prefix
3657
4493
  ? this.nk(prefix.includes('*') ? prefix : `${prefix}*`)
3658
4494
  : undefined;
4495
+ finishInvalidation = this._beginRedisInvalidation(k ?? this.nk('*'), true);
3659
4496
 
3660
4497
  if (k) {
4498
+ cascade = this._cascadeDependenciesForPattern(k);
3661
4499
  this._fenceInvalidation();
3662
4500
  const pfx = k.endsWith('*') ? k.slice(0, -1) : k;
3663
4501
  for (const liveKey of this.l1.liveKeys()) {
@@ -3684,8 +4522,7 @@ export class CacheService {
3684
4522
  this.tagIndex.clear();
3685
4523
  this.keyTags.clear();
3686
4524
  this.tagVersions.clear();
3687
- this.dependencyIndex.clear();
3688
- this.keyDependencies.clear();
4525
+ this._clearDependencyMetadata();
3689
4526
  this._pendingDiskDeletes.clear();
3690
4527
  this._keyMutationEpochs.clear();
3691
4528
  }
@@ -3693,28 +4530,24 @@ export class CacheService {
3693
4530
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
3694
4531
  try {
3695
4532
  const client = await this.getRedis();
3696
- const pattern = k ?? (this._namespace ? `${this._namespace}:*` : '*');
4533
+ const pattern = k ?? `${this._dataPrefix}*`;
3697
4534
  const keys = await this._scanKeys(client, pattern);
3698
- await this._deleteRedisKeys(client, keys);
4535
+ await this._deleteRedisKeys(client, [...new Set([...keys, ...(cascade?.keys ?? [])])]);
3699
4536
  } catch (err) {
3700
4537
  this.logger.debug('clear: Redis unavailable', { error: (err as Error).message });
3701
4538
  }
3702
4539
  }
3703
4540
 
3704
- if (this.opts.awaitInvalidationBackplane) {
3705
- await this.publishInvalidation('del-glob',
3706
- k ?? (this._namespace ? `${this._namespace}:*` : '*'),
3707
- undefined, false, true);
3708
- } else {
3709
- void this.publishInvalidation('del-glob',
3710
- k ?? (this._namespace ? `${this._namespace}:*` : '*'),
3711
- undefined, false, true);
3712
- }
4541
+ const publication = this._publishPatternAndKeyInvalidations(k ?? `${this._dataPrefix}*`, cascade?.keys ?? []);
4542
+ if (this.opts.awaitInvalidationBackplane) await publication;
4543
+ else void publication;
3713
4544
  } catch (err) {
3714
4545
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
3715
4546
  span.recordException?.(err);
3716
4547
  throw err;
3717
4548
  } finally {
4549
+ cascade?.finish();
4550
+ finishInvalidation();
3718
4551
  span.end();
3719
4552
  }
3720
4553
  }
@@ -3736,7 +4569,9 @@ export class CacheService {
3736
4569
  */
3737
4570
  ttl(cacheKey: string): number | null {
3738
4571
  this._assertActive('ttl');
3739
- return this.l1.ttl(this.nk(cacheKey));
4572
+ this._ensureCachedReadAllowed();
4573
+ const key = this.nk(cacheKey);
4574
+ return this._isLocallyInvalidated(this.l1.getEntry(key)) ? null : this.l1.ttl(key);
3740
4575
  }
3741
4576
 
3742
4577
  /**
@@ -3745,7 +4580,9 @@ export class CacheService {
3745
4580
  */
3746
4581
  has(cacheKey: string): boolean {
3747
4582
  this._assertActive('has');
3748
- return this.l1.has(this.nk(cacheKey));
4583
+ this._ensureCachedReadAllowed();
4584
+ const key = this.nk(cacheKey);
4585
+ return !this._isLocallyInvalidated(this.l1.getEntry(key)) && this.l1.has(key);
3749
4586
  }
3750
4587
 
3751
4588
  // ── Iteration ─────────────────────────────────────────────────────────────
@@ -3758,11 +4595,17 @@ export class CacheService {
3758
4595
  */
3759
4596
  *keys(): Generator<string> {
3760
4597
  this._assertActive('keys');
3761
- const prefix = this._namespace ? this._namespace + ':' : '';
4598
+ this._ensureCachedReadAllowed();
4599
+ const readEpoch = this._invalidationReadEpoch;
4600
+ const prefix = this._dataPrefix;
3762
4601
  for (const key of this.l1.liveKeys()) {
3763
- if (prefix && !key.startsWith(prefix)) continue;
3764
- yield prefix ? key.slice(prefix.length) : key;
4602
+ if (!key.startsWith(prefix)) continue;
4603
+ if (this._isLocallyInvalidated(this.l1.getEntry(key))) continue;
4604
+ this._ensureCachedReadAllowed(readEpoch);
4605
+ yield key.slice(prefix.length);
4606
+ this._ensureCachedReadAllowed(readEpoch);
3765
4607
  }
4608
+ this._ensureCachedReadAllowed(readEpoch);
3766
4609
  }
3767
4610
 
3768
4611
  /**
@@ -3774,15 +4617,16 @@ export class CacheService {
3774
4617
  */
3775
4618
  *values<T = unknown>(): Generator<T> {
3776
4619
  this._assertActive('values');
3777
- const prefix = this._namespace ? this._namespace + ':' : '';
3778
- if (!prefix) {
3779
- yield* this.l1.liveValues() as Generator<T>;
3780
- } else {
3781
- for (const [key, entry] of this.l1.liveEntries()) {
3782
- if (!key.startsWith(prefix)) continue;
3783
- yield this.l1.resolveValue(entry) as T;
3784
- }
4620
+ this._ensureCachedReadAllowed();
4621
+ const readEpoch = this._invalidationReadEpoch;
4622
+ const prefix = this._dataPrefix;
4623
+ for (const [key, entry] of this.l1.liveEntries()) {
4624
+ if (!key.startsWith(prefix)) continue;
4625
+ if (this._isLocallyInvalidated(entry)) continue;
4626
+ yield this._prepareReadValue(this.l1.resolveValue(entry) as T, readEpoch);
4627
+ this._ensureCachedReadAllowed(readEpoch);
3785
4628
  }
4629
+ this._ensureCachedReadAllowed(readEpoch);
3786
4630
  }
3787
4631
 
3788
4632
  /**
@@ -3794,11 +4638,16 @@ export class CacheService {
3794
4638
  */
3795
4639
  *entries<T = unknown>(): Generator<[string, T]> {
3796
4640
  this._assertActive('entries');
3797
- const prefix = this._namespace ? this._namespace + ':' : '';
4641
+ this._ensureCachedReadAllowed();
4642
+ const readEpoch = this._invalidationReadEpoch;
4643
+ const prefix = this._dataPrefix;
3798
4644
  for (const [key, entry] of this.l1.liveEntries()) {
3799
- if (prefix && !key.startsWith(prefix)) continue;
3800
- yield [prefix ? key.slice(prefix.length) : key, this.l1.resolveValue(entry) as T];
4645
+ if (!key.startsWith(prefix)) continue;
4646
+ if (this._isLocallyInvalidated(entry)) continue;
4647
+ yield [key.slice(prefix.length), this._prepareReadValue(this.l1.resolveValue(entry) as T, readEpoch)];
4648
+ this._ensureCachedReadAllowed(readEpoch);
3801
4649
  }
4650
+ this._ensureCachedReadAllowed(readEpoch);
3802
4651
  }
3803
4652
 
3804
4653
  /**
@@ -3823,10 +4672,15 @@ export class CacheService {
3823
4672
  */
3824
4673
  scan<T = unknown>(fn: (rawKey: string, value: T, offset: number) => void): void {
3825
4674
  this._assertActive('scan');
3826
- const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
4675
+ this._ensureCachedReadAllowed();
4676
+ const readEpoch = this._invalidationReadEpoch;
4677
+ const prefixLen = this._dataPrefix.length;
3827
4678
  this.l1.scan((key, entry, pfx) => {
3828
- fn(key, this._prepareReadValue(this.l1.resolveValue(entry) as T), pfx);
4679
+ if (this._isLocallyInvalidated(entry)) return;
4680
+ fn(key, this._prepareReadValue(this.l1.resolveValue(entry) as T, readEpoch), pfx);
4681
+ this._ensureCachedReadAllowed(readEpoch);
3829
4682
  }, prefixLen);
4683
+ this._ensureCachedReadAllowed(readEpoch);
3830
4684
  }
3831
4685
 
3832
4686
  /**
@@ -3837,26 +4691,44 @@ export class CacheService {
3837
4691
  */
3838
4692
  async touch(cacheKey: string, newTtlSeconds: number): Promise<boolean> {
3839
4693
  this._assertActive('touch');
4694
+ this._ensureCachedReadAllowed();
4695
+ const readEpoch = this._invalidationReadEpoch;
3840
4696
  if (!Number.isFinite(newTtlSeconds) || newTtlSeconds <= 0) throw new Error('touch TTL must be finite and positive');
3841
4697
  const k = this.nk(cacheKey);
4698
+ if (this._isLocallyInvalidated(this.l1.getEntry(k))) return false;
3842
4699
  const epoch = this._getKeyMutationEpoch(k);
3843
4700
  const hit = this.l1.touch(k, newTtlSeconds * 1_000);
3844
4701
  const entry = this.l1.getEntry(k);
3845
- if (hit) {
3846
- const kt = this.keyTags.get(k);
3847
- if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1_000;
4702
+ const expiresAt = entry?.expiresAt;
4703
+ if (hit && entry?.tags?.length) {
4704
+ this._rememberTags(k, entry.tags, expiresAt!);
4705
+ if (this.opts.tagStrategy === 'set') await this._registerTags(k, entry.tags, expiresAt!);
3848
4706
  }
4707
+ if (hit && entry?.dependsOn?.length) this._dependencyExpirations.set(k, expiresAt!);
3849
4708
  if (hit && !this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
3850
4709
  try {
3851
4710
  const client = await this.getRedis();
3852
- if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return hit;
4711
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return this._prepareReadValue(hit, readEpoch);
3853
4712
  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)));
4713
+ let replacement = '';
4714
+ if (this.enc.isEnabled && (this.enc.mode === 'aes-256-gcm' || this.enc.mode === 'aes-128-gcm') && typeof client.hgetall === 'function') {
4715
+ let hash: Record<string, string> | undefined;
4716
+ try { hash = await client.hgetall(k); }
4717
+ catch (error) { if (!(error instanceof Error) || !error.message.includes('WRONGTYPE')) throw error; }
4718
+ if (hash?.d) {
4719
+ if (hash.r !== entry.revision) return this._prepareReadValue(hit, readEpoch);
4720
+ const value = await this._decryptAndDeserialize(hash.d, this._redisContext(k, hash));
4721
+ hash.e = String(expiresAt);
4722
+ replacement = await this._serializeAndEncrypt(PREFIX_MSGPACK + this.codec.encode(value).toString('base64'), this._redisContext(k, hash));
4723
+ }
4724
+ }
4725
+ if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return this._prepareReadValue(hit, readEpoch);
4726
+ await client.eval(LUA_TOUCH_CACHE_ENTRY, 1, k, entry.revision ?? '', String(expiresAt), String(Math.ceil(newTtlSeconds * 1000)), replacement);
3855
4727
  } else await client.expire(k, Math.ceil(newTtlSeconds));
3856
4728
  this.cb.onSuccess();
3857
4729
  } catch { /* ok */ }
3858
4730
  }
3859
- return hit;
4731
+ return this._prepareReadValue(hit, readEpoch);
3860
4732
  }
3861
4733
 
3862
4734
  /**
@@ -3867,8 +4739,15 @@ export class CacheService {
3867
4739
  * const fresh = cache.getIfFresh('user:123');
3868
4740
  * if (fresh !== null) return fresh; // serve from L1, no network hop
3869
4741
  */
4742
+ private _isLocallyInvalidated(entry: SmartCacheEntry | undefined): boolean {
4743
+ return Boolean(entry?.tagVersions && Object.entries(entry.tagVersions).some(([tag, version]) =>
4744
+ (this.tagVersions.get(tag)?.version ?? 0) > version));
4745
+ }
4746
+
3870
4747
  getIfFresh<T = unknown>(cacheKey: string): T | null {
3871
4748
  this._assertActive('getIfFresh');
4749
+ this._ensureCachedReadAllowed();
4750
+ const readEpoch = this._invalidationReadEpoch;
3872
4751
  const k = this.nk(cacheKey);
3873
4752
  const entry = this.l1.getEntry(k);
3874
4753
  if (!entry) return null;
@@ -3876,26 +4755,35 @@ export class CacheService {
3876
4755
  if (entry.expiresAt <= now) return null; // expired
3877
4756
  if (entry.staleAt !== undefined && entry.staleAt < now) return null; // in SWR grace
3878
4757
  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);
4758
+ return this._prepareReadValue((entry.value !== undefined ? entry.value : this.codec.decode(entry.data)) as T, readEpoch);
4759
+ }
4760
+
4761
+ private _prepareWriteValue<T>(value: T): T {
4762
+ return this.opts.cloneStrategy === 'structuredClone' && value !== null && typeof value === 'object'
4763
+ ? structuredClone(value) : value;
3880
4764
  }
3881
4765
 
3882
- private _prepareReadValue<T>(val: T): T {
4766
+ private _prepareReadValue<T>(val: T, readEpoch?: number): T {
3883
4767
  if (this.opts.frozen) deepFreeze(val);
3884
- return (this.opts.cloneStrategy === 'structuredClone' && val != null && typeof val === 'object')
4768
+ const result = (this.opts.cloneStrategy === 'structuredClone' && val != null && typeof val === 'object')
3885
4769
  ? structuredClone(val)
3886
4770
  : val;
4771
+ this._ensureCachedReadAllowed(readEpoch);
4772
+ return result;
3887
4773
  }
3888
4774
 
3889
4775
  /**
3890
- * Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
4776
+ * Origin-free read across L1, optional disk, and Redis without invoking a fetcher.
3891
4777
  * Returns the cached value if found and valid, or `null` if absent / expired.
3892
- * Does not write dummy entries on misses or trigger side-effects.
4778
+ * Promotes hits and updates metrics/access policy; it can perform stale cleanup.
3893
4779
  *
3894
4780
  * @example
3895
4781
  * const val = await cache.peek<User>('user:123');
3896
4782
  */
3897
4783
  async peek<T = unknown>(cacheKey: string): Promise<T | null> {
3898
4784
  this._assertActive('peek');
4785
+ this._ensureCachedReadAllowed();
4786
+ const readProtectionEpoch = this._invalidationReadEpoch;
3899
4787
  const k = this.nk(cacheKey);
3900
4788
  const epoch = this._getKeyMutationEpoch(k);
3901
4789
  this.counters.gets++;
@@ -3904,18 +4792,20 @@ export class CacheService {
3904
4792
  const l1Hit = this.l1.get(k);
3905
4793
  if (l1Hit !== null) {
3906
4794
  if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
3907
- this._deleteIfStale(k, l1Hit.setAt ?? 0);
4795
+ this._deleteIfStale(k, l1Hit.revision);
3908
4796
  } else {
4797
+ this._ensureCachedReadAllowed(readProtectionEpoch);
3909
4798
  this.counters.l1Hits++;
3910
- return this._prepareReadValue(l1Hit.value as T);
4799
+ return this._prepareReadValue(l1Hit.value as T, readProtectionEpoch);
3911
4800
  }
3912
4801
  }
3913
4802
 
3914
4803
  // 2. L1.5 Disk
3915
- const diskHit = await this._readDiskEntry<T>(k, epoch);
4804
+ const diskHit = await this._readDiskEntry<T>(k, epoch, readProtectionEpoch);
3916
4805
  if (diskHit) {
4806
+ this._ensureCachedReadAllowed(readProtectionEpoch);
3917
4807
  this.counters.diskHits++;
3918
- return this._prepareReadValue(diskHit.value);
4808
+ return this._prepareReadValue(diskHit.value, readProtectionEpoch);
3919
4809
  }
3920
4810
 
3921
4811
  // 3. L2 Redis
@@ -3924,22 +4814,26 @@ export class CacheService {
3924
4814
  const client = await this.getRedis();
3925
4815
  const redisStart = performance.now();
3926
4816
  const redisHit = await this._readRedisEntry<T>(client, k);
4817
+ this._ensureCachedReadAllowed(readProtectionEpoch);
3927
4818
  const redisElapsed = performance.now() - redisStart;
3928
4819
  this.watchdog.recordRedis(redisElapsed);
3929
4820
  this.cb.onSuccess();
3930
4821
  if (redisHit && !redisHit.stale) {
3931
4822
  const parsed = redisHit.value;
3932
4823
  if (this._destroyed || this._getKeyMutationEpoch(k) !== epoch) return null;
3933
- if (!this._promoteRedisEntry(k, redisHit, 60_000, inferPriority(cacheKey))) return null;
4824
+ if (!this._promoteRedisEntry(k, redisHit, 60_000, inferPriority(cacheKey), readProtectionEpoch)) return null;
4825
+ this._ensureCachedReadAllowed(readProtectionEpoch);
3934
4826
  this.counters.l2Hits++;
3935
- return this._prepareReadValue(parsed as T);
4827
+ return this._prepareReadValue(parsed as T, readProtectionEpoch);
3936
4828
  }
3937
4829
  } catch (err) {
3938
- this.cb.onFailure();
4830
+ if (err instanceof CacheInvalidationUnavailableError) throw err;
4831
+ this.cb.onFailure(err);
3939
4832
  this.logger.debug('peek: Redis read failed', { cacheKey, error: (err as Error).message });
3940
4833
  }
3941
4834
  }
3942
4835
 
4836
+ this._ensureCachedReadAllowed(readProtectionEpoch);
3943
4837
  return null;
3944
4838
  }
3945
4839
 
@@ -3954,14 +4848,17 @@ export class CacheService {
3954
4848
  */
3955
4849
  async mget<T>(
3956
4850
  keys: string[],
3957
- fetchFn?: (missKeys: string[]) => Promise<Record<string, T> | Map<string, T>>,
4851
+ fetchFn?: (missKeys: string[], signal?: AbortSignal) => Promise<Record<string, T> | Map<string, T>>,
3958
4852
  ttl: number | ((key: string) => number) = 300,
3959
4853
  priority?: CachePriority,
3960
4854
  ): Promise<(T | undefined)[]> {
3961
4855
  this._assertActive('mget');
4856
+ this._ensureCachedReadAllowed();
4857
+ const readProtectionEpoch = this._invalidationReadEpoch;
3962
4858
  this.counters.gets += keys.length;
3963
4859
  const epochs = new Map(keys.map(key => [this.nk(key), this._getKeyMutationEpoch(this.nk(key))]));
3964
4860
  const span = this._startSpan('tricache.mget');
4861
+ const finishDependencies: Array<() => void> = [];
3965
4862
  if (this.opts.tracer) {
3966
4863
  span.setAttribute('cache.batch.size', keys.length);
3967
4864
  }
@@ -3969,6 +4866,7 @@ export class CacheService {
3969
4866
  const result: (T | undefined)[] = Array.from({ length: keys.length });
3970
4867
  const missIndexes: number[] = [];
3971
4868
  const missKeys: string[] = [];
4869
+ const refillMetadata = new Map<string, { tags?: string[]; dependsOn?: string[] }>();
3972
4870
 
3973
4871
  // ── Tier 1: L1 (in-memory) ──
3974
4872
  const now = Date.now();
@@ -3977,12 +4875,22 @@ export class CacheService {
3977
4875
  const entry = this.l1.getEntry(k);
3978
4876
  if (entry && entry.expiresAt > now && (entry.staleAt === undefined || entry.staleAt > now)) {
3979
4877
  if (await this._isGenerationalEntryStale(entry.tagVersions)) {
3980
- this._deleteIfStale(k, entry.setAt ?? 0);
4878
+ const tags = entry.tags ?? (entry.tagVersions ? Object.keys(entry.tagVersions) : this.keyTags.get(k)?.tags);
4879
+ const dependsOn = entry.dependsOn ?? this.keyDependencies.get(k)?.map(pattern => this.undk(pattern));
4880
+ if (tags?.length || dependsOn?.length) {
4881
+ refillMetadata.set(keys[i], {
4882
+ ...(tags?.length && { tags: [...tags] }),
4883
+ ...(dependsOn?.length && { dependsOn: [...dependsOn] }),
4884
+ });
4885
+ finishDependencies.push(this._trackPendingDependencies(k, dependsOn));
4886
+ }
4887
+ this._deleteIfStale(k, entry.revision);
3981
4888
  missIndexes.push(i);
3982
4889
  missKeys.push(keys[i]);
3983
4890
  } else {
4891
+ this.l1.recordAccess(k, entry);
3984
4892
  const val = (entry.value !== undefined ? entry.value : this.codec.decode(entry.data)) as T;
3985
- result[i] = this._prepareReadValue(val);
4893
+ result[i] = this._prepareReadValue(val, readProtectionEpoch);
3986
4894
  this.counters.l1Hits++;
3987
4895
  }
3988
4896
  } else {
@@ -3998,6 +4906,7 @@ export class CacheService {
3998
4906
  span.setAttribute('cache.l1_hits', keys.length);
3999
4907
  span.setAttribute('cache.l2_hits', 0);
4000
4908
  }
4909
+ this._ensureCachedReadAllowed(readProtectionEpoch);
4001
4910
  return result;
4002
4911
  }
4003
4912
 
@@ -4008,6 +4917,7 @@ export class CacheService {
4008
4917
  const client = await this.getRedis();
4009
4918
  const nsKeys = missKeys.map(k => this.nk(k));
4010
4919
  const remoteEntries = await this._readRedisBatch<T>(client, nsKeys);
4920
+ this._ensureCachedReadAllowed(readProtectionEpoch);
4011
4921
 
4012
4922
  for (let j = 0; j < missKeys.length; j++) {
4013
4923
  const idx = missIndexes[j];
@@ -4017,10 +4927,10 @@ export class CacheService {
4017
4927
  !this._destroyed && this._getKeyMutationEpoch(k) === epochs.get(k)) {
4018
4928
  const p = priority ?? inferPriority(missKeys[j]);
4019
4929
  const ttlVal = typeof ttl === 'function' ? ttl(missKeys[j]) : ttl;
4020
- if (!this._promoteRedisEntry(k, entry, this._jitterTtl(ttlVal * 1_000), p)) continue;
4930
+ if (!this._promoteRedisEntry(k, entry, this._jitterTtl(ttlVal * 1_000), p, readProtectionEpoch)) continue;
4021
4931
  this.counters.l2Hits++;
4022
4932
  l2HitCount++;
4023
- result[idx] = this._prepareReadValue(entry.value as T);
4933
+ result[idx] = this._prepareReadValue(entry.value as T, readProtectionEpoch);
4024
4934
  missIndexes[j] = -1;
4025
4935
  missKeys[j] = '';
4026
4936
  }
@@ -4032,7 +4942,8 @@ export class CacheService {
4032
4942
  missIndexes.push(...remainingIdx);
4033
4943
  missKeys.push(...remainingKeys);
4034
4944
  } catch (err) {
4035
- this.cb.onFailure();
4945
+ if (err instanceof CacheInvalidationUnavailableError) throw err;
4946
+ this.cb.onFailure(err);
4036
4947
  this.logger.debug('mget: Redis unavailable, continuing to disk/fetch', { error: (err as Error).message });
4037
4948
  }
4038
4949
  }
@@ -4041,10 +4952,10 @@ export class CacheService {
4041
4952
  if (!this._diskDisabled && missKeys.length > 0) {
4042
4953
  for (let j = missKeys.length - 1; j >= 0; j--) {
4043
4954
  const k = this.nk(missKeys[j]);
4044
- const diskHit = await this._readDiskEntry<T>(k, epochs.get(k)!);
4955
+ const diskHit = await this._readDiskEntry<T>(k, epochs.get(k)!, readProtectionEpoch);
4045
4956
  if (diskHit && (diskHit.entry.staleAt === undefined || diskHit.entry.staleAt > Date.now())) {
4046
4957
  this.counters.diskHits++;
4047
- result[missIndexes[j]] = this._prepareReadValue(diskHit.value);
4958
+ result[missIndexes[j]] = this._prepareReadValue(diskHit.value, readProtectionEpoch);
4048
4959
  missIndexes.splice(j, 1);
4049
4960
  missKeys.splice(j, 1);
4050
4961
  }
@@ -4052,6 +4963,7 @@ export class CacheService {
4052
4963
  }
4053
4964
 
4054
4965
  // ── Tier 3: fetchFn for whatever still missed ──
4966
+ this._ensureCachedReadAllowed(readProtectionEpoch);
4055
4967
  if (missKeys.length > 0 && fetchFn) {
4056
4968
  const owned = new Map<string, { promise: Promise<unknown>; resolve(value: T | undefined): void; reject(error: unknown): void }>();
4057
4969
  const waiting: Promise<void>[] = [];
@@ -4069,19 +4981,25 @@ export class CacheService {
4069
4981
  this.counters.stampedes++;
4070
4982
  }
4071
4983
  const index = missIndexes[j];
4072
- waiting.push(promise.then(value => { result[index] = this._prepareReadValue(value as T | undefined); }));
4984
+ waiting.push(promise.then(value => { result[index] = this._prepareReadValue(value as T | undefined, readProtectionEpoch); }));
4073
4985
  }
4074
4986
  // Observe coalesced failures immediately while the originating batch is still running.
4075
4987
  const settled = Promise.allSettled(waiting);
4076
4988
  try {
4077
4989
  if (owned.size > 0) {
4078
4990
  this.counters.fetches++;
4079
- const fetched = await fetchFn([...owned.keys()]);
4991
+ const fetched = await this._runOrigin(signal => signal
4992
+ ? fetchFn([...owned.keys()], signal)
4993
+ : fetchFn([...owned.keys()]), owned.size);
4994
+ this._ensureCachedReadAllowed(readProtectionEpoch);
4080
4995
  await Promise.all([...owned].map(async ([key, entry]) => {
4081
4996
  const value = fetched instanceof Map ? fetched.get(key) : Object.hasOwn(fetched, key) ? fetched[key] : undefined;
4082
4997
  if (!this._destroyed && this._getKeyMutationEpoch(this.nk(key)) === epochs.get(this.nk(key))) {
4083
4998
  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);
4999
+ if (value !== undefined || this.opts.notFoundTtl > 0) {
5000
+ await this._set(key, value === undefined && this.opts.notFoundTtl > 0 ? null : value, resolvedTtl, priority,
5001
+ refillMetadata.get(key), readProtectionEpoch);
5002
+ }
4085
5003
  }
4086
5004
  entry.resolve(value);
4087
5005
  }));
@@ -4108,12 +5026,14 @@ export class CacheService {
4108
5026
  span.setAttribute('cache.l2_hits', l2HitCount);
4109
5027
  }
4110
5028
 
5029
+ this._ensureCachedReadAllowed(readProtectionEpoch);
4111
5030
  return result;
4112
5031
  } catch (err) {
4113
5032
  span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
4114
5033
  span.recordException?.(err);
4115
5034
  throw err;
4116
5035
  } finally {
5036
+ for (const finish of finishDependencies) finish();
4117
5037
  span.end();
4118
5038
  }
4119
5039
  }
@@ -4205,16 +5125,16 @@ export class CacheService {
4205
5125
  */
4206
5126
  async warmFromL2(pattern: string, opts?: { priority?: CachePriority }): Promise<number> {
4207
5127
  this._assertActive('warmFromL2');
5128
+ this._ensureCachedReadAllowed();
5129
+ const readEpoch = this._invalidationReadEpoch;
4208
5130
  if (this._redisDisabled) return 0;
4209
5131
  try {
4210
5132
  const client = await this.getRedis();
4211
5133
  const nsPattern = this.nk(pattern);
4212
5134
 
4213
5135
  // Collect all matching keys via SCAN (handles single-node and Cluster)
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
- });
5136
+ const matchedKeys = (await this._scanKeys(client, nsPattern)).filter(key => key.startsWith(this._dataPrefix));
5137
+ this._ensureCachedReadAllowed(readEpoch);
4218
5138
 
4219
5139
  if (matchedKeys.length === 0) {
4220
5140
  this.cb.onSuccess();
@@ -4224,19 +5144,23 @@ export class CacheService {
4224
5144
  // Fetch values in a pipeline and load into L1
4225
5145
  const epochs = new Map(matchedKeys.map(key => [key, this._getKeyMutationEpoch(key)]));
4226
5146
  const results = await this._readRedisBatch<unknown>(client, matchedKeys);
5147
+ this._ensureCachedReadAllowed(readEpoch);
4227
5148
  let loaded = 0;
4228
5149
  for (const key of matchedKeys) {
4229
5150
  const entry = results.get(key);
4230
5151
  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++;
5152
+ if (this._promoteRedisEntry(key, entry, 10 * 60 * 1000, opts?.priority ?? inferPriority(this.undk(key)), readEpoch) && this.l1.has(key)) loaded++;
4232
5153
  }
4233
5154
 
4234
5155
  this.logger.info('warmFromL2 complete', {
4235
5156
  pattern, matched: matchedKeys.length, loaded,
4236
5157
  });
5158
+ this._ensureCachedReadAllowed(readEpoch);
4237
5159
  return loaded;
4238
5160
  } catch (err) {
4239
- this.cb.onFailure();
5161
+ if (err instanceof CacheInvalidationUnavailableError) throw err;
5162
+ this._ensureCachedReadAllowed(readEpoch);
5163
+ this.cb.onFailure(err);
4240
5164
  this.logger.debug('warmFromL2: Redis unavailable', { error: (err as Error).message });
4241
5165
  return 0;
4242
5166
  }
@@ -4264,7 +5188,7 @@ export class CacheService {
4264
5188
  }
4265
5189
 
4266
5190
  // 1. Scan in-process tagIndex (set strategy)
4267
- const tagPrefix = this.nk('_tag_:');
5191
+ const tagPrefix = this.tagIndexPrefix();
4268
5192
  for (const tagKey of this.tagIndex.keys()) {
4269
5193
  const t = tagKey.startsWith(tagPrefix) ? tagKey.slice(tagPrefix.length) : tagKey;
4270
5194
  if (tagMatches(t)) matched.add(t);
@@ -4290,20 +5214,20 @@ export class CacheService {
4290
5214
  const client = await this.getRedis();
4291
5215
  if (this.opts.tagStrategy === 'generational') {
4292
5216
  const redisPattern = isPattern
4293
- ? this.nk(`tag_ver:${tag}`)
4294
- : this.nk(`tag_ver:${tag}${delim}*`);
5217
+ ? this.tagVersionKey(tag)
5218
+ : `${this.tagVersionKey(tag)}${delim}*`;
4295
5219
  const scannedKeys = await this._scanKeys(client, redisPattern);
4296
- const pfx = this.nk('tag_ver:');
5220
+ const pfx = this.tagVersionPrefix();
4297
5221
  for (const sk of scannedKeys) {
4298
5222
  const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
4299
5223
  if (tagMatches(t)) matched.add(t);
4300
5224
  }
4301
5225
  } else {
4302
5226
  const redisPattern = isPattern
4303
- ? this.nk(`_tag_:${tag}`)
4304
- : this.nk(`_tag_:${tag}${delim}*`);
5227
+ ? this.tagIndexKey(tag)
5228
+ : `${this.tagIndexKey(tag)}${delim}*`;
4305
5229
  const scannedKeys = await this._scanKeys(client, redisPattern);
4306
- const pfx = this.nk('_tag_:');
5230
+ const pfx = this.tagIndexPrefix();
4307
5231
  for (const sk of scannedKeys) {
4308
5232
  const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
4309
5233
  if (tagMatches(t)) matched.add(t);
@@ -4351,7 +5275,7 @@ export class CacheService {
4351
5275
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
4352
5276
  try {
4353
5277
  const client = await this.getRedis();
4354
- newVer = await client.incr(this.nk(`tag_ver:${tag}`));
5278
+ newVer = await client.incr(this.tagVersionKey(tag));
4355
5279
  } catch (err) {
4356
5280
  this.logger.debug('invalidateTag: Redis unavailable', { tag, error: (err as Error).message });
4357
5281
  const current = this.tagVersions.get(tag)?.version ?? 0;
@@ -4366,7 +5290,7 @@ export class CacheService {
4366
5290
  return;
4367
5291
  }
4368
5292
 
4369
- const tagKey = this.nk(`_tag_:${tag}`);
5293
+ const tagKey = this.tagIndexKey(tag);
4370
5294
  const members = new Set(this.tagIndex.get(tagKey) ?? []);
4371
5295
 
4372
5296
  this.tagIndex.delete(tagKey);
@@ -4406,7 +5330,7 @@ export class CacheService {
4406
5330
  try {
4407
5331
  const client = await this.getRedis();
4408
5332
  const pl = client.pipeline();
4409
- for (const tag of tags) pl.incr(this.nk(`tag_ver:${tag}`));
5333
+ for (const tag of tags) pl.incr(this.tagVersionKey(tag));
4410
5334
  const results = await pl.exec() as Array<[Error | null, number]>;
4411
5335
  for (let i = 0; i < tags.length; i++) {
4412
5336
  const [err, newVer] = results[i] ?? [null, null];
@@ -4431,7 +5355,7 @@ export class CacheService {
4431
5355
  const tagKeys: string[] = [];
4432
5356
  const allMembers = new Set<string>();
4433
5357
  for (const tag of tags) {
4434
- const tagKey = this.nk(`_tag_:${tag}`);
5358
+ const tagKey = this.tagIndexKey(tag);
4435
5359
  tagKeys.push(tagKey);
4436
5360
  const members = this.tagIndex.get(tagKey) ?? new Set<string>();
4437
5361
  for (const k of members) allMembers.add(k);
@@ -4600,12 +5524,23 @@ export class CacheService {
4600
5524
  // L2: PING command
4601
5525
  let l2: number | null = null;
4602
5526
  if (!this._redisDisabled) {
5527
+ let client: AnyRedisClient;
5528
+ try {
5529
+ client = await this.getRedis();
5530
+ } catch {
5531
+ // Admission rejection is not a failed Redis command. In particular it
5532
+ // must not release another caller's half-open probe reservation.
5533
+ return { l1, disk, l2: null };
5534
+ }
4603
5535
  try {
4604
- const client = await this.getRedis();
4605
5536
  const t2 = Date.now();
4606
5537
  await client.ping();
5538
+ this.cb.onSuccess();
4607
5539
  l2 = Date.now() - t2;
4608
- } catch { l2 = null; }
5540
+ } catch {
5541
+ this.cb.onFailure();
5542
+ l2 = null;
5543
+ }
4609
5544
  }
4610
5545
 
4611
5546
  return { l1, disk, l2 };
@@ -4633,6 +5568,7 @@ export class CacheService {
4633
5568
  * ─────────────────────────────────────────────────────────────────────────────
4634
5569
  */
4635
5570
  health(): CacheHealthStatus {
5571
+ this._checkBackplaneDeadline();
4636
5572
  const watchdogTel = this.watchdog.getTelemetry();
4637
5573
  const diskPruning = !this._diskDisabled && this.disk.isPruning;
4638
5574
  const diskLowSpace = !this._diskDisabled && this.disk.hostVolumeLowSpace;
@@ -4661,6 +5597,14 @@ export class CacheService {
4661
5597
  circuitBreakerState: this.cb.currentState,
4662
5598
  diskPruningActive: diskPruning,
4663
5599
  diskHostVolumeLowSpace: diskLowSpace,
5600
+ invalidationReadProtection: {
5601
+ enabled: this._strictInvalidationReadProtectionEnabled(),
5602
+ active: this._strictInvalidationReadProtectionEnabled() && !this._backplaneAvailable,
5603
+ reason: this._strictInvalidationReadProtectionEnabled() && !this._backplaneAvailable ? this._backplaneUnavailableReason : undefined,
5604
+ since: this._strictInvalidationReadProtectionEnabled() && !this._backplaneAvailable ? this._backplaneUnavailableSince : null,
5605
+ durationMs: this._strictInvalidationReadProtectionEnabled() && !this._backplaneAvailable ? Math.max(0, performance.now() - this._backplaneStateSince) : 0,
5606
+ deadlineMs: this._strictInvalidationReadProtectionEnabled() ? this.opts.backplaneMaxStalenessMs : undefined,
5607
+ },
4664
5608
  watchdog: watchdogTel,
4665
5609
  },
4666
5610
  };
@@ -4681,6 +5625,8 @@ export class CacheService {
4681
5625
  */
4682
5626
  async drainToL2(): Promise<number> {
4683
5627
  this._assertActive('drainToL2');
5628
+ this._ensureCachedReadAllowed();
5629
+ const readEpoch = this._invalidationReadEpoch;
4684
5630
  if (this._redisDisabled || this.opts.l2WriteMode === 'read-only') return 0;
4685
5631
  try {
4686
5632
  const entries = this.l1.exportEntries([]);
@@ -4689,12 +5635,15 @@ export class CacheService {
4689
5635
  await Promise.all(entries.map(async ({ key, entry }) => {
4690
5636
  const epoch = this._getKeyMutationEpoch(key);
4691
5637
  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);
5638
+ await this._writeRedisEntry(key, this.l1.resolveValue(entry), entry.expiresAt, entry.setAt ?? Date.now(), entry.revision ?? crypto.randomUUID(),
5639
+ entry.tagVersions, entry.staleAt, entry.tags, entry.dependsOn, () => this._cachedReadAllowed(readEpoch) && this._getKeyMutationEpoch(key) === epoch);
4694
5640
  written++;
4695
5641
  }));
5642
+ this._ensureCachedReadAllowed(readEpoch);
4696
5643
  return written;
4697
5644
  } catch (err) {
5645
+ if (err instanceof CacheInvalidationUnavailableError) throw err;
5646
+ this._ensureCachedReadAllowed(readEpoch);
4698
5647
  this.logger.debug('drainToL2: Redis unavailable', { error: (err as Error).message });
4699
5648
  return 0;
4700
5649
  }
@@ -4725,33 +5674,35 @@ export class CacheService {
4725
5674
  */
4726
5675
  async setIfAbsent<T>(cacheKey: string, value: T, ttlSeconds = 300, priority?: CachePriority): Promise<boolean> {
4727
5676
  this._assertActive('setIfAbsent');
5677
+ value = this._prepareWriteValue(value);
4728
5678
  const k = this.nk(cacheKey);
4729
5679
 
4730
5680
  // Fast path: L1 check (process-local, no network hop)
4731
5681
  if (this.l1.has(k)) return false;
5682
+ const packed = this.codec.encode(value);
4732
5683
 
4733
5684
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
4734
5685
  try {
4735
5686
  const client = await this.getRedis();
4736
- const serialized = JSON.stringify(value);
4737
- const toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
5687
+ const toStore = await this._serializeAndEncrypt(PREFIX_MSGPACK + packed.toString('base64'), this._redisContext(k));
4738
5688
  // SET key value EX ttl NX — atomic; returns 'OK' on success, null if key exists
4739
5689
  const result = await client.set(k, toStore, 'EX', ttlSeconds, 'NX');
4740
5690
  this.cb.onSuccess();
4741
5691
  if (result === null) return false; // already exists in Redis
4742
5692
  } catch (err) {
4743
- this.cb.onFailure();
5693
+ this.cb.onFailure(err);
4744
5694
  this.logger.debug('setIfAbsent: Redis unavailable, falling back to L1 check', { cacheKey, error: (err as Error).message });
4745
5695
  // Re-check L1 after Redis failure — another thread may have won the race
4746
5696
  if (this.l1.has(k)) return false;
4747
5697
  }
4748
5698
  }
4749
5699
 
5700
+ if (this._destroyed) return false;
4750
5701
  const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
4751
5702
  const p = priority ?? inferPriority(cacheKey);
4752
5703
  this._bumpKeyMutation(k);
4753
5704
  this._invalidateDiskKey(k);
4754
- this.l1.set(k, value, ttlMs, p);
5705
+ this.l1.setPacked(k, packed, value, ttlMs, p);
4755
5706
  this.counters.sets++;
4756
5707
  return true;
4757
5708
  }
@@ -4780,7 +5731,7 @@ export class CacheService {
4780
5731
  const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5_000);
4781
5732
  const retryInterval = Math.max(10, options?.retryInterval ?? 100);
4782
5733
 
4783
- const lockKey = this.nk(`lock:${resourceKey}`);
5734
+ const lockKey = this.lockKey(resourceKey);
4784
5735
  const token = crypto.randomUUID();
4785
5736
  const deadline = Date.now() + acquireTimeout;
4786
5737
 
@@ -4889,6 +5840,7 @@ export class CacheService {
4889
5840
  this._otelMetrics.sets = meter.createCounter('tricache.sets.total', { description: 'Total set operations' });
4890
5841
  this._otelMetrics.deletes = meter.createCounter('tricache.deletes.total', { description: 'Total delete operations' });
4891
5842
  this._otelMetrics.swrRevalidations = meter.createCounter('tricache.swr.revalidations', { description: 'SWR background revalidations' });
5843
+ this._otelMetrics.invalidationReadRejections = meter.createCounter('tricache.invalidation.read.rejections', { description: 'Reads rejected by invalidation protection' });
4892
5844
 
4893
5845
  const gL1Entries = meter.createObservableGauge('tricache.l1.entries', { description: 'Current L1 entry count' });
4894
5846
  const gL1Bytes = meter.createObservableGauge('tricache.l1.bytes', { description: 'Current L1 memory usage in bytes' });
@@ -4937,7 +5889,7 @@ export class CacheService {
4937
5889
  * console.log(key, hits, (sizeBytes / 1024).toFixed(1) + ' KB'));
4938
5890
  */
4939
5891
  hotKeys(n = 10): Array<{ key: string; hits: number; sizeBytes: number }> {
4940
- const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
5892
+ const prefixLen = this._dataPrefix.length;
4941
5893
  return this.l1.hotKeys(n).map(({ key, hits, sizeBytes }) => ({
4942
5894
  key: prefixLen > 0 ? key.slice(prefixLen) : key,
4943
5895
  hits,
@@ -4959,25 +5911,121 @@ export class CacheService {
4959
5911
  /**
4960
5912
  * When an exact key `deletedKey` is removed, cascade to every dependent key
4961
5913
  * that was registered via `dependsOn` and whose source pattern matches.
4962
- * Transitive dependencies are traversed with cycle protection via a visited Set.
5914
+ * Collect the complete closure before mutating indices, including current pending
5915
+ * writers. Fence all affected work synchronously; callers release Redis read
5916
+ * fences only after remote deletion has settled.
4963
5917
  */
4964
- private _cascadeDependencies(deletedKey: string, visited: Set<string> = new Set()): void {
4965
- if (visited.has(deletedKey)) return;
4966
- visited.add(deletedKey);
4967
-
4968
- for (const [pattern, dependents] of this.dependencyIndex) {
4969
- if (!this._matchesGlob(deletedKey, pattern)) continue;
4970
- for (const dep of dependents) {
4971
- if (visited.has(dep)) continue;
4972
- this.l1.delete(dep);
4973
- if (!this._diskDisabled) this.disk.delete(dep);
4974
- void this.publishInvalidation('del', dep, undefined, false, true);
4975
- this.logger.debug('Dependency cascade: invalidated dependent key', {
4976
- trigger: deletedKey.slice(0, 60), dependent: dep.slice(0, 60),
4977
- });
4978
- this._cascadeDependencies(dep, visited);
5918
+ private _cascadeDependencies(deletedKey: string): DependencyCascade {
5919
+ return this._cascadeDependencyClosure(deletedKey, pattern => this._matchesGlob(deletedKey, pattern), deletedKey);
5920
+ }
5921
+
5922
+ private _cascadeDependenciesForPattern(deletedPattern: string): DependencyCascade {
5923
+ return this._cascadeDependencyClosure(deletedPattern, pattern => this._globPatternsIntersect(deletedPattern, pattern));
5924
+ }
5925
+
5926
+ private _cascadeDependencyClosure(trigger: string, matchesInitialPattern: (dependencyPattern: string) => boolean,
5927
+ skipInitialKey?: string): DependencyCascade {
5928
+ const graph = new Map<string, Set<string>>();
5929
+ for (const [pattern, dependents] of this.dependencyIndex) graph.set(pattern, new Set(dependents));
5930
+ for (const registration of this._pendingDependencies) {
5931
+ if (this._getKeyMutationEpoch(registration.key) !== registration.epoch) continue;
5932
+ for (const pattern of registration.patterns) {
5933
+ const dependents = graph.get(pattern) ?? new Set<string>();
5934
+ dependents.add(registration.key);
5935
+ graph.set(pattern, dependents);
5936
+ }
5937
+ }
5938
+
5939
+ const visited = new Set(skipInitialKey ? [skipInitialKey] : []);
5940
+ const queue = [trigger];
5941
+ for (let i = 0; i < queue.length; i++) {
5942
+ for (const [pattern, dependents] of graph) {
5943
+ if (i === 0 ? !matchesInitialPattern(pattern) : !this._matchesGlob(queue[i], pattern)) continue;
5944
+ for (const dependent of dependents) {
5945
+ if (visited.has(dependent)) continue;
5946
+ visited.add(dependent);
5947
+ queue.push(dependent);
5948
+ }
4979
5949
  }
4980
5950
  }
5951
+
5952
+ const keys = queue.slice(1);
5953
+ const finishers = keys.map(key => this._beginRedisInvalidation(key, false));
5954
+ for (const key of keys) {
5955
+ this._bumpKeyMutation(key);
5956
+ this.inflight.delete(key);
5957
+ this._invalidateDiskKey(key);
5958
+ this.l1.delete(key);
5959
+ this._removeKeyTags(key);
5960
+ this._removeKeyDependencies(key);
5961
+ this.logger.debug('Dependency cascade: invalidated dependent key', {
5962
+ trigger: trigger.slice(0, 60), dependent: key.slice(0, 60),
5963
+ });
5964
+ }
5965
+ return { keys, finish: () => { for (const finish of finishers) finish(); } };
5966
+ }
5967
+
5968
+ /** Whether two `*`-only globs can match at least one common string. */
5969
+ private _globPatternsIntersect(left: string, right: string): boolean {
5970
+ const pending: Array<[number, number]> = [[0, 0]];
5971
+ const seen = new Set<string>();
5972
+ while (pending.length > 0) {
5973
+ const [i, j] = pending.pop()!;
5974
+ const state = `${i}:${j}`;
5975
+ if (seen.has(state)) continue;
5976
+ seen.add(state);
5977
+ if (i === left.length && j === right.length) return true;
5978
+ const leftToken = left[i], rightToken = right[j];
5979
+ if (leftToken === '*') pending.push([i + 1, j]);
5980
+ if (rightToken === '*') pending.push([i, j + 1]);
5981
+ const tokensOverlap = leftToken !== undefined && rightToken !== undefined && (
5982
+ leftToken === '*' ? rightToken === '*' || !isGlobLineTerminator(rightToken)
5983
+ : rightToken === '*' ? !isGlobLineTerminator(leftToken) : leftToken === rightToken);
5984
+ if (tokensOverlap) pending.push([leftToken === '*' ? i : i + 1, rightToken === '*' ? j : j + 1]);
5985
+ }
5986
+ return false;
5987
+ }
5988
+
5989
+ private async _publishPatternAndKeyInvalidations(pattern: string, dependentKeys: string[]): Promise<void> {
5990
+ const results = await Promise.allSettled([
5991
+ this.publishInvalidation('del-glob', pattern, undefined, false, true),
5992
+ ...dependentKeys.filter(key => !this._matchesGlob(key, pattern))
5993
+ .map(key => this.publishInvalidation('del', key, undefined, false, true)),
5994
+ ]);
5995
+ const failed = results.find(result => result.status === 'rejected');
5996
+ if (failed?.status === 'rejected') throw failed.reason;
5997
+ }
5998
+
5999
+ /** Attempt every publication even when an awaited transport rejects one key. */
6000
+ private async _publishKeyInvalidations(keys: string[], isCrossRegionRelay = false): Promise<void> {
6001
+ const results = await Promise.allSettled(keys.map(key =>
6002
+ this.publishInvalidation('del', key, undefined, isCrossRegionRelay, true)));
6003
+ const failed = results.find(result => result.status === 'rejected');
6004
+ if (failed?.status === 'rejected') throw failed.reason;
6005
+ }
6006
+
6007
+ /** A peer's 'del' can accompany a set: remove dependent Redis values, never the source. */
6008
+ private _completeBackplaneCascade(cascade: DependencyCascade | undefined): void {
6009
+ if (!cascade?.keys.length) return;
6010
+ const complete = async () => {
6011
+ try {
6012
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
6013
+ try {
6014
+ await this._deleteRedisKeys(await this.getRedis(), cascade.keys);
6015
+ this.cb.onSuccess();
6016
+ } catch (error) {
6017
+ this.cb.onFailure(error);
6018
+ this.logger.warn('Dependency cascade: Redis deletion failed', { error: (error as Error).message });
6019
+ }
6020
+ }
6021
+ await this._publishKeyInvalidations(cascade.keys);
6022
+ } finally {
6023
+ cascade.finish();
6024
+ }
6025
+ };
6026
+ void complete().catch(error => {
6027
+ this.logger.warn('Dependency cascade: publication failed', { error: (error as Error).message });
6028
+ });
4981
6029
  }
4982
6030
 
4983
6031
 
@@ -4985,6 +6033,7 @@ export class CacheService {
4985
6033
 
4986
6034
  /** Return a full metrics snapshot. */
4987
6035
  metrics(): CacheMetrics {
6036
+ this._checkBackplaneDeadline();
4988
6037
  const c = this.counters;
4989
6038
  const l1s = this.l1.getStats();
4990
6039
  const div = (n: number, d: number) => (d > 0 ? n / d : 0);
@@ -4992,6 +6041,11 @@ export class CacheService {
4992
6041
  return {
4993
6042
  namespace: this.opts.namespace,
4994
6043
  uptimeMs: Date.now() - c.startedAt,
6044
+ work: {
6045
+ origin: this._originWork.metrics(),
6046
+ background: this._backgroundWork.metrics(),
6047
+ },
6048
+ ...(this._originCapacityLimiter && { originCapacity: this._originCapacityLimiter.metrics() }),
4995
6049
 
4996
6050
  gets: {
4997
6051
  total: c.gets,
@@ -5012,12 +6066,13 @@ export class CacheService {
5012
6066
  counters: {
5013
6067
  errors: c.counterErrors,
5014
6068
  singletonDivergences: c.singletonDivergences,
6069
+ invalidationReadRejections: c.invalidationReadRejections,
5015
6070
  },
5016
6071
 
5017
6072
  bloom: {
5018
6073
  checksTotal: l1s.bloom.checks,
5019
6074
  falsePositives: l1s.bloom.falsePositives,
5020
- falsePositiveRate: div(l1s.bloom.falsePositives, l1s.bloom.checks),
6075
+ falsePositiveRate: div(l1s.bloom.falsePositives, l1s.bloom.absentChecks),
5021
6076
  },
5022
6077
 
5023
6078
  compression: {
@@ -5029,6 +6084,15 @@ export class CacheService {
5029
6084
  backplane: {
5030
6085
  enabled: this.opts.invalidationBackplane && !this._redisDisabled,
5031
6086
  mode: this.opts.backplaneMode,
6087
+ readProtectionEnabled: this._strictInvalidationReadProtectionEnabled(),
6088
+ readProtectionActive: this._strictInvalidationReadProtectionEnabled() && !this._backplaneAvailable,
6089
+ readProtectionReason: this._strictInvalidationReadProtectionEnabled() && !this._backplaneAvailable
6090
+ ? this._backplaneUnavailableReason : undefined,
6091
+ readProtectionSince: this._strictInvalidationReadProtectionEnabled() && !this._backplaneAvailable
6092
+ ? this._backplaneUnavailableSince : null,
6093
+ readProtectionDurationMs: this._strictInvalidationReadProtectionEnabled() && !this._backplaneAvailable
6094
+ ? Math.max(0, performance.now() - this._backplaneStateSince) : 0,
6095
+ readProtectionDeadlineMs: this._strictInvalidationReadProtectionEnabled() ? this.opts.backplaneMaxStalenessMs : undefined,
5032
6096
  sent: c.invSent,
5033
6097
  received: c.invReceived,
5034
6098
  skipped: c.invSkipped,
@@ -5082,7 +6146,7 @@ export class CacheService {
5082
6146
  enabled: true as const,
5083
6147
  trackedKeys: this.latencyTracker.trackedKeys,
5084
6148
  slowestKeys: this.latencyTracker.snapshot(
5085
- this._namespace ? this._namespace.length + 1 : 0, // strip "namespace:" prefix
6149
+ this._dataPrefix.length,
5086
6150
  this.opts.adaptiveTtlMultiplier,
5087
6151
  this.opts.adaptiveTtlMinMs,
5088
6152
  this.opts.adaptiveTtlMaxMs,
@@ -5108,9 +6172,12 @@ export class CacheService {
5108
6172
  * @param prefix - Metric name prefix. Default: `"tricache"`
5109
6173
  */
5110
6174
  static toPrometheusText(m: CacheMetrics, prefix = 'tricache', instanceName?: string): string {
6175
+ if (!/^[a-zA-Z_:][a-zA-Z0-9_:]*$/.test(prefix)) {
6176
+ throw new TypeError(`Invalid Prometheus metric prefix '${prefix}': must match [a-zA-Z_:][a-zA-Z0-9_:]*`);
6177
+ }
5111
6178
  const parts: string[] = [];
5112
- if (m.namespace) parts.push(`namespace="${m.namespace}"`);
5113
- if (instanceName) parts.push(`instance="${instanceName}"`);
6179
+ if (m.namespace) parts.push(`namespace="${escapePrometheusLabel(m.namespace)}"`);
6180
+ if (instanceName) parts.push(`instance="${escapePrometheusLabel(instanceName)}"`);
5114
6181
  const lbl = parts.length ? `{${parts.join(',')}}` : '';
5115
6182
  const lines: string[] = [];
5116
6183
 
@@ -5135,6 +6202,15 @@ export class CacheService {
5135
6202
  counter('deletes', m.deletes.total, 'Total delete() calls');
5136
6203
  counter('swr_revalidations', m.revalidations.total, 'Stale-While-Revalidate background refreshes');
5137
6204
 
6205
+ if (m.work) {
6206
+ gauge('origin_work_active', m.work.origin.active, 'Per-cache active physical origin work reservations');
6207
+ gauge('origin_work_capacity', m.work.origin.capacity, 'Per-cache origin work admission capacity');
6208
+ counter('origin_work_rejected', m.work.origin.rejected, 'Per-cache origin work admission rejections');
6209
+ gauge('background_work_active', m.work.background.active, 'Per-cache active background refresh reservations');
6210
+ gauge('background_work_capacity', m.work.background.capacity, 'Per-cache background refresh admission capacity');
6211
+ counter('background_work_rejected', m.work.background.rejected, 'Per-cache background refresh admission rejections');
6212
+ }
6213
+
5138
6214
  gauge('l1_hit_rate', m.gets.l1HitRate, 'Fraction of gets served from L1 RAM (0-1)');
5139
6215
  gauge('disk_hit_rate', m.gets.diskHitRate, 'Fraction of gets served from disk (0-1)');
5140
6216
  gauge('l2_hit_rate', m.gets.l2HitRate, 'Fraction of gets served from Redis (0-1)');
@@ -5143,6 +6219,11 @@ export class CacheService {
5143
6219
  gauge('l1_entries', m.l1.entries, 'Current L1 entry count');
5144
6220
  gauge('l1_size_bytes', m.l1.sizeBytes, 'Current L1 used bytes');
5145
6221
  gauge('disk_files', m.disk.files, 'Current L1.5 disk file count');
6222
+ const breakerStates = { closed: 0, half_open: 1, open: 2 } as const;
6223
+ if (m.l2CircuitBreaker) {
6224
+ gauge('l2_circuit_state', breakerStates[m.l2CircuitBreaker.state],
6225
+ 'Local Redis circuit state (0: closed, 1: half-open probe, 2: open)');
6226
+ }
5146
6227
 
5147
6228
  if (m.disk.latencyWatchdog) {
5148
6229
  gauge('disk_latency_bypass_stage', m.disk.latencyWatchdog.bypassStage, 'Disk latency watchdog bypass stage (0: normal, 1: 25%, 2: 75%, 3: 100%)');
@@ -5165,6 +6246,16 @@ export class CacheService {
5165
6246
  if (m.backplane.enabled) {
5166
6247
  counter('backplane_sent', m.backplane.sent, 'Invalidation messages sent via Pub/Sub');
5167
6248
  counter('backplane_received', m.backplane.received, 'Invalidation messages received from peers');
6249
+ gauge('backplane_read_protection_enabled', m.backplane.readProtectionEnabled ? 1 : 0,
6250
+ 'Strict cached-read protection enabled (1: enabled, 0: disabled)');
6251
+ gauge('backplane_read_protection_active', m.backplane.readProtectionActive ? 1 : 0,
6252
+ 'Strict cached-read protection active (1: cached reads rejected, 0: available)');
6253
+ gauge('backplane_read_protection_duration_seconds', (m.backplane.readProtectionDurationMs ?? 0) / 1000,
6254
+ 'Monotonic time spent with the strict read gate closed');
6255
+ gauge('backplane_read_protection_deadline_seconds', (m.backplane.readProtectionDeadlineMs ?? 0) / 1000,
6256
+ 'Configured consumer proof deadline (zero when protection is disabled)');
6257
+ counter('invalidation_read_rejections', m.counters.invalidationReadRejections ?? 0,
6258
+ 'Cached reads rejected while invalidation was unavailable');
5168
6259
  }
5169
6260
  if (m.oom.enabled) {
5170
6261
  counter('oom_evictions', m.oom.evictions,
@@ -5196,7 +6287,14 @@ export class CacheService {
5196
6287
  this._assertActive('rotateEncryptionKey');
5197
6288
  this.enc.rotateKey(newKeyBase64, newMode);
5198
6289
  if (this._workerPool) {
5199
- await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
6290
+ await this._workerPool.drainAndReinit({
6291
+ ...this.enc.toWorkerInit(),
6292
+ size: this.opts.workerPoolSize || undefined,
6293
+ compression: this.opts.compression,
6294
+ compressionThresholdBytes: this.opts.compressionThresholdBytes,
6295
+ maxPendingTasks: this.opts.workerMaxPendingTasks,
6296
+ maxPendingBytes: this.opts.workerMaxPendingBytes,
6297
+ });
5200
6298
  }
5201
6299
  this.logger.info('tricache: encryption key rotated dynamically', { mode: this.enc.mode });
5202
6300
  }
@@ -5204,22 +6302,35 @@ export class CacheService {
5204
6302
  /** Close Redis connections and stop all background timers. */
5205
6303
  async destroy(): Promise<void> {
5206
6304
  this._destroyed = true;
6305
+ this._lifecycle.abort();
5207
6306
  this._fenceInvalidation();
5208
- this._backplaneAvailable = false;
6307
+ this._setBackplaneUnavailable('destroyed');
6308
+ this._retryBackplaneSubscription = null;
6309
+ this._backplaneSubscriptionReady = false;
6310
+ const preparedBackplaneClient = this._preparedBackplaneClient;
6311
+ this._preparedBackplaneClient = null;
6312
+ if (this._backplaneHeartbeatInterval) {
6313
+ clearInterval(this._backplaneHeartbeatInterval);
6314
+ this._backplaneHeartbeatInterval = null;
6315
+ }
5209
6316
  this.l1.clear();
5210
6317
  try { this._otelCleanup?.(); } catch { /* fail-soft telemetry teardown */ }
5211
6318
  this._otelCleanup = null;
5212
6319
  this.tagVersions.clear();
5213
6320
  for (const dispose of this._backplaneDisposers.splice(0)) dispose();
6321
+ this._tagVersionRefreshes.clear();
5214
6322
  this._pendingDiskDeletes.clear();
6323
+ this._pendingRedisInvalidations.clear();
6324
+ this._pendingSpills.clear();
6325
+ this._protectedSpillRevisions.clear();
5215
6326
  this._keyMutationEpochs.clear();
5216
6327
  this.inflight.clear();
5217
6328
  this.revalidating.clear();
5218
6329
  this._l1Counters.clear();
5219
6330
  this.tagIndex.clear();
5220
6331
  this.keyTags.clear();
5221
- this.dependencyIndex.clear();
5222
- this.keyDependencies.clear();
6332
+ this._clearDependencyMetadata();
6333
+ this._pendingDependencies.clear();
5223
6334
  const g = globalThis as Record<string, unknown>;
5224
6335
  const key = CacheService.globalKey(this.opts);
5225
6336
  if (g[key] === this) {
@@ -5235,6 +6346,10 @@ export class CacheService {
5235
6346
  }
5236
6347
  ProcessTerminationBus.unregister(this);
5237
6348
  this._shutdownHandler = null;
6349
+ if (preparedBackplaneClient && !this.opts.redisSubClient &&
6350
+ preparedBackplaneClient !== this.subClient && preparedBackplaneClient !== this.streamClient) {
6351
+ try { await preparedBackplaneClient.disconnect(); } catch { /* unused owned subscriber */ }
6352
+ }
5238
6353
  if (this._workerPool) {
5239
6354
  await this._workerPool.destroy();
5240
6355
  this._workerPool = null;
@@ -5262,7 +6377,14 @@ export class CacheService {
5262
6377
  await this._ipcServer.close();
5263
6378
  this._ipcServer = undefined;
5264
6379
  }
5265
- if (!this._diskDisabled) this.disk.close();
6380
+ if (!this._diskDisabled) {
6381
+ const drained = await this._drainPendingDiskWork(8_000);
6382
+ if (drained) this.disk.close();
6383
+ else {
6384
+ this.logger.warn('destroy: disk work did not drain; deferring disk index close until physical writes settle');
6385
+ void this.disk.whenIdle().then(() => this.disk.close());
6386
+ }
6387
+ }
5266
6388
  }
5267
6389
 
5268
6390
  /**