tricache 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-pJ-nFcVj.d.ts → cache-service-B108FzER.d.ts} +63 -3
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-26GCO3UU.js → cache-service-GYPZFB7O.js} +2 -2
  5. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  6. package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
  7. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  8. package/dist/chunk-OYDU3SMI.js +89 -0
  9. package/dist/{chunk-VXFTFZ5N.js → chunk-VNRDL5RA.js} +117 -138
  10. package/dist/{chunk-7SZSQS55.js → chunk-WYF7NOAT.js} +1831 -759
  11. package/dist/cli.cjs +1757 -777
  12. package/dist/cli.d.cts +12 -0
  13. package/dist/cli.js +27 -6
  14. package/dist/dashboard/index.cjs +111 -29
  15. package/dist/dashboard/index.d.cts +185 -0
  16. package/dist/dashboard/index.d.ts +5 -3
  17. package/dist/dashboard/index.js +1 -1
  18. package/dist/drizzle/index.cjs +1757 -773
  19. package/dist/drizzle/index.d.cts +46 -0
  20. package/dist/drizzle/index.d.ts +2 -2
  21. package/dist/drizzle/index.js +1 -1
  22. package/dist/edge/index.cjs +280 -153
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +254 -147
  26. package/dist/hono/index.cjs +1805 -793
  27. package/dist/hono/index.d.cts +93 -0
  28. package/dist/hono/index.d.ts +7 -5
  29. package/dist/hono/index.js +16 -9
  30. package/dist/{hono-DuNvciyq.d.ts → hono-3rDMYVtY.d.ts} +23 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1946 -842
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +137 -57
  36. package/dist/index.cjs +2073 -937
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +40 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1849 -806
  42. package/dist/nestjs/index.d.cts +285 -0
  43. package/dist/nestjs/index.d.ts +103 -30
  44. package/dist/nestjs/index.js +115 -32
  45. package/dist/next/index.cjs +1913 -887
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +174 -107
  49. package/dist/prisma/index.cjs +11 -1
  50. package/dist/prisma/index.d.cts +62 -0
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +11 -1
  53. package/dist/serialize-worker.d.cts +2 -0
  54. package/dist/{types-5HXqBfAf.d.ts → types-BA4pz1A0.d.cts} +26 -9
  55. package/dist/types-BA4pz1A0.d.ts +1519 -0
  56. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  57. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  58. package/package.json +96 -36
  59. package/src/adapters/auto-pipeliner.ts +107 -24
  60. package/src/adapters/node-redis.ts +123 -25
  61. package/src/cache-service.ts +1238 -659
  62. package/src/cli.ts +24 -6
  63. package/src/cross-region.ts +21 -3
  64. package/src/dashboard/handler.ts +26 -6
  65. package/src/dashboard/html.ts +35 -10
  66. package/src/dashboard/index.ts +35 -13
  67. package/src/dashboard/types.ts +3 -1
  68. package/src/disk-tier.ts +171 -65
  69. package/src/edge/cache.ts +202 -129
  70. package/src/edge/hono.ts +23 -6
  71. package/src/edge/types.ts +2 -0
  72. package/src/hono/index.ts +19 -9
  73. package/src/http/express.ts +110 -26
  74. package/src/http/fastify.ts +38 -28
  75. package/src/http/utils.ts +54 -20
  76. package/src/ipc-telemetry.ts +35 -9
  77. package/src/nestjs/decorators.ts +1 -1
  78. package/src/nestjs/index.ts +2 -0
  79. package/src/nestjs/keyv-adapter.ts +68 -0
  80. package/src/nestjs/tricache.module.ts +13 -11
  81. package/src/nestjs/tricache.store.ts +51 -20
  82. package/src/nestjs/types.ts +29 -15
  83. package/src/next/cache-handler.ts +132 -57
  84. package/src/next/index.ts +1 -0
  85. package/src/next/isr-handler.ts +1 -4
  86. package/src/next/types.ts +21 -0
  87. package/src/prisma/index.ts +12 -1
  88. package/src/smart-memory-cache.ts +65 -27
  89. package/src/types.ts +27 -2
  90. package/src/utils/cgroup.ts +12 -0
  91. package/src/utils/deadline.ts +14 -0
  92. package/src/utils/diagnostics.ts +27 -0
  93. package/src/utils/redis-slot.ts +13 -0
  94. package/src/wasm/bloom-filter-wasm.ts +9 -4
  95. package/src/worker-pool.ts +17 -8
  96. package/src/wtiny-lfu.ts +20 -6
  97. package/dist/chunk-BQRURGGD.js +0 -60
