diff --git a/backend/internal/handler/openai_codex_models_fallback_test.go b/backend/internal/handler/openai_codex_models_fallback_test.go new file mode 100644 index 0000000000..205e377e73 --- /dev/null +++ b/backend/internal/handler/openai_codex_models_fallback_test.go @@ -0,0 +1,119 @@ +package handler + +import ( + "net/http" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestCodexModelsFallsBackToLocalManifestWhenUpstreamCannotServeModels(t *testing.T) { + cases := []struct { + name string + firstStatus int + firstBody string + }{ + {name: "upstream 5xx", firstStatus: http.StatusServiceUnavailable}, + {name: "empty manifest", firstStatus: http.StatusOK, firstBody: `{"models":[]}`}, + {name: "non JSON body", firstStatus: http.StatusOK, firstBody: `not-json`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + handler, upstream, groupID := newCodexModelsFailoverTestHandlerWithAccountCount(tc.firstStatus, 1, 3) + upstream.firstBody = tc.firstBody + + recorder := performCodexModelsRequest(t, handler, groupID) + + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.NotEmpty(t, recorder.Header().Get("ETag")) + slugs := codexHandlerManifestSlugs(t, recorder) + require.Contains(t, slugs, "gpt-5.6-sol") + require.NotContains(t, slugs, "gpt-image-2") + }) + } +} + +func TestCodexModelsFallsBackToLocalManifestAfterAllCandidatesFail(t *testing.T) { + handler, upstream, groupID := newCodexModelsFailoverTestHandler(http.StatusServiceUnavailable) + upstream.statuses = map[int64]int{ + 1: http.StatusServiceUnavailable, + 2: http.StatusServiceUnavailable, + } + + recorder := performCodexModelsRequest(t, handler, groupID) + + require.Equal(t, []int64{1, 2}, upstream.calls()) + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Contains(t, codexHandlerManifestSlugs(t, recorder), "gpt-5.6-sol") +} + +func TestCodexModelsFallbackPrefersGroupModelsListConfig(t *testing.T) { + handler, upstream, groupID := newCodexModelsFailoverTestHandler(http.StatusServiceUnavailable) + upstream.statuses = map[int64]int{ + 1: http.StatusServiceUnavailable, + 2: http.StatusServiceUnavailable, + } + group := &service.Group{ID: groupID, Platform: service.PlatformOpenAI} + group.ModelAllowlist = service.GroupModelAllowlist{ + Enabled: true, + Models: []string{"gpt-5.6-luna", "gpt-6.2-sol"}, + } + + recorder := performCodexModelsRequestForGroup(t, handler, group, "") + + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.ElementsMatch(t, []string{"gpt-5.6-luna", "gpt-6.2-sol"}, codexHandlerManifestSlugs(t, recorder)) +} + +func TestCodexModelsUpstreamManifestWinsOverLocalFallback(t *testing.T) { + handler, upstream, groupID := newCodexModelsFailoverTestHandlerWithAccountCount(http.StatusOK, 1, 3) + upstream.firstBody = `{"models":[{"slug":"upstream-only-model"}]}` + + recorder := performCodexModelsRequest(t, handler, groupID) + + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Equal(t, []string{"upstream-only-model"}, codexHandlerManifestSlugs(t, recorder)) +} + +func TestCodexModelsFallbackSupportsETagRevalidation(t *testing.T) { + handler, upstream, groupID := newCodexModelsFailoverTestHandlerWithAccountCount(http.StatusServiceUnavailable, 1, 3) + group := &service.Group{ID: groupID, Platform: service.PlatformOpenAI} + + first := performCodexModelsRequestForGroup(t, handler, group, "") + require.Equal(t, http.StatusOK, first.Code, first.Body.String()) + etag := first.Header().Get("ETag") + require.NotEmpty(t, etag) + require.NotEmpty(t, upstream.calls()) + + second := performCodexModelsRequestForGroup(t, handler, group, etag) + require.Equal(t, http.StatusNotModified, second.Code, second.Body.String()) + require.Empty(t, second.Body.Bytes()) +} + +func TestCodexModelsKeepsUpstreamErrorWhenLocalFallbackIsEmpty(t *testing.T) { + handler, upstream, groupID := newCodexModelsFailoverTestHandlerWithAccountCount(http.StatusServiceUnavailable, 1, 3) + group := &service.Group{ID: groupID, Platform: service.PlatformOpenAI} + // Dedicated image models are dropped from Codex manifests, so the local + // list is empty and the original upstream error must be preserved. + group.ModelAllowlist = service.GroupModelAllowlist{Enabled: true, Models: []string{"gpt-image-2"}} + + recorder := performCodexModelsRequestForGroup(t, handler, group, "") + + require.Equal(t, http.StatusBadGateway, recorder.Code, recorder.Body.String()) + require.NotEmpty(t, upstream.calls()) +} + +// codexModelsGroupWithoutLocalFallback configures a model list that Codex +// cannot advertise (image-generation only). The #5252 local fallback therefore +// stays empty and tests can still observe the original upstream error. +func codexModelsGroupWithoutLocalFallback(groupID int64) *service.Group { + return &service.Group{ + ID: groupID, + Platform: service.PlatformOpenAI, + ModelAllowlist: service.GroupModelAllowlist{ + Enabled: true, + Models: []string{"gpt-image-2"}, + }, + } +} diff --git a/backend/internal/handler/openai_codex_models_handler.go b/backend/internal/handler/openai_codex_models_handler.go index 6c17bee83b..2daac343a9 100644 --- a/backend/internal/handler/openai_codex_models_handler.go +++ b/backend/internal/handler/openai_codex_models_handler.go @@ -20,6 +20,9 @@ import ( // when disabled, groups with explicit mappings are generated locally; // otherwise ChatGPT manifests are proxied verbatim and custom API key manifests // receive provider-compatibility normalization plus short-lived caching. +// When no upstream can serve /models (missing endpoint, 5xx, or an empty +// manifest), a local fallback manifest is generated instead of failing the +// request while the group still has a usable local model list (#5252). func (h *OpenAIGatewayHandler) CodexModels(c *gin.Context) { if c.Request.Context().Err() != nil { return @@ -106,6 +109,9 @@ func (h *OpenAIGatewayHandler) CodexModels(c *gin.Context) { return } if lastUpstreamErr != nil { + if h.writeLocalCodexModelsFallback(c, apiKey.Group) { + return + } h.errorResponse(c, infraerrors.Code(lastUpstreamErr), "upstream_error", infraerrors.Message(lastUpstreamErr)) return } @@ -122,15 +128,29 @@ func (h *OpenAIGatewayHandler) CodexModels(c *gin.Context) { if c.Request.Context().Err() != nil { return } - if service.IsRetryableCodexModelsManifestError(err) && switchCount < maxAccountSwitches { - failedAccountIDs[account.ID] = struct{}{} - switchCount++ - lastUpstreamErr = err - continue + if service.IsRetryableCodexModelsManifestError(err) { + if switchCount < maxAccountSwitches { + failedAccountIDs[account.ID] = struct{}{} + switchCount++ + lastUpstreamErr = err + continue + } + // All candidates failed (or the switch budget is exhausted): an + // upstream without a usable /models endpoint must not break the + // client model picker while the group can describe its models + // locally (#5252). + if h.writeLocalCodexModelsFallback(c, apiKey.Group) { + return + } } h.errorResponse(c, infraerrors.Code(err), "upstream_error", infraerrors.Message(err)) return } + // A 2xx manifest with no models is as unusable as a failed request for + // Codex clients. Prefer the local catalog when one exists. + if service.CodexModelsManifestIsEmpty(manifest.Body) && h.writeLocalCodexModelsFallback(c, apiKey.Group) { + return + } if err := h.gatewayService.CompleteAPIKeyCodexModelsManifestForClient(manifest, account); err != nil { h.errorResponse(c, http.StatusInternalServerError, "api_error", "Failed to complete Codex models manifest") return @@ -152,6 +172,25 @@ func (h *OpenAIGatewayHandler) CodexModels(c *gin.Context) { } } +// writeLocalCodexModelsFallback writes a locally generated Codex manifest when +// the selected upstreams cannot serve /models. It reports false when the local +// model list is empty so the caller can preserve the original upstream error. +func (h *OpenAIGatewayHandler) writeLocalCodexModelsFallback(c *gin.Context, group *service.Group) bool { + if h == nil || h.gatewayService == nil { + return false + } + manifest, configured, err := h.gatewayService.BuildLocalCodexModelsFallbackManifest( + c.Request.Context(), + group, + c.GetHeader("If-None-Match"), + ) + if err != nil || !configured || manifest == nil { + return false + } + h.writeCodexModelsResponse(c, group, manifest) + return true +} + // writeCodexModelsResponse records the ETag the group's manifest is served with, // so codex.response.metadata events can be translated to it, and writes the // manifest response. diff --git a/backend/internal/handler/openai_codex_models_handler_test.go b/backend/internal/handler/openai_codex_models_handler_test.go index 5d102cfbf9..f5129389a7 100644 --- a/backend/internal/handler/openai_codex_models_handler_test.go +++ b/backend/internal/handler/openai_codex_models_handler_test.go @@ -534,7 +534,7 @@ func TestCodexModelsReturnsLastUpstreamErrorWhenAccountsAreExhausted(t *testing. 1: http.StatusServiceUnavailable, 2: http.StatusGatewayTimeout, } - recorder := performCodexModelsRequest(t, handler, groupID) + recorder := performCodexModelsRequestForGroup(t, handler, codexModelsGroupWithoutLocalFallback(groupID), "") if got, want := upstream.calls(), []int64{1, 2}; !equalInt64Slices(got, want) { t.Fatalf("upstream account calls: got %v, want %v", got, want) @@ -555,7 +555,7 @@ func TestCodexModelsHonorsAccountSwitchLimit(t *testing.T) { 3: http.StatusGatewayTimeout, 4: http.StatusInternalServerError, } - recorder := performCodexModelsRequest(t, handler, groupID) + recorder := performCodexModelsRequestForGroup(t, handler, codexModelsGroupWithoutLocalFallback(groupID), "") if got, want := upstream.calls(), []int64{1, 2, 3}; !equalInt64Slices(got, want) { t.Fatalf("upstream account calls: got %v, want %v", got, want) diff --git a/backend/internal/service/openai_codex_models_fallback.go b/backend/internal/service/openai_codex_models_fallback.go new file mode 100644 index 0000000000..3cc2163774 --- /dev/null +++ b/backend/internal/service/openai_codex_models_fallback.go @@ -0,0 +1,120 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/pkg/openai" +) + +// BuildLocalCodexModelsFallbackManifest generates a Codex models manifest from +// local configuration when no selected upstream can serve its /models endpoint. +// Model sources are tried in priority order: the group's models_list_config +// (ModelAllowlist), the group accounts' model_mapping keys, and finally the +// default OpenAI catalog used by /v1/models. Retired models are removed with +// the same filter as /v1/models so the degraded catalog cannot advertise +// upstream models that the accounts can no longer serve. +// +// A configured=false result with a nil error means the local list is empty, so +// callers must keep the original upstream error instead of returning an empty +// manifest. +func (s *OpenAIGatewayService) BuildLocalCodexModelsFallbackManifest( + ctx context.Context, + group *Group, + ifNoneMatch string, +) (*OpenAIModelsResponse, bool, error) { + if group == nil || group.Platform != PlatformOpenAI { + return nil, false, nil + } + var visible, catalog []Account + if s != nil && s.accountRepo != nil { + var err error + visible, catalog, err = loadCodexGroupCatalogAccounts(ctx, s.accountRepo, group.ID) + if err != nil { + return nil, false, fmt.Errorf("load local Codex models accounts: %w", err) + } + } + modelIDs := localCodexFallbackModelIDs(group, visible) + if len(modelIDs) == 0 { + return nil, false, nil + } + body, err := buildCodexModelsManifestForAccounts( + PlatformOpenAI, + modelIDs, + catalog, + group, + nil, + true, + ) + if err != nil { + return nil, false, fmt.Errorf("build local Codex models manifest: %w", err) + } + // The builder drops models that a Codex manifest cannot advertise (for + // example dedicated image-generation models). An empty result must not + // replace the upstream error with an empty 200 response. + if CodexModelsManifestIsEmpty(body) { + return nil, false, nil + } + manifest := &OpenAIModelsResponse{ + Body: body, + ETag: codexModelsManifestBodyETag(body), + } + if codexModelsManifestETagMatches(ifNoneMatch, manifest.ETag) { + manifest.Body = nil + manifest.NotModified = true + } + return manifest, true, nil +} + +// localCodexFallbackModelIDs resolves the local model list in the same priority +// order the fallback documents. An enabled group list wins over account +// mappings, and mappings win over the default catalog. +func localCodexFallbackModelIDs(group *Group, accounts []Account) []string { + var modelIDs []string + if group != nil && group.ModelAllowlistEnabled() { + modelIDs = concreteCodexModelIDs(group.ModelAllowlist.Models) + } + if len(modelIDs) == 0 { + modelIDs = openAIConfiguredCodexModelIDs(accounts) + } + if len(modelIDs) == 0 { + modelIDs = openai.DefaultModelIDs() + } + return filterRetiredOpenAIModelIDs(accounts, modelIDs) +} + +// concreteCodexModelIDs keeps concrete model names. Wildcard patterns are +// routing rules that cannot be expanded without an upstream catalog; emitting +// them verbatim would advertise a literal "*" slug to Codex clients. +func concreteCodexModelIDs(models []string) []string { + seen := make(map[string]struct{}, len(models)) + filtered := make([]string, 0, len(models)) + for _, modelID := range models { + modelID = strings.TrimSpace(modelID) + if modelID == "" || strings.Contains(modelID, "*") { + continue + } + key := strings.ToLower(modelID) + if _, ok := seen[key]; ok { + continue + } + seen[key] = struct{}{} + filtered = append(filtered, modelID) + } + return filtered +} + +// CodexModelsManifestIsEmpty reports whether a validated Codex manifest +// advertises no models. A body that cannot be decoded is never treated as +// empty so an unexpected upstream shape keeps its existing response path. +func CodexModelsManifestIsEmpty(body []byte) bool { + var envelope struct { + Models []json.RawMessage `json:"models"` + } + if err := json.Unmarshal(body, &envelope); err != nil { + return false + } + return len(envelope.Models) == 0 +} diff --git a/backend/internal/service/openai_codex_models_fallback_test.go b/backend/internal/service/openai_codex_models_fallback_test.go new file mode 100644 index 0000000000..c65804e963 --- /dev/null +++ b/backend/internal/service/openai_codex_models_fallback_test.go @@ -0,0 +1,170 @@ +package service + +import ( + "context" + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +type codexFallbackAccountRepo struct { + AccountRepository + accounts []Account +} + +func (r codexFallbackAccountRepo) ListSchedulableByGroupID(context.Context, int64) ([]Account, error) { + return append([]Account(nil), r.accounts...), nil +} + +func (r codexFallbackAccountRepo) ListModelAvailabilityCandidates(context.Context, *int64, []string, bool) ([]Account, error) { + return append([]Account(nil), r.accounts...), nil +} + +func newCodexFallbackTestService(accounts []Account) *OpenAIGatewayService { + return NewOpenAIGatewayService( + codexFallbackAccountRepo{accounts: accounts}, + nil, nil, nil, nil, nil, nil, + nil, // cfg + nil, nil, nil, nil, nil, + nil, // httpUpstream + nil, nil, nil, nil, nil, nil, nil, nil, + ) +} + +func codexFallbackManifestSlugs(t *testing.T, manifest *OpenAIModelsResponse) []string { + t.Helper() + require.NotNil(t, manifest) + var envelope struct { + Models []struct { + Slug string `json:"slug"` + } `json:"models"` + } + require.NoError(t, json.Unmarshal(manifest.Body, &envelope)) + slugs := make([]string, 0, len(envelope.Models)) + for _, model := range envelope.Models { + slugs = append(slugs, model.Slug) + } + return slugs +} + +func newCodexFallbackAPIKeyAccount(mapping map[string]any) Account { + credentials := map[string]any{ + "api_key": "sk-fallback", + "base_url": "https://upstream.example/v1", + } + if len(mapping) > 0 { + credentials["model_mapping"] = mapping + } + return Account{ + ID: 1, + Name: "fallback-upstream", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: credentials, + } +} + +func TestBuildLocalCodexModelsFallbackManifestPrefersGroupModelsListConfig(t *testing.T) { + accounts := []Account{ + newCodexFallbackAPIKeyAccount(map[string]any{"mapped-alias": "upstream-model"}), + } + group := &Group{ID: 7, Platform: PlatformOpenAI} + group.ModelAllowlist = GroupModelAllowlist{ + Enabled: true, + Models: []string{"gpt-5.6-luna", "*", "gpt-6.2-sol", "gpt-5.6-luna"}, + } + + manifest, configured, err := newCodexFallbackTestService(accounts). + BuildLocalCodexModelsFallbackManifest(context.Background(), group, "") + + require.NoError(t, err) + require.True(t, configured) + require.Equal(t, []string{"gpt-5.6-luna", "gpt-6.2-sol"}, codexFallbackManifestSlugs(t, manifest)) +} + +func TestBuildLocalCodexModelsFallbackManifestUsesAccountModelMapping(t *testing.T) { + accounts := []Account{ + newCodexFallbackAPIKeyAccount(map[string]any{"alias-b": "target-b", "alias-a": "target-a"}), + } + group := &Group{ID: 7, Platform: PlatformOpenAI} + + manifest, configured, err := newCodexFallbackTestService(accounts). + BuildLocalCodexModelsFallbackManifest(context.Background(), group, "") + + require.NoError(t, err) + require.True(t, configured) + require.Equal(t, []string{"alias-a", "alias-b"}, codexFallbackManifestSlugs(t, manifest)) +} + +func TestBuildLocalCodexModelsFallbackManifestUsesDefaultModels(t *testing.T) { + accounts := []Account{newCodexFallbackAPIKeyAccount(nil)} + group := &Group{ID: 7, Platform: PlatformOpenAI} + + manifest, configured, err := newCodexFallbackTestService(accounts). + BuildLocalCodexModelsFallbackManifest(context.Background(), group, "") + + require.NoError(t, err) + require.True(t, configured) + slugs := codexFallbackManifestSlugs(t, manifest) + require.Contains(t, slugs, "gpt-5.6-sol") + // Dedicated media models cannot be advertised in a Codex manifest. + require.NotContains(t, slugs, "gpt-image-2") +} + +func TestBuildLocalCodexModelsFallbackManifestFiltersRetiredModels(t *testing.T) { + accounts := []Account{{ + ID: 1, + Name: "fallback-oauth", + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{"access_token": "token"}, + }} + group := &Group{ID: 7, Platform: PlatformOpenAI} + + manifest, configured, err := newCodexFallbackTestService(accounts). + BuildLocalCodexModelsFallbackManifest(context.Background(), group, "") + + require.NoError(t, err) + require.True(t, configured) + slugs := codexFallbackManifestSlugs(t, manifest) + require.Contains(t, slugs, "gpt-5.6-sol") + require.NotContains(t, slugs, "gpt-5.5") +} + +func TestBuildLocalCodexModelsFallbackManifestEmptyLocalList(t *testing.T) { + accounts := []Account{newCodexFallbackAPIKeyAccount(nil)} + group := &Group{ID: 7, Platform: PlatformOpenAI} + group.ModelAllowlist = GroupModelAllowlist{Enabled: true, Models: []string{"gpt-image-2"}} + + manifest, configured, err := newCodexFallbackTestService(accounts). + BuildLocalCodexModelsFallbackManifest(context.Background(), group, "") + + require.NoError(t, err) + require.False(t, configured) + require.Nil(t, manifest) +} + +func TestBuildLocalCodexModelsFallbackManifestSupportsETagRevalidation(t *testing.T) { + accounts := []Account{newCodexFallbackAPIKeyAccount(nil)} + group := &Group{ID: 7, Platform: PlatformOpenAI} + service := newCodexFallbackTestService(accounts) + + first, configured, err := service.BuildLocalCodexModelsFallbackManifest(context.Background(), group, "") + require.NoError(t, err) + require.True(t, configured) + require.NotEmpty(t, first.ETag) + + second, configured, err := service.BuildLocalCodexModelsFallbackManifest(context.Background(), group, first.ETag) + require.NoError(t, err) + require.True(t, configured) + require.True(t, second.NotModified) + require.Nil(t, second.Body) + require.Equal(t, first.ETag, second.ETag) +}