Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 45 additions & 1 deletion cache/cache.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cache

import "time"
import (
"time"
)

// Cache interface defines the methods for a cache implementation.
type Cache[K comparable] interface {
Expand All @@ -13,3 +15,45 @@ type Cache[K comparable] interface {
// Delete removes a value from the cache by key.
Delete(key K)
}

// LRUCache interface defines the methods for a Least Recently Used (LRU) cache implementation.
type LRUCache[K comparable, V any] interface {
// Get retrieves a value from the cache by key.
Get(key K) (value V, found bool)

// Put adds a value to the cache with the specified key and expiration time.
Put(key K, value V, expiration time.Duration)

// Delete removes a value from the cache by key.
Delete(key K)
}

// EvictionReason represents the reason for evicting an item from the cache.
type EvictionReason string

const (
// EvictCapacity indicates that the item was evicted due to reaching the maximum capacity of the cache.
EvictCapacity EvictionReason = "capacity"
// EvictTTL indicates that the item was evicted due to exceeding its time-to-live (TTL).
EvictTTL EvictionReason = "TTL"
// EvictReplace indicates that the item was evicted due to being replaced by a new value.
EvictReplace EvictionReason = "replace"
// EvictDelete indicates that the item was evicted due to being explicitly deleted from the cache.
EvictDelete EvictionReason = "delete"
// EvictPurge indicates that the item was evicted due to a purge operation on the cache.
EvictPurge EvictionReason = "purge"
)

// Options struct defines the configuration options for the LRU cache.
type Options[K comparable, V any] struct {
// MaxSize defines the maximum number of items the cache can hold.
MaxSize int // 0 = unlimited count
// MaxBytes defines the maximum bytes the cache can hold.
MaxBytes int64 // 0 = unlimited bytes
// SizeOf is a function that calculates the byte usage of the value
SizeOf func(key K, value V) int64 // required if MaxBytes > 0
// OnEvict is a callback function that is called when an item is evicted from the cache.
OnEvict func(key K, value V, reason EvictionReason)
// SweepInterval defines the interval at which the cache will sweep for expired items.
SweepInterval time.Duration
}
235 changes: 235 additions & 0 deletions cache/lru.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,235 @@
package cache

import (
"context"
"fmt"
"math"
"sync"
"sync/atomic"
"time"

hashicorp "github.com/hashicorp/golang-lru/v2"
)

const (
// DefaultMemoryCacheSweepInterval is the default interval for sweeping expired items from the cache.
DefaultMemoryCacheSweepInterval = time.Minute * 5
)

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


type lruCache[V any] struct {
data V
cacheDuration time.Duration
startTime time.Time
memorySize int64
evictionReason EvictionReason
}

type evictionEvent[K comparable, V any] struct {
key K
value *lruCache[V]
}

// NewLRUCache creates a new lruCache entry with the given value and TTL
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.

lc := &lruCache[V]{data: data, cacheDuration: cacheDuration, startTime: time.Now(), evictionReason: EvictCapacity}

return lc
}

// IsExpired checks if the cache entry's TTL has elapsed.
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.

if l.cacheDuration <= 0 {
return false
}
return time.Now().After(l.startTime.Add(l.cacheDuration))
}

// LRUStore is a thread-safe LRU cache implementation that supports expiration and memory size limits.
type LRUStore[K comparable, V any] struct {
store *hashicorp.Cache[K, *lruCache[V]]
// maximumMemory Maximum Memory byte size of the cache
maximumMemory int64 // 0 = unlimited bytes
// sizeOf computes memory usage for each key/value entry.
sizeOf func(key K, value V) int64
// sweepInterval controls how often expired entries are removed.
sweepInterval time.Duration
// onEvict callback when an entry is evicted.
OnEvict func(key K, value V, reason EvictionReason)
// currentMemory Memory used by the cache
currentMemory int64
// mu mutex for synchronizing access to the cache
mu sync.Mutex
// pendingEvicts holds the list of eviction events to be processed after releasing the lock
pendingEvicts []evictionEvent[K, V]
}

