feat(cache): implement O(1) eviction policies and O(k) TTL cleanup #781
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.

Summary
Implements O(1) eviction policies and O(k) TTL cleanup for the in-memory cache, addressing Issues 3 and 4 from #162.
Issues Addressed in This PR
Issue 3: Expensive TTL Cleanup ✅
Problem:
cleanupExpiredEntries()examined ALL cache entries - O(n) complexity.Solution: Implemented
ExpirationHeap(min-heap ordered by expiration time).Issue 4: Expensive Eviction ✅
Problem:
SelectVictim()scanned ALL entries to find eviction candidate - O(n) complexity.Solution: Implemented O(1) eviction policies using proper data structures:
Performance Improvement
Tests Added
TestFIFOPolicyOptimized- Tests FIFO O(1) operations (Evict, UpdateIndex, OnRemove)TestLRUPolicyOptimized- Tests LRU O(1) operations (Evict, UpdateIndex, OnRemove, OnAccess)TestLFUPolicyOptimized- Tests LFU O(1) operations (Evict, UpdateIndex, OnRemove, OnAccess)TestExpirationHeapOperations- Tests all heap operations (Size, PeekNext, UpdateExpiration, PopExpired)TestInMemoryCacheEviction- Tests eviction integration with InMemoryCacheIssues Already Addressed (Not in This PR)
Issue 1: Unnecessary Sorting in FindSimilar ✅
Problem:
sort.Slice(results, ...)added O(n log n) overhead to find best match.Already Fixed in PR #347: The sorting was removed. Now the best match is tracked during iteration - O(n) single pass, no sorting needed.
Issue 2: Linear Search for Similarity ✅
Problem: Computing dot product with every cache entry - O(n) per query.
Already Fixed in PR #504: HNSW (Hierarchical Navigable Small World) index was added for approximate nearest neighbor search - O(log n) average case.
FIX #162