GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(rate): add periodic GC for expired counter entries · majorcontext/keep@b1c46df

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • internal/rate
    • counter.go
    • gc_test.go
  • keep.go
  • keep_test.go
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎internal/rate/counter.go‎

Copy file name to clipboardExpand all lines: internal/rate/counter.go
+30-3Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,10 @@ func (realClock) Now() time.Time { return time.Now() }
1919

2020
// Store is a thread-safe sliding window counter store.
2121
type Store struct {
22-
mu sync.Mutex
23-
data map[string][]time.Time
24-
clock Clock
22+
mu sync.Mutex
23+
data map[string][]time.Time
24+
clock Clock
25+
stopCh chan struct{}
2526
}
2627

2728
// NewStore creates a new counter store using real time.
@@ -64,6 +65,32 @@ func (s *Store) Count(key string, window time.Duration) int {
6465
return count
6566
}
6667

68+
// StartGC begins periodic garbage collection in a background goroutine.
69+
// Runs every interval, removing entries older than maxAge.
70+
// Call StopGC to stop the goroutine.
71+
func (s *Store) StartGC(interval, maxAge time.Duration) {
72+
s.stopCh = make(chan struct{})
73+
go func() {
74+
ticker := time.NewTicker(interval)
75+
defer ticker.Stop()
76+
for {
77+
select {
78+
case <-ticker.C:
79+
s.GC(maxAge)
80+
case <-s.stopCh:
81+
return
82+
}
83+
}
84+
}()
85+
}
86+
87+
// StopGC stops the periodic garbage collection goroutine.
88+
func (s *Store) StopGC() {
89+
if s.stopCh != nil {
90+
close(s.stopCh)
91+
}
92+
}
93+
6794
// GC removes entries older than maxAge from all keys.
6895
// Removes keys that become empty.
6996
func (s *Store) GC(maxAge time.Duration) {
Collapse file

‎internal/rate/gc_test.go‎

Copy file name to clipboard
+108Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
package rate
2+
3+
import (
4+
"testing"
5+
"time"
6+
)
7+
8+
func TestStore_StartGC(t *testing.T) {
9+
clk := newMockClock()
10+
s := NewStoreWithClock(clk)
11+
12+
// Add some entries.
13+
s.Increment("key1")
14+
s.Increment("key2")
15+
16+
// Verify entries exist.
17+
s.mu.Lock()
18+
initialLen := len(s.data)
19+
s.mu.Unlock()
20+
if initialLen != 2 {
21+
t.Fatalf("expected 2 keys before GC, got %d", initialLen)
22+
}
23+
24+
// Start GC with a short interval and maxAge of 1 hour.
25+
// Entries were added at mock clock time; we'll advance the clock
26+
// past maxAge so entries become stale.
27+
const gcInterval = 10 * time.Millisecond
28+
const maxAge = time.Hour
29+
s.StartGC(gcInterval, maxAge)
30+
defer s.StopGC()
31+
32+
// Advance mock clock past maxAge so entries are considered expired.
33+
clk.Advance(2 * time.Hour)
34+
35+
// Wait long enough for at least one GC tick to fire.
36+
deadline := time.Now().Add(500 * time.Millisecond)
37+
for time.Now().Before(deadline) {
38+
s.mu.Lock()
39+
remaining := len(s.data)
40+
s.mu.Unlock()
41+
if remaining == 0 {
42+
break
43+
}
44+
time.Sleep(gcInterval)
45+
}
46+
47+
s.mu.Lock()
48+
remaining := len(s.data)
49+
s.mu.Unlock()
50+
51+
if remaining != 0 {
52+
t.Errorf("expected all expired entries to be removed by GC, got %d keys remaining", remaining)
53+
}
54+
}
55+
56+
func TestStore_StopGC(t *testing.T) {
57+
clk := newMockClock()
58+
s := NewStoreWithClock(clk)
59+
60+
s.Increment("key1")
61+
62+
const gcInterval = 10 * time.Millisecond
63+
const maxAge = time.Hour
64+
65+
s.StartGC(gcInterval, maxAge)
66+
67+
// Stop GC immediately.
68+
s.StopGC()
69+
70+
// Advance mock clock so entries would be expired if GC ran.
71+
clk.Advance(2 * time.Hour)
72+
73+
// Wait longer than a few GC intervals to confirm GC has stopped.
74+
time.Sleep(50 * time.Millisecond)
75+
76+
// Entries should still be present because GC was stopped before it
77+
// could run with the advanced clock time.
78+
// (GC may have run zero or one times between StartGC and StopGC with
79+
// old clock time, so the key may or may not still exist. What matters
80+
// is that the goroutine is no longer running. We verify this by
81+
// confirming no panic on double-close and that StopGC is idempotent
82+
// in the sense that calling it again doesn't panic.)
83+
84+
// After StopGC, the stopCh is closed. Calling StopGC again would
85+
// panic on a double-close. Verify the goroutine has exited by
86+
// ensuring no further GC runs modify state after the stop.
87+
//
88+
// Reset clock to present so all entries are "fresh" relative to maxAge.
89+
// (They were added at clk's initial time; clk is now 2h ahead, so
90+
// entries are 2h old. Reset to just after epoch so they look fresh.)
91+
clk.mu.Lock()
92+
clk.t = time.Date(2024, 1, 1, 0, 0, 1, 0, time.UTC)
93+
clk.mu.Unlock()
94+
95+
// Add a new entry after stop.
96+
s.Increment("key2")
97+
98+
// Wait a bit; if GC were still running it might remove entries.
99+
time.Sleep(50 * time.Millisecond)
100+
101+
s.mu.Lock()
102+
_, hasKey2 := s.data["key2"]
103+
s.mu.Unlock()
104+
105+
if !hasKey2 {
106+
t.Error("GC should not be running after StopGC; key2 should still be present")
107+
}
108+
}
Collapse file

‎keep.go‎

Copy file name to clipboardExpand all lines: keep.go
+11Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"fmt"
66
"sort"
77
"sync"
8+
"time"
89

910
keepcel "github.com/majorcontext/keep/internal/cel"
1011
"github.com/majorcontext/keep/internal/config"
@@ -85,13 +86,23 @@ func Load(rulesDir string, opts ...Option) (*Engine, error) {
8586
return nil, err
8687
}
8788

89+
store.StartGC(60*time.Second, 24*time.Hour)
90+
8891
return &Engine{
8992
evaluators: evaluators,
9093
rateStore: store,
9194
cfg: cfg,
9295
}, nil
9396
}
9497

