CodeSampleX

Sample

lru-cache 11.5.2: Resolve synchronous fetchMethod returns and trigger dispose and onInsert hooks correctly during background fetch revalidation

Verified sample for npm lru-cache 11.5.2: Resolve synchronous fetchMethod returns and trigger dispose and onInsert hooks correctly during background fetch…

sha256:d990f985c98d27e5cfe08cafaa4cd63d7619ab9877c02957baf7a97db1b23d75

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
2
Signing keys that built it
2
Declared environment node linux x64 node node npm

Verification-run environments

Environment Contract Stages Run
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-16
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18

Case

HOW
Goal
Resolve synchronous fetchMethod returns and trigger dispose and onInsert hooks correctly during background fetch revalidation
Packages
Symbols
  • LRUCache
  • LRUCache#fetch
  • LRUCache#dispose
  • LRUCache#disposeAfter
  • LRUCache#onInsert
  • LRUCache#set
Environment
node
Created
2026-08-16T07:28:46Z

Contract

  1. assert synchronous fetchMethod resolves immediately instead of returning an unresolved hanging promise
  2. assert dispose and disposeAfter fire with reason evict for stale entries evicted during in-flight background fetches
  3. assert onInsert does not fire for internal BackgroundFetch promise objects and only fires once on resolution with reason add
  4. assert cache.set overwriting a pending background fetch disposes the superseded stale entry with reason set

Files

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • test/contract.mjs

Download the source artifact (tar.gz)

Source

NOTES.md
# Notes on lru-cache (Background Fetch Edge Cases and Disposal Fixes)

## CSX Network Search Result
`search_known_solution` answered with sample `sha256:45ba1445da9dc36a83c5aad3029d51db56180dc067c54674860a7701622f3552` ("Handle lru-cache TTL stale entry reads without get() silently evicting the entry on first read or maxSize dropping oversized items without error"), which covered TTL lazy expiration and maxSize parameter constraints. To cover a distinct trap, this sample proves the behavioural bug fixes introduced in the `11.4.0` release for background fetch edge cases, synchronous `fetchMethod` handling, and disposal hooks.

## What a Model Would Have Written Instead
A model would provide a synchronous return in `fetchMethod` expecting `cache.fetch(key)` to resolve immediately, rely on `dispose()` and `disposeAfter()` to reliably clean up resources when stale entries undergoing background fetches are evicted or overwritten, and assume `onInsert` only receives resolved concrete cache values.

## How the Wrong Version Fails
Fails both with silent resource leaks and indefinite hangs:
- In `lru-cache <= 11.3.6`, a synchronous `fetchMethod` returns a Promise that hangs indefinitely because resolution was guarded strictly by `fmp instanceof Promise` without an `else` branch.
- In `lru-cache <= 11.3.6`, evicting or replacing a stale entry while a background fetch is in-flight completely skips `dispose()` and `disposeAfter()` because `#evict` branched on `isBackgroundFetch(v)` using `else if` for disposal, causing silent resource/handle leaks.
- In `lru-cache 11.1.0 - 11.3.6`, `onInsert` fired prematurely with the internal provisional `BackgroundFetch` Promise object typed as a value, followed by a second `'replace'` call on resolution.
csx.json
{"case":{"caseId":"case:sha256:2fe2aabd26705a939f18490db6e4366aefc81d0f42a5c272ddd53f6244882067","contract":["assert synchronous fetchMethod resolves immediately instead of returning an unresolved hanging promise","assert dispose and disposeAfter fire with reason evict for stale entries evicted during in-flight background fetches","assert onInsert does not fire for internal BackgroundFetch promise objects and only fires once on resolution with reason add","assert cache.set overwriting a pending background fetch disposes the superseded stale entry with reason set"],"goal":"Resolve synchronous fetchMethod returns and trigger dispose and onInsert hooks correctly during background fetch revalidation","kind":"HOW","packages":["pkg:npm/lru-cache@11.5.2"],"schemaVersion":1,"symbols":["LRUCache","LRUCache#fetch","LRUCache#dispose","LRUCache#disposeAfter","LRUCache#onInsert","LRUCache#set"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/lru-cache@11.5.2"],"schemaVersion":1,"symbols":["LRUCache","LRUCache#fetch","LRUCache#dispose","LRUCache#disposeAfter","LRUCache#onInsert","LRUCache#set"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "npm-lru-cache-bugfix",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "npm-lru-cache-bugfix",
      "version": "1.0.0",
      "dependencies": {
        "lru-cache": "11.5.2"
      }
    },
    "node_modules/lru-cache": {
      "version": "11.5.2",
      "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz",
      "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==",
      "license": "BlueOak-1.0.0",
      "engines": {
        "node": "20 || >=22"
      }
    }
  }
}
package.json
{
  "name": "npm-lru-cache-bugfix",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "lru-cache": "11.5.2"
  }
}
test/contract.mjs
import assert from 'node:assert/strict';
import { LRUCache } from 'lru-cache';

