GeezerVison is showing github.com — feat(rate): add periodic GC for expired counter entries · majorcontext/keep@b1c46df
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: internal/rate/counter.go +30-3Lines changed: 30 additions & 3 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -19,9 +19,10 @@ func (realClock) Now() time.Time { return time.Now() } | 19 | 19 |
| 20 | 20 | // Store is a thread-safe sliding window counter store. | 21 | 21 | 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{} | 25 | 26 | } | 26 | 27 |
| 27 | 28 | // NewStore creates a new counter store using real time. | @@ -64,6 +65,32 @@ func (s *Store) Count(key string, window time.Duration) int { | 64 | 65 | return count | 65 | 66 | } | 66 | 67 |
| | 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 | + | 67 | 94 | // GC removes entries older than maxAge from all keys. | 68 | 95 | // Removes keys that become empty. | 69 | 96 | func (s *Store) GC(maxAge time.Duration) { | |
Collapse file Copy file name to clipboard +108Lines changed: 108 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 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 Copy file name to clipboardExpand all lines: keep.go +11Lines changed: 11 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 5 | 5 | "fmt" | 6 | 6 | "sort" | 7 | 7 | "sync" | | 8 | + "time" | 8 | 9 |
| 9 | 10 | keepcel "github.com/majorcontext/keep/internal/cel" | 10 | 11 | "github.com/majorcontext/keep/internal/config" | @@ -85,13 +86,23 @@ func Load(rulesDir string, opts ...Option) (*Engine, error) { | 85 | 86 | return nil, err | 86 | 87 | } | 87 | 88 |
| | 89 | + store.StartGC(60*time.Second, 24*time.Hour) | | 90 | + | 88 | 91 | return &Engine{ | 89 | 92 | evaluators: evaluators, | 90 | 93 | rateStore: store, | 91 | 94 | cfg: cfg, | 92 | 95 | }, nil | 93 | 96 | } | 94 | 97 |
| | 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 | + | 95 | 106 | // Evaluate runs all rules in the given scope against the call and returns | 96 | 107 | // the policy decision. | 97 | 108 | func (e *Engine) Evaluate(call Call, scope string) (EvalResult, error) { | |
Collapse file Copy file name to clipboardExpand all lines: keep_test.go +9Lines changed: 9 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -13,6 +13,7 @@ func TestLoad_ValidRules(t *testing.T) { | 13 | 13 | if err != nil { | 14 | 14 | t.Fatalf("Load() error: %v", err) | 15 | 15 | } | | 16 | + defer eng.Close() | 16 | 17 |
| 17 | 18 | scopes := eng.Scopes() | 18 | 19 | want := []string{"anthropic-gateway", "linear-tools"} | @@ -57,6 +58,7 @@ func TestLoad_WithOptions(t *testing.T) { | 57 | 58 | if err != nil { | 58 | 59 | t.Fatalf("Load() error: %v", err) | 59 | 60 | } | | 61 | + defer eng.Close() | 60 | 62 | if len(eng.Scopes()) == 0 { | 61 | 63 | t.Error("expected at least one scope") | 62 | 64 | } | @@ -67,6 +69,7 @@ func TestEngine_Scopes(t *testing.T) { | 67 | 69 | if err != nil { | 68 | 70 | t.Fatalf("Load() error: %v", err) | 69 | 71 | } | | 72 | + defer eng.Close() | 70 | 73 |
| 71 | 74 | scopes := eng.Scopes() | 72 | 75 | // Must be sorted. | @@ -83,6 +86,7 @@ func TestEvaluate_Allow(t *testing.T) { | 83 | 86 | if err != nil { | 84 | 87 | t.Fatalf("Load() error: %v", err) | 85 | 88 | } | | 89 | + defer eng.Close() | 86 | 90 |
| 87 | 91 | result, err := eng.Evaluate(keep.Call{ | 88 | 92 | Operation: "create_issue", | @@ -101,6 +105,7 @@ func TestEvaluate_Deny(t *testing.T) { | 101 | 105 | if err != nil { | 102 | 106 | t.Fatalf("Load() error: %v", err) | 103 | 107 | } | | 108 | + defer eng.Close() | 104 | 109 |
| 105 | 110 | result, err := eng.Evaluate(keep.Call{ | 106 | 111 | Operation: "delete_issue", | @@ -122,6 +127,7 @@ func TestEvaluate_DenyWhen(t *testing.T) { | 122 | 127 | if err != nil { | 123 | 128 | t.Fatalf("Load() error: %v", err) | 124 | 129 | } | | 130 | + defer eng.Close() | 125 | 131 |
| 126 | 132 | result, err := eng.Evaluate(keep.Call{ | 127 | 133 | Operation: "create_issue", | @@ -143,6 +149,7 @@ func TestEvaluate_Redact(t *testing.T) { | 143 | 149 | if err != nil { | 144 | 150 | t.Fatalf("Load() error: %v", err) | 145 | 151 | } | | 152 | + defer eng.Close() | 146 | 153 |
| 147 | 154 | result, err := eng.Evaluate(keep.Call{ | 148 | 155 | Operation: "llm.tool_result", | @@ -171,6 +178,7 @@ func TestEvaluate_UnknownScope(t *testing.T) { | 171 | 178 | if err != nil { | 172 | 179 | t.Fatalf("Load() error: %v", err) | 173 | 180 | } | | 181 | + defer eng.Close() | 174 | 182 |
| 175 | 183 | _, err = eng.Evaluate(keep.Call{ | 176 | 184 | Operation: "anything", | @@ -217,6 +225,7 @@ func TestReload(t *testing.T) { | 217 | 225 | if err != nil { | 218 | 226 | t.Fatalf("Load() error: %v", err) | 219 | 227 | } | | 228 | + defer eng.Close() | 220 | 229 |
| 221 | 230 | if len(eng.Scopes()) != 1 { | 222 | 231 | t.Fatalf("Scopes() = %v, want 1 scope", eng.Scopes()) | |
|