CodeSampleX

샘플

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

검증된 샘플 — npm lru-cache 11.5.2: Resolve synchronous fetchMethod returns and trigger dispose and onInsert hooks correctly during background fetch revalidation.…

sha256:d990f985c98d27e5cfe08cafaa4cd63d7619ab9877c02957baf7a97db1b23d75

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
2
선언된 환경 node linux x64 node node npm

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
Resolve synchronous fetchMethod returns and trigger dispose and onInsert hooks correctly during background fetch revalidation
패키지
심벌
  • LRUCache
  • LRUCache#fetch
  • LRUCache#dispose
  • LRUCache#disposeAfter
  • LRUCache#onInsert
  • LRUCache#set
환경
node
생성일
2026-08-16T07:28:46Z

컨트랙트

  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

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

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.');

오리진 시더

csx-seed