tricache 1.0.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +89 -93
  2. package/dashboards/tricache-alerts.yaml +80 -4
  3. package/dashboards/tricache-grafana.json +54 -1
  4. package/dashboards/tricache-inventory.rules.yml +21 -0
  5. package/dist/cache-service-BV5T8-20.d.cts +1064 -0
  6. package/dist/cache-service-UZXOQGEY.js +14 -0
  7. package/dist/{cache-service-CREOp7MM.d.ts → cache-service-tpyrXvlH.d.ts} +157 -24
  8. package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
  9. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  10. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  11. package/dist/{chunk-2AJKEQMZ.js → chunk-KV7KISK2.js} +54 -5
  12. package/dist/{chunk-JYQFQJNJ.js → chunk-MB3DMVWN.js} +3424 -1022
  13. package/dist/chunk-RBJRTGFK.js +94 -0
  14. package/dist/chunk-S5N65I45.js +17 -0
  15. package/dist/cli.cjs +3694 -1070
  16. package/dist/cli.d.cts +12 -0
  17. package/dist/cli.js +210 -14
  18. package/dist/dashboard/index.cjs +111 -29
  19. package/dist/dashboard/index.d.cts +185 -0
  20. package/dist/dashboard/index.d.ts +5 -3
  21. package/dist/dashboard/index.js +1 -1
  22. package/dist/drizzle/index.cjs +3578 -1068
  23. package/dist/drizzle/index.d.cts +46 -0
  24. package/dist/drizzle/index.d.ts +2 -2
  25. package/dist/drizzle/index.js +6 -2
  26. package/dist/edge/index.cjs +368 -162
  27. package/dist/edge/index.d.cts +134 -0
  28. package/dist/edge/index.d.ts +11 -4
  29. package/dist/edge/index.js +314 -155
  30. package/dist/hono/index.cjs +3614 -1087
  31. package/dist/hono/index.d.cts +93 -0
  32. package/dist/hono/index.d.ts +7 -5
  33. package/dist/hono/index.js +16 -9
  34. package/dist/hono-CMv2VdQ6.d.cts +404 -0
  35. package/dist/{hono-DSV2ve66.d.ts → hono-Dvq04kX9.d.ts} +33 -7
  36. package/dist/http/index.cjs +3712 -1124
  37. package/dist/http/index.d.cts +103 -0
  38. package/dist/http/index.d.ts +13 -5
  39. package/dist/http/index.js +92 -43
  40. package/dist/index.cjs +4067 -1252
  41. package/dist/index.d.cts +1071 -0
  42. package/dist/index.d.ts +123 -27
  43. package/dist/index.js +878 -21
  44. package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.cts} +1 -0
  45. package/dist/murmur3-DF8BFRnu.d.ts +99 -0
  46. package/dist/nestjs/index.cjs +3635 -1112
  47. package/dist/nestjs/index.d.cts +299 -0
  48. package/dist/nestjs/index.d.ts +120 -33
  49. package/dist/nestjs/index.js +132 -43
  50. package/dist/next/index.cjs +3704 -1175
  51. package/dist/next/index.d.cts +238 -0
  52. package/dist/next/index.d.ts +39 -11
  53. package/dist/next/index.js +202 -102
  54. package/dist/prisma/index.cjs +29 -18
  55. package/dist/prisma/index.d.cts +62 -0
  56. package/dist/prisma/index.d.ts +2 -2
  57. package/dist/prisma/index.js +17 -18
  58. package/dist/serialize-worker.cjs +162 -39
  59. package/dist/serialize-worker.d.cts +2 -0
  60. package/dist/serialize-worker.js +9 -7
  61. package/dist/{types-Dyip5wAl.d.ts → types-F8vRWMrE.d.cts} +186 -54
  62. package/dist/types-F8vRWMrE.d.ts +1636 -0
  63. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  64. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  65. package/package.json +116 -37
  66. package/src/adapters/auto-pipeliner.ts +150 -26
  67. package/src/adapters/node-redis.ts +106 -27
  68. package/src/cache-service.ts +2215 -793
  69. package/src/cli.ts +25 -14
  70. package/src/codec.ts +3 -3
  71. package/src/compression.ts +39 -16
  72. package/src/cross-region.ts +22 -4
  73. package/src/dashboard/handler.ts +26 -6
  74. package/src/dashboard/html.ts +35 -10
  75. package/src/dashboard/index.ts +35 -13
  76. package/src/dashboard/types.ts +3 -1
  77. package/src/disk-tier.ts +448 -102
  78. package/src/drizzle/index.ts +2 -1
  79. package/src/edge/adapters/cloudflare-do.ts +25 -10
  80. package/src/edge/adapters/cloudflare-kv.ts +12 -9
  81. package/src/edge/adapters/upstash.ts +27 -11
  82. package/src/edge/cache.ts +200 -110
  83. package/src/edge/hono.ts +23 -6
  84. package/src/edge/types.ts +17 -5
  85. package/src/encryption.ts +50 -18
  86. package/src/env.d.ts +1 -1
  87. package/src/errors.ts +12 -0
  88. package/src/hono/index.ts +19 -9
  89. package/src/http/express.ts +62 -17
  90. package/src/http/fastify.ts +35 -21
  91. package/src/http/utils.ts +60 -20
  92. package/src/index.ts +6 -0
  93. package/src/ipc-telemetry.ts +35 -9
  94. package/src/latency-watchdog.ts +5 -1
  95. package/src/nestjs/decorators.ts +11 -6
  96. package/src/nestjs/index.ts +2 -0
  97. package/src/nestjs/keyv-adapter.ts +68 -0
  98. package/src/nestjs/tricache.module.ts +15 -12
  99. package/src/nestjs/tricache.store.ts +69 -26
  100. package/src/nestjs/types.ts +30 -16
  101. package/src/next/cache-handler.ts +151 -53
  102. package/src/next/index.ts +1 -0
  103. package/src/next/types.ts +25 -0
  104. package/src/origin-capacity.ts +134 -0
  105. package/src/prisma/index.ts +17 -24
  106. package/src/remote-snapshot.ts +37 -27
  107. package/src/serialize-worker.ts +8 -5
  108. package/src/sigv4-snapshot-adapter.ts +37 -27
  109. package/src/smart-memory-cache.ts +121 -44
  110. package/src/types.ts +117 -37
  111. package/src/utils/cgroup.ts +12 -0
  112. package/src/utils/config-comparison.ts +29 -0
  113. package/src/utils/deadline.ts +14 -0
  114. package/src/utils/diagnostics.ts +27 -0
  115. package/src/utils/lz4-size.ts +74 -0
  116. package/src/utils/namespace-key.ts +48 -0
  117. package/src/utils/query-key.ts +13 -0
  118. package/src/utils/redis-slot.ts +13 -0
  119. package/src/utils/snapshot-transfer.ts +83 -0
  120. package/src/utils/work-limits.ts +73 -0
  121. package/src/utils/write-revision.ts +4 -0
  122. package/src/wasm/bloom-filter-wasm.ts +25 -5
  123. package/src/worker-pool.ts +44 -15
  124. package/src/wtiny-lfu.ts +82 -20
  125. package/dist/cache-service-MG7PN6MX.js +0 -12
  126. package/dist/chunk-3I5L7K6I.js +0 -704
  127. package/dist/chunk-BQRURGGD.js +0 -60
