Skip to content

Feat: Introduce LRU cache. (kubevela/pkg#138) - #4

Open
roguepikachu wants to merge 6 commits into
mainfrom
feat/pr-138-snyk
Open

roguepikachu wants to merge 6 commits into
mainfrom
feat/pr-138-snyk

Conversation

@roguepikachu

@roguepikachu roguepikachu commented Aug 25, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Copy of kubevela/pkg#138 (kash2104:issue-136) onto this fork so the Snyk GitHub integration can run against the same commits.
  • Fork main is synced with kubevela/pkg main (b40d331).
  • Head is the exact upstream PR tip (4bdf3b1).

Test plan

Summary by CodeRabbit

  • New Features
    • Added a thread-safe, generic LRU cache with typed keys and values.
    • Supports expiration, capacity and byte-size limits, automatic cleanup, and purge operations.
    • Added eviction notifications with reasons for expiration, replacement, deletion, capacity limits, and purging.
    • Added memory usage tracking and configurable value sizing.
  • Tests
    • Added coverage for expiration, eviction, deletion, replacement, purging, limits, callbacks, and cancellation.

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>
…s set.

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

coderabbitai Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 5a72212a-18ae-43fa-92ad-5cd89c042df0

📥 Commits

Reviewing files that changed from the base of the PR and between b40d331 and 4bdf3b1.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (4)
  • cache/cache.go
  • cache/lru.go
  • cache/lru_test.go
  • go.mod

Included review availability: Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

The PR adds a generic, thread-safe LRU cache. It supports TTL expiration, item and byte limits, eviction callbacks, background sweeping, deletion, purge, and atomic byte accounting. Comprehensive tests cover the new behavior.

Changes

Generic LRU cache

Layer / File(s) Summary
Cache contract and construction
cache/cache.go, cache/lru.go, go.mod
Defines generic cache interfaces, options, eviction reasons, entry metadata, and store state. Validates limits and byte sizing. Integrates Hashicorp LRU storage and context-based shutdown.
Expiration and eviction operations
cache/lru.go
Adds TTL sweeping, synchronized Get, Put, and Delete operations, capacity and byte-based eviction, replacement handling, purge behavior, byte accounting, and deferred eviction callbacks.
Cache behavior validation
cache/lru_test.go
Tests expiration, typed values, capacity limits, byte limits, replacement, deletion, purge, byte accounting, context cancellation, eviction callbacks, and background sweeping.

Estimated code review effort: 4 (Complex) | ~45 minutes

Merge Risk: ⚪ Minimal · up to 4bdf3

The PR introduces the LRU cache change and has no evidenced actionable merge-blocking risk at the current head; it is merge-ready after normal checks and review.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant LRUStore
  participant lruCache
  participant OnEvict
  Caller->>LRUStore: Put key, value, and TTL
  LRUStore->>lruCache: store entry and enforce limits
  lruCache-->>LRUStore: return evicted entry
  LRUStore->>OnEvict: report eviction reason
  LRUStore->>lruCache: sweep expired entries
  LRUStore->>OnEvict: report EvictTTL
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely identifies the main change: introducing an LRU cache. The issue reference is relevant to the pull request.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 3 files. (1 skipped: 1 …
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 3 files. (1 skipped: 1 unsupported.)

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/pr-138-snyk

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@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.

4 issues 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:33">
P3: `NewLRUCache` is exported but returns `*lruCache[V]`, an unexported type. Callers outside this package can only use the value via type inference (`:=`) and can't name the type directly, which limits usability of this public constructor. Either export the `lruCache` type or make `NewLRUCache` unexported if it's only meant for internal use.</violation>

<violation number="2" location="cache/lru.go:74">
P2: A negative `MaxBytes` silently becomes an unlimited cache, despite only zero being documented as unlimited. Return a configuration error for negative limits instead of disabling the bound.</violation>

<violation number="3" location="cache/lru.go:112">
P3: `NewLRUStore` never validates `ctx`. If a caller passes a `nil` context, the background `run` goroutine panics on `ctx.Done()`. Consider defaulting to `context.Background()` when `ctx == nil`, or documenting that a non-nil context is required.</violation>
</file>

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

<violation number="1" location="cache/lru_test.go:38">
P3: The "basic put and get" test sleeps an unconditional 3 seconds just to let a 2-second TTL lapse, and the other expiry tests use fixed 200ms sleeps. Besides adding ~3.5s to every unit-test run, relying on wall-clock sleeps to drive expiry makes the tests dependent on timer scheduling; under a paused or heavily loaded CI runner a TTL can be checked sooner than expected. Prefer a short, tunable TTL (tens of milliseconds) or a way to advance time so the tests stay fast and deterministic.</violation>
</file>

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

Re-trigger cubic

Comment thread cache/lru.go
opts.MaxSize = math.MaxInt
}

if opts.MaxBytes < 0 {

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: A negative MaxBytes silently becomes an unlimited cache, despite only zero being documented as unlimited. Return a configuration error for negative limits instead of disabling the bound.

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

<comment>A negative `MaxBytes` silently becomes an unlimited cache, despite only zero being documented as unlimited. Return a configuration error for negative limits instead of disabling the bound.</comment>

<file context>
@@ -0,0 +1,235 @@
+		opts.MaxSize = math.MaxInt
+	}
+
+	if opts.MaxBytes < 0 {
+		opts.MaxBytes = 0
+	}
</file context>

Comment thread cache/lru.go

lc.store = lru

go lc.run(ctx)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: NewLRUStore never validates ctx. If a caller passes a nil context, the background run goroutine panics on ctx.Done(). Consider defaulting to context.Background() when ctx == nil, or documenting that a non-nil context is required.

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

<comment>`NewLRUStore` never validates `ctx`. If a caller passes a `nil` context, the background `run` goroutine panics on `ctx.Done()`. Consider defaulting to `context.Background()` when `ctx == nil`, or documenting that a non-nil context is required.</comment>

<file context>
@@ -0,0 +1,235 @@
+
+	lc.store = lru
+
+	go lc.run(ctx)
+
+	return lc, nil
</file context>
Suggested change
go lc.run(ctx)
if ctx == nil {
ctx = context.Background()
}
go lc.run(ctx)

Comment thread cache/lru.go
}

