diff --git a/coverage.txt b/coverage.txt index 8af241a..39c56ba 100644 --- a/coverage.txt +++ b/coverage.txt @@ -3,8 +3,8 @@ ℹ file | line % | branch % | funcs % | uncovered lines ℹ ---------------------------------------------------------- ℹ src | | | | -ℹ lru.js | 100.00 | 99.37 | 100.00 | +ℹ lru.js | 100.00 | 99.35 | 100.00 | ℹ ---------------------------------------------------------- -ℹ all files | 100.00 | 99.37 | 100.00 | +ℹ all files | 100.00 | 99.35 | 100.00 | ℹ ---------------------------------------------------------- ℹ end of coverage report diff --git a/openspec/changes/archive/.gitkeep b/openspec/changes/archive/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/openspec/changes/archive/2026-11-25-deduplicate-lru-insertion-and-traversal/.openspec.yaml b/openspec/changes/archive/2026-11-25-deduplicate-lru-insertion-and-traversal/.openspec.yaml new file mode 100644 index 0000000..c701210 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-deduplicate-lru-insertion-and-traversal/.openspec.yaml @@ -0,0 +1,3 @@ +schema: spec-driven +created: 2026-11-24 +skip_specs: true diff --git a/openspec/changes/archive/2026-11-25-deduplicate-lru-insertion-and-traversal/design.md b/openspec/changes/archive/2026-11-25-deduplicate-lru-insertion-and-traversal/design.md new file mode 100644 index 0000000..3d47d7f --- /dev/null +++ b/openspec/changes/archive/2026-11-25-deduplicate-lru-insertion-and-traversal/design.md @@ -0,0 +1,61 @@ +# Design + +## Context + +`src/lru.js` implements the `LRU` class as a doubly-linked list (`first`/`last` pointers) plus an `items` hash map (`Object.create(null)`). Two patterns are duplicated (see proposal.md - Why): + +1. **Insertion block** — byte-identical in `setWithEvicted()` (lines 362-376) and `set()` (lines 410-424): create the item, wire first/last, set `this.last`. +2. **Traversal-and-skip-expired** — near-identical in `keys()`, `entries()`, `values()`, `toJSON()`: walk `first`→`last`, skip expired via `#isExpired`, collect. + +Constraints (AGENTS.md §3.2, §6.1, §7.1): tabs/double-quotes/semicolons; 100% line coverage; O(1) get/set/delete; traversal must access items directly (never call `get()`, which moves items and deletes expired entries mid-iteration). + +## Goals / Non-Goals + +**Goals:** +- Single source of truth for the insertion block via `#insertItem(key, value)`. +- Single source of truth for the live-item traversal via `#forEachLive(callback)`. +- Byte-for-byte behavioral equivalence; 100% line coverage preserved. + +**Non-Goals:** +- No change to the update-existing-key branch (already near-identical, not the flagged duplication). +- No change to the `keys`-array overloads of `entries()`/`values()`. +- No change to `forEach()`, `cleanup()`, `sizeByTTL()`, `keysByTTL()`, `valuesByTTL()` — distinct semantics. +- No public API change. + +## Decisions + +### D1: `#insertItem(key, value)` returns the created item + +The helper performs the full insertion: `item = this.items[key] = { expiry, key, prev: this.last, next: null, value }`, then `if (++this.size === 1) this.first = item; else this.last.next = item;`, then `this.last = item;`, and returns `item`. + +- **Why return the item?** Both callers already assign the result to a local `item` and the surrounding code is identical; returning keeps the call sites a one-liner and preserves the exact `prev: this.last` capture-before-reassignment ordering. +- **Eviction stays in the caller.** `set()` calls `this.evict()` (fires onEvict); `setWithEvicted()` calls `this.#evictItem()` and captures the evicted item for its return value. Only the post-eviction insertion is shared. This preserves the divergent eviction semantics while removing the duplicated block. +- **Alternative considered:** a single `#setInternal(key, value, { silent })` that also handles eviction. Rejected — it would couple the two eviction paths and risk changing onEvict firing behavior; the flagged duplication is only the insertion block. + +### D2: `#forEachLive(callback)` for traversal + +A private helper that walks `for (let x = this.first; x !== null; x = x.next)`, skips expired items via `#isExpired(x)`, and invokes `callback(item)` per live item. `keys()`, `entries()`, `values()`, `toJSON()` each call it with a collector callback. + +- **Why a callback rather than a returned array?** The four methods collect different shapes (`x.key`, `[x.key, x.value]`, `x.value`, `{key,value,expiry}`). A callback keeps the traversal logic shared while letting each caller decide what to collect. +- **Why not a generator?** A generator would add allocation/iteration overhead to the hot path; a plain callback loop preserves the current O(1)-amortized, allocation-light traversal. +- **Direct item access (AGENTS.md §7.1):** the helper reads `x.key`/`x.value`/`x.expiry` directly and uses `#isExpired` — it never calls `get()`, so LRU order is not mutated and expired items are not deleted mid-iteration. +- **Alternative considered:** a shared `#collectLive(selector)` returning an array. Rejected — `toJSON()` builds objects and `entries()` builds pairs; a selector callback is the minimal shared surface. + +### D3: Helper placement + +Place `#insertItem` and `#forEachLive` adjacent to the related private helpers (`#unlink`, `#removeItem`, `#evictItem`) to keep private infrastructure grouped. + +## Risks / Trade-offs + +- [Ordering bug in `#insertItem`] → The `prev: this.last` capture and `++this.size === 1` first-wiring must execute in the exact original order; verified by the full 173-test suite and 100% coverage. +- [Coverage gap on new helpers] → Both helpers are exercised transitively by every existing set/keys/entries/values/toJSON test, so 100% line coverage is maintained without new tests. +- [Behavior drift] → Pure refactor; no observable change. The existing suite is the regression guard. +- [Callback allocation in `#forEachLive`] → Negligible; the callback is a small closure per call, matching the current per-method allocation profile. + +## Migration Plan + +Single-file change to `src/lru.js`. No migration, no data changes, no deploy steps. Rollback is a `git revert` of the commit. + +## Open Questions + +None. diff --git a/openspec/changes/archive/2026-11-25-deduplicate-lru-insertion-and-traversal/proposal.md b/openspec/changes/archive/2026-11-25-deduplicate-lru-insertion-and-traversal/proposal.md new file mode 100644 index 0000000..75d01f0 --- /dev/null +++ b/openspec/changes/archive/2026-11-25-deduplicate-lru-insertion-and-traversal/proposal.md @@ -0,0 +1,28 @@ +# Proposal + +## Why + +A code-quality audit (issue #547, rule QUAL-003, low severity) found two copy-paste patterns in `src/lru.js` that are a maintenance hazard: the insertion block in `setWithEvicted()` is byte-identical to the one in `set()`, and the "walk the linked list, skip expired, collect" pattern is near-duplicated across `keys()`, `entries()`, `values()`, and `toJSON()`. Keeping multiple copies in sync risks silent divergence that could break LRU ordering or TTL handling. Extracting shared helpers gives each pattern a single source of truth. + +## What Changes + +- Extract the duplicated post-eviction insertion block into a private helper `#insertItem(key, value)` that creates the item, wires the first/last pointers, sets `this.last`, and returns the item. Both `set()` and `setWithEvicted()` call it after their own eviction handling. +- Extract the shared "walk list, skip expired, collect" traversal into a private helper `#forEachLive(callback)` and rewrite `keys()`, `entries()`, `values()`, and `toJSON()` to use it. +- No public API changes. No behavior changes. No breaking changes. + +## Capabilities + +### New Capabilities + +None. This is a pure internal refactor with no spec-level behavior change. + +### Modified Capabilities + +None. No requirement changes. The change opts out of specs via `skip_specs: true` in `.openspec.yaml` because behavior is unchanged — specs describe behavior, and nothing observable changes. + +## Impact + +- **Code:** `src/lru.js` only. Two new private methods (`#insertItem`, `#forEachLive`); call-site updates in `set()`, `setWithEvicted()`, `keys()`, `entries()`, `values()`, `toJSON()`. +- **API:** None. Public surface unchanged. +- **Dependencies:** None. +- **Tests:** Existing 173 tests must continue to pass; 100% line coverage must be maintained. No new tests required (behavior is unchanged), but coverage of the new helpers is exercised transitively by the existing suite. diff --git a/openspec/changes/archive/2026-11-25-deduplicate-lru-insertion-and-traversal/tasks.md b/openspec/changes/archive/2026-11-25-deduplicate-lru-insertion-and-traversal/tasks.md new file mode 100644 index 0000000..1acabfd --- /dev/null +++ b/openspec/changes/archive/2026-11-25-deduplicate-lru-insertion-and-traversal/tasks.md @@ -0,0 +1,23 @@ +# Tasks + +## 1. Shared insertion helper + +- [ ] 1.1 Add private method `#insertItem(key, value)` to `src/lru.js` that creates the item (`this.items[key] = { expiry, key, prev: this.last, next: null, value }`), wires first/last (`if (++this.size === 1) this.first = item; else this.last.next = item;`), sets `this.last = item`, and returns `item`. Verify by reading the new method and confirming it matches the original insertion block byte-for-byte. +- [ ] 1.2 Replace the inline insertion block in `setWithEvicted()` with a call to `#insertItem(key, value)` (after the `#evictItem()` eviction handling). Verify `npm run test` passes. +- [ ] 1.3 Replace the inline insertion block in `set()` with a call to `#insertItem(key, value)` (after the `this.evict()` eviction handling). Verify `npm run test` passes. + +## 2. Shared traversal helper + +- [ ] 2.1 Add private method `#forEachLive(callback)` to `src/lru.js` that walks `for (let x = this.first; x !== null; x = x.next)`, skips expired items via `#isExpired(x)`, and invokes `callback(x)` per live item. Verify by reading the new method. +- [ ] 2.2 Rewrite `keys()`, `entries()`, `values()`, and `toJSON()` to use `#forEachLive` for the no-`keys`-argument traversal branch. Verify `npm run test` passes and output is unchanged. + +## 3. Verification + +- [ ] 3.1 Run `npm run lint` and confirm no errors. +- [ ] 3.2 Run `npm run coverage` and confirm 100% line coverage is maintained. +- [ ] 3.3 Run `npm run test` and confirm all 173 tests pass. + +## Workflow follow-up + +- Archive the change after the project's review requirements are satisfied. +- Verify the archived result. diff --git a/openspec/config.yaml b/openspec/config.yaml new file mode 100644 index 0000000..2805cb6 --- /dev/null +++ b/openspec/config.yaml @@ -0,0 +1,32 @@ +schema: spec-driven + +# Project context (optional) +# Add only constraints that should guide OpenSpec artifacts and workflows. +# Include constraints an agent cannot infer by reading the code. +# Keep general project documentation and discoverable codebase facts out. +# Example: +# context: | +# Designs and tasks must cover Windows, macOS, and Linux +# Write all artifacts in Spanish + +# Per-artifact rules (optional) +# Add custom rules for specific artifacts. +# Example: +# rules: +# proposal: +# - Keep proposals under 500 words +# - Always state what is out of scope +# tasks: +# - Break tasks into chunks of max 2 hours + +# Per-operation guidance (optional) +# Add advisory guidance for how apply and archive work should be conducted. +# This is separate from artifact rules above. +# Example: +# operations: +# apply: +# guidance: +# - Keep test summaries concise +# archive: +# guidance: +# - Summarize the archive outcome before finishing diff --git a/openspec/specs/.gitkeep b/openspec/specs/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/lru.js b/src/lru.js index e82a76b..163db94 100644 --- a/src/lru.js +++ b/src/lru.js @@ -96,11 +96,7 @@ export class LRU { entries(keys) { if (keys === undefined) { const result = []; - for (let x = this.first; x !== null; x = x.next) { - if (!this.#isExpired(x)) { - result.push([x.key, x.value]); - } - } + this.#forEachLive((x) => result.push([x.key, x.value])); return result; } @@ -289,6 +285,51 @@ export class LRU { return item; } + /** + * Creates and links a new item at the most recently used position. + * Wires the first/last pointers and returns the created item. + * + * @param {string} key - The key to store. + * @param {*} value - The value to store. + * @returns {Object} The created and linked item. + * @private + */ + #insertItem(key, value) { + const item = (this.items[key] = { + expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, + key: key, + prev: this.last, + next: null, + value, + }); + + if (++this.size === 1) { + this.first = item; + } else { + this.last.next = item; + } + + this.last = item; + + return item; + } + + /** + * Invokes a callback for each live (non-expired) item in LRU order. + * Accesses items directly without calling get(), so LRU order is not + * mutated and expired items are not deleted mid-iteration. + * + * @param {function(Object): void} callback - Function to call for each live item. + * @private + */ + #forEachLive(callback) { + for (let x = this.first; x !== null; x = x.next) { + if (!this.#isExpired(x)) { + callback(x); + } + } + } + /** * Efficiently moves an item to the end of the LRU list (most recently used position). * This is an internal optimization method that avoids the overhead of the full set() operation @@ -318,11 +359,7 @@ export class LRU { */ keys() { const result = []; - for (let x = this.first; x !== null; x = x.next) { - if (!this.#isExpired(x)) { - result.push(x.key); - } - } + this.#forEachLive((x) => result.push(x.key)); return result; } @@ -359,21 +396,7 @@ export class LRU { }; } - item = this.items[key] = { - expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, - key: key, - prev: this.last, - next: null, - value, - }; - - if (++this.size === 1) { - this.first = item; - } else { - this.last.next = item; - } - - this.last = item; + item = this.#insertItem(key, value); } this.#stats.sets++; @@ -407,21 +430,7 @@ export class LRU { this.evict(); } - item = this.items[key] = { - expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, - key: key, - prev: this.last, - next: null, - value, - }; - - if (++this.size === 1) { - this.first = item; - } else { - this.last.next = item; - } - - this.last = item; + item = this.#insertItem(key, value); } this.#stats.sets++; @@ -440,11 +449,7 @@ export class LRU { values(keys) { if (keys === undefined) { const result = []; - for (let x = this.first; x !== null; x = x.next) { - if (!this.#isExpired(x)) { - result.push(x.value); - } - } + this.#forEachLive((x) => result.push(x.value)); return result; } @@ -590,15 +595,13 @@ export class LRU { */ toJSON() { const result = []; - for (let x = this.first; x !== null; x = x.next) { - if (!this.#isExpired(x)) { - result.push({ - key: x.key, - value: x.value, - expiry: x.expiry, - }); - } - } + this.#forEachLive((x) => { + result.push({ + key: x.key, + value: x.value, + expiry: x.expiry, + }); + }); return result; }