-
Notifications
You must be signed in to change notification settings - Fork 208
Add LRU capacity to ValidatingCache, remove sentinel pattern, add storage Update #4731
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
yrobla
wants to merge
1
commit into
main
Choose a base branch
from
revert-4730-issue-4494
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,173 @@ | ||
| // SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| // Package cache provides a generic, capacity-bounded cache with singleflight | ||
| // deduplication and per-hit liveness validation. | ||
| package cache | ||
|
|
||
| import ( | ||
| "errors" | ||
| "fmt" | ||
|
|
||
| lru "github.com/hashicorp/golang-lru/v2" | ||
| "golang.org/x/sync/singleflight" | ||
| ) | ||
|
|
||
| // ErrExpired is returned by the check function passed to New to signal that a | ||
| // cached entry has definitively expired and should be evicted. | ||
| var ErrExpired = errors.New("cache entry expired") | ||
|
|
||
| // ValidatingCache is a node-local write-through cache backed by a | ||
| // capacity-bounded LRU map, with singleflight-deduplicated restore on cache | ||
| // miss and lazy liveness validation on cache hit. | ||
| // | ||
| // Type parameter K is the key type (must be comparable). | ||
| // Type parameter V is the cached value type. | ||
| // | ||
| // The no-resurrection invariant (preventing a concurrent restore from | ||
| // overwriting a deletion) is enforced via ContainsOrAdd: if a concurrent | ||
| // writer stored a value between load() returning and the cache being updated, | ||
| // the prior writer's value wins and the just-loaded value is discarded via | ||
| // onEvict. | ||
| type ValidatingCache[K comparable, V any] struct { | ||
| lruCache *lru.Cache[K, V] | ||
| flight singleflight.Group | ||
| load func(key K) (V, error) | ||
| check func(key K, val V) error | ||
| // onEvict is kept here so we can call it when discarding a concurrently | ||
| // loaded value that lost the race to a prior writer. | ||
| onEvict func(key K, val V) | ||
| } | ||
|
|
||
| // New creates a ValidatingCache with the given capacity and callbacks. | ||
| // | ||
| // capacity is the maximum number of entries; it must be >= 1. When the cache | ||
| // is full and a new entry must be stored, the least-recently-used entry is | ||
| // evicted first. Values less than 1 panic. | ||
| // | ||
| // load is called on a cache miss to restore the value; it must not be nil. | ||
| // check is called on every cache hit to confirm liveness. It receives both the | ||
| // key and the cached value so callers can inspect the value without a separate | ||
| // read. Returning ErrExpired evicts the entry; any other error is transient | ||
| // (cached value returned unchanged). It must not be nil. | ||
| // onEvict is called after any eviction (LRU or expiry); it may be nil. | ||
| func New[K comparable, V any]( | ||
| capacity int, | ||
| load func(K) (V, error), | ||
| check func(K, V) error, | ||
| onEvict func(K, V), | ||
| ) *ValidatingCache[K, V] { | ||
| if capacity < 1 { | ||
| panic(fmt.Sprintf("cache.New: capacity must be >= 1, got %d", capacity)) | ||
| } | ||
| if load == nil { | ||
| panic("cache.New: load must not be nil") | ||
| } | ||
| if check == nil { | ||
| panic("cache.New: check must not be nil") | ||
| } | ||
|
|
||
| c, err := lru.NewWithEvict(capacity, onEvict) | ||
| if err != nil { | ||
| // Only possible if size < 0, which we have already ruled out above. | ||
| panic(fmt.Sprintf("cache.New: lru.NewWithEvict: %v", err)) | ||
| } | ||
|
|
||
| return &ValidatingCache[K, V]{ | ||
| lruCache: c, | ||
| load: load, | ||
| check: check, | ||
| onEvict: onEvict, | ||
| } | ||
| } | ||
|
|
||
| // getHit validates a known-present cache entry and returns its value. | ||
| // If the entry has definitively expired it is evicted and (zero, false) is | ||
| // returned. Transient check errors leave the entry in place and return the | ||
| // cached value. | ||
| func (c *ValidatingCache[K, V]) getHit(key K, val V) (V, bool) { | ||
| if err := c.check(key, val); err != nil { | ||
| if errors.Is(err, ErrExpired) { | ||
| // Remove fires the eviction callback automatically. | ||
| c.lruCache.Remove(key) | ||
| var zero V | ||
| return zero, false | ||
| } | ||
| } | ||
| return val, true | ||
| } | ||
|
|
||
| // Get returns the value for key, loading it on a cache miss. On a cache hit | ||
| // the entry's liveness is validated via the check function provided to New: | ||
| // ErrExpired evicts the entry and returns (zero, false); transient errors | ||
| // return the cached value unchanged. On a cache miss, load is called under a | ||
| // singleflight group so at most one restore runs concurrently per key. | ||
| func (c *ValidatingCache[K, V]) Get(key K) (V, bool) { | ||
| if val, ok := c.lruCache.Get(key); ok { | ||
| return c.getHit(key, val) | ||
| } | ||
|
|
||
| // Cache miss: use singleflight to prevent concurrent restores for the same key. | ||
| type result struct{ v V } | ||
| raw, err, _ := c.flight.Do(fmt.Sprint(key), func() (any, error) { | ||
| // Re-check the cache: a concurrent singleflight group may have stored | ||
| // the value between our miss check above and acquiring this group. | ||
| if existing, ok := c.lruCache.Get(key); ok { | ||
| return result{v: existing}, nil | ||
| } | ||
|
|
||
| v, loadErr := c.load(key) | ||
| if loadErr != nil { | ||
| return nil, loadErr | ||
| } | ||
|
|
||
| // Guard against a concurrent Set or Remove that occurred while load() was | ||
| // running. ContainsOrAdd stores only if absent; if another writer got | ||
| // in first, their value wins and we discard ours via onEvict. | ||
| ok, _ := c.lruCache.ContainsOrAdd(key, v) | ||
| if ok { | ||
| // Another writer stored a value first; discard our loaded value and | ||
| // return the winner's. ContainsOrAdd and Get are separate lock | ||
| // acquisitions, so the winner may itself have been evicted by LRU | ||
| // pressure between the two calls — fall back to our freshly loaded | ||
| // value in that case rather than returning a zero value. | ||
| winner, found := c.lruCache.Get(key) | ||
| if !found { | ||
| // Winner was evicted between ContainsOrAdd and Get; keep our | ||
| // freshly loaded value rather than returning a zero value. | ||
| return result{v: v}, nil | ||
| } | ||
|
Check failure on line 139 in pkg/cache/validating_cache.go
|
||
| // Discard our loaded value in favour of the winner. | ||
| if c.onEvict != nil { | ||
| c.onEvict(key, v) | ||
| } | ||
| return result{v: winner}, nil | ||
| } | ||
|
|
||
| return result{v: v}, nil | ||
| }) | ||
| if err != nil { | ||
| var zero V | ||
| return zero, false | ||
| } | ||
| r, ok := raw.(result) | ||
| return r.v, ok | ||
| } | ||
|
|
||
| // Set stores value under key, moving the entry to the MRU position. If the | ||
| // cache is at capacity, the least-recently-used entry is evicted first and | ||
| // onEvict is called for it. | ||
| func (c *ValidatingCache[K, V]) Set(key K, value V) { | ||
| c.lruCache.Add(key, value) | ||
| } | ||
|
|
||
| // Remove evicts the entry for key, calling onEvict if the key was present. | ||
| // It is a no-op if the key is not in the cache. | ||
| func (c *ValidatingCache[K, V]) Remove(key K) { | ||
| c.lruCache.Remove(key) | ||
| } | ||
|
|
||
| // Len returns the number of entries currently in the cache. | ||
| func (c *ValidatingCache[K, V]) Len() int { | ||
| return c.lruCache.Len() | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔴 In the
!foundbranch ofValidatingCache.Get(pkg/cache/validating_cache.go:135-138), when a concurrent winner is evicted by LRU pressure betweenContainsOrAddandlruCache.Get, the freshly-loaded valuevis returned to the caller without callingonEvict(key, v). For the session manager use case,onEvictissess.Close()which releases backend HTTP connections — skipping it means those connections are never closed, leaking resources. The fix is to callc.onEvict(key, v)in the!foundbranch before returning.Extended reasoning...
What the bug is and how it manifests
In
ValidatingCache.Get(pkg/cache/validating_cache.go), afterload(key)completes, the code callsc.lruCache.ContainsOrAdd(key, v). WhenContainsOrAddreturnsok=true, a concurrent writer already stored a value for this key, sovshould be discarded. The code then callsc.lruCache.Get(key)to retrieve the winner. If the winner was itself evicted by LRU pressure in the narrow window between these two independent lock acquisitions,foundis false and the code takes the!foundbranch (lines 135-138), returningresult{v: v}directly — without callingonEvict(key, v)and without storingvin the cache.The specific code path that triggers it
At line 131:
ok, _ := c.lruCache.ContainsOrAdd(key, v)— returnsok=truewhen a concurrentSetstored a value betweenload()returning andContainsOrAddrunning. At line 133:winner, found := c.lruCache.Get(key)—ContainsOrAddandGetare separate mutex acquisitions; another goroutine can add a new key to a full cache between them, evicting the winner. At lines 135-138:if !found { return result{v: v}, nil }— returnsvto the caller without: (1) storingvin the cache, (2) callingc.onEvict(key, v). The code comment at line 125 explicitly acknowledges the race: "ContainsOrAdd and Get are separate lock acquisitions". The design comment at line 27 states "the prior writer's value wins and the just-loaded value is discarded via onEvict" — this contract is violated in the!foundsub-case.Why existing code doesn't prevent it
The normal discard path at lines 141-143 correctly calls
c.onEvict(key, v)when the winner is alive. The!foundbranch is an intentional fallback to avoid returning a zero value, but it omits the matchingonEvictcall. There is no other mechanism that cleans upvwhen the winner disappears between the two lock acquisitions.What the impact would be
Two consequences: (1)
vis not cached — the nextGetfor the same key triggers another fullload()call; (2) more critically for the session manager,onEvict = sess.Close()is never called forv. Sincevwas never stored insm.sessions, a subsequentsm.sessions.Remove(sessionID)inTerminate()is a no-op. The returned session holds open backend HTTP connections that are never explicitly closed, leaking resources until process restart.Step-by-step proof (capacity=1)
Get('k'), misses, enters singleflight,load('k')starts.Set('k', 'winner')— cache:{k: winner}.Set('k2', 'x')— cache is full; 'k' (winner) is evicted viaonEvict. Cache:{k2: x}.loadreturns'from-load'. A callsContainsOrAdd('k', 'from-load'). Since 'k' is now absent (evicted in step 3),ContainsOrAddadds it and returnsok=false— this is the normal path. (Alternatively:)ContainsOrAddsees 'k' present (ok=true from B's write) but beforelruCache.Get('k')runs. Thenfound=false. A returnsresult{v: 'from-load'}to its caller without callingonEvict('k', 'from-load'). The caller holds a session with open HTTP connections;onEvict/sess.Close()is never called, leaking those connections.How to fix it
Call
c.onEvict(key, v)in the!foundbranch before returning:Alternatively — and arguably more correct — since the winner is gone and
vis fresh from storage, storevin the cache (c.lruCache.Add(key, v)) so the nextGetfinds it without a redundantload()round-trip.