package/src/disk-tier.ts CHANGED
@@ -39,7 +39,7 @@ export type { DiskBackpressureStats };
39
39
  */
40
40
  export class BoundedDiskQueue {
41
41
  private active = 0;
42
- private queue: Array<() => void> = [];
42
+ private queue: Array<(admitted: boolean) => void> = [];
43
43
  private spillsDropped = 0;
44
44
  private consecutiveFailures = 0;
45
45
  private circuitState: 'closed' | 'open' | 'half-open' = 'closed';
@@ -51,7 +51,27 @@ export class BoundedDiskQueue {
51
51
  private readonly writeTimeoutMs: number = 500,
52
52
  private readonly failureThreshold: number = 5,
53
53
  private readonly cooldownMs: number = 5000,
54
- ) {}
54
+ ) {
55
+ if (!Number.isInteger(maxConcurrent) || maxConcurrent < 1 || !Number.isInteger(maxPending) || maxPending < 0 ||
56
+ !Number.isFinite(writeTimeoutMs) || writeTimeoutMs <= 0 || !Number.isInteger(failureThreshold) || failureThreshold < 1 ||
57
+ !Number.isFinite(cooldownMs) || cooldownMs < 0) {
58
+ throw new Error('Disk queue limits and timeout must be finite positive values (pending/cooldown may be zero)');
59
+ }
60
+ }
61
+
62
+ get isSaturated(): boolean {
63
+ return this.active >= this.maxConcurrent && this.queue.length >= this.maxPending;
64
+ }
65
+
66
+ private releaseSlot(): void {
67
+ if (this.circuitState === 'open') {
68
+ for (const next of this.queue.splice(0)) next(false);
69
+ }
70
+ const next = this.queue.shift();
71
+ // Transfer the reservation so newly arriving calls cannot steal a queued slot.
72
+ if (next) next(true);
73
+ else this.active--;
74
+ }
55
75
 
