diff --git a/acceleration/internal/api/fallback_answer_test.go b/acceleration/internal/api/fallback_answer_test.go new file mode 100644 index 0000000000..987b00d24d --- /dev/null +++ b/acceleration/internal/api/fallback_answer_test.go @@ -0,0 +1,125 @@ +package api + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/suite" + + "github.com/GetStream/Vision-Agents/acceleration/internal/llm" + "github.com/GetStream/Vision-Agents/acceleration/internal/llm/anthropic" + "github.com/GetStream/Vision-Agents/acceleration/internal/llm/openai" + "github.com/GetStream/Vision-Agents/acceleration/internal/llmrouter" + "github.com/GetStream/Vision-Agents/acceleration/internal/options" + "github.com/GetStream/Vision-Agents/acceleration/internal/routing" + "github.com/GetStream/Vision-Agents/acceleration/internal/search" + "github.com/GetStream/Vision-Agents/acceleration/internal/searchrouter" +) + +// FallbackAnswerSuite is what a caller is told when a model failed and its fallbacks were +// refused: only a refusal's own text, or that something went wrong. +type FallbackAnswerSuite struct { + suite.Suite +} + +func TestFallbackAnswerSuite(t *testing.T) { + suite.Run(t, new(FallbackAnswerSuite)) +} + +// allowingOnly is a customer whose policies allow only the models named. +type allowingOnly []string + +func (a allowingOnly) Admit(context.Context, routing.Owner) (routing.Admission, error) { + return routing.Admission{Models: a}, nil +} + +// erringSearch is a search vendor that fails every query with err. +type erringSearch struct{ err error } + +func (f erringSearch) Search(context.Context, search.Query) (search.Result, error) { + return search.Result{}, f.err +} +func (erringSearch) Start(context.Context) error { return nil } +func (erringSearch) Close() error { return nil } +func (erringSearch) Provider() string { return "stub" } +func (erringSearch) Model() string { return "fast" } + +func (s *FallbackAnswerSuite) TestATurnWhoseFallbackThePolicyDoesNotAllowAnswersSomethingWentWrong() { + vendor := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusServiceUnavailable) + fmt.Fprint(w, `{"error":{"message":"vendor-internal-body","type":"server_error"}}`) + })) + s.T().Cleanup(vendor.Close) + registry := llmrouter.NewRegistry() + registry.Register("openai", func(spec routing.Spec) (llmrouter.Provider, error) { + return llmrouter.Started(openai.New(openai.Options{APIKey: "test", BaseURL: vendor.URL, Model: spec.Model})) + }) + registry.Register("anthropic", func(spec routing.Spec) (llmrouter.Provider, error) { + return llmrouter.Started(anthropic.New(anthropic.Options{APIKey: "test", BaseURL: vendor.URL, Model: spec.Model})) + }) + router, err := llmrouter.New(llmrouter.Options{Registry: registry, Gate: allowingOnly{"openai/gpt-5.6-luna"}, Config: routing.ModalityConfig{ + Providers: []routing.ProviderConfig{ + {Provider: "openai", Model: "gpt-5.6-luna", Languages: []string{"en"}}, + {Provider: "anthropic", Model: "claude-opus-5", Languages: []string{"en"}}, + }, + }}) + s.Require().NoError(err) + s.T().Cleanup(router.Close) + session, err := router.Start(s.T().Context(), llmrouter.Request{CustomerID: "acme", Providers: []string{"openai/gpt-5.6-luna", "anthropic/claude-opus-5"}}) + s.Require().NoError(err) + s.T().Cleanup(func() { _ = session.Close() }) + + _, err = session.Create(s.T().Context(), llm.ResponseParams{Input: []llm.Message{{Role: llm.User, Content: "Hello"}}}) + + s.Require().Error(err) + s.Equal(somethingWentWrong, refusalText(err)) +} + +// searched is the error a search on a priority list of quick/fast and spare/fast answers, +// quick failing with quickErr and spare with spareErr; allowed, when set, is every model the +// customer's policies allow. +func (s *FallbackAnswerSuite) searched(quickErr, spareErr error, allowed ...string) error { + registry := searchrouter.NewRegistry() + registry.Register("quick", func(routing.Spec) (search.Provider, error) { return erringSearch{err: quickErr}, nil }) + registry.Register("spare", func(routing.Spec) (search.Provider, error) { return erringSearch{err: spareErr}, nil }) + opts := searchrouter.Options{Registry: registry, Config: routing.ModalityConfig{ + Providers: []routing.ProviderConfig{ + {Provider: "quick", Model: "fast", Languages: []string{"en"}}, + {Provider: "spare", Model: "fast", Languages: []string{"en"}}, + }, + }} + if len(allowed) > 0 { + opts.Gate = allowingOnly(allowed) + } + router, err := searchrouter.New(opts) + s.Require().NoError(err) + s.T().Cleanup(router.Close) + session, err := router.Start(s.T().Context(), searchrouter.Request{CustomerID: "acme", Target: "quick/fast", + Options: options.Search{Providers: []string{"quick/fast", "spare/fast"}}}) + s.Require().NoError(err) + + _, err = session.Search(s.T().Context(), search.Query{Text: "traffic"}) + s.Require().Error(err) + return searchFailed(s.T().Context(), err) +} + +func (s *FallbackAnswerSuite) TestASearchWhoseFallbackThePolicyDoesNotAllowAnswersSomethingWentWrong() { + answer := s.searched(errors.New(`GET "https://vendor.example.com/search": 502 vendor-internal-body`), nil, "quick/fast") + + _, refused := answer.(interface{ apiError() APIError }) + s.False(refused, "a failure goes on as is, and the caller is told only that something went wrong") +} + +func (s *FallbackAnswerSuite) TestASearchEveryModelRefusedAnswersTheirTexts() { + answer := s.searched(routing.Refused(errors.New("the query is too long")), routing.Refused(errors.New("the query is too long"))) + + refused, ok := answer.(interface{ apiError() APIError }) + s.Require().True(ok) + s.Equal("quick/fast: the query is too long\nspare/fast: the query is too long\nsearchrouter: no fallback provider available", + refused.apiError().Message) +} diff --git a/acceleration/internal/api/session_create_test.go b/acceleration/internal/api/session_create_test.go index 918ef21a34..7deb3baa6e 100644 --- a/acceleration/internal/api/session_create_test.go +++ b/acceleration/internal/api/session_create_test.go @@ -472,6 +472,45 @@ func (s *SessionCreateSuite) TestASessionOnAModelOfTheCustomersOwnIsAnsweredByIt s.Equal("https://8.8.8.8/v1 acme/tuned-27b sk-own", s.answerTo(opened.Id, "Hello?")) } +// priorityListAgent is an agent config whose llm is first and whose llm_fallbacks follow it, so a +// session opened on it starts a priority list. +func (s *SessionCreateSuite) priorityListAgent(first string, fallbacks ...string) *string { + var created AgentConfig + s.Require().Equal(http.StatusCreated, s.serverClient.do(http.MethodPost, "/v1/agents/configs", AgentConfigRequest{ + Name: "agent-" + s.utils.uuid(), Llm: pointerTo(first), LlmFallbacks: &fallbacks, + }, &created)) + return &created.Id +} + +func (s *SessionCreateSuite) TestAPriorityListWhoseModelKeyFailsToOpenAnswersSomethingWentWrong() { + name := "broken-" + s.utils.uuid() + sealed, err := s.sealer.SealWithAAD("sk-own", []byte(s.utils.uuid())) + s.Require().NoError(err) + s.Require().NoError(s.store.CustomModels.Insert(context.Background(), &store.CustomModel{ + CustomerID: s.customerID(), Name: name, BaseURL: "https://8.8.8.8/v1", Model: "acme/tuned-27b", + APIKeySealed: sealed, KEKVersion: s.sealer.CurrentVersion(), + })) + request := textSession(nil) + request.ConfigId = s.priorityListAgent("custom/"+name, "custom/not-there-"+s.utils.uuid()) + + status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/sessions", request) + + s.Equal(http.StatusInternalServerError, status) + s.Equal(somethingWentWrong, failure, "the key's failure is the router's, and a refused entry beside it does not make it the caller's") +} + +func (s *SessionCreateSuite) TestAPriorityListOfModelsTheCustomerDoesNotHoldIsRefusedWithTheirNames() { + first, second := "not-there-"+s.utils.uuid(), "gone-"+s.utils.uuid() + request := textSession(nil) + request.ConfigId = s.priorityListAgent("custom/"+first, "custom/"+second) + + status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/sessions", request) + + s.Equal(http.StatusBadRequest, status) + s.Contains(failure, "custom/"+first+`" is not one of this customer's models`) + s.Contains(failure, "custom/"+second+`" is not one of this customer's models`) +} + func (s *SessionCreateSuite) TestARoleOutsideUserAndAssistantIsRefused() { status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/sessions", map[string]any{ "text": true, "incognito": true, "llm": "recites/recites-model", diff --git a/acceleration/internal/api/streams_test.go b/acceleration/internal/api/streams_test.go index 4e4fa0c7e8..bedca007fa 100644 --- a/acceleration/internal/api/streams_test.go +++ b/acceleration/internal/api/streams_test.go @@ -594,6 +594,41 @@ func (s *StreamsSuite) TestAnotherCustomersModelIsNotOneThisCustomerCanName() { s.Contains(refused["error"], "not one of this customer's models") } +// brokenKeyModel stores a custom model whose key was sealed for another row, so opening it fails. +func (s *StreamsSuite) brokenKeyModel() string { + name := "broken-" + s.utils.uuid() + sealed, err := s.sealer.SealWithAAD("sk-own", []byte(s.utils.uuid())) + s.Require().NoError(err) + s.Require().NoError(s.store.CustomModels.Insert(context.Background(), &store.CustomModel{ + CustomerID: s.customerID(), Name: name, BaseURL: "https://8.8.8.8/v1", Model: "acme/tuned-27b", + APIKeySealed: sealed, KEKVersion: s.sealer.CurrentVersion(), + })) + return name +} + +func (s *StreamsSuite) TestAPriorityListWhoseModelKeyFailsToOpenAnswersSomethingWentWrong() { + broken := s.brokenKeyModel() + + answering := s.start("/v1/llm/stream", frame{"target": "custom/" + broken, "llm": frame{"providers": []string{ + "custom/" + broken, "custom/not-there-" + s.utils.uuid()}}}) + + failed := s.nextFrame(answering) + s.Equal("error", failed["type"]) + s.Equal(somethingWentWrong, failed["error"], "the key's failure is the router's, and a refused entry beside it does not make it the caller's") +} + +func (s *StreamsSuite) TestAPriorityListOfModelsTheCustomerDoesNotHoldIsRefusedWithTheirNames() { + first, second := "not-there-"+s.utils.uuid(), "gone-"+s.utils.uuid() + + answering := s.start("/v1/llm/stream", frame{"target": "custom/" + first, + "llm": frame{"providers": []string{"custom/" + first, "custom/" + second}}}) + + refused := s.nextFrame(answering) + s.Equal("error", refused["type"]) + s.Contains(refused["error"], "custom/"+first+`" is not one of this customer's models`) + s.Contains(refused["error"], "custom/"+second+`" is not one of this customer's models`) +} + func (s *StreamsSuite) TestAPictureAModelCannotSeeIsRefusedRatherThanSentAnyway() { answering := s.start("/v1/llm/stream", frame{"target": "llm-flow"}) s.Equal("started", s.nextFrame(answering)["type"]) diff --git a/acceleration/internal/llmrouter/fallback_class_test.go b/acceleration/internal/llmrouter/fallback_class_test.go new file mode 100644 index 0000000000..ab7156d2f5 --- /dev/null +++ b/acceleration/internal/llmrouter/fallback_class_test.go @@ -0,0 +1,70 @@ +package llmrouter + +import ( + "errors" + + "github.com/GetStream/Vision-Agents/acceleration/internal/llm" + "github.com/GetStream/Vision-Agents/acceleration/internal/routing" +) + +// errVendorDown is a failure on the vendor's side, whose text the caller is never sent. +var errVendorDown = errors.New(`POST "https://vendor.example.com/responses": 503 vendor-internal-body`) + +// turnFailing asks one turn of a session started on the priority list of models, each of +// which fails the turn with its error in fails; allowed, when set, is every model the +// customer's policies allow. +func (s *LLMRouterSuite) turnFailing(fails map[string]error, providers []string, allowed ...string) error { + registry := NewRegistry() + var configs []routing.ProviderConfig + for _, name := range providers { + provider := newStubLLM() + provider.createErr = fails[name] + registry.Register(name, func(routing.Spec) (Provider, error) { return Started[llm.LLM](provider, nil) }) + configs = append(configs, routing.ProviderConfig{Provider: name, Model: "m", Languages: []string{"en"}}) + } + options := Options{Registry: registry, Config: routing.ModalityConfig{Providers: configs}} + if len(allowed) > 0 { + options.Gate = allowing(allowed) + } + router, err := New(options) + s.Require().NoError(err) + s.T().Cleanup(router.Close) + var list []string + for _, name := range providers { + list = append(list, name+"/m") + } + session, err := router.Start(s.ctx, Request{CustomerID: "acme", Providers: list}) + s.Require().NoError(err) + s.T().Cleanup(func() { _ = session.Close() }) + + _, err = session.Create(s.ctx, llm.ResponseParams{Input: []llm.Message{{Role: llm.User, Content: "Hello"}}}) + s.Require().Error(err) + return err +} + +func (s *LLMRouterSuite) TestATurnAFallbackFailedOnIsNotTheCallersMistakeForTheOthersRefusingIt() { + err := s.turnFailing(map[string]error{ + "first": routing.Refused(errors.New("first: the prompt is too long")), + "second": routing.Refused(errors.New("second: the prompt is too long")), + "third": errVendorDown, + }, []string{"first", "second", "third"}) + + s.NotErrorIs(err, routing.ErrRequest) +} + +func (s *LLMRouterSuite) TestATurnThatFailedIsNotTheCallersMistakeForAFallbackThePolicyDoesNotAllow() { + err := s.turnFailing(map[string]error{"first": errVendorDown}, []string{"first", "second"}, "first/m") + + s.NotErrorIs(err, routing.ErrModelNotAllowed) + s.NotErrorIs(err, routing.ErrRequest) +} + +func (s *LLMRouterSuite) TestATurnEveryModelRefusedIsRefusedWithTheirTexts() { + err := s.turnFailing(map[string]error{ + "first": routing.Refused(errors.New("first: the prompt is too long")), + "second": routing.Refused(errors.New("second: the prompt is too long")), + }, []string{"first", "second"}) + + s.ErrorIs(err, routing.ErrRequest) + s.Equal("first: the prompt is too long\nsecond: the prompt is too long\nllmrouter: no fallback provider available", err.Error()) +} diff --git a/acceleration/internal/llmrouter/fallback_test.go b/acceleration/internal/llmrouter/fallback_test.go index 5cd9f93fe0..7327a9a57d 100644 --- a/acceleration/internal/llmrouter/fallback_test.go +++ b/acceleration/internal/llmrouter/fallback_test.go @@ -182,7 +182,9 @@ func TestAFallbackNeverReachesAModelThePolicyDoesNotAllow(t *testing.T) { _, err = session.Create(t.Context(), llm.ResponseParams{Input: []llm.Message{{Role: llm.User, Content: "Hello"}}}) - require.ErrorIs(t, err, routing.ErrModelNotAllowed) + // The turn failed at its vendor, so it is not refused for the policy: the policy is only + // why no fallback answered. + require.ErrorContains(t, err, routing.ErrModelNotAllowed.Error()) require.Zero(t, asked.Load(), "the model the policy does not allow was never asked") } diff --git a/acceleration/internal/llmrouter/router.go b/acceleration/internal/llmrouter/router.go index aad695facb..419eb1a03e 100644 --- a/acceleration/internal/llmrouter/router.go +++ b/acceleration/internal/llmrouter/router.go @@ -242,7 +242,9 @@ func (r *Router) Start(ctx context.Context, request Request) (*Session, error) { } }), nil } - return nil, stack.Wrap(errors.Join(append(failures, errors.New("llmrouter: no fallback provider available"))...)) + // The last line is no candidate's error, so it stays out of the join that decides + // whether the candidates refused the request or failed it. + return nil, stack.Wrap(errors.Join(routing.Join(failures...), errors.New("llmrouter: no fallback provider available"))) } return session, nil } diff --git a/acceleration/internal/routing/chain_class_test.go b/acceleration/internal/routing/chain_class_test.go new file mode 100644 index 0000000000..2b2c7983e3 --- /dev/null +++ b/acceleration/internal/routing/chain_class_test.go @@ -0,0 +1,73 @@ +package routing + +import ( + "context" + "errors" + "log/slog" +) + +// heldModels is a customer with two models: "held" works, and "unreadable" fails because its +// lookup breaks on the deployment's side. Every other name is refused. +type heldModels struct{} + +var errStoreDown = errors.New("store: custom model: connection refused to db.internal:5432") + +func (heldModels) CustomModel(_ context.Context, _, name string) (ProviderConfig, Endpoint, error) { + switch name { + case "held": + return ProviderConfig{Provider: CustomProvider, Model: name}, Endpoint{BaseURL: "https://models.example.com/v1", Model: name}, nil + case "unreadable": + return ProviderConfig{}, Endpoint{}, errStoreDown + } + return ProviderConfig{}, Endpoint{}, Refused(errors.New(`routing: "custom/` + name + `" is not one of this customer's models`)) +} + +func (s *RoutingSuite) TestAPriorityListKeepsTheClassOfEachEntrysError() { + registry := NewRegistry[*stubProvider]() + registry.Register(CustomProvider, func(spec Spec) (*stubProvider, error) { return &stubProvider{model: spec.Model}, nil }) + router, err := New(Options[*stubProvider]{ + Modality: LLM, Config: s.config(), Registry: registry, Models: heldModels{}, Logger: slog.New(slog.DiscardHandler), + }) + s.Require().NoError(err) + s.T().Cleanup(router.Close) + start := func(providers ...string) error { + _, _, err := router.Select(s.ctx, Request{CustomerID: "acme", Target: providers[0], Providers: providers}) + return err + } + + for name, test := range map[string]struct { + providers []string + refused bool + }{ + "an entry that failed beside one that was refused": {[]string{"custom/unreadable", "custom/absent"}, false}, + "a refused entry before one that failed": {[]string{"custom/absent", "custom/unreadable"}, false}, + "an entry that failed alone": {[]string{"custom/unreadable"}, false}, + "every entry refused": {[]string{"custom/absent", "custom/missing"}, true}, + } { + err := start(test.providers...) + s.Require().Error(err, name) + s.Equal(test.refused, errors.Is(err, ErrRequest), name) + } + s.NoError(start("custom/absent", "custom/held"), "a model the customer holds serves a list whose first entry is refused") +} + +// An empty entry, and a model of the customer's own on a router that serves none, are the +// caller's to correct. Beside an entry nothing answers to, the list is still refused with +// every entry's text. +func (s *RoutingSuite) TestAPriorityListEntryTheCallerGotWrongIsRefusedBesideAnother() { + router := s.newRouter() + for name, test := range map[string]struct { + providers []string + text string + }{ + "an empty entry": {[]string{"", "unknown"}, "routing: nothing in the priority list , unknown can serve this request: " + + "routing: target is required\nrouting: unknown target \"unknown\""}, + "a model of the customer's own": {[]string{"custom/mine", "unknown"}, "routing: nothing in the priority list custom/mine, unknown can serve this request: " + + "routing: \"custom/mine\" was asked for, and this deployment has no models of a customer's own\nrouting: unknown target \"unknown\""}, + } { + _, _, err := router.Select(s.ctx, Request{CustomerID: "acme", Target: test.providers[0], Providers: test.providers}) + s.Require().Error(err, name) + s.ErrorIs(err, ErrRequest, name) + s.Equal(test.text, err.Error(), name) + } +} diff --git a/acceleration/internal/routing/registry.go b/acceleration/internal/routing/registry.go index e9bcebc20a..8c8fe23f46 100644 --- a/acceleration/internal/routing/registry.go +++ b/acceleration/internal/routing/registry.go @@ -109,11 +109,14 @@ func (r refused) Unwrap() []error { return []error{r.err, ErrRequest} } func Refused(err error) error { return refused{err: err} } // Join joins the errors of the candidates a request was tried on. Once one of them failed -// on its own account, the request is not the caller's mistake for another one refusing it: -// the join says every error but is only the ones that are not refusals. +// on its own account, the request is not the caller's mistake for another one refusing it, +// or for the customer's policies not allowing another one: the join says every error but is +// only the ones that are neither. func Join(errs ...error) error { joined := errors.Join(errs...) - failures := slices.DeleteFunc(slices.Clone(errs), func(err error) bool { return errors.Is(err, ErrRequest) }) + failures := slices.DeleteFunc(slices.Clone(errs), func(err error) bool { + return errors.Is(err, ErrRequest) || errors.Is(err, ErrModelNotAllowed) + }) if len(failures) == 0 || len(failures) == len(errs) { return joined } diff --git a/acceleration/internal/routing/router.go b/acceleration/internal/routing/router.go index 635e991d01..5b30cda7be 100644 --- a/acceleration/internal/routing/router.go +++ b/acceleration/internal/routing/router.go @@ -1097,7 +1097,7 @@ func (r *Router[P]) resolveChain(ctx context.Context, request Request) ([]Candid if len(refusals) == 0 { return nil, stack.Wrap(errors.New(message)) } - return nil, stack.Wrap(fmt.Errorf("%s: %w", message, errors.Join(refusals...))) + return nil, stack.Wrap(fmt.Errorf("%s: %w", message, Join(refusals...))) } demote(chain) @@ -1122,6 +1122,11 @@ func (r *Router[P]) resolveEntry(ctx context.Context, customerID, target string, named = append(named, provider) } if len(named) == 0 { + // An empty entry, or a model of the customer's own on a router that has none, is the + // caller's to correct, as a name nothing answers to is. + if _, own := CustomName(target); target == "" || (own && r.models == nil) { + return nil, Refused(err) + } return nil, err } return r.candidates(ctx, named), nil diff --git a/acceleration/internal/searchrouter/fallback_class_test.go b/acceleration/internal/searchrouter/fallback_class_test.go new file mode 100644 index 0000000000..b492cdd1a0 --- /dev/null +++ b/acceleration/internal/searchrouter/fallback_class_test.go @@ -0,0 +1,83 @@ +package searchrouter + +import ( + "context" + "errors" + "log/slog" + + "github.com/GetStream/Vision-Agents/acceleration/internal/options" + "github.com/GetStream/Vision-Agents/acceleration/internal/routing" + "github.com/GetStream/Vision-Agents/acceleration/internal/search" +) + +// errVendorDown is a failure on the vendor's side, whose text the caller is never sent. +var errVendorDown = errors.New(`GET "https://vendor.example.com/search?q=traffic": 502 vendor-internal-body`) + +// allowing is a customer whose policies allow only the models named. +type allowing []string + +func (a allowing) Admit(context.Context, routing.Owner) (routing.Admission, error) { + return routing.Admission{Models: a}, nil +} + +// searchFailing asks one search of a session started on a priority list of one model of each +// vendor, n of them, the ith failing with fails[i]; allowed, when set, is the indexes of the +// models the customer's policies allow. It returns the vendors' names and the error. +func (s *SearchRouterSuite) searchFailing(fails []error, allowed ...int) ([]string, error) { + names := vendors(len(fails)) + stubs := map[string]*stubSearch{} + var list, allows []string + for i, name := range names { + stubs[name] = &stubSearch{model: "fast", err: fails[i]} + list = append(list, name+"/fast") + } + for _, i := range allowed { + allows = append(allows, list[i]) + } + config := routing.ModalityConfig{} + registry := NewRegistry() + for _, name := range names { + config.Providers = append(config.Providers, routing.ProviderConfig{Provider: name, Model: "fast", Languages: []string{"en"}}) + registry.Register(name, func(routing.Spec) (search.Provider, error) { return stubs[name], nil }) + } + opts := Options{Config: config, Registry: registry, Logger: slog.New(slog.DiscardHandler)} + if len(allows) > 0 { + opts.Gate = allowing(allows) + } + router, err := New(opts) + s.Require().NoError(err) + s.T().Cleanup(router.Close) + session, err := router.Start(s.ctx, Request{CustomerID: "acme", Target: list[0], Options: options.Search{Providers: list}}) + s.Require().NoError(err) + + _, err = session.Search(s.ctx, search.Query{Text: "traffic"}) + s.Require().Error(err) + return names, err +} + +func (s *SearchRouterSuite) TestASearchThatFailedIsNotTheCallersMistakeForAFallbackThePolicyDoesNotAllow() { + _, err := s.searchFailing([]error{errVendorDown, nil}, 0) + + s.NotErrorIs(err, routing.ErrModelNotAllowed) + s.NotErrorIs(err, routing.ErrRequest) +} + +func (s *SearchRouterSuite) TestASearchAFallbackFailedIsNotTheCallersMistakeForTheOthersRefusingIt() { + _, err := s.searchFailing([]error{ + routing.Refused(errors.New("the query is too long")), + routing.Refused(errors.New("the query is too long")), + errVendorDown, + }) + + s.NotErrorIs(err, routing.ErrRequest) +} + +func (s *SearchRouterSuite) TestASearchEveryModelRefusedIsRefusedWithTheirTexts() { + names, err := s.searchFailing([]error{ + routing.Refused(errors.New("the query is too long")), + routing.Refused(errors.New("the query is too long")), + }) + + s.ErrorIs(err, routing.ErrRequest) + s.Equal(names[0]+"/fast: the query is too long\n"+names[1]+"/fast: the query is too long\nsearchrouter: no fallback provider available", err.Error()) +} diff --git a/acceleration/internal/searchrouter/router.go b/acceleration/internal/searchrouter/router.go index 5f542cbab0..cedab530d3 100644 --- a/acceleration/internal/searchrouter/router.go +++ b/acceleration/internal/searchrouter/router.go @@ -154,7 +154,9 @@ func (r *Router) Start(ctx context.Context, request Request) (*Session, error) { } return next, found, nil } - return nil, search.Result{}, stack.Wrap(errors.Join(append(failures, errors.New("searchrouter: no fallback provider available"))...)) + // The last line is no candidate's error, so it stays out of the join that decides + // whether the candidates refused the request or failed it. + return nil, search.Result{}, stack.Wrap(errors.Join(routing.Join(failures...), errors.New("searchrouter: no fallback provider available"))) } return session, nil }