// NewLRUStore creates a new LRUStore with the given options.
func NewLRUStore[K comparable, V any](ctx context.Context, opts Options[K, V]) (*LRUStore[K, V], error) {
if opts.MaxSize <= 0 {
// 0 = unlimited count: use the largest possible size so that only
// the byte budget (MaxBytes) drives eviction.
opts.MaxSize = math.MaxInt
}

if opts.MaxBytes < 0 {
opts.MaxBytes = 0
}

if opts.MaxBytes > 0 && opts.SizeOf == nil {
return nil, fmt.Errorf("SizeOf function must be provided when MaxBytes is greater than 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.


if opts.SweepInterval <= 0 {
opts.SweepInterval = DefaultMemoryCacheSweepInterval
}

lc := &LRUStore[K, V]{
maximumMemory: opts.MaxBytes,
sizeOf: opts.SizeOf,
sweepInterval: opts.SweepInterval,
OnEvict: opts.OnEvict,
currentMemory: 0,
}

lru, err := hashicorp.NewWithEvict(opts.MaxSize, func(key K, value *lruCache[V]) {
if value != nil {
atomic.AddInt64(&lc.currentMemory, -value.memorySize)
}
if lc.OnEvict != nil && value != nil {
lc.pendingEvicts = append(lc.pendingEvicts, evictionEvent[K, V]{
key: key,
value: value,
})
}
})

if err != nil {
return nil, err
}

lc.store = lru

go lc.run(ctx)

return lc, nil

}

// run starts a goroutine that periodically sweeps the cache for expired items.
func (l *LRUStore[K, V]) run(ctx context.Context) {
ticker := time.NewTicker(l.sweepInterval)
defer ticker.Stop()

for {
select {
case <-ctx.Done():
return
case <-ticker.C:
l.mu.Lock()
for _, key := range l.store.Keys() {
val, ok := l.store.Peek(key)
if ok && val != nil && val.IsExpired() {
val.evictionReason = 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.

}
}
l.executeEviction()
}
}
}

// Get retrieves a value from the cache by key.
func (l *LRUStore[K, V]) Get(key K) (value V, found bool) {
l.mu.Lock()
defer l.executeEviction()
lc, ok := l.store.Get(key)

if !ok {
return
}

if lc.IsExpired() {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
lc.evictionReason = 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.

return
}

return lc.data, true
}

// 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
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
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.

defer l.executeEviction()
lc := NewLRUCache(value, cacheDuration)

if l.sizeOf != nil {
lc.memorySize = l.sizeOf(key, value)
}

if l.maximumMemory != 0 && lc.memorySize > l.maximumMemory {
return
}

if prevValue, ok := l.store.Peek(key); ok && prevValue != nil {
prevValue.evictionReason = EvictReplace
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.

}

if l.maximumMemory != 0 {
for atomic.LoadInt64(&l.currentMemory)+lc.memorySize > l.maximumMemory {
_, _, ok := l.store.RemoveOldest()
if !ok {
// If there is nothing left to evict, refuse the write.
return
}
}
}

// track bytes whenever sizeOf is provided, even if maximumMemory is 0.
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).

atomic.AddInt64(&l.currentMemory, lc.memorySize)
}

l.store.Add(key, lc)

}

// Delete removes a value from the cache by key.
func (l *LRUStore[K, V]) Delete(key K) {
l.mu.Lock()
defer l.executeEviction()
if val, ok := l.store.Peek(key); ok && val != nil {
val.evictionReason = EvictDelete
l.store.Remove(key)
}
}

// CurrentBytes returns the current memory usage of the cache in bytes.
func (l *LRUStore[K, V]) CurrentBytes() int64 {
return atomic.LoadInt64(&l.currentMemory)
}

// Purge removes all items from the cache.
func (l *LRUStore[K, V]) Purge() {
l.mu.Lock()
defer l.executeEviction()
for _, key := range l.store.Keys() {
if val, ok := l.store.Peek(key); ok && val != nil {
val.evictionReason = EvictPurge
}
}
l.store.Purge()
}

func (l *LRUStore[K, V]) executeEviction() {
evicts := l.pendingEvicts
l.pendingEvicts = nil
l.mu.Unlock()

for _, evict := range evicts {
if l.OnEvict != nil && evict.value != nil {
l.OnEvict(evict.key, evict.value.data, evict.value.evictionReason)
}
}
}
Loading
Loading