サンプル
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…
sha256:d990f985c98d27e5cfe08cafaa4cd63d7619ab9877c02957baf7a97db1b23d75
このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。
合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。
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
コントラクト
- 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
ファイル
- NOTES.md
- csx.json
- package-lock.json
- package.json
- test/contract.mjs
ソース
# 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.
{"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"}
{
"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"
}
}
}
}
{
"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"
}
}
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.');