-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathgateway_stream_test.go
More file actions
1719 lines (1597 loc) · 54.3 KB
/
Copy pathgateway_stream_test.go
File metadata and controls
1719 lines (1597 loc) · 54.3 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
package aigateway
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/ferro-labs/ai-gateway/config"
"github.com/ferro-labs/ai-gateway/models"
"github.com/ferro-labs/ai-gateway/observability"
"github.com/ferro-labs/ai-gateway/pkg/circuitbreaker"
"github.com/ferro-labs/ai-gateway/pkg/metrics"
"github.com/ferro-labs/ai-gateway/plugin"
cacheplugin "github.com/ferro-labs/ai-gateway/plugin/cache"
"github.com/ferro-labs/ai-gateway/providers"
"github.com/ferro-labs/ai-gateway/providers/core"
)
// Streaming on the shared request pipeline.
//
// These tests assert the properties streaming INHERITS by being routed through
// routeTargets rather than through a loop of its own, plus the one property the
// pipeline must NOT take over: a stream's outcome is not known when the start
// call returns, so the circuit breaker and the concurrency slot stay with the
// response. See targetPlan.responseOutlivesCall.
const streamPipelineModel = "stream-pipeline-model-v1"
func streamPipelineRequest() providers.Request {
return providers.Request{
Model: streamPipelineModel,
Stream: true,
Messages: []providers.Message{{Role: "user", Content: "hi"}},
}
}
// countingStreamProvider records how many times CompleteStream was called.
type countingStreamProvider struct {
mockStreamProvider
calls atomic.Int64
}
func newCountingStreamProvider(name string, fn func(context.Context) (<-chan providers.StreamChunk, error)) *countingStreamProvider {
p := &countingStreamProvider{}
p.name = name
p.models = []string{streamPipelineModel}
p.streamFn = func(ctx context.Context, _ providers.Request) (<-chan providers.StreamChunk, error) {
p.calls.Add(1)
return fn(ctx)
}
return p
}
// chunkStream returns a finished stream carrying one content delta and a usage
// block, which is the shape every OpenAI-compatible provider ends on.
func chunkStream(model string) <-chan providers.StreamChunk {
ch := make(chan providers.StreamChunk, 2)
ch <- providers.StreamChunk{
ID: "chatcmpl-pipeline",
Object: "chat.completion.chunk",
Created: 1,
Model: model,
Choices: []providers.StreamChoice{{
Index: 0,
Delta: providers.MessageDelta{Role: "assistant", Content: "hello"},
}},
}
ch <- providers.StreamChunk{
Object: "chat.completion.chunk",
Model: model,
Usage: &providers.Usage{PromptTokens: 7, CompletionTokens: 3, TotalTokens: 10},
}
close(ch)
return ch
}
// TestRouteStream_RetryIsHonouredInEveryStrategyMode is the streaming half of
// F19.
//
// Streaming used to run its own target loop, so uniform retry was a property it
// happened to share rather than one it inherited. Routing the start through the
// pipeline makes retryPolicyFor the only retry authority on this surface too,
// which is what stops the two loops drifting apart again.
func TestRouteStream_RetryIsHonouredInEveryStrategyMode(t *testing.T) {
modes := []config.StrategyMode{
config.ModeSingle,
config.ModeFallback,
config.ModeLoadBalance,
config.ModeLatency,
config.ModeCostOptimized,
config.ModeConditional,
config.ModeContentBased,
config.ModeABTest,
}
for _, mode := range modes {
t.Run(string(mode), func(t *testing.T) {
cfg := config.Config{
Strategy: config.StrategyConfig{Mode: mode},
Targets: []config.Target{{
VirtualKey: mockProviderName,
Weight: 1,
Retry: &config.RetryConfig{Attempts: 3, InitialBackoffMs: 1},
}},
}
switch mode {
case config.ModeConditional:
cfg.Strategy.Conditions = []config.Condition{
{Key: "model", Value: streamPipelineModel, TargetKey: mockProviderName},
}
case config.ModeContentBased:
cfg.Strategy.ContentConditions = []config.ContentCondition{
{Type: "prompt_contains", Value: "hi", TargetKey: mockProviderName},
}
case config.ModeABTest:
cfg.Strategy.ABVariants = []config.ABVariantConfig{
{TargetKey: mockProviderName, Weight: 1, Label: "control"},
}
}
gw, err := newTestGateway(t, cfg)
if err != nil {
t.Fatalf("new gateway: %v", err)
}
p := newCountingStreamProvider(mockProviderName, func(context.Context) (<-chan providers.StreamChunk, error) {
return nil, core.StatusError(mockProviderName, http.StatusInternalServerError, "boom")
})
gw.RegisterProvider(p)
if _, err := gw.RouteStream(context.Background(), streamPipelineRequest()); err == nil {
t.Fatal("expected the stream start to fail")
}
if got := p.calls.Load(); got != 3 {
t.Errorf("mode %s made %d stream-start attempts, want 3", mode, got)
}
})
}
}
// TestRouteStream_FailedStartObservesDuration is F63 on the streaming surface.
//
// A stream that never started still took time. Observing successes only left
// the streaming failure modes out of the histogram entirely, so its quantiles
// answered "how fast are the streams that worked".
func TestRouteStream_FailedStartObservesDuration(t *testing.T) {
gw, err := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: mockProviderName}},
})
if err != nil {
t.Fatalf("new gateway: %v", err)
}
gw.RegisterProvider(&mockStreamProvider{
mockProvider: mockProvider{name: mockProviderName, models: []string{streamPipelineModel}},
streamErr: core.StatusError(mockProviderName, http.StatusInternalServerError, "boom"),
})
labels := map[string]string{"provider": mockProviderName, "model": streamPipelineModel}
before := durationSampleCount(t, labels)
if _, err := gw.RouteStream(context.Background(), streamPipelineRequest()); err == nil {
t.Fatal("expected the stream start to fail")
}
if delta := durationSampleCount(t, labels) - before; delta != 1 {
t.Errorf("a failed stream start added %d duration samples, want 1", delta)
}
// F64: the failure must name the target that produced it.
if !requestMetricLabelExists(t, mockProviderName, streamPipelineModel, "error") {
t.Errorf("no streaming error sample carries provider=%q", mockProviderName)
}
}
// TestRouteStream_MidStreamFailureObservesDuration is F63 for the failure mode
// that costs the most time: the stream started, ran, and then broke. It is the
// one a duration histogram most needs to see and the one it could not.
func TestRouteStream_MidStreamFailureObservesDuration(t *testing.T) {
gw, err := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: mockProviderName}},
})
if err != nil {
t.Fatalf("new gateway: %v", err)
}
gw.RegisterProvider(&mockStreamProvider{
mockProvider: mockProvider{name: mockProviderName, models: []string{streamPipelineModel}},
streamFn: func(context.Context, providers.Request) (<-chan providers.StreamChunk, error) {
ch := make(chan providers.StreamChunk, 2)
ch <- providers.StreamChunk{
Model: streamPipelineModel,
Choices: []providers.StreamChoice{{Delta: providers.MessageDelta{Content: "par"}}},
}
ch <- providers.StreamChunk{Error: errors.New("upstream dropped the connection")}
close(ch)
return ch, nil
},
})
labels := map[string]string{"provider": mockProviderName, "model": streamPipelineModel}
before := durationSampleCount(t, labels)
ch, err := gw.RouteStream(context.Background(), streamPipelineRequest())
if err != nil {
t.Fatalf("RouteStream: %v", err)
}
for range ch { //nolint:revive // draining is the point
}
if delta := durationSampleCount(t, labels) - before; delta != 1 {
t.Errorf("a mid-stream failure added %d duration samples, want 1", delta)
}
}
// TestRouteStream_PluginRejectionObservesDuration is F63 on the streaming
// plugin-abort path — the one the non-streaming path already observed.
func TestRouteStream_PluginRejectionObservesDuration(t *testing.T) {
gw, err := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: mockProviderName}},
})
if err != nil {
t.Fatalf("new gateway: %v", err)
}
gw.RegisterProvider(&mockStreamProvider{
mockProvider: mockProvider{name: mockProviderName, models: []string{streamPipelineModel}},
})
if err := gw.RegisterPlugin(plugin.StageBeforeRequest, &testPlugin{
name: "denier",
typ: plugin.TypeGuardrail,
execFn: func(_ context.Context, pctx *plugin.Context) error {
pctx.Reject = true
pctx.Reason = "denied"
return nil
},
}); err != nil {
t.Fatalf("register plugin: %v", err)
}
// A rejection happens before any target is resolved, so it is recorded
// against metrics.NoProviderLabel, exactly as the chat path records it.
labels := map[string]string{"provider": metrics.NoProviderLabel, "model": streamPipelineModel}
before := durationSampleCount(t, labels)
if _, err := gw.RouteStream(context.Background(), streamPipelineRequest()); err == nil {
t.Fatal("expected the guardrail to reject the stream")
}
if delta := durationSampleCount(t, labels) - before; delta != 1 {
t.Errorf("a rejected stream added %d duration samples, want 1", delta)
}
}
// TestRouteStream_SpanCarriesResponseModel is F71.
//
// gen_ai.response.model is stamped when the channel drains, alongside the
// stream's terminal usage and cost attribution.
func TestRouteStream_SpanCarriesResponseModel(t *testing.T) {
gw, err := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: mockProviderName}},
})
if err != nil {
t.Fatalf("new gateway: %v", err)
}
fp := &fakeProvider{}
gw.SetObservability(fp)
gw.RegisterProvider(&mockStreamProvider{
mockProvider: mockProvider{name: mockProviderName, models: []string{streamPipelineModel}},
streamFn: func(context.Context, providers.Request) (<-chan providers.StreamChunk, error) {
// Provider chunk identity remains part of the forwarded wire stream;
// internal terminal attribution remains routed/client-visible.
return chunkStream(streamPipelineModel + "-2026-01-01"), nil
},
})
ch, err := gw.RouteStream(context.Background(), streamPipelineRequest())
if err != nil {
t.Fatalf("RouteStream: %v", err)
}
drainStream(t, ch)
span := fp.rootSpan()
if span == nil {
t.Fatal("no root span was started")
}
span.mu.Lock()
got, ok := span.attrs[observability.AttrGenAIResponseModel]
tokensIn, tokensOut := span.tokensIn, span.tokensOut
span.mu.Unlock()
if !ok {
t.Fatalf("streaming span carries no %s", observability.AttrGenAIResponseModel)
}
if want := streamPipelineModel; got != want {
t.Errorf("%s = %v, want %q", observability.AttrGenAIResponseModel, got, want)
}
// The usage half of F71, guarded so a regression cannot zero it again.
if tokensIn != 7 || tokensOut != 3 {
t.Errorf("streaming span usage = (%d, %d), want (7, 3)", tokensIn, tokensOut)
}
}
// TestRouteStream_HalfOpenProbeReleasedOnAbandonedStart is the invariant that
// wedges a target permanently when it breaks.
//
// A start that overruns the gateway's own start deadline is abandoned, but the
// call keeps running and may still SUCCEED. Nothing downstream will ever see
// that channel, so the half-open probe cbProvider admitted is resolved by the
// abandoning goroutine instead. Left held, it is never repaired: resolveState
// only moves Open to HalfOpen on a timer, never a HalfOpen circuit stuck at its
// probe cap, so the target rejects every later request until the process
// restarts.
//
// The pipeline must therefore hand streaming a *cbProvider-decorated provider
// and resolve nothing itself — if the breaker were resolved when the start call
// returned, or if the decoration stopped being outermost, this test wedges.
func TestRouteStream_HalfOpenProbeReleasedOnAbandonedStart(t *testing.T) {
release := make(chan struct{})
started := make(chan struct{}, 1)
gw, err := newTestGateway(t, config.Config{
// Shorter than the start the provider is about to perform, so the wait
// is abandoned while the call is still in flight.
RequestTimeout: "50ms",
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{
VirtualKey: mockProviderName,
CircuitBreaker: &config.CircuitBreakerConfig{
FailureThreshold: 1,
SuccessThreshold: 1,
MaxHalfThreshold: 1,
Timeout: "10ms",
},
}},
})
if err != nil {
t.Fatalf("new gateway: %v", err)
}
gw.RegisterProvider(&mockStreamProvider{
mockProvider: mockProvider{name: mockProviderName, models: []string{streamPipelineModel}},
streamFn: func(context.Context, providers.Request) (<-chan providers.StreamChunk, error) {
select {
case started <- struct{}{}:
default:
}
<-release
return chunkStream(streamPipelineModel), nil
},
})
// Force the breaker open, then let it age into half-open so the next start
// is admitted as its single probe.
cb := gw.circuitBreakerFor(t, mockProviderName)
cb.RecordFailure()
time.Sleep(30 * time.Millisecond)
// The start overruns the 50ms deadline and is abandoned.
if _, err := gw.RouteStream(context.Background(), streamPipelineRequest()); err == nil {
t.Fatal("expected the abandoned stream start to fail")
}
<-started
// Now let the abandoned call succeed. Its channel reaches nobody, so the
// probe must be released by the abandoning goroutine.
close(release)
deadline := time.Now().Add(2 * time.Second)
for !cb.Allow() {
if time.Now().After(deadline) {
t.Fatal("the circuit never admitted another request: the half-open probe from an abandoned-but-successful start was stranded, wedging the target for good")
}
time.Sleep(10 * time.Millisecond)
}
}
// TestRouteStream_ConcurrencySlotHeldForWholeStream guards the second half of
// responseOutlivesCall.
//
// The pipeline releases a target's concurrency slot when the leaf call returns.
// For a stream that is the moment the response HEADERS arrive, so releasing
// there would let unlimited streams run against a cap that only ever counted
// their setup. Streaming takes the limiter as a provider wrapper instead, which
// holds the slot until the last chunk.
func TestRouteStream_ConcurrencySlotHeldForWholeStream(t *testing.T) {
gw, err := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{
VirtualKey: mockProviderName,
Concurrency: &config.ConcurrencyConfig{MaxConcurrency: 1, QueueSize: 1},
}},
})
if err != nil {
t.Fatalf("new gateway: %v", err)
}
hold := make(chan struct{})
gw.RegisterProvider(&mockStreamProvider{
mockProvider: mockProvider{name: mockProviderName, models: []string{streamPipelineModel}},
streamFn: func(context.Context, providers.Request) (<-chan providers.StreamChunk, error) {
ch := make(chan providers.StreamChunk, 1)
go func() {
defer close(ch)
<-hold
ch <- providers.StreamChunk{
Model: streamPipelineModel,
Usage: &providers.Usage{PromptTokens: 1, CompletionTokens: 1, TotalTokens: 2},
}
}()
return ch, nil
},
})
// The first stream has started but not finished, so it still owns the only
// slot.
first, err := gw.RouteStream(context.Background(), streamPipelineRequest())
if err != nil {
t.Fatalf("first RouteStream: %v", err)
}
// A second start must find the limiter occupied. Its own context bounds the
// wait so a released slot shows up as a success rather than a hang.
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
defer cancel()
_, secondErr := gw.RouteStream(ctx, streamPipelineRequest())
close(hold)
drainStream(t, first)
if secondErr == nil {
t.Fatal("a second stream started while the first still held the only concurrency slot: the slot was released when the start call returned instead of when the stream ended")
}
if !errors.Is(secondErr, providers.ErrProviderSaturated) && !errors.Is(secondErr, context.DeadlineExceeded) {
t.Errorf("second stream failed with %v, want saturation or the queue wait timing out", secondErr)
}
}
// circuitBreakerFor returns the breaker the gateway built for one target,
// creating the per-target resilience state the same way a request would.
func (g *Gateway) circuitBreakerFor(t *testing.T, key string) *circuitbreaker.CircuitBreaker {
t.Helper()
g.mu.Lock()
g.ensureCircuitBreakersLocked()
cb := g.circuitBreakers[key]
g.mu.Unlock()
if cb == nil {
t.Fatalf("no circuit breaker configured for target %q", key)
}
return cb
}
func assertNoCallbackErrors(t *testing.T, callbackErrs <-chan error) {
t.Helper()
for {
select {
case err := <-callbackErrs:
t.Error(err)
default:
return
}
}
}
func TestGateway_RouteStream_BeforePluginCanSetNilRequest(t *testing.T) {
gw, _ := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: "missing"}},
})
_ = gw.RegisterPlugin(plugin.StageBeforeRequest, &testPlugin{
name: "nil-request",
typ: plugin.TypeGuardrail,
execFn: func(_ context.Context, pctx *plugin.Context) error {
pctx.Request = nil
return nil
},
})
_, err := gw.RouteStream(context.Background(), providers.Request{
Model: "gpt-4o",
Messages: []providers.Message{{Role: "user", Content: "hi"}},
})
if err == nil {
t.Fatal("expected error for missing streaming provider")
}
}
func TestGateway_RouteStream_RunAfterReceivesStreamResponse(t *testing.T) {
gw, _ := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: mockProviderName}},
})
gw.RegisterProvider(&mockStreamProvider{
mockProvider: mockProvider{name: mockProviderName, models: []string{"gpt-4o"}},
streamFn: func(context.Context, providers.Request) (<-chan providers.StreamChunk, error) {
ch := make(chan providers.StreamChunk, 3)
ch <- providers.StreamChunk{
ID: "chatcmpl-stream",
Object: "chat.completion.chunk",
Created: 123,
Model: "gpt-4o",
Choices: []providers.StreamChoice{{
Index: 0,
Delta: providers.MessageDelta{Role: "assistant", Content: "hello "},
}},
}
ch <- providers.StreamChunk{
ID: "chatcmpl-stream",
Object: "chat.completion.chunk",
Created: 123,
Model: "gpt-4o",
Choices: []providers.StreamChoice{{
Index: 0,
Delta: providers.MessageDelta{Content: "world"},
FinishReason: "stop",
}},
}
ch <- providers.StreamChunk{
ID: "chatcmpl-stream",
Object: "chat.completion.chunk",
Created: 123,
Model: "gpt-4o",
Usage: &providers.Usage{PromptTokens: 2, CompletionTokens: 3, TotalTokens: 5},
}
close(ch)
return ch, nil
},
})
var afterCalls int
callbackErrs := make(chan error, 8)
_ = gw.RegisterPlugin(plugin.StageAfterRequest, &testPlugin{
name: "after",
typ: plugin.TypeLogging,
execFn: func(_ context.Context, pctx *plugin.Context) error {
afterCalls++
if pctx.Request == nil {
callbackErrs <- errors.New("after plugin request is nil")
}
if pctx.Response == nil {
callbackErrs <- errors.New("after plugin response is nil")
return nil
}
if pctx.Response.Provider != mockProviderName {
callbackErrs <- fmt.Errorf("after plugin provider = %q, want mock", pctx.Response.Provider)
}
if pctx.Response.Model != "gpt-4o" {
callbackErrs <- fmt.Errorf("after plugin model = %q, want gpt-4o", pctx.Response.Model)
}
if pctx.Response.Usage.TotalTokens != 5 {
callbackErrs <- fmt.Errorf("after plugin total tokens = %d, want 5", pctx.Response.Usage.TotalTokens)
}
if len(pctx.Response.Choices) == 0 {
callbackErrs <- errors.New("after plugin choices are empty")
} else if got := pctx.Response.Choices[0].Message.Content; got != "hello world" {
callbackErrs <- fmt.Errorf("after plugin content = %q, want hello world", got)
}
return nil
},
})
ch, err := gw.RouteStream(context.Background(), providers.Request{
Model: "gpt-4o",
Messages: []providers.Message{{Role: "user", Content: "hi"}},
Stream: true,
})
if err != nil {
t.Fatalf("RouteStream: %v", err)
}
drainStream(t, ch)
assertNoCallbackErrors(t, callbackErrs)
if afterCalls != 1 {
t.Fatalf("after plugin calls = %d, want 1", afterCalls)
}
}
func TestGateway_RouteStream_RunOnErrorReceivesStreamError(t *testing.T) {
streamErr := errors.New("stream failed")
gw, _ := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: mockProviderName}},
})
gw.RegisterProvider(&mockStreamProvider{
mockProvider: mockProvider{name: mockProviderName, models: []string{"gpt-4o"}},
streamFn: func(context.Context, providers.Request) (<-chan providers.StreamChunk, error) {
ch := make(chan providers.StreamChunk, 1)
ch <- providers.StreamChunk{Error: streamErr}
close(ch)
return ch, nil
},
})
var onErrorCalls int
callbackErrs := make(chan error, 2)
_ = gw.RegisterPlugin(plugin.StageOnError, &testPlugin{
name: "on-error",
typ: plugin.TypeLogging,
execFn: func(_ context.Context, pctx *plugin.Context) error {
onErrorCalls++
if !errors.Is(pctx.Error, streamErr) {
callbackErrs <- fmt.Errorf("on-error plugin error = %v, want %v", pctx.Error, streamErr)
}
if pctx.Response != nil {
callbackErrs <- fmt.Errorf("on-error plugin response = %#v, want nil", pctx.Response)
}
return nil
},
})
ch, err := gw.RouteStream(context.Background(), providers.Request{
Model: "gpt-4o",
Messages: []providers.Message{{Role: "user", Content: "hi"}},
Stream: true,
})
if err != nil {
t.Fatalf("RouteStream: %v", err)
}
for chunk := range ch {
if !errors.Is(chunk.Error, streamErr) {
t.Fatalf("stream chunk error = %v, want %v", chunk.Error, streamErr)
}
}
assertNoCallbackErrors(t, callbackErrs)
if onErrorCalls != 1 {
t.Fatalf("on-error plugin calls = %d, want 1", onErrorCalls)
}
}
func TestGateway_RouteStream_AfterPluginRejectRunsOnError(t *testing.T) {
gw, _ := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: mockProviderName}},
})
gw.RegisterProvider(&mockStreamProvider{
mockProvider: mockProvider{name: mockProviderName, models: []string{"gpt-4o"}},
streamFn: func(context.Context, providers.Request) (<-chan providers.StreamChunk, error) {
ch := make(chan providers.StreamChunk, 2)
ch <- providers.StreamChunk{
Model: "gpt-4o",
Choices: []providers.StreamChoice{{
Index: 0,
Delta: providers.MessageDelta{Role: "assistant", Content: "ok"},
FinishReason: "stop",
}},
}
ch <- providers.StreamChunk{
Usage: &providers.Usage{PromptTokens: 1, CompletionTokens: 1, TotalTokens: 2},
}
close(ch)
return ch, nil
},
})
var onErrorCalls int
callbackErrs := make(chan error, 1)
_ = gw.RegisterPlugin(plugin.StageAfterRequest, &testPlugin{
name: "after",
typ: plugin.TypeGuardrail,
execFn: func(_ context.Context, pctx *plugin.Context) error {
pctx.Reject = true
pctx.Reason = "after plugin rejected"
return nil
},
})
_ = gw.RegisterPlugin(plugin.StageOnError, &testPlugin{
name: "on-error",
typ: plugin.TypeLogging,
execFn: func(_ context.Context, pctx *plugin.Context) error {
onErrorCalls++
var rejection *plugin.RejectionError
if !errors.As(pctx.Error, &rejection) {
callbackErrs <- fmt.Errorf("on-error plugin error = %T(%v), want *plugin.RejectionError", pctx.Error, pctx.Error)
}
return nil
},
})
ch, err := gw.RouteStream(context.Background(), providers.Request{
Model: "gpt-4o",
Messages: []providers.Message{{Role: "user", Content: "hi"}},
Stream: true,
})
if err != nil {
t.Fatalf("RouteStream: %v", err)
}
var sawPluginErr bool
for chunk := range ch {
if chunk.Error != nil {
sawPluginErr = true
}
}
if !sawPluginErr {
t.Fatal("expected stream chunk carrying after plugin rejection error")
}
assertNoCallbackErrors(t, callbackErrs)
if onErrorCalls != 1 {
t.Fatalf("on-error plugin calls = %d, want 1", onErrorCalls)
}
}
func TestGateway_Route_AfterPluginRejectRunsOnError(t *testing.T) {
gw, _ := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: mockProviderName}},
})
gw.RegisterProvider(&mockProvider{
name: mockProviderName,
models: []string{"gpt-4o"},
resp: &providers.Response{ID: "r1", Model: "gpt-4o", Provider: mockProviderName},
})
var onErrorCalls int
_ = gw.RegisterPlugin(plugin.StageAfterRequest, &testPlugin{
name: "after",
typ: plugin.TypeGuardrail,
execFn: func(_ context.Context, pctx *plugin.Context) error {
pctx.Reject = true
pctx.Reason = "after plugin rejected"
return nil
},
})
_ = gw.RegisterPlugin(plugin.StageOnError, &testPlugin{
name: "on-error",
typ: plugin.TypeLogging,
execFn: func(_ context.Context, pctx *plugin.Context) error {
onErrorCalls++
var rejection *plugin.RejectionError
if !errors.As(pctx.Error, &rejection) {
t.Fatalf("on-error plugin error = %T(%v), want *plugin.RejectionError", pctx.Error, pctx.Error)
}
return nil
},
})
_, err := gw.Route(context.Background(), providers.Request{
Model: "gpt-4o",
Messages: []providers.Message{{Role: "user", Content: "hi"}},
})
if err == nil {
t.Fatal("expected after plugin rejection")
}
if onErrorCalls != 1 {
t.Fatalf("on-error plugin calls = %d, want 1", onErrorCalls)
}
}
func TestGateway_Route_AfterLoggingPanicStaysNonFatal(t *testing.T) {
gw, _ := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: mockProviderName}},
})
gw.RegisterProvider(&mockProvider{
name: mockProviderName,
models: []string{"gpt-4o"},
resp: &providers.Response{ID: "r1", Model: "gpt-4o", Provider: mockProviderName},
})
var onErrorCalls int
_ = gw.RegisterPlugin(plugin.StageAfterRequest, &testPlugin{
name: "after-logger",
typ: plugin.TypeLogging,
execFn: func(context.Context, *plugin.Context) error {
panic("log sink down")
},
})
_ = gw.RegisterPlugin(plugin.StageOnError, &testPlugin{
name: "on-error",
typ: plugin.TypeLogging,
execFn: func(context.Context, *plugin.Context) error {
onErrorCalls++
return nil
},
})
resp, err := gw.Route(context.Background(), providers.Request{
Model: "gpt-4o",
Messages: []providers.Message{{Role: "user", Content: "hi"}},
})
if err != nil {
t.Fatalf("Route() error = %v, want nil", err)
}
if resp.ID != "r1" {
t.Fatalf("response ID = %q, want r1", resp.ID)
}
if onErrorCalls != 0 {
t.Fatalf("on-error plugin calls = %d, want 0", onErrorCalls)
}
}
func TestGateway_RouteStream_AfterLoggingErrorStaysNonFatal(t *testing.T) {
gw, _ := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: mockProviderName}},
})
gw.RegisterProvider(&mockStreamProvider{
mockProvider: mockProvider{name: mockProviderName, models: []string{"gpt-4o"}},
streamFn: func(context.Context, providers.Request) (<-chan providers.StreamChunk, error) {
ch := make(chan providers.StreamChunk, 2)
ch <- providers.StreamChunk{
Model: "gpt-4o",
Choices: []providers.StreamChoice{{
Index: 0,
Delta: providers.MessageDelta{Role: "assistant", Content: "ok"},
FinishReason: "stop",
}},
}
ch <- providers.StreamChunk{
Usage: &providers.Usage{PromptTokens: 1, CompletionTokens: 1, TotalTokens: 2},
}
close(ch)
return ch, nil
},
})
var onErrorCalls int
_ = gw.RegisterPlugin(plugin.StageAfterRequest, &testPlugin{
name: "after-logger",
typ: plugin.TypeLogging,
execFn: func(context.Context, *plugin.Context) error {
return fmt.Errorf("log sink down")
},
})
_ = gw.RegisterPlugin(plugin.StageOnError, &testPlugin{
name: "on-error",
typ: plugin.TypeLogging,
execFn: func(context.Context, *plugin.Context) error {
onErrorCalls++
return nil
},
})
ch, err := gw.RouteStream(context.Background(), providers.Request{
Model: "gpt-4o",
Messages: []providers.Message{{Role: "user", Content: "hi"}},
Stream: true,
})
if err != nil {
t.Fatalf("RouteStream: %v", err)
}
var chunks int
for chunk := range ch {
chunks++
if chunk.Error != nil {
t.Fatalf("stream chunk error = %v, want nil", chunk.Error)
}
}
if chunks == 0 {
t.Fatal("expected stream chunks")
}
if onErrorCalls != 0 {
t.Fatalf("on-error plugin calls = %d, want 0", onErrorCalls)
}
}
func TestGateway_RouteStream_ResponseCacheHitSkipsProvider(t *testing.T) {
gw, _ := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{Mode: config.ModeSingle},
Targets: []config.Target{{VirtualKey: mockProviderName}},
})
var streamCalls atomic.Int32
gw.RegisterProvider(&mockStreamProvider{
mockProvider: mockProvider{name: mockProviderName, models: []string{"gpt-4o"}},
streamFn: func(context.Context, providers.Request) (<-chan providers.StreamChunk, error) {
streamCalls.Add(1)
ch := make(chan providers.StreamChunk, 2)
ch <- providers.StreamChunk{
ID: "chatcmpl-cacheable",
Object: "chat.completion.chunk",
Created: 123,
Model: "gpt-4o",
Choices: []providers.StreamChoice{{
Index: 0,
Delta: providers.MessageDelta{Role: "assistant", Content: "cached"},
FinishReason: "stop",
}},
}
ch <- providers.StreamChunk{
ID: "chatcmpl-cacheable",
Object: "chat.completion.chunk",
Created: 123,
Model: "gpt-4o",
Usage: &providers.Usage{PromptTokens: 1, CompletionTokens: 1, TotalTokens: 2},
}
close(ch)
return ch, nil
},
})
cache := &cacheplugin.ResponseCache{}
if err := cache.Init(map[string]any{"max_age": 60}); err != nil {
t.Fatalf("cache init: %v", err)
}
_ = gw.RegisterPlugin(plugin.StageBeforeRequest, cache)
_ = gw.RegisterPlugin(plugin.StageAfterRequest, cache)
req := providers.Request{
Model: "gpt-4o",
Messages: []providers.Message{{Role: "user", Content: "hi"}},
Stream: true,
}
first, err := gw.RouteStream(context.Background(), req)
if err != nil {
t.Fatalf("first RouteStream: %v", err)
}
drainStream(t, first)
if got := streamCalls.Load(); got != 1 {
t.Fatalf("stream calls after first request = %d, want 1", got)
}
second, err := gw.RouteStream(context.Background(), req)
if err != nil {
t.Fatalf("second RouteStream: %v", err)
}
var content string
var usage *providers.Usage
for chunk := range second {
if chunk.Error != nil {
t.Fatalf("cached stream chunk error: %v", chunk.Error)
}
for _, choice := range chunk.Choices {
content += choice.Delta.Content
}
if chunk.Usage != nil {
usage = chunk.Usage
}
}
if got := streamCalls.Load(); got != 1 {
t.Fatalf("stream calls after cache hit = %d, want 1", got)
}
if content != "cached" {
t.Fatalf("cached stream content = %q, want cached", content)
}
if usage == nil || usage.TotalTokens != 2 {
t.Fatalf("cached stream usage = %#v, want total tokens 2", usage)
}
}
func TestGateway_RouteStream_ContentBasedPromptRegex(t *testing.T) {
gw, err := newTestGateway(t, config.Config{
Strategy: config.StrategyConfig{
Mode: config.ModeContentBased,
ContentConditions: []config.ContentCondition{{
Type: "prompt_regex",
Value: `(?i)\b(code|function)\b`,
TargetKey: "code-stream",
}},
},
Targets: []config.Target{
{VirtualKey: "general-stream"},
{VirtualKey: "code-stream"},
},
})
if err != nil {
t.Fatal(err)
}
selected := make(chan string, 2)
recordStream := func(name string) func(context.Context, providers.Request) (<-chan providers.StreamChunk, error) {
return func(context.Context, providers.Request) (<-chan providers.StreamChunk, error) {
selected <- name
ch := make(chan providers.StreamChunk)
close(ch)
return ch, nil
}
}
gw.RegisterProvider(&mockStreamProvider{
mockProvider: mockProvider{
name: "general-stream",
models: []string{"gpt-4o"},
},
streamFn: recordStream("general-stream"),
})
gw.RegisterProvider(&mockStreamProvider{
mockProvider: mockProvider{
name: "code-stream",
models: []string{"gpt-4o"},
},
streamFn: recordStream("code-stream"),
})
out, err := gw.RouteStream(context.Background(), providers.Request{
Model: "gpt-4o",
Stream: true,
Messages: []providers.Message{{Role: "user", Content: "write a Go function"}},
})
if err != nil {
t.Fatalf("RouteStream: %v", err)
}
for range out { //nolint:revive // empty-block: intentionally draining the stream to completion
}
select {
case got := <-selected:
if got != "code-stream" {