98+
// Close stops the rate counter GC goroutine. Call this when the engine
99+
// is no longer needed to prevent goroutine leaks.
100+
func (e *Engine) Close() {
101+
if e.rateStore != nil {
102+
e.rateStore.StopGC()
103+
}
104+
}
105+
95106
// Evaluate runs all rules in the given scope against the call and returns
96107
// the policy decision.
97108
func (e *Engine) Evaluate(call Call, scope string) (EvalResult, error) {
Collapse file

‎keep_test.go‎

Copy file name to clipboardExpand all lines: keep_test.go
+9Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ func TestLoad_ValidRules(t *testing.T) {
1313
if err != nil {
1414
t.Fatalf("Load() error: %v", err)
1515
}
16+
defer eng.Close()
1617

1718
scopes := eng.Scopes()
1819
want := []string{"anthropic-gateway", "linear-tools"}
@@ -57,6 +58,7 @@ func TestLoad_WithOptions(t *testing.T) {
5758
if err != nil {
5859
t.Fatalf("Load() error: %v", err)
5960
}
61+
defer eng.Close()
6062
if len(eng.Scopes()) == 0 {
6163
t.Error("expected at least one scope")
6264
}
@@ -67,6 +69,7 @@ func TestEngine_Scopes(t *testing.T) {
6769
if err != nil {
6870
t.Fatalf("Load() error: %v", err)
6971
}
72+
defer eng.Close()
7073

7174
scopes := eng.Scopes()
7275
// Must be sorted.
@@ -83,6 +86,7 @@ func TestEvaluate_Allow(t *testing.T) {
8386
if err != nil {
8487
t.Fatalf("Load() error: %v", err)
8588
}
89+
defer eng.Close()
8690

8791
result, err := eng.Evaluate(keep.Call{
8892
Operation: "create_issue",
@@ -101,6 +105,7 @@ func TestEvaluate_Deny(t *testing.T) {
101105
if err != nil {
102106
t.Fatalf("Load() error: %v", err)
103107
}
108+
defer eng.Close()
104109

105110
result, err := eng.Evaluate(keep.Call{
106111
Operation: "delete_issue",
@@ -122,6 +127,7 @@ func TestEvaluate_DenyWhen(t *testing.T) {
122127
if err != nil {
123128
t.Fatalf("Load() error: %v", err)
124129
}
130+
defer eng.Close()
125131

126132
result, err := eng.Evaluate(keep.Call{
127133
Operation: "create_issue",
@@ -143,6 +149,7 @@ func TestEvaluate_Redact(t *testing.T) {
143149
if err != nil {
144150
t.Fatalf("Load() error: %v", err)
145151
}
152+
defer eng.Close()
146153

147154
result, err := eng.Evaluate(keep.Call{
148155
Operation: "llm.tool_result",
@@ -171,6 +178,7 @@ func TestEvaluate_UnknownScope(t *testing.T) {
171178
if err != nil {
172179
t.Fatalf("Load() error: %v", err)
173180
}
181+
defer eng.Close()
174182

175183
_, err = eng.Evaluate(keep.Call{
176184
Operation: "anything",
@@ -217,6 +225,7 @@ func TestReload(t *testing.T) {
217225
if err != nil {
218226
t.Fatalf("Load() error: %v", err)
219227
}
228+
defer eng.Close()
220229

221230
if len(eng.Scopes()) != 1 {
222231
t.Fatalf("Scopes() = %v, want 1 scope", eng.Scopes())

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.