56
76
  public async schedule<T>(task: () => Promise<T>): Promise<T | null> {
57
77
  const now = performance.now();
@@ -73,22 +93,30 @@ export class BoundedDiskQueue {
73
93
  return null;
74
94
  }
75
95
 
76
- if (this.queue.length >= this.maxPending) {
96
+ if (this.isSaturated) {
77
97
  this.spillsDropped++;
78
98
  return null; // Bounded memory queue: drop spill to preserve main thread
79
99
  }
80
100
 
81
101
  // Wait for slot in concurrency pool
82
102
  if (this.active >= this.maxConcurrent) {
83
- await new Promise<void>((resolve) => this.queue.push(resolve));
103
+ const admitted = await new Promise<boolean>((resolve) => this.queue.push(resolve));
104
+ if (!admitted) {
105
+ this.spillsDropped++;
106
+ return null;
107
+ }
108
+ } else {
109
+ this.active++;
84
110
  }
85
-
86
- this.active++;
87
111
  let timeoutId: NodeJS.Timeout | null = null;
112
+ const work = Promise.resolve().then(task);
113
+ // A caller timeout does not cancel filesystem I/O. Release its physical slot
114
+ // only when the underlying operation settles, including on late failure.
115
+ void work.then(() => this.releaseSlot(), () => this.releaseSlot());
88
116
 
89
117
  try {
90
118
  const result = await Promise.race([
91
- task(),
119
+ work,
92
120
  new Promise<never>((_, reject) => {
93
121
  timeoutId = setTimeout(
94
122
  () => reject(new Error(`Disk write exceeded timeout of ${this.writeTimeoutMs}ms`)),
@@ -110,14 +138,12 @@ export class BoundedDiskQueue {
110
138
  if (this.consecutiveFailures >= this.failureThreshold || this.circuitState === 'half-open') {
111
139
  this.circuitState = 'open';
112
140
  this.lastStateChangeMonotonic = performance.now();
141
+ for (const next of this.queue.splice(0)) next(false);
113
142
  }
114
143
  this.spillsDropped++;
115
144
  return null;
116
145
  } finally {
117
146
  if (timeoutId) clearTimeout(timeoutId);
118
- this.active--;
119
- const next = this.queue.shift();
120
- if (next) next();
121
147
  }
122
148
  }
123
149
 
@@ -267,6 +293,13 @@ export class DiskTier {
267
293
  private diskUsageBytes = 0;
268
294
  private usageCounted = false;
269
295
  private fileCount = 0; // maintained in-memory; avoids walkCacheFiles() in stats
296
+ private reservedBytes = 0;
297
+ private reservedFiles = 0;
298
+ private saveSequence = 0;
299
+ private epoch = 0;
300
+ private readonly pendingSaves = new Map<string, { token: symbol; setAt: number }>();
301
+ private closed = false;
302
+ private readonly invalidatedKeys = new Set<string>();
270
303
  /** Next bucket index (0–255) for the staggered janitor wheel. */
271
304
  private _nextJanitorBucket = 0;
272
305
 
@@ -305,6 +338,7 @@ export class DiskTier {
305
338
  // ── Helpers ───────────────────────────────────────────────────────────────
306
339
 
307
340
  private ensureDir(): void {
341
+ if (this.closed) return;
308
342
  if (this.dirReady) return;
309
343
  try {
310
344
  fs.mkdirSync(this.opts.dir, { recursive: true, mode: 0o700 });
@@ -427,8 +461,25 @@ export class DiskTier {
427
461
  *
428
462
  * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
429
463
  */
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')}`);
464
+ private hashToWritePath(hash: string, expiresAt: number, setAt?: number): string {
465
+ const expiry = Math.floor(expiresAt).toString(16).padStart(12, '0');
466
+ if (setAt === undefined) return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}`);
467
+ const written = Math.floor(setAt).toString(16).padStart(12, '0');
468
+ const sequence = (++this.saveSequence).toString(16).padStart(12, '0');
469
+ return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}_${written}_${sequence}_${crypto.randomBytes(6).toString('hex')}`);
470
+ }
471
+
472
+ private findFilePaths(hash: string): string[] {
473
+ const bucket = path.join(this.opts.dir, hash.slice(0, 2));
474
+ try {
475
+ return fs.readdirSync(bucket).filter(file => !file.endsWith('.tmp') && (file === hash || file.startsWith(hash + '_')))
476
+ .map(file => path.join(bucket, file));
477
+ } catch { return []; }
478
+ }
479
+
480
+ private fileWrittenAt(file: string): number {
481
+ const parts = path.basename(file).split('_');
482
+ return parts.length >= 4 ? parseInt(parts[2], 16) : fs.statSync(file).mtimeMs;
432
483
  }
433
484
 
434
485
  /**
@@ -438,20 +489,30 @@ export class DiskTier {
438
489
  * Returns null when the bucket dir does not exist or the key is absent.
439
490
  */
440
491
  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;
492
+ let match: string | null = null;
493
+ let newest = -Infinity;
494
+ let sequence = -1;
495
+ for (const file of this.findFilePaths(hash)) {
496
+ try {
497
+ const written = this.fileWrittenAt(file);
498
+ const order = parseInt(path.basename(file).split('_')[3] ?? '0', 16);
499
+ if (written > newest || (written === newest && order > sequence)) {
500
+ match = file;
501
+ newest = written;
502
+ sequence = order;
503
+ }
504
+ } catch { /* raced with deletion */ }
452
505
  }
453
- if (!match) return null;
454
- return path.join(bucketPath, match);
506
+ return match;
507
+ }
508
+
509
+ private removeFile(filePath: string): void {
510
+ try {
511
+ const size = fs.statSync(filePath).size;
512
+ fs.unlinkSync(filePath);
513
+ this.diskUsageBytes = Math.max(0, this.diskUsageBytes - size);
514
+ this.fileCount = Math.max(0, this.fileCount - 1);
515
+ } catch { /* already gone or locked */ }
455
516
  }
456
517
 
457
518
  /**
@@ -530,6 +591,7 @@ export class DiskTier {
530
591
  * so the Node.js event loop is never stalled waiting for disk I/O.
531
592
  */
532
593
  async save(key: string, entry: DiskCacheEntry): Promise<void> {
594
+ if (this.closed || this.diskQueue.isSaturated) return;
533
595
  if (this.isForbidden(key)) return;
534
596
  if (entry.expiresAt <= Date.now()) return;
535
597
 
@@ -543,7 +605,7 @@ export class DiskTier {
543
605
  }
544
606
 
545
607
  // 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) {
608
+ if (this._hostVolumeLowSpace || this._isPruning || this.diskUsageBytes + this.reservedBytes >= this.opts.maxBytes) {
547
609
  this._spillsShedTotal++;
548
610
  return;
549
611
  }
@@ -556,11 +618,12 @@ export class DiskTier {
556
618
  // ── Synchronous phase: pack + encrypt (CPU-only, no I/O) ─────────────
557
619
  let final: Buffer;
558
620
  try {
621
+ const { value: _value, ...storedEntry } = entry as DiskCacheEntry & { value?: unknown };
559
622
  const payload: DiskPayload = {
560
623
  version: DISK_TIER_VERSION,
561
624
  key,
562
625
  entry: {
563
- ...entry,
626
+ ...storedEntry,
564
627
  data: entry.data instanceof Uint8Array
565
628
  ? Buffer.from(entry.data)
566
629
  : entry.data,
@@ -578,8 +641,9 @@ export class DiskTier {
578
641
  // to check expiry with a 16-byte partial read — no decrypt or unpack needed.
579
642
  const header = Buffer.allocUnsafe(V2_HEADER_LEN);
580
643
  DISK_MAGIC_V2.copy(header, 0);
581
- header.writeBigUInt64LE(BigInt(entry.expiresAt), 8);
644
+ header.writeBigUInt64LE(BigInt(Math.floor(entry.expiresAt)), 8);
582
645
  final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
646
+ if (final.length > this.opts.entryMaxBytes || this.diskUsageBytes + this.reservedBytes + final.length > this.opts.maxBytes) return;
583
647
  } catch (err) {
584
648
  this.opts.logger.debug('DiskTier: pack/encrypt failed', { key: key.slice(0, 50), error: (err as Error).message });
585
649
  return;
@@ -587,21 +651,42 @@ export class DiskTier {
587
651
 
588
652
  // ── Async phase: mkdir + write to same-dir tmp + atomic rename ────
589
653
  const hash = this.keyToHash(key);
590
- const filePath = this.hashToWritePath(hash, entry.expiresAt);
654
+ const setAt = entry.setAt ?? Date.now();
655
+ if ((this.pendingSaves.get(key)?.setAt ?? 0) > setAt) return;
656
+ const filePath = this.hashToWritePath(hash, entry.expiresAt, setAt);
591
657
  const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString('hex')}.tmp`;
658
+ const token = Symbol(key);
659
+ const epoch = this.epoch;
660
+ this.pendingSaves.set(key, { token, setAt });
661
+ const current = () => !this.closed && this.epoch === epoch && this.pendingSaves.get(key)?.token === token;
662
+ let started = false;
663
+ let released = false;
664
+ let accounted = false;
665
+ const releaseReservation = () => {
666
+ if (released) return;
667
+ released = true;
668
+ this.reservedBytes = Math.max(0, this.reservedBytes - final.length);
669
+ this.reservedFiles = Math.max(0, this.reservedFiles - 1);
670
+ if (this.pendingSaves.get(key)?.token === token) this.pendingSaves.delete(key);
671
+ };
592
672
 
593
673
  // Optimistically reserve quota before queuing so concurrent spills respect the cap
594
- this.diskUsageBytes += final.length;
595
- this.fileCount++;
674
+ this.reservedBytes += final.length;
675
+ this.reservedFiles++;
596
676
 
597
677
  if (this.diskUsageBytes >= this.opts.maxBytes * 0.80 && !this._isPruning) {
598
678
  void this.triggerChunkedPrune();
599
679
  }
600
680
 
601
681
  const result = await this.diskQueue.schedule(async () => {
682
+ started = true;
602
683
  try {
684
+ if (!current()) return false;
685
+ const previous = this.findFilePath(hash);
686
+ if (previous && this.fileWrittenAt(previous) > setAt) return false;
603
687
  await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
604
688
  await fs.promises.writeFile(tmpPath, final, { mode: 0o600 });
689
+ if (!current()) return false;
605
690
 
606
691
  // Atomic rename with micro-retry loop for Windows NTFS handle release
607
692
  try {
@@ -616,6 +701,20 @@ export class DiskTier {
616
701
  }
617
702
  }
618
703
 
704
+ if (!current()) {
705
+ try { await fs.promises.unlink(filePath); } catch { /* already removed */ }
706
+ return false;
707
+ }
708
+
709
+ // Remove all superseded versions, not just the one with the largest TTL.
710
+ for (const previousPath of this.findFilePaths(hash)) {
711
+ if (previousPath !== filePath) this.removeFile(previousPath);
712
+ }
713
+ this.diskUsageBytes += final.length;
714
+ this.fileCount++;
715
+ accounted = true;
716
+ this.invalidatedKeys.delete(key);
717
+
619
718
  if (this._db) {
620
719
  const priority = typeof entry.priority === 'number' ? entry.priority : 2;
621
720
  const lastAccess = typeof entry.lastAccess === 'number' ? entry.lastAccess : Date.now();
@@ -625,23 +724,25 @@ export class DiskTier {
625
724
  return true;
626
725
  } catch (err) {
627
726
  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 */ }
727
+ if (accounted) this.removeFile(filePath);
631
728
  this.opts.logger.debug('DiskTier: save failed', { key: key.slice(0, 50), error: (err as Error).message });
632
729
  throw err;
730
+ } finally {
731
+ try { await fs.promises.unlink(tmpPath); } catch { /* renamed, removed, or never created */ }
732
+ releaseReservation();
733
+ if (this.invalidatedKeys.has(key) && !this.pendingSaves.has(key)) this.delete(key, true);
633
734
  }
634
735
  });
635
736
 
636
- if (result === null) {
737
+ if (result === null && !started) {
637
738
  // 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);
739
+ releaseReservation();
640
740
  }
641
741
  }
642
742
 
643
743
  /** Load a key from disk, or return null on miss/expiry/corruption. */
644
744
  load(key: string): DiskCacheEntry | null {
745
+ if (this.invalidatedKeys.has(key) || this.closed) return null;
645
746
  if (this.isForbidden(key)) return null;
646
747
  this.ensureDir();
647
748
  if (!this.dirReady) return null;
@@ -674,8 +775,8 @@ export class DiskTier {
674
775
  // opening the file when the entry is already stale.
675
776
  if (!this._db) {
676
777
  const filename = path.basename(filePath);
677
- if (filename.length === 77 && filename[64] === '_') {
678
- const expiresAt = parseInt(filename.slice(65), 16);
778
+ if (filename.length >= 77 && filename[64] === '_') {
779
+ const expiresAt = parseInt(filename.slice(65, 77), 16);
679
780
  if (expiresAt <= Date.now()) {
680
781
  try {
681
782
  const sz = fs.statSync(filePath).size;
@@ -698,11 +799,7 @@ export class DiskTier {
698
799
 
699
800
  const raw = fs.readFileSync(filePath);
700
801
  // 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 */ }
802
+ for (const storedPath of this.findFilePaths(hash)) this.removeFile(storedPath);
706
803
  if (this._db) this._stmtDelete!.run(hash);
707
804
 
708
805
  let decrypted: Buffer;
@@ -733,24 +830,25 @@ export class DiskTier {
733
830
  }
734
831
  }
735
832
 
736
- /** Explicitly delete a key from disk (cache invalidation). */
737
- delete(key: string): void {
833
+ /** Synchronously fence queued/running saves while leaving filesystem cleanup deferred. */
834
+ invalidate(key: string): void {
835
+ this.pendingSaves.delete(key);
836
+ this.invalidatedKeys.add(key);
837
+ }
838
+
839
+ /** Delete all versions; deferred cleanup must not cancel a newer save. */
840
+ delete(key: string, invalidatedOnly = false): void {
841
+ if (invalidatedOnly && (!this.invalidatedKeys.has(key) || this.pendingSaves.has(key))) return;
842
+ if (!invalidatedOnly) this.pendingSaves.delete(key);
738
843
  const hash = this.keyToHash(key);
739
- let filePath: string | null;
844
+ const files = new Set(this.findFilePaths(hash));
740
845
  if (this._db) {
741
846
  const row = this._stmtSelect!.get(hash) as { file_path: string } | undefined;
742
- filePath = row?.file_path ?? null;
847
+ if (row?.file_path) files.add(row.file_path);
743
848
  this._stmtDelete!.run(hash);
744
- } else {
745
- filePath = this.findFilePath(hash);
746
849
  }
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 */ }
850
+ for (const file of files) this.removeFile(file);
851
+ this.invalidatedKeys.delete(key);
754
852
  }
755
853
 
756
854
  /** Purge all expired entries. Returns number deleted. */
@@ -793,8 +891,8 @@ export class DiskTier {
793
891
  }
794
892
 
795
893
  // ── 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);
894
+ if (filename.length >= 77 && filename[64] === '_') {
895
+ const expiresAt = parseInt(filename.slice(65, 77), 16);
798
896
  if (expiresAt <= now) {
799
897
  try {
800
898
  const sz = fs.statSync(filePath).size;
@@ -912,8 +1010,8 @@ export class DiskTier {
912
1010
  continue;
913
1011
  }
914
1012
 
915
- if (file.length === 77 && file[64] === '_') {
916
- const expiresAt = parseInt(file.slice(65), 16);
1013
+ if (file.length >= 77 && file[64] === '_') {
1014
+ const expiresAt = parseInt(file.slice(65, 77), 16);
917
1015
  if (expiresAt <= now) {
918
1016
  const fp = path.join(orphanBucketP, file);
919
1017
  try {
@@ -954,8 +1052,8 @@ export class DiskTier {
954
1052
 
955
1053
  // ── V3 fast path: expiresAt encoded in filename, zero file I/O for live entries
956
1054
  // 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);
1055
+ if (file.length >= 77 && file[64] === '_') {
1056
+ const expiresAt = parseInt(file.slice(65, 77), 16);
959
1057
  if (expiresAt <= now) {
960
1058
  const filePath = path.join(bucketPath, file);
961
1059
  try {
@@ -1019,6 +1117,9 @@ export class DiskTier {
1019
1117
 
1020
1118
  /** Delete every file in the disk cache. Returns the count deleted. */
1021
1119
  clear(): number {
1120
+ this.epoch++;
1121
+ this.pendingSaves.clear();
1122
+ this.invalidatedKeys.clear();
1022
1123
  this.ensureDir();
1023
1124
  if (!this.dirReady) return 0;
1024
1125
  let cleared = 0;
@@ -1084,6 +1185,7 @@ export class DiskTier {
1084
1185
  * yielding to the event loop via setImmediate between chunks.
1085
1186
  */
1086
1187
  public async triggerChunkedPrune(): Promise<number> {
1188
+ if (this.closed) return 0;
1087
1189
  if (this._isPruning) return 0;
1088
1190
  this._isPruning = true;
1089
1191
  this._pruneRounds++;
@@ -1094,7 +1196,7 @@ export class DiskTier {
1094
1196
  const targetBytes = Math.floor(this.opts.maxBytes * 0.60);
1095
1197
 
1096
1198
  if (this._db && this._stmtPruneChunk) {
1097
- while (this.diskUsageBytes > targetBytes) {
1199
+ while (!this.closed && this.diskUsageBytes > targetBytes) {
1098
1200
  const rows = this._stmtPruneChunk.all() as Array<{ key_hash: string; file_path: string; size: number }>;
1099
1201
  if (!rows || rows.length === 0) break;
1100
1202
 
@@ -1116,7 +1218,7 @@ export class DiskTier {
1116
1218
  }
1117
1219
  }
1118
1220
  } else {
1119
- while (this.diskUsageBytes > targetBytes) {
1221
+ while (!this.closed && this.diskUsageBytes > targetBytes) {
1120
1222
  const files = this.walkCacheFiles();
1121
1223
  if (files.length === 0) break;
1122
1224
  const chunk = files.slice(0, 500);
@@ -1214,6 +1316,10 @@ export class DiskTier {
1214
1316
 
1215
1317
  /** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
1216
1318
  close(): void {
1319
+ this.closed = true;
1320
+ this.epoch++;
1321
+ this.pendingSaves.clear();
1322
+ this.invalidatedKeys.clear();
1217
1323
  if (this._db) {
1218
1324
  try { this._db.close(); } catch { /* ok */ }
1219
1325
  this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete =