Skip to content

Feat: Introduce LRU cache. - #138

Merged
anoop2811 merged 7 commits into
kubevela:mainfrom
kash2104:issue-136
Aug 26, 2026
Merged

anoop2811 merged 7 commits into
kubevela:mainfrom
kash2104:issue-136

Conversation

@kash2104

@kash2104 kash2104 commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

This PR introduces an LRU cache backed by hashicorp/golang-lru.

Along with the cache implementation, it provides configurable cache options that allow the LRU cache to support byte-based memory accounting in addition to the standard entry-count limit.

The cache provides the following operations:

  • Put
  • Get
  • Delete
  • Purge
  • CurrentBytes

These operations have been implemented to account for the configured byte limit and maintain the current memory usage of the cache accordingly.

The cache also supports configurable cache expiration and periodic sweeping of expired entries.


Summary by cubic

Introduces a generic, thread-safe LRU cache with per-item TTL, byte budgets, and post-unlock eviction callbacks for predictable, race-free in-memory caching. No existing code paths change.

  • Adds LRUStore[K,V] with Get/Put/Delete, plus Purge and CurrentBytes; Put accepts per-item TTL.
  • Options: MaxSize (0=unlimited), MaxBytes (0=unlimited), SizeOf (required if MaxBytes>0), OnEvict, SweepInterval (default 5m).
  • Enforces byte budgets: rejects single items > MaxBytes, evicts LRU entries to fit, and tracks CurrentBytes whenever SizeOf is set, even if MaxBytes=0.
  • Periodically sweeps expired items and stops on context cancel; eviction reasons include capacity, TTL, replace, delete, and purge; callbacks run after unlocking.
  • Exposes LRUCache, Options, and EvictionReason in cache/cache.go; adds github.com/hashicorp/golang-lru/v2.

Written for commit 4bdf3b1. Summary will update on new commits.

Review in cubic

@codecov

codecov Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.15686% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.52%. Comparing base (b40d331) to head (4bdf3b1).

Files with missing lines Patch % Lines
cache/lru.go 92.15% 4 Missing and 4 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #138      +/-   ##
==========================================
- Coverage   88.55%   88.52%   -0.03%     
==========================================
  Files          94       95       +1     
  Lines        4883     4985     +102     
==========================================
+ Hits         4324     4413      +89     
- Misses        369      378       +9     
- Partials      190      194       +4     
Flag Coverage Δ
unit-test 88.52% <92.15%> (-0.03%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 5 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="cache/lru.go">

<violation number="1" location="cache/lru.go:156">
P2: Overwriting an existing key invokes `OnEvict(EvictCapacity)` even though the entry was not evicted for capacity. `Put` calls `l.store.Remove(key)` for a present key before re-adding, which runs the hashicorp eviction callback with no reason stored, so the callback reports `EvictCapacity`; the same happens for `Delete` and `Purge`. `EvictionReason` is documented as describing why an item was removed (capacity vs TTL), but replacements and explicit deletes are labeled as capacity evictions. Any caller using `OnEvict` to free external resources only on genuine capacity eviction (or to distinguish reasons) will act incorrectly for every overwrite.</violation>
</file>

Tip: instead of fixing issues one by one fix them all with cubic

Re-trigger cubic

Comment thread cache/lru.go Resolved
Comment thread cache/lru.go Resolved
Comment thread cache/lru.go
}

