tricache 0.5.1 → 0.6.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.
@@ -24,6 +24,10 @@ import { WasmBloomFilter } from './wasm/bloom-filter-wasm';
24
24
 
25
25
  /** Fraction of candidates evicted in one pass when a limit is exceeded */
26
26
  const EVICTION_BATCH_PERCENT = 0.2;
27
+ /** Reservoir sample window for smartEvict() — Redis-style. */
28
+ const EVICTION_SAMPLE = 16;
29
+ /** Number of lowest-scored candidates evicted per smartEvict() call. */
30
+ const EVICT_COUNT = Math.max(1, Math.ceil(EVICTION_SAMPLE * EVICTION_BATCH_PERCENT)); // 4
27
31
 
28
32
  // ─── Pure-JS Bloom filter fallback ───────────────────────────────────────────
29
33
 
@@ -242,12 +246,14 @@ function globMatch(pattern: string, key: string): boolean {
242
246
  // ─── SmartMemoryCache ─────────────────────────────────────────────────────────
243
247
 
244
248
  export interface SmartMemoryCacheOptions {
245
- maxBytes: number;
246
- maxEntries: number;
247
- categories: Record<string, CategoryLimit>;
248
- diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
249
- onEviction?: (key: string, reason: EvictionReason) => void;
250
- logger: ILogger;
249
+ maxBytes: number;
250
+ maxEntries: number;
251
+ categories: Record<string, CategoryLimit>;
252
+ diskSpill?: (key: string, entry: SmartCacheEntry) => void | Promise<void>;
253
+ onEviction?: (key: string, reason: EvictionReason) => void;
254
+ logger: ILogger;
255
+ /** Fraction of maxEntries / maxBytes at which proactive eviction fires (default 0.9). */
256
+ evictionWatermark?: number;
251
257
  }
252
258
 
253
259
  export class SmartMemoryCache {
@@ -271,6 +277,18 @@ export class SmartMemoryCache {
271
277
  /** Counts every _delete() call — used to trigger bloom rebuild from ALL deletion paths. */
272
278
  private _bloomDirtyCount = 0;
273
279
 
280
+ /**
281
+ * Pre-allocated eviction candidate pools — reused across every smartEvict() call to
282
+ * eliminate per-call heap pressure. Each slot holds a mutable {key, score} record
283
+ * that is overwritten in-place rather than replaced with a new object literal.
284
+ * Safe because JS is single-threaded: smartEvict() completes synchronously before
285
+ * any other code can observe the pool state.
286
+ */
287
+ private readonly _evictPool: Array<{ key: string; score: number }> =
288
+ Array.from({ length: EVICTION_SAMPLE }, () => ({ key: '', score: 0 }));
289
+ private readonly _evictGPool: Array<{ key: string; score: number }> =
290
+ Array.from({ length: EVICTION_SAMPLE }, () => ({ key: '', score: 0 }));
291
+
274
292
  constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>) {
275
293
  this.opts = opts;
276
294
  this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
@@ -342,8 +360,9 @@ export class SmartMemoryCache {
342
360
  // capacity become uncommon. Both dimensions are guarded so that
343
361
  // large-payload workloads (where maxBytes is the binding constraint)
344
362
  // benefit equally alongside entry-count-bound workloads.
345
- const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * 0.9);
346
- const byteWatermark = this.totalSize + neededSize >= Math.floor(this.opts.maxBytes * 0.9);
363
+ const wm = this.opts.evictionWatermark ?? 0.9;
364
+ const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * wm);
365
+ const byteWatermark = this.totalSize + neededSize >= Math.floor(this.opts.maxBytes * wm);
347
366
  if (entryWatermark || byteWatermark) {
348
367
  this.smartEvict(category, false);
349
368
  }
@@ -396,16 +415,15 @@ export class SmartMemoryCache {
396
415
 
397
416
  private smartEvict(targetCat: string, catOvf: boolean): void {
398
417
  const now = Date.now();
399
- const SAMPLE = 16; // Redis-style sample window
400
- const EVICT = Math.max(1, Math.ceil(SAMPLE * EVICTION_BATCH_PERCENT)); // ~4
401
-
402
- const pool: Array<{ key: string; score: number }> = [];
418
+ const pool = this._evictPool;
419
+ const gPool = this._evictGPool;
420
+ let poolLen = 0;
403
421
 
404
422
  if (catOvf) {
405
423
  // Phase 1 — O(catSize) category-local reservoir sample.
406
424
  // Uses the categoryKeys index to iterate only the overflowing category's keys,
407
425
  // avoiding an O(N) scan of the entire cache. Guarantees at least
408
- // min(catSize, EVICT) entries from the overflowing category in the pool so
426
+ // min(catSize, EVICT_COUNT) entries from the overflowing category in the pool so
409
427
  // the priority score ordering is always deterministic in practice.
410
428
  const catKeySet = this.categoryKeys.get(targetCat);
411
429
  if (catKeySet) {
@@ -415,44 +433,59 @@ export class SmartMemoryCache {
415
433
  if (!entry || (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now)) continue;
416
434
  catSeen++;
417
435
  const s = this.score(entry, 100, now, key);
418
- if (pool.length < EVICT) {
419
- pool.push({ key, score: s });
436
+ if (poolLen < EVICT_COUNT) {
437
+ pool[poolLen].key = key; pool[poolLen].score = s; poolLen++;
420
438
  } else {
421
439
  const j = Math.floor(Math.random() * catSeen);
422
- if (j < EVICT) pool[j] = { key, score: s };
440
+ if (j < EVICT_COUNT) { pool[j].key = key; pool[j].score = s; }
423
441
  }
424
442
  }
425
443
  }
426
444
  }
427
445
 
428
- // Phase 2 — global reservoir sample fills remaining SAMPLE-pool.length slots.
429
- // Skipped entirely when Phase 1 already collected a full EVICT-sized pool
430
- // (the common catOvf case — overflowing categories always have ≥ EVICT entries).
446
+ // Phase 2 — global reservoir sample fills remaining EVICTION_SAMPLE-poolLen slots.
447
+ // Skipped entirely when Phase 1 already collected a full EVICT_COUNT-sized pool
448
+ // (the common catOvf case — overflowing categories always have ≥ EVICT_COUNT entries).
431
449
  // Also the sole phase when !catOvf (global over-capacity, no preferred category).
432
- if (pool.length < EVICT) {
433
- const remaining = SAMPLE - pool.length;
450
+ if (poolLen < EVICT_COUNT) {
451
+ const remaining = EVICTION_SAMPLE - poolLen;
434
452
  let globalSeen = 0;
435
- const globalPool: Array<{ key: string; score: number }> = [];
453
+ let gLen = 0;
436
454
  for (const [key, entry] of this.cache) {
437
455
  if (entry.priority === 4 /* CRITICAL */ && entry.expiresAt > now) continue;
438
456
  if (catOvf && this.getCategory(key) === targetCat) continue; // already sampled above
439
457
  globalSeen++;
440
458
  const s = this.score(entry, 0, now, key);
441
- if (globalPool.length < remaining) {
442
- globalPool.push({ key, score: s });
459
+ if (gLen < remaining) {
460
+ gPool[gLen].key = key; gPool[gLen].score = s; gLen++;
443
461
  } else {
444
462
  const j = Math.floor(Math.random() * globalSeen);
445
- if (j < remaining) globalPool[j] = { key, score: s };
463
+ if (j < remaining) { gPool[j].key = key; gPool[j].score = s; }
446
464
  }
447
465
  }
448
- pool.push(...globalPool);
466
+ // Manual merge — no spread, no new array
467
+ for (let i = 0; i < gLen; i++) {
468
+ pool[poolLen].key = gPool[i].key; pool[poolLen].score = gPool[i].score; poolLen++;
469
+ }
449
470
  }
450
471
 
451
- if (pool.length === 0) return;
472
+ if (poolLen === 0) return;
473
+
474
+ // Insertion sort — O(poolLen²) but poolLen ≤ EVICTION_SAMPLE=16 (max 256 comparisons).
475
+ // Faster than Array.sort() at this scale: no comparator closure call overhead,
476
+ // no timsort startup, no allocation. Sorts in-place within the pre-allocated pool.
477
+ for (let i = 1; i < poolLen; i++) {
478
+ const sk = pool[i].key, ss = pool[i].score;
479
+ let j = i - 1;
480
+ while (j >= 0 && pool[j].score > ss) {
481
+ pool[j + 1].key = pool[j].key; pool[j + 1].score = pool[j].score; j--;
482
+ }
483
+ pool[j + 1].key = sk; pool[j + 1].score = ss;
484
+ }
452
485
 
453
- // Sort only the tiny merged pool (O(SAMPLE * log(SAMPLE)) ≈ 64 comparisons)
454
- pool.sort((a, b) => a.score - b.score);
455
- for (const { key } of pool.slice(0, EVICT)) {
486
+ const toEvict = Math.min(EVICT_COUNT, poolLen);
487
+ for (let i = 0; i < toEvict; i++) {
488
+ const key = pool[i].key;
456
489
  const entry = this.cache.get(key);
457
490
  if (entry && this.opts.diskSpill) this.opts.diskSpill(key, entry); // L1.5 spill
458
491
  this._delete(key, 'capacity');
package/src/types.ts CHANGED
@@ -222,6 +222,19 @@ export interface CacheMetrics {
222
222
 
223
223
  l1: { entries: number; sizeBytes: number; maxBytes: number };
224
224
  disk: { files: number; sizeKB: number; maxKB: number };
225
+
226
+ /** Adaptive TTL statistics — present only when `adaptiveTtl` is enabled */
227
+ adaptiveTtl?: {
228
+ enabled: true;
229
+ /** Number of unique keys currently tracked in the latency ring buffers */
230
+ trackedKeys: number;
231
+ /**
232
+ * Top-20 slowest keys by p95 fetch latency, sorted descending.
233
+ * Keys are shown without the instance namespace prefix.
234
+ * Only keys with ≥ 5 recorded samples appear here.
235
+ */
236
+ slowestKeys: Array<{ key: string; p95Ms: number; adaptedTtlSec: number }>;
237
+ };
225
238
  }
226
239
 
227
240
  // ─── Configuration ───────────────────────────────────────────────────────────
@@ -249,6 +262,12 @@ export interface CacheOptions {
249
262
  l1MaxBytes?: number;
250
263
  /** Max total entries in L1. Default: 2000 */
251
264
  l1MaxEntries?: number;
265
+ /**
266
+ * Fraction of `l1MaxEntries` / `l1MaxBytes` at which proactive eviction fires
267
+ * before the hard limit is reached. Range: 0–1. Default: 0.9.
268
+ * Lower (e.g. 0.8) reduces GC pressure at the cost of slightly more eviction work.
269
+ */
270
+ l1EvictionWatermark?: number;
252
271
  /**
253
272
  * Per-category limits keyed by the key prefix (e.g. `'org:'`).
254
273
  * Merged over the built-in defaults.
@@ -515,4 +534,65 @@ export interface CacheOptions {
515
534
  * frozen: process.env.NODE_ENV !== 'production'
516
535
  */
517
536
  frozen?: boolean;
537
+
538
+ // ── Adaptive TTL ──────────────────────────────────────────────────────────
539
+
540
+ /**
541
+ * When `true`, tricache tracks per-key fetch latency in a rolling ring buffer
542
+ * and automatically derives an optimal TTL from the p95 fetch duration:
543
+ *
544
+ * ```
545
+ * adaptedTtl = clamp(p95LatencyMs × adaptiveTtlMultiplier, adaptiveTtlMin, adaptiveTtlMax)
546
+ * ```
547
+ *
548
+ * The caller-supplied `ttlSeconds` is used until at least 5 samples are collected
549
+ * for a key, then the library takes over TTL management autonomously.
550
+ *
551
+ * Expensive keys (slow DB queries) get cached longer; cheap keys stay close to
552
+ * their base TTL. Callers no longer need to reason about individual TTL values.
553
+ *
554
+ * Default: `false`.
555
+ */
556
+ adaptiveTtl?: boolean;
557
+
558
+ /**
559
+ * Minimum TTL (seconds) the adaptive tuner will ever assign.
560
+ * Guards against extremely fast fetches producing near-zero TTLs.
561
+ * Default: `10`.
562
+ */
563
+ adaptiveTtlMin?: number;
564
+
565
+ /**
566
+ * Maximum TTL (seconds) the adaptive tuner will ever assign.
567
+ * Guards against pathologically slow fetches producing indefinite caching.
568
+ * Default: `86400` (24 hours).
569
+ */
570
+ adaptiveTtlMax?: number;
571
+
572
+ /**
573
+ * `p95FetchLatencyMs × adaptiveTtlMultiplier = adaptedTtlSeconds`.
574
+ *
575
+ * Intuition: a 200 ms p95 fetch with the default multiplier of 20 yields a
576
+ * 4-second TTL. A 2 000 ms fetch yields 40 seconds. Increase the multiplier
577
+ * if you want the cache to absorb more upstream pressure.
578
+ *
579
+ * Default: `20`.
580
+ */
581
+ adaptiveTtlMultiplier?: number;
582
+
583
+ /**
584
+ * Number of fetch duration samples kept per key in the ring buffer.
585
+ * Larger values smooth out latency spikes but use slightly more memory
586
+ * (~8 bytes × samples per tracked key).
587
+ * Default: `32`.
588
+ */
589
+ adaptiveTtlSamples?: number;
590
+
591
+ /**
592
+ * Maximum number of distinct keys tracked by the adaptive TTL system.
593
+ * When the cap is reached, the oldest-tracked key is evicted from the
594
+ * ring-buffer store to make room for the new key.
595
+ * Default: `5000`.
596
+ */
597
+ adaptiveTtlMaxKeys?: number;
518
598
  }