forked from llm-d/llm-d-router
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregistry_test.go
More file actions
1396 lines (1126 loc) · 47.6 KB
/
Copy pathregistry_test.go
File metadata and controls
1396 lines (1126 loc) · 47.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2025 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package registry
import (
"context"
"fmt"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/go-logr/logr"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
testclock "k8s.io/utils/clock/testing"
crmetrics "sigs.k8s.io/controller-runtime/pkg/metrics"
"github.com/llm-d/llm-d-router/pkg/epp/flowcontrol/contracts"
"github.com/llm-d/llm-d-router/pkg/epp/framework/interface/flowcontrol"
"github.com/llm-d/llm-d-router/pkg/epp/framework/interface/flowcontrol/mocks"
eppmetrics "github.com/llm-d/llm-d-router/pkg/epp/metrics"
)
// --- Test Harness ---
// registryTestHarness provides a fully initialized test harness for the `FlowRegistry`.
type registryTestHarness struct {
t *testing.T
fr *FlowRegistry
config Config
fakeClock *testclock.FakeClock
}
// harnessOptions configures the test harness.
type harnessOptions struct {
config *Config
manualGC bool
}
// newRegistryTestHarness creates and starts a new `FlowRegistry` for testing.
func newRegistryTestHarness(t *testing.T, opts harnessOptions) *registryTestHarness {
t.Helper()
var cfg *Config
var err error
if opts.config != nil {
cfg = opts.config.Clone()
} else {
cfg, err = NewConfig(
newTestPriorityBandPolicyDefaults(),
WithFlowGCTimeout(5*time.Minute),
WithPriorityBand(&PriorityBandConfig{Priority: highPriority}),
WithPriorityBand(&PriorityBandConfig{Priority: lowPriority}),
)
require.NoError(t, err, "Test setup: failed to create default config")
}
fakeClock := testclock.NewFakeClock(time.Now())
registryOpts := []RegistryOption{withClock(fakeClock)}
fr := NewFlowRegistry(cfg, logr.Discard(), registryOpts...)
if !opts.manualGC {
ctx, cancel := context.WithCancel(context.Background())
var wg sync.WaitGroup
wg.Go(func() {
fr.RunMaintenanceLoop(ctx)
})
t.Cleanup(func() {
cancel()
wg.Wait()
})
}
return ®istryTestHarness{
t: t,
fr: fr,
config: *fr.config,
fakeClock: fakeClock,
}
}
// assertFlowExists synchronously checks if a flow's queue exists.
func (h *registryTestHarness) assertFlowExists(key flowcontrol.FlowKey, msgAndArgs ...any) {
h.t.Helper()
_, err := h.fr.ManagedQueue(key)
assert.NoError(h.t, err, msgAndArgs...)
}
// assertFlowDoesNotExist synchronously checks if a flow's queue does not exist.
func (h *registryTestHarness) assertFlowDoesNotExist(key flowcontrol.FlowKey, msgAndArgs ...any) {
h.t.Helper()
_, err := h.fr.ManagedQueue(key)
require.Error(h.t, err, "Expected an error when getting a non-existent flow, but got none")
assert.ErrorIs(h.t, err, contracts.ErrFlowInstanceNotFound, msgAndArgs...)
}
// openConnectionOnFlow ensures a flow is registered for the provided `key`.
func (h *registryTestHarness) openConnectionOnFlow(key flowcontrol.FlowKey) {
h.t.Helper()
h.fr.mu.RLock()
_, exists := h.fr.config.PriorityBands[key.Priority]
h.fr.mu.RUnlock()
if !exists {
// Provision the band without asserting it into the desired set, so GC tests exercise
// collection of idle, undesired bands. Tests that need a band protected from GC mark it
// desired explicitly via ApplyDesiredPriorities.
require.NoError(h.t, h.fr.ensurePriorityBand(key.Priority), "Provisioning band for flow %s should not fail", key)
}
err := h.fr.WithConnection(key, func(conn contracts.ActiveFlowConnection) error { return nil })
require.NoError(h.t, err, "Registering flow %s should not fail", key)
h.assertFlowExists(key, "Flow %s should exist after registration", key)
}
// --- `FlowRegistryClient` API Tests ---
func TestFlowRegistry_WithConnection_AndHandle(t *testing.T) {
t.Parallel()
t.Run("ShouldJITRegisterFlow_OnFirstConnection", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{})
key := flowcontrol.FlowKey{ID: "jit-flow", Priority: highPriority}
h.assertFlowDoesNotExist(key, "Flow should not exist before the first connection")
err := h.fr.WithConnection(key, func(conn contracts.ActiveFlowConnection) error {
h.assertFlowExists(key, "Flow should exist immediately after JIT registration within the connection")
require.NotNil(t, conn, "Connection handle provided to callback must not be nil")
return nil
})
require.NoError(t, err, "WithConnection should succeed for a new flow")
h.assertFlowExists(key, "Flow should remain in the registry after the connection is closed")
})
t.Run("ShouldFail_WhenFlowIDIsEmpty", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{})
key := flowcontrol.FlowKey{ID: "", Priority: highPriority} // Invalid key
err := h.fr.WithConnection(key, func(conn contracts.ActiveFlowConnection) error {
t.Fatal("Callback must not be executed when the provided flow key is invalid")
return nil
})
require.Error(t, err, "WithConnection must return an error for an empty flow ID")
assert.ErrorIs(t, err, contracts.ErrFlowIDEmpty, "The returned error must be of the correct type")
})
t.Run("ShouldFail_WhenJITFails", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{})
// Priority 999 has no configured band, so flow provisioning fails at JIT registration.
key := flowcontrol.FlowKey{ID: "test-flow", Priority: 999}
err := h.fr.WithConnection(key, func(conn contracts.ActiveFlowConnection) error {
t.Fatal("Callback must not be executed when the flow fails to register JIT")
return nil
})
require.Error(t, err, "WithConnection must return an error for a failed flow JIT registration")
assert.ErrorIs(t, err, contracts.ErrPriorityBandNotFound, "The returned error must propagate the reason")
})
t.Run("Handle_GetDataPlane_ShouldReturnNonNil", func(t *testing.T) {
t.Parallel()
// Create a registry
h := newRegistryTestHarness(t, harnessOptions{})
key := flowcontrol.FlowKey{ID: "test-flow", Priority: highPriority}
err := h.fr.WithConnection(key, func(conn contracts.ActiveFlowConnection) error {
dataPlane := conn.GetDataPlane()
assert.NotNil(t, dataPlane, "GetDataPlane() must never return nil")
return nil
})
require.NoError(t, err)
})
}
// --- `FlowRegistryAdmin` API Tests ---
func TestFlowRegistry_Stats(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{})
keyHigh := flowcontrol.FlowKey{ID: "high-pri-flow", Priority: highPriority}
keyLow := flowcontrol.FlowKey{ID: "low-pri-flow", Priority: lowPriority}
h.openConnectionOnFlow(keyHigh)
h.openConnectionOnFlow(keyLow)
mqHigh, _ := h.fr.ManagedQueue(keyHigh)
mqLow, _ := h.fr.ManagedQueue(keyLow)
require.NoError(t, mqHigh.Add(mocks.NewMockQueueItemAccessor(10, "req1", keyHigh)),
"Adding item to queue should not fail")
require.NoError(t, mqLow.Add(mocks.NewMockQueueItemAccessor(30, "req3", keyLow)),
"Adding item to queue should not fail")
// Although the production `Stats()` method provides a 'fuzzy snapshot' under high contention, our test validates it
// in a quiescent state, so these assertions can and must be exact.
globalStats := h.fr.Stats()
assert.Equal(t, uint64(2), globalStats.TotalLen, "Global TotalLen should be the sum of all items")
assert.Equal(t, uint64(40), globalStats.TotalByteSize, "Global TotalByteSize should be the sum of all item sizes")
// Verify per-band stats are correctly propagated, not just global totals.
highBandStats, ok := globalStats.PerPriorityBandStats[highPriority]
require.True(t, ok, "PerPriorityBandStats should contain the high-priority band")
assert.Equal(t, uint64(1), highBandStats.Len,
"High-priority band should track 1 item")
assert.Equal(t, uint64(10), highBandStats.ByteSize,
"High-priority band should track 10 bytes")
lowBandStats, ok := globalStats.PerPriorityBandStats[lowPriority]
require.True(t, ok, "PerPriorityBandStats should contain the low-priority band")
assert.Equal(t, uint64(1), lowBandStats.Len,
"Low-priority band should track 1 item")
assert.Equal(t, uint64(30), lowBandStats.ByteSize,
"Low-priority band should track 30 bytes")
}
// --- Garbage Collection Tests ---
func TestFlowRegistry_GarbageCollection(t *testing.T) {
t.Run("ShouldCollectIdleFlow", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{manualGC: true})
key := flowcontrol.FlowKey{ID: "idle-flow", Priority: highPriority}
h.openConnectionOnFlow(key) // Create a flow, which is born Idle.
h.fakeClock.Step(h.config.FlowGCTimeout + time.Second) // Advance the clock just past the GC timeout.
h.fr.ExecuteGCCycle() // Manually and deterministically trigger a GC cycle.
h.assertFlowDoesNotExist(key, "Idle flow should be collected by the GC")
})
t.Run("ShouldNotCollectActiveFlow", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{})
key := flowcontrol.FlowKey{ID: "active-flow", Priority: highPriority}
var wg sync.WaitGroup
leaseAcquired := make(chan struct{})
releaseLease := make(chan struct{})
wg.Go(func() {
// This goroutine holds the lease. It will not exit until the main test goroutine calls `wg.Done()`.
err := h.fr.WithConnection(key, func(contracts.ActiveFlowConnection) error {
close(leaseAcquired) // Signal to the main test that the lease is now active.
<-releaseLease // Block here, holding the lease, until signaled.
return nil
})
require.NoError(t, err, "WithConnection in the background goroutine should not fail")
})
t.Cleanup(func() {
close(releaseLease) // Unblock the goroutine.
wg.Wait() // Wait for the goroutine to fully exit.
})
<-leaseAcquired // Wait until the goroutine confirms that it has acquired the lease.
h.fakeClock.Step(h.config.FlowGCTimeout * 2) // Advance the clock well past the GC timeout.
h.fr.ExecuteGCCycle() // Manually and deterministically trigger a GC cycle.
h.assertFlowExists(key, "An active flow must not be garbage collected, even after a forced GC cycle")
})
t.Run("ShouldResetGCTimer_WhenFlowBecomesActive", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{})
key := flowcontrol.FlowKey{ID: "reactivated-flow", Priority: highPriority}
h.openConnectionOnFlow(key) // Create an flow with a new idleness timer.
h.fakeClock.Step(h.config.FlowGCTimeout - time.Second) // Advance the clock to just before the GC timeout.
h.openConnectionOnFlow(key) // Open a new connection, resetting its idleness timer.
h.fakeClock.Step(2 * time.Second) // Advance the clock again.
h.fr.ExecuteGCCycle() // Manually and deterministically trigger a GC cycle.
h.assertFlowExists(key, "Flow should survive GC because its idleness timer was reset")
})
t.Run("ShouldSkipGC_WhenIdleTimeoutExpired_ButActiveLeaseExists", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{})
key := flowcontrol.FlowKey{ID: "race-resurrected-flow", Priority: highPriority}
h.openConnectionOnFlow(key)
// Manually manipulate the state to simulate a race condition.
// The flow is "Technically Idle" (timeout expired) ...
val, ok := h.fr.flowStates.Load(key)
require.True(t, ok)
state := val.(*flowState)
// Force the idle timestamp to be old.
oldTime := h.fakeClock.Now().Add(-h.config.FlowGCTimeout * 2)
state.mu.Lock()
state.becameIdleAt = oldTime
// ... BUT it has an active lease (simulating a request arriving just now).
// Note: In the real code, these two updates happen atomically, but we force this
// state to verify the GC's safety priority (Lease > Time).
state.leaseCount = 1
state.mu.Unlock()
// Trigger GC.
h.fr.ExecuteGCCycle()
// The GC should have seen the leaseCount > 0 and skipped the deletion, despite the expired timestamp.
h.assertFlowExists(key, "Flow must not be collected if lease > 0, even if idle timer is expired")
})
}
// --- Dynamic Provisioning Tests ---
func TestFlowRegistry_DynamicProvisioning(t *testing.T) {
t.Parallel()
t.Run("SubmitDesiredPriorities_DoesNotBlockWithoutProcessor", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{manualGC: true})
done := make(chan struct{})
go func() {
defer close(done)
for i := range 100 {
h.fr.SubmitDesiredPriorities(map[int]struct{}{i: {}})
}
}()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("SubmitDesiredPriorities blocked without a processor consumer")
}
})
t.Run("ShouldRejectUnknownPriority_WhenBandNotProvisioned", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{})
key := flowcontrol.FlowKey{ID: "unprovisioned-flow", Priority: 55}
err := h.fr.WithConnection(key, func(conn contracts.ActiveFlowConnection) error {
return nil
})
require.Error(t, err)
assert.ErrorIs(t, err, contracts.ErrPriorityBandNotFound)
})
t.Run("ShouldCreateBand_WhenPriorityIsUnknown", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{})
dynamicPrio := 55
key := flowcontrol.FlowKey{ID: "dynamic-flow", Priority: dynamicPrio}
h.fr.ApplyDesiredPriorities(map[int]struct{}{dynamicPrio: {}})
err := h.fr.WithConnection(key, func(conn contracts.ActiveFlowConnection) error {
return nil
})
require.NoError(t, err, "WithConnection should succeed after control-plane provisioning")
h.fr.mu.RLock()
_, existsInConfig := h.fr.config.PriorityBands[dynamicPrio]
h.fr.mu.RUnlock()
assert.True(t, existsInConfig, "Dynamic priority must be added to global config definition")
stats := h.fr.Stats()
_, existsInStats := stats.PerPriorityBandStats[dynamicPrio]
assert.True(t, existsInStats, "Dynamic priority must appear in global stats")
_, err = h.fr.ManagedQueue(key)
assert.NoError(t, err, "Dynamic band must be provisioned")
})
t.Run("ShouldHandleConcurrentDynamicCreation", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{})
dynamicPrio := 77
key := flowcontrol.FlowKey{ID: "race-flow", Priority: dynamicPrio}
h.fr.ApplyDesiredPriorities(map[int]struct{}{dynamicPrio: {}})
var wg sync.WaitGroup
concurrency := 10
wg.Add(concurrency)
for range concurrency {
go func() {
defer wg.Done()
_ = h.fr.WithConnection(key, func(conn contracts.ActiveFlowConnection) error { return nil })
}()
}
wg.Wait()
h.fr.mu.RLock()
_, exists := h.fr.config.PriorityBands[dynamicPrio]
h.fr.mu.RUnlock()
assert.True(t, exists, "Band should exist after concurrent creation attempts")
})
t.Run("ShouldPersistDynamicBands", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{})
dynamicPrio := 88
key := flowcontrol.FlowKey{ID: "scaling-flow", Priority: dynamicPrio}
h.fr.ApplyDesiredPriorities(map[int]struct{}{dynamicPrio: {}})
h.openConnectionOnFlow(key)
_, policyErr := h.fr.FairnessPolicy(dynamicPrio)
assert.NoError(t, policyErr, "The dynamic priority band must have been configured")
mq, err := h.fr.ManagedQueue(key)
require.NoError(t, err, "Existing flows should be auto-synced")
require.NotNil(t, mq)
})
t.Run("ShouldUseNegativeBandTemplate_WhenPriorityBelowZero", func(t *testing.T) {
t.Parallel()
defaults := newTestPriorityBandPolicyDefaults()
negativeMaxBytes := uint64(256)
cfg, err := NewConfig(defaults,
WithDefaultNegativePriorityBand(&PriorityBandConfig{
MaxBytes: negativeMaxBytes,
}),
)
require.NoError(t, err)
h := newRegistryTestHarness(t, harnessOptions{config: cfg})
negativePrio := -5
key := flowcontrol.FlowKey{ID: "negative-flow", Priority: negativePrio}
h.fr.ApplyDesiredPriorities(map[int]struct{}{negativePrio: {}})
err = h.fr.WithConnection(key, func(conn contracts.ActiveFlowConnection) error {
return nil
})
require.NoError(t, err, "WithConnection should succeed for negative priority")
h.fr.mu.RLock()
band, exists := h.fr.config.PriorityBands[negativePrio]
h.fr.mu.RUnlock()
require.True(t, exists, "Negative priority band should be dynamically provisioned")
assert.Equal(t, negativeMaxBytes, band.MaxBytes,
"Negative priority band should use DefaultNegativePriorityBand template")
})
t.Run("ShouldFallBackToDefaultBand_WhenNegativeTemplateIsNil", func(t *testing.T) {
t.Parallel()
defaults := newTestPriorityBandPolicyDefaults()
cfg, err := NewConfig(defaults)
require.NoError(t, err)
h := newRegistryTestHarness(t, harnessOptions{config: cfg})
negativePrio := -3
key := flowcontrol.FlowKey{ID: "fallback-flow", Priority: negativePrio}
h.fr.ApplyDesiredPriorities(map[int]struct{}{negativePrio: {}})
err = h.fr.WithConnection(key, func(conn contracts.ActiveFlowConnection) error {
return nil
})
require.NoError(t, err)
h.fr.mu.RLock()
band, exists := h.fr.config.PriorityBands[negativePrio]
h.fr.mu.RUnlock()
require.True(t, exists, "Negative priority band should still be provisioned")
assert.Equal(t, defaultPriorityBandMaxBytes, band.MaxBytes,
"Without negative template, should fall back to default band's MaxBytes")
})
t.Run("ShouldUseDefaultBand_WhenPositivePriorityWithNegativeTemplate", func(t *testing.T) {
t.Parallel()
defaults := newTestPriorityBandPolicyDefaults()
negativeMaxBytes := uint64(100)
cfg, err := NewConfig(defaults,
WithDefaultNegativePriorityBand(&PriorityBandConfig{
MaxBytes: negativeMaxBytes,
}),
)
require.NoError(t, err)
h := newRegistryTestHarness(t, harnessOptions{config: cfg})
positivePrio := 42
key := flowcontrol.FlowKey{ID: "positive-flow", Priority: positivePrio}
h.fr.ApplyDesiredPriorities(map[int]struct{}{positivePrio: {}})
err = h.fr.WithConnection(key, func(conn contracts.ActiveFlowConnection) error {
return nil
})
require.NoError(t, err)
h.fr.mu.RLock()
band, exists := h.fr.config.PriorityBands[positivePrio]
h.fr.mu.RUnlock()
require.True(t, exists, "Positive priority band should be provisioned")
assert.Equal(t, defaultPriorityBandMaxBytes, band.MaxBytes,
"Positive priorities should use DefaultPriorityBand, not the negative template")
})
}
// --- Concurrency Tests ---
func TestFlowRegistry_Concurrency(t *testing.T) {
t.Parallel()
t.Run("ConcurrentJITRegistrations_ShouldBeSafe", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{})
key := flowcontrol.FlowKey{ID: "concurrent-flow", Priority: highPriority}
numGoroutines := 50
var wg sync.WaitGroup
wg.Add(numGoroutines)
// Hammer the `WithConnection` method for the same key from many goroutines.
for range numGoroutines {
go func() {
defer wg.Done()
err := h.fr.WithConnection(key, func(contracts.ActiveFlowConnection) error {
// Do a small amount of work inside the connection.
time.Sleep(1 * time.Millisecond)
return nil
})
require.NoError(t, err, "Concurrent WithConnection calls must not fail")
}()
}
wg.Wait()
// The primary assertion is that this completes without the race detector firing.
// We can also check that the flow state is consistent.
h.assertFlowExists(key, "Flow must exist after concurrent JIT registration")
})
t.Run("ShouldRecover_WhenGCDeletesFlow_DuringConnectionAttempt", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{})
key := flowcontrol.FlowKey{ID: "zombie-race-flow", Priority: highPriority}
// We want to force the specific race in pinActiveFlow where:
// 1. User loads ptr A.
// 2. GC deletes ptr A from Map.
// 3. User checks map, sees nil or ptr B.
// 4. User retries.
var wg sync.WaitGroup
stopCh := make(chan struct{})
// Routine 1: The "User" - Constantly tries to connect.
wg.Go(func() {
for {
select {
case <-stopCh:
return
default:
// This triggers the optimistic loop.
err := h.fr.WithConnection(key, func(c contracts.ActiveFlowConnection) error {
return nil
})
if err != nil {
h.t.Logf("Connection failed during race: %v", err)
}
}
}
})
// Routine 2: The "GC" - Constantly deletes the flow.
wg.Go(func() {
for {
select {
case <-stopCh:
return
default:
// Forcefully delete the key to trigger the "Zombie" condition in Routine 1.
h.fr.flowStates.Delete(key)
time.Sleep(100 * time.Microsecond) // Yield briefly to let Routine 1 make progress
}
}
})
// Let the chaos run for a bit.
time.Sleep(100 * time.Millisecond)
close(stopCh)
wg.Wait()
// Final consistency check: Ensure that we can still connect successfully after the chaos.
// If the optimistic loop works, the final state in the map should be valid.
h.openConnectionOnFlow(key)
})
t.Run("ShouldBackOff_WhenFlowIsMarkedForDeletion_ButStillInMap", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{})
key := flowcontrol.FlowKey{ID: "doomed-flow", Priority: highPriority}
h.openConnectionOnFlow(key)
// Get the original flow state object.
val, ok := h.fr.flowStates.Load(key)
require.True(t, ok)
originalState := val.(*flowState)
// Manually poison it (simulate GC step: marked but not yet deleted from map).
originalState.mu.Lock()
originalState.markedForDeletion = true
originalState.mu.Unlock()
// Launch a background routine to simulate the GC completing the deletion.
// Without this, the main thread would spin forever in pinActiveFlow reloading the same doomed object.
var wg sync.WaitGroup
wg.Go(func() {
// Yield to allow the main thread to enter the retry loop and hit the "poisoned" check at least once.
time.Sleep(10 * time.Millisecond)
h.fr.flowStates.Delete(key)
})
// Attempt to connect.
// It should spin briefly, detect the deletion, create a new flow, and succeed.
err := h.fr.WithConnection(key, func(c contracts.ActiveFlowConnection) error {
return nil
})
require.NoError(t, err, "WithConnection should recover and succeed")
wg.Wait()
// Verification: Ensure we are using a fresh object, not the resurrected corpse.
newVal, ok := h.fr.flowStates.Load(key)
require.True(t, ok)
assert.NotSame(t, originalState, newVal, "Should have created a new flow object, not reused the marked one")
})
t.Run("ConcurrentDynamicBandProvisioning_WithGC", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{})
const (
numWorkers = 10
numPriorities = 20 // Create 20 different dynamic bands
opsPerWorker = 10
)
var wg sync.WaitGroup
wg.Add(numWorkers + 1) // +1 for GC goroutine
// Workers: Create flows at random priorities
for i := range numWorkers {
go func() {
defer wg.Done()
for j := range opsPerWorker {
priority := 100 + (j % numPriorities) // Rotate through priorities
key := flowcontrol.FlowKey{
ID: fmt.Sprintf("flow-%d-%d", i, j),
Priority: priority,
}
_ = h.fr.WithConnection(key, func(contracts.ActiveFlowConnection) error {
time.Sleep(1 * time.Millisecond)
return nil
})
}
}()
}
// Wait for at least one band to be created.
require.Eventually(t, func() bool {
count := 0
h.fr.priorityBandStates.Range(func(_, _ any) bool {
count++
return true
})
return count > 0
}, 5*time.Second, 10*time.Millisecond, "Dynamic bands should be created")
// Check bands were created before GC collects them all
bandCount := 0
h.fr.priorityBandStates.Range(func(_, _ any) bool {
bandCount++
return true
})
require.True(t, bandCount > 0, "Dynamic bands should be created during concurrent workload")
// GC Worker: Constantly running GC cycles
go func() {
defer wg.Done()
for range 10 {
h.fakeClock.Step(h.config.FlowGCTimeout + time.Second)
h.fr.ExecuteGCCycle()
time.Sleep(5 * time.Millisecond)
}
}()
wg.Wait()
// Primary assertion: no race detector failures
// Test completing without races proves concurrent band provisioning/GC is safe
})
}
func TestFlowRegistry_deletePriorityBand(t *testing.T) {
t.Parallel()
// highPriority (20) and lowPriority (10) come from package-level constants
const dynamicPrio = 120
t.Run("ShouldDeleteDynamicBand", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{})
// Create a dynamic priority band via JIT provisioning
err := h.fr.ensurePriorityBand(dynamicPrio)
require.NoError(t, err)
// Verify band exists in registry config
h.fr.mu.RLock()
_, exists := h.fr.config.PriorityBands[dynamicPrio]
h.fr.mu.RUnlock()
require.True(t, exists, "Dynamic band should exist in registry config")
// Verify band exists in registry
_, ok := h.fr.priorityBands.Load(dynamicPrio)
require.True(t, ok, "Band should exist")
h.fr.mu.RLock()
_, ok = h.fr.config.PriorityBands[dynamicPrio]
h.fr.mu.RUnlock()
require.True(t, ok, "Band should exist in config")
// Delete the band
h.fr.priorityBandStates.Delete(dynamicPrio)
h.fr.cleanupPriorityBandResources([]int{dynamicPrio})
// Verify band removed from registry config
h.fr.mu.RLock()
_, exists = h.fr.config.PriorityBands[dynamicPrio]
h.fr.mu.RUnlock()
assert.False(t, exists, "Band should be removed from registry config")
// Verify band removed from stats
_, exists = h.fr.perPriorityBandStats.Load(dynamicPrio)
assert.False(t, exists, "Band should be removed from stats tracking")
// Verify band removed from registry
_, ok = h.fr.priorityBands.Load(dynamicPrio)
assert.False(t, ok, "Band should be removed from registry")
h.fr.mu.RLock()
_, ok = h.fr.config.PriorityBands[dynamicPrio]
h.fr.mu.RUnlock()
assert.False(t, ok, "Band should be removed from config")
// Verify removed from ordered list
h.fr.mu.RLock()
orderedList := h.fr.orderedPriorityLevels
h.fr.mu.RUnlock()
for _, p := range orderedList {
assert.NotEqual(t, dynamicPrio, p, "Band priority should be removed from ordered list in registry")
}
})
t.Run("ShouldNotAffectOtherBands", func(t *testing.T) {
t.Parallel()
// Note: this creates the highPriority, lowPriority bands
h := newRegistryTestHarness(t, harnessOptions{})
// Create a dynamic band
err := h.fr.ensurePriorityBand(dynamicPrio)
require.NoError(t, err)
// Verify both static and dynamic bands exist
h.fr.mu.RLock()
_, highExists := h.fr.config.PriorityBands[highPriority]
_, lowExists := h.fr.config.PriorityBands[lowPriority]
_, dynamicExists := h.fr.config.PriorityBands[dynamicPrio]
h.fr.mu.RUnlock()
require.True(t, highExists && lowExists && dynamicExists, "All bands should exist")
// Delete the dynamic band
h.fr.priorityBandStates.Delete(dynamicPrio)
h.fr.cleanupPriorityBandResources([]int{dynamicPrio})
// Verify static bands still exist
h.fr.mu.RLock()
_, highExists = h.fr.config.PriorityBands[highPriority]
_, lowExists = h.fr.config.PriorityBands[lowPriority]
_, dynamicExists = h.fr.config.PriorityBands[dynamicPrio]
h.fr.mu.RUnlock()
assert.True(t, highExists, "Static high priority band should still exist")
assert.True(t, lowExists, "Static low priority band should still exist")
assert.False(t, dynamicExists, "Dynamic band should be deleted")
})
t.Run("ShouldHandleNonExistentBand", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{})
// Try to delete a band that doesn't exist - should not panic
require.NotPanics(t, func() {
h.fr.priorityBandStates.Delete(999)
h.fr.cleanupPriorityBandResources([]int{999})
})
})
}
// --- Priority Band Garbage Collection Tests ---
func TestFlowRegistry_PriorityBandGarbageCollection(t *testing.T) {
const dynamicPrio = 99
t.Run("ShouldCollectIdleDynamicBand", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{manualGC: true})
key := flowcontrol.FlowKey{ID: "test-flow", Priority: dynamicPrio}
// Create dynamic band via JIT provisioning
h.openConnectionOnFlow(key)
// Verify band exists
h.fr.mu.RLock()
_, exists := h.fr.config.PriorityBands[dynamicPrio]
h.fr.mu.RUnlock()
require.True(t, exists, "Dynamic band should exist after flow creation")
// Step 1: Collect the flow (makes band empty)
h.fakeClock.Step(h.config.FlowGCTimeout + time.Second)
h.fr.ExecuteGCCycle()
h.assertFlowDoesNotExist(key, "Flow should be collected")
// Band should still exist (in grace period)
h.fr.mu.RLock()
_, exists = h.fr.config.PriorityBands[dynamicPrio]
h.fr.mu.RUnlock()
assert.True(t, exists, "Band should still exist during grace period")
// Step 2: Wait for band GC timeout
h.fakeClock.Step(h.config.PriorityBandGCTimeout + time.Second)
h.fr.ExecuteGCCycle()
// Band should be collected
h.fr.mu.RLock()
_, exists = h.fr.config.PriorityBands[dynamicPrio]
h.fr.mu.RUnlock()
assert.False(t, exists, "Dynamic band should be collected after timeout")
})
t.Run("ShouldNotCollectStaticBands", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{manualGC: true})
// Advance time well past any GC timeout
h.fakeClock.Step(h.config.FlowGCTimeout + h.config.PriorityBandGCTimeout + time.Hour)
h.fr.ExecuteGCCycle()
// Static bands should still exist
h.fr.mu.RLock()
_, highExists := h.fr.config.PriorityBands[highPriority]
_, lowExists := h.fr.config.PriorityBands[lowPriority]
h.fr.mu.RUnlock()
assert.True(t, highExists, "Static high priority band should never be collected")
assert.True(t, lowExists, "Static low priority band should never be collected")
})
t.Run("ShouldNotCollectStaticBands_AfterFlowActivity", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{manualGC: true})
staticPriorities := []int{highPriority, 0}
// Opening a flow at a static priority creates a transient priorityBandState whose lease
// drops to zero once the flow idles, making the band a GC candidate.
for _, priority := range staticPriorities {
h.openConnectionOnFlow(flowcontrol.FlowKey{ID: "static-band-flow", Priority: priority})
}
// Collect the flows, then age the now-idle band states past the band GC timeout.
h.fakeClock.Step(h.config.FlowGCTimeout + time.Second)
h.fr.ExecuteGCCycle()
h.fakeClock.Step(h.config.PriorityBandGCTimeout + time.Second)
h.fr.ExecuteGCCycle()
for _, priority := range staticPriorities {
h.fr.mu.RLock()
_, exists := h.fr.config.PriorityBands[priority]
h.fr.mu.RUnlock()
assert.True(t, exists, "Static band %d should survive GC after its flows are collected", priority)
key := flowcontrol.FlowKey{ID: "follow-up-flow", Priority: priority}
err := h.fr.WithConnection(key, func(conn contracts.ActiveFlowConnection) error { return nil })
assert.NoError(t, err, "Request at static priority %d should succeed after GC", priority)
}
})
t.Run("ShouldNotCollectControlPlaneDesiredBand_AfterInactivity", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{manualGC: true})
// A dynamically provisioned band (one the control plane desires but that is not in the static
// EPP config) must survive GC for as long as it stays desired — even after inactivity has
// collected all of its flows and left the band idle. Reaping an idle-but-desired band makes
// every request at that priority fail until the next reconcile re-provisions it. Regression: #1354.
const desiredPrio = -1
h.fr.ApplyDesiredPriorities(map[int]struct{}{desiredPrio: {}})
// A request arrives, creating then releasing a flow at the desired priority.
key := flowcontrol.FlowKey{ID: "batch-A", Priority: desiredPrio}
h.openConnectionOnFlow(key)
// Inactivity: the flow idles and is collected, dropping the band's lease to zero and
// making it a GC candidate, despite the control plane still desiring it.
h.fakeClock.Step(h.config.FlowGCTimeout + time.Second)
h.fr.ExecuteGCCycle()
h.fakeClock.Step(h.config.PriorityBandGCTimeout + time.Second)
h.fr.ExecuteGCCycle()
h.fr.mu.RLock()
_, exists := h.fr.config.PriorityBands[desiredPrio]
h.fr.mu.RUnlock()
require.True(t, exists,
"Control-plane-desired band %d must survive GC after inactivity", desiredPrio)
// A follow-up request to the still-desired band must not be rejected with ErrPriorityBandNotFound.
err := h.fr.WithConnection(key, func(conn contracts.ActiveFlowConnection) error { return nil })
require.NoError(t, err,
"Request to a still-desired band must succeed after inactivity")
})
t.Run("ShouldCollectMultipleBands_InOneCycle", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{manualGC: true})
// Create 3 dynamic bands
prio1, prio2, prio3 := 101, 102, 103
h.openConnectionOnFlow(flowcontrol.FlowKey{ID: "flow-1", Priority: prio1})
h.openConnectionOnFlow(flowcontrol.FlowKey{ID: "flow-2", Priority: prio2})
h.openConnectionOnFlow(flowcontrol.FlowKey{ID: "flow-3", Priority: prio3})
// Verify all bands exist
h.fr.mu.RLock()
_, exists1 := h.fr.config.PriorityBands[prio1]
_, exists2 := h.fr.config.PriorityBands[prio2]
_, exists3 := h.fr.config.PriorityBands[prio3]
h.fr.mu.RUnlock()
require.True(t, exists1 && exists2 && exists3, "All dynamic bands should exist")
// Collect all flows (all bands become empty)
h.fakeClock.Step(h.config.FlowGCTimeout + time.Second)
h.fr.ExecuteGCCycle()
// Wait for band GC timeout
h.fakeClock.Step(h.config.PriorityBandGCTimeout + time.Second)
h.fr.ExecuteGCCycle()
// All bands should be collected in a single GC cycle
h.fr.mu.RLock()
_, exists1 = h.fr.config.PriorityBands[prio1]
_, exists2 = h.fr.config.PriorityBands[prio2]
_, exists3 = h.fr.config.PriorityBands[prio3]
h.fr.mu.RUnlock()
assert.False(t, exists1, "Band 1 should be collected")
assert.False(t, exists2, "Band 2 should be collected")
assert.False(t, exists3, "Band 3 should be collected")
})
t.Run("ShouldCollectBand_AfterFlowIdle", func(t *testing.T) {
t.Parallel()
h := newRegistryTestHarness(t, harnessOptions{})
key := flowcontrol.FlowKey{ID: "test-flow", Priority: dynamicPrio}
// Create flow
h.openConnectionOnFlow(key)
// Verify band exists
_, ok := h.fr.priorityBands.Load(dynamicPrio)
require.True(t, ok, "Band should exist on registry")
// Collect the flow
h.fakeClock.Step(h.config.FlowGCTimeout + time.Second)