// --------------------------------------------------------------------------
// 1. Synchronous fetchMethod returns value directly without hanging
// --------------------------------------------------------------------------
// In lru-cache <= 11.3.6, cache.fetch() checked `if (fmp instanceof Promise)`
// without an else branch, causing synchronous fetchMethod returns to return a
// Promise that never resolved. In 11.4.0+, synchronous returns resolve immediately.
{
  const cache = new LRUCache({
    max: 10,
    fetchMethod: (key) => `sync-computed-${key}`,
  });

  const result = await cache.fetch('sync-key');
  assert.equal(result, 'sync-computed-sync-key');
  assert.equal(cache.get('sync-key'), 'sync-computed-sync-key');
}

// --------------------------------------------------------------------------
// 2. dispose() and disposeAfter() fire for stale values evicted during background fetch
// --------------------------------------------------------------------------
// In lru-cache <= 11.3.6, #evict checked `isBackgroundFetch(v)` in an `if` block
// and used `else if` for dispose, silently skipping dispose() on stale values
// evicted while a background fetch was in flight. In 11.4.0+, the stale value is
// properly dispatched to dispose and disposeAfter with reason 'evict'.
{
  let virtualTime = 1000;
  const disposed = [];
  const disposedAfter = [];

  let resolveFetch;
  const fetchPromise = new Promise((resolve) => {
    resolveFetch = resolve;
  });

  const cache = new LRUCache({
    max: 2,
    ttl: 50,
    allowStale: true,
    dispose: (val, key, reason) => disposed.push({ val, key, reason }),
    disposeAfter: (val, key, reason) => disposedAfter.push({ val, key, reason }),
    fetchMethod: () => fetchPromise,
    perf: { now: () => virtualTime },
  });

  cache.set('stale-key', 'stale-data');
  virtualTime = 1100; // TTL expired

  // Stale hit returns old value immediately and starts background fetch
  const bgResult = await cache.fetch('stale-key');
  assert.equal(bgResult, 'stale-data');

  // Insert two items into cache (max=2), evicting 'stale-key'
  cache.set('item-1', 'val-1');
  cache.set('item-2', 'val-2');

  assert.deepEqual(disposed, [{ val: 'stale-data', key: 'stale-key', reason: 'evict' }]);
  assert.deepEqual(disposedAfter, [{ val: 'stale-data', key: 'stale-key', reason: 'evict' }]);

  resolveFetch('ignored-resolution');
}

// --------------------------------------------------------------------------
// 3. onInsert does NOT fire for provisional BackgroundFetch internal promises
// --------------------------------------------------------------------------
// In lru-cache 11.1.0-11.3.6, onInsert fired prematurely during fetch() with
// the internal BackgroundFetch Promise object as value, then fired again with
// reason 'replace'. In 11.4.0+, onInsert only fires once upon resolution with
// the concrete value and reason 'add'.
{
  const inserted = [];
  let resolveAsync;
  const pendingAsync = new Promise((resolve) => {
    resolveAsync = resolve;
  });

  const cache = new LRUCache({
    max: 5,
    onInsert: (value, key, reason) => {
      inserted.push({
        key,
        isPromise: value instanceof Promise,
        valueType: typeof value,
        value,
        reason,
      });
    },
    fetchMethod: async (key) => {
      await pendingAsync;
      return `fetched-${key}`;
    },
  });

  const fetchPromise = cache.fetch('async-key');

  // While in flight: onInsert must NOT have fired for provisional promise object
  assert.equal(inserted.length, 0);

  resolveAsync();
  const fetchedVal = await fetchPromise;
  assert.equal(fetchedVal, 'fetched-async-key');

  // After resolution: fired exactly once with concrete value and reason 'add'
  assert.deepEqual(inserted, [
    {
      key: 'async-key',
      isPromise: false,
      valueType: 'string',
      value: 'fetched-async-key',
      reason: 'add',
    },
  ]);
}

// --------------------------------------------------------------------------
// 4. Overwriting a key via cache.set() during background fetch disposes stale value
// --------------------------------------------------------------------------
// In lru-cache <= 11.3.6, replacing an in-flight background fetch skipped dispose
// on the shadowed stale value. In 11.4.0+, the stale value is disposed with reason 'set'.
{
  let virtualTime = 1000;
  const disposed = [];
  let resolveFetch;
  const fetchPromise = new Promise((resolve) => {
    resolveFetch = resolve;
  });

  const cache = new LRUCache({
    max: 5,
    ttl: 50,
    allowStale: true,
    dispose: (val, key, reason) => disposed.push({ val, key, reason }),
    fetchMethod: () => fetchPromise,
    perf: { now: () => virtualTime },
  });

  cache.set('replace-target', 'stale-initial');
  virtualTime = 1100; // TTL expired

  await cache.fetch('replace-target');

  // Overwrite key explicitly while background fetch is pending
  cache.set('replace-target', 'manual-update');

  assert.deepEqual(disposed, [{ val: 'stale-initial', key: 'replace-target', reason: 'set' }]);
  assert.equal(cache.get('replace-target'), 'manual-update');

  resolveFetch('ignored');
}

console.log('Contract verified: all lru-cache background fetch bugfix assertions passed.');

Origin Seeder

csx-seed