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

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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