forked from llm-d/llm-d-router
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller_test.go
More file actions
1178 lines (1020 loc) · 43.4 KB
/
Copy pathcontroller_test.go
File metadata and controls
1178 lines (1020 loc) · 43.4 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.
*/
// Note on Time-Based Lifecycle Tests:
// Tests validating the controller's handling of request TTLs (e.g., OnReqCtxTimeout*) rely on real-time timers
// (context.WithDeadline). The injected testclock.FakeClock is used to control the timing of internal loops,
// but it cannot manipulate the timers used by the standard context package. Therefore, these specific
// tests use time.Sleep or assertions on real-time durations.
package controller
import (
"context"
"errors"
"fmt"
"sync"
"testing"
"time"
"github.com/go-logr/logr"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"k8s.io/utils/clock"
testclock "k8s.io/utils/clock/testing"
"github.com/llm-d/llm-d-router/pkg/epp/flowcontrol/contracts"
"github.com/llm-d/llm-d-router/pkg/epp/flowcontrol/contracts/mocks"
"github.com/llm-d/llm-d-router/pkg/epp/flowcontrol/controller/internal"
"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"
fwkfcmocks "github.com/llm-d/llm-d-router/pkg/epp/framework/interface/flowcontrol/mocks"
"github.com/llm-d/llm-d-router/pkg/epp/framework/plugins/flowcontrol/usagelimits"
)
// --- Test Harness & Fixtures ---
type mockSaturationDetector struct {
flowcontrol.SaturationDetector
}
func (m *mockSaturationDetector) Saturation(_ context.Context, _ []datalayer.Endpoint) float64 {
return 0.0
}
// testHarness holds the `FlowController` and its dependencies under test.
type testHarness struct {
fc *FlowController
cfg *Config
// clock is the clock interface used by the controller.
clock clock.WithTicker
mockRegistry *mockRegistryClient
// mockClock provides access to FakeClock methods (Step, HasWaiters) if and only if the underlying clock is a
// FakeClock.
mockClock *testclock.FakeClock
mockProcessorFactory *mockProcessorFactory
}
// unitHarnessOption allows configuring the test harness.
type unitHarnessOption func(*testHarnessOpts)
type testHarnessOpts struct {
clock clock.WithTicker
}
func withHarnessClock(c clock.WithTicker) unitHarnessOption {
return func(o *testHarnessOpts) {
o.clock = c
}
}
// newUnitHarness creates a test environment with a mock processor factory, suitable for focused unit tests of the
// controller's logic. It starts the controller's run loop using the provided context for lifecycle management.
func newUnitHarness(
ctx context.Context,
t *testing.T,
cfg *Config,
registry *mockRegistryClient,
processor *mockProcessor,
opts ...unitHarnessOption,
) *testHarness {
t.Helper()
harnessOpts := &testHarnessOpts{
clock: testclock.NewFakeClock(time.Now()),
}
for _, opt := range opts {
opt(harnessOpts)
}
mockDetector := &mockSaturationDetector{}
mockEndpointCandidates := &mocks.MockEndpointCandidates{}
mockProcessorFactory := &mockProcessorFactory{processor: processor}
usageLimitPolicy := usagelimits.DefaultPolicy()
// Default the registry if nil, simplifying tests that don't focus on registry interaction.
if registry == nil {
registry = &mockRegistryClient{FlowRegistryDataPlane: &mocks.MockRegistryDataPlane{}}
}
fc := NewFlowController(ctx, "test-pool", cfg, Deps{
Registry: registry,
SaturationDetector: mockDetector,
EndpointCandidates: mockEndpointCandidates,
UsageLimitPolicy: usageLimitPolicy,
Clock: harnessOpts.clock,
ProcessorFactory: mockProcessorFactory.new,
})
h := &testHarness{
fc: fc,
cfg: cfg,
clock: harnessOpts.clock,
mockRegistry: registry,
mockProcessorFactory: mockProcessorFactory,
}
if fc, ok := harnessOpts.clock.(*testclock.FakeClock); ok {
h.mockClock = fc
}
return h
}
// newIntegrationHarness creates a test environment that uses real `Processor`s, suitable for integration tests
// validating the controller-processor interaction.
func newIntegrationHarness(ctx context.Context, t *testing.T, cfg *Config, registry *mockRegistryClient) *testHarness {
t.Helper()
mockDetector := &mockSaturationDetector{}
mockEndpointCandidates := &mocks.MockEndpointCandidates{}
usageLimitPolicy := usagelimits.DefaultPolicy()
// Align FakeClock with system time. See explanation in newUnitHarness.
mockClock := testclock.NewFakeClock(time.Now())
if registry == nil {
registry = &mockRegistryClient{
FlowRegistryDataPlane: &mocks.MockRegistryDataPlane{},
}
}
fc := NewFlowController(ctx, "test-pool", cfg, Deps{
Registry: registry,
SaturationDetector: mockDetector,
EndpointCandidates: mockEndpointCandidates,
UsageLimitPolicy: usageLimitPolicy,
Clock: mockClock,
})
h := &testHarness{
fc: fc,
cfg: cfg,
clock: mockClock,
mockRegistry: registry,
mockClock: mockClock,
}
return h
}
// mockActiveFlowConnection is a local mock for the `contracts.ActiveFlowConnection` interface.
type mockActiveFlowConnection struct {
RegistryV contracts.FlowRegistry
RegistryFunc func() contracts.FlowRegistry
FlowKeyV flowcontrol.FlowKey
}
func (m *mockActiveFlowConnection) GetDataPlane() contracts.FlowRegistryDataPlane {
if m.RegistryFunc != nil {
return m.RegistryFunc()
}
return m.RegistryV
}
func (m *mockActiveFlowConnection) FlowKey() flowcontrol.FlowKey {
return m.FlowKeyV
}
// mockRegistryClient is a mock for the private `registryClient` interface.
type mockRegistryClient struct {
contracts.FlowRegistryObserver
contracts.FlowRegistryDataPlane
WithConnectionFunc func(key flowcontrol.FlowKey, fn func(conn contracts.ActiveFlowConnection) error) error
StatsFunc func() contracts.AggregateStats
}
func (m *mockRegistryClient) WithConnection(
key flowcontrol.FlowKey,
fn func(conn contracts.ActiveFlowConnection) error,
) error {
if m.WithConnectionFunc != nil {
return m.WithConnectionFunc(key, fn)
}
return fn(&mockActiveFlowConnection{RegistryV: m})
}
func (m *mockRegistryClient) Stats() contracts.AggregateStats {
if m.StatsFunc != nil {
return m.StatsFunc()
}
return contracts.AggregateStats{}
}
func (m *mockRegistryClient) SubmitDesiredPriorities(_ map[int]struct{}) {}
func (m *mockRegistryClient) PriorityBandUpdateChannel() <-chan map[int]struct{} {
return nil
}
func (m *mockRegistryClient) FlowGCTimeout() time.Duration {
return time.Minute
}
func (m *mockRegistryClient) ApplyDesiredPriorities(_ map[int]struct{}) {}
func (m *mockRegistryClient) ExecuteGCCycle() {}
// mockProcessor is a mock for the internal `Processor` interface.
type mockProcessor struct {
SubmitFunc func(item *internal.FlowItem) error
SubmitOrBlockFunc func(ctx context.Context, item *internal.FlowItem) error
// runCtx captures the context provided to the Run method for lifecycle assertions.
runCtx context.Context
runCtxMu sync.RWMutex
// runStarted is closed when the Run method is called, allowing tests to synchronize with worker startup.
runStarted chan struct{}
}
func (m *mockProcessor) Submit(item *internal.FlowItem) error {
if m.SubmitFunc != nil {
return m.SubmitFunc(item)
}
return nil
}
func (m *mockProcessor) SubmitOrBlock(ctx context.Context, item *internal.FlowItem) error {
if m.SubmitOrBlockFunc != nil {
return m.SubmitOrBlockFunc(ctx, item)
}
return nil
}
func (m *mockProcessor) Run(ctx context.Context) {
m.runCtxMu.Lock()
m.runCtx = ctx
m.runCtxMu.Unlock()
if m.runStarted != nil {
close(m.runStarted)
}
// Block until the context is cancelled, simulating a running worker.
<-ctx.Done()
}
// Context returns the context captured during the Run method call.
func (m *mockProcessor) Context() context.Context {
m.runCtxMu.RLock()
defer m.runCtxMu.RUnlock()
return m.runCtx
}
// mockProcessorFactory allows tests to inject specific `mockProcessor` instances.
type mockProcessorFactory struct {
processor *mockProcessor
}
// new is the factory function conforming to the `ProcessorFactory` signature.
func (f *mockProcessorFactory) new(
_ context.Context, // The factory does not use the lifecycle context; it's passed to the processor's Run method later.
_ contracts.FlowRegistry,
_ contracts.FlowRegistryBackground,
_ flowcontrol.SaturationDetector,
_ contracts.EndpointCandidates,
_ flowcontrol.UsageLimitPolicy,
_ clock.WithTicker,
_ time.Duration,
_ int,
_ logr.Logger,
) processor {
if f.processor != nil {
return f.processor
}
// Return a default mock processor if one is not explicitly registered by the test.
return &mockProcessor{}
}
var defaultFlowKey = flowcontrol.FlowKey{ID: "test-flow", Priority: 100}
func newTestRequest(key flowcontrol.FlowKey) *fwkfcmocks.MockFlowControlRequest {
return &fwkfcmocks.MockFlowControlRequest{
FlowKeyV: key,
ByteSizeV: 100,
IDV: "req-" + key.ID,
}
}
// --- Test Cases ---
// TestFlowController_EnqueueAndWait covers the primary API entry point, focusing on validation, distribution logic,
// retries, and the request lifecycle (including post-distribution cancellation/timeout).
func TestFlowController_EnqueueAndWait(t *testing.T) {
t.Parallel()
t.Run("Rejections", func(t *testing.T) {
t.Parallel()
t.Run("OnReqCtxExpiredBeforeDistribution", func(t *testing.T) {
t.Parallel()
// Test that if the request context provided to EnqueueAndWait is already expired, it returns immediately.
// Configure processor to block until context expiry.
processor := &mockProcessor{
SubmitFunc: func(_ *internal.FlowItem) error { return internal.ErrProcessorBusy },
SubmitOrBlockFunc: func(ctx context.Context, _ *internal.FlowItem) error {
<-ctx.Done() // Wait for the context to be done.
return context.Cause(ctx) // Return the cause.
},
}
h := newUnitHarness(t.Context(), t, &Config{DefaultRequestTTL: 1 * time.Minute}, nil, processor)
h.mockRegistry.WithConnectionFunc = func(key flowcontrol.FlowKey, fn func(_ contracts.ActiveFlowConnection) error) error {
return fn(&mockActiveFlowConnection{
RegistryV: h.mockRegistry,
FlowKeyV: key,
})
}
h.mockRegistry.FlowRegistryDataPlane = &mocks.MockRegistryDataPlane{}
req := newTestRequest(defaultFlowKey)
// Use a context with a deadline in the past.
reqCtx, cancel := context.WithDeadlineCause(
context.Background(),
h.clock.Now().Add(-1*time.Second),
types.ErrTTLExpired)
defer cancel()
outcome, err := h.fc.EnqueueAndWait(reqCtx, req)
require.Error(t, err, "EnqueueAndWait must fail if request context deadline is exceeded")
assert.ErrorIs(t, err, types.ErrRejected, "error should wrap ErrRejected")
assert.ErrorIs(t, err, types.ErrTTLExpired, "error should wrap types.ErrTTLExpired from the context cause")
assert.Equal(t, types.QueueOutcomeRejectedOther, outcome, "outcome should be QueueOutcomeRejectedOther")
})
t.Run("OnControllerShutdown", func(t *testing.T) {
t.Parallel()
// Create a context specifically for the controller's lifecycle.
ctx, cancel := context.WithCancel(t.Context())
h := newUnitHarness(ctx, t, &Config{}, nil, nil)
cancel() // Immediately stop the controller.
req := newTestRequest(defaultFlowKey)
// The request context is valid, but the controller itself is stopped.
outcome, err := h.fc.EnqueueAndWait(context.Background(), req)
require.Error(t, err, "EnqueueAndWait must reject requests if controller is not running")
assert.ErrorIs(t, err, types.ErrRejected, "error should wrap ErrRejected")
assert.ErrorIs(t, err, types.ErrFlowControllerNotRunning, "error should wrap ErrFlowControllerNotRunning")
assert.Equal(t, types.QueueOutcomeRejectedOther, outcome,
"outcome should be QueueOutcomeRejectedOther on shutdown")
})
t.Run("OnControllerShutdownDuringFinalization", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(t.Context())
h := newUnitHarness(ctx, t, &Config{}, nil, nil)
item := internal.NewItem(newTestRequest(defaultFlowKey), 0, time.Now())
result := make(chan struct {
outcome types.QueueOutcome
err error
}, 1)
go func() {
outcome, err := h.fc.awaitFinalization(context.Background(), item)
result <- struct {
outcome types.QueueOutcome
err error
}{outcome: outcome, err: err}
}()
cancel()
select {
case r := <-result:
require.Error(t, r.err, "awaitFinalization must fail when controller shuts down")
assert.ErrorIs(t, r.err, types.ErrFlowControllerNotRunning,
"error should wrap ErrFlowControllerNotRunning")
assert.Equal(t, types.QueueOutcomeRejectedOther, r.outcome,
"outcome should be QueueOutcomeRejectedOther on shutdown")
case <-time.After(time.Second):
t.Fatal("awaitFinalization did not return after controller shutdown")
}
})
t.Run("OnControllerShutdownTakesPrecedenceOverRequestCancellation", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(t.Context())
h := newUnitHarness(ctx, t, &Config{}, nil, nil)
reqCtx, reqCancel := context.WithCancel(context.Background())
item := internal.NewItem(newTestRequest(defaultFlowKey), 0, time.Now())
reqCancel()
cancel()
outcome, err := h.fc.awaitFinalization(reqCtx, item)
require.Error(t, err, "awaitFinalization must fail when controller shuts down")
assert.ErrorIs(t, err, types.ErrFlowControllerNotRunning,
"controller shutdown should take precedence over request cancellation")
assert.Equal(t, types.QueueOutcomeRejectedOther, outcome,
"shutdown should return the rejected outcome")
})
t.Run("OnControllerShutdownPreservesQueuedOutcome", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(t.Context())
h := newUnitHarness(ctx, t, &Config{}, nil, nil)
item := internal.NewItem(newTestRequest(defaultFlowKey), 0, time.Now())
item.SetHandle(&fwkfcmocks.MockQueueItemHandle{})
cancel()
outcome, err := h.fc.awaitFinalization(context.Background(), item)
require.Error(t, err, "awaitFinalization must fail when controller shuts down")
assert.ErrorIs(t, err, types.ErrEvicted,
"a queued item should be evicted, not rejected, during shutdown")
assert.ErrorIs(t, err, types.ErrFlowControllerNotRunning,
"queued shutdown should preserve the shutdown cause")
assert.Equal(t, types.QueueOutcomeEvictedOther, outcome,
"a queued item should return the evicted outcome")
})
t.Run("OnRegistryConnectionError", func(t *testing.T) {
t.Parallel()
mockRegistry := &mockRegistryClient{FlowRegistryDataPlane: &mocks.MockRegistryDataPlane{}}
h := newUnitHarness(t.Context(), t, &Config{}, mockRegistry, nil)
expectedErr := errors.New("simulated connection failure")
// Configure the registry to fail when attempting to retrieve ActiveFlowConnection.
mockRegistry.WithConnectionFunc = func(
_ flowcontrol.FlowKey,
_ func(conn contracts.ActiveFlowConnection) error,
) error {
return expectedErr
}
req := newTestRequest(defaultFlowKey)
outcome, err := h.fc.EnqueueAndWait(context.Background(), req)
require.Error(t, err, "EnqueueAndWait must reject requests if registry connection fails")
assert.ErrorIs(t, err, types.ErrRejected, "error should wrap ErrRejected")
assert.ErrorIs(t, err, expectedErr, "error should wrap the underlying connection error")
assert.Equal(t, types.QueueOutcomeRejectedOther, outcome,
"outcome should be QueueOutcomeRejectedOther for transient registry errors")
})
t.Run("OnManagedQueueError", func(t *testing.T) {
t.Parallel()
mockRegistry := &mockRegistryClient{FlowRegistryDataPlane: &mocks.MockRegistryDataPlane{}}
h := newUnitHarness(t.Context(), t, &Config{}, mockRegistry, nil)
// Create a faulty setup that successfully leases the flow but fails to return the
// ManagedQueue. This setup should be considered as unavailable.
faultyRegistry := &mocks.MockRegistryDataPlane{
ManagedQueueFunc: func(_ flowcontrol.FlowKey) (contracts.ManagedQueue, error) {
return nil, errors.New("invariant violation: queue retrieval failed")
},
}
mockRegistry.WithConnectionFunc = func(
key flowcontrol.FlowKey,
fn func(conn contracts.ActiveFlowConnection) error,
) error {
return fn(&mockActiveFlowConnection{
RegistryV: faultyRegistry,
FlowKeyV: key,
})
}
req := newTestRequest(defaultFlowKey)
outcome, err := h.fc.EnqueueAndWait(context.Background(), req)
require.Error(t, err, "EnqueueAndWait must reject requests if queue doesn't exist for flow")
assert.ErrorIs(t, err, types.ErrRejected, "error should wrap ErrRejected")
assert.Equal(t, types.QueueOutcomeRejectedCapacity, outcome,
"outcome should be QueueOutcomeRejectedCapacity when queue doesn't exist for the flow")
})
})
// Distribution tests validate the JSQ-Bytes algorithm, the two-phase submission strategy, and error handling during
// the handoff, including time-based failures during blocking fallback.
t.Run("Distribution", func(t *testing.T) {
t.Parallel()
// Define a long default TTL to prevent unexpected timeouts unless a test case explicitly sets a shorter one.
const defaultTestTTL = 5 * time.Second
testCases := []struct {
name string
setupProcessor func(t *testing.T) *mockProcessor
// requestTTL overrides the default TTL for time-sensitive tests.
requestTTL time.Duration
expectedOutcome types.QueueOutcome
expectErr bool
expectErrIs error
}{
{
name: "SubmitSucceeds_NonBlocking",
setupProcessor: func(t *testing.T) *mockProcessor {
return &mockProcessor{
SubmitFunc: func(item *internal.FlowItem) error {
// Simulate asynchronous processing and successful dispatch.
go item.FinalizeWithOutcome(types.QueueOutcomeDispatched, nil)
return nil
},
}
},
expectedOutcome: types.QueueOutcomeDispatched,
},
{
// Validates the scenario where the request's TTL expires while the controller is blocked waiting for capacity.
// NOTE: This relies on real time passing, as context.WithDeadline timers cannot be controlled by FakeClock.
name: "Rejects_AfterBlocking_WhenTTL_Expires",
requestTTL: 50 * time.Millisecond, // Short TTL to keep the test fast.
setupProcessor: func(t *testing.T) *mockProcessor {
return &mockProcessor{
// Reject the non-blocking attempt.
SubmitFunc: func(_ *internal.FlowItem) error { return internal.ErrProcessorBusy },
// Block the fallback attempt until the context (carrying the TTL deadline) expires.
SubmitOrBlockFunc: func(ctx context.Context, _ *internal.FlowItem) error {
<-ctx.Done()
return ctx.Err()
},
}
},
// No runActions needed; we rely on the real-time timer to expire.
// When the blocking call fails due to context expiry, the outcome is RejectedOther.
expectedOutcome: types.QueueOutcomeRejectedOther,
expectErr: true,
// The error must reflect the specific cause of the context cancellation (ErrTTLExpired).
expectErrIs: types.ErrTTLExpired,
},
{
name: "Rejects_OnProcessorShutdownDuringSubmit",
setupProcessor: func(t *testing.T) *mockProcessor {
return &mockProcessor{
// Simulate the processor shutting down during the non-blocking handoff.
SubmitFunc: func(_ *internal.FlowItem) error { return types.ErrFlowControllerNotRunning },
SubmitOrBlockFunc: func(_ context.Context, _ *internal.FlowItem) error {
return types.ErrFlowControllerNotRunning
},
}
},
expectedOutcome: types.QueueOutcomeRejectedOther,
expectErr: true,
expectErrIs: types.ErrFlowControllerNotRunning,
},
{
name: "Rejects_OnProcessorShutdownDuringSubmitOrBlock",
setupProcessor: func(t *testing.T) *mockProcessor {
return &mockProcessor{
SubmitFunc: func(_ *internal.FlowItem) error { return internal.ErrProcessorBusy },
// Simulate the processor shutting down during the blocking handoff.
SubmitOrBlockFunc: func(_ context.Context, _ *internal.FlowItem) error {
return types.ErrFlowControllerNotRunning
},
}
},
expectedOutcome: types.QueueOutcomeRejectedOther,
expectErr: true,
expectErrIs: types.ErrFlowControllerNotRunning,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
// Arrange
mockRegistry := &mockRegistryClient{FlowRegistryDataPlane: &mocks.MockRegistryDataPlane{}}
// Configure the harness with the appropriate TTL.
harnessConfig := &Config{DefaultRequestTTL: defaultTestTTL}
if tc.requestTTL > 0 {
harnessConfig.DefaultRequestTTL = tc.requestTTL
}
h := newUnitHarness(t.Context(), t, harnessConfig, mockRegistry, tc.setupProcessor(t))
// Configure the registry to return the specified setup.
mockRegistry.WithConnectionFunc = func(
key flowcontrol.FlowKey,
fn func(conn contracts.ActiveFlowConnection) error,
) error {
return fn(&mockActiveFlowConnection{
RegistryV: h.mockRegistry,
FlowKeyV: key,
})
}
// Act
var outcome types.QueueOutcome
var err error
startTime := time.Now() // Capture real start time for duration checks.
// Use a background context for the parent; the request lifecycle is governed by the config/derived context.
outcome, err = h.fc.EnqueueAndWait(context.Background(), newTestRequest(defaultFlowKey))
// Assert
if tc.expectErr {
require.Error(t, err, "expected an error during EnqueueAndWait but got nil")
assert.ErrorIs(t, err, tc.expectErrIs, "error should wrap the expected underlying cause")
// All failures during the distribution phase (capacity, timeout, shutdown) should result in a rejection.
assert.ErrorIs(t, err, types.ErrRejected, "rejection errors must wrap types.ErrRejected")
// Specific assertion for real-time TTL tests.
if errors.Is(tc.expectErrIs, types.ErrTTLExpired) {
duration := time.Since(startTime)
// Ensure the test didn't return instantly. Use a tolerance for CI environments.
// This validates that the real-time wait actually occurred.
assert.GreaterOrEqual(t, duration, tc.requestTTL-30*time.Millisecond,
"EnqueueAndWait returned faster than the TTL allows, indicating the timer did not function correctly")
}
} else {
require.NoError(t, err, "expected no error during EnqueueAndWait but got: %v", err)
}
assert.Equal(t, tc.expectedOutcome, outcome, "outcome did not match expected value")
})
}
})
t.Run("Retry", func(t *testing.T) {
t.Parallel()
// This test specifically validates the behavior when the request context is cancelled externally while the
// controller is blocked in the SubmitOrBlock phase.
t.Run("Rejects_OnRequestContextCancelledWhileBlocking", func(t *testing.T) {
t.Parallel()
mockRegistry := &mockRegistryClient{FlowRegistryDataPlane: &mocks.MockRegistryDataPlane{}}
mockRegistry.WithConnectionFunc = func(
key flowcontrol.FlowKey,
fn func(conn contracts.ActiveFlowConnection,
) error) error {
return fn(&mockActiveFlowConnection{
RegistryV: mockRegistry,
FlowKeyV: key,
})
}
// Use a long TTL to ensure the failure is due to cancellation, not timeout.
processor := &mockProcessor{
// Reject non-blocking attempt.
SubmitFunc: func(_ *internal.FlowItem) error { return internal.ErrProcessorBusy },
// Block the fallback attempt until the context is cancelled.
SubmitOrBlockFunc: func(ctx context.Context, _ *internal.FlowItem) error {
<-ctx.Done()
return ctx.Err()
},
}
h := newUnitHarness(t.Context(), t, &Config{DefaultRequestTTL: 10 * time.Second}, mockRegistry, processor)
// Create a cancellable context for the request.
reqCtx, cancelReq := context.WithCancel(context.Background())
// Cancel the request shortly after starting the operation.
// We use real time sleep here as we are testing external cancellation signals interacting with the context.
go func() { time.Sleep(10 * time.Millisecond); cancelReq() }()
outcome, err := h.fc.EnqueueAndWait(reqCtx, newTestRequest(defaultFlowKey))
require.Error(t, err, "EnqueueAndWait must fail when context is cancelled during a blocking submit")
assert.ErrorIs(t, err, types.ErrRejected, "error should wrap ErrRejected")
assert.ErrorIs(t, err, context.Canceled, "error should wrap the underlying ctx.Err() (context.Canceled)")
assert.Equal(t, types.QueueOutcomeRejectedOther, outcome,
"outcome should be QueueOutcomeRejectedOther when cancelled during distribution")
})
})
// Lifecycle covers the post-distribution phase, focusing on how the controller handles context cancellation and TTL
// expiry while the request is buffered or queued by the processor (Asynchronous Finalization).
t.Run("Lifecycle", func(t *testing.T) {
t.Parallel()
// Validates that the controller correctly initiates asynchronous finalization when the request context is cancelled
// after ownership has been transferred to the processor.
t.Run("OnReqCtxCancelledAfterDistribution", func(t *testing.T) {
t.Parallel()
// Use a long TTL to ensure the failure is due to cancellation.
// Channel for synchronization.
itemSubmitted := make(chan *internal.FlowItem, 1)
// Configure the processor to accept the item but never finalize it, simulating a queued request.
processor := &mockProcessor{
SubmitFunc: func(item *internal.FlowItem) error {
item.SetHandle(&fwkfcmocks.MockQueueItemHandle{})
itemSubmitted <- item
return nil
},
}
h := newUnitHarness(t.Context(), t, &Config{DefaultRequestTTL: 10 * time.Second}, nil, processor)
h.mockRegistry.WithConnectionFunc = func(key flowcontrol.FlowKey, fn func(_ contracts.ActiveFlowConnection) error) error {
return fn(&mockActiveFlowConnection{
RegistryV: h.mockRegistry,
FlowKeyV: key,
})
}
h.mockRegistry.FlowRegistryDataPlane = &mocks.MockRegistryDataPlane{}
reqCtx, cancelReq := context.WithCancel(context.Background())
req := newTestRequest(defaultFlowKey)
var outcome types.QueueOutcome
var err error
done := make(chan struct{})
go func() {
outcome, err = h.fc.EnqueueAndWait(reqCtx, req)
close(done)
}()
// 1. Wait for the item to be successfully distributed.
var item *internal.FlowItem
select {
case item = <-itemSubmitted:
// Success. Ownership has transferred. EnqueueAndWait is now in the select loop.
case <-time.After(1 * time.Second):
t.Fatal("timed out waiting for item to be submitted to the processor")
}
// 2. Cancel the request context.
cancelReq()
// 3. Wait for EnqueueAndWait to return.
select {
case <-done:
// Success. The controller detected the cancellation and unblocked the caller.
case <-time.After(1 * time.Second):
t.Fatal("timed out waiting for EnqueueAndWait to return after cancellation")
}
// 4. Assertions for EnqueueAndWait's return values.
require.Error(t, err, "EnqueueAndWait should return an error when the request is cancelled post-distribution")
// The outcome should be Evicted (as the handle was set).
assert.ErrorIs(t, err, types.ErrEvicted, "error should wrap ErrEvicted")
// The underlying cause must be propagated.
assert.ErrorIs(t, err, types.ErrContextCancelled, "error should wrap ErrContextCancelled")
assert.Equal(t, types.QueueOutcomeEvictedContextCancelled, outcome, "outcome should be EvictedContextCancelled")
// 5. Assert that the FlowItem itself was indeed finalized by the controller.
finalState := item.FinalState()
require.NotNil(t, finalState, "Item should have been finalized asynchronously by the controller")
assert.Equal(t, types.QueueOutcomeEvictedContextCancelled, finalState.Outcome,
"Item's internal outcome must match the returned outcome")
})
// Validates the asynchronous finalization path due to TTL expiry.
// Note: This relies on real time passing, as context.WithDeadline timers cannot be controlled by FakeClock.
t.Run("OnReqCtxTimeoutAfterDistribution", func(t *testing.T) {
t.Parallel()
// Configure a short TTL to keep the test reasonably fast.
itemSubmitted := make(chan *internal.FlowItem, 1)
// Configure the processor to accept the item but never finalize it.
processor := &mockProcessor{
SubmitFunc: func(item *internal.FlowItem) error {
item.SetHandle(&fwkfcmocks.MockQueueItemHandle{})
itemSubmitted <- item
return nil
},
}
const requestTTL = 50 * time.Millisecond
h := newUnitHarness(t.Context(), t, &Config{
DefaultRequestTTL: requestTTL,
ExpiryCleanupInterval: time.Minute,
}, nil, processor, withHarnessClock(clock.RealClock{}))
h.mockRegistry.WithConnectionFunc = func(key flowcontrol.FlowKey, fn func(_ contracts.ActiveFlowConnection) error) error {
return fn(&mockActiveFlowConnection{
RegistryV: h.mockRegistry,
FlowKeyV: key,
})
}
req := newTestRequest(defaultFlowKey)
// Use a context for the call itself that won't time out independently.
enqueueCtx, enqueueCancel := context.WithTimeout(context.Background(), 2*time.Second)
defer enqueueCancel()
var outcome types.QueueOutcome
var err error
done := make(chan struct{})
startTime := time.Now() // Capture start time to validate duration.
go func() {
outcome, err = h.fc.EnqueueAndWait(enqueueCtx, req)
close(done)
}()
// 1. Wait for the item to be submitted.
var item *internal.FlowItem
select {
case item = <-itemSubmitted:
case <-time.After(1 * time.Second):
t.Fatal("timed out waiting for item to be submitted to the processor")
}
// 2.Wait for the TTL to expire (Real time). We do NOT call Step().
// Wait for EnqueueAndWait to return due to the TTL expiry.
select {
case <-done:
// Success. Now validate that enough time actually passed.
duration := time.Since(startTime)
assert.GreaterOrEqual(t, duration, requestTTL-30*time.Millisecond, // tolerance for CI environments
"EnqueueAndWait returned faster than the TTL allows, indicating the timer did not function correctly")
case <-time.After(1 * time.Second):
t.Fatal("timed out waiting for EnqueueAndWait to return after TTL expiry")
}
// 4. Assertions for EnqueueAndWait's return values.
require.Error(t, err, "EnqueueAndWait should return an error when TTL expires post-distribution")
assert.ErrorIs(t, err, types.ErrEvicted, "error should wrap ErrEvicted")
assert.ErrorIs(t, err, types.ErrTTLExpired, "error should wrap the underlying cause (types.ErrTTLExpired)")
assert.Equal(t, types.QueueOutcomeEvictedTTL, outcome, "outcome should be EvictedTTL")
// 5. Assert FlowItem final state.
finalState := item.FinalState()
require.NotNil(t, finalState, "Item should have been finalized asynchronously by the controller")
assert.Equal(t, types.QueueOutcomeEvictedTTL, finalState.Outcome,
"Item's internal outcome must match the returned outcome")
})
// Validates that the Flow Registry lease is held (pinned) for the entire duration of the request, including the
// time spent blocking in the processor's queue. If the lease is released early, the Garbage Collector could delete
// the flow while requests are queued.
t.Run("LeaseHeldDuringQueueing", func(t *testing.T) {
t.Parallel()
// Synchronization channels
leaseReleased := make(chan struct{})
processorEntered := make(chan struct{})
unblockProcessor := make(chan struct{})
// 1. Setup Registry: Trace when the lease is released.
mockRegistry := &mockRegistryClient{FlowRegistryDataPlane: &mocks.MockRegistryDataPlane{}}
mockRegistry.WithConnectionFunc = func(
key flowcontrol.FlowKey,
fn func(conn contracts.ActiveFlowConnection) error,
) error {
// Execute the controller's logic.
err := fn(&mockActiveFlowConnection{
RegistryV: mockRegistry,
FlowKeyV: key,
})
// Signal that the closure has finished and the lease is about to be released.
close(leaseReleased)
return err
}
// 2. Setup Processor: Simulate a long wait in the queue.
processor := &mockProcessor{
SubmitFunc: func(_ *internal.FlowItem) error { return internal.ErrProcessorBusy },
SubmitOrBlockFunc: func(ctx context.Context, item *internal.FlowItem) error {
close(processorEntered) // Signal that we are now "queued"
// Block until the test allows us to proceed.
select {
case <-unblockProcessor:
item.FinalizeWithOutcome(types.QueueOutcomeDispatched, nil)
return nil
case <-ctx.Done():
return ctx.Err()
}
},
}
h := newUnitHarness(t.Context(), t, &Config{}, mockRegistry, processor)
// 3. Run EnqueueAndWait in the background.
go func() {
_, _ = h.fc.EnqueueAndWait(context.Background(), newTestRequest(defaultFlowKey))
}()
// 4. Wait for the request to enter the queue (Blocking phase).
select {
case <-processorEntered:
// Success: The request is now blocked inside the processor.
case <-time.After(1 * time.Second):
t.Fatal("timed out waiting for request to enter processor")
}
// 5. Verify the lease is still held.
// If leaseReleased is closed, it means the controller returned from WithConnection while the request was still
// inside SubmitOrBlock.
select {
case <-leaseReleased:
t.Fatal("registry lease was released while the request was still queued.")
default:
// Success: The lease is still held.
}
// 6. Cleanup: Unblock the processor and allow the lease to release.
close(unblockProcessor)
// Verify that the lease is eventually released after processing finishes.
select {
case <-leaseReleased:
// Success
case <-time.After(1 * time.Second):
t.Fatal("timed out waiting for lease to release after processing finished")
}
})
})
}
// TestFlowController_WorkerManagement covers the lifecycle of the processor (worker), including startup
func TestFlowController_WorkerManagement(t *testing.T) {
t.Parallel()
// Startup validates that the worker starts
t.Run("Startup", func(t *testing.T) {
t.Parallel()
mockRegistry := &mockRegistryClient{
FlowRegistryDataPlane: &mocks.MockRegistryDataPlane{},
StatsFunc: func() contracts.AggregateStats {
// The current state of the world according to the registry.
return contracts.AggregateStats{}
}}
// Initialize the processor mock with the channel needed to synchronize startup.
processor := &mockProcessor{runStarted: make(chan struct{})}
h := newUnitHarness(t.Context(), t, &Config{}, mockRegistry, processor)
// Wait for the worker goroutine to have started and captured its context.
select {
case <-h.mockProcessorFactory.processor.runStarted:
// Worker is running.
case <-time.After(2 * time.Second):
t.Fatalf("timed out waiting for worker to start")
}
})
}
// Helper function to create a realistic mock registry environment for integration/concurrency tests.
func setupRegistryForConcurrency(t *testing.T, flowKey flowcontrol.FlowKey) *mockRegistryClient {
t.Helper()
mockRegistry := &mockRegistryClient{}
// Configure the registry and its dependencies required by the real Processor implementation.
// Use high-fidelity mock queues (MockManagedQueue) that implement the necessary interfaces and synchronization.
currentQueue := &mocks.MockManagedQueue{FlowKeyV: flowKey}
dataplane := &mocks.MockRegistryDataPlane{
ManagedQueueFunc: func(_ flowcontrol.FlowKey) (contracts.ManagedQueue, error) {
return currentQueue, nil
},
// Configuration required for Processor initialization and dispatch logic.
AllOrderedPriorityLevelsFunc: func() []int { return []int{flowKey.Priority} },
PriorityBandAccessorFunc: func(priority int) (flowcontrol.PriorityBandAccessor, error) {
if priority == flowKey.Priority {
return &fwkfcmocks.MockPriorityBandAccessor{
PriorityV: priority,
IterateQueuesFunc: func(f func(flowcontrol.FlowQueueAccessor) bool) {
f(currentQueue.FlowQueueAccessor())
},
}, nil
}
return nil, fmt.Errorf("unexpected priority %d", priority)
},
FairnessPolicyFunc: func(_ int) (flowcontrol.FairnessPolicy, error) {
return &fwkfcmocks.MockFairnessPolicy{
PickFunc: func(_ context.Context, _ flowcontrol.PriorityBandAccessor) (flowcontrol.FlowQueueAccessor, error) {
return currentQueue.FlowQueueAccessor(), nil
},
}, nil
},
// Configure stats reporting based on the live state of the mock queues.
StatsFunc: func() contracts.AggregateStats {
return contracts.AggregateStats{
TotalLen: uint64(currentQueue.Len()),
TotalByteSize: currentQueue.ByteSize(),
PerPriorityBandStats: map[int]contracts.PriorityBandStats{
flowKey.Priority: {
Len: uint64(currentQueue.Len()),
ByteSize: currentQueue.ByteSize(),
CapacityBytes: 1e9, // Effectively unlimited capacity to ensure dispatch success.
},
},
}
},
}
// Configure the registry connection.
mockRegistry.WithConnectionFunc = func(key flowcontrol.FlowKey, fn func(conn contracts.ActiveFlowConnection) error) error {
return fn(&mockActiveFlowConnection{
RegistryV: dataplane,
FlowKeyV: key,