Debian Codegraph @

pkg/sievecache/sievecache.go

raw symbols SCIP
1 package sievecache
2
3 import (
4 "errors"
5 "math"
6 )
7
8 // SieveCache provides an efficient in-memory cache with the SIEVE eviction algorithm.
9 // This is the single-threaded implementation.
10 type SieveCache[K comparable, V any] struct {
11 // Map of keys to indices in the nodes slice (pointer, 8 bytes)
12 indices map[K]int
13 // Slice of all cache nodes (pointer + len + cap, 24 bytes)
14 nodes []Node[K, V]
15 // Bit array for visited flags using 1 bit per entry (pointer, 8 bytes)
16 visited *BitSet
17 // Grouping integer fields together for better memory alignment (each 8 bytes)
18 capacity int
19 hand int
20 // Place smaller fields last to minimize padding (bool is 1 byte)
21 handInitialized bool
22 }
23
24 // New creates a new cache with the given capacity.
25 // Returns an error if capacity is less than or equal to zero.
26 func New[K comparable, V any](capacity int) (*SieveCache[K, V], error) {
27 if capacity <= 0 {
28 return nil, errors.New("SieveCache: capacity must be greater than 0")
29 }
30
31 return &SieveCache[K, V]{
32 indices: make(map[K]int, capacity),
33 nodes: make([]Node[K, V], 0, capacity),
34 visited: NewBitSet(capacity),
35 hand: 0,
36 handInitialized: false,
37 capacity: capacity,
38 }, nil
39 }
40
41 // Capacity returns the maximum number of entries the cache can hold.
42 func (c *SieveCache[K, V]) Capacity() int {
43 return c.capacity
44 }
45
46 // Len returns the number of cached values.
47 func (c *SieveCache[K, V]) Len() int {
48 return len(c.nodes)
49 }
50
51 // IsEmpty returns true when no values are currently cached.
52 func (c *SieveCache[K, V]) IsEmpty() bool {
53 return len(c.nodes) == 0
54 }
55
56 // ContainsKey returns true if there is a value in the cache mapped to by key.
57 func (c *SieveCache[K, V]) ContainsKey(key K) bool {
58 _, exists := c.indices[key]
59 return exists
60 }
61
62 // Get returns the value in the cache mapped to by key.
63 // If no value exists for key, returns the zero value of V and false.
64 // This operation marks the entry as "visited" in the SIEVE algorithm,
65 // which affects eviction decisions.
66 func (c *SieveCache[K, V]) Get(key K) (V, bool) {
67 var zero V
68 idx, exists := c.indices[key]
69 if !exists {
70 return zero, false
71 }
72
73 // Mark as visited for the SIEVE algorithm
74 c.visited.Set(idx, true)
75 return c.nodes[idx].Value, true
76 }
77
78 // GetPointer returns a pointer to the value in the cache mapped to by key.
79 // If no value exists for key, returns nil.
80 // This operation marks the entry as "visited" in the SIEVE algorithm,
81 // which affects eviction decisions.
82 func (c *SieveCache[K, V]) GetPointer(key K) *V {
83 idx, exists := c.indices[key]
84 if !exists {
85 return nil
86 }
87
88 // Mark as visited for the SIEVE algorithm
89 c.visited.Set(idx, true)
90 return &c.nodes[idx].Value
91 }
92
93 // Insert maps key to value in the cache, possibly evicting old entries.
94 // If the key already exists, its value is updated and the entry is marked as visited.
95 // Returns true when this is a new entry, and false if an existing entry was updated.
96 func (c *SieveCache[K, V]) Insert(key K, value V) bool {
97 // Check if key already exists
98 if idx, exists := c.indices[key]; exists {
99 // Update existing entry
100 c.visited.Set(idx, true)
101 c.nodes[idx].Value = value
102 return false
103 }
104
105 // Evict if at capacity
106 if len(c.nodes) >= c.capacity {
107 _, evicted := c.Evict()
108 // When the cache is full and *all* entries are marked `visited`, our Evict() performs
109 // a first pass that clears the `visited` bits but may return false without removing
110 // anything. We still must free a slot before inserting, so we call Evict() a second
111 // time. This mirrors the original SIEVE miss path, which keeps scanning (wrapping once)
112 // until it finds an item to evict after clearing bits.
113 if !evicted {
114 c.Evict()
115 }
116 }
117
118 // Add new node to the end
119 node := NewNode(key, value)
120 c.nodes = append(c.nodes, node)
121 idx := len(c.nodes) - 1
122 c.visited.Append(false) // Initialize as not visited
123 c.indices[key] = idx
124 return true
125 }
126
127 // Remove removes the cache entry mapped to by key.
128 // Returns the value removed from the cache and true if the key was present.
129 // If key did not map to any value, returns the zero value of V and false.
130 func (c *SieveCache[K, V]) Remove(key K) (V, bool) {
131 var zero V
132 idx, exists := c.indices[key]
133 if !exists {
134 return zero, false
135 }
136
137 delete(c.indices, key)
138
139 // If this is the last element, just remove it
140 if idx == len(c.nodes)-1 {
141 node := c.nodes[len(c.nodes)-1]
142 c.nodes = c.nodes[:len(c.nodes)-1]
143 c.visited.Truncate(len(c.nodes))
144 return node.Value, true
145 }
146
147 // Update hand if needed (scan direction is from low to high indices)
148 if c.handInitialized {
149 lastIdx := len(c.nodes) - 1
150 if c.hand == idx {
151 newLen := len(c.nodes) - 1
152 if newLen == 0 {
153 c.handInitialized = false
154 } else if idx >= newLen {
155 c.hand = 0
156 }
157 // Otherwise keep hand at same position (swapped element will be there)
158 } else if c.hand == lastIdx {
159 // If hand points to the last element (which will be moved to idx)
160 c.hand = idx
161 }
162 }
163
164 // Remove the node by replacing it with the last one and updating the map
165 removedNode := c.nodes[idx]
166 lastIdx := len(c.nodes) - 1
167 lastNode := c.nodes[lastIdx]
168
169 // Move the last node to the removed position
170 c.nodes[idx] = lastNode
171 c.visited.Set(idx, c.visited.Get(lastIdx))
172
173 // Truncate slices
174 c.nodes = c.nodes[:lastIdx]
175 c.visited.Truncate(lastIdx)
176
177 // Update the indices map for the moved node
178 if idx < len(c.nodes) {
179 c.indices[lastNode.Key] = idx
180 }
181
182 return removedNode.Value, true
183 }
184
185 // Evict removes and returns a value from the cache that was not recently accessed.
186 // This method implements the SIEVE eviction algorithm.
187 // Returns the evicted value and true if a suitable entry was found, or the zero
188 // value of V and false if all entries have been recently accessed or the cache is empty.
189 func (c *SieveCache[K, V]) Evict() (V, bool) {
190 var zero V
191 if len(c.nodes) == 0 {
192 return zero, false
193 }
194
195 // Start from the hand pointer or index 0 (tail/oldest) if hand is not initialized
196 var currentIdx int
197 if c.handInitialized {
198 currentIdx = c.hand
199 } else {
200 currentIdx = 0
201 }
202 startIdx := currentIdx
203
204 // Track whether we've wrapped around
205 wrapped := false
206 foundIdx := -1
207
208 // Scan for a non-visited entry (from tail toward head)
209 for {
210 // If current node is not visited, mark it for eviction
211 if !c.visited.Get(currentIdx) {
212 foundIdx = currentIdx
213 break
214 }
215
216 // Mark as non-visited for next scan
217 c.visited.Set(currentIdx, false)
218
219 // Move to next node (toward head) or wrap to beginning (tail)
220 if currentIdx+1 < len(c.nodes) {
221 currentIdx++
222 } else {
223 // Wrap around to beginning of slice
224 if wrapped {
225 // If we've already wrapped, break to avoid infinite loop
226 break
227 }
228 wrapped = true
229 currentIdx = 0
230 }
231
232 // If we've looped back to start, we've checked all nodes
233 if currentIdx == startIdx {
234 break
235 }
236 }
237
238 // If we found a node to evict
239 if foundIdx >= 0 {
240 evictIdx := foundIdx
241 lastIdx := len(c.nodes) - 1
242
243 // Update the hand pointer to the next position in scan order
244 if evictIdx == lastIdx {
245 // Evicting the last element, hand wraps to 0
246 if len(c.nodes) > 1 {
247 c.hand = 0
248 c.handInitialized = true
249 } else {
250 c.handInitialized = false
251 }
252 } else {
253 // swap_remove will move the last element to evictIdx
254 // Hand should point to evictIdx (where the moved element now is) to continue scanning
255 // But if hand would be >= new length, wrap to 0
256 newLen := len(c.nodes) - 1
257 if evictIdx < newLen {
258 c.hand = evictIdx
259 } else {
260 c.hand = 0
261 }
262 c.handInitialized = true
263 }
264
265 // Remove the key from the map
266 delete(c.indices, c.nodes[evictIdx].Key)
267
268 // Remove the node and return its value
269 nodeToEvict := c.nodes[evictIdx]
270
271 if evictIdx == lastIdx {
272 // If last node, just remove it
273 c.nodes = c.nodes[:len(c.nodes)-1]
274 c.visited.Truncate(len(c.nodes))
275 return nodeToEvict.Value, true
276 }
277
278 // Otherwise swap with the last node
279 lastNode := c.nodes[lastIdx]
280 c.nodes[evictIdx] = lastNode
281 c.visited.Set(evictIdx, c.visited.Get(lastIdx))
282 c.nodes = c.nodes[:lastIdx]
283 c.visited.Truncate(lastIdx)
284
285 // Update the indices map for the moved node
286 c.indices[lastNode.Key] = evictIdx
287
288 return nodeToEvict.Value, true
289 }
290
291 return zero, false
292 }
293
294 // Clear removes all entries from the cache.
295 func (c *SieveCache[K, V]) Clear() {
296 // Pre-allocate map with capacity hint to avoid rehashing during growth
297 c.indices = make(map[K]int, c.capacity)
298 // Pre-allocate slice with capacity hint to minimize reallocations
299 c.nodes = make([]Node[K, V], 0, c.capacity)
300 // Initialize bit set
301 c.visited = NewBitSet(c.capacity)
302 c.hand = 0
303 c.handInitialized = false
304 }
305
306 // Keys returns a slice of all keys in the cache.
307 func (c *SieveCache[K, V]) Keys() []K {
308 // Pre-allocate with exact capacity
309 keys := make([]K, len(c.nodes))
310 for i, node := range c.nodes {
311 keys[i] = node.Key
312 }
313 return keys
314 }
315
316 // Values returns a slice of all values in the cache.
317 func (c *SieveCache[K, V]) Values() []V {
318 // Pre-allocate with exact capacity
319 values := make([]V, len(c.nodes))
320 for i, node := range c.nodes {
321 values[i] = node.Value
322 }
323 return values
324 }
325
326 // Items returns a slice of all key-value pairs in the cache.
327 func (c *SieveCache[K, V]) Items() []struct {
328 Key K
329 Value V
330 } {
331 // Pre-allocate with exact capacity
332 items := make([]struct {
333 Key K
334 Value V
335 }, len(c.nodes))
336
337 for i, node := range c.nodes {
338 items[i].Key = node.Key
339 items[i].Value = node.Value
340 }
341
342 return items
343 }
344
345 // ForEach iterates over all entries in the cache and applies the function f to each pair.
346 // The iteration order is not specified and should not be relied upon.
347 func (c *SieveCache[K, V]) ForEach(f func(k K, v V)) {
348 for _, node := range c.nodes {
349 f(node.Key, node.Value)
350 }
351 }
352
353 // ForEachValue iterates over all values in the cache and applies the function f to each.
354 // This allows modifying the values in-place.
355 func (c *SieveCache[K, V]) ForEachValue(f func(v *V)) {
356 for i := range c.nodes {
357 f(&c.nodes[i].Value)
358 }
359 }
360
361 // Retain only keeps elements specified by the predicate.
362 // Removes all entries for which f returns false.
363 func (c *SieveCache[K, V]) Retain(f func(k K, v V) bool) {
364 // Use a more efficient allocation strategy for the removal list
365 nodeCount := len(c.nodes)
366 if nodeCount == 0 {
367 return
368 }
369
370 // Start with a small capacity and grow as needed
371 // This avoids over-allocation for large caches with few removals
372 initialCap := min(32, nodeCount/4)
373 if initialCap < 8 {
374 initialCap = 8
375 }
376
377 // Collect indices to remove
378 toRemove := make([]int, 0, initialCap)
379
380 for i, node := range c.nodes {
381 if !f(node.Key, node.Value) {
382 toRemove = append(toRemove, i)
383 }
384 }
385
386 // Remove indices from highest to lowest to avoid invalidating other indices
387 for i := len(toRemove) - 1; i >= 0; i-- {
388 idx := toRemove[i]
389
390 // Remove from map
391 delete(c.indices, c.nodes[idx].Key)
392
393 // If it's the last element, just remove it
394 if idx == len(c.nodes)-1 {
395 c.nodes = c.nodes[:len(c.nodes)-1]
396 c.visited.Truncate(len(c.nodes))
397 } else {
398 // Replace with the last element
399 lastIdx := len(c.nodes) - 1
400 lastNode := c.nodes[lastIdx]
401
402 // Move the last node to the removed position
403 c.nodes[idx] = lastNode
404 c.visited.Set(idx, c.visited.Get(lastIdx))
405 c.nodes = c.nodes[:lastIdx]
406 c.visited.Truncate(lastIdx)
407
408 // Update indices map if not removed
409 if idx < len(c.nodes) {
410 c.indices[lastNode.Key] = idx
411 }
412
413 // Update hand if needed
414 if c.handInitialized {
415 if c.hand == idx {
416 // Hand was pointing to the removed node, move it to previous
417 if idx > 0 {
418 c.hand = idx - 1
419 } else if len(c.nodes) > 0 {
420 c.hand = len(c.nodes) - 1
421 } else {
422 c.handInitialized = false
423 }
424 } else if c.hand == lastIdx {
425 // Hand was pointing to the last node that was moved
426 c.hand = idx
427 }
428 }
429 }
430 }
431 }
432
433 // RecommendedCapacity analyzes the current cache utilization and recommends a new capacity.
434 // Parameters:
435 // - minFactor: Minimum scaling factor (e.g., 0.5 means recommend at least 50% of current capacity)
436 // - maxFactor: Maximum scaling factor (e.g., 2.0 means recommend at most 200% of current capacity)
437 // - lowThreshold: Utilization threshold below which capacity is reduced
438 // - highThreshold: Utilization threshold above which capacity is increased
439 func (c *SieveCache[K, V]) RecommendedCapacity(minFactor, maxFactor, lowThreshold, highThreshold float64) int {
440 // If the cache is empty, return the current capacity
441 if len(c.nodes) == 0 {
442 return c.capacity
443 }
444
445 // Count entries with visited flag set
446 visitedCount := c.visited.CountSetBits()
447
448 // Calculate the utilization ratio (visited entries / total entries)
449 utilizationRatio := float64(visitedCount) / float64(len(c.nodes))
450
451 // Calculate fill ratio (total entries / capacity)
452 fillRatio := float64(len(c.nodes)) / float64(c.capacity)
453
454 // Low fill ratio threshold (consider the cache underfilled below this)
455 lowFillThreshold := 0.1 // 10% filled
456
457 // Fill ratio takes precedence over utilization:
458 // If the cache is severely underfilled, we should decrease capacity
459 // regardless of utilization
460 if fillRatio < lowFillThreshold {
461 // Calculate how much to decrease based on how empty the cache is
462 fillBelowThreshold := 0.0
463 if fillRatio > 0.0 {
464 fillBelowThreshold = (lowFillThreshold - fillRatio) / lowFillThreshold
465 } else {
466 fillBelowThreshold = 1.0
467 }
468 // Apply the minFactor as a floor
469 scalingFactor := 1.0 - (1.0-minFactor)*fillBelowThreshold
470
471 // Apply the scaling factor to current capacity and ensure it's at least 1
472 return max(1, int(math.Round(float64(c.capacity)*scalingFactor)))
473 }
474
475 // For normal fill levels, use the original logic based on utilization
476 var scalingFactor float64
477 if utilizationRatio >= highThreshold {
478 // High utilization - recommend increasing the capacity
479 // Scale between 1.0 and maxFactor based on utilization above the high threshold
480 utilizationAboveThreshold := (utilizationRatio - highThreshold) / (1.0 - highThreshold)
481 scalingFactor = 1.0 + (maxFactor-1.0)*utilizationAboveThreshold
482 } else if utilizationRatio <= lowThreshold {
483 // Low utilization - recommend decreasing capacity
484 // Scale between minFactor and 1.0 based on how far below the low threshold
485 utilizationBelowThreshold := (lowThreshold - utilizationRatio) / lowThreshold
486 scalingFactor = 1.0 - (1.0-minFactor)*utilizationBelowThreshold
487 } else {
488 // Normal utilization - keep current capacity
489 scalingFactor = 1.0
490 }
491
492 // Apply the scaling factor to current capacity and ensure it's at least 1
493 return max(1, int(math.Round(float64(c.capacity)*scalingFactor)))
494 }