package/src/disk-tier.ts CHANGED
@@ -21,6 +21,8 @@ import os from 'os';
21
21
  import { CacheCodec, defaultCodec } from './codec.js';
22
22
  import type { DiskCacheEntry, ILogger, DiskBackpressureStats } from './types.js';
23
23
  import type { CacheEncryption } from './encryption.js';
24
+ import { encodeNamespaceSegment } from './utils/namespace-key.js';
25
+ import { isWriteRevision } from './utils/write-revision.js';
24
26
  import {
25
27
  compressWithHeader,
26
28
  decompressWithHeader,
@@ -39,11 +41,12 @@ export type { DiskBackpressureStats };
39
41
  */
40
42
  export class BoundedDiskQueue {
41
43
  private active = 0;
42
- private queue: Array<() => void> = [];
44
+ private queue: Array<(admitted: boolean) => void> = [];
43
45
  private spillsDropped = 0;
44
46
  private consecutiveFailures = 0;
45
47
  private circuitState: 'closed' | 'open' | 'half-open' = 'closed';
46
48
  private lastStateChangeMonotonic = performance.now();
49
+ private readonly idleWaiters = new Set<() => void>();
47
50
 
48
51
  constructor(
49
52
  private readonly maxConcurrent: number = Math.min(4, Math.max(1, Math.floor((os?.availableParallelism?.() ?? 4) / 4))),
@@ -51,7 +54,51 @@ export class BoundedDiskQueue {
51
54
  private readonly writeTimeoutMs: number = 500,
52
55
  private readonly failureThreshold: number = 5,
53
56
  private readonly cooldownMs: number = 5000,
54
- ) {}
57
+ ) {
58
+ if (!Number.isInteger(maxConcurrent) || maxConcurrent < 1 || !Number.isInteger(maxPending) || maxPending < 0 ||
59
+ !Number.isFinite(writeTimeoutMs) || writeTimeoutMs <= 0 || !Number.isInteger(failureThreshold) || failureThreshold < 1 ||
60
+ !Number.isFinite(cooldownMs) || cooldownMs < 0) {
61
+ throw new Error('Disk queue limits and timeout must be finite positive values (pending/cooldown may be zero)');
62
+ }
63
+ }
64
+
65
+ get isSaturated(): boolean {
66
+ return this.active >= this.maxConcurrent && this.queue.length >= this.maxPending;
67
+ }
68
+
69
+ private releaseSlot(): void {
70
+ if (this.circuitState === 'open') {
71
+ for (const next of this.queue.splice(0)) next(false);
72
+ }
73
+ const next = this.queue.shift();
74
+ // Transfer the reservation so newly arriving calls cannot steal a queued slot.
75
+ if (next) next(true);
76
+ else this.active--;
77
+ if (this.active === 0 && this.queue.length === 0) {
78
+ for (const resolve of this.idleWaiters) resolve();
79
+ this.idleWaiters.clear();
80
+ }
81
+ }
82
+
83
+ /** Wait for physical work, not caller promises that may already have timed out. */
84
+ async drain(timeoutMs = 8_000): Promise<boolean> {
85
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0) throw new Error('Drain timeout must be finite and non-negative');
86
+ if (this.active === 0 && this.queue.length === 0) return true;
87
+ return new Promise<boolean>(resolve => {
88
+ let settled = false;
89
+ const finish = (idle: boolean) => {
90
+ if (settled) return;
91
+ settled = true;
92
+ clearTimeout(timer);
93
+ this.idleWaiters.delete(onIdle);
94
+ resolve(idle);
95
+ };
96
+ const onIdle = () => finish(true);
97
+ const timer = setTimeout(() => finish(false), timeoutMs);
98
+ this.idleWaiters.add(onIdle);
99
+ if (this.active === 0 && this.queue.length === 0) onIdle();
100
+ });
101
+ }
55
102
 
56
103
  public async schedule<T>(task: () => Promise<T>): Promise<T | null> {
57
104
  const now = performance.now();
@@ -73,22 +120,30 @@ export class BoundedDiskQueue {
73
120
  return null;
74
121
  }
75
122
 
76
- if (this.queue.length >= this.maxPending) {
123
+ if (this.isSaturated) {
77
124
  this.spillsDropped++;
78
125
  return null; // Bounded memory queue: drop spill to preserve main thread
79
126
  }
80
127
 
81
128
  // Wait for slot in concurrency pool
82
129
  if (this.active >= this.maxConcurrent) {
83
- await new Promise<void>((resolve) => this.queue.push(resolve));
130
+ const admitted = await new Promise<boolean>((resolve) => this.queue.push(resolve));
131
+ if (!admitted) {
132
+ this.spillsDropped++;
133
+ return null;
134
+ }
135
+ } else {
136
+ this.active++;
84
137
  }
85
-
86
- this.active++;
87
138
  let timeoutId: NodeJS.Timeout | null = null;
139
+ const work = Promise.resolve().then(task);
140
+ // A caller timeout does not cancel filesystem I/O. Release its physical slot
141
+ // only when the underlying operation settles, including on late failure.
142
+ void work.then(() => this.releaseSlot(), () => this.releaseSlot());
88
143
 
89
144
  try {
90
145
  const result = await Promise.race([
91
- task(),
146
+ work,
92
147
  new Promise<never>((_, reject) => {
93
148
  timeoutId = setTimeout(
94
149
  () => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
@@ -110,14 +165,12 @@ export class BoundedDiskQueue {
110
165
  if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === 'half-open') {
111
166
  this.circuitState = 'open';
112
167
  this.lastStateChangeMonotonic = performance.now();
168
+ for (const next of this.queue.splice(0)) next(false);
113
169
  }
114
170
  this.spillsDropped++;
115
171
  return null;
116
172
  } finally {
117
173
  if (timeoutId) clearTimeout(timeoutId);
118
- this.active--;
119
- const next = this.queue.shift();
120
- if (next) next();
121
174
  }
122
175
  }
123
176
 
@@ -131,6 +184,19 @@ export class BoundedDiskQueue {
131
184
  };
132
185
  }
133
186
 
187
+ /** Resolve when every admitted physical task, including timed-out callers, settles. */
188
+ public whenIdle(): Promise<void> {
189
+ if (this.active === 0 && this.queue.length === 0) return Promise.resolve();
190
+ return new Promise(resolve => {
191
+ const onIdle = () => {
192
+ this.idleWaiters.delete(onIdle);
193
+ resolve();
194
+ };
195
+ this.idleWaiters.add(onIdle);
196
+ if (this.active === 0 && this.queue.length === 0) onIdle();
197
+ });
198
+ }
199
+
134
200
  public reset(): void {
135
201
  this.consecutiveFailures = 0;
136
202
  this.circuitState = 'closed';
@@ -201,7 +267,7 @@ const DISK_TIER_VERSION = 1;
201
267
  */
202
268
  export function resolveDefaultDiskDir(namespace?: string, logger?: ILogger): { dir: string; isShm: boolean } {
203
269
  const ns = namespace?.trim() ?? '';
204
- const nsDir = ns ? `tricache-disk-${ns}` : 'tricache-disk';
270
+ const nsDir = `tricache-disk-v3-${encodeNamespaceSegment(ns)}`;
205
271
 
206
272
  if (process.platform === 'linux') {
207
273
  const shmPath = '/dev/shm';
@@ -267,6 +333,16 @@ export class DiskTier {
267
333
  private diskUsageBytes = 0;
268
334
  private usageCounted = false;
269
335
  private fileCount = 0; // maintained in-memory; avoids walkCacheFiles() in stats
336
+ private reservedBytes = 0;
337
+ private reservedFiles = 0;
338
+ private saveSequence = 0;
339
+ private epoch = 0;
340
+ private readonly pendingSaves = new Map<string, { token: symbol; setAt: number; revision?: string }>();
341
+ private closed = false;
342
+ private readonly invalidatedKeys = new Set<string>();
343
+ /** Hash buckets are bounded to 256; successful creation can be reused between spills. */
344
+ private readonly readyBuckets = new Set<string>();
345
+ private readonly pendingBuckets = new Map<string, Promise<void>>();
270
346
  /** Next bucket index (0–255) for the staggered janitor wheel. */
271
347
  private _nextJanitorBucket = 0;
272
348
 
@@ -305,6 +381,7 @@ export class DiskTier {
305
381
  // ── Helpers ───────────────────────────────────────────────────────────────
306
382
 
307
383
  private ensureDir(): void {
384
+ if (this.closed) return;
308
385
  if (this.dirReady) return;
309
386
  try {
310
387
  fs.mkdirSync(this.opts.dir, { recursive: true, mode: 0o700 });
@@ -315,6 +392,21 @@ export class DiskTier {
315
392
  }
316
393
  }
317
394
 
395
+ private ensureBucket(hash: string): Promise<void> {
396
+ const bucket = hash.slice(0, 2);
397
+ if (this.readyBuckets.has(bucket)) return Promise.resolve();
398
+ const pending = this.pendingBuckets.get(bucket);
399
+ if (pending) return pending;
400
+ const creation = Promise.resolve().then(async () => {
401
+ await fs.promises.mkdir(path.join(this.opts.dir, bucket), { recursive: true });
402
+ if (!this.closed) this.readyBuckets.add(bucket);
403
+ }).finally(() => {
404
+ if (this.pendingBuckets.get(bucket) === creation) this.pendingBuckets.delete(bucket);
405
+ });
406
+ this.pendingBuckets.set(bucket, creation);
407
+ return creation;
408
+ }
409
+
318
410
  /**
319
411
  * Initialise the SQLite metadata index. Called once after the cache directory
320
412
  * is confirmed to exist. On any failure the instance silently falls back to
@@ -427,8 +519,31 @@ export class DiskTier {
427
519
  *
428
520
  * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
429
521
  */
430
- private hashToWritePath(hash: string, expiresAt: number): string {
431
- return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiresAt.toString(16).padStart(12, '0')}`);
522
+ private hashToWritePath(hash: string, expiresAt: number, setAt?: number, revision?: string): string {
523
+ const expiry = Math.floor(expiresAt).toString(16).padStart(12, '0');
524
+ if (setAt === undefined) return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}`);
525
+ const written = Math.floor(setAt).toString(16).padStart(12, '0');
526
+ const sequence = (++this.saveSequence).toString(16).padStart(12, '0');
527
+ const identity = revision ? this.revisionSuffix(revision) : '';
528
+ return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}_${written}_${sequence}_${crypto.randomBytes(6).toString('hex')}${identity}`);
529
+ }
530
+
531
+ /** Fixed, path-safe suffix lets cleanup select a revision without decoding its payload. */
532
+ private revisionSuffix(revision: string): string {
533
+ return `_r${crypto.createHash('sha256').update(revision).digest('hex')}`;
534
+ }
535
+
536
+ private findFilePaths(hash: string): string[] {
537
+ const bucket = path.join(this.opts.dir, hash.slice(0, 2));
538
+ try {
539
+ return fs.readdirSync(bucket).filter(file => !file.endsWith('.tmp') && (file === hash || file.startsWith(hash + '_')))
540
+ .map(file => path.join(bucket, file));
541
+ } catch { return []; }
542
+ }
543
+
544
+ private fileWrittenAt(file: string): number {
545
+ const parts = path.basename(file).split('_');
546
+ return parts.length >= 4 ? parseInt(parts[2], 16) : fs.statSync(file).mtimeMs;
432
547
  }
433
548
 
434
549
  /**
@@ -438,20 +553,30 @@ export class DiskTier {
438
553
  * Returns null when the bucket dir does not exist or the key is absent.
439
554
  */
440
555
  private findFilePath(hash: string): string | null {
441
- const bucketPath = path.join(this.opts.dir, hash.slice(0, 2));
442
- let files: string[];
443
- try { files = fs.readdirSync(bucketPath); } catch { return null; }
444
- // Return the lexicographically largest match: V3 filenames are
445
- // "{hash}_{expiresHex12}", so lex-max = largest timestamp = newest entry.
446
- // If the same key was evicted to disk twice (different TTLs → different names),
447
- // this ensures we always serve and delete the freshest copy; the janitor cleans
448
- // up the stale one when its encoded timestamp expires.
449
- let match: string | undefined;
450
- for (const f of files) {
451
- if ((f === hash || f.startsWith(hash + '_')) && (!match || f > match)) match = f;
556
+ let match: string | null = null;
557
+ let newest = -Infinity;
558
+ let sequence = -1;
559
+ for (const file of this.findFilePaths(hash)) {
560
+ try {
561
+ const written = this.fileWrittenAt(file);
562
+ const order = parseInt(path.basename(file).split('_')[3] ?? '0', 16);
563
+ if (written > newest || (written === newest && order > sequence)) {
564
+ match = file;
565
+ newest = written;
566
+ sequence = order;
567
+ }
568
+ } catch { /* raced with deletion */ }
452
569
  }
453
- if (!match) return null;
454
- return path.join(bucketPath, match);
570
+ return match;
571
+ }
572
+
573
+ private removeFile(filePath: string): void {
574
+ try {
575
+ const size = fs.statSync(filePath).size;
576
+ fs.unlinkSync(filePath);
577
+ this.diskUsageBytes = Math.max(0, this.diskUsageBytes - size);
578
+ this.fileCount = Math.max(0, this.fileCount - 1);
579
+ } catch { /* already gone or locked */ }
455
580
  }
456
581
 
457
582
  /**
@@ -497,9 +622,9 @@ export class DiskTier {
497
622
  * magic + plaintext expiresAt live in the outer 16-byte header written by `save`).
498
623
  * Returns the buffer unchanged when no encryption instance is configured.
499
624
  */
500
- private encryptV2(data: Buffer): Buffer {
625
+ private encryptV2(data: Buffer, key: string): Buffer {
501
626
  if (!this.opts.encryption) return data;
502
- return this.opts.encryption.encryptBuffer(data);
627
+ return this.opts.encryption.encryptBuffer(data, JSON.stringify(['tricache-disk-v2', key]));
503
628
  }
504
629
 
505
630
  /**
@@ -508,9 +633,9 @@ export class DiskTier {
508
633
  * CacheEncryption blob (IV|TAG|CT for GCM, IV|CT for CTR, key⊕data for XOR);
509
634
  * without one the payload is raw msgpack.
510
635
  */
511
- private decryptV2(inner: Buffer): Buffer {
636
+ private decryptV2(inner: Buffer, key: string): Buffer {
512
637
  if (!this.opts.encryption) return inner;
513
- return this.opts.encryption.decryptBuffer(inner);
638
+ return this.opts.encryption.decryptBuffer(inner, JSON.stringify(['tricache-disk-v2', key]));
514
639
  }
515
640
 
516
641
  // ── Public API ────────────────────────────────────────────────────────────
@@ -518,18 +643,20 @@ export class DiskTier {
518
643
  /**
519
644
  * Spill an evicted L1 entry to disk.
520
645
  *
521
- * Returns a Promise that resolves when the file is durably written. Callers
646
+ * Returns after the queue caller completes or times out; this is not an fsync
647
+ * durability guarantee. drain() separately waits for physical work. Callers
522
648
  * that treat the spill as fire-and-forget should do:
523
649
  * `void disk.save(key, entry)`
524
650
  *
525
651
  * Implementation notes:
526
- * - pack() + AES-256-GCM encrypt run synchronously — both are pure CPU,
527
- * sub-millisecond for entries up to diskEntryMaxBytes, and do not block
528
- * on any external resource.
529
- * - The actual write syscall (mkdir + writeFile) is async via fs.promises,
530
- * so the Node.js event loop is never stalled waiting for disk I/O.
652
+ * - Serialization/compression/encryption run synchronously; CPU cost depends
653
+ * on payload shape and size. Index and version-cleanup work can also block.
654
+ * - Staging writes and rename use fs.promises. Bucket creation is coalesced,
655
+ * and failed staging cleanup has one owner in the physical task's finally.
531
656
  */
532
657
  async save(key: string, entry: DiskCacheEntry): Promise<void> {
658
+ if (this.closed || this.diskQueue.isSaturated) return;
659
+ if (entry.revision !== undefined && !isWriteRevision(entry.revision)) return;
533
660
  if (this.isForbidden(key)) return;
534
661
  if (entry.expiresAt <= Date.now()) return;
535
662
 
@@ -543,7 +670,7 @@ export class DiskTier {
543
670
  }
544
671
 
545
672
  // Fast-shed incoming spills while host volume is low (<10%), pruning is active, or quota is reached
546
- if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes >= this.opts.maxBytes) {
673
+ if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes + this.reservedBytes >= this.opts.maxBytes) {
547
674
  this._spillsShedTotal++;
548
675
  return;
549
676
  }
@@ -556,11 +683,12 @@ export class DiskTier {
556
683
  // ── Synchronous phase: pack + encrypt (CPU-only, no I/O) ─────────────
557
684
  let final: Buffer;
558
685
  try {
686
+ const { value: _value, ...storedEntry } = entry as DiskCacheEntry & { value?: unknown };
559
687
  const payload: DiskPayload = {
560
688
  version: DISK_TIER_VERSION,
561
689
  key,
562
690
  entry: {
563
- ...entry,
691
+ ...storedEntry,
564
692
  data: entry.data instanceof Uint8Array
565
693
  ? Buffer.from(entry.data)
566
694
  : entry.data,
@@ -578,8 +706,9 @@ export class DiskTier {
578
706
  // to check expiry with a 16-byte partial read — no decrypt or unpack needed.
579
707
  const header = Buffer.allocUnsafe(V2_HEADER_LEN);
580
708
  DISK_MAGIC_V2.copy(header, 0);
581
- header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
582
- final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
709
+ header.writeBigUInt64LE(BigInt(Math.floor(entry.expiresAt)), 8);
710
+ final = Buffer.concat([header, this.encryptV2(toEncrypt, key)]);
711
+ if (final.length > this.opts.entryMaxBytes || this.diskUsageBytes + this.reservedBytes + final.length > this.opts.maxBytes) return;
583
712
  } catch (err) {
584
713
  this.opts.logger.debug('DiskTier: pack/encrypt failed', { key: key.slice(0, 50), error: (err as Error).message });
585
714
  return;
@@ -587,21 +716,55 @@ export class DiskTier {
587
716
 
588
717
  // ── Async phase: mkdir + write to same-dir tmp + atomic rename ────
589
718
  const hash = this.keyToHash(key);
590
- const filePath = this.hashToWritePath(hash, entry.expiresAt);
719
+ const setAt = entry.setAt ?? Date.now();
720
+ if ((this.pendingSaves.get(key)?.setAt ?? 0) > setAt) return;
721
+ const filePath = this.hashToWritePath(hash, entry.expiresAt, setAt, entry.revision);
591
722
  const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString('hex')}.tmp`;
723
+ const token = Symbol(key);
724
+ const epoch = this.epoch;
725
+ this.pendingSaves.set(key, { token, setAt, revision: entry.revision });
726
+ const current = () => !this.closed && this.epoch === epoch && this.pendingSaves.get(key)?.token === token;
727
+ let started = false;
728
+ let released = false;
729
+ let accounted = false;
730
+ const releaseReservation = () => {
731
+ if (released) return;
732
+ released = true;
733
+ this.reservedBytes = Math.max(0, this.reservedBytes - final.length);
734
+ this.reservedFiles = Math.max(0, this.reservedFiles - 1);
735
+ if (this.pendingSaves.get(key)?.token === token) this.pendingSaves.delete(key);
736
+ };
592
737
 
593
738
  // Optimistically reserve quota before queuing so concurrent spills respect the cap
594
- this.diskUsageBytes += final.length;
595
- this.fileCount++;
739
+ this.reservedBytes += final.length;
740
+ this.reservedFiles++;
596
741
 
597
742
  if (this.diskUsageBytes >= this.opts.maxBytes * 0.80 && !this._isPruning) {
598
743
  void this.triggerChunkedPrune();
599
744
  }
600
745
 
601
746
  const result = await this.diskQueue.schedule(async () => {
747
+ started = true;
748
+ let cleanupTemporary = false;
602
749
  try {
603
- await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
604
- await fs.promises.writeFile(tmpPath, final, { mode: 0o600 });
750
+ if (!current()) return false;
751
+ const previous = this.findFilePath(hash);
752
+ if (previous && this.fileWrittenAt(previous) > setAt) return false;
753
+ await this.ensureBucket(hash);
754
+ if (!current()) return false;
755
+ cleanupTemporary = true; // A failed write can still leave a partial staging file.
756
+ try {
757
+ await fs.promises.writeFile(tmpPath, final, { mode: 0o600 });
758
+ } catch (writeError: unknown) {
759
+ // Another process/operator may remove a known bucket. Retry once after
760
+ // invalidating its cached readiness; do not retry other filesystem errors.
761
+ if ((writeError as { code?: string })?.code !== 'ENOENT' || !current()) throw writeError;
762
+ this.readyBuckets.delete(hash.slice(0, 2));
763
+ await this.ensureBucket(hash);
764
+ if (!current()) return false;
765
+ await fs.promises.writeFile(tmpPath, final, { mode: 0o600 });
766
+ }
767
+ if (!current()) return false;
605
768
 
606
769
  // Atomic rename with micro-retry loop for Windows NTFS handle release
607
770
  try {
@@ -615,6 +778,21 @@ export class DiskTier {
615
778
  throw renameErr;
616
779
  }
617
780
  }
781
+ cleanupTemporary = false; // Successful rename consumed the staging path.
782
+
783
+ if (!current()) {
784
+ try { await fs.promises.unlink(filePath); } catch { /* already removed */ }
785
+ return false;
786
+ }
787
+
788
+ // Remove all superseded versions, not just the one with the largest TTL.
789
+ for (const previousPath of this.findFilePaths(hash)) {
790
+ if (previousPath !== filePath) this.removeFile(previousPath);
791
+ }
792
+ this.diskUsageBytes += final.length;
793
+ this.fileCount++;
794
+ accounted = true;
795
+ this.invalidatedKeys.delete(key);
618
796
 
619
797
  if (this._db) {
620
798
  const priority = typeof entry.priority === 'number' ? entry.priority : 2;
@@ -624,24 +802,27 @@ export class DiskTier {
624
802
  this.opts.logger.debug('DiskTier: entry saved', { key: key.slice(0, 50), bytes: final.length });
625
803
  return true;
626
804
  } catch (err) {
627
- try { await fs.promises.unlink(tmpPath); } catch { /* ignore if already gone/failed */ }
628
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length); // rollback
629
- this.fileCount = Math.max(0, this.fileCount - 1);
630
- if (this._db) try { this._stmtDelete!.run(hash); } catch { /* ok */ }
805
+ if (accounted) this.removeFile(filePath);
631
806
  this.opts.logger.debug('DiskTier: save failed', { key: key.slice(0, 50), error: (err as Error).message });
632
807
  throw err;
808
+ } finally {
809
+ if (cleanupTemporary) {
810
+ try { await fs.promises.unlink(tmpPath); } catch { /* removed, partially created, or never created */ }
811
+ }
812
+ releaseReservation();
813
+ if (this.invalidatedKeys.has(key) && !this.pendingSaves.has(key)) this.delete(key, true);
633
814
  }
634
815
  });
635
816
 
636
- if (result === null) {
817
+ if (result === null && !started) {
637
818
  // Fast-dropped by BoundedDiskQueue backpressure / circuit breaker: rollback reservation
638
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length);
639
- this.fileCount = Math.max(0, this.fileCount - 1);
819
+ releaseReservation();
640
820
  }
641
821
  }
642
822
 
643
823
  /** Load a key from disk, or return null on miss/expiry/corruption. */
644
824
  load(key: string): DiskCacheEntry | null {
825
+ if (this.invalidatedKeys.has(key) || this.closed) return null;
645
826
  if (this.isForbidden(key)) return null;
646
827
  this.ensureDir();
647
828
  if (!this.dirReady) return null;
@@ -674,8 +855,8 @@ export class DiskTier {
674
855
  // opening the file when the entry is already stale.
675
856
  if (!this._db) {
676
857
  const filename = path.basename(filePath);
677
- if (filename.length === 77 && filename[64] === '_') {
678
- const expiresAt = parseInt(filename.slice(65), 16);
858
+ if (filename.length >= 77 && filename[64] === '_') {
859
+ const expiresAt = parseInt(filename.slice(65, 77), 16);
679
860
  if (expiresAt <= Date.now()) {
680
861
  try {
681
862
  const sz = fs.statSync(filePath).size;
@@ -692,65 +873,184 @@ export class DiskTier {
692
873
  if (stat.size > this.opts.entryMaxBytes) {
693
874
  fs.unlinkSync(filePath);
694
875
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
876
+ this.fileCount = Math.max(0, this.fileCount - 1);
695
877
  if (this._db) this._stmtDelete!.run(hash);
696
878
  return null;
697
879
  }
698
880
 
699
881
  const raw = fs.readFileSync(filePath);
700
882
  // Delete immediately — entry will be promoted back to L1
701
- try {
702
- fs.unlinkSync(filePath);
703
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
704
- this.fileCount = Math.max(0, this.fileCount - 1);
705
- } catch { /* ok */ }
883
+ for (const storedPath of this.findFilePaths(hash)) this.removeFile(storedPath);
706
884
  if (this._db) this._stmtDelete!.run(hash);
885
+ return this.decodeLoadedPayload(key, raw);
886
+ } catch (err) {
887
+ if (this._db) try { this._stmtDelete!.run(hash); } catch { /* ok */ }
888
+ this.opts.logger.debug('DiskTier: load failed', { key: key.slice(0, 50), error: (err as Error).message });
889
+ return null;
890
+ }
891
+ }
707
892
 
708
- let decrypted: Buffer;
709
- if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
710
- // V2/V3: quick expiry guard from plaintext header before paying decrypt cost
711
- const expiresAt = Number(raw.readBigUInt64LE(8));
712
- if (expiresAt <= Date.now()) return null;
713
- try { decrypted = this.decryptV2(raw.subarray(V2_HEADER_LEN)); } catch { return null; }
714
- } else {
715
- // V1 / legacy unencrypted — backward compat
716
- try { decrypted = this.decrypt(raw); } catch { return null; }
893
+ /**
894
+ * Async variant of load() for the SQLite-indexed path.
895
+ *
896
+ * Disk hits sit directly on the request path in front of Redis. The sync
897
+ * load() above blocks the event loop for readdir/stat/read/unlink; under
898
+ * concurrent pressure those small stalls add up to tail latency. This
899
+ * variant keeps the same consume-on-read and validation semantics but uses
900
+ * fs.promises, and only removes the indexed file instead of scanning the
901
+ * whole bucket. Superseded files remain unreachable through the index and
902
+ * are removed by the existing expiry janitor.
903
+ *
904
+ * File-only mode (no node:sqlite) falls back to the synchronous path.
905
+ */
906
+ async loadAsync(key: string): Promise<DiskCacheEntry | null> {
907
+ if (this.invalidatedKeys.has(key) || this.closed) return null;
908
+ if (this.isForbidden(key)) return null;
909
+ this.ensureDir();
910
+ if (!this.dirReady) return null;
911
+ if (!this._db) return this.load(key);
912
+
913
+ const hash = this.keyToHash(key);
914
+ let row: { file_path: string; expires_at: number } | undefined;
915
+ try {
916
+ row = this._stmtSelect!.get(hash) as { file_path: string; expires_at: number } | undefined;
917
+ } catch { return null; }
918
+ if (!row) return null;
919
+
920
+ if (row.expires_at <= Date.now()) {
921
+ if (this.deleteIndexRowIfCurrent(hash, row.file_path)) {
922
+ try {
923
+ const stat = await fs.promises.stat(row.file_path);
924
+ await fs.promises.unlink(row.file_path);
925
+ this.diskUsageBytes = Math.max(0, this.diskUsageBytes - stat.size);
926
+ this.fileCount = Math.max(0, this.fileCount - 1);
927
+ } catch { /* already gone */ }
928
+ }
929
+ return null;
930
+ }
931
+
932
+ let raw: Buffer;
933
+ try {
934
+ // Match the synchronous loader's admission check before allocating the payload.
935
+ const stat = await fs.promises.stat(row.file_path);
936
+ if (stat.size > this.opts.entryMaxBytes) {
937
+ if (this.deleteIndexRowIfCurrent(hash, row.file_path)) {
938
+ try {
939
+ await fs.promises.unlink(row.file_path);
940
+ this.diskUsageBytes = Math.max(0, this.diskUsageBytes - stat.size);
941
+ this.fileCount = Math.max(0, this.fileCount - 1);
942
+ } catch { /* already removed by another path */ }
943
+ }
944
+ return null;
717
945
  }
946
+ raw = await fs.promises.readFile(row.file_path);
947
+ } catch {
948
+ // A newer spill may have replaced the row while readFile() ran. Only
949
+ // remove the row when it still describes the file that failed to read.
950
+ this.deleteIndexRowIfCurrent(hash, row.file_path);
951
+ return null;
952
+ }
718
953
 
719
- const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? 'brotli');
720
- const payload = this.codec.decode(uncompressed) as DiskPayload;
721
- if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
722
- if (payload.entry.expiresAt <= Date.now()) return null;
954
+ // Consume the indexed file. Only the caller that still owns the row removes
955
+ // the file and adjusts accounting; a newer spill may have replaced it while
956
+ // readFile() ran, and that newer entry must remain readable.
957
+ if (this.deleteIndexRowIfCurrent(hash, row.file_path)) {
958
+ try {
959
+ await fs.promises.unlink(row.file_path);
960
+ this.diskUsageBytes = Math.max(0, this.diskUsageBytes - raw.length);
961
+ this.fileCount = Math.max(0, this.fileCount - 1);
962
+ } catch { /* already removed by another path */ }
963
+ }
723
964
 
724
- const entry = payload.entry;
725
- if (entry.data instanceof Uint8Array) entry.data = Buffer.from(entry.data);
965
+ // Recheck in case the file grew after stat() or the limit changed while reading.
966
+ if (raw.length > this.opts.entryMaxBytes) return null;
726
967
 
727
- this.opts.logger.debug('DiskTier: hit (→L1)', { key: key.slice(0, 50), ageMs: Date.now() - payload.writtenAt });
728
- return entry;
968
+ try {
969
+ return this.decodeLoadedPayload(key, raw);
729
970
  } catch (err) {
730
- if (this._db) try { this._stmtDelete!.run(hash); } catch { /* ok */ }
731
971
  this.opts.logger.debug('DiskTier: load failed', { key: key.slice(0, 50), error: (err as Error).message });
732
972
  return null;
733
973
  }
734
974
  }
735
975
 
736
- /** Explicitly delete a key from disk (cache invalidation). */
737
- delete(key: string): void {
976
+ /**
977
+ * Delete the index row for `hash` only if it still points at `filePath`.
978
+ * The check and delete are synchronous, so a newer spill cannot slip between
979
+ * them. Returns true when this caller removed the row.
980
+ */
981
+ private deleteIndexRowIfCurrent(hash: string, filePath: string): boolean {
982
+ try {
983
+ const latest = this._stmtSelect!.get(hash) as { file_path: string } | undefined;
984
+ if (latest?.file_path !== filePath) return false;
985
+ this._stmtDelete!.run(hash);
986
+ return true;
987
+ } catch {
988
+ return false;
989
+ }
990
+ }
991
+
992
+ /** Decode and validate a raw disk payload. Callers own file cleanup. */
993
+ private decodeLoadedPayload(key: string, raw: Buffer): DiskCacheEntry | null {
994
+ let decrypted: Buffer;
995
+ if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
996
+ // V2/V3: quick expiry guard from plaintext header before paying decrypt cost
997
+ const expiresAt = Number(raw.readBigUInt64LE(8));
998
+ if (expiresAt <= Date.now()) return null;
999
+ try { decrypted = this.decryptV2(raw.subarray(V2_HEADER_LEN), key); } catch { return null; }
1000
+ } else {
1001
+ // V1 / legacy unencrypted — backward compat
1002
+ try { decrypted = this.decrypt(raw); } catch { return null; }
1003
+ }
1004
+
1005
+ const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? 'brotli');
1006
+ const payload = this.codec.decode(uncompressed) as DiskPayload;
1007
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
1008
+ if (payload.entry.revision !== undefined && !isWriteRevision(payload.entry.revision)) return null;
1009
+ if (payload.entry.expiresAt <= Date.now()) return null;
1010
+
1011
+ const entry = payload.entry;
1012
+ if (entry.data instanceof Uint8Array) entry.data = Buffer.from(entry.data);
1013
+
1014
+ this.opts.logger.debug('DiskTier: hit (→L1)', { key: key.slice(0, 50), ageMs: Date.now() - payload.writtenAt });
1015
+ return entry;
1016
+ }
1017
+
1018
+ /** Synchronously fence queued/running saves while leaving filesystem cleanup deferred. */
1019
+ invalidate(key: string): void {
1020
+ this.pendingSaves.delete(key);
1021
+ this.invalidatedKeys.add(key);
1022
+ }
1023
+
1024
+ /** Cancel and remove only the observed write; newer pending or stored spills survive. */
1025
+ deleteIfRevision(key: string, revision: string): void {
1026
+ if (this.closed || !isWriteRevision(revision)) return;
1027
+ if (this.pendingSaves.get(key)?.revision === revision) this.pendingSaves.delete(key);
738
1028
  const hash = this.keyToHash(key);
739
- let filePath: string | null;
1029
+ const suffix = this.revisionSuffix(revision);
1030
+ const files = new Set(this.findFilePaths(hash));
740
1031
  if (this._db) {
741
1032
  const row = this._stmtSelect!.get(hash) as { file_path: string } | undefined;
742
- filePath = row?.file_path ?? null;
1033
+ if (row?.file_path.endsWith(suffix)) {
1034
+ files.add(row.file_path);
1035
+ this._stmtDelete!.run(hash);
1036
+ }
1037
+ }
1038
+ for (const file of files) if (file.endsWith(suffix)) this.removeFile(file);
1039
+ }
1040
+
1041
+ /** Delete all versions; deferred cleanup must not cancel a newer save. */
1042
+ delete(key: string, invalidatedOnly = false): void {
1043
+ if (invalidatedOnly && (!this.invalidatedKeys.has(key) || this.pendingSaves.has(key))) return;
1044
+ if (!invalidatedOnly) this.pendingSaves.delete(key);
1045
+ const hash = this.keyToHash(key);
1046
+ const files = new Set(this.findFilePaths(hash));
1047
+ if (this._db) {
1048
+ const row = this._stmtSelect!.get(hash) as { file_path: string } | undefined;
1049
+ if (row?.file_path) files.add(row.file_path);
743
1050
  this._stmtDelete!.run(hash);
744
- } else {
745
- filePath = this.findFilePath(hash);
746
1051
  }
747
- if (!filePath) return;
748
- try {
749
- const stat = fs.statSync(filePath);
750
- fs.unlinkSync(filePath);
751
- this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
752
- this.fileCount = Math.max(0, this.fileCount - 1);
753
- } catch { /* ok */ }
1052
+ for (const file of files) this.removeFile(file);
1053
+ this.invalidatedKeys.delete(key);
754
1054
  }
755
1055
 
756
1056
  /** Purge all expired entries. Returns number deleted. */
@@ -793,8 +1093,8 @@ export class DiskTier {
793
1093
  }
794
1094
 
795
1095
  // ── V3 fast path: expiresAt encoded in filename, zero file I/O for live entries
796
- if (filename.length === 77 && filename[64] === '_') {
797
- const expiresAt = parseInt(filename.slice(65), 16);
1096
+ if (filename.length >= 77 && filename[64] === '_') {
1097
+ const expiresAt = parseInt(filename.slice(65, 77), 16);
798
1098
  if (expiresAt <= now) {
799
1099
  try {
800
1100
  const sz = fs.statSync(filePath).size;
@@ -912,8 +1212,8 @@ export class DiskTier {
912
1212
  continue;
913
1213
  }
914
1214
 
915
- if (file.length === 77 && file[64] === '_') {
916
- const expiresAt = parseInt(file.slice(65), 16);
1215
+ if (file.length >= 77 && file[64] === '_') {
1216
+ const expiresAt = parseInt(file.slice(65, 77), 16);
917
1217
  if (expiresAt <= now) {
918
1218
  const fp = path.join(orphanBucketP, file);
919
1219
  try {
@@ -954,8 +1254,8 @@ export class DiskTier {
954
1254
 
955
1255
  // ── V3 fast path: expiresAt encoded in filename, zero file I/O for live entries
956
1256
  // Filename format: {sha256-64-hex}_{expiresAt-12-hex} = 77 chars total.
957
- if (file.length === 77 && file[64] === '_') {
958
- const expiresAt = parseInt(file.slice(65), 16);
1257
+ if (file.length >= 77 && file[64] === '_') {
1258
+ const expiresAt = parseInt(file.slice(65, 77), 16);
959
1259
  if (expiresAt <= now) {
960
1260
  const filePath = path.join(bucketPath, file);
961
1261
  try {
@@ -1019,6 +1319,9 @@ export class DiskTier {
1019
1319
 
1020
1320
  /** Delete every file in the disk cache. Returns the count deleted. */
1021
1321
  clear(): number {
1322
+ this.epoch++;
1323
+ this.pendingSaves.clear();
1324
+ this.invalidatedKeys.clear();
1022
1325
  this.ensureDir();
1023
1326
  if (!this.dirReady) return 0;
1024
1327
  let cleared = 0;
@@ -1084,6 +1387,7 @@ export class DiskTier {
1084
1387
  * yielding to the event loop via setImmediate between chunks.
1085
1388
  */
1086
1389
  public async triggerChunkedPrune(): Promise<number> {
1390
+ if (this.closed) return 0;
1087
1391
  if (this._isPruning) return 0;
1088
1392
  this._isPruning = true;
1089
1393
  this._pruneRounds++;
@@ -1094,32 +1398,41 @@ export class DiskTier {
1094
1398
  const targetBytes = Math.floor(this.opts.maxBytes * 0.60);
1095
1399
 
1096
1400
  if (this._db && this._stmtPruneChunk) {
1097
- while (this.diskUsageBytes > targetBytes) {
1401
+ while (!this.closed && this.diskUsageBytes > targetBytes) {
1098
1402
  const rows = this._stmtPruneChunk.all() as Array<{ key_hash: string; file_path: string; size: number }>;
1099
1403
  if (!rows || rows.length === 0) break;
1404
+ let progress = 0;
1100
1405
 
1101
1406
  for (const row of rows) {
1407
+ let removed = false;
1102
1408
  try {
1103
1409
  fs.unlinkSync(row.file_path);
1104
- } catch { /* already gone */ }
1410
+ removed = true;
1411
+ } catch (error) {
1412
+ // Only ENOENT proves the indexed file no longer occupies storage.
1413
+ if ((error as { code?: string }).code !== 'ENOENT') continue;
1414
+ }
1415
+ try { this._stmtDelete!.run(row.key_hash); }
1416
+ catch { continue; } // Keep conservative accounting if index cleanup fails.
1105
1417
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
1106
1418
  this.fileCount = Math.max(0, this.fileCount - 1);
1107
- this._entriesPruned++;
1108
- prunedInThisRound++;
1109
- try { this._stmtDelete!.run(row.key_hash); } catch { /* ok */ }
1419
+ progress++;
1420
+ if (removed) { this._entriesPruned++; prunedInThisRound++; }
1110
1421
 
1111
1422
  if (this.diskUsageBytes <= targetBytes) break;
1112
1423
  }
1113
1424
 
1425
+ if (progress === 0) break; // Permission/read-only errors must not create a retry loop.
1114
1426
  if (this.diskUsageBytes > targetBytes) {
1115
1427
  await new Promise<void>(resolve => setImmediate(resolve));
1116
1428
  }
1117
1429
  }
1118
1430
  } else {
1119
- while (this.diskUsageBytes > targetBytes) {
1431
+ while (!this.closed && this.diskUsageBytes > targetBytes) {
1120
1432
  const files = this.walkCacheFiles();
1121
1433
  if (files.length === 0) break;
1122
1434
  const chunk = files.slice(0, 500);
1435
+ let progress = 0;
1123
1436
 
1124
1437
  for (const filePath of chunk) {
1125
1438
  try {
@@ -1129,11 +1442,13 @@ export class DiskTier {
1129
1442
  this.fileCount = Math.max(0, this.fileCount - 1);
1130
1443
  this._entriesPruned++;
1131
1444
  prunedInThisRound++;
1445
+ progress++;
1132
1446
  } catch { /* already gone */ }
1133
1447
 
1134
1448
  if (this.diskUsageBytes <= targetBytes) break;
1135
1449
  }
1136
1450
 
1451
+ if (progress === 0) break;
1137
1452
  if (this.diskUsageBytes > targetBytes) {
1138
1453
  await new Promise<void>(resolve => setImmediate(resolve));
1139
1454
  }
@@ -1207,6 +1522,31 @@ export class DiskTier {
1207
1522
  return this.diskQueue;
1208
1523
  }
1209
1524
 
1525
+ /** Wait for admitted physical spill tasks, including work past its caller timeout. */
1526
+ async drain(timeoutMs = 8_000): Promise<boolean> {
1527
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0) throw new Error('Drain timeout must be finite and non-negative');
1528
+ const deadline = performance.now() + timeoutMs;
1529
+ while (true) {
1530
+ const remaining = Math.max(0, deadline - performance.now());
1531
+ if (!await this.diskQueue.drain(remaining)) return false;
1532
+ // Slot release precedes save() reservation cleanup in its continuation.
1533
+ if (this.pendingSaves.size === 0 && this.diskQueue.getStats().activeWrites === 0 &&
1534
+ this.diskQueue.getStats().pendingWrites === 0) return true;
1535
+ if (performance.now() >= deadline) return false;
1536
+ await new Promise<void>(resolve => setImmediate(resolve));
1537
+ }
1538
+ }
1539
+
1540
+ /** Wait unboundedly for physical writes and their reservation cleanup before closing the index. */
1541
+ async whenIdle(): Promise<void> {
1542
+ while (true) {
1543
+ await this.diskQueue.whenIdle();
1544
+ await new Promise<void>(resolve => setImmediate(resolve));
1545
+ if (this.pendingSaves.size === 0 && this.pendingBuckets.size === 0 &&
1546
+ this.diskQueue.getStats().activeWrites === 0 && this.diskQueue.getStats().pendingWrites === 0) return;
1547
+ }
1548
+ }
1549
+
1210
1550
  /** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
1211
1551
  get indexMode(): 'sqlite' | 'file-only' {
1212
1552
  return this._db ? 'sqlite' : 'file-only';
@@ -1214,6 +1554,12 @@ export class DiskTier {
1214
1554
 
1215
1555
  /** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
1216
1556
  close(): void {
1557
+ this.closed = true;
1558
+ this.epoch++;
1559
+ this.pendingSaves.clear();
1560
+ this.invalidatedKeys.clear();
1561
+ this.readyBuckets.clear();
1562
+ this.pendingBuckets.clear();
1217
1563
  if (this._db) {
1218
1564
  try { this._db.close(); } catch { /* ok */ }
1219
1565
  this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete =