diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go index c48a9f99cd..352ab5b4d9 100644 --- a/backend/internal/handler/admin/account_handler.go +++ b/backend/internal/handler/admin/account_handler.go @@ -964,7 +964,11 @@ func (h *AccountHandler) GetByID(c *gin.Context) { } } - response.Success(c, h.buildAccountResponseWithRuntime(c.Request.Context(), account)) + result := h.buildAccountResponseWithRuntime(c.Request.Context(), account) + if h.accountTestService != nil && account != nil && account.IsGrok() { + result.GrokModelDiagnostics = h.accountTestService.GetGrokModelDiagnostics(c.Request.Context(), account) + } + response.Success(c, result) } // CheckMixedChannel handles checking mixed channel risk for account-group binding. @@ -3090,6 +3094,11 @@ func (h *AccountHandler) SyncUpstreamModels(c *gin.Context) { response.Error(c, http.StatusBadGateway, "Failed to sync upstream models from upstream") return } + if catalog != nil && account != nil && account.IsGrok() && account.ID > 0 && h.accountTestService != nil { + if latest, readErr := h.adminService.GetAccount(c.Request.Context(), account.ID); readErr == nil && latest != nil { + catalog.GrokModelDiagnostics = h.accountTestService.GetGrokModelDiagnostics(c.Request.Context(), latest) + } + } response.Success(c, catalog) } diff --git a/backend/internal/handler/admin/account_handler_grok_model_diagnostics_test.go b/backend/internal/handler/admin/account_handler_grok_model_diagnostics_test.go new file mode 100644 index 0000000000..487bdacd2d --- /dev/null +++ b/backend/internal/handler/admin/account_handler_grok_model_diagnostics_test.go @@ -0,0 +1,347 @@ +package admin + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestAccountHandlerGrokModelDiagnosticsGetByID(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &grokDiagHandlerUpstream{} + account := grokDiagDetailAccount(t) + account.Credentials["access_token"] = "access-secret" + account.Credentials["refresh_token"] = "refresh-secret" + handler, router := newGrokDiagDetailRouter(&simpleModeAccountService{stubAdminService: newStubAdminService(), account: account}, upstream) + + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/accounts/25", nil)) + + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + body := rec.Body.String() + require.Contains(t, body, `"current_concurrency"`) + diag := grokDiagResponseObject(t, body) + require.Equal(t, "fresh", diag["state"]) + require.Equal(t, "https://cli-chat-proxy.grok.com/v1/models", diag["endpoint"]) + require.Equal(t, []any{"grok-4.7"}, diag["models"]) + mappings, ok := diag["mappings"].([]any) + require.True(t, ok) + require.NotEmpty(t, mappings) + got := grokDiagMappingsByRequested(t, mappings) + require.Equal(t, "listed", got["friendly"]["status"]) + require.Equal(t, "grok-4.7", got["friendly"]["upstream"]) + require.Equal(t, "not_listed", got["composer-2.5"]["status"]) + require.Equal(t, "grok-composer-2.5-fast", got["composer-2.5"]["upstream"]) + require.Zero(t, upstream.calls) + require.NotContains(t, body, "access-secret") + require.NotContains(t, body, "refresh-secret") + require.NotContains(t, body, `"models":null`) + require.NotContains(t, body, `"mappings":null`) + + raw, err := json.Marshal(handler.buildAccountResponseWithRuntime(context.Background(), &account)) + require.NoError(t, err) + require.NotContains(t, string(raw), "grok_model_diagnostics") +} + +func TestAccountHandlerGrokModelDiagnosticsOmitsNonGrokAndMissingSnapshot(t *testing.T) { + gin.SetMode(gin.TestMode) + nonGrok := service.Account{ID: 3, Name: "claude", Platform: service.PlatformAnthropic, Type: service.AccountTypeOAuth, Status: service.StatusActive} + _, nonGrokRouter := newGrokDiagDetailRouter(&simpleModeAccountService{stubAdminService: newStubAdminService(), account: nonGrok}, &grokDiagHandlerUpstream{}) + nonGrokRec := httptest.NewRecorder() + nonGrokRouter.ServeHTTP(nonGrokRec, httptest.NewRequest(http.MethodGet, "/accounts/3", nil)) + require.Equal(t, http.StatusOK, nonGrokRec.Code, nonGrokRec.Body.String()) + require.NotContains(t, nonGrokRec.Body.String(), "grok_model_diagnostics") + + old := service.Account{ + ID: 25, Name: "old-grok", Platform: service.PlatformGrok, Type: service.AccountTypeOAuth, Status: service.StatusActive, + Credentials: map[string]any{"access_token": "old-access-secret"}, + } + _, oldRouter := newGrokDiagDetailRouter(&simpleModeAccountService{stubAdminService: newStubAdminService(), account: old}, &grokDiagHandlerUpstream{}) + oldRec := httptest.NewRecorder() + oldRouter.ServeHTTP(oldRec, httptest.NewRequest(http.MethodGet, "/accounts/25", nil)) + require.Equal(t, http.StatusOK, oldRec.Code, oldRec.Body.String()) + diag := grokDiagResponseObject(t, oldRec.Body.String()) + require.Equal(t, "unknown", diag["state"]) + require.Empty(t, diag["models"]) + require.IsType(t, []any{}, diag["models"]) + require.IsType(t, []any{}, diag["mappings"]) + require.NotContains(t, oldRec.Body.String(), "old-access-secret") + require.NotContains(t, oldRec.Body.String(), `"models":null`) + require.NotContains(t, oldRec.Body.String(), `"mappings":null`) +} + +func TestAccountHandlerGrokModelDiagnosticsSyncRereadsLatestAccount(t *testing.T) { + gin.SetMode(gin.TestMode) + initial := &service.Account{ + ID: 25, Name: "grok", Platform: service.PlatformGrok, Type: service.AccountTypeAPIKey, Status: service.StatusActive, + Credentials: map[string]any{ + "api_key": "sync-secret", + "base_url": "https://relay.example.com/v1", + "model_mapping": map[string]any{"friendly": "grok-4.7"}, + }, + } + scope, err := service.NewGrokCatalogScope(25, service.AccountTypeAPIKey, "https://relay.example.com/v1/models") + require.NoError(t, err) + latestSnap := &service.GrokObservedModelsSnapshot{ + Models: []string{"grok-from-reread"}, + FetchedAt: time.Now().UTC().Add(-time.Minute).Format(time.RFC3339Nano), + Scope: scope, + } + rawSnap, err := json.Marshal(latestSnap) + require.NoError(t, err) + var decoded map[string]any + require.NoError(t, json.Unmarshal(rawSnap, &decoded)) + latest := *initial + latest.Extra = map[string]any{"grok_observed_models": decoded} + adminSvc := &grokDiagRereadAdmin{stubAdminService: newStubAdminService(), first: initial, latest: &latest} + repo := &grokDiagCatalogRepo{account: cloneGrokDiagAccount(initial)} + upstream := &grokDiagHandlerUpstream{responses: []*http.Response{ + {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"data":[{"id":"grok-4.7"}]}`))}, + {StatusCode: http.StatusBadGateway, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":"registry-down"}`))}, + }} + router := newGrokDiagSyncRouter(adminSvc, repo, upstream) + + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/25/models/sync-upstream", nil)) + + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + body := rec.Body.String() + var payload struct { + Data struct { + Models []string `json:"models"` + DiscoverySource string `json:"discovery_source"` + } `json:"data"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &payload)) + require.Equal(t, []string{"grok-4.7"}, payload.Data.Models) + require.Equal(t, "upstream", payload.Data.DiscoverySource) + diag := grokDiagResponseObject(t, body) + require.Equal(t, []any{"grok-from-reread"}, diag["models"]) + require.Equal(t, "fresh", diag["state"]) + require.GreaterOrEqual(t, adminSvc.calls, 2) + require.NotContains(t, body, "sync-secret") + require.NotContains(t, body, "registry-down") + require.NotContains(t, body, `"models":null`) + require.NotContains(t, body, `"mappings":null`) +} + +func TestAccountHandlerGrokModelDiagnosticsSyncErrorAndPreviewStayUnchanged(t *testing.T) { + gin.SetMode(gin.TestMode) + adminSvc := &simpleModeAccountService{stubAdminService: newStubAdminService(), account: service.Account{ + ID: 44, Platform: service.PlatformGrok, Type: service.AccountTypeAPIKey, Status: service.StatusActive, + Credentials: map[string]any{"base_url": "https://relay.example.com/v1"}, + }} + router := newGrokDiagSyncRouter(adminSvc, nil, &grokDiagHandlerUpstream{}) + errorRec := httptest.NewRecorder() + router.ServeHTTP(errorRec, httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/44/models/sync-upstream", nil)) + require.Equal(t, http.StatusBadRequest, errorRec.Code, errorRec.Body.String()) + require.Contains(t, errorRec.Body.String(), "No Grok API key is available") + require.NotContains(t, errorRec.Body.String(), "grok_model_diagnostics") + + previewRouter := newGrokDiagSyncRouter(newStubAdminService(), nil, &grokDiagHandlerUpstream{responses: []*http.Response{ + {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"data":[{"id":"grok-4.7"}]}`))}, + {StatusCode: http.StatusBadGateway, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":"registry-secret"}`))}, + }}) + previewRec := httptest.NewRecorder() + previewReq := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/models/sync-upstream-preview", bytes.NewBufferString(`{ + "platform":"grok","type":"apikey","base_url":"https://relay.example.com/v1","api_key":"preview-secret", + "model_mapping":{"friendly":"grok-4.7"} + }`)) + previewReq.Header.Set("Content-Type", "application/json") + previewRouter.ServeHTTP(previewRec, previewReq) + require.Equal(t, http.StatusOK, previewRec.Code, previewRec.Body.String()) + require.Contains(t, previewRec.Body.String(), `"models":["grok-4.7"]`) + require.NotContains(t, previewRec.Body.String(), "grok_model_diagnostics") + require.NotContains(t, previewRec.Body.String(), "preview-secret") + require.NotContains(t, previewRec.Body.String(), "registry-secret") +} + +func newGrokDiagDetailRouter(adminSvc service.AdminService, upstream *grokDiagHandlerUpstream) (*AccountHandler, *gin.Engine) { + handler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, nil, newGrokDiagTestService(nil, upstream), nil, nil, nil, nil, nil) + router := gin.New() + router.GET("/accounts/:id", handler.GetByID) + return handler, router +} + +func newGrokDiagSyncRouter(adminSvc service.AdminService, repo service.AccountRepository, upstream *grokDiagHandlerUpstream) *gin.Engine { + handler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, nil, newGrokDiagTestService(repo, upstream), nil, nil, nil, nil, nil) + router := gin.New() + router.POST("/api/v1/admin/accounts/:id/models/sync-upstream", handler.SyncUpstreamModels) + router.POST("/api/v1/admin/accounts/models/sync-upstream-preview", handler.SyncUpstreamModelsPreview) + return router +} + +func newGrokDiagTestService(repo service.AccountRepository, upstream service.HTTPUpstream) *service.AccountTestService { + return service.NewAccountTestService(repo, nil, nil, nil, nil, upstream, &config.Config{ + Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}, + }, nil) +} + +func grokDiagDetailAccount(t *testing.T) service.Account { + t.Helper() + scope, err := service.NewGrokCatalogScope(25, service.AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models") + require.NoError(t, err) + snap := &service.GrokObservedModelsSnapshot{ + Models: []string{"grok-4.7"}, + FetchedAt: time.Now().UTC().Add(-time.Hour).Format(time.RFC3339Nano), + Scope: scope, + } + raw, err := json.Marshal(snap) + require.NoError(t, err) + var decoded map[string]any + require.NoError(t, json.Unmarshal(raw, &decoded)) + return service.Account{ + ID: 25, Name: "grok", Platform: service.PlatformGrok, Type: service.AccountTypeOAuth, Status: service.StatusActive, + Credentials: map[string]any{"model_mapping": map[string]any{ + "friendly": "grok-4.7", + "composer-2.5": "composer-2.5", + }}, + Extra: map[string]any{"grok_observed_models": decoded}, + } +} + +func grokDiagResponseObject(t *testing.T, body string) map[string]any { + t.Helper() + var payload map[string]any + require.NoError(t, json.Unmarshal([]byte(body), &payload)) + data, ok := payload["data"].(map[string]any) + require.True(t, ok, body) + diag, ok := data["grok_model_diagnostics"].(map[string]any) + require.True(t, ok, body) + return diag +} + +func grokDiagMappingsByRequested(t *testing.T, mappings []any) map[string]map[string]any { + t.Helper() + out := make(map[string]map[string]any, len(mappings)) + for _, raw := range mappings { + item, ok := raw.(map[string]any) + require.True(t, ok) + requested, _ := item["requested"].(string) + out[requested] = item + } + return out +} + +type grokDiagRereadAdmin struct { + *stubAdminService + first *service.Account + latest *service.Account + calls int +} + +func (s *grokDiagRereadAdmin) GetAccount(context.Context, int64) (*service.Account, error) { + s.calls++ + if s.calls == 1 { + return cloneGrokDiagAccount(s.first), nil + } + return cloneGrokDiagAccount(s.latest), nil +} + +type grokDiagCatalogRepo struct { + service.AccountRepository + mu sync.Mutex + account *service.Account +} + +func (r *grokDiagCatalogRepo) GetByID(_ context.Context, id int64) (*service.Account, error) { + r.mu.Lock() + defer r.mu.Unlock() + if r.account == nil || r.account.ID != id { + return nil, service.ErrAccountNotFound + } + return cloneGrokDiagAccount(r.account), nil +} + +func (r *grokDiagCatalogRepo) UpdateExtra(context.Context, int64, map[string]any) error { + return nil +} + +func (r *grokDiagCatalogRepo) CompareAndSwapGrokObservedModels(_ context.Context, id int64, expected, next json.RawMessage) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + if r.account == nil || r.account.ID != id { + return false, nil + } + var current any + if r.account.Extra != nil { + current = r.account.Extra["grok_observed_models"] + } + currentJSON, err := json.Marshal(current) + if err != nil { + return false, err + } + var expectedValue any + var currentValue any + if err := json.Unmarshal(expected, &expectedValue); err != nil { + return false, err + } + if err := json.Unmarshal(currentJSON, ¤tValue); err != nil { + return false, err + } + if !reflect.DeepEqual(expectedValue, currentValue) { + return false, nil + } + var decoded any + if err := json.Unmarshal(next, &decoded); err != nil { + return false, err + } + if r.account.Extra == nil { + r.account.Extra = map[string]any{} + } + r.account.Extra["grok_observed_models"] = decoded + return true, nil +} + +func cloneGrokDiagAccount(src *service.Account) *service.Account { + if src == nil { + return nil + } + raw, err := json.Marshal(src) + if err != nil { + copied := *src + return &copied + } + var dst service.Account + if err := json.Unmarshal(raw, &dst); err != nil { + copied := *src + return &copied + } + return &dst +} + +type grokDiagHandlerUpstream struct { + mu sync.Mutex + calls int + responses []*http.Response +} + +func (u *grokDiagHandlerUpstream) Do(*http.Request, string, int64, int) (*http.Response, error) { + u.mu.Lock() + defer u.mu.Unlock() + u.calls++ + if len(u.responses) == 0 { + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(`{"data":[{"id":"grok-4.7"}]}`)), Header: make(http.Header)}, nil + } + resp := u.responses[0] + u.responses = u.responses[1:] + return resp, nil +} + +func (u *grokDiagHandlerUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, accountConcurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return u.Do(req, proxyURL, accountID, accountConcurrency) +} diff --git a/backend/internal/handler/dto/account_mapper_redact_test.go b/backend/internal/handler/dto/account_mapper_redact_test.go index 9a979a66b6..d061a3325b 100644 --- a/backend/internal/handler/dto/account_mapper_redact_test.go +++ b/backend/internal/handler/dto/account_mapper_redact_test.go @@ -100,3 +100,58 @@ func TestAccountFromServiceShallow_NilCredentialsOmitsStatus(t *testing.T) { require.Nil(t, got.Credentials) require.Nil(t, got.CredentialsStatus) } + +func TestAccountFromService_RedactsGrokModelDiagnostics(t *testing.T) { + src := &service.Account{ + ID: 25, Name: "grok", Platform: service.PlatformGrok, Type: service.AccountTypeOAuth, + Credentials: map[string]any{ + "access_token": "access-secret", + "refresh_token": "refresh-secret", + "api_key": "sk-secret", + "base_url": "https://cli-chat-proxy.grok.com/v1", + "model_mapping": map[string]any{"friendly": "grok-4.7"}, + }, + Extra: map[string]any{"grok_observed_models": map[string]any{"models": []any{"grok-4.7"}}}, + } + + got := AccountFromService(src) + require.Nil(t, got.GrokModelDiagnostics) + shallow := AccountFromServiceShallow(src) + require.Nil(t, shallow.GrokModelDiagnostics) + + diagnostics := &service.GrokModelDiagnostics{ + State: "fresh", + Endpoint: "https://cli-chat-proxy.grok.com/v1/models", + Models: []string{"grok-4.7"}, + Mappings: []service.GrokModelDiagnosticItem{{Requested: "friendly", Upstream: "grok-4.7", Status: "listed"}}, + LastAttempt: &service.GrokCatalogAttempt{ + StartedAt: "2026-10-25T06:00:00Z", FinishedAt: "2026-10-25T06:00:01Z", Status: "failed", ErrorCode: "http_error", + Scope: &service.GrokCatalogScope{AccountID: 25, AccountType: service.AccountTypeOAuth, Endpoint: "https://cli-chat-proxy.grok.com/v1/models"}, + }, + } + diagRaw, err := json.Marshal(diagnostics) + require.NoError(t, err) + require.NotContains(t, string(diagRaw), "access-secret") + require.NotContains(t, string(diagRaw), "query-secret") + require.NotContains(t, string(diagRaw), "s3cret") + require.NotContains(t, string(diagRaw), "user:") + require.Contains(t, string(diagRaw), `"models":["grok-4.7"]`) + require.NotContains(t, string(diagRaw), `"models":null`) + require.NotContains(t, string(diagRaw), `"mappings":null`) + got.GrokModelDiagnostics = diagnostics + raw, err := json.Marshal(got) + require.NoError(t, err) + body := string(raw) + require.Contains(t, body, `"grok_model_diagnostics"`) + require.Contains(t, body, `"mappings":[`) + require.NotContains(t, body, "access-secret") + require.NotContains(t, body, "refresh-secret") + require.NotContains(t, body, "sk-secret") + require.NotContains(t, body, "query-secret") + require.NotContains(t, body, "s3cret") + + listRaw, err := json.Marshal(AccountListItemFromAccount(got)) + require.NoError(t, err) + require.NotContains(t, string(listRaw), "grok_model_diagnostics") + require.NotContains(t, string(listRaw), "access-secret") +} diff --git a/backend/internal/handler/dto/types.go b/backend/internal/handler/dto/types.go index f24a4a3ac7..930cc98193 100644 --- a/backend/internal/handler/dto/types.go +++ b/backend/internal/handler/dto/types.go @@ -328,6 +328,9 @@ type Account struct { GroupIDs []int64 `json:"group_ids,omitempty"` Groups []*Group `json:"groups,omitempty"` + + // 仅账号详情填充。列表和公共 mapper 不计算,避免把目录诊断扩散到调度响应。 + GrokModelDiagnostics *service.GrokModelDiagnostics `json:"grok_model_diagnostics,omitempty"` } // AccountListItem is the compact representation returned by the admin account diff --git a/backend/internal/pkg/apicompat/anthropic_to_responses.go b/backend/internal/pkg/apicompat/anthropic_to_responses.go index a54ca94133..c27e445537 100644 --- a/backend/internal/pkg/apicompat/anthropic_to_responses.go +++ b/backend/internal/pkg/apicompat/anthropic_to_responses.go @@ -68,7 +68,7 @@ func AnthropicToResponsesWithMinOutputTokens(req *AnthropicRequest, minOutputTok // An explicit thinking disable takes precedence over output_config.effort. effort := anthropicReasoningEffort(req) - if openai.IsGPT61SolModelSpelling(req.Model) && req.OutputConfig != nil && req.OutputConfig.Effort == "max" && effort != "none" { + if (openai.IsGPT61SolModelSpelling(req.Model) || openai.IsGPT61TerraModelSpelling(req.Model)) && req.OutputConfig != nil && req.OutputConfig.Effort == "max" && effort != "none" { effort = "max" } out.Reasoning = &ResponsesReasoning{ diff --git a/backend/internal/pkg/openai/constants.go b/backend/internal/pkg/openai/constants.go index 8c1d7c9571..f213459eca 100644 --- a/backend/internal/pkg/openai/constants.go +++ b/backend/internal/pkg/openai/constants.go @@ -25,6 +25,7 @@ var DefaultModels = []Model{ {ID: "gpt-5.6", Object: "model", Created: 1780876800, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.6 (Sol)"}, {ID: "gpt-5.6-terra", Object: "model", Created: 1780876800, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.6 Terra"}, {ID: "gpt-5.6-luna", Object: "model", Created: 1780876800, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.6 Luna"}, + {ID: "gpt-6.1-terra", Object: "model", Created: 1704067200, OwnedBy: "openai", Type: "model", DisplayName: "GPT-6.1 Terra"}, {ID: "gpt-6.1-sol", Object: "model", Created: 1790640000, OwnedBy: "openai", Type: "model", DisplayName: "GPT-6.1 Sol"}, {ID: "gpt-6-sol", Object: "model", Created: 1790035200, OwnedBy: "openai", Type: "model", DisplayName: "GPT-6 Sol"}, {ID: "gpt-6-luna", Object: "model", Created: 1790035200, OwnedBy: "openai", Type: "model", DisplayName: "GPT-6 Luna"}, @@ -216,6 +217,27 @@ func IsGPT61SolModelSpelling(model string) bool { } } +func IsGPT61TerraModelSpelling(model string) bool { + canonical := CanonicalizeOpenAIModelAliasSpelling(model) + if canonical == "gpt-6.1-terra" { + return true + } + suffix, ok := strings.CutPrefix(canonical, "gpt-6.1-terra-") + if !ok { + return false + } + switch suffix { + case "none", "low", "medium", "high", "xhigh", "max", "openai-compact": + return true + default: + return false + } +} + +func RequiresResponsesForToolCalls(model string) bool { + return IsGPT61SolModelSpelling(model) || IsGPT61TerraModelSpelling(model) +} + // ValidateGPT61SolReasoningEffort rejects disabled reasoning instead of silently // increasing the client's requested effort on compatibility paths. func ValidateGPT61SolReasoningEffort(model, effort string) error { diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index d3f8b5d9a9..bd9b1b0419 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -680,7 +680,9 @@ func lockAndMergeAccountProbeExtra( false ), extra -> 'opencode_go_usage_auto_refresh', - extra -> 'opencode_go_usage_snapshot' + extra -> 'opencode_go_usage_snapshot', + extra -> 'grok_observed_models', + extra -> 'upstream_model_metadata' FROM accounts WHERE id = $1 AND deleted_at IS NULL FOR NO KEY UPDATE @@ -709,6 +711,8 @@ func lockAndMergeAccountProbeExtra( currentOllamaSnapshot []byte currentOpenCodeAutoRefresh []byte currentOpenCodeSnapshot []byte + currentGrokObservedModels []byte + currentUpstreamModelMetadata []byte ) if err := rows.Scan( &identityUnchanged, @@ -723,6 +727,8 @@ func lockAndMergeAccountProbeExtra( &opencodeGroupIdentityUnchanged, ¤tOpenCodeAutoRefresh, ¤tOpenCodeSnapshot, + ¤tGrokObservedModels, + ¤tUpstreamModelMetadata, ); err != nil { return nil, err } @@ -836,6 +842,21 @@ func lockAndMergeAccountProbeExtra( } } } + // Grok 目录和能力 metadata 是同步写入的受管状态。普通更新在行锁内采用最新 + // 数据库值,忽略表单旧值、缺键和注入。来源身份变化不删除已有成功快照。 + for key, raw := range map[string][]byte{ + "grok_observed_models": currentGrokObservedModels, + service.UpstreamModelMetadataExtraKey: currentUpstreamModelMetadata, + } { + delete(extra, key) + value, ok, err := decodeAccountExtraJSON(raw) + if err != nil { + return nil, err + } + if ok { + extra[key] = value + } + } return extra, nil } diff --git a/backend/internal/repository/account_repo_grok_managed_extra_integration_test.go b/backend/internal/repository/account_repo_grok_managed_extra_integration_test.go new file mode 100644 index 0000000000..84edfd5623 --- /dev/null +++ b/backend/internal/repository/account_repo_grok_managed_extra_integration_test.go @@ -0,0 +1,326 @@ +//go:build integration + +package repository + +import ( + "context" + "encoding/json" + "errors" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestGrokManagedExtraSurvivesOrdinaryUpdate(t *testing.T) { + freshModels := map[string]any{ + "models": []any{"fresh-model"}, + "fetched_at": "2026-10-25T12:00:00Z", + } + freshMetadata := map[string]any{ + "models": map[string]any{"fresh-model": map[string]any{"id": "fresh-model"}}, + } + failedModels := map[string]any{ + "models": []any{"fresh-model"}, + "fetched_at": "2026-10-25T12:00:00Z", + "last_attempt": map[string]any{ + "status": "failed", + "error_code": "transport", + "started_at": "2026-10-25T13:00:00Z", + "finished_at": "2026-10-25T13:00:01Z", + }, + } + oldModels := map[string]any{ + "models": []any{"old-model"}, + "fetched_at": "2026-10-24T12:00:00Z", + } + oldMetadata := map[string]any{ + "models": map[string]any{"old-model": map[string]any{"id": "old-model"}}, + } + + tests := []struct { + name string + accountType string + credentials map[string]any + storedExtra map[string]any + updateExtra map[string]any + updateCreds map[string]any + wantModels map[string]any + wantMetadata map[string]any + wantBaseURL string + }{ + { + name: "oauth old form", + accountType: service.AccountTypeOAuth, + credentials: map[string]any{"access_token": "token-keep"}, + storedExtra: map[string]any{ + "unrelated": "keep", + "grok_observed_models": freshModels, + service.UpstreamModelMetadataExtraKey: freshMetadata, + }, + updateExtra: map[string]any{ + "unrelated": "keep", + "note": "from-form", + "grok_observed_models": oldModels, + service.UpstreamModelMetadataExtraKey: oldMetadata, + }, + wantModels: freshModels, + wantMetadata: freshMetadata, + }, + { + name: "apikey missing keys", + accountType: service.AccountTypeAPIKey, + credentials: map[string]any{"api_key": "sk-keep", "base_url": "https://api.example.test/v1"}, + storedExtra: map[string]any{ + "unrelated": "keep", + "grok_observed_models": freshModels, + service.UpstreamModelMetadataExtraKey: freshMetadata, + }, + updateExtra: map[string]any{ + "unrelated": "keep", + "note": "from-form", + }, + wantModels: freshModels, + wantMetadata: freshMetadata, + }, + { + name: "injection when absent", + accountType: service.AccountTypeOAuth, + credentials: map[string]any{"access_token": "token-keep"}, + storedExtra: map[string]any{"unrelated": "keep"}, + updateExtra: map[string]any{ + "unrelated": "keep", + "note": "from-form", + "grok_observed_models": oldModels, + service.UpstreamModelMetadataExtraKey: oldMetadata, + }, + }, + { + name: "failed attempt", + accountType: service.AccountTypeAPIKey, + credentials: map[string]any{"api_key": "sk-keep"}, + storedExtra: map[string]any{ + "unrelated": "keep", + "grok_observed_models": failedModels, + service.UpstreamModelMetadataExtraKey: freshMetadata, + }, + updateExtra: map[string]any{ + "unrelated": "keep", + "note": "from-form", + "grok_observed_models": oldModels, + service.UpstreamModelMetadataExtraKey: oldMetadata, + }, + wantModels: failedModels, + wantMetadata: freshMetadata, + }, + { + name: "source identity change keeps success", + accountType: service.AccountTypeOAuth, + credentials: map[string]any{ + "access_token": "token-keep", + "base_url": "https://old.example.test/v1", + }, + storedExtra: map[string]any{ + "unrelated": "keep", + "grok_observed_models": freshModels, + service.UpstreamModelMetadataExtraKey: freshMetadata, + }, + updateExtra: map[string]any{ + "unrelated": "keep", + "note": "from-form", + "grok_observed_models": nil, + }, + updateCreds: map[string]any{ + "access_token": "token-keep", + "base_url": "https://new.example.test/v1", + }, + wantModels: freshModels, + wantMetadata: freshMetadata, + wantBaseURL: "https://new.example.test/v1", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tx := testEntTx(t) + repo := newAccountRepositoryWithSQL(tx.Client(), tx, nil) + account := mustCreateAccount(t, tx.Client(), &service.Account{ + Name: "grok-managed-" + tt.name, + Platform: service.PlatformGrok, + Type: tt.accountType, + Credentials: tt.credentials, + Extra: tt.storedExtra, + }) + account.Name = "renamed" + account.Extra = tt.updateExtra + if tt.updateCreds != nil { + account.Credentials = tt.updateCreds + } + + require.NoError(t, repo.Update(context.Background(), account)) + + got := readGrokManagedExtra(t, tx, account.ID) + require.Equal(t, "renamed", got.name) + require.Equal(t, "from-form", got.note) + require.Equal(t, "keep", got.unrelated) + require.Equal(t, tt.wantModels, got.models) + require.Equal(t, tt.wantMetadata, got.metadata) + if tt.wantBaseURL != "" { + require.Equal(t, tt.wantBaseURL, got.baseURL) + } + }) + } +} + +func TestGrokManagedExtraUpdateOverlapsCatalogCAS(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + account := mustCreateGrokCatalogAccount(t, testEntClient(t), "grok-managed-overlap") + t.Cleanup(func() { + cleanupCtx := context.Background() + _, _ = integrationDB.ExecContext(cleanupCtx, "DELETE FROM scheduler_outbox WHERE account_id = $1", account.ID) + _, _ = integrationDB.ExecContext(cleanupCtx, "DELETE FROM accounts WHERE id = $1", account.ID) + }) + + freshModels := `{"models":["fresh-model"],"fetched_at":"2026-10-25T12:00:00Z","last_attempt":{"status":"failed","error_code":"transport","started_at":"2026-10-25T13:00:00Z","finished_at":"2026-10-25T13:00:01Z"}}` + freshMetadata := `{"models":{"fresh-model":{"id":"fresh-model"}}}` + + tx, err := integrationEntClient.Tx(ctx) + require.NoError(t, err) + t.Cleanup(func() { _ = tx.Rollback() }) + + locked := make(chan struct{}) + release := make(chan struct{}) + holderDone := make(chan struct{}) + var holderErr error + go func() { + defer close(holderDone) + rows, queryErr := tx.QueryContext(ctx, `SELECT id FROM accounts WHERE id = $1 FOR NO KEY UPDATE`, account.ID) + if queryErr != nil { + holderErr = queryErr + return + } + if !rows.Next() { + holderErr = rows.Err() + if holderErr == nil { + holderErr = errors.New("catalog account row was not locked") + } + _ = rows.Close() + return + } + var id int64 + if scanErr := rows.Scan(&id); scanErr != nil { + holderErr = scanErr + _ = rows.Close() + return + } + if closeErr := rows.Close(); closeErr != nil { + holderErr = closeErr + return + } + close(locked) + select { + case <-release: + case <-ctx.Done(): + holderErr = ctx.Err() + return + } + _, execErr := tx.ExecContext(ctx, ` + UPDATE accounts + SET extra = jsonb_set( + jsonb_set(COALESCE(extra, '{}'::jsonb), '{grok_observed_models}', $2::jsonb, true), + '{upstream_model_metadata}', $3::jsonb, true) + WHERE id = $1`, account.ID, freshModels, freshMetadata) + if execErr != nil { + holderErr = execErr + return + } + holderErr = tx.Commit() + }() + + select { + case <-locked: + case <-holderDone: + t.Fatalf("catalog lock holder finished early: %v", holderErr) + case <-ctx.Done(): + t.Fatal("timed out waiting for the catalog row lock") + } + + updateDone := make(chan error, 1) + go func() { + repo := newAccountRepositoryWithSQL(integrationEntClient, integrationDB, nil) + account.Name = "saved-during-cas" + account.Extra = map[string]any{ + "unrelated": "keep", + "note": "from-form", + "grok_observed_models": map[string]any{ + "models": []any{"old-model"}, "fetched_at": "2026-10-24T12:00:00Z", + }, + service.UpstreamModelMetadataExtraKey: map[string]any{ + "models": map[string]any{"old-model": map[string]any{"id": "old-model"}}, + }, + } + updateDone <- repo.Update(ctx, account) + }() + close(release) + + select { + case err = <-updateDone: + require.NoError(t, err) + case <-ctx.Done(): + t.Fatal("timed out waiting for the overlapping account update") + } + <-holderDone + require.NoError(t, holderErr) + + got := readGrokManagedExtra(t, integrationDB, account.ID) + require.Equal(t, "saved-during-cas", got.name) + require.Equal(t, "from-form", got.note) + require.Equal(t, "keep", got.unrelated) + require.Equal(t, []any{"fresh-model"}, got.models["models"]) + require.Equal(t, "2026-10-25T12:00:00Z", got.models["fetched_at"]) + attempt, ok := got.models["last_attempt"].(map[string]any) + require.True(t, ok) + require.Equal(t, "failed", attempt["status"]) + require.Equal(t, "transport", attempt["error_code"]) + require.Equal(t, map[string]any{ + "models": map[string]any{"fresh-model": map[string]any{"id": "fresh-model"}}, + }, got.metadata) +} + +type grokManagedExtraRow struct { + name string + note string + unrelated string + baseURL string + models map[string]any + metadata map[string]any +} + +func readGrokManagedExtra(t *testing.T, q grokCatalogSQL, id int64) grokManagedExtraRow { + t.Helper() + rows, err := q.QueryContext(context.Background(), ` + SELECT name, + COALESCE(extra->>'note', ''), + COALESCE(extra->>'unrelated', ''), + COALESCE(credentials->>'base_url', ''), + COALESCE((extra->'grok_observed_models')::text, 'null'), + COALESCE((extra->'upstream_model_metadata')::text, 'null') + FROM accounts + WHERE id = $1`, id) + require.NoError(t, err) + defer func() { _ = rows.Close() }() + require.True(t, rows.Next()) + var row grokManagedExtraRow + var modelsRaw, metadataRaw string + require.NoError(t, rows.Scan(&row.name, &row.note, &row.unrelated, &row.baseURL, &modelsRaw, &metadataRaw)) + require.NoError(t, rows.Err()) + if modelsRaw != "null" { + require.NoError(t, json.Unmarshal([]byte(modelsRaw), &row.models)) + } + if metadataRaw != "null" { + require.NoError(t, json.Unmarshal([]byte(metadataRaw), &row.metadata)) + } + return row +} diff --git a/backend/internal/repository/account_repo_grok_managed_extra_test.go b/backend/internal/repository/account_repo_grok_managed_extra_test.go new file mode 100644 index 0000000000..ff224d210b --- /dev/null +++ b/backend/internal/repository/account_repo_grok_managed_extra_test.go @@ -0,0 +1,171 @@ +package repository + +import ( + "context" + "encoding/json" + "regexp" + "testing" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + "github.com/DATA-DOG/go-sqlmock" + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestLockAndMergeAccountProbeExtraKeepsLatestGrokManagedKeys(t *testing.T) { + freshModels := []byte(`{"fetched_at":"2026-10-25T12:00:00Z","models":["fresh-model"]}`) + freshMetadata := []byte(`{"models":{"fresh-model":{"id":"fresh-model"}}}`) + failedModels := []byte(`{"fetched_at":"2026-10-25T12:00:00Z","last_attempt":{"error_code":"transport","finished_at":"2026-10-25T13:00:01Z","started_at":"2026-10-25T13:00:00Z","status":"failed"},"models":["fresh-model"]}`) + + tests := []struct { + name string + accountType string + credentials map[string]any + inputExtra map[string]any + databaseModels []byte + databaseMetadata []byte + wantModels map[string]any + wantMetadata map[string]any + }{ + { + name: "old client snapshot and metadata lose to the locked row", + accountType: service.AccountTypeOAuth, + credentials: map[string]any{"access_token": "token-keep"}, + inputExtra: map[string]any{ + "note": "from-form", + "grok_observed_models": map[string]any{ + "models": []any{"old-model"}, "fetched_at": "2026-10-24T12:00:00Z", + }, + service.UpstreamModelMetadataExtraKey: map[string]any{ + "models": map[string]any{"old-model": map[string]any{"id": "old-model"}}, + }, + }, + databaseModels: freshModels, + databaseMetadata: freshMetadata, + wantModels: map[string]any{ + "fetched_at": "2026-10-25T12:00:00Z", + "models": []any{"fresh-model"}, + }, + wantMetadata: map[string]any{ + "models": map[string]any{"fresh-model": map[string]any{"id": "fresh-model"}}, + }, + }, + { + name: "apikey payload that omits the keys still restores them", + accountType: service.AccountTypeAPIKey, + credentials: map[string]any{"api_key": "sk-keep"}, + inputExtra: map[string]any{"note": "from-form"}, + databaseModels: freshModels, + databaseMetadata: freshMetadata, + wantModels: map[string]any{ + "fetched_at": "2026-10-25T12:00:00Z", + "models": []any{"fresh-model"}, + }, + wantMetadata: map[string]any{ + "models": map[string]any{"fresh-model": map[string]any{"id": "fresh-model"}}, + }, + }, + { + name: "injection does not create keys missing from the locked row", + accountType: service.AccountTypeOAuth, + credentials: map[string]any{"access_token": "token-keep"}, + inputExtra: map[string]any{ + "note": "from-form", + "grok_observed_models": map[string]any{ + "models": []any{"injected"}, "fetched_at": "2026-10-25T12:00:00Z", + }, + service.UpstreamModelMetadataExtraKey: map[string]any{"models": map[string]any{}}, + }, + }, + { + name: "failed attempt is kept when the client sends an older success", + accountType: service.AccountTypeAPIKey, + credentials: map[string]any{"api_key": "sk-keep"}, + inputExtra: map[string]any{ + "note": "from-form", + "grok_observed_models": map[string]any{ + "models": []any{"old-model"}, "fetched_at": "2026-10-24T12:00:00Z", + }, + }, + databaseModels: failedModels, + databaseMetadata: freshMetadata, + wantModels: map[string]any{ + "fetched_at": "2026-10-25T12:00:00Z", + "models": []any{"fresh-model"}, + "last_attempt": map[string]any{ + "error_code": "transport", + "finished_at": "2026-10-25T13:00:01Z", + "started_at": "2026-10-25T13:00:00Z", + "status": "failed", + }, + }, + wantMetadata: map[string]any{ + "models": map[string]any{"fresh-model": map[string]any{"id": "fresh-model"}}, + }, + }, + { + name: "credential identity change still keeps the locked success", + accountType: service.AccountTypeOAuth, + credentials: map[string]any{"access_token": "token-new", "base_url": "https://new.example.test/v1"}, + inputExtra: map[string]any{ + "note": "from-form", + "grok_observed_models": nil, + }, + databaseModels: freshModels, + databaseMetadata: freshMetadata, + wantModels: map[string]any{ + "fetched_at": "2026-10-25T12:00:00Z", + "models": []any{"fresh-model"}, + }, + wantMetadata: map[string]any{ + "models": map[string]any{"fresh-model": map[string]any{"id": "fresh-model"}}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + t.Cleanup(func() { _ = client.Close() }) + + credentials, err := json.Marshal(normalizeJSONMap(tt.credentials)) + require.NoError(t, err) + mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")). + WithArgs(int64(41), service.PlatformGrok, tt.accountType, string(credentials), nil). + WillReturnRows(sqlmock.NewRows([]string{ + "identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", + "enabled", "rate_sync_enabled", "snapshot", + "ollama_session", "ollama_auto", "ollama_snapshot", + "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", + "grok_observed_models", "upstream_model_metadata", + }).AddRow(false, false, true, nil, nil, nil, nil, nil, nil, false, nil, nil, tt.databaseModels, tt.databaseMetadata)) + + account := &service.Account{ + ID: 41, + Platform: service.PlatformGrok, + Type: tt.accountType, + Credentials: tt.credentials, + Extra: tt.inputExtra, + } + got, err := lockAndMergeAccountProbeExtra(context.Background(), client, account, nil, nil) + require.NoError(t, err) + require.Equal(t, "from-form", got["note"]) + if tt.wantModels == nil { + require.NotContains(t, got, "grok_observed_models") + } else { + require.Equal(t, tt.wantModels, got["grok_observed_models"]) + } + if tt.wantMetadata == nil { + require.NotContains(t, got, service.UpstreamModelMetadataExtraKey) + } else { + require.Equal(t, tt.wantMetadata, got[service.UpstreamModelMetadataExtraKey]) + } + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} diff --git a/backend/internal/repository/account_repo_grok_models.go b/backend/internal/repository/account_repo_grok_models.go new file mode 100644 index 0000000000..29b1b26dea --- /dev/null +++ b/backend/internal/repository/account_repo_grok_models.go @@ -0,0 +1,61 @@ +package repository + +import ( + "bytes" + "context" + "encoding/json" + "errors" + + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/service" +) + +var errGrokCatalogInvalidJSON = errors.New("grok model catalog: invalid json") + +var _ service.GrokCatalogSnapshotRepository = (*accountRepository)(nil) + +const compareAndSwapGrokObservedModelsSQL = `UPDATE accounts +SET extra = jsonb_set(COALESCE(extra, '{}'::jsonb), '{grok_observed_models}', $3::jsonb, true), + updated_at = NOW() +WHERE id = $1 AND deleted_at IS NULL AND platform = 'grok' + AND COALESCE(extra -> 'grok_observed_models', 'null'::jsonb) = $2::jsonb` + +func (r *accountRepository) CompareAndSwapGrokObservedModels(ctx context.Context, id int64, expected, next json.RawMessage) (bool, error) { + if scoped := r.accountTransactionScope(ctx); scoped != r { + return scoped.CompareAndSwapGrokObservedModels(ctx, id, expected, next) + } + expectedArg, err := grokCatalogJSONArg(expected) + if err != nil { + return false, err + } + nextArg, err := grokCatalogJSONArg(next) + if err != nil { + return false, err + } + result, err := clientFromContext(ctx, r.client).ExecContext(ctx, compareAndSwapGrokObservedModelsSQL, id, expectedArg, nextArg) + if err != nil { + return false, err + } + affected, err := result.RowsAffected() + if err != nil { + return false, err + } + if affected == 0 { + return false, nil + } + if dbent.TxFromContext(ctx) == nil { + r.syncSchedulerAccountSnapshot(ctx, id) + } + return true, nil +} + +func grokCatalogJSONArg(raw json.RawMessage) (string, error) { + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 { + return "null", nil + } + if !json.Valid(trimmed) { + return "", errGrokCatalogInvalidJSON + } + return string(trimmed), nil +} diff --git a/backend/internal/repository/account_repo_grok_models_integration_test.go b/backend/internal/repository/account_repo_grok_models_integration_test.go new file mode 100644 index 0000000000..514646fe74 --- /dev/null +++ b/backend/internal/repository/account_repo_grok_models_integration_test.go @@ -0,0 +1,374 @@ +//go:build integration + +package repository + +import ( + "context" + "database/sql" + "encoding/json" + "sync" + "testing" + "time" + + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestGrokCatalogCASPreservesSingleKeyAndRejectsStaleExpected(t *testing.T) { + ctx := context.Background() + tx := testEntTx(t) + cache := &schedulerCacheRecorder{} + repo := newAccountRepositoryWithSQL(tx.Client(), tx, cache) + account := mustCreateGrokCatalogAccount(t, tx.Client(), "grok-cas-stale") + before := readGrokCatalogRow(t, tx, account.ID) + + nextJSON := json.RawMessage(`{"fetched_at":"2026-10-25T02:00:01Z","models":["grok-4.7"]}`) + applied, err := repo.CompareAndSwapGrokObservedModels(ctx, account.ID, nil, nextJSON) + require.NoError(t, err) + require.True(t, applied) + require.Len(t, cache.setAccounts, 1) + require.Equal(t, "keep", cache.setAccounts[0].Extra["unrelated"]) + + applied, err = repo.CompareAndSwapGrokObservedModels(ctx, account.ID, nil, json.RawMessage(`{"models":["stale"]}`)) + require.NoError(t, err) + require.False(t, applied) + + after := readGrokCatalogRow(t, tx, account.ID) + require.Equal(t, "keep", after.unrelated) + require.Equal(t, []string{"grok-4.7"}, after.models) + require.Equal(t, "2026-10-25T02:00:01Z", after.fetchedAt) + require.Equal(t, before.token, after.token) + require.Equal(t, before.status, after.status) + require.Equal(t, before.rateMultiplier, after.rateMultiplier) + require.Equal(t, 0, grokCatalogOutboxCount(t, tx, account.ID)) + + inTxCache := &schedulerCacheRecorder{} + inTxRepo := newAccountRepositoryWithSQL(integrationEntClient, integrationDB, inTxCache) + replacement := json.RawMessage(`{"fetched_at":"2026-10-25T03:00:01Z","models":["grok-4.6"]}`) + applied, err = inTxRepo.CompareAndSwapGrokObservedModels(dbent.NewTxContext(ctx, tx), account.ID, after.rawModels, replacement) + require.NoError(t, err) + require.True(t, applied, "context transaction must see the uncommitted row") + require.Empty(t, inTxCache.setAccounts) + replaced := readGrokCatalogRow(t, tx, account.ID) + require.Equal(t, []string{"grok-4.6"}, replaced.models) + require.Equal(t, "keep", replaced.unrelated) + require.Equal(t, before.token, replaced.token) + require.Equal(t, before.rateMultiplier, replaced.rateMultiplier) + require.Equal(t, 0, grokCatalogOutboxCount(t, tx, account.ID)) +} + +func TestGrokCatalogCASTreatsNullMissingAndKeyOrderAsSameValue(t *testing.T) { + ctx := context.Background() + + t.Run("missing key", func(t *testing.T) { + tx := testEntTx(t) + repo := newAccountRepositoryWithSQL(tx.Client(), tx, nil) + account := mustCreateGrokCatalogAccount(t, tx.Client(), "grok-cas-missing") + applied, err := repo.CompareAndSwapGrokObservedModels(ctx, account.ID, json.RawMessage("null"), json.RawMessage(`{"models":["grok-4.5"],"fetched_at":"2026-10-25T02:00:01Z"}`)) + require.NoError(t, err) + require.True(t, applied) + row := readGrokCatalogRow(t, tx, account.ID) + require.Equal(t, []string{"grok-4.5"}, row.models) + require.Equal(t, "keep", row.unrelated) + }) + + t.Run("json null", func(t *testing.T) { + tx := testEntTx(t) + repo := newAccountRepositoryWithSQL(tx.Client(), tx, nil) + account := mustCreateGrokCatalogAccount(t, tx.Client(), "grok-cas-json-null") + _, err := tx.ExecContext(ctx, `UPDATE accounts SET extra = jsonb_set(extra, '{grok_observed_models}', 'null'::jsonb, true) WHERE id = $1`, account.ID) + require.NoError(t, err) + applied, err := repo.CompareAndSwapGrokObservedModels(ctx, account.ID, nil, json.RawMessage(`{"models":["from-json-null"]}`)) + require.NoError(t, err) + require.True(t, applied) + row := readGrokCatalogRow(t, tx, account.ID) + require.Equal(t, []string{"from-json-null"}, row.models) + require.Equal(t, "keep", row.unrelated) + }) + + t.Run("sql null", func(t *testing.T) { + tx := testEntTx(t) + repo := newAccountRepositoryWithSQL(tx.Client(), tx, nil) + account := mustCreateGrokCatalogAccount(t, tx.Client(), "grok-cas-sql-null") + // The column is NOT NULL today. Drop it only inside this rolled-back + // transaction so the COALESCE(extra, '{}') branch is actually executed. + _, err := tx.ExecContext(ctx, `ALTER TABLE accounts ALTER COLUMN extra DROP NOT NULL`) + require.NoError(t, err) + _, err = tx.ExecContext(ctx, `UPDATE accounts SET extra = NULL WHERE id = $1`, account.ID) + require.NoError(t, err) + applied, err := repo.CompareAndSwapGrokObservedModels(ctx, account.ID, json.RawMessage(" \t"), json.RawMessage(`{"models":["from-sql-null"]}`)) + require.NoError(t, err) + require.True(t, applied) + row := readGrokCatalogRow(t, tx, account.ID) + require.Equal(t, []string{"from-sql-null"}, row.models) + require.Empty(t, row.unrelated) + }) + + t.Run("key order is not a conflict", func(t *testing.T) { + tx := testEntTx(t) + repo := newAccountRepositoryWithSQL(tx.Client(), tx, nil) + account := mustCreateGrokCatalogAccount(t, tx.Client(), "grok-cas-order") + original := json.RawMessage(`{"z_source":"upstream_v1_models","models":["grok-4.5"],"fetched_at":"2026-10-25T02:00:01Z"}`) + applied, err := repo.CompareAndSwapGrokObservedModels(ctx, account.ID, nil, original) + require.NoError(t, err) + require.True(t, applied) + + reordered := json.RawMessage(`{"fetched_at":"2026-10-25T02:00:01Z","models":["grok-4.5"],"z_source":"upstream_v1_models"}`) + applied, err = repo.CompareAndSwapGrokObservedModels(ctx, account.ID, reordered, json.RawMessage(`{"models":["grok-4.7"],"fetched_at":"2026-10-25T03:00:01Z"}`)) + require.NoError(t, err) + require.True(t, applied) + row := readGrokCatalogRow(t, tx, account.ID) + require.Equal(t, []string{"grok-4.7"}, row.models) + require.Equal(t, "keep", row.unrelated) + require.NotContains(t, string(row.rawModels), "z_source") + }) +} + +func TestGrokCatalogCASDoesNotUpdateSoftDeletedOrOtherPlatform(t *testing.T) { + ctx := context.Background() + tx := testEntTx(t) + repo := newAccountRepositoryWithSQL(tx.Client(), tx, nil) + nextJSON := json.RawMessage(`{"models":["should-not-land"]}`) + + deleted := mustCreateGrokCatalogAccount(t, tx.Client(), "grok-cas-deleted") + _, err := tx.ExecContext(ctx, `UPDATE accounts SET deleted_at = NOW() WHERE id = $1`, deleted.ID) + require.NoError(t, err) + applied, err := repo.CompareAndSwapGrokObservedModels(ctx, deleted.ID, nil, nextJSON) + require.NoError(t, err) + require.False(t, applied) + row := readGrokCatalogRow(t, tx, deleted.ID) + require.Empty(t, row.models) + require.Equal(t, "keep", row.unrelated) + require.True(t, row.deleted) + + other := mustCreateAccount(t, tx.Client(), &service.Account{ + Name: "grok-cas-openai", + Platform: service.PlatformOpenAI, + Type: service.AccountTypeOAuth, + Extra: map[string]any{"unrelated": "keep"}, + Credentials: map[string]any{"access_token": "token-keep"}, + }) + applied, err = repo.CompareAndSwapGrokObservedModels(ctx, other.ID, nil, nextJSON) + require.NoError(t, err) + require.False(t, applied) + row = readGrokCatalogRow(t, tx, other.ID) + require.Empty(t, row.models) + require.Equal(t, "keep", row.unrelated) + require.Equal(t, "token-keep", row.token) +} + +func TestGrokCatalogCASConcurrentIndependentTransactionsMergeSuccess(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + account := mustCreateGrokCatalogAccount(t, testEntClient(t), "grok-cas-concurrent") + t.Cleanup(func() { + cleanupCtx := context.Background() + _, _ = integrationDB.ExecContext(cleanupCtx, "DELETE FROM scheduler_outbox WHERE account_id = $1", account.ID) + _, _ = integrationDB.ExecContext(cleanupCtx, "DELETE FROM accounts WHERE id = $1", account.ID) + }) + + tx1, err := integrationEntClient.Tx(ctx) + require.NoError(t, err) + tx2, err := integrationEntClient.Tx(ctx) + require.NoError(t, err) + t.Cleanup(func() { + _ = tx1.Rollback() + _ = tx2.Rollback() + }) + pid1 := grokCatalogBackendPID(t, tx1) + pid2 := grokCatalogBackendPID(t, tx2) + require.NotEqual(t, pid1, pid2) + + scope, err := service.NewGrokCatalogScope(account.ID, service.AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models") + require.NoError(t, err) + success := service.GrokCatalogObservation{ + Models: []string{"from-success"}, + Attempt: service.GrokCatalogAttempt{ + StartedAt: "2026-10-25T02:00:00Z", + FinishedAt: "2026-10-25T02:00:01Z", + Status: "success", + Scope: scope, + }, + } + failure := service.GrokCatalogObservation{Attempt: service.GrokCatalogAttempt{ + StartedAt: "2026-10-25T04:00:00Z", + FinishedAt: "2026-10-25T04:00:01Z", + Status: "failed", + ErrorCode: "transport", + Scope: scope, + }} + + entered := make(chan struct{}, 2) + release := make(chan struct{}) + first := make(chan bool, 2) + repo1 := &grokCatalogGatingRepo{AccountRepository: newAccountRepositoryWithSQL(tx1.Client(), tx1, nil), entered: entered, release: release, first: first} + repo2 := &grokCatalogGatingRepo{AccountRepository: newAccountRepositoryWithSQL(tx2.Client(), tx2, nil), entered: entered, release: release, first: first} + + var wg sync.WaitGroup + errCh := make(chan error, 2) + wg.Add(2) + run := func(tx *dbent.Tx, repo service.AccountRepository, observation service.GrokCatalogObservation) { + defer wg.Done() + _, persistErr := service.PersistGrokCatalogObservation(ctx, repo, account.ID, observation) + if persistErr != nil { + _ = tx.Rollback() + errCh <- persistErr + return + } + errCh <- tx.Commit() + } + go run(tx1, repo1, success) + go run(tx2, repo2, failure) + for i := 0; i < 2; i++ { + select { + case <-entered: + case <-ctx.Done(): + t.Fatal("timed out waiting for both catalog CAS attempts") + } + } + close(release) + wg.Wait() + close(errCh) + for err := range errCh { + require.NoError(t, err) + } + var applied, rejected int + close(first) + for value := range first { + if value { + applied++ + } else { + rejected++ + } + } + require.Equal(t, 1, applied) + require.Equal(t, 1, rejected) + + row := readGrokCatalogRow(t, integrationDB, account.ID) + require.Equal(t, []string{"from-success"}, row.models) + require.Equal(t, "2026-10-25T02:00:01Z", row.fetchedAt) + require.Equal(t, "failed", row.lastStatus) + require.Equal(t, "2026-10-25T04:00:00Z", row.lastStarted) + require.Equal(t, "keep", row.unrelated) + require.Equal(t, "token-keep", row.token) + require.False(t, row.deleted) + require.Equal(t, 0, grokCatalogOutboxCount(t, integrationDB, account.ID)) +} + +type grokCatalogSQL interface { + QueryContext(context.Context, string, ...any) (*sql.Rows, error) + ExecContext(context.Context, string, ...any) (sql.Result, error) +} + +type grokCatalogRow struct { + unrelated string + rawModels json.RawMessage + models []string + fetchedAt string + lastStatus string + lastStarted string + token string + status string + rateMultiplier string + deleted bool +} + +func readGrokCatalogRow(t *testing.T, q grokCatalogSQL, id int64) grokCatalogRow { + t.Helper() + rows, err := q.QueryContext(context.Background(), ` + SELECT COALESCE(extra->>'unrelated', ''), + COALESCE((extra->'grok_observed_models')::text, 'null'), + COALESCE(credentials->>'access_token', ''), + status, + rate_multiplier::text, + deleted_at IS NOT NULL + FROM accounts + WHERE id = $1`, id) + require.NoError(t, err) + defer func() { _ = rows.Close() }() + require.True(t, rows.Next()) + var row grokCatalogRow + var raw string + require.NoError(t, rows.Scan(&row.unrelated, &raw, &row.token, &row.status, &row.rateMultiplier, &row.deleted)) + require.NoError(t, rows.Err()) + row.rawModels = json.RawMessage(raw) + if raw != "null" { + var payload struct { + Models []string `json:"models"` + FetchedAt string `json:"fetched_at"` + Last *struct { + Status string `json:"status"` + StartedAt string `json:"started_at"` + } `json:"last_attempt"` + } + require.NoError(t, json.Unmarshal(row.rawModels, &payload)) + row.models = payload.Models + row.fetchedAt = payload.FetchedAt + if payload.Last != nil { + row.lastStatus = payload.Last.Status + row.lastStarted = payload.Last.StartedAt + } + } + return row +} + +func grokCatalogOutboxCount(t *testing.T, q grokCatalogSQL, id int64) int { + t.Helper() + rows, err := q.QueryContext(context.Background(), `SELECT COUNT(*) FROM scheduler_outbox WHERE account_id = $1`, id) + require.NoError(t, err) + defer func() { _ = rows.Close() }() + require.True(t, rows.Next()) + var count int + require.NoError(t, rows.Scan(&count)) + require.NoError(t, rows.Err()) + return count +} + +func grokCatalogBackendPID(t *testing.T, q grokCatalogSQL) int { + t.Helper() + rows, err := q.QueryContext(context.Background(), `SELECT pg_backend_pid()`) + require.NoError(t, err) + defer func() { _ = rows.Close() }() + require.True(t, rows.Next()) + var pid int + require.NoError(t, rows.Scan(&pid)) + require.NoError(t, rows.Err()) + return pid +} + +func mustCreateGrokCatalogAccount(t *testing.T, client *dbent.Client, name string) *service.Account { + t.Helper() + return mustCreateAccount(t, client, &service.Account{ + Name: name, + Platform: service.PlatformGrok, + Type: service.AccountTypeOAuth, + Extra: map[string]any{"unrelated": "keep"}, + Credentials: map[string]any{"access_token": "token-keep"}, + }) +} + +type grokCatalogGatingRepo struct { + service.AccountRepository + entered chan struct{} + release <-chan struct{} + first chan bool + calls int +} + +func (g *grokCatalogGatingRepo) CompareAndSwapGrokObservedModels(ctx context.Context, id int64, expected, next json.RawMessage) (bool, error) { + g.calls++ + if g.calls == 1 { + g.entered <- struct{}{} + select { + case <-g.release: + case <-ctx.Done(): + return false, ctx.Err() + } + } + applied, err := g.AccountRepository.(service.GrokCatalogSnapshotRepository).CompareAndSwapGrokObservedModels(ctx, id, expected, next) + if g.calls == 1 && err == nil { + g.first <- applied + } + return applied, err +} diff --git a/backend/internal/repository/account_repo_grok_models_test.go b/backend/internal/repository/account_repo_grok_models_test.go new file mode 100644 index 0000000000..d81dfb61f8 --- /dev/null +++ b/backend/internal/repository/account_repo_grok_models_test.go @@ -0,0 +1,334 @@ +//go:build unit + +package repository + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "regexp" + "testing" + "time" + + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + "github.com/DATA-DOG/go-sqlmock" +) + +const grokCatalogCASQuery = `UPDATE accounts +SET extra = jsonb_set(COALESCE(extra, '{}'::jsonb), '{grok_observed_models}', $3::jsonb, true), + updated_at = NOW() +WHERE id = $1 AND deleted_at IS NULL AND platform = 'grok' + AND COALESCE(extra -> 'grok_observed_models', 'null'::jsonb) = $2::jsonb` + +func TestGrokCatalogCASWritesSingleKeyAndReportsRows(t *testing.T) { + t.Parallel() + + nextJSON := jsonRaw(`{"fetched_at":"2026-10-25T02:00:01Z","models":["grok-4.7"]}`) + cases := []struct { + name string + affected int64 + execErr error + resultErr error + want bool + wantErr string + }{ + {name: "applied", affected: 1, want: true}, + {name: "conflict", affected: 0, want: false}, + {name: "db error", execErr: errors.New("db down"), wantErr: "db down"}, + {name: "rows affected error", affected: 1, resultErr: errors.New("rows failed"), wantErr: "rows failed"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + var queries []string + repo, mock := newGrokCatalogCASRepo(t, &queries) + expectation := mock.ExpectExec(regexp.QuoteMeta(grokCatalogCASQuery)). + WithArgs(int64(25), "null", string(nextJSON)) + if tc.execErr != nil { + expectation.WillReturnError(tc.execErr) + } else if tc.resultErr != nil { + expectation.WillReturnResult(sqlmock.NewErrorResult(tc.resultErr)) + } else { + expectation.WillReturnResult(sqlmock.NewResult(0, tc.affected)) + } + + applied, err := repo.CompareAndSwapGrokObservedModels(context.Background(), 25, nil, nextJSON) + + if tc.wantErr != "" { + require.EqualError(t, err, tc.wantErr) + require.False(t, applied) + } else { + require.NoError(t, err) + require.Equal(t, tc.want, applied) + } + require.NoError(t, mock.ExpectationsWereMet()) + require.Len(t, queries, 1) + require.NotContains(t, queries[0], "credentials") + require.NotContains(t, queries[0], "rate_multiplier") + require.NotContains(t, queries[0], "status") + require.NotContains(t, queries[0], "scheduler_outbox") + require.NotContains(t, queries[0], "grok-4.7") + require.NotContains(t, queries[0], "unrelated") + }) + } +} + +func TestGrokCatalogCASNormalizesEmptyJSONAndRejectsInvalidJSON(t *testing.T) { + t.Parallel() + + t.Run("empty values are null", func(t *testing.T) { + t.Parallel() + repo, mock := newGrokCatalogCASRepo(t, nil) + mock.ExpectExec(regexp.QuoteMeta(grokCatalogCASQuery)). + WithArgs(int64(25), "null", "null"). + WillReturnResult(sqlmock.NewResult(0, 1)) + + applied, err := repo.CompareAndSwapGrokObservedModels(context.Background(), 25, jsonRaw(" \n\t"), nil) + + require.NoError(t, err) + require.True(t, applied) + require.NoError(t, mock.ExpectationsWereMet()) + }) + + t.Run("invalid json does not execute", func(t *testing.T) { + t.Parallel() + repo, mock := newGrokCatalogCASRepo(t, nil) + + applied, err := repo.CompareAndSwapGrokObservedModels(context.Background(), 25, jsonRaw("{"), jsonRaw(`{"models":["grok-4.7"]}`)) + + require.ErrorIs(t, err, errGrokCatalogInvalidJSON) + require.False(t, applied) + require.NoError(t, mock.ExpectationsWereMet()) + }) + + t.Run("existing json keeps its bytes", func(t *testing.T) { + t.Parallel() + expected := jsonRaw(`{"models":["grok-4.5"],"fetched_at":"2026-10-25T02:00:01Z"}`) + nextJSON := jsonRaw(`{"fetched_at":"2026-10-25T03:00:01Z","models":["grok-4.7"]}`) + repo, mock := newGrokCatalogCASRepo(t, nil) + mock.ExpectExec(regexp.QuoteMeta(grokCatalogCASQuery)). + WithArgs(int64(25), string(expected), string(nextJSON)). + WillReturnResult(sqlmock.NewResult(0, 0)) + + applied, err := repo.CompareAndSwapGrokObservedModels(context.Background(), 25, expected, nextJSON) + + require.NoError(t, err) + require.False(t, applied) + require.NoError(t, mock.ExpectationsWereMet()) + }) +} + +func TestGrokCatalogCASUsesTransactionClientAndSkipsCache(t *testing.T) { + t.Parallel() + + nextJSON := jsonRaw(`{"models":["grok-4.7"]}`) + db, mock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + t.Cleanup(func() { _ = client.Close() }) + mock.ExpectBegin() + tx, err := client.Tx(context.Background()) + require.NoError(t, err) + exec := &recordingSQLExecutor{err: errors.New("must use transaction client")} + cache := &grokCatalogCacheSpy{} + repo := newAccountRepositoryWithSQL(client, exec, cache) + mock.ExpectExec(regexp.QuoteMeta(grokCatalogCASQuery)). + WithArgs(int64(25), "null", string(nextJSON)). + WillReturnResult(sqlmock.NewResult(0, 1)) + + applied, err := repo.CompareAndSwapGrokObservedModels(dbent.NewTxContext(context.Background(), tx), 25, nil, nextJSON) + + require.NoError(t, err) + require.True(t, applied) + require.Empty(t, exec.execQueries) + require.Zero(t, cache.setAccounts) + require.Zero(t, cache.bucketOps) + mock.ExpectRollback() + require.NoError(t, tx.Rollback()) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestGrokCatalogCASAppliesOnCallerTransactionNotBaseClient(t *testing.T) { + t.Parallel() + + nextJSON := jsonRaw(`{"models":["grok-4.7"]}`) + baseDB, baseMock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { _ = baseDB.Close() }) + baseClient := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, baseDB))) + t.Cleanup(func() { _ = baseClient.Close() }) + + txDB, txMock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { _ = txDB.Close() }) + txClient := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, txDB))) + t.Cleanup(func() { _ = txClient.Close() }) + txMock.ExpectBegin() + tx, err := txClient.Tx(context.Background()) + require.NoError(t, err) + txMock.ExpectExec(regexp.QuoteMeta(grokCatalogCASQuery)). + WithArgs(int64(25), "null", string(nextJSON)). + WillReturnResult(sqlmock.NewResult(0, 1)) + + exec := &recordingSQLExecutor{err: errors.New("must use transaction client")} + cache := &grokCatalogCacheSpy{} + repo := newAccountRepositoryWithSQL(baseClient, exec, cache) + + applied, err := repo.CompareAndSwapGrokObservedModels(dbent.NewTxContext(context.Background(), tx), 25, nil, nextJSON) + + require.NoError(t, err) + require.True(t, applied) + require.Empty(t, exec.execQueries) + require.Zero(t, cache.setAccounts) + require.Zero(t, cache.bucketOps) + require.NoError(t, baseMock.ExpectationsWereMet()) + txMock.ExpectRollback() + require.NoError(t, tx.Rollback()) + require.NoError(t, txMock.ExpectationsWereMet()) +} + +func TestGrokCatalogCASRefreshesSingleAccountOutsideTransaction(t *testing.T) { + t.Parallel() + + nextJSON := jsonRaw(`{"models":["grok-4.7"],"fetched_at":"2026-10-25T02:00:01Z"}`) + db, mock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + t.Cleanup(func() { _ = client.Close() }) + cache := &grokCatalogCacheSpy{} + repo := newAccountRepositoryWithSQL(client, db, cache) + mock.ExpectExec(regexp.QuoteMeta(grokCatalogCASQuery)). + WithArgs(int64(25), "null", string(nextJSON)). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectQuery(`(?s)SELECT .* FROM "accounts" WHERE .*`). + WithArgs(int64(25)). + WillReturnRows(updatedAccountRows(25, `{"unrelated":"keep","grok_observed_models":{"models":["grok-4.7"],"fetched_at":"2026-10-25T02:00:01Z"}}`)) + mock.ExpectQuery(`(?s)account_groups`). + WillReturnRows(sqlmock.NewRows([]string{"account_id", "group_id", "priority", "created_at"})) + + applied, err := repo.CompareAndSwapGrokObservedModels(context.Background(), 25, nil, nextJSON) + + require.NoError(t, err) + require.True(t, applied) + require.Equal(t, 1, cache.setAccounts) + require.Zero(t, cache.bucketOps) + require.NotNil(t, cache.lastAccount) + require.Equal(t, "keep", cache.lastAccount.Extra["unrelated"]) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func newGrokCatalogCASRepo(t *testing.T, queries *[]string) (*accountRepository, sqlmock.Sqlmock) { + t.Helper() + var ( + db *sql.DB + mock sqlmock.Sqlmock + err error + ) + if queries == nil { + db, mock, err = sqlmock.New() + } else { + db, mock, err = sqlmock.New(sqlmock.QueryMatcherOption(grokCatalogQueryCapture{queries: queries})) + } + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + t.Cleanup(func() { _ = client.Close() }) + return newAccountRepositoryWithSQL(client, db, nil), mock +} + +type grokCatalogQueryCapture struct { + queries *[]string +} + +func (m grokCatalogQueryCapture) Match(expectedSQL, actualSQL string) error { + if m.queries != nil { + *m.queries = append(*m.queries, actualSQL) + } + return sqlmock.QueryMatcherRegexp.Match(expectedSQL, actualSQL) +} + +type grokCatalogCacheSpy struct { + setAccounts int + bucketOps int + lastAccount *service.Account +} + +func (s *grokCatalogCacheSpy) GetSnapshot(context.Context, service.SchedulerBucket) ([]*service.Account, bool, error) { + return nil, false, nil +} + +func (s *grokCatalogCacheSpy) CaptureBucketWriteToken(context.Context, service.SchedulerBucket) (service.SchedulerBucketWriteToken, error) { + s.bucketOps++ + return service.SchedulerBucketWriteToken{}, nil +} + +func (s *grokCatalogCacheSpy) SetSnapshot(context.Context, service.SchedulerBucket, service.SchedulerBucketWriteToken, []service.Account) error { + s.bucketOps++ + return nil +} + +func (s *grokCatalogCacheSpy) RetireBucket(context.Context, service.SchedulerBucket) error { + s.bucketOps++ + return nil +} + +func (s *grokCatalogCacheSpy) ReopenBucket(context.Context, service.SchedulerBucket) (service.SchedulerBucketWriteToken, error) { + s.bucketOps++ + return service.SchedulerBucketWriteToken{}, nil +} + +func (s *grokCatalogCacheSpy) TryAcquireGroupLifecycleLease(context.Context, int64, time.Duration) (service.SchedulerGroupLifecycleLease, bool, error) { + s.bucketOps++ + return service.SchedulerGroupLifecycleLease{}, false, nil +} + +func (s *grokCatalogCacheSpy) ReleaseGroupLifecycleLease(context.Context, service.SchedulerGroupLifecycleLease) error { + s.bucketOps++ + return nil +} + +func (s *grokCatalogCacheSpy) GetAccount(context.Context, int64) (*service.Account, error) { + return nil, nil +} + +func (s *grokCatalogCacheSpy) SetAccount(_ context.Context, account *service.Account) error { + s.setAccounts++ + s.lastAccount = account + return nil +} + +func (s *grokCatalogCacheSpy) DeleteAccount(context.Context, int64) error { return nil } + +func (s *grokCatalogCacheSpy) UpdateLastUsed(context.Context, map[int64]time.Time) error { + return nil +} + +func (s *grokCatalogCacheSpy) TryLockBucket(context.Context, service.SchedulerBucket, time.Duration) (bool, error) { + s.bucketOps++ + return false, nil +} + +func (s *grokCatalogCacheSpy) UnlockBucket(context.Context, service.SchedulerBucket) error { + s.bucketOps++ + return nil +} + +func (s *grokCatalogCacheSpy) ListBuckets(context.Context) ([]service.SchedulerBucket, error) { + return nil, nil +} + +func (s *grokCatalogCacheSpy) GetOutboxWatermark(context.Context) (int64, error) { return 0, nil } + +func (s *grokCatalogCacheSpy) SetOutboxWatermark(context.Context, int64) error { return nil } + +func jsonRaw(s string) json.RawMessage { + return json.RawMessage(s) +} diff --git a/backend/internal/repository/account_repo_opencode_go_usage_test.go b/backend/internal/repository/account_repo_opencode_go_usage_test.go index 8a5add8ffd..43581ec231 100644 --- a/backend/internal/repository/account_repo_opencode_go_usage_test.go +++ b/backend/internal/repository/account_repo_opencode_go_usage_test.go @@ -76,6 +76,7 @@ func openCodeGoMergeMockColumns() []string { "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", + "grok_observed_models", "upstream_model_metadata", } } @@ -188,7 +189,7 @@ func TestLockAndMergeAccountProbeExtraPreservesOpenCodeGoManagedState(t *testing mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")). WithArgs(tt.account.ID, tt.account.Platform, tt.account.Type, string(credentials), nil). WillReturnRows(sqlmock.NewRows(openCodeGoMergeMockColumns()). - AddRow(false, false, tt.proxyUnchanged, nil, nil, nil, nil, nil, nil, tt.groupUnchanged, tt.databaseAuto, tt.databaseSnapshot)) + AddRow(false, false, tt.proxyUnchanged, nil, nil, nil, nil, nil, nil, tt.groupUnchanged, tt.databaseAuto, tt.databaseSnapshot, nil, nil)) got, err := lockAndMergeAccountProbeExtra(context.Background(), client, tt.account, nil, nil) require.NoError(t, err) diff --git a/backend/internal/repository/account_repo_upstream_billing_probe_update_test.go b/backend/internal/repository/account_repo_upstream_billing_probe_update_test.go index d3778ac00f..15bccacf79 100644 --- a/backend/internal/repository/account_repo_upstream_billing_probe_update_test.go +++ b/backend/internal/repository/account_repo_upstream_billing_probe_update_test.go @@ -81,8 +81,8 @@ func TestLockAndMergeAccountProbeExtraUsesCurrentDatabaseSnapshot(t *testing.T) mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")). WithArgs(int64(27), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil). - WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot"}). - AddRow(tt.identityUnchanged, false, true, tt.databaseEnabled, nil, tt.databaseSnapshot, nil, nil, nil, false, nil, nil)) + WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata"}). + AddRow(tt.identityUnchanged, false, true, tt.databaseEnabled, nil, tt.databaseSnapshot, nil, nil, nil, false, nil, nil, nil, nil)) account := &service.Account{ ID: 27, @@ -172,8 +172,8 @@ func TestLockAndMergeAccountProbeExtraNeverInfersProbeFromRateSync(t *testing.T) mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")). WithArgs(int64(31), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil). - WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot"}). - AddRow(true, false, true, tt.databaseEnabled, tt.databaseRateSync, nil, nil, nil, nil, false, nil, nil)) + WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata"}). + AddRow(true, false, true, tt.databaseEnabled, tt.databaseRateSync, nil, nil, nil, nil, false, nil, nil, nil, nil)) account := &service.Account{ ID: 31, @@ -211,8 +211,8 @@ func TestLockAndMergeAccountProbeExtraProtectsOllamaManagedFields(t *testing.T) mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")). WithArgs(int64(29), service.PlatformAnthropic, service.AccountTypeAPIKey, `{"api_key":"key","base_url":"https://ollama.com"}`, nil). - WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot"}). - AddRow(identityUnchanged, identityUnchanged, true, nil, nil, nil, []byte(`"local-ciphertext"`), []byte(`true`), []byte(`{"status":"ok"}`), false, nil, nil)) + WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata"}). + AddRow(identityUnchanged, identityUnchanged, true, nil, nil, nil, []byte(`"local-ciphertext"`), []byte(`true`), []byte(`{"status":"ok"}`), false, nil, nil, nil, nil)) account := &service.Account{ ID: 29, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, @@ -371,8 +371,8 @@ func TestUpdateWithAccountBillingSettingsRollsBackWhenOutboxFails(t *testing.T) mock.ExpectBegin() mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")). WithArgs(int64(27), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil). - WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot"}). - AddRow(true, false, true, []byte(`true`), []byte(`true`), []byte(`{"status":"ok"}`), nil, nil, nil, false, nil, nil)) + WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata"}). + AddRow(true, false, true, []byte(`true`), []byte(`true`), []byte(`{"status":"ok"}`), nil, nil, nil, false, nil, nil, nil, nil)) mock.ExpectExec(`(?s)UPDATE .*accounts.*SET.*WHERE .*id.*`). WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectQuery(`(?s)SELECT .* FROM "accounts" WHERE "id" = \$1`). diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go index b5545ee18e..0521f7a90b 100644 --- a/backend/internal/service/admin_account.go +++ b/backend/internal/service/admin_account.go @@ -687,6 +687,9 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U delete(normalizedExtra, OllamaCloudUsageSnapshotExtraKey) delete(normalizedExtra, OpenCodeGoUsageAutoRefreshExtraKey) delete(normalizedExtra, OpenCodeGoUsageSnapshotExtraKey) + // 目录观察和能力 metadata 只由同步写入。表单里的旧值或注入值不能进入本次更新。 + delete(normalizedExtra, grokObservedModelsExtraKey) + delete(normalizedExtra, UpstreamModelMetadataExtraKey) // 保留配额用量和专用服务受管字段,防止普通账号编辑意外覆盖。 for _, key := range []string{ "quota_used", @@ -695,6 +698,8 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U "quota_weekly_used", "quota_weekly_start", grokBillingExtraKey, + grokObservedModelsExtraKey, + UpstreamModelMetadataExtraKey, UpstreamBillingProbeEnabledExtraKey, UpstreamBillingRateSyncEnabledExtraKey, UpstreamBillingProbeExtraKey, diff --git a/backend/internal/service/admin_account_grok_catalog_test.go b/backend/internal/service/admin_account_grok_catalog_test.go new file mode 100644 index 0000000000..209f04fcbf --- /dev/null +++ b/backend/internal/service/admin_account_grok_catalog_test.go @@ -0,0 +1,176 @@ +package service + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestUpdateAccountKeepsGrokCatalogManagedByDatabase(t *testing.T) { + freshModels := map[string]any{ + "models": []string{"fresh-model"}, + "fetched_at": "2026-10-25T12:00:00Z", + } + freshMetadata := map[string]any{ + "models": map[string]any{"fresh-model": map[string]any{"id": "fresh-model"}}, + } + failedSnapshot := map[string]any{ + "models": []string{"fresh-model"}, + "fetched_at": "2026-10-25T12:00:00Z", + "last_attempt": map[string]any{ + "started_at": "2026-10-25T13:00:00Z", + "finished_at": "2026-10-25T13:00:01Z", + "status": "failed", + "error_code": "transport", + }, + } + oldModels := map[string]any{ + "models": []string{"old-model"}, + "fetched_at": "2026-10-24T12:00:00Z", + } + oldMetadata := map[string]any{ + "models": map[string]any{"old-model": map[string]any{"id": "old-model"}}, + } + + tests := []struct { + name string + accountType string + credentials map[string]any + storedExtra map[string]any + inputExtra map[string]any + inputCreds map[string]any + wantModels any + wantMetadata any + wantBaseURL string + }{ + { + name: "oauth stale form does not replace fresh snapshot or metadata", + accountType: AccountTypeOAuth, + credentials: map[string]any{"access_token": "token-keep"}, + storedExtra: map[string]any{ + grokObservedModelsExtraKey: freshModels, + UpstreamModelMetadataExtraKey: freshMetadata, + }, + inputExtra: map[string]any{ + "grok_client_tool_cache_enabled": true, + grokObservedModelsExtraKey: oldModels, + UpstreamModelMetadataExtraKey: oldMetadata, + }, + wantModels: freshModels, + wantMetadata: freshMetadata, + }, + { + name: "apikey form opened without keys does not delete them", + accountType: AccountTypeAPIKey, + credentials: map[string]any{"api_key": "sk-keep", "base_url": "https://api.example.test/v1"}, + storedExtra: map[string]any{ + grokObservedModelsExtraKey: freshModels, + UpstreamModelMetadataExtraKey: freshMetadata, + }, + inputExtra: map[string]any{ + "grok_client_tool_cache_enabled": true, + }, + wantModels: freshModels, + wantMetadata: freshMetadata, + }, + { + name: "injected catalog is ignored when the account has none", + accountType: AccountTypeOAuth, + credentials: map[string]any{"access_token": "token-keep"}, + storedExtra: map[string]any{"note": "keep"}, + inputExtra: map[string]any{ + "note": "from-form", + grokObservedModelsExtraKey: oldModels, + UpstreamModelMetadataExtraKey: oldMetadata, + }, + }, + { + name: "failed attempt is not rolled back to an older success", + accountType: AccountTypeAPIKey, + credentials: map[string]any{"api_key": "sk-keep"}, + storedExtra: map[string]any{ + grokObservedModelsExtraKey: failedSnapshot, + UpstreamModelMetadataExtraKey: freshMetadata, + }, + inputExtra: map[string]any{ + grokObservedModelsExtraKey: oldModels, + UpstreamModelMetadataExtraKey: oldMetadata, + }, + wantModels: failedSnapshot, + wantMetadata: freshMetadata, + }, + { + name: "changing the saved endpoint keeps the old success", + accountType: AccountTypeOAuth, + credentials: map[string]any{ + "access_token": "token-keep", + "base_url": "https://old.example.test/v1", + }, + storedExtra: map[string]any{ + grokObservedModelsExtraKey: freshModels, + UpstreamModelMetadataExtraKey: freshMetadata, + }, + inputExtra: map[string]any{ + grokObservedModelsExtraKey: nil, + }, + inputCreds: map[string]any{ + "base_url": "https://new.example.test/v1", + }, + wantModels: freshModels, + wantMetadata: freshMetadata, + wantBaseURL: "https://new.example.test/v1", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + const accountID = int64(25) + repo := &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{ + accountID: { + ID: accountID, + Name: "grok", + Platform: PlatformGrok, + Type: tt.accountType, + Status: StatusActive, + Credentials: tt.credentials, + Extra: tt.storedExtra, + }, + }} + + got, err := (&adminServiceImpl{accountRepo: repo}).UpdateAccount(context.Background(), accountID, &UpdateAccountInput{ + Extra: tt.inputExtra, + Credentials: tt.inputCreds, + }) + require.NoError(t, err) + if tt.wantModels == nil { + require.NotContains(t, got.Extra, grokObservedModelsExtraKey) + } else { + require.Equal(t, tt.wantModels, got.Extra[grokObservedModelsExtraKey]) + } + if tt.wantMetadata == nil { + require.NotContains(t, got.Extra, UpstreamModelMetadataExtraKey) + } else { + require.Equal(t, tt.wantMetadata, got.Extra[UpstreamModelMetadataExtraKey]) + } + if _, ok := tt.inputExtra["grok_client_tool_cache_enabled"]; ok { + require.Equal(t, true, got.Extra["grok_client_tool_cache_enabled"]) + } + if tt.wantBaseURL != "" { + require.Equal(t, tt.wantBaseURL, got.GetCredential("base_url")) + require.Equal(t, "token-keep", got.GetCredential("access_token")) + oldScope, scopeErr := NewGrokCatalogScope(accountID, tt.accountType, "https://old.example.test/v1/models") + require.NoError(t, scopeErr) + current, scopeErr := NewGrokCatalogScope(accountID, tt.accountType, "https://new.example.test/v1/models") + require.NoError(t, scopeErr) + snapshot := parseGrokObservedModels(got.Extra) + require.NotNil(t, snapshot) + snapshot.Scope = oldScope + diag := EvaluateGrokModelDiagnostics(got, current, snapshot, time.Date(2026, 10, 25, 18, 0, 0, 0, time.UTC)) + require.Equal(t, "source_changed", diag.State) + require.Equal(t, []string{"fresh-model"}, diag.Models) + } + }) + } +} diff --git a/backend/internal/service/billing_service.go b/backend/internal/service/billing_service.go index bd639ebfab..43bad94393 100644 --- a/backend/internal/service/billing_service.go +++ b/backend/internal/service/billing_service.go @@ -591,6 +591,20 @@ func (s *BillingService) initFallbackPricing() { } // GPT-6 Sol/Luna official rates, 2026-09-22. + s.fallbackPrices["gpt-6.1-terra"] = &ModelPricing{ + InputPricePerToken: 1e-6, + InputPricePerTokenPriority: 2e-6, + OutputPricePerToken: 5e-6, + OutputPricePerTokenPriority: 10e-6, + CacheCreationPricePerToken: 1.25e-6, + CacheCreationPricePerTokenPriority: 2.5e-6, + CacheReadPricePerToken: 0.05e-6, + CacheReadPricePerTokenPriority: 0.1e-6, + CacheCreationPriceExplicit: true, + LongContextInputThreshold: 272_000, + LongContextInputMultiplier: 2, + LongContextOutputMultiplier: 1.5, + } s.fallbackPrices["gpt-6.1-sol"] = &ModelPricing{ InputPricePerToken: 2e-6, InputPricePerTokenPriority: 4e-6, @@ -1256,7 +1270,7 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing { // OpenAI(GPT-5 / Codex 族):仅匹配已知型号,避免未知 OpenAI 型号误计价。 if normalized := normalizeKnownOpenAICodexModel(modelLower); normalized != "" { switch normalized { - case "gpt-6.1-sol", "gpt-6-sol", "gpt-6-luna": + case "gpt-6.1-terra", "gpt-6.1-sol", "gpt-6-sol", "gpt-6-luna": return s.fallbackPrices[normalized] case "gpt-6-astra": return s.fallbackPrices["gpt-6-astra"] @@ -1432,7 +1446,7 @@ func (s *BillingService) getModelPricingAt(model string, pricingAt time.Time) (* InputPricePerTokenPriority: litellmPricing.InputCostPerTokenPriority, OutputPricePerToken: litellmPricing.OutputCostPerToken, OutputPricePerTokenPriority: litellmPricing.OutputCostPerTokenPriority, - CacheCreationPriceExplicit: (openai.IsGPT6SolOrLunaModelSpelling(model) || openai.IsGPT61SolModelSpelling(model)) && litellmPricing.CacheCreationInputTokenCostExplicit, + CacheCreationPriceExplicit: (openai.IsGPT6SolOrLunaModelSpelling(model) || openai.IsGPT61SolModelSpelling(model) || openai.IsGPT61TerraModelSpelling(model)) && litellmPricing.CacheCreationInputTokenCostExplicit, CacheCreationPricePerToken: litellmPricing.CacheCreationInputTokenCost, CacheCreationPricePerTokenPriority: litellmPricing.CacheCreationInputTokenCostPriority, CacheReadPricePerToken: litellmPricing.CacheReadInputTokenCost, @@ -1952,7 +1966,7 @@ func (s *BillingService) applyModelSpecificPricingPolicyEx(model string, pricing return &cloned } normalized := normalizeKnownOpenAICodexModel(model) - usesCacheWritePremium := isOpenAIGPT56Model(normalized) || (openai.IsGPT6SolOrLunaModelSpelling(normalized) || openai.IsGPT61SolModelSpelling(normalized)) + usesCacheWritePremium := isOpenAIGPT56Model(normalized) || (openai.IsGPT6SolOrLunaModelSpelling(normalized) || openai.IsGPT61SolModelSpelling(normalized) || openai.IsGPT61TerraModelSpelling(normalized)) needsCacheCreationPolicy := usesCacheWritePremium && !pricing.CacheCreationPriceExplicit && (pricing.CacheCreationPricePerToken <= 0 || (pricing.InputPricePerTokenPriority > 0 && pricing.CacheCreationPricePerTokenPriority <= 0)) fastRatio := openAIModelFastPricingRatio(normalized) @@ -1978,7 +1992,7 @@ func (s *BillingService) applyModelSpecificPricingPolicyEx(model string, pricing } if fastRatio > 0 { enforceOpenAIFastPricingRatio(&cloned, fastRatio) - if (openai.IsGPT6SolOrLunaModelSpelling(normalized) || openai.IsGPT61SolModelSpelling(normalized)) && cloned.CacheCreationPriceExplicit { + if (openai.IsGPT6SolOrLunaModelSpelling(normalized) || openai.IsGPT61SolModelSpelling(normalized) || openai.IsGPT61TerraModelSpelling(normalized)) && cloned.CacheCreationPriceExplicit { cloned.CacheCreationPricePerTokenPriority = cloned.CacheCreationPricePerToken * fastRatio } } @@ -1990,7 +2004,7 @@ func (s *BillingService) applyModelSpecificPricingPolicyEx(model string, pricing // 档的模型(如 gpt-5.5-pro、gpt-5.4-mini/nano)返回 0。 func openAIModelFastPricingRatio(normalized string) float64 { switch normalized { - case "gpt-5.4", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-6-astra", "gpt-6.1-sol", "gpt-6-sol", "gpt-6-luna": + case "gpt-5.4", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-6-astra", "gpt-6.1-terra", "gpt-6.1-sol", "gpt-6-sol", "gpt-6-luna": return 2.0 case "gpt-5.5": return 2.5 diff --git a/backend/internal/service/billing_service_test.go b/backend/internal/service/billing_service_test.go index d02c942cb3..cb68489b49 100644 --- a/backend/internal/service/billing_service_test.go +++ b/backend/internal/service/billing_service_test.go @@ -2049,6 +2049,8 @@ func TestNewModelPricingCatalogFallbackAndContext(t *testing.T) { input, output, write, read float64 }{ {"gpt-6.1-sol", 2e-6, 10e-6, 2.5e-6, 0.1e-6}, + {"gpt-6.1-terra", 1e-6, 5e-6, 1.25e-6, 0.05e-6}, + {"openai/gpt-6.1-terra-max", 1e-6, 5e-6, 1.25e-6, 0.05e-6}, {"gpt-6-sol", 2e-6, 10e-6, 2.5e-6, 0.2e-6}, {"gpt-6-luna", 0.1e-6, 0.5e-6, 0.125e-6, 0.01e-6}, } { diff --git a/backend/internal/service/grok_model_catalog.go b/backend/internal/service/grok_model_catalog.go new file mode 100644 index 0000000000..99f60971bb --- /dev/null +++ b/backend/internal/service/grok_model_catalog.go @@ -0,0 +1,310 @@ +package service + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "net/url" + "strconv" + "strings" + "time" +) + +const ( + grokCatalogStatusSuccess = "success" + grokCatalogStatusFailed = "failed" + grokCatalogStatusConfiguredFallback = "configured_fallback" +) + +var ( + errGrokCatalogInvalidResponse = errors.New("grok catalog: invalid response") + errGrokCatalogEmpty = errors.New("grok catalog: empty catalog") + errGrokCatalogInvalidModelsURL = errors.New("grok catalog: invalid models url") + errGrokCatalogInvalidObservation = errors.New("grok catalog: invalid observation") +) + +type GrokCatalogScope struct { + AccountID int64 `json:"account_id"` + AccountType string `json:"account_type"` + Endpoint string `json:"endpoint"` + Fingerprint string `json:"fingerprint"` +} + +type GrokCatalogAttempt struct { + StartedAt string `json:"started_at"` + FinishedAt string `json:"finished_at"` + Status string `json:"status"` + ErrorCode string `json:"error_code,omitempty"` + Scope *GrokCatalogScope `json:"scope,omitempty"` +} + +type GrokObservedModelsSnapshot struct { + Models []string `json:"models"` + FetchedAt string `json:"fetched_at"` + Source string `json:"source,omitempty"` + Scope *GrokCatalogScope `json:"scope,omitempty"` + SuccessStartedAt string `json:"success_started_at,omitempty"` + LastAttempt *GrokCatalogAttempt `json:"last_attempt,omitempty"` +} + +type GrokCatalogObservation struct { + Models []string + Attempt GrokCatalogAttempt +} + +func NewGrokCatalogScope(accountID int64, accountType, modelsURL string) (*GrokCatalogScope, error) { + parsed, err := url.Parse(modelsURL) + if err != nil { + return nil, errGrokCatalogInvalidModelsURL + } + scheme := strings.ToLower(parsed.Scheme) + if parsed.Hostname() == "" || (scheme != "http" && scheme != "https") { + return nil, errGrokCatalogInvalidModelsURL + } + endpoint := scheme + "://" + strings.ToLower(parsed.Host) + strings.TrimRight(parsed.EscapedPath(), "/") + canonical := endpoint + if parsed.RawQuery != "" { + canonical += "?" + parsed.RawQuery + } + return &GrokCatalogScope{ + AccountID: accountID, + AccountType: accountType, + Endpoint: endpoint, + Fingerprint: grokCatalogFingerprint(canonical, accountID, accountType), + }, nil +} + +func grokCatalogFingerprint(canonicalURL string, accountID int64, accountType string) string { + payload := canonicalURL + "\n" + strconv.FormatInt(accountID, 10) + "\n" + accountType + sum := sha256.Sum256([]byte(payload)) + return hex.EncodeToString(sum[:]) +} + +func MergeGrokCatalogObservation(previous *GrokObservedModelsSnapshot, observation GrokCatalogObservation) (*GrokObservedModelsSnapshot, bool, error) { + if err := validateGrokCatalogObservation(observation); err != nil { + return nil, false, err + } + started, err := time.Parse(time.RFC3339Nano, observation.Attempt.StartedAt) + if err != nil { + return nil, false, errGrokCatalogInvalidObservation + } + + next := cloneGrokObservedSnapshot(previous) + if next == nil { + next = &GrokObservedModelsSnapshot{} + } + changed := false + if shouldReplaceGrokCatalogAttempt(next.LastAttempt, started) { + next.LastAttempt = cloneGrokCatalogAttempt(&observation.Attempt) + changed = true + } + if observation.Attempt.Status == grokCatalogStatusSuccess && shouldReplaceGrokCatalogSuccess(next, started) { + applyGrokCatalogSuccess(next, observation) + changed = true + } + return next, changed, nil +} + +func validateGrokCatalogObservation(observation GrokCatalogObservation) error { + switch observation.Attempt.Status { + case grokCatalogStatusSuccess, grokCatalogStatusFailed, grokCatalogStatusConfiguredFallback: + default: + return errGrokCatalogInvalidObservation + } + switch observation.Attempt.ErrorCode { + case "", "configuration", "http_error", "transport", "invalid_response", "empty_catalog", "too_large", "persistence": + default: + return errGrokCatalogInvalidObservation + } + started, err := time.Parse(time.RFC3339Nano, observation.Attempt.StartedAt) + if err != nil { + return errGrokCatalogInvalidObservation + } + finished, err := time.Parse(time.RFC3339Nano, observation.Attempt.FinishedAt) + if err != nil { + return errGrokCatalogInvalidObservation + } + if finished.Before(started) { + return errGrokCatalogInvalidObservation + } + if observation.Attempt.Status == grokCatalogStatusSuccess { + if observation.Attempt.Scope == nil || !grokCatalogHasModelID(observation.Models) { + return errGrokCatalogInvalidObservation + } + } + return nil +} + +func grokCatalogHasModelID(models []string) bool { + for _, model := range models { + if strings.TrimSpace(model) != "" { + return true + } + } + return false +} + +func shouldReplaceGrokCatalogAttempt(current *GrokCatalogAttempt, started time.Time) bool { + if current == nil { + return true + } + previous, err := time.Parse(time.RFC3339Nano, current.StartedAt) + if err != nil { + return true + } + return started.After(previous) +} + +func shouldReplaceGrokCatalogSuccess(current *GrokObservedModelsSnapshot, started time.Time) bool { + if current == nil || current.SuccessStartedAt == "" { + return true + } + previous, err := time.Parse(time.RFC3339Nano, current.SuccessStartedAt) + if err != nil { + return true + } + return started.After(previous) +} + +func applyGrokCatalogSuccess(dst *GrokObservedModelsSnapshot, observation GrokCatalogObservation) { + dst.Models = append([]string(nil), observation.Models...) + dst.FetchedAt = observation.Attempt.FinishedAt + dst.SuccessStartedAt = observation.Attempt.StartedAt + dst.Scope = cloneGrokCatalogScope(observation.Attempt.Scope) +} + +func cloneGrokObservedSnapshot(src *GrokObservedModelsSnapshot) *GrokObservedModelsSnapshot { + if src == nil { + return nil + } + dst := *src + if src.Models != nil { + dst.Models = append([]string(nil), src.Models...) + } + dst.Scope = cloneGrokCatalogScope(src.Scope) + dst.LastAttempt = cloneGrokCatalogAttempt(src.LastAttempt) + return &dst +} + +func cloneGrokCatalogAttempt(src *GrokCatalogAttempt) *GrokCatalogAttempt { + if src == nil { + return nil + } + dst := *src + dst.Scope = cloneGrokCatalogScope(src.Scope) + return &dst +} + +func cloneGrokCatalogScope(src *GrokCatalogScope) *GrokCatalogScope { + if src == nil { + return nil + } + dst := *src + return &dst +} + +func parseGrokCatalogModelIDs(body []byte) ([]string, error) { + body = bytes.TrimSpace(body) + if len(body) == 0 || !json.Valid(body) { + return nil, errGrokCatalogInvalidResponse + } + + var raw json.RawMessage + if err := json.Unmarshal(body, &raw); err != nil { + return nil, errGrokCatalogInvalidResponse + } + raw = bytes.TrimSpace(raw) + if len(raw) == 0 || bytes.Equal(raw, []byte("null")) { + return nil, errGrokCatalogInvalidResponse + } + + var entries []json.RawMessage + switch raw[0] { + case '[': + items, err := decodeGrokCatalogArray(raw) + if err != nil { + return nil, err + } + entries = items + case '{': + var obj map[string]json.RawMessage + if err := json.Unmarshal(raw, &obj); err != nil { + return nil, errGrokCatalogInvalidResponse + } + if errRaw, ok := obj["error"]; ok && !bytes.Equal(bytes.TrimSpace(errRaw), []byte("null")) { + return nil, errGrokCatalogInvalidResponse + } + sawCatalog := false + if data, ok := obj["data"]; ok { + sawCatalog = true + items, err := decodeGrokCatalogArray(data) + if err != nil { + return nil, err + } + entries = append(entries, items...) + } + if models, ok := obj["models"]; ok { + sawCatalog = true + items, err := decodeGrokCatalogArray(models) + if err != nil { + return nil, err + } + entries = append(entries, items...) + } + if !sawCatalog { + return nil, errGrokCatalogInvalidResponse + } + default: + return nil, errGrokCatalogInvalidResponse + } + + ids, err := grokCatalogIDsFromEntries(entries) + if err != nil { + return nil, err + } + if len(ids) == 0 { + return nil, errGrokCatalogEmpty + } + return ids, nil +} + +func decodeGrokCatalogArray(raw json.RawMessage) ([]json.RawMessage, error) { + raw = bytes.TrimSpace(raw) + if len(raw) == 0 || raw[0] != '[' { + return nil, errGrokCatalogInvalidResponse + } + var items []json.RawMessage + if err := json.Unmarshal(raw, &items); err != nil { + return nil, errGrokCatalogInvalidResponse + } + return items, nil +} + +func grokCatalogIDsFromEntries(entries []json.RawMessage) ([]string, error) { + models := make([]string, 0, len(entries)) + for _, raw := range entries { + raw = bytes.TrimSpace(raw) + if len(raw) == 0 || bytes.Equal(raw, []byte("null")) { + return nil, errGrokCatalogInvalidResponse + } + switch raw[0] { + case '"': + var id string + if err := json.Unmarshal(raw, &id); err != nil { + return nil, errGrokCatalogInvalidResponse + } + models = append(models, id) + case '{': + var entry upstreamModelEntry + if err := json.Unmarshal(raw, &entry); err != nil { + return nil, errGrokCatalogInvalidResponse + } + models = append(models, grokUpstreamModelEntryID(entry)) + default: + return nil, errGrokCatalogInvalidResponse + } + } + return dedupeAndSortModelIDs(models), nil +} diff --git a/backend/internal/service/grok_model_catalog_store.go b/backend/internal/service/grok_model_catalog_store.go new file mode 100644 index 0000000000..6d524812c8 --- /dev/null +++ b/backend/internal/service/grok_model_catalog_store.go @@ -0,0 +1,112 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "reflect" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +var ( + errGrokCatalogSnapshotRepositoryUnavailable = infraerrors.InternalServer( + "GROK_CATALOG_SNAPSHOT_REPOSITORY_UNAVAILABLE", + "grok model catalog snapshot repository is unavailable", + ) + errGrokCatalogAccountMismatch = errors.New("grok model catalog account mismatch") + errGrokCatalogConcurrentChange = errors.New("grok model catalog changed concurrently") +) + +// GrokCatalogSnapshotRepository is the narrow compare-and-swap capability for one +// observed-model snapshot. It is intentionally not part of AccountRepository. +type GrokCatalogSnapshotRepository interface { + CompareAndSwapGrokObservedModels(ctx context.Context, id int64, expected, next json.RawMessage) (bool, error) +} + +// PersistGrokCatalogObservation merges one observation into the account snapshot. +// The observation is fixed for every attempt; a conflict rereads and merges again, +// at most three times, and never falls back to an unlocked extra update. +func PersistGrokCatalogObservation(ctx context.Context, repo AccountRepository, accountID int64, observation GrokCatalogObservation) (*GrokObservedModelsSnapshot, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + cas, err := grokCatalogSnapshotRepository(repo) + if err != nil { + return nil, err + } + if accountID <= 0 || (observation.Attempt.Scope != nil && observation.Attempt.Scope.AccountID != accountID) { + return nil, errGrokCatalogAccountMismatch + } + + for attempt := 0; attempt < 3; attempt++ { + if err := ctx.Err(); err != nil { + return nil, err + } + account, err := repo.GetByID(ctx, accountID) + if err != nil { + return nil, err + } + if account == nil { + return nil, ErrAccountNotFound + } + if account.ID != accountID || account.Platform != PlatformGrok { + return nil, errGrokCatalogAccountMismatch + } + previous := parseGrokObservedModels(account.Extra) + next, changed, err := MergeGrokCatalogObservation(previous, observation) + if err != nil { + return nil, err + } + if !changed { + return next, nil + } + var current any + if account.Extra != nil { + current = account.Extra[grokObservedModelsExtraKey] + } + expectedJSON, err := json.Marshal(current) + if err != nil { + return nil, err + } + nextJSON, err := json.Marshal(next) + if err != nil { + return nil, err + } + if err := ctx.Err(); err != nil { + return nil, err + } + applied, err := cas.CompareAndSwapGrokObservedModels(ctx, accountID, expectedJSON, nextJSON) + if err != nil { + return nil, err + } + if applied { + return next, nil + } + } + return nil, errGrokCatalogConcurrentChange +} + +func grokCatalogSnapshotRepository(repo AccountRepository) (GrokCatalogSnapshotRepository, error) { + if isNilGrokCatalogValue(repo) { + return nil, errGrokCatalogSnapshotRepositoryUnavailable + } + cas, ok := repo.(GrokCatalogSnapshotRepository) + if !ok || isNilGrokCatalogValue(cas) { + return nil, errGrokCatalogSnapshotRepositoryUnavailable + } + return cas, nil +} + +func isNilGrokCatalogValue(value any) bool { + if value == nil { + return true + } + rv := reflect.ValueOf(value) + switch rv.Kind() { + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice: + return rv.IsNil() + default: + return false + } +} diff --git a/backend/internal/service/grok_model_catalog_store_test.go b/backend/internal/service/grok_model_catalog_store_test.go new file mode 100644 index 0000000000..8c620c92f9 --- /dev/null +++ b/backend/internal/service/grok_model_catalog_store_test.go @@ -0,0 +1,644 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "errors" + "reflect" + "sync" + "testing" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/stretchr/testify/require" +) + +var errGrokCatalogMemoryInvalidJSON = errors.New("grok model catalog: invalid json") + +func TestGrokCatalogPersistMergesAfterConflictWithoutUpdateExtra(t *testing.T) { + t.Parallel() + + scope := grokCatalogPersistScope(t, 25) + repo := newGrokCatalogMemoryRepo(&Account{ + ID: 25, + Platform: PlatformGrok, + Credentials: map[string]any{"access_token": "token-keep"}, + Extra: map[string]any{ + "unrelated": "keep", + grokObservedModelsExtraKey: map[string]any{ + "models": []any{"base"}, + "fetched_at": "2026-10-25T01:00:01Z", + "success_started_at": "2026-10-25T01:00:00Z", + "last_attempt": map[string]any{ + "started_at": "2026-10-25T01:00:00Z", + "finished_at": "2026-10-25T01:00:01Z", + "status": "success", + }, + }, + }, + }) + repo.conflictsRemaining = 1 + repo.onConflict = func(account *Account) { + account.Extra[grokObservedModelsExtraKey] = map[string]any{ + "models": []any{"concurrent"}, + "fetched_at": "2026-10-25T02:00:01Z", + "success_started_at": "2026-10-25T02:00:00Z", + "last_attempt": map[string]any{ + "started_at": "2026-10-25T02:00:00Z", + "finished_at": "2026-10-25T02:00:01Z", + "status": "success", + }, + } + } + observation := GrokCatalogObservation{Attempt: GrokCatalogAttempt{ + StartedAt: "2026-10-25T04:00:00Z", + FinishedAt: "2026-10-25T04:00:01Z", + Status: "failed", + ErrorCode: "transport", + Scope: scope, + }} + + got, err := PersistGrokCatalogObservation(context.Background(), repo, 25, observation) + + require.NoError(t, err) + require.Equal(t, []string{"concurrent"}, got.Models) + require.Equal(t, "2026-10-25T02:00:01Z", got.FetchedAt) + require.Equal(t, "2026-10-25T02:00:00Z", got.SuccessStartedAt) + require.Equal(t, "2026-10-25T04:00:00Z", got.LastAttempt.StartedAt) + require.Equal(t, "failed", got.LastAttempt.Status) + require.Equal(t, "2026-10-25T04:00:00Z", observation.Attempt.StartedAt) + require.Equal(t, 2, repo.casCalls) + require.Equal(t, 2, repo.getCalls) + require.Zero(t, repo.updateExtraCalls) + stored, err := repo.GetByID(context.Background(), 25) + require.NoError(t, err) + require.Equal(t, "keep", stored.Extra["unrelated"]) + require.Equal(t, "token-keep", stored.Credentials["access_token"]) + snap := parseGrokObservedModels(stored.Extra) + require.Equal(t, []string{"concurrent"}, snap.Models) + require.Equal(t, "2026-10-25T04:00:01Z", snap.LastAttempt.FinishedAt) + got.Models[0] = "mutated" + require.Equal(t, []string{"concurrent"}, parseGrokObservedModels(stored.Extra).Models) +} + +func TestGrokCatalogPersistStopsAfterThreeConflicts(t *testing.T) { + t.Parallel() + + scope := grokCatalogPersistScope(t, 25) + repo := newGrokCatalogMemoryRepo(&Account{ + ID: 25, + Platform: PlatformGrok, + Extra: map[string]any{ + "unrelated": "keep", + grokObservedModelsExtraKey: map[string]any{ + "models": []any{"kept"}, + "fetched_at": "2026-10-25T01:00:01Z", + "success_started_at": "2026-10-25T01:00:00Z", + }, + }, + }) + repo.conflictsRemaining = 3 + + got, err := PersistGrokCatalogObservation(context.Background(), repo, 25, grokCatalogPersistSuccess(scope, "2026-10-25T03:00:00Z", "2026-10-25T03:00:01Z", "replacement")) + + require.Nil(t, got) + require.ErrorIs(t, err, errGrokCatalogConcurrentChange) + require.Equal(t, 3, repo.getCalls) + require.Equal(t, 3, repo.casCalls) + require.Zero(t, repo.updateExtraCalls) + stored, err := repo.GetByID(context.Background(), 25) + require.NoError(t, err) + require.Equal(t, "keep", stored.Extra["unrelated"]) + require.Equal(t, []string{"kept"}, parseGrokObservedModels(stored.Extra).Models) +} + +func TestGrokCatalogPersistRejectsDeletedMismatchAndMissingCapability(t *testing.T) { + t.Parallel() + + t.Run("nil repository", func(t *testing.T) { + t.Parallel() + got, err := PersistGrokCatalogObservation(context.Background(), nil, 25, grokCatalogPersistFailure(t, 25)) + require.Nil(t, got) + require.ErrorIs(t, err, errGrokCatalogSnapshotRepositoryUnavailable) + require.True(t, infraerrors.IsInternalServer(err)) + }) + + t.Run("typed nil repository", func(t *testing.T) { + t.Parallel() + var repo *grokCatalogMemoryRepo + got, err := PersistGrokCatalogObservation(context.Background(), repo, 25, grokCatalogPersistFailure(t, 25)) + require.Nil(t, got) + require.ErrorIs(t, err, errGrokCatalogSnapshotRepositoryUnavailable) + }) + + t.Run("capability missing does not update extra", func(t *testing.T) { + t.Parallel() + repo := &grokCatalogRepoWithoutCAS{} + got, err := PersistGrokCatalogObservation(context.Background(), repo, 25, grokCatalogPersistFailure(t, 25)) + require.Nil(t, got) + require.ErrorIs(t, err, errGrokCatalogSnapshotRepositoryUnavailable) + require.Zero(t, repo.getCalls) + require.Zero(t, repo.updateCalls) + }) + + t.Run("deleted account", func(t *testing.T) { + t.Parallel() + repo := newGrokCatalogMemoryRepo(grokCatalogPersistAccount()) + repo.deleted = true + got, err := PersistGrokCatalogObservation(context.Background(), repo, 25, grokCatalogPersistSuccess(grokCatalogPersistScope(t, 25), "2026-10-25T03:00:00Z", "2026-10-25T03:00:01Z", "grok-4.7")) + require.Nil(t, got) + require.ErrorIs(t, err, ErrAccountNotFound) + require.Zero(t, repo.casCalls) + }) + + t.Run("scope account id mismatches", func(t *testing.T) { + t.Parallel() + repo := newGrokCatalogMemoryRepo(grokCatalogPersistAccount()) + got, err := PersistGrokCatalogObservation(context.Background(), repo, 25, grokCatalogPersistSuccess(grokCatalogPersistScope(t, 99), "2026-10-25T03:00:00Z", "2026-10-25T03:00:01Z", "grok-4.7")) + require.Nil(t, got) + require.ErrorIs(t, err, errGrokCatalogAccountMismatch) + require.Zero(t, repo.getCalls) + require.Zero(t, repo.casCalls) + stored, err := repo.GetByID(context.Background(), 25) + require.NoError(t, err) + require.Equal(t, []string{"kept"}, parseGrokObservedModels(stored.Extra).Models) + require.Equal(t, "keep", stored.Extra["unrelated"]) + }) + + t.Run("loaded account id mismatches", func(t *testing.T) { + t.Parallel() + repo := &grokCatalogMismatchedIDRepo{grokCatalogMemoryRepo: newGrokCatalogMemoryRepo(grokCatalogPersistAccount())} + got, err := PersistGrokCatalogObservation(context.Background(), repo, 25, grokCatalogPersistFailure(t, 25)) + require.Nil(t, got) + require.ErrorIs(t, err, errGrokCatalogAccountMismatch) + require.Zero(t, repo.casCalls) + require.Equal(t, []string{"kept"}, parseGrokObservedModels(repo.account.Extra).Models) + }) + + t.Run("platform mismatches", func(t *testing.T) { + t.Parallel() + account := grokCatalogPersistAccount() + account.Platform = PlatformOpenAI + repo := newGrokCatalogMemoryRepo(account) + got, err := PersistGrokCatalogObservation(context.Background(), repo, 25, grokCatalogPersistFailure(t, 25)) + require.Nil(t, got) + require.ErrorIs(t, err, errGrokCatalogAccountMismatch) + require.Zero(t, repo.casCalls) + require.Equal(t, "keep", repo.account.Extra["unrelated"]) + }) + + t.Run("non positive account id", func(t *testing.T) { + t.Parallel() + repo := newGrokCatalogMemoryRepo(grokCatalogPersistAccount()) + got, err := PersistGrokCatalogObservation(context.Background(), repo, 0, grokCatalogPersistFailure(t, 25)) + require.Nil(t, got) + require.ErrorIs(t, err, errGrokCatalogAccountMismatch) + require.Zero(t, repo.getCalls) + }) +} + +func TestGrokCatalogPersistKeepsNewerSnapshotWhenObservationIsOlder(t *testing.T) { + t.Parallel() + + scope := grokCatalogPersistScope(t, 25) + repo := newGrokCatalogMemoryRepo(&Account{ + ID: 25, + Platform: PlatformGrok, + Extra: map[string]any{ + "unrelated": "keep", + grokObservedModelsExtraKey: map[string]any{ + "models": []any{"newer"}, + "fetched_at": "2026-10-25T05:00:01Z", + "success_started_at": "2026-10-25T05:00:00Z", + "last_attempt": map[string]any{ + "started_at": "2026-10-25T05:00:00Z", + "finished_at": "2026-10-25T05:00:01Z", + "status": "success", + }, + }, + }, + }) + + got, err := PersistGrokCatalogObservation(context.Background(), repo, 25, grokCatalogPersistSuccess(scope, "2026-10-25T03:00:00Z", "2026-10-25T03:00:01Z", "older")) + + require.NoError(t, err) + require.Equal(t, []string{"newer"}, got.Models) + require.Equal(t, "2026-10-25T05:00:01Z", got.FetchedAt) + require.Zero(t, repo.casCalls) + require.Zero(t, repo.updateExtraCalls) + stored, err := repo.GetByID(context.Background(), 25) + require.NoError(t, err) + require.Equal(t, []string{"newer"}, parseGrokObservedModels(stored.Extra).Models) + require.Equal(t, "keep", stored.Extra["unrelated"]) +} + +func TestGrokCatalogPersistCancelStopsImmediately(t *testing.T) { + t.Parallel() + + t.Run("already canceled", func(t *testing.T) { + t.Parallel() + repo := newGrokCatalogMemoryRepo(grokCatalogPersistAccount()) + repo.writesWithoutContextCheck = true + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + got, err := PersistGrokCatalogObservation(ctx, repo, 25, grokCatalogPersistSuccess(grokCatalogPersistScope(t, 25), "2026-10-25T03:00:00Z", "2026-10-25T03:00:01Z", "grok-4.7")) + + require.Nil(t, got) + require.ErrorIs(t, err, context.Canceled) + require.Zero(t, repo.getCalls) + require.Zero(t, repo.casCalls) + require.Equal(t, []string{"kept"}, parseGrokObservedModels(repo.account.Extra).Models) + }) + + t.Run("canceled between attempts", func(t *testing.T) { + t.Parallel() + repo := newGrokCatalogMemoryRepo(grokCatalogPersistAccount()) + repo.writesWithoutContextCheck = true + repo.conflictsRemaining = 3 + ctx, cancel := context.WithCancel(context.Background()) + repo.afterCAS = func() { cancel() } + + got, err := PersistGrokCatalogObservation(ctx, repo, 25, grokCatalogPersistSuccess(grokCatalogPersistScope(t, 25), "2026-10-25T03:00:00Z", "2026-10-25T03:00:01Z", "grok-4.7")) + + require.Nil(t, got) + require.ErrorIs(t, err, context.Canceled) + require.Equal(t, 1, repo.casCalls) + require.Equal(t, []string{"kept"}, parseGrokObservedModels(repo.account.Extra).Models) + }) +} + +func TestGrokCatalogPersistMemoryRepoDeepCopiesAndMergesExtra(t *testing.T) { + t.Parallel() + + extra := map[string]any{ + "unrelated": "keep", + grokObservedModelsExtraKey: map[string]any{ + "models": []any{"kept"}, + }, + } + account := &Account{ID: 25, Platform: PlatformGrok, Extra: extra, Credentials: map[string]any{"access_token": "token-keep"}} + repo := newGrokCatalogMemoryRepo(account) + extra["unrelated"] = "changed-input" + account.Credentials["access_token"] = "changed-input" + + got, err := repo.GetByID(context.Background(), 25) + require.NoError(t, err) + require.Equal(t, "keep", got.Extra["unrelated"]) + got.Extra["unrelated"] = "changed-read" + got.Extra[grokObservedModelsExtraKey].(map[string]any)["models"] = []any{"changed-read"} + got.Credentials["access_token"] = "changed-read" + + again, err := repo.GetByID(context.Background(), 25) + require.NoError(t, err) + require.Equal(t, "keep", again.Extra["unrelated"]) + require.Equal(t, []any{"kept"}, again.Extra[grokObservedModelsExtraKey].(map[string]any)["models"]) + require.Equal(t, "token-keep", again.Credentials["access_token"]) + + metadata := map[string]any{"source": "manual"} + require.NoError(t, repo.UpdateExtra(context.Background(), 25, map[string]any{"metadata": metadata})) + metadata["source"] = "mutated" + stored, err := repo.GetByID(context.Background(), 25) + require.NoError(t, err) + require.Equal(t, "keep", stored.Extra["unrelated"]) + require.Equal(t, "manual", stored.Extra["metadata"].(map[string]any)["source"]) + require.Equal(t, []any{"kept"}, stored.Extra[grokObservedModelsExtraKey].(map[string]any)["models"]) + + require.NoError(t, repo.UpdateExtra(context.Background(), 25, map[string]any{ + grokObservedModelsExtraKey: map[string]any{"models": []any{"replaced"}}, + })) + stored, err = repo.GetByID(context.Background(), 25) + require.NoError(t, err) + require.Equal(t, "keep", stored.Extra["unrelated"]) + require.Equal(t, "manual", stored.Extra["metadata"].(map[string]any)["source"]) + require.Equal(t, []any{"replaced"}, stored.Extra[grokObservedModelsExtraKey].(map[string]any)["models"]) + require.ErrorIs(t, repo.UpdateExtra(context.Background(), 99, map[string]any{"metadata": "x"}), ErrAccountNotFound) +} + +func TestGrokCatalogPersistConcurrentWritersAreRaceSafe(t *testing.T) { + repo := newGrokCatalogMemoryRepo(&Account{ + ID: 25, + Platform: PlatformGrok, + Credentials: map[string]any{"access_token": "token-keep"}, + Extra: map[string]any{"unrelated": "keep"}, + }) + scope := grokCatalogPersistScope(t, 25) + var wg sync.WaitGroup + errCh := make(chan error, 3) + wg.Add(3) + go func() { + defer wg.Done() + _, err := PersistGrokCatalogObservation(context.Background(), repo, 25, grokCatalogPersistSuccess(scope, "2026-10-25T02:00:00Z", "2026-10-25T02:00:01Z", "older")) + errCh <- err + }() + go func() { + defer wg.Done() + _, err := PersistGrokCatalogObservation(context.Background(), repo, 25, grokCatalogPersistSuccess(scope, "2026-10-25T03:00:00Z", "2026-10-25T03:00:01Z", "newer")) + errCh <- err + }() + go func() { + defer wg.Done() + for i := 0; i < 50; i++ { + got, err := repo.GetByID(context.Background(), 25) + if err != nil { + errCh <- err + return + } + got.Extra["unrelated"] = "mutated" + if raw, ok := got.Extra[grokObservedModelsExtraKey].(map[string]any); ok { + raw["models"] = []any{"mutated"} + } + } + }() + wg.Wait() + close(errCh) + for err := range errCh { + require.NoError(t, err) + } + + stored, err := repo.GetByID(context.Background(), 25) + require.NoError(t, err) + require.Equal(t, "keep", stored.Extra["unrelated"]) + require.Equal(t, "token-keep", stored.Credentials["access_token"]) + require.Equal(t, []string{"newer"}, parseGrokObservedModels(stored.Extra).Models) + require.Zero(t, repo.updateExtraCalls) +} + +func grokCatalogPersistScope(t *testing.T, accountID int64) *GrokCatalogScope { + t.Helper() + scope, err := NewGrokCatalogScope(accountID, AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models") + require.NoError(t, err) + return scope +} + +func grokCatalogPersistSuccess(scope *GrokCatalogScope, started, finished, model string) GrokCatalogObservation { + return GrokCatalogObservation{ + Models: []string{model}, + Attempt: GrokCatalogAttempt{ + StartedAt: started, + FinishedAt: finished, + Status: "success", + Scope: scope, + }, + } +} + +func grokCatalogPersistFailure(t *testing.T, accountID int64) GrokCatalogObservation { + t.Helper() + return GrokCatalogObservation{Attempt: GrokCatalogAttempt{ + StartedAt: "2026-10-25T03:00:00Z", + FinishedAt: "2026-10-25T03:00:01Z", + Status: "failed", + ErrorCode: "transport", + Scope: grokCatalogPersistScope(t, accountID), + }} +} + +func grokCatalogPersistAccount() *Account { + return &Account{ + ID: 25, + Platform: PlatformGrok, + Credentials: map[string]any{"access_token": "token-keep"}, + Extra: map[string]any{ + "unrelated": "keep", + grokObservedModelsExtraKey: map[string]any{ + "models": []any{"kept"}, + "fetched_at": "2026-10-25T01:00:01Z", + "success_started_at": "2026-10-25T01:00:00Z", + "last_attempt": map[string]any{ + "started_at": "2026-10-25T01:00:00Z", + "finished_at": "2026-10-25T01:00:01Z", + "status": "failed", + "error_code": "transport", + }, + }, + }, + } +} + +type grokCatalogRepoWithoutCAS struct { + AccountRepository + getCalls int + updateCalls int +} + +func (r *grokCatalogRepoWithoutCAS) GetByID(context.Context, int64) (*Account, error) { + r.getCalls++ + return nil, ErrAccountNotFound +} + +func (r *grokCatalogRepoWithoutCAS) UpdateExtra(context.Context, int64, map[string]any) error { + r.updateCalls++ + return nil +} + +type grokCatalogMismatchedIDRepo struct { + *grokCatalogMemoryRepo +} + +func (r *grokCatalogMismatchedIDRepo) GetByID(ctx context.Context, id int64) (*Account, error) { + account, err := r.grokCatalogMemoryRepo.GetByID(ctx, id) + if account != nil { + account.ID = id + 1 + } + return account, err +} + +// grokCatalogMemoryRepo is the thread-safe account fixture shared with later catalog persistence tests. +type grokCatalogMemoryRepo struct { + AccountRepository + mu sync.Mutex + account *Account + deleted bool + getCalls int + casCalls int + updateExtraCalls int + conflictsRemaining int + writesWithoutContextCheck bool + onConflict func(*Account) + afterCAS func() +} + +func newGrokCatalogMemoryRepo(account *Account) *grokCatalogMemoryRepo { + return &grokCatalogMemoryRepo{account: cloneGrokCatalogMemoryAccount(account)} +} + +func (r *grokCatalogMemoryRepo) GetByID(ctx context.Context, id int64) (*Account, error) { + if !r.writesWithoutContextCheck { + if err := ctx.Err(); err != nil { + return nil, err + } + } + r.mu.Lock() + defer r.mu.Unlock() + r.getCalls++ + if r.deleted || r.account == nil || r.account.ID != id { + return nil, ErrAccountNotFound + } + return cloneGrokCatalogMemoryAccount(r.account), nil +} + +func (r *grokCatalogMemoryRepo) UpdateExtra(ctx context.Context, id int64, updates map[string]any) error { + if err := ctx.Err(); err != nil { + return err + } + r.mu.Lock() + defer r.mu.Unlock() + r.updateExtraCalls++ + if r.deleted || r.account == nil || r.account.ID != id { + return ErrAccountNotFound + } + if r.account.Extra == nil { + r.account.Extra = map[string]any{} + } + for key, value := range updates { + r.account.Extra[key] = cloneGrokCatalogMemoryValue(value) + } + return nil +} + +func (r *grokCatalogMemoryRepo) CompareAndSwapGrokObservedModels(ctx context.Context, id int64, expected, next json.RawMessage) (bool, error) { + if !r.writesWithoutContextCheck { + if err := ctx.Err(); err != nil { + return false, err + } + } + expectedJSON, err := normalizeGrokCatalogMemoryJSON(expected) + if err != nil { + return false, err + } + nextJSON, err := normalizeGrokCatalogMemoryJSON(next) + if err != nil { + return false, err + } + r.mu.Lock() + defer r.mu.Unlock() + r.casCalls++ + if r.conflictsRemaining > 0 { + r.conflictsRemaining-- + if r.onConflict != nil { + r.onConflict(r.account) + } + if r.afterCAS != nil { + r.afterCAS() + } + return false, nil + } + if r.deleted || r.account == nil || r.account.ID != id || r.account.Platform != PlatformGrok { + if r.afterCAS != nil { + r.afterCAS() + } + return false, nil + } + current, err := grokCatalogMemoryCurrentJSON(r.account) + if err != nil { + return false, err + } + if !grokCatalogMemoryJSONEqual(current, expectedJSON) { + if r.afterCAS != nil { + r.afterCAS() + } + return false, nil + } + var decoded any + if err := json.Unmarshal(nextJSON, &decoded); err != nil { + return false, err + } + if r.account.Extra == nil { + r.account.Extra = map[string]any{} + } + r.account.Extra[grokObservedModelsExtraKey] = cloneGrokCatalogMemoryValue(decoded) + if r.afterCAS != nil { + r.afterCAS() + } + return true, nil +} + +func grokCatalogMemoryCurrentJSON(account *Account) (json.RawMessage, error) { + var current any + if account != nil && account.Extra != nil { + current = account.Extra[grokObservedModelsExtraKey] + } + raw, err := json.Marshal(current) + if err != nil { + return nil, err + } + return raw, nil +} + +func normalizeGrokCatalogMemoryJSON(raw json.RawMessage) (json.RawMessage, error) { + if len(bytesTrimSpace(raw)) == 0 { + return json.RawMessage("null"), nil + } + if !json.Valid(raw) { + return nil, errGrokCatalogMemoryInvalidJSON + } + return raw, nil +} + +func grokCatalogMemoryJSONEqual(left, right json.RawMessage) bool { + var lhs, rhs any + if err := json.Unmarshal(left, &lhs); err != nil { + return false + } + if err := json.Unmarshal(right, &rhs); err != nil { + return false + } + return reflect.DeepEqual(lhs, rhs) +} + +func cloneGrokCatalogMemoryAccount(account *Account) *Account { + if account == nil { + return nil + } + cloned := *account + cloned.Extra = cloneGrokCatalogMemoryMap(account.Extra) + cloned.Credentials = cloneGrokCatalogMemoryMap(account.Credentials) + if account.GroupIDs != nil { + cloned.GroupIDs = append([]int64(nil), account.GroupIDs...) + } + if account.RateMultiplier != nil { + value := *account.RateMultiplier + cloned.RateMultiplier = &value + } + return &cloned +} + +func cloneGrokCatalogMemoryMap(in map[string]any) map[string]any { + if in == nil { + return nil + } + cloned, ok := cloneGrokCatalogMemoryValue(in).(map[string]any) + if !ok { + return map[string]any{} + } + return cloned +} + +func cloneGrokCatalogMemoryValue(value any) any { + raw, err := json.Marshal(value) + if err != nil { + panic("grok catalog memory value must be json: " + err.Error()) + } + var cloned any + if err := json.Unmarshal(raw, &cloned); err != nil { + panic("grok catalog memory value must be json: " + err.Error()) + } + return cloned +} + +func bytesTrimSpace(raw []byte) []byte { + start, end := 0, len(raw) + for start < end && isASCIISpace(raw[start]) { + start++ + } + for end > start && isASCIISpace(raw[end-1]) { + end-- + } + return raw[start:end] +} + +func isASCIISpace(b byte) bool { + return b == ' ' || b == '\n' || b == '\t' || b == '\r' +} diff --git a/backend/internal/service/grok_model_catalog_sync_test.go b/backend/internal/service/grok_model_catalog_sync_test.go new file mode 100644 index 0000000000..2aea769e92 --- /dev/null +++ b/backend/internal/service/grok_model_catalog_sync_test.go @@ -0,0 +1,945 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + "github.com/stretchr/testify/require" +) + +const ( + grokCatalogSyncSecretToken = "oauth-access-token" + grokCatalogSyncSecretRefresh = "oauth-refresh-token" + grokCatalogFallbackWarning = "The upstream model list was unavailable; configured IDs were used only for capability enrichment." + grokCatalogSaveFailure = "Failed to save upstream model catalog" + grokCatalogMetadataFailure = "Failed to save upstream model metadata" +) + +func TestGrokCatalogSyncSavesIDOnlyModelsWhenMetadataRegistryFails(t *testing.T) { + account := grokOAuthModelSyncTestAccount("https://cli-chat-proxy.grok.com/v1") + account.Credentials["model_mapping"] = map[string]any{"alias": "grok-configured"} + account.Extra = map[string]any{"note": "keep"} + credentialsBefore := cloneGrokCatalogMemoryValue(account.Credentials) + repo := newGrokCatalogMemoryRepo(account) + upstream := newGrokCatalogUpstream(http.StatusOK, `{"data":[{"model":"grok-4.7"}]}`, http.StatusBadGateway, `{"error":"registry-down"}`) + svc := &AccountTestService{ + accountRepo: repo, + httpUpstream: upstream, + cfg: upstreamModelSyncTestConfig(), + grokTokenProvider: NewGrokTokenProvider(nil, nil), + } + + catalog, err := svc.SyncUpstreamModelCatalog(context.Background(), account) + require.NoError(t, err) + require.Equal(t, "upstream", catalog.DiscoverySource) + require.Equal(t, []string{"grok-4.7"}, catalog.Models) + require.Contains(t, catalog.Warnings, UpstreamModelSyncWarning{ + Code: UpstreamModelMetadataIncompleteCode, + Message: "Model IDs were synced, but capability metadata is incomplete.", + }) + require.Equal(t, []string{"grok-4.7"}, parseGrokObservedModels(account.Extra).Models) + require.Equal(t, "keep", account.Extra["note"]) + require.Equal(t, credentialsBefore, cloneGrokCatalogMemoryValue(account.Credentials)) + + stored, err := repo.GetByID(context.Background(), account.ID) + require.NoError(t, err) + snap := parseGrokObservedModels(stored.Extra) + require.Equal(t, []string{"grok-4.7"}, snap.Models) + require.NotContains(t, snap.Models, "grok-configured") + require.Equal(t, "keep", stored.Extra["note"]) + require.Equal(t, grokCatalogStatusSuccess, snap.LastAttempt.Status) + require.Empty(t, snap.LastAttempt.ErrorCode) + require.Equal(t, "https://cli-chat-proxy.grok.com/v1/models", snap.Scope.Endpoint) + require.Equal(t, account.ID, snap.Scope.AccountID) + require.Equal(t, account.Type, snap.Scope.AccountType) + scope, err := NewGrokCatalogScope(account.ID, account.Type, upstream.modelsRequests()[0].URL.String()) + require.NoError(t, err) + require.Equal(t, scope.Fingerprint, snap.Scope.Fingerprint) + require.Equal(t, 1, repo.casCalls) + require.Zero(t, repo.updateExtraCalls) + require.Len(t, upstream.modelsRequests(), 1) + require.Len(t, upstream.registryRequests(), 1) + storedJSON := grokCatalogJSON(t, stored.Extra) + require.NotContains(t, storedJSON, grokCatalogSyncSecretToken) + require.NotContains(t, storedJSON, grokCatalogSyncSecretRefresh) + require.NotContains(t, storedJSON, "registry-down") +} + +func TestGrokCatalogSyncConfiguredFallbackDoesNotRefreshSuccess(t *testing.T) { + for _, status := range []int{http.StatusNotFound, http.StatusMethodNotAllowed} { + t.Run(http.StatusText(status), func(t *testing.T) { + account := grokCatalogAccountWithSuccess([]string{"grok-4.7"}, time.Now().Add(-time.Hour).UTC()) + account.Credentials["model_mapping"] = map[string]any{ + "alias": "grok-configured", + "wildcard": "grok-*", + } + previous := parseGrokObservedModels(account.Extra) + repo := newGrokCatalogMemoryRepo(account) + upstream := newGrokCatalogUpstream(status, `{"error":"hidden-upstream-body"}`, http.StatusBadGateway, `{"error":"registry-down"}`) + svc := grokCatalogSyncService(repo, upstream) + + catalog, err := svc.SyncUpstreamModelCatalog(context.Background(), account) + require.NoError(t, err) + require.Equal(t, "configured_fallback", catalog.DiscoverySource) + require.Equal(t, []string{"grok-configured"}, catalog.Models) + require.Contains(t, catalog.Warnings, UpstreamModelSyncWarning{ + Code: "grok_model_catalog_configured_fallback", + Message: grokCatalogFallbackWarning, + }) + + stored, err := repo.GetByID(context.Background(), account.ID) + require.NoError(t, err) + snap := parseGrokObservedModels(stored.Extra) + require.Equal(t, previous.Models, snap.Models) + require.Equal(t, previous.FetchedAt, snap.FetchedAt) + require.Equal(t, previous.SuccessStartedAt, snap.SuccessStartedAt) + require.Equal(t, previous.Scope.Fingerprint, snap.Scope.Fingerprint) + require.Equal(t, grokCatalogStatusConfiguredFallback, snap.LastAttempt.Status) + require.Equal(t, "http_error", snap.LastAttempt.ErrorCode) + require.NotContains(t, grokCatalogJSON(t, stored.Extra), "hidden-upstream-body") + require.NotContains(t, snap.Models, "grok-configured") + }) + } +} + +func TestGrokCatalogSyncKeepsSuccessOnHTTPErrors(t *testing.T) { + for _, status := range []int{http.StatusUnauthorized, http.StatusForbidden, http.StatusTooManyRequests, http.StatusInternalServerError} { + t.Run(http.StatusText(status), func(t *testing.T) { + account := grokCatalogAccountWithSuccess([]string{"grok-4.7"}, time.Now().Add(-time.Hour).UTC()) + previous := parseGrokObservedModels(account.Extra) + repo := newGrokCatalogMemoryRepo(account) + upstream := newGrokCatalogUpstream(status, `{"error":"hidden-upstream-body"}`, http.StatusOK, `{}`) + svc := grokCatalogSyncService(repo, upstream) + + _, err := svc.SyncUpstreamModelCatalog(context.Background(), account) + requireGrokHTTPSyncError(t, err, status) + snap := grokCatalogStoredSnapshot(t, repo, account.ID) + requireGrokSuccessPreserved(t, previous, snap) + require.Equal(t, grokCatalogStatusFailed, snap.LastAttempt.Status) + require.Equal(t, "http_error", snap.LastAttempt.ErrorCode) + require.NotContains(t, grokCatalogJSON(t, snap), "hidden-upstream-body") + require.NotContains(t, err.Error(), "hidden-upstream-body") + }) + } +} + +func TestGrokCatalogSyncHTTPErrorSurvivesObservationSaveFailure(t *testing.T) { + account := grokCatalogAccountWithSuccess([]string{"grok-4.7"}, time.Now().Add(-time.Hour).UTC()) + previous := parseGrokObservedModels(account.Extra) + repo := &grokCatalogCASErrorRepo{grokCatalogMemoryRepo: newGrokCatalogMemoryRepo(account), err: errors.New("database unavailable")} + upstream := newGrokCatalogUpstream(http.StatusForbidden, `{"error":"hidden-upstream-body"}`, http.StatusOK, `{}`) + svc := grokCatalogSyncService(repo, upstream) + + _, err := svc.SyncUpstreamModelCatalog(context.Background(), account) + requireGrokHTTPSyncError(t, err, http.StatusForbidden) + require.NotContains(t, syncSafeMessage(t, err), "database unavailable") + snap := grokCatalogStoredSnapshot(t, repo, account.ID) + require.Equal(t, previous.Models, snap.Models) + require.Equal(t, previous.FetchedAt, snap.FetchedAt) +} + +func TestGrokCatalogSyncKeepsSuccessOnEmptyMalformedAndOversize(t *testing.T) { + tests := []struct { + name string + body string + limit int64 + message string + code string + }{ + { + name: "empty", + body: `{"data":[]}`, + message: "Upstream returned no supported models", + code: "empty_catalog", + }, + { + name: "malformed", + body: `not-json`, + message: "Upstream model list response was not valid JSON", + code: "invalid_response", + }, + { + name: "error envelope", + body: `{"error":{"message":"hidden-upstream-body"}}`, + message: "Upstream model list response was not valid JSON", + code: "invalid_response", + }, + { + name: "too large", + body: `{"data":[{"model":"grok-overflow"}]}` + strings.Repeat(" ", 80), + limit: int64(len(`{"data":[{"model":"grok-overflow"}]}`)), + message: "Upstream model list response is too large", + code: "too_large", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := grokCatalogAccountWithSuccess([]string{"grok-4.7"}, time.Now().Add(-time.Hour).UTC()) + previous := parseGrokObservedModels(account.Extra) + repo := newGrokCatalogMemoryRepo(account) + upstream := newGrokCatalogUpstream(http.StatusOK, tt.body, http.StatusOK, `{}`) + cfg := upstreamModelSyncTestConfig() + if tt.limit > 0 { + cfg.Gateway.ModelsListReadMaxBytes = tt.limit + } + svc := grokCatalogSyncService(repo, upstream) + svc.cfg = cfg + + _, err := svc.SyncUpstreamModelCatalog(context.Background(), account) + require.Equal(t, tt.message, syncSafeMessage(t, err)) + require.Equal(t, UpstreamModelSyncErrorUpstream, syncKind(t, err)) + snap := grokCatalogStoredSnapshot(t, repo, account.ID) + requireGrokSuccessPreserved(t, previous, snap) + require.Equal(t, grokCatalogStatusFailed, snap.LastAttempt.Status) + require.Equal(t, tt.code, snap.LastAttempt.ErrorCode) + require.NotContains(t, snap.Models, "grok-overflow") + require.NotContains(t, grokCatalogJSON(t, snap), "hidden-upstream-body") + }) + } +} + +func TestGrokCatalogSyncReportsCatalogSaveFailureAsInternal(t *testing.T) { + account := grokCatalogAccountWithSuccess([]string{"grok-old"}, time.Now().Add(-time.Hour).UTC()) + repo := &grokCatalogCASErrorRepo{grokCatalogMemoryRepo: newGrokCatalogMemoryRepo(account), err: errors.New("database unavailable")} + upstream := newGrokCatalogUpstream(http.StatusOK, `{"data":[{"model":"grok-4.7"}]}`, http.StatusOK, `{}`) + svc := grokCatalogSyncService(repo, upstream) + + catalog, err := svc.SyncUpstreamModelCatalog(context.Background(), account) + require.Nil(t, catalog) + require.Equal(t, grokCatalogSaveFailure, syncSafeMessage(t, err)) + require.Equal(t, UpstreamModelSyncErrorInternal, syncKind(t, err)) + require.NotContains(t, syncSafeMessage(t, err), "database unavailable") + snap := grokCatalogStoredSnapshot(t, repo, account.ID) + require.Equal(t, []string{"grok-old"}, snap.Models) +} + +func TestGrokCatalogSyncReportsMetadataSaveFailureWithoutRollback(t *testing.T) { + account := grokCatalogAccountWithSuccess([]string{"grok-old"}, time.Now().Add(-time.Hour).UTC()) + repo := &upstreamModelMetadataRepoStub{ + account: account, + err: errors.New("metadata database unavailable"), + } + body := `{"data":[{"model":"grok-4.7","reasoning":true,"supported_reasoning_levels":["low","high"],"input_modalities":["text"],"context_window":128000}]}` + upstream := newGrokCatalogUpstream(http.StatusOK, body, http.StatusOK, `{}`) + svc := grokCatalogSyncService(repo, upstream) + + catalog, err := svc.SyncUpstreamModelCatalog(context.Background(), account) + require.Nil(t, catalog) + require.Equal(t, grokCatalogMetadataFailure, syncSafeMessage(t, err)) + require.Equal(t, UpstreamModelSyncErrorInternal, syncKind(t, err)) + snap := parseGrokObservedModels(account.Extra) + require.Equal(t, []string{"grok-4.7"}, snap.Models) + require.Equal(t, grokCatalogStatusSuccess, snap.LastAttempt.Status) + require.NotEqual(t, "metadata database unavailable", syncSafeMessage(t, err)) + require.Greater(t, repo.casCalls, 0) +} + +func TestGrokCatalogSyncPreviewAndPureReadDoNotPersist(t *testing.T) { + account := grokOAuthModelSyncTestAccount("https://cli-chat-proxy.grok.com/v1") + account.ID = 0 + repo := newGrokCatalogMemoryRepo(grokOAuthModelSyncTestAccount("https://cli-chat-proxy.grok.com/v1")) + upstream := newGrokCatalogUpstream(http.StatusOK, `{"data":[{"model":"grok-4.7"}]}`, http.StatusBadGateway, `{"error":"registry-down"}`) + svc := grokCatalogSyncService(repo, upstream) + + catalog, err := svc.SyncUpstreamModelCatalog(context.Background(), account) + require.NoError(t, err) + require.Equal(t, "upstream", catalog.DiscoverySource) + require.Equal(t, []string{"grok-4.7"}, catalog.Models) + require.Zero(t, repo.casCalls) + require.Nil(t, parseGrokObservedModels(account.Extra)) + + readAccount := grokOAuthModelSyncTestAccount("https://cli-chat-proxy.grok.com/v1") + readRepo := newGrokCatalogMemoryRepo(readAccount) + readUpstream := newGrokCatalogUpstream(http.StatusOK, `{"data":[{"id":"display","model":"grok-4.7"}]}`, http.StatusOK, `{}`) + readSvc := grokCatalogSyncService(readRepo, readUpstream) + before := len(readUpstream.requests) + result, err := readSvc.fetchUpstreamModelListWithObservation(context.Background(), readAccount) + require.NoError(t, err) + require.Equal(t, []string{"grok-4.7"}, result.Models) + require.NotNil(t, result.GrokObservation) + require.Equal(t, []string{"grok-4.7"}, result.GrokObservation.Models) + require.Equal(t, grokCatalogStatusSuccess, result.GrokObservation.Attempt.Status) + require.Equal(t, "https://cli-chat-proxy.grok.com/v1/models", result.GrokObservation.Attempt.Scope.Endpoint) + models, fetchErr := readSvc.FetchUpstreamSupportedModels(context.Background(), readAccount) + require.NoError(t, fetchErr) + require.Equal(t, []string{"grok-4.7"}, models) + require.Zero(t, readRepo.casCalls) + require.Zero(t, readRepo.updateExtraCalls) + require.Empty(t, readUpstream.registryRequests()) + require.Len(t, readUpstream.modelsRequests(), 2) + require.Equal(t, before+2, len(readUpstream.requests)) +} + +func TestGrokCatalogSyncNonGrokOmitsDiscoverySource(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"data":[{ + "id":"gpt-test", + "reasoning":false, + "input_modalities":["text"], + "context_window":128000 + }]}`)), + }} + repo := &upstreamModelMetadataRepoStub{} + svc := &AccountTestService{accountRepo: repo, httpUpstream: upstream, cfg: upstreamModelSyncTestConfig()} + catalog, err := svc.SyncUpstreamModelCatalog(context.Background(), &Account{ + ID: 44, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "key", "base_url": "https://provider.example/v1"}, + }) + require.NoError(t, err) + require.Empty(t, catalog.DiscoverySource) + require.NotContains(t, grokCatalogJSON(t, catalog), "discovery_source") + require.Zero(t, repo.casCalls) +} + +func TestGrokCatalogSyncManualIgnoresFreshTTL(t *testing.T) { + account := grokOAuthModelSyncTestAccount("https://cli-chat-proxy.grok.com/v1") + scope, err := NewGrokCatalogScope(account.ID, account.Type, "https://cli-chat-proxy.grok.com/v1/models") + require.NoError(t, err) + seedGrokCatalogSuccess(account, []string{"grok-old"}, time.Now().Add(-time.Minute).UTC(), scope) + repo := newGrokCatalogMemoryRepo(account) + upstream := newGrokCatalogUpstream(http.StatusOK, `{"data":[{"model":"grok-4.7"}]}`, http.StatusBadGateway, `{"error":"registry-down"}`) + svc := grokCatalogSyncService(repo, upstream) + + catalog, err := svc.SyncUpstreamModelCatalog(context.Background(), account) + require.NoError(t, err) + require.Equal(t, []string{"grok-4.7"}, catalog.Models) + require.Equal(t, []string{"grok-4.7"}, grokCatalogStoredSnapshot(t, repo, account.ID).Models) + require.Len(t, upstream.modelsRequests(), 1) +} + +func TestGrokCatalogSyncConfigErrorsDoNotFabricateSuccess(t *testing.T) { + t.Run("missing token provider", func(t *testing.T) { + account := grokCatalogAccountWithSuccess([]string{"grok-4.7"}, time.Now().Add(-time.Hour).UTC()) + delete(account.Credentials, "access_token") + previous := parseGrokObservedModels(account.Extra) + repo := newGrokCatalogMemoryRepo(account) + upstream := newGrokCatalogUpstream(http.StatusOK, `{"data":[{"model":"grok-new"}]}`, http.StatusOK, `{}`) + svc := &AccountTestService{accountRepo: repo, httpUpstream: upstream, cfg: upstreamModelSyncTestConfig()} + + _, err := svc.SyncUpstreamModelCatalog(context.Background(), account) + require.Equal(t, "Grok token provider is not configured", syncSafeMessage(t, err)) + require.Equal(t, UpstreamModelSyncErrorConfiguration, syncKind(t, err)) + require.Empty(t, upstream.requests) + snap := grokCatalogStoredSnapshot(t, repo, account.ID) + requireGrokSuccessPreserved(t, previous, snap) + require.Equal(t, grokCatalogStatusFailed, snap.LastAttempt.Status) + require.Equal(t, "configuration", snap.LastAttempt.ErrorCode) + require.Nil(t, snap.LastAttempt.Scope) + require.NotContains(t, grokCatalogJSON(t, snap), grokCatalogSyncSecretRefresh) + }) + + t.Run("invalid base url", func(t *testing.T) { + account := grokCatalogAccountWithSuccess([]string{"grok-4.7"}, time.Now().Add(-time.Hour).UTC()) + account.Credentials["base_url"] = "http://insecure.example.test/v1" + previous := parseGrokObservedModels(account.Extra) + repo := newGrokCatalogMemoryRepo(account) + upstream := newGrokCatalogUpstream(http.StatusOK, `{"data":[{"model":"grok-new"}]}`, http.StatusOK, `{}`) + svc := grokCatalogSyncService(repo, upstream) + + _, err := svc.SyncUpstreamModelCatalog(context.Background(), account) + require.Equal(t, "Invalid Grok base URL", syncSafeMessage(t, err)) + require.Equal(t, UpstreamModelSyncErrorConfiguration, syncKind(t, err)) + require.Empty(t, upstream.requests) + snap := grokCatalogStoredSnapshot(t, repo, account.ID) + requireGrokSuccessPreserved(t, previous, snap) + require.Equal(t, grokCatalogStatusFailed, snap.LastAttempt.Status) + require.Equal(t, "configuration", snap.LastAttempt.ErrorCode) + require.Nil(t, snap.LastAttempt.Scope) + }) +} + +func TestGrokCatalogSyncObservationTimeIsStableAcrossCASRetry(t *testing.T) { + account := grokOAuthModelSyncTestAccount("https://cli-chat-proxy.grok.com/v1") + inner := newGrokCatalogMemoryRepo(account) + inner.conflictsRemaining = 1 + repo := &grokCatalogCASRecordRepo{grokCatalogMemoryRepo: inner} + upstream := newGrokCatalogUpstream(http.StatusOK, `{"data":[{"model":"grok-4.7"}]}`, http.StatusBadGateway, `{"error":"registry-down"}`) + svc := grokCatalogSyncService(repo, upstream) + + _, err := svc.SyncUpstreamModelCatalog(context.Background(), account) + require.NoError(t, err) + require.GreaterOrEqual(t, len(repo.nextPayloads()), 2) + first := grokCatalogPayloadTimes(t, repo.nextPayloads()[0]) + second := grokCatalogPayloadTimes(t, repo.nextPayloads()[1]) + require.Equal(t, first, second) + require.NotEmpty(t, first.started) +} + +func TestGrokCatalogSyncKeepsAPIKeyAndCustomURLIdentity(t *testing.T) { + t.Run("api key uses its own base url", func(t *testing.T) { + account := &Account{ + ID: 21, + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "xai-key", + "base_url": "https://xai.example.com/v1", + }, + } + repo := newGrokCatalogMemoryRepo(account) + upstream := newGrokCatalogUpstream(http.StatusOK, `{"data":[{"model":"grok-4.7"}]}`, http.StatusBadGateway, `{"error":"registry-down"}`) + svc := &AccountTestService{accountRepo: repo, httpUpstream: upstream, cfg: upstreamModelSyncTestConfig()} + + catalog, err := svc.SyncUpstreamModelCatalog(context.Background(), account) + require.NoError(t, err) + require.Equal(t, "upstream", catalog.DiscoverySource) + req := upstream.modelsRequests()[0] + require.Equal(t, "https://xai.example.com/v1/models", req.URL.String()) + require.Equal(t, "Bearer xai-key", req.Header.Get("Authorization")) + require.Empty(t, req.Header.Get("X-Grok-Client-Version")) + require.Empty(t, req.Header.Get("X-UserID")) + snap := grokCatalogStoredSnapshot(t, repo, account.ID) + require.Equal(t, "https://xai.example.com/v1/models", snap.Scope.Endpoint) + require.Equal(t, AccountTypeAPIKey, snap.Scope.AccountType) + }) + + t.Run("custom oauth url does not add cli identity", func(t *testing.T) { + account := grokOAuthModelSyncTestAccount("https://custom.example.test/v1") + account.Credentials["header_override_enabled"] = true + account.Credentials["header_overrides"] = map[string]any{"X-Account-Trace": "trace-1"} + proxyID := int64(4) + account.ProxyID = &proxyID + account.Proxy = &Proxy{Protocol: "http", Host: "proxy.example.test", Port: 8080} + repo := newGrokCatalogMemoryRepo(account) + upstream := newGrokCatalogUpstream(http.StatusOK, `{"data":[{"model":"grok-4.7"}]}`, http.StatusBadGateway, `{"error":"registry-down"}`) + svc := grokCatalogSyncService(repo, upstream) + + _, err := svc.SyncUpstreamModelCatalog(context.Background(), account) + require.NoError(t, err) + req := upstream.modelsRequests()[0] + require.Equal(t, "https://custom.example.test/v1/models", req.URL.String()) + require.Empty(t, req.Header.Get("X-UserID")) + require.Empty(t, req.Header.Get("X-Email")) + require.NotEmpty(t, req.Header.Get("X-Grok-Client-Version")) + require.Equal(t, []string{"trace-1"}, headerValuesEqualFold(req.Header, "X-Account-Trace")) + require.Equal(t, account.Proxy.URL(), upstream.proxyURLs[0]) + require.Equal(t, "https://custom.example.test/v1/models", grokCatalogStoredSnapshot(t, repo, account.ID).Scope.Endpoint) + }) +} + +func TestGrokCatalogBackgroundSkipsOnlyFreshMatchingScope(t *testing.T) { + account := grokOAuthModelSyncTestAccount("") + scope, err := NewGrokCatalogScope(account.ID, account.Type, "https://cli-chat-proxy.grok.com/v1/models") + require.NoError(t, err) + seedGrokCatalogSuccess(account, []string{"grok-4.7"}, time.Now().Add(-time.Minute).UTC(), scope) + repo := newGrokCatalogMemoryRepo(account) + upstream := newGrokCatalogUpstream(http.StatusOK, `{"data":[{"model":"grok-new"}]}`, http.StatusOK, `{}`) + svc := &GrokQuotaService{accountRepo: repo, httpUpstream: upstream, cfg: upstreamModelSyncTestConfig()} + + require.NoError(t, svc.syncGrokObservedModels(context.Background(), account)) + require.Empty(t, upstream.requests) + require.Zero(t, repo.casCalls) + require.Equal(t, []string{"grok-4.7"}, grokCatalogStoredSnapshot(t, repo, account.ID).Models) +} + +func TestGrokCatalogBackgroundFetchesWhenSnapshotCannotBeReused(t *testing.T) { + officialScope := func(account *Account) *GrokCatalogScope { + t.Helper() + scope, err := NewGrokCatalogScope(account.ID, account.Type, "https://cli-chat-proxy.grok.com/v1/models") + require.NoError(t, err) + return scope + } + tests := []struct { + name string + setup func(account *Account) + }{ + { + name: "stale", + setup: func(account *Account) { + seedGrokCatalogSuccess(account, []string{"grok-old"}, time.Now().Add(-(grokObservedModelsTTL + time.Minute)).UTC(), officialScope(account)) + }, + }, + { + name: "missing scope", + setup: func(account *Account) { + seedGrokCatalogSuccess(account, []string{"grok-old"}, time.Now().Add(-time.Minute).UTC(), nil) + }, + }, + { + name: "source changed", + setup: func(account *Account) { + other, err := NewGrokCatalogScope(account.ID, account.Type, "https://old.example.test/v1/models") + require.NoError(t, err) + seedGrokCatalogSuccess(account, []string{"grok-old"}, time.Now().Add(-time.Minute).UTC(), other) + }, + }, + { + name: "future timestamp", + setup: func(account *Account) { + seedGrokCatalogSuccess(account, []string{"grok-old"}, time.Now().Add(-time.Hour).UTC(), officialScope(account)) + observed := account.Extra[grokObservedModelsExtraKey].(map[string]any) + observed["fetched_at"] = time.Now().Add(24 * time.Hour).UTC().Format(time.RFC3339Nano) + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := grokOAuthModelSyncTestAccount("") + tt.setup(account) + repo := newGrokCatalogMemoryRepo(account) + upstream := newGrokCatalogUpstream(http.StatusOK, `{"data":[{"model":"grok-4.7"}]}`, http.StatusOK, `{}`) + svc := &GrokQuotaService{accountRepo: repo, httpUpstream: upstream, cfg: upstreamModelSyncTestConfig()} + + require.NoError(t, svc.syncGrokObservedModels(context.Background(), account)) + require.Len(t, upstream.modelsRequests(), 1) + require.Empty(t, upstream.registryRequests()) + require.Equal(t, 1, repo.casCalls) + require.Zero(t, repo.updateExtraCalls) + snap := grokCatalogStoredSnapshot(t, repo, account.ID) + require.Equal(t, []string{"grok-4.7"}, snap.Models) + require.Equal(t, "https://cli-chat-proxy.grok.com/v1/models", snap.Scope.Endpoint) + require.Equal(t, grokCatalogStatusSuccess, snap.LastAttempt.Status) + }) + } +} + +func TestGrokCatalogBackgroundNoTokenAndConfigAreSafe(t *testing.T) { + t.Run("no token", func(t *testing.T) { + account := grokCatalogAccountWithSuccess([]string{"grok-4.7"}, time.Now().Add(-time.Hour).UTC()) + delete(account.Credentials, "access_token") + account.Credentials["refresh_token"] = "refresh-secret-value" + previous := parseGrokObservedModels(account.Extra) + repo := newGrokCatalogMemoryRepo(account) + upstream := newGrokCatalogUpstream(http.StatusOK, `{"data":[{"model":"grok-new"}]}`, http.StatusOK, `{}`) + svc := &GrokQuotaService{ + accountRepo: repo, + httpUpstream: upstream, + cfg: upstreamModelSyncTestConfig(), + tokenProvider: NewGrokTokenProvider(nil, nil), + } + + err := svc.syncGrokObservedModels(context.Background(), account) + require.Equal(t, "No Grok access token is available", syncSafeMessage(t, err)) + require.Equal(t, UpstreamModelSyncErrorConfiguration, syncKind(t, err)) + require.NotContains(t, err.Error(), "refresh-secret-value") + require.Empty(t, upstream.requests) + snap := grokCatalogStoredSnapshot(t, repo, account.ID) + requireGrokSuccessPreserved(t, previous, snap) + require.Equal(t, grokCatalogStatusFailed, snap.LastAttempt.Status) + require.Equal(t, "configuration", snap.LastAttempt.ErrorCode) + require.NotContains(t, grokCatalogJSON(t, snap), "refresh-secret-value") + require.NotContains(t, grokCatalogJSON(t, snap), grokCatalogSyncSecretRefresh) + }) + + t.Run("rejected custom url", func(t *testing.T) { + account := grokCatalogAccountWithSuccess([]string{"grok-4.7"}, time.Now().Add(-time.Hour).UTC()) + account.Credentials["base_url"] = "https://blocked.example.test/v1" + previous := parseGrokObservedModels(account.Extra) + repo := newGrokCatalogMemoryRepo(account) + upstream := newGrokCatalogUpstream(http.StatusOK, `{"data":[{"model":"grok-new"}]}`, http.StatusOK, `{}`) + cfg := upstreamModelSyncTestConfig() + cfg.Security.URLAllowlist.Enabled = true + cfg.Security.URLAllowlist.UpstreamHosts = []string{"allowed.example.test"} + svc := &GrokQuotaService{accountRepo: repo, httpUpstream: upstream, cfg: cfg} + + err := svc.syncGrokObservedModels(context.Background(), account) + require.ErrorContains(t, err, "base URL rejected by URL security policy") + require.Equal(t, UpstreamModelSyncErrorConfiguration, syncKind(t, err)) + require.NotContains(t, err.Error(), grokCatalogSyncSecretToken) + require.Empty(t, upstream.requests) + snap := grokCatalogStoredSnapshot(t, repo, account.ID) + requireGrokSuccessPreserved(t, previous, snap) + require.Equal(t, grokCatalogStatusFailed, snap.LastAttempt.Status) + require.Equal(t, "configuration", snap.LastAttempt.ErrorCode) + require.Nil(t, snap.LastAttempt.Scope) + }) +} + +func TestGrokCatalogBackgroundKeepsSuccessOnHTTPAndBodyFailures(t *testing.T) { + t.Run("http", func(t *testing.T) { + for _, status := range []int{http.StatusForbidden, http.StatusTooManyRequests, http.StatusInternalServerError} { + t.Run(http.StatusText(status), func(t *testing.T) { + account := grokCatalogAccountWithSuccess([]string{"grok-4.7"}, time.Now().Add(-(grokObservedModelsTTL + time.Hour)).UTC()) + previous := parseGrokObservedModels(account.Extra) + repo := newGrokCatalogMemoryRepo(account) + upstream := newGrokCatalogUpstream(status, `{"error":"hidden-upstream-body"}`, http.StatusOK, `{}`) + svc := &GrokQuotaService{accountRepo: repo, httpUpstream: upstream, cfg: upstreamModelSyncTestConfig()} + + err := svc.syncGrokObservedModels(context.Background(), account) + requireGrokHTTPSyncError(t, err, status) + snap := grokCatalogStoredSnapshot(t, repo, account.ID) + requireGrokSuccessPreserved(t, previous, snap) + require.Equal(t, grokCatalogStatusFailed, snap.LastAttempt.Status) + require.Equal(t, "http_error", snap.LastAttempt.ErrorCode) + require.NotContains(t, grokCatalogJSON(t, snap), "hidden-upstream-body") + }) + } + }) + + t.Run("body", func(t *testing.T) { + tests := []struct { + name string + body string + limit int64 + message string + code string + }{ + {name: "empty", body: `{"data":[]}`, message: "Upstream returned no supported models", code: "empty_catalog"}, + {name: "malformed", body: `not-json`, message: "Upstream model list response was not valid JSON", code: "invalid_response"}, + { + name: "too large", + body: `{"data":[{"model":"grok-overflow"}]}` + strings.Repeat(" ", 80), + limit: int64(len(`{"data":[{"model":"grok-overflow"}]}`)), + message: "Upstream model list response is too large", + code: "too_large", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := grokCatalogAccountWithSuccess([]string{"grok-4.7"}, time.Now().Add(-(grokObservedModelsTTL + time.Hour)).UTC()) + previous := parseGrokObservedModels(account.Extra) + repo := newGrokCatalogMemoryRepo(account) + upstream := newGrokCatalogUpstream(http.StatusOK, tt.body, http.StatusOK, `{}`) + cfg := upstreamModelSyncTestConfig() + if tt.limit > 0 { + cfg.Gateway.ModelsListReadMaxBytes = tt.limit + } + svc := &GrokQuotaService{accountRepo: repo, httpUpstream: upstream, cfg: cfg} + + err := svc.syncGrokObservedModels(context.Background(), account) + require.Equal(t, tt.message, syncSafeMessage(t, err)) + snap := grokCatalogStoredSnapshot(t, repo, account.ID) + requireGrokSuccessPreserved(t, previous, snap) + require.Equal(t, tt.code, snap.LastAttempt.ErrorCode) + require.NotContains(t, snap.Models, "grok-overflow") + }) + } + }) +} + +func TestGrokCatalogBackgroundUsesAccountProxy(t *testing.T) { + account := grokOAuthModelSyncTestAccount("") + proxyID := int64(8) + account.ProxyID = &proxyID + repo := newGrokCatalogMemoryRepo(account) + upstream := newGrokCatalogUpstream(http.StatusOK, `{"data":[{"model":"grok-4.7"}]}`, http.StatusOK, `{}`) + proxy := &Proxy{ID: proxyID, Protocol: "http", Host: "proxy.example.test", Port: 9090} + svc := &GrokQuotaService{ + accountRepo: repo, + httpUpstream: upstream, + cfg: upstreamModelSyncTestConfig(), + proxyRepo: grokCatalogProxyRepo{proxy: proxy}, + } + + require.NoError(t, svc.syncGrokObservedModels(context.Background(), account)) + require.Equal(t, proxy.URL(), upstream.proxyURLs[0]) + require.Equal(t, "grok-user-id", upstream.modelsRequests()[0].Header.Get("X-UserID")) +} + +func TestGrokCatalogBackgroundLateResultDoesNotOverwriteNewerSuccess(t *testing.T) { + account := grokOAuthModelSyncTestAccount("https://cli-chat-proxy.grok.com/v1") + repo := newGrokCatalogMemoryRepo(account) + started := make(chan struct{}, 1) + release := make(chan struct{}) + upstream := newGrokCatalogUpstream(http.StatusOK, `{"data":[{"model":"older"}]}`, http.StatusBadGateway, `{"error":"registry-down"}`) + upstream.blockFirst = true + upstream.started = started + upstream.release = release + upstream.secondBody = `{"data":[{"model":"newer"}]}` + + stale := cloneGrokCatalogMemoryAccount(account) + done := make(chan error, 1) + go func() { + done <- (&GrokQuotaService{ + accountRepo: repo, + httpUpstream: upstream, + cfg: upstreamModelSyncTestConfig(), + }).syncGrokObservedModels(context.Background(), stale) + }() + + select { + case <-started: + case <-time.After(5 * time.Second): + t.Fatal("older catalog request did not start") + } + + manualUpstreamAccount := cloneGrokCatalogMemoryAccount(account) + _, err := grokCatalogSyncService(repo, upstream).SyncUpstreamModelCatalog(context.Background(), manualUpstreamAccount) + require.NoError(t, err) + close(release) + + select { + case err := <-done: + require.NoError(t, err) + case <-time.After(5 * time.Second): + t.Fatal("older catalog request did not finish") + } + + snap := grokCatalogStoredSnapshot(t, repo, account.ID) + require.Equal(t, []string{"newer"}, snap.Models) + require.NotContains(t, snap.Models, "older") + require.Equal(t, []string{"newer"}, parseGrokObservedModels(manualUpstreamAccount.Extra).Models) +} + +type grokCatalogUpstream struct { + mu sync.Mutex + modelsStatus int + modelsBody string + secondBody string + modelsSeen int + registryCode int + registryBody string + requests []*http.Request + proxyURLs []string + blockFirst bool + started chan struct{} + release chan struct{} +} + +func newGrokCatalogUpstream(modelsStatus int, modelsBody string, registryCode int, registryBody string) *grokCatalogUpstream { + return &grokCatalogUpstream{ + modelsStatus: modelsStatus, + modelsBody: modelsBody, + registryCode: registryCode, + registryBody: registryBody, + } +} + +func (u *grokCatalogUpstream) Do(req *http.Request, proxyURL string, _ int64, _ int) (*http.Response, error) { + u.mu.Lock() + u.requests = append(u.requests, req) + u.proxyURLs = append(u.proxyURLs, proxyURL) + registry := req.URL != nil && req.URL.Host == "models.dev" + body := u.modelsBody + status := u.modelsStatus + block := false + if !registry { + u.modelsSeen++ + if u.modelsSeen == 1 { + block = u.blockFirst + } + if u.modelsSeen > 1 && u.secondBody != "" { + body = u.secondBody + status = http.StatusOK + } + } else { + body = u.registryBody + status = u.registryCode + } + started := u.started + release := u.release + u.mu.Unlock() + + if registry { + return grokCatalogHTTPResponse(status, body), nil + } + if block { + started <- struct{}{} + <-release + } + return grokCatalogHTTPResponse(status, body), nil +} + +func (u *grokCatalogUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, accountConcurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return u.Do(req, proxyURL, accountID, accountConcurrency) +} + +func (u *grokCatalogUpstream) modelsRequests() []*http.Request { + u.mu.Lock() + defer u.mu.Unlock() + return grokCatalogFilterRequests(u.requests, false) +} + +func (u *grokCatalogUpstream) registryRequests() []*http.Request { + u.mu.Lock() + defer u.mu.Unlock() + return grokCatalogFilterRequests(u.requests, true) +} + +func grokCatalogFilterRequests(requests []*http.Request, registry bool) []*http.Request { + filtered := make([]*http.Request, 0) + for _, req := range requests { + if req == nil || req.URL == nil { + continue + } + if (req.URL.Host == "models.dev") == registry { + filtered = append(filtered, req) + } + } + return filtered +} + +func grokCatalogHTTPResponse(status int, body string) *http.Response { + if status == 0 { + status = http.StatusOK + } + return &http.Response{ + StatusCode: status, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(body)), + } +} + +type grokCatalogGetter interface { + GetByID(context.Context, int64) (*Account, error) +} + +func grokCatalogSyncService(repo AccountRepository, upstream HTTPUpstream) *AccountTestService { + return &AccountTestService{ + accountRepo: repo, + httpUpstream: upstream, + cfg: upstreamModelSyncTestConfig(), + grokTokenProvider: NewGrokTokenProvider(nil, nil), + } +} + +func grokCatalogAccountWithSuccess(models []string, fetched time.Time) *Account { + account := grokOAuthModelSyncTestAccount("https://cli-chat-proxy.grok.com/v1") + scope, err := NewGrokCatalogScope(account.ID, account.Type, "https://cli-chat-proxy.grok.com/v1/models") + if err != nil { + panic(err) + } + seedGrokCatalogSuccess(account, models, fetched, scope) + return account +} + +func seedGrokCatalogSuccess(account *Account, models []string, fetched time.Time, scope *GrokCatalogScope) { + fetchedAt := fetched.UTC().Format(time.RFC3339Nano) + startedAt := fetched.Add(-time.Second).UTC().Format(time.RFC3339Nano) + snap := GrokObservedModelsSnapshot{ + Models: append([]string(nil), models...), + FetchedAt: fetchedAt, + SuccessStartedAt: startedAt, + Source: "upstream_v1_models", + Scope: scope, + LastAttempt: &GrokCatalogAttempt{ + StartedAt: startedAt, + FinishedAt: fetchedAt, + Status: grokCatalogStatusSuccess, + Scope: scope, + }, + } + raw, err := json.Marshal(snap) + if err != nil { + panic(err) + } + var asMap map[string]any + if err := json.Unmarshal(raw, &asMap); err != nil { + panic(err) + } + if account.Extra == nil { + account.Extra = map[string]any{} + } + account.Extra[grokObservedModelsExtraKey] = asMap +} + +func grokCatalogStoredSnapshot(t *testing.T, repo grokCatalogGetter, id int64) *GrokObservedModelsSnapshot { + t.Helper() + stored, err := repo.GetByID(context.Background(), id) + require.NoError(t, err) + snap := parseGrokObservedModels(stored.Extra) + require.NotNil(t, snap) + return snap +} + +func requireGrokSuccessPreserved(t *testing.T, previous, snap *GrokObservedModelsSnapshot) { + t.Helper() + require.Equal(t, previous.Models, snap.Models) + require.Equal(t, previous.FetchedAt, snap.FetchedAt) + require.Equal(t, previous.SuccessStartedAt, snap.SuccessStartedAt) + require.Equal(t, previous.Scope.Fingerprint, snap.Scope.Fingerprint) +} + +func requireGrokHTTPSyncError(t *testing.T, err error, status int) { + t.Helper() + require.Equal(t, "Upstream model list request failed with HTTP "+strconv.Itoa(status), syncSafeMessage(t, err)) + require.Equal(t, UpstreamModelSyncErrorUpstream, syncKind(t, err)) + require.Equal(t, status, upstreamModelSyncStatusCode(err)) +} + +func syncSafeMessage(t *testing.T, err error) string { + t.Helper() + var syncErr *UpstreamModelSyncError + require.ErrorAs(t, err, &syncErr) + return syncErr.SafeMessage() +} + +func syncKind(t *testing.T, err error) UpstreamModelSyncErrorKind { + t.Helper() + var syncErr *UpstreamModelSyncError + require.ErrorAs(t, err, &syncErr) + return syncErr.Kind +} + +func grokCatalogJSON(t *testing.T, value any) string { + t.Helper() + raw, err := json.Marshal(value) + require.NoError(t, err) + return string(raw) +} + +type grokCatalogCASErrorRepo struct { + *grokCatalogMemoryRepo + err error +} + +func (r *grokCatalogCASErrorRepo) CompareAndSwapGrokObservedModels(ctx context.Context, id int64, expected, next json.RawMessage) (bool, error) { + if r.err != nil { + return false, r.err + } + return r.grokCatalogMemoryRepo.CompareAndSwapGrokObservedModels(ctx, id, expected, next) +} + +type grokCatalogCASRecordRepo struct { + *grokCatalogMemoryRepo + mu sync.Mutex + nexts []json.RawMessage +} + +func (r *grokCatalogCASRecordRepo) CompareAndSwapGrokObservedModels(ctx context.Context, id int64, expected, next json.RawMessage) (bool, error) { + r.mu.Lock() + r.nexts = append(r.nexts, append(json.RawMessage(nil), next...)) + r.mu.Unlock() + return r.grokCatalogMemoryRepo.CompareAndSwapGrokObservedModels(ctx, id, expected, next) +} + +func (r *grokCatalogCASRecordRepo) nextPayloads() []json.RawMessage { + r.mu.Lock() + defer r.mu.Unlock() + return append([]json.RawMessage(nil), r.nexts...) +} + +type grokCatalogPayloadClock struct { + started string + finished string + success string +} + +func grokCatalogPayloadTimes(t *testing.T, raw json.RawMessage) grokCatalogPayloadClock { + t.Helper() + var payload struct { + SuccessStartedAt string `json:"success_started_at"` + LastAttempt struct { + StartedAt string `json:"started_at"` + FinishedAt string `json:"finished_at"` + } `json:"last_attempt"` + } + require.NoError(t, json.Unmarshal(raw, &payload)) + return grokCatalogPayloadClock{ + started: payload.LastAttempt.StartedAt, + finished: payload.LastAttempt.FinishedAt, + success: payload.SuccessStartedAt, + } +} + +type grokCatalogProxyRepo struct { + ProxyRepository + proxy *Proxy +} + +func (r grokCatalogProxyRepo) GetByID(context.Context, int64) (*Proxy, error) { + return r.proxy, nil +} diff --git a/backend/internal/service/grok_model_catalog_test.go b/backend/internal/service/grok_model_catalog_test.go new file mode 100644 index 0000000000..11d00032ca --- /dev/null +++ b/backend/internal/service/grok_model_catalog_test.go @@ -0,0 +1,573 @@ +//go:build unit + +package service + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestGrokCatalogParserParity(t *testing.T) { + t.Parallel() + + inputs := []string{ + `{"data":[{"id":"display","model":"grok-4.7"},{"model_id":"grok-4.6"}]}`, + `{"models":[{"modelId":"grok-4.6"},{"model":"grok-4.7"}]}`, + `["grok-4.7",{"id":"grok-4.6"},"grok-4.7"]`, + } + for _, input := range inputs { + manual, err := extractGrokUpstreamModelIDs([]byte(input)) + require.NoError(t, err) + observed, err := extractGrokModelIDsFromModelsBody([]byte(input)) + require.NoError(t, err) + parsed, err := parseGrokCatalogModelIDs([]byte(input)) + require.NoError(t, err) + require.Equal(t, []string{"grok-4.6", "grok-4.7"}, manual) + require.Equal(t, manual, observed) + require.Equal(t, manual, parsed) + } +} + +func TestGrokCatalogParserRejectsBadInput(t *testing.T) { + t.Parallel() + + inputs := []string{ + `{"error":{"message":"denied"}}`, + `{"error":{"message":"denied"},"data":[{"model":"grok-4.7"}]}`, + `{"data":[{"id":123}]}`, + `{"data":[{}]}`, + `{"data":[]}`, + `{"data":`, + `null`, + `{"models":{}}`, + `{"models":{"grok-4.7":{"model":"grok-4.7"}}}`, + } + for _, input := range inputs { + t.Run(input, func(t *testing.T) { + t.Parallel() + for _, parse := range []func([]byte) ([]string, error){ + parseGrokCatalogModelIDs, + extractGrokUpstreamModelIDs, + extractGrokModelIDsFromModelsBody, + } { + ids, err := parse([]byte(input)) + require.Error(t, err) + require.Empty(t, ids) + require.NotContains(t, err.Error(), "denied") + require.NotContains(t, err.Error(), "grok-4.7") + } + }) + } +} + +func TestGrokCatalogParserSkipsBlankIDsButRejectsEmpty(t *testing.T) { + t.Parallel() + + ids, err := parseGrokCatalogModelIDs([]byte(`{"data":[" grok-4.7 "," ",{"model":" grok-4.6 "}]}`)) + require.NoError(t, err) + require.Equal(t, []string{"grok-4.6", "grok-4.7"}, ids) + + for _, input := range []string{ + `{"data":[" ",""]}`, + `{"data":[{"id":" ","name":" "}]}`, + } { + ids, err := parseGrokCatalogModelIDs([]byte(input)) + require.Error(t, err) + require.Empty(t, ids) + } +} + +func TestGrokCatalogParserKeepsFieldPriorityAndModelsPrefix(t *testing.T) { + t.Parallel() + + priority := `{ + "data":[ + {"name":"display-name","slug":"slug-id","id":"id-val","model_id":"snake-id","modelId":"camel-id","model":"model-id"}, + {"name":"display-name","slug":"slug-id","id":"id-val","model_id":"snake-id","modelId":"camel-id"}, + {"name":"display-name","slug":"slug-id","id":"id-val","model_id":"snake-id"}, + {"name":"display-name","slug":"slug-id","id":"id-val"}, + {"name":"display-name","slug":"slug-id"}, + {"name":"display-name","_meta":{"slug":"meta-slug","model":"meta-model"}}, + {"name":"display-name","_meta":{"name":"meta-name"}}, + {"name":"display-name"} + ] + }` + want := []string{"camel-id", "display-name", "id-val", "meta-model", "meta-name", "model-id", "slug-id", "snake-id"} + manual, err := extractGrokUpstreamModelIDs([]byte(priority)) + require.NoError(t, err) + observed, err := extractGrokModelIDsFromModelsBody([]byte(priority)) + require.NoError(t, err) + require.Equal(t, want, manual) + require.Equal(t, manual, observed) + + prefixed := `{"data":["grok-4.5"],"models":[{"model":"models/grok-4.7"},{"id":" models/grok-4.6 "}]}` + manual, err = extractGrokUpstreamModelIDs([]byte(prefixed)) + require.NoError(t, err) + observed, err = extractGrokModelIDsFromModelsBody([]byte(prefixed)) + require.NoError(t, err) + require.Equal(t, []string{"grok-4.5", "grok-4.6", "grok-4.7"}, manual) + require.Equal(t, manual, observed) + + literal, err := parseGrokCatalogModelIDs([]byte(`["models/grok-4.5"]`)) + require.NoError(t, err) + require.Equal(t, []string{"models/grok-4.5"}, literal) +} + +func TestGrokCatalogScopeSanitizesURLAndSeparatesQuerySources(t *testing.T) { + t.Parallel() + + scope, err := NewGrokCatalogScope(25, AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models") + require.NoError(t, err) + require.Equal(t, int64(25), scope.AccountID) + require.Equal(t, AccountTypeOAuth, scope.AccountType) + require.Equal(t, "https://cli-chat-proxy.grok.com/v1/models", scope.Endpoint) + require.Equal(t, "4f0a3c6f55ad161d4e89ce04ab61826abe5f8c42e432782f8a799514b0d020b9", scope.Fingerprint) + + cased, err := NewGrokCatalogScope(25, AccountTypeOAuth, "https://User:s3cret@CLI-CHAT-PROXY.grok.com/v1/models/#frag") + require.NoError(t, err) + require.Equal(t, scope.Endpoint, cased.Endpoint) + require.Equal(t, scope.Fingerprint, cased.Fingerprint) + require.NotContains(t, cased.Endpoint, "s3cret") + require.NotContains(t, cased.Endpoint, "User") + require.NotContains(t, cased.Fingerprint, "s3cret") + require.NotContains(t, cased.Endpoint, "@") + require.NotContains(t, cased.Endpoint, "#") + require.NotContains(t, cased.Endpoint, "?") + + trailing, err := NewGrokCatalogScope(25, AccountTypeOAuth, "HTTPS://CLI-CHAT-PROXY.grok.com/v1/models/") + require.NoError(t, err) + require.Equal(t, scope.Endpoint, trailing.Endpoint) + require.Equal(t, scope.Fingerprint, trailing.Fingerprint) + + withQuery, err := NewGrokCatalogScope(25, AccountTypeOAuth, "https://user:s3cret@cli-chat-proxy.grok.com/v1/models?foo=1#frag") + require.NoError(t, err) + require.Equal(t, scope.Endpoint, withQuery.Endpoint) + require.Equal(t, "5e5c9708071c7d686bb14327cd19a2302fb6ee6a0205b39d3e79ece45103d9e8", withQuery.Fingerprint) + require.NotContains(t, withQuery.Endpoint, "foo") + require.NotContains(t, withQuery.Endpoint, "s3cret") + require.NotContains(t, withQuery.Fingerprint, "s3cret") + + otherQuery, err := NewGrokCatalogScope(25, AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models?foo=2") + require.NoError(t, err) + require.Equal(t, withQuery.Endpoint, otherQuery.Endpoint) + require.NotEqual(t, withQuery.Fingerprint, otherQuery.Fingerprint) + require.Equal(t, "b15abf83f8afe57da5762b87d1f0088f9d6fc9824dbcf37395246486baea7a4f", otherQuery.Fingerprint) + + otherAccount, err := NewGrokCatalogScope(26, AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models") + require.NoError(t, err) + require.NotEqual(t, scope.Fingerprint, otherAccount.Fingerprint) + require.Equal(t, "2fbf3925d18e8f57fc3ce9ba1d220b980f5aae12f839a872e91d4254bf0455f5", otherAccount.Fingerprint) + + otherType, err := NewGrokCatalogScope(25, AccountTypeAPIKey, "https://cli-chat-proxy.grok.com/v1/models") + require.NoError(t, err) + require.NotEqual(t, scope.Fingerprint, otherType.Fingerprint) + require.Equal(t, "0d5edf88280f126ae1b1a05caff23134583dd5a372e10aa15ab2baae693d68f7", otherType.Fingerprint) + + pathCase, err := NewGrokCatalogScope(25, AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/Models") + require.NoError(t, err) + require.Equal(t, "https://cli-chat-proxy.grok.com/v1/Models", pathCase.Endpoint) + require.NotEqual(t, scope.Fingerprint, pathCase.Fingerprint) + require.Equal(t, "b46e0a9625f3301f6fe281e669f586a08eb1952560207f929d99bb98e29d35ef", pathCase.Fingerprint) + + _, err = NewGrokCatalogScope(25, AccountTypeOAuth, "https://user:s3cret@/v1/models") + require.Error(t, err) + require.NotContains(t, err.Error(), "s3cret") + _, err = NewGrokCatalogScope(25, AccountTypeOAuth, "ftp://cli-chat-proxy.grok.com/v1/models") + require.Error(t, err) + _, err = NewGrokCatalogScope(25, AccountTypeOAuth, "/v1/models") + require.Error(t, err) + _, err = NewGrokCatalogScope(25, AccountTypeOAuth, "") + require.Error(t, err) +} + +func TestGrokCatalogMergeKeepsNewerSuccessWhenOlderArrivesLater(t *testing.T) { + t.Parallel() + + t0 := time.Date(2026, 10, 25, 2, 0, 0, 0, time.UTC) + scope, err := NewGrokCatalogScope(25, AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models") + require.NoError(t, err) + older := GrokCatalogObservation{Models: []string{"old"}, Attempt: GrokCatalogAttempt{ + StartedAt: t0.Format(time.RFC3339Nano), FinishedAt: t0.Add(3 * time.Second).Format(time.RFC3339Nano), Status: "success", Scope: scope, + }} + newer := GrokCatalogObservation{Models: []string{"new"}, Attempt: GrokCatalogAttempt{ + StartedAt: t0.Add(time.Second).Format(time.RFC3339Nano), FinishedAt: t0.Add(2 * time.Second).Format(time.RFC3339Nano), Status: "success", Scope: scope, + }} + latest, changed, err := MergeGrokCatalogObservation(nil, newer) + require.NoError(t, err) + require.True(t, changed) + require.Equal(t, []string{"new"}, latest.Models) + require.Equal(t, newer.Attempt.FinishedAt, latest.FetchedAt) + require.Equal(t, newer.Attempt.StartedAt, latest.SuccessStartedAt) + require.Equal(t, "success", latest.LastAttempt.Status) + require.Equal(t, scope.Fingerprint, latest.Scope.Fingerprint) + + merged, changed, err := MergeGrokCatalogObservation(latest, older) + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, []string{"new"}, merged.Models) + require.Equal(t, latest.FetchedAt, merged.FetchedAt) + require.Equal(t, latest.SuccessStartedAt, merged.SuccessStartedAt) + require.Equal(t, latest.LastAttempt.StartedAt, merged.LastAttempt.StartedAt) + + replaced, changed, err := MergeGrokCatalogObservation(merged, newer) + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, []string{"new"}, replaced.Models) + + first, _, err := MergeGrokCatalogObservation(nil, older) + require.NoError(t, err) + advanced, changed, err := MergeGrokCatalogObservation(first, newer) + require.NoError(t, err) + require.True(t, changed) + require.Equal(t, []string{"new"}, advanced.Models) + require.Equal(t, newer.Attempt.FinishedAt, advanced.FetchedAt) + require.Equal(t, newer.Attempt.StartedAt, advanced.SuccessStartedAt) + require.Equal(t, newer.Attempt.StartedAt, advanced.LastAttempt.StartedAt) + require.Equal(t, scope.Fingerprint, advanced.Scope.Fingerprint) +} + +func TestGrokCatalogMergeFailurePreservesSuccessScope(t *testing.T) { + t.Parallel() + + t0 := time.Date(2026, 10, 25, 2, 0, 0, 0, time.UTC) + oldScope, err := NewGrokCatalogScope(25, AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models") + require.NoError(t, err) + newScope, err := NewGrokCatalogScope(25, AccountTypeOAuth, "https://api.x.ai/v1/models?key=secret-key") + require.NoError(t, err) + require.Equal(t, "https://api.x.ai/v1/models", newScope.Endpoint) + require.NotContains(t, newScope.Endpoint, "secret-key") + require.NotContains(t, newScope.Fingerprint, "secret-key") + require.NotEqual(t, oldScope.Fingerprint, newScope.Fingerprint) + + success := GrokCatalogObservation{Models: []string{"new"}, Attempt: GrokCatalogAttempt{ + StartedAt: t0.Format(time.RFC3339Nano), FinishedAt: t0.Add(2 * time.Second).Format(time.RFC3339Nano), Status: "success", Scope: oldScope, + }} + latest, _, err := MergeGrokCatalogObservation(nil, success) + require.NoError(t, err) + + failure := GrokCatalogObservation{Models: []string{"should-not-apply"}, Attempt: GrokCatalogAttempt{ + StartedAt: t0.Add(3 * time.Second).Format(time.RFC3339Nano), FinishedAt: t0.Add(4 * time.Second).Format(time.RFC3339Nano), + Status: "failed", ErrorCode: "http_error", Scope: newScope, + }} + merged, changed, err := MergeGrokCatalogObservation(latest, failure) + require.NoError(t, err) + require.True(t, changed) + require.Equal(t, []string{"new"}, merged.Models) + require.Equal(t, latest.FetchedAt, merged.FetchedAt) + require.Equal(t, latest.SuccessStartedAt, merged.SuccessStartedAt) + require.Equal(t, oldScope.Endpoint, merged.Scope.Endpoint) + require.Equal(t, oldScope.Fingerprint, merged.Scope.Fingerprint) + require.Equal(t, "failed", merged.LastAttempt.Status) + require.Equal(t, "http_error", merged.LastAttempt.ErrorCode) + require.Equal(t, newScope.Endpoint, merged.LastAttempt.Scope.Endpoint) + require.Equal(t, newScope.Fingerprint, merged.LastAttempt.Scope.Fingerprint) +} + +func TestGrokCatalogMergeEarlierSuccessDoesNotOverwriteNewerAttempt(t *testing.T) { + t.Parallel() + + t0 := time.Date(2026, 10, 25, 2, 0, 0, 0, time.UTC) + scope, err := NewGrokCatalogScope(25, AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models") + require.NoError(t, err) + failure := GrokCatalogObservation{Models: []string{"failed-models"}, Attempt: GrokCatalogAttempt{ + StartedAt: t0.Add(time.Second).Format(time.RFC3339Nano), FinishedAt: t0.Add(2 * time.Second).Format(time.RFC3339Nano), + Status: "failed", ErrorCode: "transport", Scope: scope, + }} + failedFirst, changed, err := MergeGrokCatalogObservation(nil, failure) + require.NoError(t, err) + require.True(t, changed) + require.Empty(t, failedFirst.Models) + require.Empty(t, failedFirst.FetchedAt) + require.Empty(t, failedFirst.SuccessStartedAt) + require.Nil(t, failedFirst.Scope) + require.Equal(t, "failed", failedFirst.LastAttempt.Status) + + earlier := GrokCatalogObservation{Models: []string{"old"}, Attempt: GrokCatalogAttempt{ + StartedAt: t0.Format(time.RFC3339Nano), FinishedAt: t0.Add(3 * time.Second).Format(time.RFC3339Nano), Status: "success", Scope: scope, + }} + merged, changed, err := MergeGrokCatalogObservation(failedFirst, earlier) + require.NoError(t, err) + require.True(t, changed) + require.Equal(t, []string{"old"}, merged.Models) + require.Equal(t, earlier.Attempt.FinishedAt, merged.FetchedAt) + require.Equal(t, earlier.Attempt.StartedAt, merged.SuccessStartedAt) + require.Equal(t, scope.Fingerprint, merged.Scope.Fingerprint) + require.Equal(t, "failed", merged.LastAttempt.Status) + require.Equal(t, failure.Attempt.StartedAt, merged.LastAttempt.StartedAt) + require.Equal(t, "transport", merged.LastAttempt.ErrorCode) +} + +func TestGrokCatalogMergeConfiguredFallbackDoesNotRefreshSuccess(t *testing.T) { + t.Parallel() + + t0 := time.Date(2026, 10, 25, 2, 0, 0, 0, time.UTC) + oldScope, err := NewGrokCatalogScope(25, AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models") + require.NoError(t, err) + newScope, err := NewGrokCatalogScope(25, AccountTypeAPIKey, "https://api.x.ai/v1/models") + require.NoError(t, err) + success := GrokCatalogObservation{Models: []string{"new"}, Attempt: GrokCatalogAttempt{ + StartedAt: t0.Format(time.RFC3339Nano), FinishedAt: t0.Add(2 * time.Second).Format(time.RFC3339Nano), Status: "success", Scope: oldScope, + }} + latest, _, err := MergeGrokCatalogObservation(nil, success) + require.NoError(t, err) + + fallback := GrokCatalogObservation{Models: []string{"configured-id"}, Attempt: GrokCatalogAttempt{ + StartedAt: t0.Add(5 * time.Second).Format(time.RFC3339Nano), FinishedAt: t0.Add(6 * time.Second).Format(time.RFC3339Nano), + Status: "configured_fallback", Scope: newScope, + }} + merged, changed, err := MergeGrokCatalogObservation(latest, fallback) + require.NoError(t, err) + require.True(t, changed) + require.Equal(t, []string{"new"}, merged.Models) + require.Equal(t, latest.FetchedAt, merged.FetchedAt) + require.Equal(t, latest.SuccessStartedAt, merged.SuccessStartedAt) + require.Equal(t, oldScope.Fingerprint, merged.Scope.Fingerprint) + require.Equal(t, "configured_fallback", merged.LastAttempt.Status) + require.Equal(t, newScope.Fingerprint, merged.LastAttempt.Scope.Fingerprint) +} + +func TestGrokCatalogMergeDuplicateIsIdempotent(t *testing.T) { + t.Parallel() + + t0 := time.Date(2026, 10, 25, 2, 0, 0, 0, time.UTC) + scope, err := NewGrokCatalogScope(25, AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models") + require.NoError(t, err) + newer := GrokCatalogObservation{Models: []string{"new"}, Attempt: GrokCatalogAttempt{ + StartedAt: t0.Add(time.Second).Format(time.RFC3339Nano), FinishedAt: t0.Add(2 * time.Second).Format(time.RFC3339Nano), Status: "success", Scope: scope, + }} + latest, _, err := MergeGrokCatalogObservation(nil, newer) + require.NoError(t, err) + again, changed, err := MergeGrokCatalogObservation(latest, newer) + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, latest.Models, again.Models) + require.Equal(t, latest.FetchedAt, again.FetchedAt) + require.Equal(t, latest.SuccessStartedAt, again.SuccessStartedAt) + require.Equal(t, latest.Scope.Fingerprint, again.Scope.Fingerprint) + require.Equal(t, latest.LastAttempt.StartedAt, again.LastAttempt.StartedAt) + require.NotSame(t, latest, again) +} + +func TestGrokCatalogMergeDoesNotMutateInputs(t *testing.T) { + t.Parallel() + + t0 := time.Date(2026, 10, 25, 2, 0, 0, 0, time.UTC) + scope, err := NewGrokCatalogScope(25, AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models") + require.NoError(t, err) + prevModels := []string{"new"} + prevScope := *scope + prevAttempt := GrokCatalogAttempt{ + StartedAt: t0.Add(time.Second).Format(time.RFC3339Nano), FinishedAt: t0.Add(2 * time.Second).Format(time.RFC3339Nano), + Status: "success", Scope: &prevScope, + } + prev := &GrokObservedModelsSnapshot{ + Models: prevModels, FetchedAt: prevAttempt.FinishedAt, SuccessStartedAt: prevAttempt.StartedAt, + Source: "upstream_v1_models", Scope: &prevScope, LastAttempt: &prevAttempt, + } + obsModels := []string{"old"} + obsScope := *scope + older := GrokCatalogObservation{Models: obsModels, Attempt: GrokCatalogAttempt{ + StartedAt: t0.Format(time.RFC3339Nano), FinishedAt: t0.Add(3 * time.Second).Format(time.RFC3339Nano), Status: "success", Scope: &obsScope, + }} + + merged, changed, err := MergeGrokCatalogObservation(prev, older) + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, []string{"new"}, merged.Models) + + prevModels[0] = "mutated-prev" + obsModels[0] = "mutated-obs" + prevScope.Endpoint = "https://mutated.example/v1/models" + obsScope.Endpoint = "https://mutated-obs.example/v1/models" + prevAttempt.Status = "failed" + + require.Equal(t, []string{"new"}, merged.Models) + require.Equal(t, "https://cli-chat-proxy.grok.com/v1/models", merged.Scope.Endpoint) + require.Equal(t, "success", merged.LastAttempt.Status) + require.Equal(t, "https://cli-chat-proxy.grok.com/v1/models", merged.LastAttempt.Scope.Endpoint) + + merged.Models[0] = "mutated-result" + merged.Scope.Endpoint = "https://result.example/v1/models" + require.Equal(t, "mutated-prev", prev.Models[0]) + require.Equal(t, "https://mutated.example/v1/models", prev.Scope.Endpoint) +} + +func TestGrokCatalogMergeEqualTimestampDoesNotFlip(t *testing.T) { + t.Parallel() + + scope, err := NewGrokCatalogScope(25, AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models") + require.NoError(t, err) + first := GrokCatalogObservation{Models: []string{"kept"}, Attempt: GrokCatalogAttempt{ + StartedAt: "2026-10-25T02:00:00Z", FinishedAt: "2026-10-25T02:00:01Z", Status: "success", Scope: scope, + }} + sameInstant := GrokCatalogObservation{Models: []string{"other"}, Attempt: GrokCatalogAttempt{ + StartedAt: "2026-10-25T03:00:00+01:00", FinishedAt: "2026-10-25T03:00:05+01:00", Status: "success", Scope: scope, + }} + + prev, _, err := MergeGrokCatalogObservation(nil, first) + require.NoError(t, err) + merged, changed, err := MergeGrokCatalogObservation(prev, sameInstant) + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, []string{"kept"}, merged.Models) + require.Equal(t, "2026-10-25T02:00:01Z", merged.FetchedAt) + require.Equal(t, "2026-10-25T02:00:00Z", merged.LastAttempt.StartedAt) + + reverse, _, err := MergeGrokCatalogObservation(nil, sameInstant) + require.NoError(t, err) + merged, changed, err = MergeGrokCatalogObservation(reverse, first) + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, []string{"other"}, merged.Models) + require.Equal(t, "2026-10-25T03:00:05+01:00", merged.FetchedAt) +} + +func TestGrokCatalogMergeRejectsIllegalObservation(t *testing.T) { + t.Parallel() + + t0 := time.Date(2026, 10, 25, 2, 0, 0, 0, time.UTC) + scope, err := NewGrokCatalogScope(25, AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models") + require.NoError(t, err) + prevModels := []string{"new"} + prev := &GrokObservedModelsSnapshot{ + Models: prevModels, FetchedAt: t0.Add(2 * time.Second).Format(time.RFC3339Nano), + SuccessStartedAt: t0.Add(time.Second).Format(time.RFC3339Nano), Scope: scope, + } + validStart := t0.Format(time.RFC3339Nano) + validFinish := t0.Add(time.Second).Format(time.RFC3339Nano) + cases := []GrokCatalogObservation{ + {Models: []string{"new"}, Attempt: GrokCatalogAttempt{StartedAt: validStart, FinishedAt: validFinish, Status: "ok", Scope: scope}}, + {Models: []string{"new"}, Attempt: GrokCatalogAttempt{StartedAt: validStart, FinishedAt: validFinish, Status: "success", ErrorCode: "dial tcp: connection refused", Scope: scope}}, + {Models: []string{"new"}, Attempt: GrokCatalogAttempt{StartedAt: "yesterday", FinishedAt: validFinish, Status: "failed"}}, + {Models: []string{"new"}, Attempt: GrokCatalogAttempt{StartedAt: validStart, FinishedAt: "nope", Status: "failed"}}, + {Models: []string{"new"}, Attempt: GrokCatalogAttempt{StartedAt: validFinish, FinishedAt: validStart, Status: "failed"}}, + {Models: []string{"new"}, Attempt: GrokCatalogAttempt{StartedAt: "2026-10-25T02:00:00Z", FinishedAt: "2026-10-25T03:00:00+02:00", Status: "failed"}}, + {Models: nil, Attempt: GrokCatalogAttempt{StartedAt: validStart, FinishedAt: validFinish, Status: "success", Scope: scope}}, + {Models: []string{" ", ""}, Attempt: GrokCatalogAttempt{StartedAt: validStart, FinishedAt: validFinish, Status: "success", Scope: scope}}, + {Models: []string{"grok-4.7"}, Attempt: GrokCatalogAttempt{StartedAt: validStart, FinishedAt: validFinish, Status: "success"}}, + } + for _, observation := range cases { + got, changed, err := MergeGrokCatalogObservation(prev, observation) + require.Error(t, err) + require.Nil(t, got) + require.False(t, changed) + require.NotContains(t, err.Error(), "connection refused") + require.Equal(t, []string{"new"}, prev.Models) + } + prevModels[0] = "mutated" + require.Equal(t, "mutated", prev.Models[0]) +} + +func TestGrokCatalogMergeLegacySnapshotAcceptsSuccess(t *testing.T) { + t.Parallel() + + t0 := time.Date(2026, 10, 25, 2, 0, 0, 0, time.UTC) + scope, err := NewGrokCatalogScope(25, AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models") + require.NoError(t, err) + legacy := &GrokObservedModelsSnapshot{ + Models: []string{"legacy"}, FetchedAt: t0.Format(time.RFC3339Nano), Source: "upstream_v1_models", + } + success := GrokCatalogObservation{Models: []string{"new"}, Attempt: GrokCatalogAttempt{ + StartedAt: t0.Add(time.Second).Format(time.RFC3339Nano), FinishedAt: t0.Add(2 * time.Second).Format(time.RFC3339Nano), Status: "success", Scope: scope, + }} + merged, changed, err := MergeGrokCatalogObservation(legacy, success) + require.NoError(t, err) + require.True(t, changed) + require.Equal(t, []string{"new"}, merged.Models) + require.Equal(t, success.Attempt.FinishedAt, merged.FetchedAt) + require.Equal(t, success.Attempt.StartedAt, merged.SuccessStartedAt) + require.Equal(t, scope.Fingerprint, merged.Scope.Fingerprint) + require.Equal(t, "upstream_v1_models", merged.Source) + require.Equal(t, []string{"legacy"}, legacy.Models) + require.Nil(t, legacy.Scope) +} + +func TestGrokCatalogParseReadsLegacySnapshotWithoutScope(t *testing.T) { + t.Parallel() + + inner := map[string]any{ + "models": []any{"grok-4.7", "grok-4.6"}, + "fetched_at": "2026-10-25T02:00:00Z", + "source": "upstream_v1_models", + } + extra := map[string]any{grokObservedModelsExtraKey: inner} + snap := parseGrokObservedModels(extra) + require.NotNil(t, snap) + require.Equal(t, []string{"grok-4.7", "grok-4.6"}, snap.Models) + require.Equal(t, "2026-10-25T02:00:00Z", snap.FetchedAt) + require.Equal(t, "upstream_v1_models", snap.Source) + require.Nil(t, snap.Scope) + require.Nil(t, snap.LastAttempt) + require.Empty(t, snap.SuccessStartedAt) + require.Equal(t, "upstream_v1_models", inner["source"]) + _, ok := inner["models"] + require.True(t, ok) +} + +func TestGrokCatalogParseReadsLastAttemptWithoutModels(t *testing.T) { + t.Parallel() + + extra := map[string]any{ + grokObservedModelsExtraKey: map[string]any{ + "last_attempt": map[string]any{ + "started_at": "2026-10-25T02:00:01Z", + "finished_at": "2026-10-25T02:00:02Z", + "status": "failed", + "error_code": "transport", + }, + }, + } + snap := parseGrokObservedModels(extra) + require.NotNil(t, snap) + require.Empty(t, snap.Models) + require.NotNil(t, snap.LastAttempt) + require.Equal(t, "failed", snap.LastAttempt.Status) + require.Equal(t, "transport", snap.LastAttempt.ErrorCode) + require.Nil(t, snap.Scope) + + require.Nil(t, parseGrokObservedModels(map[string]any{ + grokObservedModelsExtraKey: map[string]any{}, + })) + require.Nil(t, parseGrokObservedModels(map[string]any{ + grokObservedModelsExtraKey: map[string]any{"models": []any{}}, + })) +} + +func TestGrokCatalogParserDoesNotStringifyObjectEntries(t *testing.T) { + t.Parallel() + + body := []byte(`{"data":[{"id":{"nested":true},"name":{"label":"nope"}},1,true,null]}`) + for _, parse := range []func([]byte) ([]string, error){ + parseGrokCatalogModelIDs, + extractGrokUpstreamModelIDs, + extractGrokModelIDsFromModelsBody, + } { + ids, err := parse(body) + require.Error(t, err) + require.Empty(t, ids) + require.NotContains(t, err.Error(), "nested") + require.NotContains(t, err.Error(), "nope") + for _, id := range ids { + require.NotContains(t, id, "{") + require.NotContains(t, id, "nested") + } + } +} + +func TestExtractUpstreamModelIDsIgnoresGrokCatalogRules(t *testing.T) { + t.Parallel() + + got, err := extractUpstreamModelIDs([]byte(`{"error":{"message":"denied"}}`)) + require.NoError(t, err) + require.Empty(t, got) + + got, err = extractUpstreamModelIDs([]byte(`{"data":[]}`)) + require.NoError(t, err) + require.Empty(t, got) + + got, err = extractUpstreamModelIDs([]byte(`{"data":[{"id":"canonical-id","model":"display-model"}]}`)) + require.NoError(t, err) + require.Equal(t, []string{"canonical-id"}, got) +} diff --git a/backend/internal/service/grok_model_diagnostics.go b/backend/internal/service/grok_model_diagnostics.go new file mode 100644 index 0000000000..43005fdb95 --- /dev/null +++ b/backend/internal/service/grok_model_diagnostics.go @@ -0,0 +1,265 @@ +package service + +import ( + "context" + "sort" + "strings" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/xai" +) + +const ( + grokModelDiagnosticStateUnknown = "unknown" + grokModelDiagnosticStateFresh = "fresh" + grokModelDiagnosticStateStale = "stale" + grokModelDiagnosticStateSourceChanged = "source_changed" + + grokModelDiagnosticStatusListed = "listed" + grokModelDiagnosticStatusNotListed = "not_listed" + grokModelDiagnosticStatusUnverifiable = "unverifiable" + grokModelDiagnosticStatusOutOfScope = "out_of_scope" +) + +// GrokModelDiagnosticItem is one local mapping compared with an account catalog. +type GrokModelDiagnosticItem struct { + Requested string `json:"requested"` + Upstream string `json:"upstream,omitempty"` + Status string `json:"status"` +} + +// GrokModelDiagnostics is an admin-only view of catalog trust and mapping +// differences. It never changes routing or the stored account. +type GrokModelDiagnostics struct { + State string `json:"state"` + Endpoint string `json:"endpoint,omitempty"` + FetchedAt string `json:"fetched_at,omitempty"` + ExpiresAt string `json:"expires_at,omitempty"` + Models []string `json:"models"` + LastAttempt *GrokCatalogAttempt `json:"last_attempt,omitempty"` + Mappings []GrokModelDiagnosticItem `json:"mappings"` +} + +// EvaluateGrokModelDiagnostics compares one account's saved mapping with a +// catalog observation. account and snapshot are not modified. Only a fresh, +// same-scope text catalog can report not_listed; other states may show the +// historical model list without claiming that something is currently absent. +func EvaluateGrokModelDiagnostics(account *Account, current *GrokCatalogScope, snapshot *GrokObservedModelsSnapshot, now time.Time) *GrokModelDiagnostics { + diag := &GrokModelDiagnostics{ + State: grokModelDiagnosticStateUnknown, + Models: []string{}, + Mappings: []GrokModelDiagnosticItem{}, + } + if current != nil { + diag.Endpoint = current.Endpoint + } + if snapshot != nil { + if snapshot.Models != nil { + diag.Models = append([]string{}, snapshot.Models...) + } + diag.FetchedAt = strings.TrimSpace(snapshot.FetchedAt) + diag.LastAttempt = cloneGrokCatalogAttempt(snapshot.LastAttempt) + } + state, fetched, haveFetched := grokModelDiagnosticState(current, snapshot, now) + diag.State = state + if haveFetched { + diag.ExpiresAt = fetched.UTC().Add(grokObservedModelsTTL).Format(time.RFC3339Nano) + } + diag.Mappings = grokDiagnosticMappings(account, state, grokDiagnosticCatalogSet(diag.Models)) + return diag +} + +// GetGrokModelDiagnostics builds the models URL that a sync would use and +// compares it with the stored observation. It does not fetch a token, send +// HTTP, or write the account. Non-Grok accounts return nil. +func (s *AccountTestService) GetGrokModelDiagnostics(ctx context.Context, account *Account) *GrokModelDiagnostics { + if s == nil || account == nil || !account.IsGrok() { + return nil + } + return EvaluateGrokModelDiagnostics(account, s.grokModelDiagnosticsScope(ctx, account), parseGrokObservedModels(account.Extra), time.Now().UTC()) +} + +func (s *AccountTestService) grokModelDiagnosticsScope(ctx context.Context, account *Account) *GrokCatalogScope { + modelsURL, err := s.grokModelDiagnosticsModelsURL(ctx, account) + if err != nil || strings.TrimSpace(modelsURL) == "" { + return nil + } + scope, err := NewGrokCatalogScope(account.ID, account.Type, modelsURL) + if err != nil { + return nil + } + return scope +} + +func (s *AccountTestService) grokModelDiagnosticsModelsURL(ctx context.Context, account *Account) (string, error) { + if s == nil || account == nil { + return "", errGrokCatalogInvalidModelsURL + } + baseURL, err := s.grokModelDiagnosticsBaseURL(ctx, account) + if err != nil { + return "", err + } + return buildOpenAIModelsURL(baseURL), nil +} + +func (s *AccountTestService) grokModelDiagnosticsBaseURL(ctx context.Context, account *Account) (string, error) { + switch account.Type { + case AccountTypeAPIKey: + baseURL := strings.TrimSpace(account.GetCredential("base_url")) + if baseURL == "" { + baseURL = "https://api.x.ai" + } + return s.validateUpstreamBaseURL(baseURL) + case AccountTypeOAuth: + validator, err := grokBaseURLValidator(account, s.cfg) + if err != nil { + return "", err + } + baseURL := account.GetGrokBaseURL() + if s.settingService != nil { + baseURL = s.settingService.ResolveGrokBaseURL(ctx, account) + } + return validator(baseURL) + default: + return "", errGrokCatalogInvalidModelsURL + } +} + +func grokModelDiagnosticState(current *GrokCatalogScope, snapshot *GrokObservedModelsSnapshot, now time.Time) (string, time.Time, bool) { + fetched, fetchedOK := time.Time{}, false + if snapshot != nil { + if parsed, ok := parseGrokCatalogTimestamp(snapshot.FetchedAt); ok && !parsed.After(now) { + fetched, fetchedOK = parsed, true + } + } + if current == nil || strings.TrimSpace(current.Fingerprint) == "" { + return grokModelDiagnosticStateUnknown, fetched, fetchedOK + } + if snapshot == nil || snapshot.Scope == nil || strings.TrimSpace(snapshot.Scope.Fingerprint) == "" || !grokCatalogHasModelID(snapshot.Models) { + return grokModelDiagnosticStateUnknown, fetched, fetchedOK + } + if !fetchedOK || fetched.After(now) { + return grokModelDiagnosticStateUnknown, time.Time{}, false + } + if snapshot.Scope.Fingerprint != current.Fingerprint { + return grokModelDiagnosticStateSourceChanged, fetched, true + } + if now.Sub(fetched) >= grokObservedModelsTTL { + return grokModelDiagnosticStateStale, fetched, true + } + return grokModelDiagnosticStateFresh, fetched, true +} + +func grokDiagnosticCatalogSet(models []string) map[string]struct{} { + set := make(map[string]struct{}, len(models)) + for _, model := range models { + observed := grokDiagnosticObservedID(model) + if observed == "" { + continue + } + set[observed] = struct{}{} + } + return set +} + +func grokDiagnosticMappings(account *Account, state string, catalog map[string]struct{}) []GrokModelDiagnosticItem { + items := []GrokModelDiagnosticItem{} + if account == nil { + return items + } + mapping := account.GetModelMapping() + if len(mapping) == 0 { + return items + } + keys := make([]string, 0, len(mapping)) + for key := range mapping { + if strings.TrimSpace(key) == "" { + continue + } + keys = append(keys, key) + } + sort.Strings(keys) + for _, key := range keys { + items = append(items, grokDiagnosticItem(key, mapping[key], state, catalog)) + } + return items +} + +func grokDiagnosticItem(requested, target, state string, catalog map[string]struct{}) GrokModelDiagnosticItem { + item := GrokModelDiagnosticItem{Requested: requested, Status: grokModelDiagnosticStatusUnverifiable} + if strings.Contains(requested, "*") || strings.Contains(target, "*") { + return item + } + trimmed := strings.TrimSpace(target) + if trimmed == "" { + return item + } + if grokDiagnosticIndependentCapability(trimmed) { + item.Upstream = grokDiagnosticObservedID(trimmed) + item.Status = grokModelDiagnosticStatusOutOfScope + return item + } + // Responses rewrites bare grok / grok-latest to grok-4.5. Chat, Messages, + // and the websocket bridge keep the literal alias. Neither generation is + // a catalog fact, so do not compare grok-4.5 or grok-4.6. + if grokDiagnosticBareAlias(trimmed) { + item.Upstream = trimmed + item.Status = grokModelDiagnosticStatusUnverifiable + return item + } + canonical := grokDiagnosticObservedID(trimmed) + item.Upstream = canonical + _, inCatalog := catalog[canonical] + switch { + case inCatalog && (state == grokModelDiagnosticStateFresh || state == grokModelDiagnosticStateStale): + item.Status = grokModelDiagnosticStatusListed + case state == grokModelDiagnosticStateFresh && xai.IsGrokTextResponsesModelID(trimmed): + item.Status = grokModelDiagnosticStatusNotListed + default: + item.Status = grokModelDiagnosticStatusUnverifiable + } + return item +} + +// grokDiagnosticObservedID uses the text alias table only. Runtime audit treats +// some -build responses as the same model; a catalog check must not. Bare +// grok / grok-latest and unknown IDs stay as written: the alias table's +// fallback generation is not unique across forwards, and case is not evidence +// that a custom id is listed. +func grokDiagnosticObservedID(model string) string { + trimmed := strings.TrimSpace(model) + if trimmed == "" || grokDiagnosticBareAlias(trimmed) { + return trimmed + } + return strings.TrimSpace(xai.ResolveGrokTextResponsesModelID(trimmed)) +} + +func grokDiagnosticBareAlias(model string) bool { + normalized := strings.ToLower(xai.StripGrokProviderPrefix(strings.TrimSpace(model))) + return normalized == "grok" || normalized == "grok-latest" +} + +func grokDiagnosticIndependentCapability(model string) bool { + normalized := strings.ToLower(strings.TrimSpace(xai.StripGrokProviderPrefix(model))) + if normalized == "" { + return false + } + if xai.IsGrokImagineModel(normalized) { + return true + } + switch { + case strings.Contains(normalized, "voice"), + strings.Contains(normalized, "realtime"), + strings.Contains(normalized, "audio"), + strings.Contains(normalized, "video"), + strings.HasPrefix(normalized, "tts"), + strings.HasPrefix(normalized, "stt"), + strings.Contains(normalized, "-tts"), + strings.Contains(normalized, "-stt"), + strings.Contains(normalized, "/tts"), + strings.Contains(normalized, "/stt"): + return true + default: + return false + } +} diff --git a/backend/internal/service/grok_model_diagnostics_test.go b/backend/internal/service/grok_model_diagnostics_test.go new file mode 100644 index 0000000000..9d6e6ffd69 --- /dev/null +++ b/backend/internal/service/grok_model_diagnostics_test.go @@ -0,0 +1,591 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + "github.com/stretchr/testify/require" +) + +func TestGrokModelDiagnosticsFreshExplicitMapping(t *testing.T) { + account := grokDiagnosticExplicitAccount() + credentialsBefore := cloneGrokDiagnosticValue(t, account.Credentials) + scope := grokDiagnosticOfficialScope(t) + now := time.Date(2026, 10, 25, 7, 0, 0, 0, time.UTC) + snapshot := grokDiagnosticFreshSnapshot(scope, time.Date(2026, 10, 25, 2, 0, 0, 0, time.UTC)) + snapshotBefore := cloneGrokDiagnosticValue(t, snapshot) + + diag := EvaluateGrokModelDiagnostics(account, scope, snapshot, now) + + requireDiagnosticArrays(t, diag) + require.Equal(t, "fresh", diag.State) + require.Equal(t, "https://cli-chat-proxy.grok.com/v1/models", diag.Endpoint) + require.Equal(t, "2026-10-25T02:00:00Z", diag.FetchedAt) + require.Equal(t, "2026-10-25T08:00:00Z", diag.ExpiresAt) + require.Equal(t, []string{"grok-4.5", "grok-4.6", "grok-4.7", "grok-4.7-build-fast"}, diag.Models) + require.Nil(t, diag.LastAttempt) + requireDiagnosticSorted(t, diag.Mappings) + got := diagnosticByRequested(diag.Mappings) + require.Equal(t, GrokModelDiagnosticItem{Requested: "friendly", Upstream: "grok-4.7", Status: "listed"}, got["friendly"]) + require.Equal(t, GrokModelDiagnosticItem{Requested: "grok-4.7-latest", Upstream: "grok-4.7", Status: "listed"}, got["grok-4.7-latest"]) + require.Equal(t, GrokModelDiagnosticItem{Requested: "composer-2.5", Upstream: "grok-composer-2.5-fast", Status: "not_listed"}, got["composer-2.5"]) + require.Equal(t, GrokModelDiagnosticItem{Requested: "custom-*", Status: "unverifiable"}, got["custom-*"]) + require.Equal(t, GrokModelDiagnosticItem{Requested: "grok-imagine-image", Upstream: "grok-imagine-image", Status: "out_of_scope"}, got["grok-imagine-image"]) + require.Equal(t, credentialsBefore, cloneGrokDiagnosticValue(t, account.Credentials)) + require.Equal(t, snapshotBefore, cloneGrokDiagnosticValue(t, snapshot)) +} + +func TestGrokModelDiagnosticsBareAliasDoesNotInventDefaultGeneration(t *testing.T) { + now := time.Date(2026, 10, 25, 7, 0, 0, 0, time.UTC) + scope := grokDiagnosticOfficialScope(t) + aliases := map[string]string{ + "grok": "grok", + "grok-latest": "grok-latest", + "Grok": "Grok", + "GROK-LATEST": "GROK-LATEST", + "xai/grok": "xai/grok", + "x-ai/Grok-Latest": "x-ai/Grok-Latest", + } + + t.Run("catalog has only the responses default", func(t *testing.T) { + diag := evaluateGrokDiagnosticMapping(t, scope, []string{"grok-4.5"}, aliases, now) + for requested, target := range aliases { + item := diagnosticByRequested(diag.Mappings)[requested] + require.Equal(t, "unverifiable", item.Status, requested) + require.Equal(t, target, item.Upstream, requested) + require.NotEqual(t, "grok-4.5", item.Upstream, requested) + require.NotEqual(t, "grok-4.6", item.Upstream, requested) + } + }) + + t.Run("catalog has only the builtin text default", func(t *testing.T) { + diag := evaluateGrokDiagnosticMapping(t, scope, []string{"grok-4.6"}, aliases, now) + for requested, target := range aliases { + item := diagnosticByRequested(diag.Mappings)[requested] + require.Equal(t, "unverifiable", item.Status, requested) + require.Equal(t, target, item.Upstream, requested) + } + }) + + t.Run("both generations still have no single forward target", func(t *testing.T) { + diag := evaluateGrokDiagnosticMapping(t, scope, []string{"grok-4.5", "grok-4.6"}, aliases, now) + for requested := range aliases { + item := diagnosticByRequested(diag.Mappings)[requested] + require.Equal(t, "unverifiable", item.Status, requested) + require.NotEqual(t, "listed", item.Status, requested) + require.NotEqual(t, "not_listed", item.Status, requested) + } + }) + + t.Run("literal catalog grok is not grok-4.6", func(t *testing.T) { + diag := evaluateGrokDiagnosticMapping(t, scope, []string{"grok"}, map[string]string{ + "pinned": "grok-4.6", + "friendly": "grok", + }, now) + got := diagnosticByRequested(diag.Mappings) + require.Equal(t, GrokModelDiagnosticItem{Requested: "pinned", Upstream: "grok-4.6", Status: "not_listed"}, got["pinned"]) + require.Equal(t, GrokModelDiagnosticItem{Requested: "friendly", Upstream: "grok", Status: "unverifiable"}, got["friendly"]) + }) + + t.Run("concrete aliases stay comparable", func(t *testing.T) { + diag := evaluateGrokDiagnosticMapping(t, scope, []string{"grok-4.5", "grok-4.7"}, map[string]string{ + "pinned": "grok-4.5", + "latest": "grok-4.7-latest", + "composer": "composer-2.5", + }, now) + got := diagnosticByRequested(diag.Mappings) + require.Equal(t, GrokModelDiagnosticItem{Requested: "pinned", Upstream: "grok-4.5", Status: "listed"}, got["pinned"]) + require.Equal(t, GrokModelDiagnosticItem{Requested: "latest", Upstream: "grok-4.7", Status: "listed"}, got["latest"]) + require.Equal(t, GrokModelDiagnosticItem{Requested: "composer", Upstream: "grok-composer-2.5-fast", Status: "not_listed"}, got["composer"]) + }) +} + +func TestGrokModelDiagnosticsCustomIDKeepsCase(t *testing.T) { + scope, err := NewGrokCatalogScope(25, AccountTypeAPIKey, "https://relay.example.com/v1/models") + require.NoError(t, err) + now := time.Date(2026, 10, 25, 7, 0, 0, 0, time.UTC) + + t.Run("different case is not a catalog match", func(t *testing.T) { + diag := evaluateGrokDiagnosticMapping(t, scope, []string{"custom-a", "other-id"}, map[string]string{ + "mixed": "Custom-A", + "other": "Other-ID", + }, now) + got := diagnosticByRequested(diag.Mappings) + require.Equal(t, GrokModelDiagnosticItem{Requested: "mixed", Upstream: "Custom-A", Status: "unverifiable"}, got["mixed"]) + require.NotEqual(t, "listed", got["mixed"].Status) + require.NotEqual(t, "custom-a", got["mixed"].Upstream) + require.Equal(t, GrokModelDiagnosticItem{Requested: "other", Upstream: "Other-ID", Status: "unverifiable"}, got["other"]) + }) + + t.Run("same case matches", func(t *testing.T) { + diag := evaluateGrokDiagnosticMapping(t, scope, []string{"Custom-A", "custom-a"}, map[string]string{ + "mixed": "Custom-A", + "lower": "custom-a", + }, now) + got := diagnosticByRequested(diag.Mappings) + require.Equal(t, GrokModelDiagnosticItem{Requested: "mixed", Upstream: "Custom-A", Status: "listed"}, got["mixed"]) + require.Equal(t, GrokModelDiagnosticItem{Requested: "lower", Upstream: "custom-a", Status: "listed"}, got["lower"]) + }) +} + +func evaluateGrokDiagnosticMapping(t *testing.T, scope *GrokCatalogScope, models []string, targets map[string]string, now time.Time) *GrokModelDiagnostics { + t.Helper() + mapping := make(map[string]any, len(targets)) + for key, target := range targets { + mapping[key] = target + } + account := &Account{ + ID: scope.AccountID, Platform: PlatformGrok, Type: scope.AccountType, + Credentials: map[string]any{"model_mapping": mapping}, + } + snapshot := &GrokObservedModelsSnapshot{ + Models: append([]string{}, models...), + FetchedAt: now.Add(-time.Hour).UTC().Format(time.RFC3339Nano), + Scope: scope, + } + return EvaluateGrokModelDiagnostics(account, scope, snapshot, now) +} + +func TestGrokModelDiagnosticsExplicitComposerTargetInCatalogIsListed(t *testing.T) { + account := grokDiagnosticExplicitAccount() + account.Credentials["model_mapping"] = map[string]any{"composer-2.5": "grok-4.7"} + scope := grokDiagnosticOfficialScope(t) + now := time.Date(2026, 10, 25, 7, 0, 0, 0, time.UTC) + + diag := EvaluateGrokModelDiagnostics(account, scope, grokDiagnosticFreshSnapshot(scope, now.Add(-time.Hour)), now) + + got := diagnosticByRequested(diag.Mappings) + require.Equal(t, GrokModelDiagnosticItem{Requested: "composer-2.5", Upstream: "grok-4.7", Status: "listed"}, got["composer-2.5"]) + require.NotEqual(t, "not_listed", got["composer-2.5"].Status) +} + +func TestGrokModelDiagnosticsBuildSuffixIsNotCatalogEquivalence(t *testing.T) { + account := grokDiagnosticExplicitAccount() + account.Credentials["model_mapping"] = map[string]any{ + "plain": "grok-4.7", + "build": "grok-4.7-build", + "build-fast": "grok-4.7-build-fast", + } + scope := grokDiagnosticOfficialScope(t) + now := time.Date(2026, 10, 25, 7, 0, 0, 0, time.UTC) + + diag := EvaluateGrokModelDiagnostics(account, scope, grokDiagnosticFreshSnapshot(scope, now.Add(-time.Hour)), now) + + got := diagnosticByRequested(diag.Mappings) + require.Equal(t, "listed", got["plain"].Status) + require.Equal(t, "grok-4.7", got["plain"].Upstream) + require.Equal(t, "unverifiable", got["build"].Status) + require.NotEqual(t, "listed", got["build"].Status) + require.NotEqual(t, "not_listed", got["build"].Status) + require.Equal(t, "grok-4.7-build-fast", got["build-fast"].Upstream) + require.Equal(t, "listed", got["build-fast"].Status) +} + +func TestGrokModelDiagnosticsMediaAndVoiceStayOutOfScope(t *testing.T) { + account := grokDiagnosticExplicitAccount() + account.Credentials["model_mapping"] = map[string]any{ + "picture": "grok-imagine-image", + "clip": "grok-imagine-video", + "legacy": "grok-video-1.5", + "speak": "grok-voice-latest", + "hear": "xai/grok-tts", + } + scope := grokDiagnosticOfficialScope(t) + now := time.Date(2026, 10, 25, 7, 0, 0, 0, time.UTC) + + diag := EvaluateGrokModelDiagnostics(account, scope, grokDiagnosticFreshSnapshot(scope, now.Add(-time.Hour)), now) + + for _, item := range diag.Mappings { + require.Equal(t, "out_of_scope", item.Status, item.Requested) + require.NotEqual(t, "not_listed", item.Status) + } + got := diagnosticByRequested(diag.Mappings) + require.Equal(t, "grok-imagine-video", got["clip"].Upstream) + require.Equal(t, "grok-video-1.5", got["legacy"].Upstream) + require.Equal(t, "grok-voice-latest", got["speak"].Upstream) + require.Equal(t, "grok-tts", got["hear"].Upstream) +} + +func TestGrokModelDiagnosticsDefaultMappingIsReadOnly(t *testing.T) { + account := &Account{ID: 25, Platform: PlatformGrok, Type: AccountTypeOAuth} + scope := grokDiagnosticOfficialScope(t) + now := time.Date(2026, 10, 25, 7, 0, 0, 0, time.UTC) + + diag := EvaluateGrokModelDiagnostics(account, scope, grokDiagnosticFreshSnapshot(scope, now.Add(-time.Hour)), now) + + require.Nil(t, account.Credentials) + require.Nil(t, account.Extra) + got := diagnosticByRequested(diag.Mappings) + require.Equal(t, "listed", got["grok-4.7"].Status) + require.Equal(t, "grok-4.7", got["grok-4.7"].Upstream) + require.Equal(t, "not_listed", got["composer-2.5"].Status) + require.Equal(t, "grok-composer-2.5-fast", got["composer-2.5"].Upstream) + require.Equal(t, "out_of_scope", got["grok-imagine-image"].Status) + require.NotEmpty(t, diag.Mappings) +} + +func TestGrokModelDiagnosticsAPIKeyUsesOwnCatalog(t *testing.T) { + scope, err := NewGrokCatalogScope(25, AccountTypeAPIKey, "https://relay.example.com/v1/models?token=query-secret") + require.NoError(t, err) + account := &Account{ + ID: 25, Platform: PlatformGrok, Type: AccountTypeAPIKey, + Credentials: map[string]any{"model_mapping": map[string]any{ + "friendly": "grok-4.7", + "older": "grok-4.6", + "private": "private-model", + "seen": "seen-model", + "picture": "grok-imagine-image", + }}, + } + now := time.Date(2026, 10, 25, 7, 0, 0, 0, time.UTC) + snapshot := &GrokObservedModelsSnapshot{ + Models: []string{"grok-3", "seen-model"}, + FetchedAt: now.Add(-time.Hour).Format(time.RFC3339Nano), + Scope: scope, + } + + diag := EvaluateGrokModelDiagnostics(account, scope, snapshot, now) + + require.Equal(t, "fresh", diag.State) + require.Equal(t, "https://relay.example.com/v1/models", diag.Endpoint) + require.NotContains(t, diag.Endpoint, "query-secret") + require.NotContains(t, diag.Endpoint, "token") + got := diagnosticByRequested(diag.Mappings) + require.Equal(t, "not_listed", got["friendly"].Status) + require.Equal(t, "not_listed", got["older"].Status) + require.Equal(t, "unverifiable", got["private"].Status) + require.Equal(t, "listed", got["seen"].Status) + require.Equal(t, "seen-model", got["seen"].Upstream) + require.Equal(t, "out_of_scope", got["picture"].Status) + raw := grokDiagnosticJSON(t, diag) + require.NotContains(t, raw, "query-secret") +} + +func TestGrokModelDiagnosticsSourceMismatchDoesNotBorrowCatalog(t *testing.T) { + account := grokDiagnosticExplicitAccount() + now := time.Date(2026, 10, 25, 7, 0, 0, 0, time.UTC) + base := grokDiagnosticOfficialScope(t) + snapshot := grokDiagnosticFreshSnapshot(base, now.Add(-time.Hour)) + alternates := []*GrokCatalogScope{ + mustGrokDiagnosticScope(t, 26, AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models"), + mustGrokDiagnosticScope(t, 25, AccountTypeAPIKey, "https://cli-chat-proxy.grok.com/v1/models"), + mustGrokDiagnosticScope(t, 25, AccountTypeOAuth, "https://api.x.ai/v1/models"), + mustGrokDiagnosticScope(t, 25, AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models?foo=1"), + } + for _, current := range alternates { + diag := EvaluateGrokModelDiagnostics(account, current, snapshot, now) + require.Equal(t, "source_changed", diag.State) + require.Equal(t, snapshot.Models, diag.Models) + require.Equal(t, current.Endpoint, diag.Endpoint) + for _, item := range diag.Mappings { + require.NotEqual(t, "listed", item.Status, item.Requested) + require.NotEqual(t, "not_listed", item.Status, item.Requested) + } + require.Equal(t, "unverifiable", diagnosticByRequested(diag.Mappings)["friendly"].Status) + require.Equal(t, "out_of_scope", diagnosticByRequested(diag.Mappings)["grok-imagine-image"].Status) + } +} + +func TestGrokModelDiagnosticsUntrustedSnapshotsDoNotClaimAbsence(t *testing.T) { + account := grokDiagnosticExplicitAccount() + scope := grokDiagnosticOfficialScope(t) + now := time.Date(2026, 10, 25, 8, 0, 0, 0, time.UTC) + fetched := time.Date(2026, 10, 25, 2, 0, 0, 0, time.UTC) + models := []string{"grok-4.5", "grok-4.6", "grok-4.7", "grok-4.7-build-fast"} + + cases := []struct { + name string + snapshot *GrokObservedModelsSnapshot + state string + }{ + {name: "missing", snapshot: nil, state: "unknown"}, + {name: "legacy-without-scope", snapshot: &GrokObservedModelsSnapshot{Models: models, FetchedAt: fetched.Format(time.RFC3339Nano), Source: "upstream_v1_models"}, state: "unknown"}, + {name: "exactly-six-hours", snapshot: grokDiagnosticFreshSnapshot(scope, fetched), state: "stale"}, + {name: "older-than-six-hours", snapshot: grokDiagnosticFreshSnapshot(scope, fetched.Add(-time.Second)), state: "stale"}, + {name: "invalid-time", snapshot: &GrokObservedModelsSnapshot{Models: models, FetchedAt: "not-a-time", Scope: scope}, state: "unknown"}, + {name: "future-time", snapshot: grokDiagnosticFreshSnapshot(scope, now.Add(time.Minute)), state: "unknown"}, + {name: "empty-models", snapshot: &GrokObservedModelsSnapshot{Models: []string{" "}, FetchedAt: fetched.Format(time.RFC3339Nano), Scope: scope}, state: "unknown"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + diag := EvaluateGrokModelDiagnostics(account, scope, tc.snapshot, now) + requireDiagnosticArrays(t, diag) + require.Equal(t, tc.state, diag.State) + for _, item := range diag.Mappings { + require.NotEqual(t, "not_listed", item.Status, item.Requested) + } + }) + } + + justFresh := EvaluateGrokModelDiagnostics(account, scope, grokDiagnosticFreshSnapshot(scope, now.Add(-6*time.Hour+time.Nanosecond)), now) + require.Equal(t, "fresh", justFresh.State) + require.Equal(t, "not_listed", diagnosticByRequested(justFresh.Mappings)["composer-2.5"].Status) + + stale := EvaluateGrokModelDiagnostics(account, scope, grokDiagnosticFreshSnapshot(scope, fetched), now) + require.Equal(t, "stale", stale.State) + require.Equal(t, models, stale.Models) + require.Equal(t, "2026-10-25T02:00:00Z", stale.FetchedAt) + require.Equal(t, "2026-10-25T08:00:00Z", stale.ExpiresAt) + require.Equal(t, "listed", diagnosticByRequested(stale.Mappings)["friendly"].Status) + require.Equal(t, "unverifiable", diagnosticByRequested(stale.Mappings)["composer-2.5"].Status) +} + +func TestGrokModelDiagnosticsFailedAttemptDoesNotReplaceFreshSuccess(t *testing.T) { + account := grokDiagnosticExplicitAccount() + scope := grokDiagnosticOfficialScope(t) + now := time.Date(2026, 10, 25, 7, 0, 0, 0, time.UTC) + successAt := time.Date(2026, 10, 25, 2, 0, 0, 0, time.UTC) + snapshot := grokDiagnosticFreshSnapshot(scope, successAt) + snapshot.LastAttempt = &GrokCatalogAttempt{ + StartedAt: now.Add(-time.Minute).Format(time.RFC3339Nano), + FinishedAt: now.Format(time.RFC3339Nano), + Status: "failed", + ErrorCode: "http_error", + Scope: scope, + } + + diag := EvaluateGrokModelDiagnostics(account, scope, snapshot, now) + + require.Equal(t, "fresh", diag.State) + require.Equal(t, "2026-10-25T02:00:00Z", diag.FetchedAt) + require.NotEqual(t, diag.FetchedAt, diag.LastAttempt.FinishedAt) + require.Equal(t, "failed", diag.LastAttempt.Status) + require.Equal(t, "http_error", diag.LastAttempt.ErrorCode) + require.Equal(t, "not_listed", diagnosticByRequested(diag.Mappings)["composer-2.5"].Status) + require.Equal(t, "listed", diagnosticByRequested(diag.Mappings)["friendly"].Status) + diag.LastAttempt.Status = "mutated" + require.Equal(t, "failed", snapshot.LastAttempt.Status) +} + +func TestGrokModelDiagnosticsUnknownWithoutCurrentScope(t *testing.T) { + account := grokDiagnosticExplicitAccount() + now := time.Date(2026, 10, 25, 7, 0, 0, 0, time.UTC) + snapshot := grokDiagnosticFreshSnapshot(grokDiagnosticOfficialScope(t), now.Add(-time.Hour)) + + diag := EvaluateGrokModelDiagnostics(account, nil, snapshot, now) + + require.Equal(t, "unknown", diag.State) + require.Empty(t, diag.Endpoint) + require.Equal(t, snapshot.Models, diag.Models) + requireNoCatalogVerdict(t, diag.Mappings) + raw := grokDiagnosticJSON(t, diag) + require.Contains(t, raw, `"models":["grok-4.5","grok-4.6","grok-4.7","grok-4.7-build-fast"]`) + require.NotContains(t, raw, `"models":null`) + require.NotContains(t, raw, `"mappings":null`) +} + +func TestGetGrokModelDiagnosticsReadsScopeWithoutTokenOrHTTP(t *testing.T) { + upstream := &grokDiagnosticHTTPUpstream{} + proxyID := int64(9) + account := grokDiagnosticExplicitAccount() + account.ProxyID = &proxyID + account.Credentials["access_token"] = "access-secret" + account.Credentials["refresh_token"] = "refresh-secret" + now := time.Now().UTC().Add(-time.Hour) + scope := grokDiagnosticOfficialScope(t) + rememberGrokObservedSnapshot(account, grokDiagnosticFreshSnapshot(scope, now)) + svc := &AccountTestService{httpUpstream: upstream} + + diag := svc.GetGrokModelDiagnostics(context.Background(), account) + + require.Equal(t, "fresh", diag.State) + require.Equal(t, "https://cli-chat-proxy.grok.com/v1/models", diag.Endpoint) + require.Equal(t, "listed", diagnosticByRequested(diag.Mappings)["friendly"].Status) + require.Zero(t, upstream.calls) + raw := grokDiagnosticJSON(t, diag) + require.NotContains(t, raw, "access-secret") + require.NotContains(t, raw, "refresh-secret") + require.Nil(t, svc.GetGrokModelDiagnostics(context.Background(), &Account{ID: 3, Platform: PlatformOpenAI, Type: AccountTypeOAuth})) + require.Nil(t, svc.GetGrokModelDiagnostics(context.Background(), nil)) +} + +func TestGetGrokModelDiagnosticsUsesSettingBaseURLAndStripsSecrets(t *testing.T) { + settings := NewSettingService(&grokBaseURLSettingRepoStub{values: map[string]string{ + SettingKeyGrokDefaultBaseURLMode: GrokDefaultBaseURLModeUSWest2, + }}, nil) + account := &Account{ID: 25, Platform: PlatformGrok, Type: AccountTypeOAuth, Credentials: map[string]any{ + "model_mapping": map[string]any{"friendly": "grok-4.7"}, + "access_token": "access-secret", + }} + cliScope := grokDiagnosticOfficialScope(t) + rememberGrokObservedSnapshot(account, grokDiagnosticFreshSnapshot(cliScope, time.Now().UTC().Add(-time.Hour))) + svc := &AccountTestService{settingService: settings} + + diag := svc.GetGrokModelDiagnostics(context.Background(), account) + + require.Equal(t, "source_changed", diag.State) + require.Equal(t, "https://us-west-2.api.x.ai/v1/models", diag.Endpoint) + require.NotEqual(t, "not_listed", diagnosticByRequested(diag.Mappings)["friendly"].Status) + require.NotEqual(t, "listed", diagnosticByRequested(diag.Mappings)["friendly"].Status) + + apiAccount := &Account{ID: 25, Platform: PlatformGrok, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "api_key": "sk-secret", + "base_url": "https://user:s3cret@relay.example.com/v1?access_token=query-secret", + "model_mapping": map[string]any{"friendly": "grok-4.7"}, + }} + apiSvc := &AccountTestService{cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}}} + apiDiag := apiSvc.GetGrokModelDiagnostics(context.Background(), apiAccount) + require.Equal(t, "unknown", apiDiag.State) + require.Equal(t, "https://relay.example.com/v1/models", apiDiag.Endpoint) + raw := grokDiagnosticJSON(t, apiDiag) + require.NotContains(t, raw, "s3cret") + require.NotContains(t, raw, "query-secret") + require.NotContains(t, raw, "sk-secret") + require.NotContains(t, raw, "user:") +} + +func TestGetGrokModelDiagnosticsInvalidScopeStaysUnknown(t *testing.T) { + account := &Account{ID: 25, Platform: PlatformGrok, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "api_key": "sk-secret", + "base_url": "https://blocked.example/v1", + }} + svc := &AccountTestService{cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{ + Enabled: true, UpstreamHosts: []string{"api.x.ai"}, + }}}} + + diag := svc.GetGrokModelDiagnostics(context.Background(), account) + + require.Equal(t, "unknown", diag.State) + require.Empty(t, diag.Endpoint) + requireDiagnosticArrays(t, diag) + require.NotContains(t, grokDiagnosticJSON(t, diag), "sk-secret") +} + +func TestGrokModelDiagnosticsSnapshotDoesNotChangeMappingOrSupport(t *testing.T) { + account := &Account{ + ID: 25, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, + Credentials: map[string]any{"model_mapping": map[string]any{ + "grok-4.6": "grok-4.6", + "composer-2.5": "composer-2.5", + "custom-*": "grok-4.7", + }}, + } + requests := []string{"grok-4.6", "composer-2.5", "custom-model", "grok-4.7", "gpt-5"} + mappingBefore := account.GetModelMapping() + supportBefore := map[string]bool{} + for _, requested := range requests { + supportBefore[requested] = account.IsModelSupported(requested) + } + mappedBefore := map[string]string{} + for _, requested := range requests { + mappedBefore[requested] = account.GetMappedModel(requested) + } + credentialsBefore := cloneGrokDiagnosticValue(t, account.Credentials) + + rememberGrokObservedSnapshot(account, grokDiagnosticFreshSnapshot(grokDiagnosticOfficialScope(t), time.Now().UTC())) + _ = EvaluateGrokModelDiagnostics(account, grokDiagnosticOfficialScope(t), parseGrokObservedModels(account.Extra), time.Now().UTC()) + + require.Equal(t, mappingBefore, account.GetModelMapping()) + require.Equal(t, credentialsBefore, cloneGrokDiagnosticValue(t, account.Credentials)) + for _, requested := range requests { + require.Equal(t, supportBefore[requested], account.IsModelSupported(requested), requested) + require.Equal(t, mappedBefore[requested], account.GetMappedModel(requested), requested) + } + require.NotContains(t, account.Credentials, "grok_observed_models") +} + +func grokDiagnosticExplicitAccount() *Account { + return &Account{ + ID: 25, Platform: PlatformGrok, Type: AccountTypeOAuth, + Credentials: map[string]any{"model_mapping": map[string]any{ + "friendly": "grok-4.7", + "grok-4.7-latest": "grok-4.7-latest", + "composer-2.5": "composer-2.5", + "custom-*": "grok-4.7", + "grok-imagine-image": "grok-imagine-image", + }}, + } +} + +func grokDiagnosticOfficialScope(t *testing.T) *GrokCatalogScope { + t.Helper() + return mustGrokDiagnosticScope(t, 25, AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models") +} + +func mustGrokDiagnosticScope(t *testing.T, accountID int64, accountType, modelsURL string) *GrokCatalogScope { + t.Helper() + scope, err := NewGrokCatalogScope(accountID, accountType, modelsURL) + require.NoError(t, err) + return scope +} + +func grokDiagnosticFreshSnapshot(scope *GrokCatalogScope, fetched time.Time) *GrokObservedModelsSnapshot { + cloned := *scope + return &GrokObservedModelsSnapshot{ + Models: []string{"grok-4.5", "grok-4.6", "grok-4.7", "grok-4.7-build-fast"}, + FetchedAt: fetched.UTC().Format(time.RFC3339Nano), + Scope: &cloned, + } +} + +func diagnosticByRequested(items []GrokModelDiagnosticItem) map[string]GrokModelDiagnosticItem { + out := make(map[string]GrokModelDiagnosticItem, len(items)) + for _, item := range items { + out[item.Requested] = item + } + return out +} + +func requireDiagnosticSorted(t *testing.T, items []GrokModelDiagnosticItem) { + t.Helper() + for i := 1; i < len(items); i++ { + require.LessOrEqual(t, items[i-1].Requested, items[i].Requested) + } +} + +func requireDiagnosticArrays(t *testing.T, diag *GrokModelDiagnostics) { + t.Helper() + require.NotNil(t, diag) + require.NotNil(t, diag.Models) + require.NotNil(t, diag.Mappings) + raw := grokDiagnosticJSON(t, diag) + require.NotContains(t, raw, `"models":null`) + require.NotContains(t, raw, `"mappings":null`) + require.Contains(t, raw, `"models":[`) + require.Contains(t, raw, `"mappings":[`) +} + +func requireNoCatalogVerdict(t *testing.T, items []GrokModelDiagnosticItem) { + t.Helper() + for _, item := range items { + require.NotEqual(t, "listed", item.Status, item.Requested) + require.NotEqual(t, "not_listed", item.Status, item.Requested) + } +} + +func grokDiagnosticJSON(t *testing.T, value any) string { + t.Helper() + raw, err := json.Marshal(value) + require.NoError(t, err) + return string(raw) +} + +func cloneGrokDiagnosticValue(t *testing.T, value any) any { + t.Helper() + raw, err := json.Marshal(value) + require.NoError(t, err) + var cloned any + require.NoError(t, json.Unmarshal(raw, &cloned)) + return cloned +} + +type grokDiagnosticHTTPUpstream struct { + calls int +} + +func (u *grokDiagnosticHTTPUpstream) Do(*http.Request, string, int64, int) (*http.Response, error) { + u.calls++ + return nil, errors.New("diagnostics must not call upstream") +} + +func (u *grokDiagnosticHTTPUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, accountConcurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return u.Do(req, proxyURL, accountID, accountConcurrency) +} diff --git a/backend/internal/service/grok_observed_models.go b/backend/internal/service/grok_observed_models.go index 3dba5f0013..23700bdd19 100644 --- a/backend/internal/service/grok_observed_models.go +++ b/backend/internal/service/grok_observed_models.go @@ -3,6 +3,8 @@ package service import ( "context" "encoding/json" + "errors" + "fmt" "io" "log/slog" "net/http" @@ -11,7 +13,6 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/pkg/xai" - "github.com/tidwall/gjson" ) const ( @@ -20,11 +21,7 @@ const ( grokObservedModelsTimeout = 15 * time.Second ) -type grokObservedModelsSnapshot struct { - Models []string `json:"models"` - FetchedAt string `json:"fetched_at"` - Source string `json:"source,omitempty"` -} +type grokObservedModelsSnapshot = GrokObservedModelsSnapshot var grokObservedModelsFlight sync.Map // accountID -> *singleflight-ish in-flight @@ -46,7 +43,12 @@ func (s *GrokQuotaService) scheduleGrokObservedModelsSync(account *Account) { ctx, cancel := context.WithTimeout(context.Background(), grokObservedModelsTimeout) defer cancel() if err := s.syncGrokObservedModels(ctx, &acc); err != nil { - slog.Debug("grok_observed_models_sync_failed", "account_id", id, "error", err) + kind, statusCode := grokObservedModelsSyncLogFields(err) + slog.Debug("grok_observed_models_sync_failed", + "account_id", id, + "error_kind", kind, + "status_code", statusCode, + ) } }() } @@ -55,12 +57,58 @@ func (s *GrokQuotaService) syncGrokObservedModels(ctx context.Context, account * if s == nil || account == nil { return nil } - // Skip if snapshot is still fresh. - if snap := parseGrokObservedModels(account.Extra); snap != nil { - if t, err := time.Parse(time.RFC3339, snap.FetchedAt); err == nil && time.Since(t) < grokObservedModelsTTL { - return nil - } + started := time.Now().UTC() + req, proxyURL, err := s.prepareGrokObservedModelsRequest(ctx, account) + if err != nil { + return s.finishGrokObservedModelsAttempt(ctx, account, nil, started, err) } + if req == nil { + return nil + } + scope := grokCatalogScopeFromRequest(account, req) + if grokObservedSnapshotFresh(parseGrokObservedModels(account.Extra), scope, time.Now().UTC()) { + return nil + } + resp, err := s.httpUpstream.Do(req, proxyURL, account.ID, account.Concurrency) + if err != nil { + return s.finishGrokObservedModelsAttempt(ctx, account, req, started, newUpstreamModelSyncUpstreamError("Failed to request upstream model list", err)) + } + defer func() { _ = resp.Body.Close() }() + + limit := resolveModelsListReadLimit(s.cfg) + body, err := io.ReadAll(io.LimitReader(resp.Body, limit+1)) + if err != nil { + return s.finishGrokObservedModelsAttempt(ctx, account, req, started, newUpstreamModelSyncUpstreamError("Failed to read upstream model list", err)) + } + if int64(len(body)) > limit { + return s.finishGrokObservedModelsAttempt(ctx, account, req, started, newUpstreamModelSyncUpstreamError("Upstream model list response is too large", fmt.Errorf("response exceeds %d bytes", limit))) + } + if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { + return s.finishGrokObservedModelsAttempt(ctx, account, req, started, &UpstreamModelSyncError{ + Kind: UpstreamModelSyncErrorUpstream, + Message: fmt.Sprintf("Upstream model list request failed with HTTP %d", resp.StatusCode), + StatusCode: resp.StatusCode, + Err: fmt.Errorf("upstream model list returned HTTP %d", resp.StatusCode), + }) + } + ids, err := extractGrokModelIDsFromModelsBody(body) + if err != nil { + if errors.Is(err, errGrokCatalogEmpty) { + return s.finishGrokObservedModelsAttempt(ctx, account, req, started, newUpstreamModelSyncUpstreamError("Upstream returned no supported models", err)) + } + return s.finishGrokObservedModelsAttempt(ctx, account, req, started, newUpstreamModelSyncUpstreamError("Upstream model list response was not valid JSON", err)) + } + if len(ids) == 0 { + return s.finishGrokObservedModelsAttempt(ctx, account, req, started, newUpstreamModelSyncUpstreamError("Upstream returned no supported models", errGrokCatalogEmpty)) + } + observation := buildGrokCatalogObservation(account, req, started, ids, nil) + if err := s.saveGrokObservedObservation(ctx, account, &observation); err != nil { + return newUpstreamModelSyncInternalError("Failed to save upstream model catalog", err) + } + return nil +} + +func (s *GrokQuotaService) prepareGrokObservedModelsRequest(ctx context.Context, account *Account) (*http.Request, string, error) { token := strings.TrimSpace(account.GetGrokAccessToken()) if token == "" && s.tokenProvider != nil { // Best-effort warm; avoid forcing refresh storms. @@ -69,7 +117,7 @@ func (s *GrokQuotaService) syncGrokObservedModels(ctx context.Context, account * } } if token == "" { - return nil + return nil, "", newUpstreamModelSyncConfigError("No Grok access token is available", nil) } baseURL := strings.TrimSpace(account.GetGrokBaseURL()) if s.settingService != nil { @@ -80,15 +128,15 @@ func (s *GrokQuotaService) syncGrokObservedModels(ctx context.Context, account * } validator, err := grokBaseURLValidator(account, s.cfg) if err != nil { - return err + return nil, "", newUpstreamModelSyncConfigError("Invalid Grok base URL", err) } validatedBaseURL, err := validator(baseURL) if err != nil { - return err + return nil, "", newUpstreamModelSyncConfigError("Invalid Grok base URL", err) } req, err := http.NewRequestWithContext(ctx, http.MethodGet, buildOpenAIModelsURL(validatedBaseURL), nil) if err != nil { - return err + return nil, "", newUpstreamModelSyncConfigError("Invalid Grok model list URL", err) } req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Accept", "application/json") @@ -113,66 +161,36 @@ func (s *GrokQuotaService) syncGrokObservedModels(ctx context.Context, account * } } if s.httpUpstream == nil { - return nil + return nil, "", nil } - resp, err := s.httpUpstream.Do(req, proxyURL, account.ID, account.Concurrency) - if err != nil { - return err - } - defer func() { _ = resp.Body.Close() }() - body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) - if err != nil { - return err - } - if resp.StatusCode >= 400 { - return nil - } - ids := extractGrokModelIDsFromModelsBody(body) - if len(ids) == 0 { - return nil - } - snap := grokObservedModelsSnapshot{ - Models: ids, - FetchedAt: time.Now().UTC().Format(time.RFC3339), - Source: "upstream_v1_models", - } - raw, err := json.Marshal(snap) - if err != nil { - return err - } - var asMap map[string]any - if err := json.Unmarshal(raw, &asMap); err != nil { - return err - } - return s.accountRepo.UpdateExtra(ctx, account.ID, map[string]any{ - grokObservedModelsExtraKey: asMap, - }) + return req, proxyURL, nil } -func extractGrokModelIDsFromModelsBody(body []byte) []string { - data := gjson.GetBytes(body, "data") - if !data.IsArray() { - // Some gateways return a bare array. - data = gjson.ParseBytes(body) +func (s *GrokQuotaService) finishGrokObservedModelsAttempt(ctx context.Context, account *Account, req *http.Request, started time.Time, cause error) error { + observation := buildGrokCatalogObservation(account, req, started, nil, cause) + if err := s.saveGrokObservedObservation(ctx, account, &observation); err != nil { + slog.Warn("grok model catalog observation was not saved", + "account_id", account.ID, + "error", err, + ) } - seen := make(map[string]struct{}) - var out []string - data.ForEach(func(_, v gjson.Result) bool { - id := strings.TrimSpace(v.Get("id").String()) - if id == "" { - id = strings.TrimSpace(v.String()) - } - if id == "" { - return true - } - if _, ok := seen[id]; ok { - return true - } - seen[id] = struct{}{} - out = append(out, id) - return true - }) - return out + return cause +} + +func (s *GrokQuotaService) saveGrokObservedObservation(ctx context.Context, account *Account, observation *GrokCatalogObservation) error { + if s == nil || account == nil || account.ID <= 0 || observation == nil || s.accountRepo == nil { + return nil + } + snap, err := PersistGrokCatalogObservation(ctx, s.accountRepo, account.ID, *observation) + if err != nil { + return err + } + rememberGrokObservedSnapshot(account, snap) + return nil +} + +func extractGrokModelIDsFromModelsBody(body []byte) ([]string, error) { + return parseGrokCatalogModelIDs(body) } func parseGrokObservedModels(extra map[string]any) *grokObservedModelsSnapshot { @@ -191,8 +209,119 @@ func parseGrokObservedModels(extra map[string]any) *grokObservedModelsSnapshot { if err := json.Unmarshal(b, &snap); err != nil { return nil } - if len(snap.Models) == 0 { + if len(snap.Models) == 0 && snap.LastAttempt == nil { return nil } return &snap } + +func buildGrokCatalogObservation(account *Account, req *http.Request, started time.Time, models []string, cause error) GrokCatalogObservation { + finished := time.Now().UTC() + if !started.IsZero() && finished.Before(started) { + finished = started + } + if started.IsZero() { + started = finished + } + attempt := GrokCatalogAttempt{ + StartedAt: started.UTC().Format(time.RFC3339Nano), + FinishedAt: finished.UTC().Format(time.RFC3339Nano), + Scope: grokCatalogScopeFromRequest(account, req), + } + if cause == nil { + attempt.Status = grokCatalogStatusSuccess + return GrokCatalogObservation{Models: append([]string(nil), models...), Attempt: attempt} + } + attempt.Status = grokCatalogStatusFailed + attempt.ErrorCode = grokCatalogErrorCode(cause) + return GrokCatalogObservation{Attempt: attempt} +} + +func grokCatalogScopeFromRequest(account *Account, req *http.Request) *GrokCatalogScope { + if account == nil || req == nil || req.URL == nil { + return nil + } + scope, err := NewGrokCatalogScope(account.ID, account.Type, req.URL.String()) + if err != nil { + return nil + } + return scope +} + +func grokObservedModelsSyncLogFields(err error) (string, int) { + var syncErr *UpstreamModelSyncError + if errors.As(err, &syncErr) { + return string(syncErr.Kind), syncErr.StatusCode + } + return "transport", 0 +} + +func grokCatalogErrorCode(err error) string { + if errors.Is(err, errGrokCatalogEmpty) { + return "empty_catalog" + } + var syncErr *UpstreamModelSyncError + if !errors.As(err, &syncErr) { + return "transport" + } + switch syncErr.Kind { + case UpstreamModelSyncErrorConfiguration, UpstreamModelSyncErrorUnsupported: + return "configuration" + case UpstreamModelSyncErrorInternal: + return "persistence" + } + switch { + case strings.Contains(syncErr.Message, "too large"): + return "too_large" + case strings.Contains(syncErr.Message, "no supported models"): + return "empty_catalog" + case strings.Contains(syncErr.Message, "not valid JSON"): + return "invalid_response" + case syncErr.StatusCode != 0: + return "http_error" + default: + return "transport" + } +} + +func grokObservedSnapshotFresh(snap *GrokObservedModelsSnapshot, scope *GrokCatalogScope, now time.Time) bool { + if snap == nil || scope == nil || strings.TrimSpace(scope.Fingerprint) == "" || !grokCatalogHasModelID(snap.Models) { + return false + } + if snap.Scope == nil || snap.Scope.Fingerprint != scope.Fingerprint { + return false + } + fetched, ok := parseGrokCatalogTimestamp(snap.FetchedAt) + if !ok || fetched.After(now) { + return false + } + return now.Sub(fetched) < grokObservedModelsTTL +} + +func parseGrokCatalogTimestamp(value string) (time.Time, bool) { + for _, layout := range []string{time.RFC3339Nano, time.RFC3339} { + parsed, err := time.Parse(layout, strings.TrimSpace(value)) + if err == nil { + return parsed, true + } + } + return time.Time{}, false +} + +func rememberGrokObservedSnapshot(account *Account, snap *GrokObservedModelsSnapshot) { + if account == nil || snap == nil { + return + } + raw, err := json.Marshal(snap) + if err != nil { + return + } + var decoded map[string]any + if err := json.Unmarshal(raw, &decoded); err != nil { + return + } + if account.Extra == nil { + account.Extra = map[string]any{} + } + account.Extra[grokObservedModelsExtraKey] = decoded +} diff --git a/backend/internal/service/grok_observed_models_log_test.go b/backend/internal/service/grok_observed_models_log_test.go new file mode 100644 index 0000000000..f62eb98410 --- /dev/null +++ b/backend/internal/service/grok_observed_models_log_test.go @@ -0,0 +1,137 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "fmt" + "log/slog" + "net/http" + "net/url" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + "github.com/stretchr/testify/require" +) + +type grokCatalogLogProxyRepo struct { + ProxyRepository + proxy *Proxy +} + +func (r grokCatalogLogProxyRepo) GetByID(context.Context, int64) (*Proxy, error) { + return r.proxy, nil +} + +type grokCatalogLoggingUpstream struct { + proxyURL string + request *http.Request +} + +func (u *grokCatalogLoggingUpstream) Do(req *http.Request, proxyURL string, _ int64, _ int) (*http.Response, error) { + u.proxyURL = proxyURL + u.request = req + // net/http puts the request URL on *url.Error. Include query and userinfo + // here because a custom endpoint can carry both, while the proxy failure is + // attached separately and may contain proxy credentials. + return nil, &url.Error{ + Op: "Get", + URL: "https://relay-user:query-userinfo-secret@relay.example.test/v1/models?api_key=review-query-marker", + Err: fmt.Errorf("proxy %s: dial failed", proxyURL), + } +} + +func (u *grokCatalogLoggingUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, accountConcurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return u.Do(req, proxyURL, accountID, accountConcurrency) +} + +type grokCatalogLogHandler struct { + inner slog.Handler + done chan struct{} +} + +func (h *grokCatalogLogHandler) Enabled(ctx context.Context, level slog.Level) bool { + return h.inner.Enabled(ctx, level) +} + +func (h *grokCatalogLogHandler) Handle(ctx context.Context, record slog.Record) error { + err := h.inner.Handle(ctx, record) + if record.Message == "grok_observed_models_sync_failed" { + select { + case h.done <- struct{}{}: + default: + } + } + return err +} + +func (h *grokCatalogLogHandler) WithAttrs(attrs []slog.Attr) slog.Handler { + return &grokCatalogLogHandler{inner: h.inner.WithAttrs(attrs), done: h.done} +} + +func (h *grokCatalogLogHandler) WithGroup(name string) slog.Handler { + return &grokCatalogLogHandler{inner: h.inner.WithGroup(name), done: h.done} +} + +func TestGrokBackgroundCatalogLogDoesNotExpandTransportURL(t *testing.T) { + var buf bytes.Buffer + handler := &grokCatalogLogHandler{ + inner: slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}), + done: make(chan struct{}, 1), + } + previous := slog.Default() + slog.SetDefault(slog.New(handler)) + t.Cleanup(func() { slog.SetDefault(previous) }) + + account := grokOAuthModelSyncTestAccount("https://relay-user:query-userinfo-secret@relay.example.test/v1?api_key=review-query-marker") + account.ID = 917283 + proxyID := int64(7) + account.ProxyID = &proxyID + proxy := &Proxy{ + ID: proxyID, + Protocol: "http", + Host: "proxy.example.test", + Port: 3128, + Username: "proxy-user", + Password: "proxy-pass-marker", + Status: StatusActive, + } + repo := newGrokCatalogMemoryRepo(account) + upstream := &grokCatalogLoggingUpstream{} + svc := &GrokQuotaService{ + accountRepo: repo, + proxyRepo: grokCatalogLogProxyRepo{proxy: proxy}, + httpUpstream: upstream, + cfg: upstreamModelSyncTestConfig(), + } + + svc.scheduleGrokObservedModelsSync(account) + select { + case <-handler.done: + case <-time.After(5 * time.Second): + t.Fatal("background catalog log missing") + } + + logged := buf.String() + require.NotContains(t, logged, "review-query-marker") + require.NotContains(t, logged, "query-userinfo-secret") + require.NotContains(t, logged, "proxy-pass-marker") + require.NotContains(t, logged, "relay-user") + require.Contains(t, logged, "account_id=917283") + require.Contains(t, logged, "error_kind=upstream") + require.Contains(t, logged, "status_code=0") + require.NotContains(t, logged, "error=") + require.NotNil(t, upstream.request) + require.Contains(t, upstream.proxyURL, "proxy-pass-marker") + + stored, err := repo.GetByID(context.Background(), account.ID) + require.NoError(t, err) + snapshot := parseGrokObservedModels(stored.Extra) + require.NotNil(t, snapshot) + require.NotNil(t, snapshot.LastAttempt) + require.Equal(t, grokCatalogStatusFailed, snapshot.LastAttempt.Status) + require.Equal(t, "transport", snapshot.LastAttempt.ErrorCode) + require.Empty(t, snapshot.Models) +} diff --git a/backend/internal/service/grok_p2_test.go b/backend/internal/service/grok_p2_test.go index 2be382d26e..f582ce92cc 100644 --- a/backend/internal/service/grok_p2_test.go +++ b/backend/internal/service/grok_p2_test.go @@ -59,8 +59,9 @@ func TestGrokStickyAffinitySeed_ScopesByModel(t *testing.T) { func TestExtractGrokModelIDsFromModelsBody(t *testing.T) { body := []byte(`{"object":"list","data":[{"id":"grok-4.5"},{"id":"grok-4.3"},{"id":"grok-4.5"}]}`) - ids := extractGrokModelIDsFromModelsBody(body) - require.Equal(t, []string{"grok-4.5", "grok-4.3"}, ids) + ids, err := extractGrokModelIDsFromModelsBody(body) + require.NoError(t, err) + require.Equal(t, []string{"grok-4.3", "grok-4.5"}, ids) } func TestAccountGrokNeedsReauth(t *testing.T) { diff --git a/backend/internal/service/grok_quota_service_test.go b/backend/internal/service/grok_quota_service_test.go index af27b67f12..7aa8558808 100644 --- a/backend/internal/service/grok_quota_service_test.go +++ b/backend/internal/service/grok_quota_service_test.go @@ -5,6 +5,7 @@ package service import ( "bytes" "context" + "encoding/json" "errors" "io" "log/slog" @@ -61,6 +62,39 @@ func (r *grokQuotaAccountRepo) UpdateExtra(_ context.Context, id int64, updates return nil } +func (r *grokQuotaAccountRepo) CompareAndSwapGrokObservedModels(ctx context.Context, id int64, expected, next json.RawMessage) (bool, error) { + if err := ctx.Err(); err != nil { + return false, err + } + if r == nil || r.mockAccountRepoForPlatform == nil { + return false, nil + } + account := r.accountsByID[id] + if account == nil || account.ID != id || account.Platform != PlatformGrok { + return false, nil + } + var current any + if account.Extra != nil { + current = account.Extra[grokObservedModelsExtraKey] + } + currentJSON, err := json.Marshal(current) + if err != nil { + return false, err + } + if !jsonValuesEqual(currentJSON, expected) { + return false, nil + } + var decoded any + if err := json.Unmarshal(next, &decoded); err != nil { + return false, err + } + if account.Extra == nil { + account.Extra = map[string]any{} + } + account.Extra[grokObservedModelsExtraKey] = decoded + return true, nil +} + func (r *grokQuotaAccountRepo) SetRateLimited(_ context.Context, id int64, resetAt time.Time) error { r.rateLimitedCalls++ r.lastRateLimitedID = id @@ -139,7 +173,7 @@ func TestSyncGrokObservedModelsUsesCLIIdentityAndAccountHeaders(t *testing.T) { require.Equal(t, "interactive", upstream.lastReq.Header.Get("X-Grok-Client-Mode")) require.Equal(t, "user-902", upstream.lastReq.Header.Get("X-UserID")) require.Equal(t, "user902@example.test", upstream.lastReq.Header.Get("X-Email")) - require.Contains(t, repo.updates[account.ID], grokObservedModelsExtraKey) + require.Equal(t, []string{"grok-4.5"}, parseGrokObservedModels(account.Extra).Models) } type grokQuotaProxyRepo struct { diff --git a/backend/internal/service/grok_response_model_audit_test.go b/backend/internal/service/grok_response_model_audit_test.go new file mode 100644 index 0000000000..bda076a557 --- /dev/null +++ b/backend/internal/service/grok_response_model_audit_test.go @@ -0,0 +1,630 @@ +//go:build unit + +package service + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestGrokResponseAuditNativeJSON(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"id":"resp_audit","object":"response","model":"grok-4.5-build","output":[],"usage":{"input_tokens":2,"output_tokens":1}}`)), + }} + account := &Account{ID: 53, Platform: PlatformGrok, Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "test-key", "base_url": "https://api.x.ai/v1"}} + svc := &OpenAIGatewayService{httpUpstream: upstream} + body := []byte(`{"model":"composer-2.5","input":"hi","stream":false}`) + result, err := svc.forwardGrokResponses(context.Background(), c, account, body, "composer-2.5", false, time.Now()) + require.NoError(t, err) + require.Equal(t, "grok-composer-2.5-fast", result.UpstreamModel) + require.Equal(t, "grok-4.5-build", result.UpstreamResponseModel) + require.Equal(t, "composer-2.5", result.Model) + require.Contains(t, rec.Body.String(), `"model":"composer-2.5"`) + require.True(t, *upstreamModelMismatch(result.UpstreamModel, result.UpstreamResponseModel)) +} + +func TestGrokResponseAuditNativeProtocols(t *testing.T) { + cases := []struct { + name, requested, returned string + stream bool + mismatchNil bool + mismatch bool + clientModel string + }{ + {name: "native-sse", requested: "composer-2.5", returned: "grok-4.5-build", stream: true, mismatch: true, clientModel: "composer-2.5"}, + {name: "native-json", requested: "composer-2.5", returned: "grok-4.5-build", stream: false, mismatch: true, clientModel: "composer-2.5"}, + {name: "normal-alias", requested: "grok-4.7", returned: "grok-4.7-build", stream: true, clientModel: "grok-4.7-build"}, + {name: "missing-model", requested: "grok-4.7", returned: "", stream: false, mismatchNil: true}, + } + for i, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + c, rec := grokAuditContext("/v1/responses") + var body string + contentType := "application/json" + if tt.stream { + contentType = "text/event-stream" + body = grokAuditResponsesSSE("", tt.returned) + } else { + body = grokAuditResponsesJSON(tt.returned) + } + upstream := &httpUpstreamRecorder{resp: grokAuditHTTPResponse(contentType, body)} + request := []byte(fmt.Sprintf(`{"model":%q,"input":"hi","stream":%t}`, tt.requested, tt.stream)) + result, err := (&OpenAIGatewayService{httpUpstream: upstream}).Forward(context.Background(), c, grokAuditAPIKeyAccount(88100+int64(i)), request) + require.NoError(t, err) + require.Equal(t, tt.requested, result.Model) + require.Equal(t, tt.stream, result.Stream) + require.Equal(t, tt.returned, result.UpstreamResponseModel) + require.False(t, result.UpstreamResponseModelConflict) + requireObservedMismatch(t, result, tt.mismatchNil, tt.mismatch) + client := rec.Body.String() + if tt.clientModel == "" { + require.False(t, gjson.Get(client, "model").Exists()) + return + } + require.Contains(t, client, `"model":"`+tt.clientModel+`"`) + if tt.returned != "" && tt.clientModel != tt.returned { + require.NotContains(t, client, tt.returned) + } + }) + } +} + +func TestGrokResponseAuditNativeNonStreamingSSE(t *testing.T) { + c, rec := grokAuditContext("/v1/responses") + upstream := &httpUpstreamRecorder{resp: grokAuditHTTPResponse("text/event-stream", grokAuditResponsesSSE("", "grok-4.5-build"))} + request := []byte(`{"model":"composer-2.5","input":"hi","stream":false}`) + result, err := (&OpenAIGatewayService{httpUpstream: upstream}).Forward(context.Background(), c, grokAuditAPIKeyAccount(88201), request) + require.NoError(t, err) + require.False(t, result.Stream) + require.Equal(t, "grok-composer-2.5-fast", result.UpstreamModel) + require.Equal(t, "grok-4.5-build", result.UpstreamResponseModel) + require.False(t, result.UpstreamResponseModelConflict) + require.True(t, *upstreamModelMismatch(result.UpstreamModel, result.UpstreamResponseModel)) + client := rec.Body.String() + require.True(t, gjson.Valid(client), "non-streaming client should receive aggregated JSON, got %s", client) + require.Equal(t, "composer-2.5", gjson.Get(client, "model").String()) + require.NotContains(t, client, "grok-4.5-build") +} + +func TestGrokResponseAuditNativeEventConflict(t *testing.T) { + for _, stream := range []bool{true, false} { + t.Run(fmt.Sprintf("stream=%t", stream), func(t *testing.T) { + c, rec := grokAuditContext("/v1/responses") + upstream := &httpUpstreamRecorder{resp: grokAuditHTTPResponse("text/event-stream", grokAuditResponsesSSE("grok-4.5", "grok-4.7-build"))} + request := []byte(fmt.Sprintf(`{"model":"composer-2.5","input":"hi","stream":%t}`, stream)) + result, err := (&OpenAIGatewayService{httpUpstream: upstream}).Forward(context.Background(), c, grokAuditAPIKeyAccount(88210), request) + require.NoError(t, err) + require.Equal(t, "grok-4.7-build", result.UpstreamResponseModel) + require.True(t, result.UpstreamResponseModelConflict) + client := rec.Body.String() + require.Contains(t, client, `"model":"composer-2.5"`) + require.NotContains(t, client, "grok-4.7-build") + require.NotContains(t, client, "grok-4.5") + }) + } +} + +func TestGrokResponseAuditForwardDoesNotLeakPreviousObservation(t *testing.T) { + c, rec := grokAuditContext("/v1/responses") + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + grokAuditHTTPResponse("application/json", grokAuditResponsesJSON("grok-4.5-build")), + grokAuditHTTPResponse("application/json", grokAuditResponsesJSON("")), + }} + svc := &OpenAIGatewayService{httpUpstream: upstream} + account := grokAuditAPIKeyAccount(88301) + first, err := svc.Forward(context.Background(), c, account, []byte(`{"model":"grok-4.7","input":"hi","stream":false}`)) + require.NoError(t, err) + require.Equal(t, "grok-4.5-build", first.UpstreamResponseModel) + + secondRec := grokAuditSwapWriter(c) + second, err := svc.Forward(context.Background(), c, account, []byte(`{"model":"grok-4.7","input":"again","stream":false}`)) + require.NoError(t, err) + require.Empty(t, second.UpstreamResponseModel) + require.False(t, second.UpstreamResponseModelConflict) + require.Nil(t, upstreamModelMismatch(second.UpstreamModel, second.UpstreamResponseModel)) + require.False(t, gjson.Get(secondRec.Body.String(), "model").Exists()) + require.NotContains(t, secondRec.Body.String(), "grok-4.5-build") + require.Contains(t, rec.Body.String(), "grok-4.5-build") +} + +func TestGrokResponseAuditRetryDoesNotKeepFailedAttemptModel(t *testing.T) { + c, _ := grokAuditContext("/v1/responses") + body := []byte(`{"model":"grok-4.7","previous_response_id":"resp_valid_history","input":[{"type":"reasoning","summary":[{"type":"summary_text","text":"keep this summary"}],"encrypted_content":"encrypted-reasoning"},{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}],"stream":false}`) + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + { + StatusCode: http.StatusBadRequest, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"code":"invalid-argument","error":"Could not decrypt the provided encrypted_content. Ensure the value is unmodified.","model":"grok-failed-attempt"}`)), + }, + grokAuditHTTPResponse("application/json", grokAuditResponsesJSON("grok-4.5-build")), + }} + result, err := (&OpenAIGatewayService{httpUpstream: upstream}).Forward(context.Background(), c, grokAuditAPIKeyAccount(88401), body) + require.NoError(t, err) + require.Len(t, upstream.requests, 2) + require.Equal(t, "grok-4.5-build", result.UpstreamResponseModel) + require.False(t, result.UpstreamResponseModelConflict) +} + +func TestGrokResponseAuditAccountFailoverDoesNotKeepFailedAttemptModel(t *testing.T) { + c, _ := grokAuditContext("/v1/responses") + first := healthyGrokOAuthGatewayTestAccount(88501, "access-token-a") + second := healthyGrokOAuthGatewayTestAccount(88502, "access-token-b") + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + { + StatusCode: http.StatusServiceUnavailable, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"temporary"},"model":"grok-failed-attempt"}`)), + }, + grokAuditHTTPResponse("application/json", grokAuditResponsesJSON("grok-4.7-build")), + }} + svc := grokAuditOAuthService(upstream, first, second) + body := []byte(`{"model":"grok-4.7","input":"hi","stream":false}`) + _, err := svc.Forward(context.Background(), c, first, body) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + + secondRec := grokAuditSwapWriter(c) + result, err := svc.Forward(context.Background(), c, second, body) + require.NoError(t, err) + require.Equal(t, "grok-4.7-build", result.UpstreamResponseModel) + require.False(t, result.UpstreamResponseModelConflict) + require.NotContains(t, secondRec.Body.String(), "grok-failed-attempt") +} + +func TestGrokResponseAuditChatRaw(t *testing.T) { + tests := []struct { + name string + stream bool + }{ + {name: "json", stream: false}, + {name: "sse", stream: true}, + } + for i, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c, rec := grokAuditContext("/v1/chat/completions") + var resp *http.Response + if tt.stream { + resp = grokAuditHTTPResponse("text/event-stream", grokAuditChatSSE("grok-4.5-build")) + } else { + resp = grokAuditHTTPResponse("application/json", grokAuditChatJSON("grok-4.5-build")) + } + upstream := &httpUpstreamRecorder{resp: resp} + request := []byte(fmt.Sprintf(`{"model":"composer-2.5","messages":[{"role":"user","content":"hi"}],"stream":%t}`, tt.stream)) + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + result, err := svc.ForwardAsChatCompletions(context.Background(), c, grokAuditAPIKeyAccount(88600+int64(i)), request, "", "") + require.NoError(t, err) + require.Equal(t, "https://api.x.ai/v1/chat/completions", upstream.lastReq.URL.String()) + require.Equal(t, "grok-composer-2.5-fast", result.UpstreamModel) + require.Equal(t, "grok-4.5-build", result.UpstreamResponseModel) + require.False(t, result.UpstreamResponseModelConflict) + require.True(t, *upstreamModelMismatch(result.UpstreamModel, result.UpstreamResponseModel)) + require.Contains(t, rec.Body.String(), `"model":"composer-2.5"`) + require.NotContains(t, rec.Body.String(), "grok-4.5-build") + }) + } +} + +func TestGrokResponseAuditChatBridge(t *testing.T) { + for i, stream := range []bool{false, true} { + name := "aggregate" + if stream { + name = "stream" + } + t.Run(name, func(t *testing.T) { + c, rec := grokAuditContext("/v1/chat/completions") + account := healthyGrokOAuthGatewayTestAccount(88700+int64(i), "access-token") + upstream := &httpUpstreamRecorder{resp: grokAuditHTTPResponse("text/event-stream", grokAuditResponsesSSE("", "grok-4.7-build"))} + request := []byte(fmt.Sprintf(`{"model":"grok-4.7","messages":[{"role":"user","content":"hi"}],"stream":%t,"prompt_cache_key":"stable-session"}`, stream)) + result, err := grokAuditOAuthService(upstream, account).ForwardAsChatCompletions(context.Background(), c, account, request, "", "") + require.NoError(t, err) + require.Equal(t, grokChatResponsesEndpoint, result.UpstreamEndpoint) + require.Contains(t, upstream.lastReq.URL.String(), "/responses") + require.Equal(t, "grok-4.7", result.UpstreamModel) + require.Equal(t, "grok-4.7-build", result.UpstreamResponseModel) + require.False(t, result.UpstreamResponseModelConflict) + mismatch := upstreamModelMismatch(result.UpstreamModel, result.UpstreamResponseModel) + require.NotNil(t, mismatch) + require.False(t, *mismatch) + require.Contains(t, rec.Body.String(), `"model":"grok-4.7"`) + require.NotContains(t, rec.Body.String(), "grok-4.7-build") + }) + } +} + +func TestGrokResponseAuditMessages(t *testing.T) { + for i, stream := range []bool{false, true} { + name := "aggregate" + if stream { + name = "stream" + } + t.Run(name, func(t *testing.T) { + c, rec := grokAuditContext("/v1/messages") + account := healthyGrokOAuthGatewayTestAccount(88800+int64(i), "access-token") + upstream := &httpUpstreamRecorder{resp: grokAuditHTTPResponse("text/event-stream", grokAuditResponsesSSE("", "grok-4.7-build"))} + request := []byte(fmt.Sprintf(`{"model":"grok-4.7","max_tokens":32,"stream":%t,"messages":[{"role":"user","content":"hi"}]}`, stream)) + result, err := grokAuditOAuthService(upstream, account).ForwardAsAnthropic(context.Background(), c, account, request, "", "") + require.NoError(t, err) + require.Contains(t, upstream.lastReq.URL.String(), "/responses") + require.Equal(t, "grok-4.7", result.Model) + require.Equal(t, "grok-4.7", result.UpstreamModel) + require.Equal(t, "grok-4.7-build", result.UpstreamResponseModel) + require.False(t, result.UpstreamResponseModelConflict) + mismatch := upstreamModelMismatch(result.UpstreamModel, result.UpstreamResponseModel) + require.NotNil(t, mismatch) + require.False(t, *mismatch) + client := rec.Body.String() + if !stream { + require.Equal(t, "grok-4.7", gjson.Get(client, "model").String()) + } + require.NotContains(t, client, "grok-4.7-build") + }) + } +} + +func TestGrokResponseAuditConvertedStreamingConflict(t *testing.T) { + sse := grokAuditResponsesSSE("grok-4.5", "grok-4.7-build") + t.Run("chat-bridge", func(t *testing.T) { + c, rec := grokAuditContext("/v1/chat/completions") + account := healthyGrokOAuthGatewayTestAccount(88901, "access-token") + upstream := &httpUpstreamRecorder{resp: grokAuditHTTPResponse("text/event-stream", sse)} + request := []byte(`{"model":"grok-4.7","messages":[{"role":"user","content":"hi"}],"stream":true,"prompt_cache_key":"stable-session"}`) + result, err := grokAuditOAuthService(upstream, account).ForwardAsChatCompletions(context.Background(), c, account, request, "", "") + require.NoError(t, err) + require.Equal(t, grokChatResponsesEndpoint, result.UpstreamEndpoint) + require.Equal(t, "grok-4.7-build", result.UpstreamResponseModel) + require.True(t, result.UpstreamResponseModelConflict) + require.Contains(t, rec.Body.String(), `"model":"grok-4.7"`) + require.NotContains(t, rec.Body.String(), "grok-4.7-build") + }) + t.Run("messages", func(t *testing.T) { + c, rec := grokAuditContext("/v1/messages") + account := healthyGrokOAuthGatewayTestAccount(88902, "access-token") + upstream := &httpUpstreamRecorder{resp: grokAuditHTTPResponse("text/event-stream", sse)} + request := []byte(`{"model":"grok-4.7","max_tokens":32,"stream":true,"messages":[{"role":"user","content":"hi"}]}`) + result, err := grokAuditOAuthService(upstream, account).ForwardAsAnthropic(context.Background(), c, account, request, "", "") + require.NoError(t, err) + require.Equal(t, "grok-4.7-build", result.UpstreamResponseModel) + require.True(t, result.UpstreamResponseModelConflict) + require.Equal(t, "grok-4.7", result.Model) + require.NotContains(t, rec.Body.String(), "grok-4.7-build") + require.NotContains(t, rec.Body.String(), "grok-4.5") + }) +} + +func TestGrokResponseAuditConvertedAggregateConflict(t *testing.T) { + sse := grokAuditResponsesSSE("grok-4.5", "grok-4.7-build") + for i, entry := range []string{"chat-bridge", "messages"} { + t.Run(entry, func(t *testing.T) { + result, client := grokAuditRunConvertedAggregate(t, entry, 89001+int64(i), sse) + require.False(t, result.Stream) + require.Equal(t, "grok-4.7", result.Model) + require.Equal(t, "grok-4.7", result.UpstreamModel) + require.Equal(t, "grok-4.7-build", result.UpstreamResponseModel) + require.True(t, result.UpstreamResponseModelConflict) + requireObservedMismatch(t, result, false, false) + require.True(t, gjson.Valid(client), "aggregate client should receive JSON, got %s", client) + require.Equal(t, "grok-4.7", gjson.Get(client, "model").String()) + require.NotContains(t, client, "grok-4.7-build") + require.NotContains(t, client, "grok-4.5") + }) + } +} + +func TestGrokResponseAuditConvertedAggregateModelBoundaries(t *testing.T) { + cases := []struct { + name, created, completed, wantModel string + conflict, mismatchNil, mismatch bool + }{ + {name: "same", created: "grok-4.7-build", completed: "grok-4.7-build", wantModel: "grok-4.7-build"}, + {name: "missing", mismatchNil: true}, + {name: "created-without-terminal-model", created: "grok-4.5", wantModel: "grok-4.5", mismatch: true}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + sse := grokAuditResponsesSSE(tt.created, tt.completed) + for i, entry := range []string{"chat-bridge", "messages"} { + t.Run(entry, func(t *testing.T) { + result, client := grokAuditRunConvertedAggregate(t, entry, 89100+int64(i), sse) + require.False(t, result.Stream) + require.Equal(t, tt.wantModel, result.UpstreamResponseModel) + require.Equal(t, tt.conflict, result.UpstreamResponseModelConflict) + requireObservedMismatch(t, result, tt.mismatchNil, tt.mismatch) + require.True(t, gjson.Valid(client), "aggregate client should receive JSON, got %s", client) + require.Equal(t, "grok-4.7", gjson.Get(client, "model").String()) + if tt.wantModel != "" && tt.wantModel != "grok-4.7" { + require.NotContains(t, client, tt.wantModel) + } + if tt.created != "" && tt.created != tt.wantModel && tt.created != "grok-4.7" { + require.NotContains(t, client, tt.created) + } + }) + } + }) + } +} + +func TestGrokResponseAuditConvertedAggregateKeepsNonGrokTerminalOnly(t *testing.T) { + sse := grokAuditResponsesSSE("gpt-5.4-mini", "gpt-5.4") + t.Run("chat", func(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"gpt-5.4","messages":[{"role":"user","content":"hi"}],"stream":false}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(string(body))) + c.Request.Header.Set("Content-Type", "application/json") + upstream := &httpUpstreamRecorder{resp: grokAuditHTTPResponse("text/event-stream", sse)} + account := &Account{ + ID: 89201, + Name: "openai-oauth", + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Concurrency: 1, + Credentials: map[string]any{ + "access_token": "oauth-token", + "chatgpt_account_id": "chatgpt-acc", + }, + } + result, err := (&OpenAIGatewayService{httpUpstream: upstream}).ForwardAsChatCompletions(context.Background(), c, account, body, "", "gpt-5.4") + require.NoError(t, err) + require.False(t, result.Stream) + require.Equal(t, "gpt-5.4", result.UpstreamResponseModel) + require.False(t, result.UpstreamResponseModelConflict) + require.Equal(t, result.Model, gjson.Get(rec.Body.String(), "model").String()) + require.NotContains(t, rec.Body.String(), "gpt-5.4-mini") + }) + t.Run("messages", func(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"gpt-5.4","max_tokens":32,"messages":[{"role":"user","content":"hi"}],"stream":false}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(string(body))) + c.Request.Header.Set("Content-Type", "application/json") + upstream := &httpUpstreamRecorder{resp: grokAuditHTTPResponse("text/event-stream", sse)} + result, err := (&OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}).ForwardAsAnthropic( + context.Background(), c, rawChatCompletionsTestAccount(), body, "", "", + ) + require.NoError(t, err) + require.False(t, result.Stream) + require.Equal(t, "gpt-5.4", result.UpstreamResponseModel) + require.False(t, result.UpstreamResponseModelConflict) + require.Equal(t, result.Model, gjson.Get(rec.Body.String(), "model").String()) + require.NotContains(t, rec.Body.String(), "gpt-5.4-mini") + }) +} + +func TestGrokResponseAuditAggregatePriorStateStaysBounded(t *testing.T) { + const repeats = 48 + overlong := strings.Repeat("界", upstreamResponseModelMaxLength+50) + late := "grok-late-distinct" + wantModel := string([]rune(overlong)[:upstreamResponseModelMaxLength]) + grok := grokAuditAPIKeyAccount(89301) + other := &Account{ID: 89302, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + + t.Run("repeated-declarations", func(t *testing.T) { + terminal, prior := grokAuditReadBufferedPriors(t, grok, grokAuditPriorModelSSE(repeats, overlong, late, overlong)) + require.Equal(t, wantModel, prior.observer.first) + require.LessOrEqual(t, len([]rune(prior.observer.first)), upstreamResponseModelMaxLength) + require.Empty(t, prior.observer.terminal) + require.True(t, prior.observer.conflict) + observer := &upstreamResponseModelObserver{} + prior.apply(observer) + observer.Observe(terminal, true) + require.Equal(t, wantModel, observer.Model()) + require.True(t, observer.Conflict()) + }) + + t.Run("overlong-model", func(t *testing.T) { + _, prior := grokAuditReadBufferedPriors(t, grok, grokAuditPriorModelSSE(1, overlong, "", "")) + require.Equal(t, wantModel, prior.observer.first) + require.LessOrEqual(t, len([]rune(prior.observer.first)), upstreamResponseModelMaxLength) + require.False(t, prior.observer.conflict) + }) + + t.Run("overlong-shared-prefix", func(t *testing.T) { + diverged := wantModel + strings.Repeat("外", 50) + _, prior := grokAuditReadBufferedPriors(t, grok, grokAuditPriorModelSSE(repeats, overlong, diverged, "")) + require.Equal(t, wantModel, prior.observer.first) + require.LessOrEqual(t, len([]rune(prior.observer.first)), upstreamResponseModelMaxLength) + require.False(t, prior.observer.conflict) + }) + + t.Run("non-grok-skips-collection", func(t *testing.T) { + terminal, prior := grokAuditReadBufferedPriors(t, other, grokAuditPriorModelSSE(repeats, "gpt-5.4-mini", "gpt-5.4-nano", "gpt-5.4")) + require.False(t, prior.enabled) + require.Empty(t, prior.observer.first) + require.False(t, prior.observer.conflict) + observer := &upstreamResponseModelObserver{} + prior.apply(observer) + observer.Observe(terminal, true) + require.Equal(t, "gpt-5.4", observer.Model()) + require.False(t, observer.Conflict()) + }) + + t.Run("entries", func(t *testing.T) { + sse := grokAuditPriorModelSSE(repeats, overlong, late, overlong) + for i, entry := range []string{"chat-bridge", "messages"} { + t.Run(entry, func(t *testing.T) { + result, client := grokAuditRunConvertedAggregate(t, entry, 89310+int64(i), sse) + require.False(t, result.Stream) + require.Equal(t, wantModel, result.UpstreamResponseModel) + require.True(t, result.UpstreamResponseModelConflict) + require.Equal(t, "grok-4.7", gjson.Get(client, "model").String()) + require.NotContains(t, client, late) + require.NotContains(t, client, wantModel) + }) + } + }) +} + +func grokAuditReadBufferedPriors(t *testing.T, account *Account, sse string) (string, openAICompatPriorModelAudit) { + t.Helper() + c, _ := grokAuditContext("/v1/messages") + resp := grokAuditHTTPResponse("text/event-stream", sse) + response, _, _, prior, err := (&OpenAIGatewayService{}).readOpenAICompatBufferedTerminal(resp, c, account, "openai messages buffered", "req-bound") + require.NoError(t, err) + require.NotNil(t, response) + return response.Model, prior +} + +func grokAuditPriorModelSSE(repeats int, repeated, late, terminal string) string { + var b strings.Builder + for i := 0; i < repeats; i++ { + if repeated == "" { + break + } + fmt.Fprintf(&b, "data: {\"type\":\"response.in_progress\",\"response\":{\"id\":\"resp_audit\",\"model\":%q,\"output\":[]}}\n\n", repeated) + } + if late != "" { + fmt.Fprintf(&b, "data: {\"type\":\"response.in_progress\",\"response\":{\"id\":\"resp_audit\",\"model\":%q,\"output\":[]}}\n\n", late) + } + b.WriteString("data: {\"type\":\"response.output_text.delta\",\"delta\":\"ok\"}\n\n") + completed := `{"id":"resp_audit","object":"response","status":"completed","output":[{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":2,"output_tokens":1}}` + if terminal != "" { + completed = fmt.Sprintf(`{"id":"resp_audit","object":"response","model":%q,"status":"completed","output":[{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":2,"output_tokens":1}}`, terminal) + } + b.WriteString("data: {\"type\":\"response.completed\",\"response\":" + completed + "}\n\n") + return b.String() +} + +func grokAuditRunConvertedAggregate(t *testing.T, entry string, id int64, sse string) (*OpenAIForwardResult, string) { + t.Helper() + switch entry { + case "chat-bridge": + c, rec := grokAuditContext("/v1/chat/completions") + account := healthyGrokOAuthGatewayTestAccount(id, "access-token") + upstream := &httpUpstreamRecorder{resp: grokAuditHTTPResponse("text/event-stream", sse)} + request := []byte(`{"model":"grok-4.7","messages":[{"role":"user","content":"hi"}],"stream":false,"prompt_cache_key":"stable-session"}`) + result, err := grokAuditOAuthService(upstream, account).ForwardAsChatCompletions(context.Background(), c, account, request, "", "") + require.NoError(t, err) + require.Equal(t, grokChatResponsesEndpoint, result.UpstreamEndpoint) + require.Contains(t, upstream.lastReq.URL.String(), "/responses") + return result, rec.Body.String() + case "messages": + c, rec := grokAuditContext("/v1/messages") + account := healthyGrokOAuthGatewayTestAccount(id, "access-token") + upstream := &httpUpstreamRecorder{resp: grokAuditHTTPResponse("text/event-stream", sse)} + request := []byte(`{"model":"grok-4.7","max_tokens":32,"stream":false,"messages":[{"role":"user","content":"hi"}]}`) + result, err := grokAuditOAuthService(upstream, account).ForwardAsAnthropic(context.Background(), c, account, request, "", "") + require.NoError(t, err) + require.Contains(t, upstream.lastReq.URL.String(), "/responses") + return result, rec.Body.String() + default: + t.Fatalf("unknown aggregate entry %s", entry) + return nil, "" + } +} + +func grokAuditSwapWriter(c *gin.Context) *httptest.ResponseRecorder { + next, rec := grokAuditContext("/v1/responses") + c.Writer = next.Writer + return rec +} + +func grokAuditContext(path string) (*gin.Context, *httptest.ResponseRecorder) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, path, nil) + c.Request.Header.Set("Content-Type", "application/json") + c.Set("api_key", &APIKey{ID: 88000}) + return c, rec +} + +func grokAuditAPIKeyAccount(id int64) *Account { + return &Account{ + ID: id, + Name: "grok-api-key", + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Concurrency: 2, + Credentials: map[string]any{"api_key": "test-key", "base_url": "https://api.x.ai/v1"}, + } +} + +func grokAuditOAuthService(upstream *httpUpstreamRecorder, accounts ...*Account) *OpenAIGatewayService { + byID := make(map[int64]*Account, len(accounts)) + for _, account := range accounts { + byID[account.ID] = account + } + repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{accountsByID: byID}} + return &OpenAIGatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: upstream, + grokTokenProvider: NewGrokTokenProvider(repo, nil), + accountRepo: repo, + } +} + +func grokAuditHTTPResponse(contentType, body string) *http.Response { + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{contentType}}, + Body: io.NopCloser(strings.NewReader(body)), + } +} + +func grokAuditResponsesJSON(model string) string { + if model == "" { + return `{"id":"resp_audit","object":"response","status":"completed","output":[],"usage":{"input_tokens":2,"output_tokens":1}}` + } + return fmt.Sprintf(`{"id":"resp_audit","object":"response","model":%q,"status":"completed","output":[],"usage":{"input_tokens":2,"output_tokens":1}}`, model) +} + +func grokAuditResponsesSSE(createdModel, completedModel string) string { + lines := make([]string, 0, 8) + if createdModel != "" { + lines = append(lines, fmt.Sprintf(`data: {"type":"response.created","response":{"id":"resp_audit","model":%q,"output":[]}}`, createdModel), "") + } + lines = append(lines, `data: {"type":"response.output_text.delta","sequence_number":0,"delta":"ok"}`, "") + completed := `{"id":"resp_audit","object":"response","status":"completed","output":[{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":2,"output_tokens":1}}` + if completedModel != "" { + completed = fmt.Sprintf(`{"id":"resp_audit","object":"response","model":%q,"status":"completed","output":[{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":2,"output_tokens":1}}`, completedModel) + } + lines = append(lines, `data: {"type":"response.completed","sequence_number":1,"response":`+completed+`}`, "") + return strings.Join(lines, "\n") +} + +func grokAuditChatJSON(model string) string { + return fmt.Sprintf(`{"id":"chatcmpl_audit","object":"chat.completion","model":%q,"choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":2,"completion_tokens":1,"total_tokens":3}}`, model) +} + +func grokAuditChatSSE(model string) string { + return strings.Join([]string{ + fmt.Sprintf(`data: {"id":"chatcmpl_audit","object":"chat.completion.chunk","model":%q,"choices":[{"index":0,"delta":{"content":"ok"}}]}`, model), + "", + fmt.Sprintf(`data: {"id":"chatcmpl_audit","object":"chat.completion.chunk","model":%q,"choices":[],"usage":{"prompt_tokens":2,"completion_tokens":1,"total_tokens":3}}`, model), + "", + "data: [DONE]", + "", + }, "\n") +} + +func requireObservedMismatch(t *testing.T, result *OpenAIForwardResult, wantNil, want bool) { + t.Helper() + got := upstreamModelMismatch(result.UpstreamModel, result.UpstreamResponseModel) + if wantNil { + require.Nil(t, got) + return + } + require.NotNil(t, got) + require.Equal(t, want, *got) +} diff --git a/backend/internal/service/openai_codex_models_service.go b/backend/internal/service/openai_codex_models_service.go index a9dd322806..bdaa684d5c 100644 --- a/backend/internal/service/openai_codex_models_service.go +++ b/backend/internal/service/openai_codex_models_service.go @@ -661,6 +661,9 @@ func configuredCodexGPTReasoningLevels(modelID string) []configuredCodexReasonin Description: "Maximum reasoning with automatic task delegation", }) } + if openai.IsGPT61TerraModelSpelling(modelID) { + levels = append([]configuredCodexReasoningLevel{{Effort: "none", Description: "No reasoning"}}, levels...) + } return levels } diff --git a/backend/internal/service/openai_codex_transform.go b/backend/internal/service/openai_codex_transform.go index 220358f1e4..f4b33dbab3 100644 --- a/backend/internal/service/openai_codex_transform.go +++ b/backend/internal/service/openai_codex_transform.go @@ -11,6 +11,7 @@ import ( ) var codexModelMap = map[string]string{ + "gpt-6.1-terra": "gpt-6.1-terra", "gpt-6.1-sol": "gpt-6.1-sol", "gpt-6-sol": "gpt-6-sol", "gpt-6-luna": "gpt-6-luna", @@ -63,6 +64,7 @@ var codexVersionModelPrefixes = []struct { prefix string target string }{ + {prefix: "gpt-6.1-terra", target: "gpt-6.1-terra"}, {prefix: "gpt-6.1-sol", target: "gpt-6.1-sol"}, {prefix: "gpt-6-sol", target: "gpt-6-sol"}, {prefix: "gpt-6-luna", target: "gpt-6-luna"}, diff --git a/backend/internal/service/openai_compat_model.go b/backend/internal/service/openai_compat_model.go index 19a6fb072c..8f4a2585bd 100644 --- a/backend/internal/service/openai_compat_model.go +++ b/backend/internal/service/openai_compat_model.go @@ -8,6 +8,9 @@ import ( ) func NormalizeOpenAICompatRequestedModel(model string) string { + if openai.IsGPT61TerraModelSpelling(model) { + return "gpt-6.1-terra" + } if openai.IsGPT61SolModelSpelling(model) { return "gpt-6.1-sol" } @@ -24,10 +27,11 @@ func NormalizeOpenAICompatRequestedModel(model string) string { } func applyOpenAICompatModelNormalization(req *apicompat.AnthropicRequest) { - if req != nil && openai.IsGPT61SolModelSpelling(req.Model) { + if req != nil && (openai.IsGPT61SolModelSpelling(req.Model) || openai.IsGPT61TerraModelSpelling(req.Model)) { canonical := openai.CanonicalizeOpenAIModelAliasSpelling(req.Model) - if effort, ok := strings.CutPrefix(canonical, "gpt-6.1-sol-"); ok && effort != "openai-compact" { - req.Model = "gpt-6.1-sol" + baseModel := NormalizeOpenAICompatRequestedModel(req.Model) + if effort, ok := strings.CutPrefix(canonical, baseModel+"-"); ok && effort != "openai-compact" { + req.Model = baseModel if req.OutputConfig == nil { req.OutputConfig = &apicompat.AnthropicOutputConfig{} } diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index af4eae36ea..6c727da0cc 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -676,7 +676,7 @@ func (s *OpenAIGatewayService) handleChatBufferedStreamingResponse( ) (*OpenAIForwardResult, error) { requestID := resp.Header.Get("x-request-id") - finalResponse, usage, acc, err := s.readOpenAICompatBufferedTerminal(resp, c, "openai chat_completions buffered", requestID) + finalResponse, usage, acc, priorModels, err := s.readOpenAICompatBufferedTerminal(resp, c, account, "openai chat_completions buffered", requestID) if err != nil { return nil, s.newOpenAICompatBufferedReadFailoverError(c, account, resp, requestID, err) } @@ -689,6 +689,7 @@ func (s *OpenAIGatewayService) handleChatBufferedStreamingResponse( if observer == nil { observer = beginUpstreamResponseModelObservation(c) } + priorModels.apply(observer) observer.Observe(finalResponse.Model, true) observer.ObserveServiceTier(finalResponse.ServiceTier, true) if strings.TrimSpace(finalResponse.Status) == "failed" { diff --git a/backend/internal/service/openai_gateway_chat_completions_raw.go b/backend/internal/service/openai_gateway_chat_completions_raw.go index 98fa8c4a0d..6943f519e6 100644 --- a/backend/internal/service/openai_gateway_chat_completions_raw.go +++ b/backend/internal/service/openai_gateway_chat_completions_raw.go @@ -95,8 +95,8 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletionsWithStartTime( // anchored to the client's stable conversation prefix. grokCacheIdentity = resolveGrokCacheIdentity(c, body, "", upstreamModel) } - if openai.IsGPT61SolModelSpelling(upstreamModel) && (len(gjson.GetBytes(body, "tools").Array()) > 0 || len(gjson.GetBytes(body, "functions").Array()) > 0) { - err := fmt.Errorf("gpt-6.1-sol requires Responses for tool calls; this account only supports Chat Completions") + if openai.RequiresResponsesForToolCalls(upstreamModel) && (len(gjson.GetBytes(body, "tools").Array()) > 0 || len(gjson.GetBytes(body, "functions").Array()) > 0) { + err := fmt.Errorf("%s requires Responses for tool calls; this account only supports Chat Completions", normalizeKnownOpenAICodexModel(upstreamModel)) writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) return nil, err } diff --git a/backend/internal/service/openai_gateway_grok.go b/backend/internal/service/openai_gateway_grok.go index 7aaa649a74..aea1e3c964 100644 --- a/backend/internal/service/openai_gateway_grok.go +++ b/backend/internal/service/openai_gateway_grok.go @@ -249,18 +249,20 @@ func (s *OpenAIGatewayService) forwardGrokResponses( } reasoningEffort := extractOpenAIReasoningEffortFromBody(patchedBody, originalModel) result := &OpenAIForwardResult{ - RequestID: firstNonEmpty(resp.Header.Get("x-request-id"), resp.Header.Get("xai-request-id")), - UpstreamHeaders: resp.Header, - ResponseID: responseID, - Usage: *usage, - Model: originalModel, - UpstreamModel: upstreamModel, - ReasoningEffort: reasoningEffort, - Stream: reqStream, - OpenAIWSMode: false, - ResponseHeaders: resp.Header.Clone(), - Duration: time.Since(startTime), - FirstTokenMs: firstTokenMs, + RequestID: firstNonEmpty(resp.Header.Get("x-request-id"), resp.Header.Get("xai-request-id")), + UpstreamHeaders: resp.Header, + ResponseID: responseID, + Usage: *usage, + Model: originalModel, + UpstreamModel: upstreamModel, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + ReasoningEffort: reasoningEffort, + Stream: reqStream, + OpenAIWSMode: false, + ResponseHeaders: resp.Header.Clone(), + Duration: time.Since(startTime), + FirstTokenMs: firstTokenMs, } // Propagate search/image counters from the shared Responses handler — without // this, stream/JSON counting runs but search_price_per_1k / image bills never apply. diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 45f890a370..dfe326e847 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -604,7 +604,7 @@ func (s *OpenAIGatewayService) handleAnthropicBufferedStreamingResponse( ) (*OpenAIForwardResult, error) { requestID := resp.Header.Get("x-request-id") - finalResponse, usage, acc, err := s.readOpenAICompatBufferedTerminal(resp, c, "openai messages buffered", requestID) + finalResponse, usage, acc, prior, err := s.readOpenAICompatBufferedTerminal(resp, c, account, "openai messages buffered", requestID) if err != nil { var readErr *openAICompatBufferedReadError if errors.As(err, &readErr) && readErr != nil { @@ -621,6 +621,7 @@ func (s *OpenAIGatewayService) handleAnthropicBufferedStreamingResponse( if observer == nil { observer = beginUpstreamResponseModelObservation(c) } + prior.apply(observer) observer.Observe(finalResponse.Model, true) observer.ObserveServiceTier(finalResponse.ServiceTier, true) @@ -771,16 +772,67 @@ func openAICompatTerminalResponse(event *apicompat.ResponsesStreamEvent, payload } } +func openAICompatBufferedPriorModel(event *apicompat.ResponsesStreamEvent) (string, bool) { + if event == nil || event.Response == nil || isOpenAICompatResponsesTerminalEvent(event.Type) { + return "", false + } + model := strings.TrimSpace(event.Response.Model) + if model == "" { + return "", false + } + return model, true +} + +// openAICompatPriorModelAudit 是一次缓冲读取的固定大小审计状态。 +// 只有 Grok 折叠非终止 model:保留一条按既有上限截断的声明和冲突位。 +// 后面的不同声明只置冲突,不按事件数量或原文长度继续保存。 +type openAICompatPriorModelAudit struct { + enabled bool + observer upstreamResponseModelObserver +} + +func newOpenAICompatPriorModelAudit(account *Account) openAICompatPriorModelAudit { + return openAICompatPriorModelAudit{enabled: account != nil && account.IsGrok()} +} + +func (a *openAICompatPriorModelAudit) record(event *apicompat.ResponsesStreamEvent) { + if a == nil || !a.enabled { + return + } + model, ok := openAICompatBufferedPriorModel(event) + if !ok { + return + } + a.observer.Observe(model, false) +} + +func (a openAICompatPriorModelAudit) apply(observer *upstreamResponseModelObserver) { + if !a.enabled || observer == nil { + return + } + if a.observer.first != "" { + observer.Observe(a.observer.first, false) + } + if a.observer.conflict { + observer.conflict = true + } +} + func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( resp *http.Response, c *gin.Context, + account *Account, logPrefix string, requestID string, -) (*apicompat.ResponsesResponse, OpenAIUsage, *apicompat.BufferedResponseAccumulator, error) { +) (*apicompat.ResponsesResponse, OpenAIUsage, *apicompat.BufferedResponseAccumulator, openAICompatPriorModelAudit, error) { acc := apicompat.NewBufferedResponseAccumulator() var usage OpenAIUsage if resp == nil || resp.Body == nil { - return nil, usage, acc, errors.New("upstream response body is nil") + return nil, usage, acc, openAICompatPriorModelAudit{}, errors.New("upstream response body is nil") + } + prior := newOpenAICompatPriorModelAudit(account) + recordPrior := func(event *apicompat.ResponsesStreamEvent) { + prior.record(event) } scanner := s.newUpstreamSSEScanner(resp.Body) @@ -858,6 +910,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if err := json.Unmarshal([]byte(payload), &event); err == nil { s.parseSSEUsageBytesWithType([]byte(payload), event.Type, &usage) acc.ProcessEvent(&event) + recordPrior(&event) if response := openAICompatTerminalResponse(&event, []byte(payload)); isOpenAICompatResponsesTerminalEvent(event.Type) && response != nil { if event.Usage != nil { usage = copyOpenAIUsageFromResponsesUsage(event.Usage) @@ -868,11 +921,11 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if response.Usage != nil { usage = copyOpenAIUsageFromResponsesUsage(response.Usage) } - return response, usage, acc, nil + return response, usage, acc, prior, nil } } } - return nil, usage, acc, nil + return nil, usage, acc, prior, nil } resetTimeout() if ev.err != nil { @@ -882,11 +935,11 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( zap.String("request_id", requestID), ) } - return nil, usage, acc, &openAICompatBufferedReadError{cause: ev.err} + return nil, usage, acc, prior, &openAICompatBufferedReadError{cause: ev.err} } if isOpenAICompatDoneSentinelLine(ev.line) { - return nil, usage, acc, nil + return nil, usage, acc, prior, nil } frame, ok := parser.AddLine(ev.line) if !ok { @@ -906,6 +959,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( s.parseSSEUsageBytesWithType([]byte(payload), event.Type, &usage) acc.ProcessEvent(&event) + recordPrior(&event) if response := openAICompatTerminalResponse(&event, []byte(payload)); isOpenAICompatResponsesTerminalEvent(event.Type) && response != nil { if event.Usage != nil { @@ -917,7 +971,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if response.Usage != nil { usage = copyOpenAIUsageFromResponsesUsage(response.Usage) } - return response, usage, acc, nil + return response, usage, acc, prior, nil } case <-timeoutCh: @@ -926,7 +980,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( zap.String("request_id", requestID), zap.Duration("interval", streamInterval), ) - return nil, usage, acc, fmt.Errorf("stream data interval timeout") + return nil, usage, acc, prior, fmt.Errorf("stream data interval timeout") } } } diff --git a/backend/internal/service/openai_gateway_messages_chat_fallback.go b/backend/internal/service/openai_gateway_messages_chat_fallback.go index d12918a3bb..59a70dd191 100644 --- a/backend/internal/service/openai_gateway_messages_chat_fallback.go +++ b/backend/internal/service/openai_gateway_messages_chat_fallback.go @@ -67,8 +67,8 @@ func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions( writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) return nil, err } - if openai.IsGPT61SolModelSpelling(upstreamModel) && len(anthropicReq.Tools) > 0 { - err := fmt.Errorf("gpt-6.1-sol requires Responses for tool calls; this account only supports Chat Completions") + if openai.RequiresResponsesForToolCalls(upstreamModel) && len(anthropicReq.Tools) > 0 { + err := fmt.Errorf("%s requires Responses for tool calls; this account only supports Chat Completions", normalizeKnownOpenAICodexModel(upstreamModel)) writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) return nil, err } diff --git a/backend/internal/service/openai_gateway_responses_chat_fallback.go b/backend/internal/service/openai_gateway_responses_chat_fallback.go index 184e3152dc..ad4e65e05e 100644 --- a/backend/internal/service/openai_gateway_responses_chat_fallback.go +++ b/backend/internal/service/openai_gateway_responses_chat_fallback.go @@ -75,8 +75,8 @@ func (s *OpenAIGatewayService) forwardResponsesViaRawChatCompletions( writeOpenAIResponsesFallbackError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) return nil, err } - if openai.IsGPT61SolModelSpelling(upstreamModel) && len(effectiveTools) > 0 { - err := fmt.Errorf("gpt-6.1-sol requires Responses for tool calls; this account only supports Chat Completions") + if openai.RequiresResponsesForToolCalls(upstreamModel) && len(effectiveTools) > 0 { + err := fmt.Errorf("%s requires Responses for tool calls; this account only supports Chat Completions", normalizeKnownOpenAICodexModel(upstreamModel)) writeOpenAIResponsesFallbackError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) return nil, err } diff --git a/backend/internal/service/openai_gpt61_terra_test.go b/backend/internal/service/openai_gpt61_terra_test.go new file mode 100644 index 0000000000..1a8877478b --- /dev/null +++ b/backend/internal/service/openai_gpt61_terra_test.go @@ -0,0 +1,142 @@ +//go:build unit + +package service + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/Wei-Shaw/sub2api/internal/pkg/openai" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestGPT61TerraIdentityAndEffort(t *testing.T) { + require.Contains(t, openai.DefaultModelIDs(), "gpt-6.1-terra") + require.Equal(t, "gpt-5.6-sol", openai.DefaultModelIDs()[0]) + require.Equal(t, "gpt-5.4", openai.DefaultTestModel) + for _, effort := range []string{"none", "low", "medium", "high", "xhigh", "max"} { + model := "openai/GPT-6.1-Terra-" + effort + require.True(t, openai.IsGPT61TerraModelSpelling(model)) + require.False(t, openai.IsGPT61SolModelSpelling(model)) + require.Equal(t, "gpt-6.1-terra", normalizeCodexModel(model)) + require.Equal(t, "gpt-6.1-terra", normalizeKnownOpenAICodexModel(model)) + require.Equal(t, "gpt-6.1-terra", NormalizeOpenAICompatRequestedModel(model)) + require.Equal(t, effort, normalizeOpenAIReasoningEffortForModel(effort, model)) + request := &apicompat.AnthropicRequest{Model: model} + applyOpenAICompatModelNormalization(request) + require.Equal(t, "gpt-6.1-terra", request.Model) + require.Equal(t, effort, request.OutputConfig.Effort) + require.Equal(t, effort, openAICompatAnthropicReasoningEffort(request, request.Model, effort)) + converted, err := apicompat.AnthropicToResponses(request) + require.NoError(t, err) + require.Equal(t, effort, converted.Reasoning.Effort) + chatConverted, err := apicompat.ChatCompletionsToResponses(&apicompat.ChatCompletionsRequest{ + Model: "gpt-6.1-terra", ReasoningEffort: effort, + Tools: []apicompat.ChatTool{{Type: "function", Function: &apicompat.ChatFunction{Name: "lookup"}}}, + }) + require.NoError(t, err) + require.Equal(t, "gpt-6.1-terra", chatConverted.Model) + require.Equal(t, effort, chatConverted.Reasoning.Effort) + require.Len(t, chatConverted.Tools, 1) + require.NoError(t, validateGPT61SolCompatRequest([]byte(`{"reasoning":{"effort":"`+effort+`"}}`), model)) + } + for _, model := range []string{"gpt-6.1-terra", "gpt-6.1-terra-openai-compact", "openai/gpt_6.1_terra"} { + require.Equal(t, "gpt-6.1-terra", normalizeKnownOpenAICodexModel(model)) + } + for _, model := range []string{"gpt-6.1-sol", "gpt-5.6-terra", "gpt-6.1-terra-pro", "gpt-6.1-terra-ultra", "gpt-6.1-terra-minimal"} { + require.False(t, openai.IsGPT61TerraModelSpelling(model)) + } + descriptor := newConfiguredCodexModelDescriptor("gpt-6.1-terra") + require.Equal(t, "medium", *descriptor.DefaultReasoningLevel) + var efforts []string + for _, level := range descriptor.SupportedReasoningLevels { + efforts = append(efforts, level.Effort) + } + require.Equal(t, []string{"none", "low", "medium", "high", "xhigh", "max"}, efforts) + require.Empty(t, descriptor.officialMetadata) + converted, err := apicompat.AnthropicToResponses(&apicompat.AnthropicRequest{Model: "gpt-6.1-terra"}) + require.NoError(t, err) + require.Equal(t, "medium", converted.Reasoning.Effort) +} + +func TestGPT61TerraAccountDiscoveryPreservesCatalog(t *testing.T) { + for _, catalog := range []string{`{"data":[{"id":"gpt-6.1-terra","owned_by":"openai"}]}`, `{"data":[]}`} { + gateway := newCodexModelsAPIKeyTestService(&codexModelsHTTPUpstreamStub{do: func(_ *http.Request, _ string, _ int64, _ int) (*http.Response, error) { + return ordinaryModelsUpstreamResponse(catalog), nil + }}) + service := &AccountTestService{openaiGatewayService: gateway} + account := newCodexModelsAPIKeyTestAccount("https://models.example/v1") + before, err := gateway.FetchOpenAIModelsList(context.Background(), account) + require.NoError(t, err) + models, err := service.FetchOpenAIAccountModels(context.Background(), account) + require.NoError(t, err) + if catalog == `{"data":[]}` { + require.Empty(t, models) + } else { + require.Len(t, models, 1) + require.Equal(t, "gpt-6.1-terra", models[0].ID) + require.Equal(t, "GPT-6.1 Terra", models[0].DisplayName) + } + after, err := gateway.FetchOpenAIModelsList(context.Background(), account) + require.NoError(t, err) + require.Equal(t, before.Body, after.Body) + } +} + +func TestGPT61TerraManifestUsesUpstreamCapabilities(t *testing.T) { + account := Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey} + reasoning := true + account.SetUpstreamModelMetadataSnapshot(UpstreamModelMetadataSnapshot{Models: map[string]UpstreamModelMetadata{ + "gpt-6.1-terra": {ID: "gpt-6.1-terra", Reasoning: &reasoning, DefaultReasoningLevel: "high", SupportedReasoningLevels: []string{"high"}, InputModalities: []string{"text"}, ContextWindow: 100000}, + }}) + service := &GatewayService{accountRepo: codexModelsVisibilityAccountRepo{byGroup: map[int64][]Account{1: {account}}}} + body, err := service.BuildCodexModelsManifestForGroup(context.Background(), &Group{ID: 1, Platform: PlatformOpenAI}, "", []string{"gpt-6.1-terra"}) + require.NoError(t, err) + models := decodeCodexManifestModels(t, body) + require.Len(t, models, 1) + require.Equal(t, []any{"text"}, models[0]["input_modalities"]) + require.Equal(t, []string{"high"}, effortsFromManifestModel(t, models[0])) + require.Equal(t, float64(100000), models[0]["context_window"]) +} + +func TestGPT61TerraChatFallbackRejectsTools(t *testing.T) { + for _, protocol := range []string{"chat", "responses", "messages"} { + for _, toolField := range []string{`"tools":[{"type":"function","function":{"name":"lookup","parameters":{"type":"object"}}}]`, `"functions":[{"name":"lookup","parameters":{"type":"object"}}]`} { + if protocol != "chat" && strings.HasPrefix(toolField, `"functions"`) { + continue + } + body := `{"model":"public","reasoning_effort":"none","messages":[{"role":"user","content":"hi"}],"input":"hi","max_tokens":100,` + toolField + `}` + if protocol == "responses" { + body = `{"model":"public","input":"hi","tools":[{"type":"function","name":"lookup","parameters":{"type":"object"}}]}` + } + if protocol == "messages" { + body = `{"model":"public","max_tokens":100,"messages":[{"role":"user","content":"hi"}],"tools":[{"name":"lookup","input_schema":{"type":"object"}}]}` + } + t.Run(protocol+toolField, func(t *testing.T) { + recorder := httptest.NewRecorder() + ginContext, _ := gin.CreateTestContext(recorder) + ginContext.Request = httptest.NewRequest(http.MethodPost, "/v1/"+protocol, strings.NewReader(body)) + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Credentials: map[string]any{"model_mapping": map[string]any{"public": "gpt-6.1-terra"}}} + service := &OpenAIGatewayService{cfg: &config.Config{}} + var err error + switch protocol { + case "chat": + _, err = service.forwardAsRawChatCompletions(context.Background(), ginContext, account, []byte(body), "") + case "responses": + _, err = service.forwardResponsesViaRawChatCompletions(context.Background(), ginContext, account, []byte(body), time.Now()) + case "messages": + _, err = service.forwardAnthropicViaRawChatCompletions(context.Background(), ginContext, account, []byte(body), "") + } + require.ErrorContains(t, err, "gpt-6.1-terra requires Responses") + require.Equal(t, http.StatusBadRequest, recorder.Code) + }) + } + } +} diff --git a/backend/internal/service/openai_model_alias.go b/backend/internal/service/openai_model_alias.go index dd822b2f4a..8a8a01a2f4 100644 --- a/backend/internal/service/openai_model_alias.go +++ b/backend/internal/service/openai_model_alias.go @@ -37,6 +37,9 @@ func normalizeKnownOpenAICodexModel(model string) string { } } + if openai.IsGPT61TerraModelSpelling(normalized) { + return "gpt-6.1-terra" + } if openai.IsGPT61SolModelSpelling(normalized) { return "gpt-6.1-sol" } @@ -163,5 +166,5 @@ func firstUsageBillingModel(candidates []string) string { } func isOpenAIGPT6Model(model string) bool { - return isOpenAIGPT6AstraModel(model) || openai.IsGPT6SolOrLunaModelSpelling(model) || openai.IsGPT61SolModelSpelling(model) + return openai.IsGPT61TerraModelSpelling(model) || isOpenAIGPT6AstraModel(model) || openai.IsGPT6SolOrLunaModelSpelling(model) || openai.IsGPT61SolModelSpelling(model) } diff --git a/backend/internal/service/pricing_service.go b/backend/internal/service/pricing_service.go index 6b8c6e0665..08f7f9d6ba 100644 --- a/backend/internal/service/pricing_service.go +++ b/backend/internal/service/pricing_service.go @@ -74,6 +74,23 @@ var ( Mode: "chat", SupportsPromptCaching: true, } + openAIGPT61TerraFallbackPricing = &LiteLLMModelPricing{ + InputCostPerToken: 1e-6, + InputCostPerTokenPriority: 2e-6, + OutputCostPerToken: 5e-6, + OutputCostPerTokenPriority: 10e-6, + CacheCreationInputTokenCost: 1.25e-6, + CacheCreationInputTokenCostPriority: 2.5e-6, + CacheReadInputTokenCost: 0.05e-6, + CacheReadInputTokenCostPriority: 0.1e-6, + LongContextInputTokenThreshold: 272_000, + LongContextInputCostMultiplier: 2, + LongContextOutputCostMultiplier: 1.5, + SupportsServiceTier: true, + LiteLLMProvider: "openai", + Mode: "chat", + SupportsPromptCaching: true, + } openAIGPT61SolFallbackPricing = &LiteLLMModelPricing{ InputCostPerToken: 2e-6, InputCostPerTokenPriority: 4e-6, @@ -1583,6 +1600,12 @@ func (s *PricingService) matchOpenAIModel(model string) *LiteLLMModelPricing { } } + if openai.IsGPT61TerraModelSpelling(model) { + if pricing, ok := s.pricingData["gpt-6.1-terra"]; ok { + return pricing + } + return openAIGPT61TerraFallbackPricing + } if openai.IsGPT61SolModelSpelling(model) { if pricing, ok := s.pricingData["gpt-6.1-sol"]; ok { return pricing diff --git a/backend/internal/service/response_model_billing_test.go b/backend/internal/service/response_model_billing_test.go index 6b04fc424a..1a09218b42 100644 --- a/backend/internal/service/response_model_billing_test.go +++ b/backend/internal/service/response_model_billing_test.go @@ -589,6 +589,127 @@ func TestOpenAIGatewayServiceRecordUsage_ResponseModelSkippedForSearchSurcharged // --- 渠道配置透传 --- +func TestGrokResponseAuditDefaultSourceKeepsCost(t *testing.T) { + tokens := UsageTokens{InputTokens: 20, OutputTokens: 10} + record := func(t *testing.T, source, responseModel string) float64 { + t.Helper() + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + userRepo := &openAIRecordUsageUserRepoStub{} + svc := newOpenAIRecordUsageServiceForTest(usageRepo, userRepo, &openAIRecordUsageSubRepoStub{}, nil) + err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: &OpenAIForwardResult{ + RequestID: "grok_audit_default_" + source + "_" + responseModel, + Model: "grok-4.7", + UpstreamModel: "grok-4.7", + UpstreamResponseModel: responseModel, + Usage: OpenAIUsage{InputTokens: tokens.InputTokens, OutputTokens: tokens.OutputTokens}, + Duration: time.Second, + }, + APIKey: &APIKey{ID: 10}, + User: &User{ID: 20}, + Account: &Account{ID: 30, Platform: PlatformGrok}, + ChannelUsageFields: ChannelUsageFields{ + ChannelID: 9, + OriginalModel: "grok-4.7", + ChannelMappedModel: "grok-4.7", + BillingModelSource: source, + }, + }) + require.NoError(t, err) + require.NotNil(t, usageRepo.lastLog) + if responseModel == "" { + require.Nil(t, usageRepo.lastLog.UpstreamResponseModel) + } else { + require.NotNil(t, usageRepo.lastLog.UpstreamResponseModel) + require.Equal(t, responseModel, *usageRepo.lastLog.UpstreamResponseModel) + } + return usageRepo.lastLog.ActualCost + } + + for _, source := range []string{"", BillingModelSourceChannelMapped} { + t.Run(source, func(t *testing.T) { + baseline := record(t, source, "") + withAlias := record(t, source, "grok-4.7-build") + withCheaper := record(t, source, "grok-4.3") + withFaster := record(t, source, "grok-4.7-fast") + require.Greater(t, baseline, 0.0) + require.InDelta(t, baseline, withAlias, 1e-12) + require.InDelta(t, baseline, withCheaper, 1e-12) + require.InDelta(t, baseline, withFaster, 1e-12) + }) + } +} + +func TestGrokResponseAuditResponseModelRejectsUnknownHigherAndConflict(t *testing.T) { + tokens := UsageTokens{InputTokens: 20, OutputTokens: 10} + record := func(t *testing.T, baseline, responseModel string, conflict bool) float64 { + t.Helper() + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + userRepo := &openAIRecordUsageUserRepoStub{} + svc := newOpenAIRecordUsageServiceForTest(usageRepo, userRepo, &openAIRecordUsageSubRepoStub{}, nil) + err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: &OpenAIForwardResult{ + RequestID: "grok_audit_explicit_" + baseline + "_" + responseModel, + Model: baseline, + UpstreamModel: baseline, + UpstreamResponseModel: responseModel, + UpstreamResponseModelConflict: conflict, + Usage: OpenAIUsage{InputTokens: tokens.InputTokens, OutputTokens: tokens.OutputTokens}, + Duration: time.Second, + }, + APIKey: &APIKey{ID: 10}, + User: &User{ID: 20}, + Account: &Account{ID: 30, Platform: PlatformGrok}, + ChannelUsageFields: ChannelUsageFields{ + ChannelID: 9, + OriginalModel: baseline, + ChannelMappedModel: baseline, + BillingModelSource: BillingModelSourceResponse, + }, + }) + require.NoError(t, err) + require.NotNil(t, usageRepo.lastLog) + return usageRepo.lastLog.ActualCost + } + + t.Run("unknown price", func(t *testing.T) { + svc := newOpenAIRecordUsageServiceForTest(&openAIRecordUsageLogRepoStub{}, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) + require.False(t, svc.billingService.HasIdentifiedTokenPricing("grok-4.5-build")) + baselineCost, err := svc.billingService.CalculateCost("grok-4.3", tokens, 1) + require.NoError(t, err) + familyCost, err := svc.billingService.CalculateCost("grok-4.5-build", tokens, 1) + require.NoError(t, err) + require.NotEqual(t, baselineCost.TotalCost, familyCost.TotalCost) + + require.InDelta(t, record(t, "grok-4.3", "", false), record(t, "grok-4.3", "grok-4.5-build", false), 1e-12) + }) + + t.Run("higher price", func(t *testing.T) { + svc := newOpenAIRecordUsageServiceForTest(&openAIRecordUsageLogRepoStub{}, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) + require.True(t, svc.billingService.HasIdentifiedTokenPricing("grok-4.7")) + require.True(t, svc.billingService.HasIdentifiedTokenPricing("grok-4.7-fast")) + baselineCost, err := svc.billingService.CalculateCost("grok-4.7", tokens, 1) + require.NoError(t, err) + fasterCost, err := svc.billingService.CalculateCost("grok-4.7-fast", tokens, 1) + require.NoError(t, err) + require.Greater(t, fasterCost.TotalCost, baselineCost.TotalCost) + + require.InDelta(t, record(t, "grok-4.7", "", false), record(t, "grok-4.7", "grok-4.7-fast", false), 1e-12) + }) + + t.Run("conflict", func(t *testing.T) { + svc := newOpenAIRecordUsageServiceForTest(&openAIRecordUsageLogRepoStub{}, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) + require.True(t, svc.billingService.HasIdentifiedTokenPricing("grok-4.3")) + baselineCost, err := svc.billingService.CalculateCost("grok-4.7", tokens, 1) + require.NoError(t, err) + cheaperCost, err := svc.billingService.CalculateCost("grok-4.3", tokens, 1) + require.NoError(t, err) + require.Less(t, cheaperCost.TotalCost, baselineCost.TotalCost) + + require.InDelta(t, record(t, "grok-4.7", "", false), record(t, "grok-4.7", "grok-4.3", true), 1e-12) + }) +} + func TestToUsageFields_ResponseModelSourcePassesThrough(t *testing.T) { r := ChannelMappingResult{ MappedModel: "claude-fable-5", diff --git a/backend/internal/service/upstream_models.go b/backend/internal/service/upstream_models.go index bfd82887f5..3d04d8ccb2 100644 --- a/backend/internal/service/upstream_models.go +++ b/backend/internal/service/upstream_models.go @@ -53,9 +53,19 @@ type UpstreamModelMetadataSnapshot struct { } type UpstreamModelCatalog struct { - Models []string `json:"models"` - Metadata map[string]UpstreamModelMetadata `json:"metadata,omitempty"` - Warnings []UpstreamModelSyncWarning `json:"warnings,omitempty"` + Models []string `json:"models"` + Metadata map[string]UpstreamModelMetadata `json:"metadata,omitempty"` + Warnings []UpstreamModelSyncWarning `json:"warnings,omitempty"` + DiscoverySource string `json:"discovery_source,omitempty"` + GrokModelDiagnostics *GrokModelDiagnostics `json:"grok_model_diagnostics,omitempty"` +} + +// upstreamModelListFetchResult is the live model list plus an optional Grok +// observation. Non-Grok fetches leave the observation nil. +type upstreamModelListFetchResult struct { + Models []string + Body []byte + GrokObservation *GrokCatalogObservation } type UpstreamModelSyncWarning struct { @@ -213,13 +223,32 @@ func (s *AccountTestService) FetchUpstreamSupportedModels(ctx context.Context, a // snapshot. When no model is complete, the existing account snapshot is left // untouched. func (s *AccountTestService) SyncUpstreamModelCatalog(ctx context.Context, account *Account) (*UpstreamModelCatalog, error) { - models, body, err := s.fetchUpstreamModelList(ctx, account) + fetched, err := s.fetchUpstreamModelListWithObservation(ctx, account) + var ( + models []string + body []byte + grokObservation *GrokCatalogObservation + ) + if fetched != nil { + models = fetched.Models + body = fetched.Body + grokObservation = fetched.GrokObservation + } liveListAvailable := err == nil if err != nil { configuredModels := configuredUpstreamModelsForCapabilitySync(account) if !upstreamModelListEndpointUnsupported(err) || len(configuredModels) == 0 { + s.keepGrokCatalogFailure(ctx, account, grokObservation) return nil, err } + if grokObservation != nil { + grokObservation.Attempt.Status = grokCatalogStatusConfiguredFallback + grokObservation.Attempt.ErrorCode = "http_error" + grokObservation.Models = nil + } + if saveErr := s.saveGrokCatalogObservation(ctx, account, grokObservation); saveErr != nil { + return nil, newUpstreamModelSyncInternalError("Failed to save upstream model catalog", saveErr) + } models = configuredModels body = nil slog.Info("upstream model list endpoint unavailable; using configured models for capability sync", @@ -228,8 +257,21 @@ func (s *AccountTestService) SyncUpstreamModelCatalog(ctx context.Context, accou "status_code", upstreamModelSyncStatusCode(err), "model_count", len(models), ) + } else if saveErr := s.saveGrokCatalogObservation(ctx, account, grokObservation); saveErr != nil { + return nil, newUpstreamModelSyncInternalError("Failed to save upstream model catalog", saveErr) } catalog := &UpstreamModelCatalog{Models: models, Metadata: make(map[string]UpstreamModelMetadata)} + if account != nil && account.IsGrok() { + if grokObservation != nil && grokObservation.Attempt.Status == grokCatalogStatusConfiguredFallback { + catalog.DiscoverySource = "configured_fallback" + catalog.Warnings = append(catalog.Warnings, UpstreamModelSyncWarning{ + Code: "grok_model_catalog_configured_fallback", + Message: "The upstream model list was unavailable; configured IDs were used only for capability enrichment.", + }) + } else if liveListAvailable { + catalog.DiscoverySource = "upstream" + } + } if len(body) > 0 { _, directMetadata, parseErr := extractUpstreamModelCatalog(body, account != nil && account.IsGrok()) if parseErr == nil { @@ -734,34 +776,54 @@ func normalizeModelRegistryBaseURL(raw string) string { } func (s *AccountTestService) fetchUpstreamModelList(ctx context.Context, account *Account) ([]string, []byte, error) { + result, err := s.fetchUpstreamModelListWithObservation(ctx, account) + if result == nil { + return nil, nil, err + } + return result.Models, result.Body, err +} + +func (s *AccountTestService) fetchUpstreamModelListWithObservation(ctx context.Context, account *Account) (*upstreamModelListFetchResult, error) { + started := time.Now().UTC() + models, body, req, err := s.fetchUpstreamModelListRequest(ctx, account) + result := &upstreamModelListFetchResult{Models: models, Body: body} + if account != nil && account.IsGrok() { + observation := buildGrokCatalogObservation(account, req, started, models, err) + result.GrokObservation = &observation + } + return result, err +} + +func (s *AccountTestService) fetchUpstreamModelListRequest(ctx context.Context, account *Account) ([]string, []byte, *http.Request, error) { if s == nil { - return nil, nil, newUpstreamModelSyncConfigError("Account test service is not configured", nil) + return nil, nil, nil, newUpstreamModelSyncConfigError("Account test service is not configured", nil) } if account == nil { - return nil, nil, newUpstreamModelSyncConfigError("Account is required", nil) + return nil, nil, nil, newUpstreamModelSyncConfigError("Account is required", nil) } if account.Platform == PlatformAntigravity && account.Type != AccountTypeAPIKey { - return s.fetchAntigravityOAuthUpstreamModels(ctx, account) + models, body, err := s.fetchAntigravityOAuthUpstreamModels(ctx, account) + return models, body, nil, err } if s.httpUpstream == nil { - return nil, nil, newUpstreamModelSyncConfigError("Upstream HTTP client is not configured", nil) + return nil, nil, nil, newUpstreamModelSyncConfigError("Upstream HTTP client is not configured", nil) } if account.IsGemini() && account.IsVertexServiceAccount() { models, err := s.fetchVertexGeminiUpstreamModels(ctx, account) - return models, nil, err + return models, nil, nil, err } req, err := s.buildUpstreamModelsRequest(ctx, account) if err != nil { - return nil, nil, err + return nil, nil, nil, err } body, err := s.readUpstreamModelsResponse(req, account) if err != nil { - return nil, nil, err + return nil, nil, req, err } extractModels := extractUpstreamModelIDs @@ -770,13 +832,38 @@ func (s *AccountTestService) fetchUpstreamModelList(ctx context.Context, account } models, err := extractModels(body) if err != nil { - return nil, nil, newUpstreamModelSyncUpstreamError("Upstream model list response was not valid JSON", err) + if account.IsGrok() && errors.Is(err, errGrokCatalogEmpty) { + return nil, nil, req, newUpstreamModelSyncUpstreamError("Upstream returned no supported models", err) + } + return nil, nil, req, newUpstreamModelSyncUpstreamError("Upstream model list response was not valid JSON", err) } if len(models) == 0 { - return nil, nil, newUpstreamModelSyncUpstreamError("Upstream returned no supported models", nil) + return nil, nil, req, newUpstreamModelSyncUpstreamError("Upstream returned no supported models", nil) } - return models, body, nil + return models, body, req, nil +} + +func (s *AccountTestService) saveGrokCatalogObservation(ctx context.Context, account *Account, observation *GrokCatalogObservation) error { + if s == nil || account == nil || !account.IsGrok() || account.ID <= 0 || observation == nil { + return nil + } + snap, err := PersistGrokCatalogObservation(ctx, s.accountRepo, account.ID, *observation) + if err != nil { + return err + } + rememberGrokObservedSnapshot(account, snap) + return nil +} + +func (s *AccountTestService) keepGrokCatalogFailure(ctx context.Context, account *Account, observation *GrokCatalogObservation) { + if err := s.saveGrokCatalogObservation(ctx, account, observation); err != nil { + slog.Warn("grok model catalog observation was not saved", + "account_id", upstreamModelSyncAccountID(account), + "platform", upstreamModelSyncPlatform(account), + "error", err, + ) + } } // readUpstreamModelsResponse 发送模型列表请求并读取受限大小的响应体;非 2xx 返回带状态码的同步错误。 @@ -1415,7 +1502,7 @@ func extractUpstreamModelIDs(body []byte) ([]string, error) { } func extractGrokUpstreamModelIDs(body []byte) ([]string, error) { - return extractUpstreamModelIDsWithSelector(body, grokUpstreamModelEntryID) + return parseGrokCatalogModelIDs(body) } func extractUpstreamModelCatalog(body []byte, grok bool) ([]string, map[string]UpstreamModelMetadata, error) { diff --git a/backend/internal/service/upstream_models_test.go b/backend/internal/service/upstream_models_test.go index e0e9f263ec..8d023f0383 100644 --- a/backend/internal/service/upstream_models_test.go +++ b/backend/internal/service/upstream_models_test.go @@ -6,6 +6,7 @@ import ( "errors" "io" "net/http" + "reflect" "strings" "testing" "time" @@ -19,6 +20,8 @@ type upstreamModelMetadataRepoStub struct { accountID int64 updates map[string]any err error + account *Account + casCalls int } func headerValuesEqualFold(header http.Header, name string) []string { @@ -36,6 +39,60 @@ func (r *upstreamModelMetadataRepoStub) UpdateExtra(_ context.Context, id int64, return r.err } +func (r *upstreamModelMetadataRepoStub) GetByID(_ context.Context, id int64) (*Account, error) { + if r == nil || r.account == nil || r.account.ID != id { + return nil, ErrAccountNotFound + } + return r.account, nil +} + +func (r *upstreamModelMetadataRepoStub) CompareAndSwapGrokObservedModels(ctx context.Context, id int64, expected, next json.RawMessage) (bool, error) { + if err := ctx.Err(); err != nil { + return false, err + } + r.casCalls++ + if r.account == nil || r.account.ID != id || r.account.Platform != PlatformGrok { + return false, nil + } + var current any + if r.account.Extra != nil { + current = r.account.Extra[grokObservedModelsExtraKey] + } + currentJSON, err := json.Marshal(current) + if err != nil { + return false, err + } + if !jsonValuesEqual(currentJSON, expected) { + return false, nil + } + var decoded any + if err := json.Unmarshal(next, &decoded); err != nil { + return false, err + } + if r.account.Extra == nil { + r.account.Extra = map[string]any{} + } + r.account.Extra[grokObservedModelsExtraKey] = decoded + return true, nil +} + +func jsonValuesEqual(left, right []byte) bool { + var lhs, rhs any + if len(left) == 0 { + left = []byte("null") + } + if len(right) == 0 { + right = []byte("null") + } + if err := json.Unmarshal(left, &lhs); err != nil { + return false + } + if err := json.Unmarshal(right, &rhs); err != nil { + return false + } + return reflect.DeepEqual(lhs, rhs) +} + func upstreamModelSyncTestConfig() *config.Config { return &config.Config{ Security: config.SecurityConfig{ diff --git a/backend/internal/service/upstream_response_model_test.go b/backend/internal/service/upstream_response_model_test.go index ea616d53ee..b97dcc4340 100644 --- a/backend/internal/service/upstream_response_model_test.go +++ b/backend/internal/service/upstream_response_model_test.go @@ -49,6 +49,7 @@ func TestUpstreamResponseModelObservationAttemptReset(t *testing.T) { func TestUpstreamModelMismatchThreeStateAndCaseInsensitiveComparison(t *testing.T) { require.Nil(t, upstreamModelMismatch("gpt-5.5", "")) + require.Nil(t, upstreamModelMismatch("grok-4.7", "")) matched := upstreamModelMismatch("gpt-5.5", "GPT-5.5") require.NotNil(t, matched) @@ -85,6 +86,11 @@ func TestUpstreamModelMismatchTreatsGrokBuildRuntimeIDsAsAliases(t *testing.T) { sentModel: "grok-4.5", responseModel: "GROK-4.5-BUILD", }, + { + name: "grok 4.7 build alias", + sentModel: "grok-4.7", + responseModel: "grok-4.7-build", + }, } for _, tt := range tests { @@ -118,6 +124,16 @@ func TestUpstreamModelMismatchDoesNotCollapseDifferentModels(t *testing.T) { sentModel: "grok-build-0.1", responseModel: "grok-4.5-build", }, + { + name: "composer fast is not a 4.5 build alias", + sentModel: "grok-composer-2.5-fast", + responseModel: "grok-4.5-build", + }, + { + name: "fast build is not the plain build alias", + sentModel: "grok-4.7-build-fast", + responseModel: "grok-4.7-build", + }, } for _, tt := range tests { diff --git a/backend/resources/model-pricing/model_prices_and_context_window.json b/backend/resources/model-pricing/model_prices_and_context_window.json index c1719fe659..57db84f6bb 100644 --- a/backend/resources/model-pricing/model_prices_and_context_window.json +++ b/backend/resources/model-pricing/model_prices_and_context_window.json @@ -17,6 +17,51 @@ "litellm_provider": "moonshot", "mode": "chat" }, + "gpt-6.1-terra": { + "cache_creation_input_token_cost": 1.25e-06, + "cache_read_input_token_cost": 5e-08, + "input_cost_per_token": 1e-06, + "output_cost_per_token": 5e-06, + "cache_creation_input_token_cost_priority": 2.5e-06, + "cache_creation_input_token_cost_flex": 6.25e-07, + "cache_creation_input_token_cost_batches": 6.25e-07, + "cache_read_input_token_cost_priority": 1e-07, + "cache_read_input_token_cost_flex": 2.5e-08, + "cache_read_input_token_cost_batches": 2.5e-08, + "input_cost_per_token_priority": 2e-06, + "input_cost_per_token_flex": 5e-07, + "input_cost_per_token_batches": 5e-07, + "output_cost_per_token_priority": 1e-05, + "output_cost_per_token_flex": 2.5e-06, + "output_cost_per_token_batches": 2.5e-06, + "long_context_input_token_threshold": 272000, + "long_context_input_cost_multiplier": 2, + "long_context_output_cost_multiplier": 1.5, + "litellm_provider": "openai", + "mode": "chat", + "max_input_tokens": 922000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "context_window": 1050000, + "supported_endpoints": [ + "/v1/chat/completions", + "/v1/responses", + "/v1/batch" + ], + "supported_modalities": [ + "text", + "image" + ], + "supported_output_modalities": [ + "text" + ], + "supports_function_calling": true, + "supports_none_reasoning_effort": true, + "supports_xhigh_reasoning_effort": true, + "supports_reasoning": true, + "supports_prompt_caching": true, + "supports_service_tier": true + }, "gpt-6.1-sol": { "cache_creation_input_token_cost": 2.5e-06, "cache_creation_input_token_cost_batches": 1.25e-06, diff --git a/frontend/src/api/__tests__/admin.accounts.grokModelDiagnostics.spec.ts b/frontend/src/api/__tests__/admin.accounts.grokModelDiagnostics.spec.ts new file mode 100644 index 0000000000..ef7c906506 --- /dev/null +++ b/frontend/src/api/__tests__/admin.accounts.grokModelDiagnostics.spec.ts @@ -0,0 +1,81 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { GrokModelDiagnostics } from '@/types' + +const { get, post } = vi.hoisted(() => ({ + get: vi.fn(), + post: vi.fn() +})) + +vi.mock('@/api/client', () => ({ + apiClient: { get, post } +})) + +import { getById, syncUpstreamModels } from '@/api/admin/accounts' + +const diagnostics: GrokModelDiagnostics = { + state: 'fresh', + endpoint: 'https://cli-chat-proxy.grok.com/v1/models', + fetched_at: '2026-10-25T11:00:00.000Z', + expires_at: '2026-10-25T17:00:00.000Z', + models: ['grok-4.7'], + last_attempt: { + started_at: '2026-10-25T11:00:00.000Z', + finished_at: '2026-10-25T11:00:01.000Z', + status: 'failed', + error_code: 'upstream_unavailable', + scope: { + account_id: 25, + account_type: 'oauth', + endpoint: 'https://cli-chat-proxy.grok.com/v1/models', + fingerprint: 'abc' + } + }, + mappings: [ + { requested: 'friendly', upstream: 'grok-4.7', status: 'listed' } + ] +} + +describe('admin account grok model diagnostics API', () => { + beforeEach(() => { + get.mockReset() + post.mockReset() + }) + + it('keeps optional diagnostics from the existing account detail response', async () => { + const account = { id: 25, platform: 'grok', grok_model_diagnostics: diagnostics } + get.mockResolvedValueOnce({ data: account }) + + await expect(getById(25)).resolves.toEqual(account) + expect(get).toHaveBeenCalledTimes(1) + expect(get).toHaveBeenCalledWith('/admin/accounts/25') + expect(get.mock.calls[0]).toHaveLength(1) + }) + + it('preserves discovery source and diagnostics on the existing sync URL', async () => { + const result = { + models: ['grok-4.7'], + discovery_source: 'upstream' as const, + grok_model_diagnostics: diagnostics, + warnings: [{ code: 'upstream_model_metadata_incomplete', message: 'incomplete' }] + } + post.mockResolvedValueOnce({ data: result }) + + await expect(syncUpstreamModels(25)).resolves.toEqual(result) + expect(post).toHaveBeenCalledTimes(1) + expect(post).toHaveBeenCalledWith('/admin/accounts/25/models/sync-upstream') + expect(post.mock.calls[0]).toHaveLength(1) + }) + + it('leaves omitted diagnostics and discovery source absent for older responses', async () => { + get.mockResolvedValueOnce({ data: { id: 3, platform: 'openai' } }) + post.mockResolvedValueOnce({ data: { models: ['gpt-6'] } }) + + const account = await getById(3) + const synced = await syncUpstreamModels(3) + + expect(account).not.toHaveProperty('grok_model_diagnostics') + expect(synced).not.toHaveProperty('discovery_source') + expect(synced).not.toHaveProperty('grok_model_diagnostics') + expect(post).toHaveBeenLastCalledWith('/admin/accounts/3/models/sync-upstream') + }) +}) diff --git a/frontend/src/api/admin/accounts.ts b/frontend/src/api/admin/accounts.ts index e504775fa3..44d0ab9be0 100644 --- a/frontend/src/api/admin/accounts.ts +++ b/frontend/src/api/admin/accounts.ts @@ -30,6 +30,7 @@ import type { OllamaCloudUsageState, GrokMediaEligibilityMode, GrokMediaEligibilityState, + GrokModelDiagnostics, OpenCodeGoUsageSettings, OpenCodeGoUsageState } from '@/types' @@ -611,6 +612,8 @@ export interface SyncUpstreamModelsResult { models: string[] metadata?: Record warnings?: UpstreamModelSyncWarning[] + discovery_source?: 'upstream' | 'configured_fallback' + grok_model_diagnostics?: GrokModelDiagnostics } export interface UpstreamModelSyncWarning { diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index 288abd793e..9ca560b519 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -251,7 +251,11 @@ -
+
-
+
+ + + +
-

{{ t('admin.accounts.selectedModels', { count: allowedModels.length }) }} {{ @@ -330,10 +379,11 @@

-
-
-

+

+
+

+
+ {{ t('admin.accounts.grokModelDiagnostics.requestColumn') }} + + {{ t('admin.accounts.grokModelDiagnostics.targetColumn') }} +
+
+
+ + + +
-

{{ t('admin.accounts.selectedModels', { count: allowedModels.length }) }} {{ @@ -852,26 +975,47 @@

-
-
-

+

+
+

{{ t('admin.accounts.mapRequestModels') }}

+
+ {{ t('admin.accounts.grokModelDiagnostics.requestColumn') }} + + {{ t('admin.accounts.grokModelDiagnostics.targetColumn') }} +
+
+