forked from llm-d/llm-d-router
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegration_test.go
More file actions
1397 lines (1189 loc) · 49.7 KB
/
Copy pathintegration_test.go
File metadata and controls
1397 lines (1189 loc) · 49.7 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 2026 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 flowcontrol_test
import (
"context"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/go-logr/logr"
"github.com/stretchr/testify/require"
"k8s.io/apimachinery/pkg/types"
ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics"
reqcommon "github.com/llm-d/llm-d-router/pkg/common/request"
contractmocks "github.com/llm-d/llm-d-router/pkg/epp/flowcontrol/contracts/mocks"
"github.com/llm-d/llm-d-router/pkg/epp/flowcontrol/controller"
"github.com/llm-d/llm-d-router/pkg/epp/flowcontrol/eviction"
"github.com/llm-d/llm-d-router/pkg/epp/flowcontrol/registry"
fcTypes "github.com/llm-d/llm-d-router/pkg/epp/flowcontrol/types"
"github.com/llm-d/llm-d-router/pkg/epp/framework/interface/datalayer"
"github.com/llm-d/llm-d-router/pkg/epp/framework/interface/flowcontrol"
fwkplugin "github.com/llm-d/llm-d-router/pkg/epp/framework/interface/plugin"
"github.com/llm-d/llm-d-router/pkg/epp/framework/interface/requestcontrol"
fwkrh "github.com/llm-d/llm-d-router/pkg/epp/framework/interface/requesthandling"
fwksched "github.com/llm-d/llm-d-router/pkg/epp/framework/interface/scheduling"
"github.com/llm-d/llm-d-router/pkg/epp/framework/plugins/flowcontrol/eviction/filtering"
evictionordering "github.com/llm-d/llm-d-router/pkg/epp/framework/plugins/flowcontrol/eviction/ordering"
"github.com/llm-d/llm-d-router/pkg/epp/framework/plugins/flowcontrol/fairness/globalstrict"
"github.com/llm-d/llm-d-router/pkg/epp/framework/plugins/flowcontrol/fairness/roundrobin"
"github.com/llm-d/llm-d-router/pkg/epp/framework/plugins/flowcontrol/ordering/fcfs"
"github.com/llm-d/llm-d-router/pkg/epp/framework/plugins/flowcontrol/ordering/slodeadline"
"github.com/llm-d/llm-d-router/pkg/epp/framework/plugins/flowcontrol/saturationdetector/concurrency"
"github.com/llm-d/llm-d-router/pkg/epp/framework/plugins/flowcontrol/usagelimits"
"github.com/llm-d/llm-d-router/pkg/epp/framework/plugins/requestcontrol/dataproducer/inflightload"
"github.com/llm-d/llm-d-router/pkg/epp/metadata"
eppmetrics "github.com/llm-d/llm-d-router/pkg/epp/metrics"
testutils "github.com/llm-d/llm-d-router/test/utils"
)
// ============================================================================
// Saturation Data Path Tests (producer + detector contracts)
// ============================================================================
// TestConcurrentSaturationReads verifies no data races when multiple goroutines
// read saturation while requests are being tracked and released concurrently.
func TestConcurrentSaturationReads(t *testing.T) {
t.Parallel()
ctx := t.Context()
pd := newProducerAndDetector(ctx, t, 100)
endpoints := []datalayer.Endpoint{pd.ep}
// Use a start barrier to ensure both goroutines begin concurrently.
start := make(chan struct{})
var wg sync.WaitGroup
// Writer: track and release 200 requests rapidly.
wg.Add(1)
go func() {
defer wg.Done()
<-start
for i := 0; i < 200; i++ {
schedEp := fwksched.NewEndpoint(pd.epMeta, datalayer.NewMetrics(), nil)
req := &fwksched.InferenceRequest{
RequestID: fmt.Sprintf("req-%d", i),
Body: &fwkrh.InferenceRequestBody{
TokenizedPrompt: &fwkrh.TokenizedPrompt{PerPromptTokens: [][]uint32{make([]uint32, 10)}},
},
}
result := &fwksched.SchedulingResult{
ProfileResults: map[string]*fwksched.ProfileRunResult{
"decode": {TargetEndpoints: []fwksched.Endpoint{schedEp}},
},
}
pd.producer.PreRequest(ctx, req, result)
req.SchedulingResult = result
pd.producer.ResponseBody(ctx, req,
&requestcontrol.Response{EndOfStream: true}, pd.epMeta)
}
}()
// Reader: read saturation 200 times concurrently with the writer.
// Track violations via atomic counter — require/assert must not be called
// from non-test goroutines.
var saturationViolations atomic.Int32
wg.Add(1)
go func() {
defer wg.Done()
<-start
for i := 0; i < 200; i++ {
sat := pd.detector.Saturation(ctx, endpoints)
if sat < 0.0 || sat > 1.0 {
saturationViolations.Add(1)
}
}
}()
close(start)
wg.Wait()
require.Equal(t, int32(0), saturationViolations.Load(),
"saturation was outside [0.0, 1.0] during concurrent reads")
require.InDelta(t, 0.0, pd.detector.Saturation(ctx, endpoints), 1e-9,
"saturation must return to exactly 0 after all concurrent operations complete")
}
// ============================================================================
// Full-Loop Controller Tests (detector wired into dispatch cycle)
// ============================================================================
// TestSaturationFullLoop wires a real InFlightLoadProducer, real concurrency
// detector, and real persistent endpoints into the FlowController's dispatch
// cycle via EndpointCandidates.Locate(). Verifies that the dispatch cycle
// gates on real saturation read through DynamicAttributes.
func TestSaturationFullLoop(t *testing.T) {
t.Parallel()
ctx := context.Background()
pd := newProducerAndDetector(ctx, t, 2)
// EndpointCandidates returns the SAME persistent endpoint objects that
// Extract() registered DynamicAttributes on. This is the critical contract.
persistentEndpoints := []datalayer.Endpoint{pd.ep}
h := newHarness(t, harnessOpts{
detector: pd.detector,
endpointCandidates: &contractmocks.MockEndpointCandidates{
Candidates: persistentEndpoints,
},
})
key := flowcontrol.FlowKey{ID: "flow-a", Priority: 0}
// Simulate 2 in-flight requests (maxConcurrency=2 on 1 endpoint -> saturation=1.0).
for i := 0; i < 2; i++ {
schedEp := fwksched.NewEndpoint(pd.epMeta, datalayer.NewMetrics(), nil)
req := &fwksched.InferenceRequest{
RequestID: fmt.Sprintf("prefill-%d", i),
Body: &fwkrh.InferenceRequestBody{
TokenizedPrompt: &fwkrh.TokenizedPrompt{PerPromptTokens: [][]uint32{make([]uint32, 50)}},
},
}
result := &fwksched.SchedulingResult{
ProfileResults: map[string]*fwksched.ProfileRunResult{
"decode": {TargetEndpoints: []fwksched.Endpoint{schedEp}},
},
}
pd.producer.PreRequest(h.ctx, req, result)
}
// Verify the detector sees saturation via the real Locate->Saturation path.
sat := pd.detector.Saturation(h.ctx, persistentEndpoints)
require.InDelta(t, 1.0, sat, 1e-9,
"2 in-flight requests with maxConcurrency=2 should report full saturation")
// Now enqueue a request through the FlowController. Since saturation=1.0,
// the dispatch cycle should NOT dispatch it -- it should queue.
results := make(chan dispatchResult, 1)
go func() {
reqCtx, reqCancel := context.WithTimeout(h.ctx, 1*time.Second)
defer reqCancel()
req := &testRequest{id: "queued-req", key: key, byteSize: 100, ttl: 1 * time.Second}
outcome, err := h.fc.EnqueueAndWait(reqCtx, req)
results <- dispatchResult{id: "queued-req", outcome: outcome, err: err}
}()
// The request has a 1s context timeout. It must NOT dispatch and must
// return with an eviction/rejection outcome within that timeout.
select {
case r := <-results:
require.NotEqual(t, fcTypes.QueueOutcomeDispatched, r.outcome,
"request dispatched despite full saturation -- "+
"the Locate->Saturation data path is broken (regression of #1474)")
require.Error(t, r.err, "saturated request should return an error (TTL or deadline)")
case <-time.After(3 * time.Second):
t.Fatal("request did not finalize within 3s -- possible dispatch cycle hang under full saturation")
}
}
// ============================================================================
// Dispatch Ordering Tests (SLO deadline)
// ============================================================================
// TestDispatchOrderingSLODeadline verifies that the SLO deadline ordering policy
// reads the x-llm-d-slo-ttft-ms header from real InferenceRequests.
func TestDispatchOrderingSLODeadline(t *testing.T) {
t.Parallel()
handle := testutils.NewTestHandle(t.Context())
sloPlugin, err := slodeadline.SLODeadlineOrderingPolicyFactory("slo", nil, handle)
require.NoError(t, err)
detector := newBlockedDetector()
h := newHarness(t, harnessOpts{
ordering: sloPlugin.(flowcontrol.OrderingPolicy),
detector: detector,
})
key := flowcontrol.FlowKey{ID: "flow-a", Priority: 0}
now := time.Now()
type reqSpec struct {
id string
sloMs string
}
specs := []reqSpec{
{"loose-10s", "10000"},
{"tight-500ms", "500"},
{"mid-2s", "2000"},
}
results := make(chan dispatchResult, len(specs))
for _, s := range specs {
go func() {
req := &testRequest{
id: s.id, key: key, byteSize: 100, ttl: 5 * time.Minute,
timestamp: now,
infReq: &fwksched.InferenceRequest{
RequestID: s.id,
Headers: map[string]string{metadata.TTFTSLOHeaderKey: s.sloMs},
},
}
outcome, err := h.fc.EnqueueAndWait(h.ctx, req)
results <- dispatchResult{id: s.id, outcome: outcome, err: err}
detector.Release()
}()
time.Sleep(5 * time.Millisecond)
}
require.Eventually(t, func() bool {
return h.reg.Stats().TotalLen == uint64(len(specs))
}, time.Second, time.Millisecond, "all requests should be queued before unblocking")
detector.Unblock(1)
var dispatchOrder []string
for i := 0; i < len(specs); i++ {
select {
case r := <-results:
require.NoError(t, r.err)
require.Equal(t, fcTypes.QueueOutcomeDispatched, r.outcome)
dispatchOrder = append(dispatchOrder, r.id)
case <-time.After(5 * time.Second):
t.Fatalf("timed out waiting for dispatch %d", i)
}
}
require.Equal(t, "tight-500ms", dispatchOrder[0], "tightest SLO should dispatch first")
require.Equal(t, "mid-2s", dispatchOrder[1], "middle SLO should dispatch second")
require.Equal(t, "loose-10s", dispatchOrder[2], "loosest SLO should dispatch last")
}
// ============================================================================
// Priority and Fairness Tests
// ============================================================================
// TestPriorityBackpressure verifies that high-priority requests dispatch before
// low-priority requests under saturation.
func TestPriorityBackpressure(t *testing.T) {
t.Parallel()
handle := testutils.NewTestHandle(t.Context())
oPolicy, err := fcfs.FCFSOrderingPolicyFactory("fcfs", nil, handle)
require.NoError(t, err)
fPolicy, err := globalstrict.GlobalStrictFairnessPolicyFactory("gs", nil, handle)
require.NoError(t, err)
defaults := registry.PriorityBandPolicyDefaults{
OrderingPolicy: oPolicy.(flowcontrol.OrderingPolicy),
FairnessPolicy: fPolicy.(flowcontrol.FairnessPolicy),
}
highBand, err := registry.NewPriorityBandConfig(10, defaults,
registry.WithBandMaxBytes(10_000_000_000),
)
require.NoError(t, err)
lowBand, err := registry.NewPriorityBandConfig(0, defaults,
registry.WithBandMaxBytes(10_000_000_000),
)
require.NoError(t, err)
detector := newBlockedDetector()
h := newHarness(t, harnessOpts{
detector: detector,
bands: []*registry.PriorityBandConfig{highBand, lowBand},
})
highKey := flowcontrol.FlowKey{ID: "high-flow", Priority: 10}
lowKey := flowcontrol.FlowKey{ID: "low-flow", Priority: 0}
results := make(chan dispatchResult, 4)
enqueue := func(id string, key flowcontrol.FlowKey) {
go func() {
req := &testRequest{id: id, key: key, byteSize: 100, ttl: 5 * time.Minute}
outcome, err := h.fc.EnqueueAndWait(h.ctx, req)
results <- dispatchResult{id: id, outcome: outcome, err: err}
detector.Release()
}()
}
enqueue("low-1", lowKey)
require.Eventually(t, func() bool {
return h.reg.Stats().TotalLen == 1
}, time.Second, time.Millisecond, "low-priority request should be queued")
enqueue("high-1", highKey)
require.Eventually(t, func() bool {
return h.reg.Stats().TotalLen == 2
}, time.Second, time.Millisecond, "both requests should be queued")
detector.Unblock(1)
var dispatchOrder []string
for i := 0; i < 2; i++ {
select {
case r := <-results:
require.NoError(t, r.err)
require.Equal(t, fcTypes.QueueOutcomeDispatched, r.outcome)
dispatchOrder = append(dispatchOrder, r.id)
case <-time.After(5 * time.Second):
t.Fatalf("timed out waiting for dispatch %d", i)
}
}
require.Equal(t, "high-1", dispatchOrder[0],
"high-priority should dispatch before low-priority under backpressure")
require.Equal(t, "low-1", dispatchOrder[1])
}
// TestFairnessRoundRobin verifies that round-robin fairness rotates dispatch
// across flows within a priority band.
func TestFairnessRoundRobin(t *testing.T) {
t.Parallel()
handle := testutils.NewTestHandle(t.Context())
rrPlugin, err := roundrobin.RoundRobinFairnessPolicyFactory("rr", nil, handle)
require.NoError(t, err)
detector := newBlockedDetector()
h := newHarness(t, harnessOpts{
fairness: rrPlugin.(flowcontrol.FairnessPolicy),
detector: detector,
})
flows := []string{"flow-a", "flow-b", "flow-c"}
const reqsPerFlow = 3
total := len(flows) * reqsPerFlow
results := make(chan dispatchResult, total)
for _, flow := range flows {
for i := 0; i < reqsPerFlow; i++ {
id := fmt.Sprintf("%s-req-%d", flow, i)
key := flowcontrol.FlowKey{ID: flow, Priority: 0}
go func() {
req := &testRequest{id: id, key: key, byteSize: 100, ttl: 5 * time.Minute}
outcome, err := h.fc.EnqueueAndWait(h.ctx, req)
results <- dispatchResult{id: id, flowID: key.ID, outcome: outcome, err: err}
detector.Release()
}()
time.Sleep(2 * time.Millisecond)
}
}
require.Eventually(t, func() bool {
return h.reg.Stats().TotalLen == uint64(total)
}, time.Second, time.Millisecond, "all requests should be queued before unblocking")
detector.Unblock(1)
var dispatchOrder []string
for i := 0; i < total; i++ {
select {
case r := <-results:
require.NoError(t, r.err)
require.Equal(t, fcTypes.QueueOutcomeDispatched, r.outcome)
dispatchOrder = append(dispatchOrder, r.flowID)
case <-time.After(5 * time.Second):
t.Fatalf("timed out waiting for dispatch %d of %d", i, total)
}
}
require.Len(t, dispatchOrder, total)
for round := 0; round < reqsPerFlow; round++ {
start := round * len(flows)
end := start + len(flows)
if end > len(dispatchOrder) {
break
}
chunk := dispatchOrder[start:end]
seen := map[string]bool{}
for _, f := range chunk {
seen[f] = true
}
require.Len(t, seen, len(flows),
"round %d: expected all %d flows in dispatch chunk %v", round, len(flows), chunk)
}
}
// TestUsageLimitThresholdGatesDispatch verifies that a UsageLimitPolicy with
// threshold < 1.0 triggers HoL blocking at partial saturation.
// With threshold=0.5, the dispatch cycle should block when saturation >= 0.5.
func TestUsageLimitThresholdGatesDispatch(t *testing.T) {
t.Parallel()
ctx := context.Background()
// maxConcurrency=10 on 1 endpoint. 5 in-flight -> saturation=0.5.
pd := newProducerAndDetector(ctx, t, 10)
// Threshold=0.5: HoL blocking triggers at 50% saturation.
halfThresholdPolicy := usagelimits.NewConstPolicy("half", 0.5)
h := newHarness(t, harnessOpts{
detector: pd.detector,
endpointCandidates: &contractmocks.MockEndpointCandidates{
Candidates: []datalayer.Endpoint{pd.ep},
},
usageLimitPolicy: halfThresholdPolicy,
})
key := flowcontrol.FlowKey{ID: "flow-a", Priority: 0}
// Drive 5 in-flight requests -> saturation=5/10=0.5 -> meets threshold.
for i := 0; i < 5; i++ {
schedEp := fwksched.NewEndpoint(pd.epMeta, datalayer.NewMetrics(), nil)
req := &fwksched.InferenceRequest{
RequestID: fmt.Sprintf("inflight-%d", i),
Body: &fwkrh.InferenceRequestBody{
TokenizedPrompt: &fwkrh.TokenizedPrompt{PerPromptTokens: [][]uint32{make([]uint32, 10)}},
},
}
result := &fwksched.SchedulingResult{
ProfileResults: map[string]*fwksched.ProfileRunResult{
"decode": {TargetEndpoints: []fwksched.Endpoint{schedEp}},
},
}
pd.producer.PreRequest(h.ctx, req, result)
}
// saturation=0.5, threshold=0.5: 0.5 >= 0.5 -> HoL blocking should trigger.
results := make(chan dispatchResult, 1)
go func() {
reqCtx, reqCancel := context.WithTimeout(h.ctx, 500*time.Millisecond)
defer reqCancel()
req := &testRequest{id: "gated-req", key: key, byteSize: 100, ttl: 500 * time.Millisecond}
outcome, err := h.fc.EnqueueAndWait(reqCtx, req)
results <- dispatchResult{id: "gated-req", outcome: outcome, err: err}
}()
select {
case r := <-results:
require.NotEqual(t, fcTypes.QueueOutcomeDispatched, r.outcome,
"request should NOT dispatch at saturation=0.5 with threshold=0.5")
require.Error(t, r.err,
"gated request should return an error (TTL or deadline)")
case <-time.After(3 * time.Second):
t.Fatal("request did not finalize within 3s -- possible dispatch cycle hang under partial saturation")
}
}
// ============================================================================
// Capacity Enforcement Tests (bytes, requests, global vs band)
// ============================================================================
// TestGlobalAndBandCapacityInteraction verifies that the global MaxRequests
// limit rejects requests even when the per-band limit has capacity.
func TestGlobalAndBandCapacityInteraction(t *testing.T) {
t.Parallel()
// Band allows 10 requests, but global allows only 3.
detector := newBlockedDetector()
h := newHarness(t, harnessOpts{
detector: detector,
maxRequests: 3,
bandMaxRequests: 10,
endpointCandidates: nonEmptyCandidates(),
})
key := flowcontrol.FlowKey{ID: "flow-a", Priority: 0}
const count = 3
release := h.fillQueue(t, key, count, 100, func() bool {
return h.reg.Stats().TotalLen == count
})
// The global limit (3) is exhausted while the band limit (10) still has room, so a further
// request must be rejected for capacity.
overflow := make(chan dispatchResult, 1)
go func() {
req := &testRequest{id: "overflow-req", key: key, byteSize: 100, ttl: 5 * time.Minute}
outcome, err := h.fc.EnqueueAndWait(h.ctx, req)
overflow <- dispatchResult{id: "overflow-req", outcome: outcome, err: err}
}()
select {
case r := <-overflow:
require.Equal(t, fcTypes.QueueOutcomeRejectedCapacity, r.outcome,
"global MaxRequests=3 should reject the overflow even though the band allows 10")
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for overflow rejection")
}
release()
}
// TestByteCapacityEnforcement verifies that the per-band byte capacity limit
// rejects requests when their cumulative byte size exceeds the band budget.
func TestByteCapacityEnforcement(t *testing.T) {
t.Parallel()
detector := newBlockedDetector()
h := newHarness(t, harnessOpts{
detector: detector,
bandMaxBytes: 1000,
endpointCandidates: nonEmptyCandidates(),
})
key := flowcontrol.FlowKey{ID: "flow-a", Priority: 0}
// 3 requests of 300 bytes each (900 total) fit within the 1000-byte budget.
release := h.fillQueue(t, key, 3, 300, func() bool {
return h.reg.Stats().TotalByteSize == 900
})
// A 4th 300-byte request would bring the band to 1200 bytes, so it must be rejected.
overflow := make(chan dispatchResult, 1)
go func() {
req := &testRequest{id: "byte-req-overflow", key: key, byteSize: 300, ttl: 5 * time.Minute}
outcome, err := h.fc.EnqueueAndWait(h.ctx, req)
overflow <- dispatchResult{id: "byte-req-overflow", outcome: outcome, err: err}
}()
select {
case r := <-overflow:
require.Equal(t, fcTypes.QueueOutcomeRejectedCapacity, r.outcome,
"request exceeding the band byte budget should be rejected")
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for byte-capacity rejection")
}
release()
}
// TestEmptyPoolRejectsAsNoEndpoints verifies the scale-from-zero path: when the candidate pool has no
// endpoints, requests buffer until capacity is exhausted, and the overflow rejection is surfaced as
// RejectedNoEndpoints (mapped to 503) rather than RejectedCapacity (429).
func TestEmptyPoolRejectsAsNoEndpoints(t *testing.T) {
t.Parallel()
// Blocked detector prevents dispatch; the pool is intentionally empty (no endpointCandidates set).
detector := newBlockedDetector()
h := newHarness(t, harnessOpts{
detector: detector,
bandMaxBytes: 1000,
})
key := flowcontrol.FlowKey{ID: "flow-a", Priority: 0}
// 3 requests of 300 bytes each (900 total) fit within the 1000-byte budget.
release := h.fillQueue(t, key, 3, 300, func() bool {
return h.reg.Stats().TotalByteSize == 900
})
// The 4th request exceeds the byte budget, but because the pool is empty the rejection must
// surface as RejectedNoEndpoints (503), not RejectedCapacity (429).
overflow := make(chan dispatchResult, 1)
go func() {
req := &testRequest{id: "noep-req-overflow", key: key, byteSize: 300, ttl: 5 * time.Minute}
outcome, err := h.fc.EnqueueAndWait(h.ctx, req)
overflow <- dispatchResult{id: "noep-req-overflow", outcome: outcome, err: err}
}()
select {
case r := <-overflow:
require.Equal(t, fcTypes.QueueOutcomeRejectedNoEndpoints, r.outcome,
"with an empty pool, a full-queue rejection should be RejectedNoEndpoints")
require.ErrorIs(t, r.err, fcTypes.ErrNoEndpoints,
"no-endpoints rejection should wrap ErrNoEndpoints")
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for no-endpoints rejection")
}
release()
}
// ============================================================================
// Eviction Pipeline Tests
// ============================================================================
// TestEvictionPipeline wires the real eviction components together:
// RequestEvictor + SheddableFilter + PriorityTimeOrdering + ImmediateResponseEvictor.
// Verifies: PreRequest->queue tracking->EvictN->channel closure->cleanup.
func TestEvictionPipeline(t *testing.T) {
t.Parallel()
ctx := t.Context()
handle := testutils.NewTestHandle(ctx)
orderPlugin, err := evictionordering.PriorityThenTimeOrderingFactory("evict-order", nil, handle)
require.NoError(t, err)
filterPlugin, err := filtering.SheddableFilterFactory("evict-filter", nil, handle)
require.NoError(t, err)
evictor := eviction.NewImmediateResponseEvictor()
requestEvictor := eviction.NewRequestEvictor(
orderPlugin.(flowcontrol.EvictionOrderingPolicy),
filterPlugin.(flowcontrol.EvictionFilterPolicy),
evictor,
)
epMeta := &datalayer.EndpointMetadata{
NamespacedName: types.NamespacedName{Name: "pod-1", Namespace: "default"},
Address: "10.0.0.1",
Port: "8000",
}
schedEndpoint := fwksched.NewEndpoint(epMeta, datalayer.NewMetrics(), nil)
makeResult := func() *fwksched.SchedulingResult {
return &fwksched.SchedulingResult{
PrimaryProfileName: "decode",
ProfileResults: map[string]*fwksched.ProfileRunResult{
"decode": {TargetEndpoints: []fwksched.Endpoint{schedEndpoint}},
},
}
}
// Sheddable requests have priority < 0.
sheddableReq := &fwksched.InferenceRequest{
RequestID: "shed-1",
Headers: map[string]string{reqcommon.RequestIDHeaderKey: "shed-1"},
Objectives: fwksched.RequestObjectives{Priority: -1},
}
// Non-sheddable requests have priority >= 0.
protectedReq := &fwksched.InferenceRequest{
RequestID: "protect-1",
Headers: map[string]string{reqcommon.RequestIDHeaderKey: "protect-1"},
Objectives: fwksched.RequestObjectives{Priority: 1},
}
reqCtx, reqCancel := context.WithCancel(ctx)
defer reqCancel()
requestEvictor.PreRequest(reqCtx, sheddableReq, makeResult())
requestEvictor.PreRequest(reqCtx, protectedReq, makeResult())
inFlight, evictable := requestEvictor.Stats()
require.Equal(t, 2, inFlight, "both requests should be tracked in-flight")
require.Equal(t, 1, evictable,
"only the sheddable request (priority < 0) should be evictable")
reg := requestEvictor.EvictionRegistry()
sheddableCh := reg.Get("shed-1")
require.NotNil(t, sheddableCh, "sheddable request should have an eviction channel")
evictedIDs, err := requestEvictor.EvictN(ctx, 1)
require.NoError(t, err)
require.Equal(t, []string{"shed-1"}, evictedIDs)
select {
case <-sheddableCh:
// Channel was closed by ImmediateResponseEvictor -- eviction signaled.
default:
t.Fatal("eviction channel should be closed after EvictN")
}
// Protected request's channel should still be open.
protectedCh := reg.Get("protect-1")
require.NotNil(t, protectedCh)
select {
case <-protectedCh:
t.Fatal("protected request's channel should not be closed")
default:
}
// Complete the protected request normally.
requestEvictor.ResponseBody(ctx, protectedReq,
&requestcontrol.Response{EndOfStream: true}, epMeta)
inFlight, evictable = requestEvictor.Stats()
require.Equal(t, 0, inFlight, "all requests should be cleaned up after eviction and completion")
require.Equal(t, 0, evictable)
}
// ============================================================================
// Error/Non-Happy-Path Tests (TTL, context cancel)
// ============================================================================
// TestTTLExpiryEvictsQueuedRequest verifies that a request queued under
// saturation is evicted with QueueOutcomeEvictedTTL + ErrTTLExpired when its
// TTL expires.
func TestTTLExpiryEvictsQueuedRequest(t *testing.T) {
t.Parallel()
detector := newBlockedDetector()
h := newHarness(t, harnessOpts{detector: detector})
key := flowcontrol.FlowKey{ID: "flow-a", Priority: 0}
results := make(chan dispatchResult, 1)
go func() {
req := &testRequest{id: "ttl-req", key: key, byteSize: 100, ttl: 100 * time.Millisecond}
outcome, err := h.fc.EnqueueAndWait(h.ctx, req)
results <- dispatchResult{id: "ttl-req", outcome: outcome, err: err}
}()
select {
case r := <-results:
require.Error(t, r.err)
require.ErrorIs(t, r.err, fcTypes.ErrEvicted,
"TTL-expired request should be wrapped with ErrEvicted")
require.ErrorIs(t, r.err, fcTypes.ErrTTLExpired,
"TTL-expired request should contain ErrTTLExpired")
require.Equal(t, fcTypes.QueueOutcomeEvictedTTL, r.outcome,
"TTL-expired request should have outcome QueueOutcomeEvictedTTL")
case <-time.After(5 * time.Second):
t.Fatal("request did not return after TTL expiry")
}
}
// TestCallerContextCancellationEvictsRequest verifies that cancelling the
// caller's context while a request is queued produces the correct eviction
// outcome and error chain.
func TestCallerContextCancellationEvictsRequest(t *testing.T) {
t.Parallel()
detector := newBlockedDetector()
h := newHarness(t, harnessOpts{detector: detector})
key := flowcontrol.FlowKey{ID: "flow-a", Priority: 0}
reqCtx, reqCancel := context.WithCancel(h.ctx)
results := make(chan dispatchResult, 1)
go func() {
req := &testRequest{id: "cancel-req", key: key, byteSize: 100, ttl: 5 * time.Minute}
outcome, err := h.fc.EnqueueAndWait(reqCtx, req)
results <- dispatchResult{id: "cancel-req", outcome: outcome, err: err}
}()
require.Eventually(t, func() bool {
return h.reg.Stats().TotalLen == 1
}, time.Second, time.Millisecond, "request should be queued before cancelling")
reqCancel()
select {
case r := <-results:
require.Error(t, r.err)
require.ErrorIs(t, r.err, fcTypes.ErrEvicted,
"cancelled request should be wrapped with ErrEvicted")
require.Equal(t, fcTypes.QueueOutcomeEvictedContextCancelled, r.outcome,
"cancelled request should have QueueOutcomeEvictedContextCancelled")
case <-time.After(5 * time.Second):
t.Fatal("request did not return after context cancellation")
}
}
// ============================================================================
// Shutdown and Lifecycle Tests
// ============================================================================
// TestConcurrentEnqueueDuringShutdown verifies there are no races or panics
// when requests are being enqueued concurrently with controller shutdown.
func TestConcurrentEnqueueDuringShutdown(t *testing.T) {
t.Parallel()
detector := newBlockedDetector()
h := newHarness(t, harnessOpts{
detector: detector,
controllerCfg: &controller.Config{
DefaultRequestTTL: 0,
ExpiryCleanupInterval: 10 * time.Millisecond,
EnqueueChannelBufferSize: 100,
},
})
key := flowcontrol.FlowKey{ID: "flow-a", Priority: 0}
const numRequests = 50
results := make(chan dispatchResult, numRequests)
for i := 0; i < numRequests; i++ {
id := fmt.Sprintf("req-%d", i)
go func() {
req := &testRequest{id: id, key: key, byteSize: 100}
outcome, err := h.fc.EnqueueAndWait(context.Background(), req)
results <- dispatchResult{id: id, outcome: outcome, err: err}
}()
}
// Cancel mid-flight while goroutines are still enqueuing.
time.Sleep(10 * time.Millisecond)
h.cancel()
for i := 0; i < numRequests; i++ {
select {
case r := <-results:
// Every request must reach a terminal state -- no panics, no hangs.
require.NotEqual(t, fcTypes.QueueOutcomeDispatched, r.outcome,
"no request should dispatch (detector is blocked and controller is shutting down)")
require.Error(t, r.err,
"every request should receive an error during shutdown")
require.ErrorIs(t, r.err, fcTypes.ErrFlowControllerNotRunning,
"every request should report the shutdown cause")
case <-time.After(5 * time.Second):
t.Fatalf("request %d hung during concurrent shutdown", i)
}
}
}
// TestGracefulShutdownDrainsQueuedRequests verifies that when the controller's
// context is cancelled (simulating pod termination), all queued requests receive
// a clean eviction outcome rather than hanging or panicking.
func TestGracefulShutdownDrainsQueuedRequests(t *testing.T) {
t.Parallel()
detector := newBlockedDetector()
h := newHarness(t, harnessOpts{
detector: detector,
})
key := flowcontrol.FlowKey{ID: "flow-a", Priority: 0}
const numRequests = 10
results := make(chan dispatchResult, numRequests)
for i := 0; i < numRequests; i++ {
id := fmt.Sprintf("req-%d", i)
go func() {
req := &testRequest{id: id, key: key, byteSize: 100, ttl: 5 * time.Minute}
outcome, err := h.fc.EnqueueAndWait(h.ctx, req)
results <- dispatchResult{id: id, outcome: outcome, err: err}
}()
time.Sleep(2 * time.Millisecond)
}
// Wait for all requests to queue (detector is blocked).
require.Eventually(t, func() bool {
return h.reg.Stats().TotalLen == uint64(numRequests)
}, time.Second, time.Millisecond, "all requests should be queued before shutdown")
// Simulate pod termination: cancel the controller context.
h.cancel()
var evicted int
for i := 0; i < numRequests; i++ {
select {
case r := <-results:
require.Error(t, r.err, "queued request should receive an error on shutdown")
switch r.outcome {
case fcTypes.QueueOutcomeEvictedOther,
fcTypes.QueueOutcomeEvictedContextCancelled,
fcTypes.QueueOutcomeRejectedOther:
evicted++
}
case <-time.After(5 * time.Second):
t.Fatalf("request %d did not return within 5s of shutdown -- possible hang", i)
}
}
require.Equal(t, numRequests, evicted,
"all queued requests should be evicted or rejected, not silently dropped")
}
// ============================================================================
// Production Edge Cases
// ============================================================================
// TestZombieCapacityStarvation verifies that TTL-expired items still in the
// queue (zombies) consume capacity until the cleanup sweep runs. If the sweep
// interval is long, new requests are falsely rejected because capacity is held
// by dead items.
func TestZombieCapacityStarvation(t *testing.T) {
t.Parallel()
detector := newBlockedDetector()
h := newHarness(t, harnessOpts{
detector: detector,
bandMaxRequests: 3,
endpointCandidates: nonEmptyCandidates(),
controllerCfg: &controller.Config{
DefaultRequestTTL: 50 * time.Millisecond,
ExpiryCleanupInterval: 10 * time.Second,
EnqueueChannelBufferSize: 100,
},
})
key := flowcontrol.FlowKey{ID: "flow-a", Priority: 0}
// Fill capacity with 3 requests that will expire via TTL.
expired := make(chan dispatchResult, 3)
for i := 0; i < 3; i++ {
id := fmt.Sprintf("zombie-%d", i)
go func() {
req := &testRequest{id: id, key: key, byteSize: 100, ttl: 50 * time.Millisecond}
outcome, err := h.fc.EnqueueAndWait(h.ctx, req)
expired <- dispatchResult{id: id, outcome: outcome, err: err}
}()
time.Sleep(5 * time.Millisecond)
}
// Wait for all to expire.
for i := 0; i < 3; i++ {
select {
case r := <-expired:
require.ErrorIs(t, r.err, fcTypes.ErrTTLExpired)
case <-time.After(5 * time.Second):
t.Fatalf("zombie %d did not expire", i)
}
}
// All 3 expired, but cleanup hasn't run (interval=10s).
// The new request is rejected because zombies still consume capacity
// in the registry's atomic counters.
newResult := make(chan dispatchResult, 1)
go func() {
reqCtx, reqCancel := context.WithTimeout(h.ctx, 200*time.Millisecond)
defer reqCancel()
req := &testRequest{id: "post-zombie", key: key, byteSize: 100, ttl: 200 * time.Millisecond}
outcome, err := h.fc.EnqueueAndWait(reqCtx, req)
newResult <- dispatchResult{id: "post-zombie", outcome: outcome, err: err}
}()
select {
case r := <-newResult:
// Zombie capacity starvation: the 3 expired items still occupy
// capacity slots until the cleanup sweep reclaims them (interval=10s).
require.Equal(t, fcTypes.QueueOutcomeRejectedCapacity, r.outcome,
"post-zombie request should be rejected -- expired items consume capacity until cleanup sweep runs")
case <-time.After(5 * time.Second):
t.Fatal("post-zombie request hung")
}
}
// TestEndpointReregistrationSaturationAccuracy verifies that when an endpoint
// is deleted and re-added (pod cycling), the saturation detector accurately
// reflects the state -- in-flight requests from before the delete should not
// leak into the new tracker.
func TestEndpointReregistrationSaturationAccuracy(t *testing.T) {
t.Parallel()
ctx := t.Context()
handle := testutils.NewTestHandle(ctx)
producerName := "rereg-producer"
producerPlugin, err := inflightload.InFlightLoadProducerFactory(
producerName, fwkplugin.StrictDecoder([]byte(`{}`)), handle,
)
require.NoError(t, err)
producer := producerPlugin.(*inflightload.InFlightLoadProducer)
detectorCfgJSON := []byte(fmt.Sprintf(
`{"maxConcurrency": 10, "inFlightLoadProducerName": %q}`, producerName,
))
detectorPlugin, err := concurrency.ConcurrencyDetectorFactory(
"rereg-detector", fwkplugin.StrictDecoder(detectorCfgJSON), handle,
)
require.NoError(t, err)
detector := detectorPlugin.(flowcontrol.SaturationDetector)
epMeta := &datalayer.EndpointMetadata{
NamespacedName: types.NamespacedName{Name: "pod-1", Namespace: "default"},
}
ep := datalayer.NewEndpoint(epMeta, datalayer.NewMetrics())
require.NoError(t, producer.Extract(ctx, datalayer.EndpointEvent{
Type: datalayer.EventAddOrUpdate, Endpoint: ep,
}))
// Track a request on the original endpoint.
schedEp := fwksched.NewEndpoint(epMeta, datalayer.NewMetrics(), nil)
oldReq := &fwksched.InferenceRequest{
RequestID: "old-req",
Body: &fwkrh.InferenceRequestBody{
TokenizedPrompt: &fwkrh.TokenizedPrompt{PerPromptTokens: [][]uint32{make([]uint32, 50)}},
},
}
oldResult := &fwksched.SchedulingResult{
ProfileResults: map[string]*fwksched.ProfileRunResult{
"decode": {TargetEndpoints: []fwksched.Endpoint{schedEp}},
},
}
producer.PreRequest(ctx, oldReq, oldResult)
sat := detector.Saturation(ctx, []datalayer.Endpoint{ep})
require.Greater(t, sat, 0.0, "saturation should be nonzero with in-flight request")