// Put adds a value to the cache with the specified key and expiration time.
func (l *LRUStore[K, V]) Put(key K, value V, cacheDuration time.Duration) {

@cubic-dev-ai cubic-dev-ai Bot Aug 12, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Overwriting an existing key invokes OnEvict(EvictCapacity) even though the entry was not evicted for capacity. Put calls l.store.Remove(key) for a present key before re-adding, which runs the hashicorp eviction callback with no reason stored, so the callback reports EvictCapacity; the same happens for Delete and Purge. EvictionReason is documented as describing why an item was removed (capacity vs TTL), but replacements and explicit deletes are labeled as capacity evictions. Any caller using OnEvict to free external resources only on genuine capacity eviction (or to distinguish reasons) will act incorrectly for every overwrite.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At cache/lru.go, line 156:

<comment>Overwriting an existing key invokes `OnEvict(EvictCapacity)` even though the entry was not evicted for capacity. `Put` calls `l.store.Remove(key)` for a present key before re-adding, which runs the hashicorp eviction callback with no reason stored, so the callback reports `EvictCapacity`; the same happens for `Delete` and `Purge`. `EvictionReason` is documented as describing why an item was removed (capacity vs TTL), but replacements and explicit deletes are labeled as capacity evictions. Any caller using `OnEvict` to free external resources only on genuine capacity eviction (or to distinguish reasons) will act incorrectly for every overwrite.</comment>

<file context>
@@ -0,0 +1,201 @@
+}
+
+// Put adds a value to the cache with the specified key and expiration time.
+func (l *LRUStore[K, V]) Put(key K, value V, cacheDuration time.Duration) {
+	l.mu.Lock()
+	defer l.mu.Unlock()
</file context>
Fix with cubic

@kash2104 kash2104 Aug 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Introduced delete, replace and purge evictionReasons.

Comment thread cache/lru.go Resolved
Comment thread cache/lru_test.go Resolved

@roguepikachu roguepikachu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Took a pass on this. The overall shape looks right to me, hashicorp lru plus SizeOf and generics is what I was hoping for. A few things I think we should fix before helm starts depending on it, left them inline.

Comment thread cache/lru.go

if opts.SizeOf == nil {
opts.SizeOf = func(_ K, _ V) int64 { return 0 }
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If MaxBytes is set and SizeOf is nil we silently count everything as 0, so the byte cap does nothing. I'd rather return an error here. SizeOf should be required when MaxBytes > 0.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good now. Constructor errors when MaxBytes is set and SizeOf is missing.

Comment thread cache/lru.go
val, ok := l.store.Peek(key)
if ok && val != nil && val.IsExpired() {
l.evictionReason.Store(key, EvictTTL)
l.store.Remove(key)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this has the same race we fixed on the TTL store. If a Put replaces this key between Peek and Remove, we delete the new value. Can we hold the lock across the expire check and remove, or only remove if the peeked entry is still the current one?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here it would be better to use the lock since for checking the previous value, we would again have to Peek and compare it with the previous Peek value.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is addressed. Sweep now holds the lock across the expire check and remove, so a concurrent Put cannot get wiped.

Comment thread cache/lru.go

if lc.IsExpired() {
l.evictionReason.Store(key, EvictTTL)
l.store.Remove(key)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same concern here. Get then Remove is not atomic with Put, so a refresh can get wiped.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is addressed. Get now holds the lock for the expire check and remove.

Comment thread cache/lru.go
}

if prevValue, ok := l.store.Peek(key); ok && prevValue != nil {
l.store.Remove(key)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When we Remove before re-adding, OnEvict fires as capacity even though this is just an overwrite. Delete and Purge will look like capacity evictions too, and that will mess up helm metrics. Maybe skip OnEvict for explicit replace/delete, or add a distinct reason.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The hashicorp-lru always fires the onEvict callback when we are using the Remove function. So instead of skipping the callback, adding a new reason EvictReplace would be a better options.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added the replace evictionReason.

Comment thread cache/lru.go Outdated
for atomic.LoadInt64(&l.currentMemory)+lc.memorySize > l.maximumMemory {
if oldestKey, _, ok := l.store.GetOldest(); ok {
l.evictionReason.Store(oldestKey, EvictCapacity)
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Storing the reason by key in a side map feels racy to me. GetOldest then RemoveOldest can race with sweep, and a later Put of the same key can pick up the wrong reason. Could we keep the reason on the entry itself?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Introduced a new reason and moved this reason to the lruCache struct so that now the reason is attached to the value being stored instead of the cache key.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is addressed. Reason lives on the entry now, so we are not racing on a side map keyed by K.

Comment thread cache/lru.go

// Put adds a value to the cache with the specified key and expiration time.
func (l *LRUStore[K, V]) Put(key K, value V, cacheDuration time.Duration) {
l.mu.Lock()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Put holds mu while OnEvict runs, but Get, Delete, and sweep don't take mu at all. If OnEvict calls Put we can deadlock on this path, and byte accounting can still race on the others. Can we lock all mutating paths the same way and fire OnEvict after unlocking?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is addressed in f200364. All mutating paths take the lock, and OnEvict runs after unlock via executeEviction.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 2 files (changes from recent commits).

Reply with feedback, questions, or to request a fix.

Fix all with cubic | Re-trigger cubic

Comment thread cache/lru.go Resolved
@roguepikachu

Copy link
Copy Markdown
Collaborator

I re-ran this on the new head (f8b9bed). The race hardening is moving the right way, and SizeOf validation is a good fix. I still see one blocker and one follow-up concern, left inline.

Comment thread cache/lru.go Outdated
atomic.AddInt64(&lc.currentMemory, -value.memorySize)
}
if lc.OnEvict != nil && value != nil {
lc.OnEvict(key, value.data, value.evictionReason)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: OnEvict is still called while l.mu is held by Put/Get/Delete/Purge/sweep paths that trigger store.Remove/RemoveOldest/Purge. If callback code re-enters the same store (for example Put on eviction), this deadlocks because sync.Mutex is not re-entrant. I would buffer evicted items while locked and invoke OnEvict after unlocking.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Introduced a new field for the LRUStore and a new function which first does the unlocking and then goes on to execute the onEvict callback.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is addressed. Buffering pendingEvicts and firing OnEvict after unlock is what I wanted here.

Comment thread cache/lru.go Outdated
}

lru, err := hashicorp.NewWithEvict(opts.MaxSize, func(key K, value *lruCache[V]) {
if value != nil && opts.MaxBytes != 0 {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up: CurrentBytes accounting still only updates when MaxBytes != 0. With unlimited MaxBytes plus SizeOf configured, CurrentBytes remains 0, which breaks observability callers that want usage without enforcing a hard cap.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have removed the additional condition of opts.MaxBytes

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still pending on b539a09.

Put only sets memorySize and updates currentMemory when maximumMemory != 0, so with MaxBytes: 0 and a SizeOf configured, CurrentBytes() stays 0.

Please track whenever SizeOf is set, and only use MaxBytes for the eviction budget.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add the memory of the value to the currentMemory for updation when sizeOf is set. Added a separate conditoin for memory addition when sizeOf is present even if the maximumMemory is 0.

@kash2104
kash2104 requested a review from roguepikachu August 20, 2026 04:10
@roguepikachu

roguepikachu commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator

@kash2104, could you resolve all comments that are addressed and also take a look at the cubic comments? Happy to re-review it once these are done. Thanks!

@roguepikachu roguepikachu added the type/enhancement New feature or request label Aug 20, 2026
@kash2104

Copy link
Copy Markdown
Contributor Author

Hey @roguepikachu , have addressed the bot comments and review suggestions.

Signed-off-by: kash2104 <kparikh1104@gmail.com>
Signed-off-by: kash2104 <kparikh1104@gmail.com>
Signed-off-by: kash2104 <kparikh1104@gmail.com>
Add eviction reason for delete and purge.

Signed-off-by: kash2104 <kparikh1104@gmail.com>
@roguepikachu

Copy link
Copy Markdown
Collaborator

Hey @kash2104 #138 (comment), this still remains unaddressed please have a look.

…s set.

Signed-off-by: kash2104 <kparikh1104@gmail.com>
@kash2104

Copy link
Copy Markdown
Contributor Author

Hey @roguepikachu , updated the Put function to address the review.

@roguepikachu roguepikachu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nits on unused defaults + comment cleanup (non-blocking polish before merge):

  1. Drop or actually use DefaultLRUCacheMemory / DefaultLRUCacheSize
  2. Fix/tighten a few comments (NewLRUCache, IsExpired, narrating Put comment, and the test placeholder)

No unused imports spotted in cache/; the dead surface is those unused consts.

@roguepikachu roguepikachu left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kash2104 Nits on unused defaults + comment cleanup (non-blocking polish before merge):

  1. Drop or actually use DefaultLRUCacheMemory / DefaultLRUCacheSize
  2. Fix/tighten a few comments (NewLRUCache, IsExpired, narrating Put comment, and the test placeholder)

No unused imports spotted in cache/; the dead surface is those unused consts.

Comment thread cache/lru.go
DefaultLRUCacheMemory = 1024 * 1024 * 256 // 256MB
// DefaultLRUCacheSize for LRUCacheMemoryStore
DefaultLRUCacheSize = 1000
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: DefaultLRUCacheMemory / DefaultLRUCacheSize are unused (nothing in this repo or the consumer PRs references them; kubevela hardcodes 256 << 20 instead).

Please either drop them, or wire them as the real defaults in NewLRUStore / the Helm provider so they are not dead API surface.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Currently would be dropping these since in the follow-up, we are introducing cli flag for setting these fields and fallback to default in the kubevela repo would be a better option instead of using the constants from pkg repo

Comment thread cache/lru.go
}

// NewLRUCache new lru cache instance
func NewLRUCache[V any](data V, cacheDuration time.Duration) *lruCache[V] {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (comment cleanup): please use a normal Go doc, e.g.

// NewLRUCache creates an LRU cache entry with the given value and TTL.

Comment thread cache/lru.go
}

// isExpired whether the cache data expires
func (l *lruCache[V]) IsExpired() bool {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (comment cleanup): godoc name does not match the method. Please use:

// IsExpired reports whether the cache entry's TTL has elapsed.

Comment thread cache/lru.go
}

// Update the current memory usage after adding the new item to the cache if sizeOf is provided
if l.sizeOf != nil {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (comment cleanup): this comment only restates the next few lines. Prefer deleting it, or keep a short why note if needed (e.g. that we track bytes whenever sizeOf is set, even when MaxBytes == 0).

Comment thread cache/lru_test.go
store.Put("b", "world", 0)
store.Purge()
// placeholder-noop-keep-context

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: please delete // placeholder-noop-keep-context. Looks like a leftover placeholder and does not help the test.

Signed-off-by: kash2104 <kparikh1104@gmail.com>
Signed-off-by: kash2104 <kparikh1104@gmail.com>

@roguepikachu roguepikachu left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Thank you for following up rigorously and your contribution!

@anoop2811

Copy link
Copy Markdown
Member

Thank you for your contribution @kash2104 !

@anoop2811
anoop2811 merged commit a4214d8 into kubevela:main Aug 26, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type/enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants