Skip to content

Fix cache eviction order, redundant matchesQuery recursion, and sync/async misuse#20

Merged
Hexagon merged 2 commits intomainfrom
copilot/review-performance-architecture
Feb 20, 2026
Merged

Fix cache eviction order, redundant matchesQuery recursion, and sync/async misuse#20
Hexagon merged 2 commits intomainfrom
copilot/review-performance-architecture

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Feb 20, 2026

Several correctness and performance issues found during architectural review of the core KV primitives.

Cache eviction was backwards (+ falsy-zero bug)

KVLedgerCache.evictOldestEntries() used pop() — removing the newest entry — instead of shift() to remove the oldest. The documented intent is FIFO eviction; the implementation was LIFO, so freshly-written entries were discarded while stale ones accumulated.

Separately, if (oldestOffset) silently skipped eviction for any entry at offset 0 (falsy), leaking memory.

// Before: evicts newest, skips offset 0
const oldestOffset = this.cacheEntries.pop() as number;
if (oldestOffset) { ... }

// After: evicts oldest, handles offset 0
const oldestOffset = this.cacheEntries.shift();
if (oldestOffset !== undefined) { ... }

matchesQuery() did redundant O(n²) recursive work

Inside the for loop, at every step i, the code created a new KVKeyInstance, sliced both key and query arrays, and re-ran matchesQuery on the tail — work the outer loop was already doing in subsequent iterations. Removed entirely; behavior is unchanged.

KVIndex.get() called key.get() on every recursion

key.get()[keyIndex] inside the inner recurse function re-invoked the getter on every call. Cached to const keyParts = key.get() once before entering recursion.

Unnecessary await on sync methods in kv.ts

transaction.create() and transaction.toUint8Array() are synchronous but were called with await, misleading readers about the async nature of the surrounding code.


🔒 GitHub Advanced Security automatically protects Copilot coding agent pull requests. You can protect all pull requests by enabling Advanced Security for your repositories. Learn more about Advanced Security.

… optimization, and code clarity

Co-authored-by: Hexagon <419737+Hexagon@users.noreply.github.com>
Copilot AI changed the title [WIP] Review performance and architectural soundness Fix cache eviction order, redundant matchesQuery recursion, and sync/async misuse Feb 20, 2026
Copilot AI requested a review from Hexagon February 20, 2026 22:45
@Hexagon Hexagon marked this pull request as ready for review February 20, 2026 22:45
@Hexagon Hexagon merged commit 15c8a93 into main Feb 20, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants