11package ai
22
33import (
4+ "fmt"
5+ "os"
6+ "strings"
7+ "sync"
8+ "sync/atomic"
49 "testing"
510 "time"
611
@@ -71,6 +76,30 @@ func TestRateLimiter_AllowAndCap(t *testing.T) {
7176 }
7277}
7378
79+ func TestRateLimiter_AllowKeyEnforcesFairnessAndAggregateCap (t * testing.T ) {
80+ r := NewRateLimiter (4 )
81+ for index := 0 ; index < 2 ; index ++ {
82+ if ! r .AllowKey ("org-a/session-a" ) {
83+ t .Fatalf ("session A call %d was unexpectedly limited" , index )
84+ }
85+ }
86+ if r .AllowKey ("org-a/session-a" ) {
87+ t .Fatal ("one session consumed more than its fair share" )
88+ }
89+ for index := 0 ; index < 2 ; index ++ {
90+ if ! r .AllowKey ("org-a/session-b" ) {
91+ t .Fatalf ("session B call %d was unexpectedly limited" , index )
92+ }
93+ }
94+ if r .AllowKey ("org-a/session-c" ) {
95+ t .Fatal ("many sessions exceeded the aggregate cap" )
96+ }
97+ _ , used , max := r .Stats ()
98+ if used != 4 || max != 4 {
99+ t .Fatalf ("stats used=%d max=%d" , used , max )
100+ }
101+ }
102+
74103func TestRateLimiter_Disabled (t * testing.T ) {
75104 r := NewRateLimiter (0 )
76105 for i := 0 ; i < 5 ; i ++ {
@@ -86,3 +115,118 @@ func TestRateLimiter_NilSafe(t *testing.T) {
86115 t .Fatal ("nil limiter should allow" )
87116 }
88117}
118+
119+ func TestDistributedRateLimiterSharesAggregateAndFairnessAcrossInstances (t * testing.T ) {
120+ provider := storage .NewMemory ()
121+ now := time .Date (2026 , 8 , 28 , 12 , 0 , 0 , 0 , time .UTC )
122+ first := NewDistributedRateLimiter (4 , provider , "acme" , func () time.Time { return now })
123+ second := NewDistributedRateLimiter (4 , provider , "acme" , func () time.Time { return now })
124+ assertDistributedLimit (t , first , second )
125+ }
126+
127+ func TestDistributedRateLimiterConcurrentCASHasNoLostIncrements (t * testing.T ) {
128+ provider := storage .NewMemory ()
129+ now := time .Date (2026 , 8 , 28 , 12 , 0 , 0 , 0 , time .UTC )
130+ first := NewDistributedRateLimiter (10 , provider , "concurrent" , func () time.Time { return now })
131+ second := NewDistributedRateLimiter (10 , provider , "concurrent" , func () time.Time { return now })
132+ var allowed atomic.Int32
133+ var wait sync.WaitGroup
134+ for index := 0 ; index < 40 ; index ++ {
135+ wait .Add (1 )
136+ go func (index int ) {
137+ defer wait .Done ()
138+ limiter := first
139+ if index % 2 == 1 {
140+ limiter = second
141+ }
142+ if limiter .AllowKey (fmt .Sprintf ("session-%d" , index )) {
143+ allowed .Add (1 )
144+ }
145+ }(index )
146+ }
147+ wait .Wait ()
148+ if got := allowed .Load (); got != 10 {
149+ t .Fatalf ("allowed calls = %d, want exactly 10" , got )
150+ }
151+ }
152+
153+ type flakyRateProvider struct {
154+ storage.Provider
155+ failList bool
156+ }
157+
158+ func (provider * flakyRateProvider ) CompareAndSwapBlob (name string , expected , replacement []byte ) (bool , error ) {
159+ return provider .Provider .(storage.BlobCAS ).CompareAndSwapBlob (name , expected , replacement )
160+ }
161+
162+ func (provider * flakyRateProvider ) ListBlobs (prefix string ) ([]storage.Blob , error ) {
163+ if provider .failList {
164+ provider .failList = false
165+ return nil , fmt .Errorf ("injected cleanup failure" )
166+ }
167+ return provider .Provider .ListBlobs (prefix )
168+ }
169+
170+ func TestDistributedRateLimiterRetriesPostAdmissionCleanup (t * testing.T ) {
171+ provider := & flakyRateProvider {Provider : storage .NewMemory ()}
172+ now := time .Date (2026 , 8 , 28 , 12 , 0 , 0 , 0 , time .UTC )
173+ limiter := NewDistributedRateLimiter (10 , provider , "cleanup" , func () time.Time { return now })
174+ if ! limiter .AllowKey ("session-a" ) {
175+ t .Fatal ("initial admission failed" )
176+ }
177+ now = now .Add (time .Hour )
178+ provider .failList = true
179+ if ! limiter .AllowKey ("session-b" ) {
180+ t .Fatal ("cleanup failure changed committed admission" )
181+ }
182+ prefix := "ai-rate/" + limiter .scope + "/"
183+ blobs , err := provider .Provider .ListBlobs (prefix )
184+ if err != nil || len (blobs ) != 2 {
185+ t .Fatalf ("buckets after failed cleanup=%d err=%v, want 2" , len (blobs ), err )
186+ }
187+ if ! limiter .AllowKey ("session-c" ) {
188+ t .Fatal ("second current-hour admission failed" )
189+ }
190+ blobs , err = provider .Provider .ListBlobs (prefix )
191+ if err != nil || len (blobs ) != 1 || ! strings .HasSuffix (blobs [0 ].Name , bucketKey (now )) {
192+ t .Fatalf ("buckets after cleanup retry=%+v err=%v" , blobs , err )
193+ }
194+ }
195+
196+ func TestDistributedRateLimiterPostgresProviders (t * testing.T ) {
197+ dsn := os .Getenv ("TEST_POSTGRES_DSN" )
198+ if dsn == "" {
199+ t .Skip ("TEST_POSTGRES_DSN not set" )
200+ }
201+ firstProvider , err := storage .NewPostgres (storage.PostgresOptions {DSN : dsn })
202+ if err != nil {
203+ t .Fatal (err )
204+ }
205+ t .Cleanup (func () { _ = firstProvider .Close () })
206+ secondProvider , err := storage .NewPostgres (storage.PostgresOptions {DSN : dsn })
207+ if err != nil {
208+ t .Fatal (err )
209+ }
210+ t .Cleanup (func () { _ = secondProvider .Close () })
211+ now := time .Date (2026 , 8 , 28 , 12 , 0 , 0 , 0 , time .UTC )
212+ scope := fmt .Sprintf ("rate-test-%d" , time .Now ().UnixNano ())
213+ first := NewDistributedRateLimiter (4 , firstProvider , scope , func () time.Time { return now })
214+ second := NewDistributedRateLimiter (4 , secondProvider , scope , func () time.Time { return now })
215+ assertDistributedLimit (t , first , second )
216+ }
217+
218+ func assertDistributedLimit (t * testing.T , first , second * RateLimiter ) {
219+ t .Helper ()
220+ if ! first .AllowKey ("session-a" ) || ! second .AllowKey ("session-a" ) {
221+ t .Fatal ("first two calls for one session should be allowed" )
222+ }
223+ if second .AllowKey ("session-a" ) {
224+ t .Fatal ("one session exceeded its fleet-wide fair share" )
225+ }
226+ if ! second .AllowKey ("session-b" ) || ! first .AllowKey ("session-b" ) {
227+ t .Fatal ("second session should consume the remaining aggregate share" )
228+ }
229+ if first .AllowKey ("session-c" ) {
230+ t .Fatal ("instances exceeded the fleet-wide aggregate cap" )
231+ }
232+ }
0 commit comments