// 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

Choose a reason for hiding this comment

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

P3: NewLRUCache is exported but returns *lruCache[V], an unexported type. Callers outside this package can only use the value via type inference (:=) and can't name the type directly, which limits usability of this public constructor. Either export the lruCache type or make NewLRUCache unexported if it's only meant for internal use.

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

<comment>`NewLRUCache` is exported but returns `*lruCache[V]`, an unexported type. Callers outside this package can only use the value via type inference (`:=`) and can't name the type directly, which limits usability of this public constructor. Either export the `lruCache` type or make `NewLRUCache` unexported if it's only meant for internal use.</comment>

<file context>
@@ -0,0 +1,235 @@
+}
+
+// NewLRUCache creates a new lruCache entry with the given value and TTL
+func NewLRUCache[V any](data V, cacheDuration time.Duration) *lruCache[V] {
+	lc := &lruCache[V]{data: data, cacheDuration: cacheDuration, startTime: time.Now(), evictionReason: EvictCapacity}
+
</file context>

Comment thread cache/lru_test.go
store.Put("test", "test data", time.Second*2)
store.Put("test2", "test data", 0)
store.Put("test3", "test data", -1)
time.Sleep(3 * time.Second)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The "basic put and get" test sleeps an unconditional 3 seconds just to let a 2-second TTL lapse, and the other expiry tests use fixed 200ms sleeps. Besides adding ~3.5s to every unit-test run, relying on wall-clock sleeps to drive expiry makes the tests dependent on timer scheduling; under a paused or heavily loaded CI runner a TTL can be checked sooner than expected. Prefer a short, tunable TTL (tens of milliseconds) or a way to advance time so the tests stay fast and deterministic.

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

<comment>The "basic put and get" test sleeps an unconditional 3 seconds just to let a 2-second TTL lapse, and the other expiry tests use fixed 200ms sleeps. Besides adding ~3.5s to every unit-test run, relying on wall-clock sleeps to drive expiry makes the tests dependent on timer scheduling; under a paused or heavily loaded CI runner a TTL can be checked sooner than expected. Prefer a short, tunable TTL (tens of milliseconds) or a way to advance time so the tests stay fast and deterministic.</comment>

<file context>
@@ -0,0 +1,314 @@
+		store.Put("test", "test data", time.Second*2)
+		store.Put("test2", "test data", 0)
+		store.Put("test3", "test data", -1)
+		time.Sleep(3 * time.Second)
+
+		value, found := store.Get("test")
</file context>

@roguepikachu

Copy link
Copy Markdown
Owner Author

Hi @kash2104 could you address the Cubic comments and the Unit test CI failure. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants