diff --git a/README.md b/README.md index 6bb4068644..b06839745f 100644 --- a/README.md +++ b/README.md @@ -163,6 +163,12 @@ Model authenticity: no content intervention or secondary filtering — experienc + +aimzoon +Thanks to Aimzoon for sponsoring this project! Aimzoon provides stable, cost-effective AI API access services, enabling developers to quickly connect popular AI services to coding tools such as Codex, Claude Code, and Gemini CLI. No complex configuration — faster onboarding, more stable calls, and lower costs. Ongoing promotions including discounted Codex rates and special pricing, with free trial credits upon registration, bringing AI coding into your daily workflow. Click here to register and try it out! + + + ## Overview @@ -605,12 +611,19 @@ per-turn user and account concurrency slots, which are released between turns. ```yaml gateway: openai_ws: + # Total time to receive and decompress the first client message. + client_first_message_timeout_seconds: 30 # Close a client socket idle between completed turns; 0 disables this safeguard. ingress_inter_turn_idle_timeout_seconds: 300 # Distributed API-key limit for live client ingress sessions; 0 disables it. max_ingress_connections_per_api_key: 64 ``` +The first-message timeout is a total read deadline. Deployments that accept +large contexts or image-heavy requests over slower links can raise it to +120-300 seconds. It expires before HTTP bridge routing, so bridge mode does not +override this limit. + The connection cap is coordinated through Redis using a 60-second lease that is refreshed every 20 seconds. A process that cannot confirm a lease for a full lease lifetime closes its local WebSocket rather than continuing outside @@ -728,14 +741,13 @@ For API-key accounts, select **Grok → API Key** in the create-account dialog. ```toml [models] -default = "sub2api-grok" -web_search = "sub2api-grok" +default = "grok" +web_search = "grok" -[model."sub2api-grok"] +[model."grok"] model = "grok-4.5" base_url = "https://your-sub2api.example.com/v1" -name = "Grok 4.5 via Sub2API" -description = "Grok 4.5 through a Sub2API Grok group" +name = "Grok 4.5" api_key = "sk-your-sub2api-key" api_backend = "responses" context_window = 1000000 @@ -746,7 +758,7 @@ Back up an existing `config.toml` before merging the entry. The file contains a ```bash grok inspect -grok -p "Reply with sub2api-ok" -m sub2api-grok +grok -p "Reply with sub2api-ok" -m grok ``` The `base_url` above is the public Sub2API URL ending in `/v1`, not `api.x.ai` or the internal xAI OAuth proxy URL. diff --git a/README_CN.md b/README_CN.md index 348e1c93c4..b1139dd122 100644 --- a/README_CN.md +++ b/README_CN.md @@ -166,6 +166,11 @@ + +aimzoon +感谢 Aimzoon 对本项目的赞助! Aimzoon 提供稳定、高性价比的 AI API 接入服务,支持开发者将常用 AI 服务快速接入 Codex、Claude Code、Gemini CLI 等编程工具。无需复杂配置,更快接入,更稳调用,更省成本。codex倍率优惠,特价倍率等促销不断,注册即送免费体验额度,让 AI 编程真正进入日常工作流。点击这里注册体验! + + diff --git a/README_JA.md b/README_JA.md index ac18b36387..ba556139ee 100644 --- a/README_JA.md +++ b/README_JA.md @@ -161,6 +161,12 @@ + +aimzoon +Aimzoon のご支援に感謝します!Aimzoon は安定してコストパフォーマンスに優れた AI API 接続サービスを提供し、開発者が主要な AI サービスを Codex、Claude Code、Gemini CLI などのコーディングツールへ素早く接続できるようにします。複雑な設定は不要で、より速い接続、より安定した呼び出し、より低いコストを実現。Codex レート割引や特価レートなどのキャンペーンも随時開催中、登録するだけで無料お試しクレジットをプレゼント。AI コーディングを日常のワークフローへ。こちらから登録してお試しください! + + + ## 概要 diff --git a/assets/partners/logos/aimzoon.jpg b/assets/partners/logos/aimzoon.jpg new file mode 100644 index 0000000000..3fa8c653c8 Binary files /dev/null and b/assets/partners/logos/aimzoon.jpg differ diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index c64f02bbc3..7a29ae6cd9 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -0.1.153 +0.1.155 diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 9cae353c78..86721fbac0 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -70,6 +70,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { concurrencyCache := repository.ProvideConcurrencyCache(redisClient, configConfig) schedulerCache := repository.ProvideSchedulerCache(redisClient, configConfig) accountRepository := repository.NewAccountRepository(client, db, schedulerCache) + adminAccountRepository := repository.NewAdminAccountRepository(client, db, schedulerCache) concurrencyService := service.ProvideConcurrencyService(concurrencyCache, accountRepository, configConfig) apiKeyService := service.ProvideAPIKeyService(apiKeyRepository, userRepository, groupRepository, userSubscriptionRepository, userGroupRateRepository, apiKeyCache, configConfig, billingCacheService, concurrencyService) apiKeyAuthCacheInvalidator := service.ProvideAPIKeyAuthCacheInvalidator(apiKeyService) @@ -96,9 +97,6 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { usageLogRepository := repository.NewUsageLogRepository(client, db) usageService := service.NewUsageService(usageLogRepository, userRepository, client, apiKeyAuthCacheInvalidator) opsRepository := repository.NewOpsRepository(db) - batchImageRepository := repository.NewBatchImageRepository(db) - batchImageQueue := repository.NewBatchImageQueue(redisClient, configConfig) - batchImageDownloadLimiter := repository.NewBatchImageDownloadLimiter(redisClient, configConfig) usageBillingRepository := repository.NewUsageBillingRepository(client, db) gatewayCache := repository.NewGatewayCache(redisClient) schedulerOutboxRepository := repository.NewSchedulerOutboxRepository(db) @@ -137,11 +135,6 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { channelRepository := repository.NewChannelRepository(db) channelService := service.NewChannelService(channelRepository, groupRepository, apiKeyAuthCacheInvalidator, pricingService) modelPricingResolver := service.NewModelPricingResolver(channelService, billingService) - batchImageModelPricingResolver := service.ProvideBatchImageModelPricingResolver(modelPricingResolver) - batchImagePublicService := service.NewBatchImagePublicService(batchImageRepository, accountRepository, groupRepository, userGroupRateRepository, batchImageQueue, batchImageModelPricingResolver, usageBillingRepository, apiKeyAuthCacheInvalidator, configConfig) - batchImageDownloadService := service.NewBatchImageDownloadService(batchImageRepository, accountRepository, batchImageDownloadLimiter, configConfig) - batchImageCleanupService := service.ProvideBatchImageCleanupService(batchImageRepository, accountRepository, configConfig) - batchImageWorkerRuntime := service.ProvideBatchImageWorkerRuntime(batchImageRepository, accountRepository, batchImageQueue, usageBillingRepository, usageLogRepository, batchImageModelPricingResolver, apiKeyAuthCacheInvalidator, configConfig) notificationEmailService := service.NewNotificationEmailService(settingRepository, emailService) balanceNotifyService := service.ProvideBalanceNotifyService(emailService, settingRepository, accountRepository, notificationEmailService) gatewayService := service.NewGatewayService(accountRepository, groupRepository, usageLogRepository, usageBillingRepository, userRepository, userSubscriptionRepository, userGroupRateRepository, gatewayCache, configConfig, schedulerSnapshotService, concurrencyService, billingService, rateLimitService, billingCacheService, identityService, httpUpstream, deferredService, claudeTokenProvider, sessionLimitCache, rpmCache, digestSessionStore, settingService, tlsFingerprintProfileService, channelService, modelPricingResolver, balanceNotifyService, serviceUserPlatformQuotaRepository) @@ -183,7 +176,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { dashboardHandler := admin.NewDashboardHandler(dashboardService, dashboardAggregationService) proxyExitInfoProber := repository.NewProxyExitInfoProber(configConfig) proxyLatencyCache := repository.NewProxyLatencyCache(redisClient) - adminService := service.NewAdminService(userRepository, groupRepository, accountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService) + adminService := service.NewAdminService(userRepository, groupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService) adminUserHandler := admin.NewUserHandler(adminService, concurrencyService, serviceUserPlatformQuotaRepository, billingCache) groupCapacityService := service.NewGroupCapacityService(accountRepository, groupRepository, concurrencyService, sessionLimitCache, rpmCache) groupHandler := admin.NewGroupHandler(adminService, dashboardService, groupCapacityService) @@ -191,10 +184,10 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { antigravityQuotaFetcher := service.NewAntigravityQuotaFetcher(proxyRepository) grokQuotaFetcher := service.NewGrokQuotaFetcher() grokQuotaService := service.ProvideGrokQuotaService(accountRepository, proxyRepository, grokTokenProvider, httpUpstream, usageLogRepository) - openAIQuotaService := service.ProvideOpenAIQuotaService(accountRepository, proxyRepository, openAITokenProvider, privacyClientFactory) + openAIQuotaService := service.ProvideOpenAIQuotaService(accountRepository, proxyRepository, openAITokenProvider, privacyClientFactory, openAIGatewayService) usageCache := service.NewUsageCache() - accountUsageService := service.NewAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher, geminiQuotaService, antigravityQuotaFetcher, grokQuotaFetcher, grokQuotaService, openAIQuotaService, usageCache, identityCache, tlsFingerprintProfileService) - accountTestService := service.NewAccountTestService(accountRepository, geminiTokenProvider, claudeTokenProvider, grokTokenProvider, antigravityGatewayService, httpUpstream, configConfig, tlsFingerprintProfileService) + accountUsageService := service.ProvideAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher, geminiQuotaService, antigravityQuotaFetcher, grokQuotaFetcher, grokQuotaService, openAIQuotaService, usageCache, identityCache, tlsFingerprintProfileService, openAIGatewayService) + accountTestService := service.ProvideAccountTestService(accountRepository, geminiTokenProvider, claudeTokenProvider, grokTokenProvider, antigravityGatewayService, httpUpstream, configConfig, tlsFingerprintProfileService, openAIGatewayService) crsSyncService := service.NewCRSSyncService(accountRepository, proxyRepository, oAuthService, openAIOAuthService, geminiOAuthService, configConfig) accountHandler := admin.ProvideAccountHandler(adminService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, rateLimitService, accountUsageService, accountTestService, concurrencyService, crsSyncService, sessionLimitCache, rpmCache, compositeTokenCacheInvalidator, grokQuotaService) adminAnnouncementHandler := admin.NewAnnouncementHandler(announcementService) @@ -208,7 +201,8 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { openAIOAuthHandler := admin.NewOpenAIOAuthHandler(openAIOAuthService, adminService, openAIQuotaService) geminiOAuthHandler := admin.NewGeminiOAuthHandler(geminiOAuthService) antigravityOAuthHandler := admin.NewAntigravityOAuthHandler(antigravityOAuthService) - grokOAuthHandler := admin.NewGrokOAuthHandler(grokOAuthService, adminService, grokQuotaService) + tokenRefreshService := service.ProvideTokenRefreshService(accountRepository, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, compositeTokenCacheInvalidator, schedulerCache, configConfig, tempUnschedCache, privacyClientFactory, proxyRepository, oAuthRefreshAPI, openAIGatewayService) + grokOAuthHandler := admin.NewGrokOAuthHandler(grokOAuthService, adminService, grokQuotaService, tokenRefreshService) proxyHandler := admin.NewProxyHandler(adminService) adminRedeemHandler := admin.NewRedeemHandler(adminService, redeemService) promoHandler := admin.NewPromoHandler(promoService) @@ -267,6 +261,13 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { handlerPaymentHandler := handler.NewPaymentHandler(paymentService, paymentConfigService) paymentWebhookHandler := handler.NewPaymentWebhookHandler(paymentService, registry) availableChannelHandler := handler.NewAvailableChannelHandler(channelService, apiKeyService, settingService) + batchImageRepository := repository.NewBatchImageRepository(db) + batchImageQueue := repository.NewBatchImageQueue(redisClient, configConfig) + batchImageModelPricingResolver := service.ProvideBatchImageModelPricingResolver(modelPricingResolver) + batchImagePublicService := service.NewBatchImagePublicService(batchImageRepository, accountRepository, groupRepository, userGroupRateRepository, batchImageQueue, batchImageModelPricingResolver, usageBillingRepository, apiKeyAuthCacheInvalidator, configConfig) + batchImageDownloadLimiter := repository.NewBatchImageDownloadLimiter(redisClient, configConfig) + batchImageDownloadService := service.NewBatchImageDownloadService(batchImageRepository, accountRepository, batchImageDownloadLimiter, configConfig) + batchImageCleanupService := service.ProvideBatchImageCleanupService(batchImageRepository, accountRepository, configConfig) batchImageHandler := handler.NewBatchImageHandler(batchImagePublicService, batchImageDownloadService, batchImageCleanupService) idempotencyCoordinator := service.ProvideIdempotencyCoordinator(idempotencyRepository, configConfig) idempotencyCleanupService := service.ProvideIdempotencyCleanupService(idempotencyRepository, configConfig) @@ -281,10 +282,10 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { opsAlertEvaluatorService := service.ProvideOpsAlertEvaluatorService(opsService, opsRepository, emailService, redisClient, configConfig, proxyRepository) opsCleanupService := service.ProvideOpsCleanupService(opsRepository, db, redisClient, configConfig, channelMonitorService, settingRepository, opsService) opsScheduledReportService := service.ProvideOpsScheduledReportService(opsService, userService, emailService, redisClient, configConfig) - tokenRefreshService := service.ProvideTokenRefreshService(accountRepository, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, compositeTokenCacheInvalidator, schedulerCache, configConfig, tempUnschedCache, privacyClientFactory, proxyRepository, oAuthRefreshAPI, openAIGatewayService) accountExpiryService := service.ProvideAccountExpiryService(accountRepository) proxyExpiryService := service.ProvideProxyExpiryService(proxyRepository) subscriptionExpiryService := service.ProvideSubscriptionExpiryService(userSubscriptionRepository, settingRepository, notificationEmailService, leaderLockCache, db) + batchImageWorkerRuntime := service.ProvideBatchImageWorkerRuntime(batchImageRepository, accountRepository, batchImageQueue, usageBillingRepository, usageLogRepository, batchImageModelPricingResolver, apiKeyAuthCacheInvalidator, configConfig) scheduledTestRunnerService := service.ProvideScheduledTestRunnerService(scheduledTestPlanRepository, scheduledTestService, accountTestService, rateLimitService, configConfig) paymentOrderExpiryService := service.ProvidePaymentOrderExpiryService(paymentService, leaderLockCache, db) channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService) diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index 1262845cea..2064c0c7ea 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -580,6 +580,18 @@ type TokenRefreshConfig struct { MaxRetries int `mapstructure:"max_retries"` // 重试退避基础时间(秒) RetryBackoffSeconds int `mapstructure:"retry_backoff_seconds"` + // 每次从数据库读取的候选账号上限 + CandidatePageSize int `mapstructure:"candidate_page_size"` + // 每个平台允许的并发刷新数 + ProviderConcurrency int `mapstructure:"provider_concurrency"` + // 每个平台、每个进程允许的刷新请求速率 + ProviderQPS int `mapstructure:"provider_qps"` + // 一个周期内连续临时失败达到此值后停止该平台 + ProviderFailureThreshold int `mapstructure:"provider_failure_threshold"` + // 单次上游刷新尝试的超时(秒) + AttemptTimeoutSeconds int `mapstructure:"attempt_timeout_seconds"` + // 单个后台刷新周期的总超时(秒) + CycleTimeoutSeconds int `mapstructure:"cycle_timeout_seconds"` } type PricingConfig struct { @@ -748,6 +760,11 @@ type GatewayConfig struct { // OpenAIResponseHeaderTimeout: OpenAI/Codex 上游等待响应头的超时时间(秒),0表示无超时 // OpenAI/Codex 请求可能在上游排队较久;默认不使用通用响应头超时截断。 OpenAIResponseHeaderTimeout int `mapstructure:"openai_response_header_timeout"` + // OpenAIFirstOutputTimeoutSeconds: native HTTP Responses 首个语义输出超时(秒),0表示禁用。 + OpenAIFirstOutputTimeoutSeconds int `mapstructure:"openai_first_output_timeout_seconds"` + // OpenAIHighEffortFirstOutputTimeoutSeconds: high/xhigh/max 推理的首个语义输出超时(秒)。 + // 0 表示回退到 OpenAIFirstOutputTimeoutSeconds。 + OpenAIHighEffortFirstOutputTimeoutSeconds int `mapstructure:"openai_high_effort_first_output_timeout_seconds"` // 请求体最大字节数,用于网关请求体大小限制 MaxBodySize int64 `mapstructure:"max_body_size"` // 非流式上游响应体读取上限(字节),用于防止无界读取导致内存放大 @@ -919,6 +936,9 @@ func (c *UserMessageQueueConfig) GetEffectiveMode() string { return "" } +// DefaultOpenAIWSClientFirstMessageTimeoutSeconds preserves the legacy ingress deadline. +const DefaultOpenAIWSClientFirstMessageTimeoutSeconds = 30 + // GatewayOpenAIWSConfig OpenAI Responses WebSocket 配置。 // 注意:默认全局开启;如需回滚可使用 force_http 或关闭 enabled。 type GatewayOpenAIWSConfig struct { @@ -926,6 +946,9 @@ type GatewayOpenAIWSConfig struct { ModeRouterV2Enabled bool `mapstructure:"mode_router_v2_enabled"` // IngressModeDefault: ingress 默认模式(off/ctx_pool/passthrough/http_bridge) IngressModeDefault string `mapstructure:"ingress_mode_default"` + // ClientFirstMessageTimeoutSeconds bounds the total time to read and decompress + // the first client response.create message after the WebSocket upgrade. + ClientFirstMessageTimeoutSeconds int `mapstructure:"client_first_message_timeout_seconds"` // IngressInterTurnIdleTimeoutSeconds bounds the time a client may remain idle // between completed ingress turns. Zero disables this protection. IngressInterTurnIdleTimeoutSeconds int `mapstructure:"ingress_inter_turn_idle_timeout_seconds"` @@ -1944,6 +1967,8 @@ func setDefaults() { // Gateway viper.SetDefault("gateway.response_header_timeout", 600) // 600秒(10分钟)等待上游响应头,LLM高负载时可能排队较久 viper.SetDefault("gateway.openai_response_header_timeout", 0) + viper.SetDefault("gateway.openai_first_output_timeout_seconds", 0) + viper.SetDefault("gateway.openai_high_effort_first_output_timeout_seconds", 0) viper.SetDefault("gateway.log_upstream_error_body", true) viper.SetDefault("gateway.log_upstream_error_body_max_bytes", 2048) viper.SetDefault("gateway.inject_beta_for_apikey", false) @@ -1958,6 +1983,7 @@ func setDefaults() { viper.SetDefault("gateway.openai_ws.enabled", true) viper.SetDefault("gateway.openai_ws.mode_router_v2_enabled", false) viper.SetDefault("gateway.openai_ws.ingress_mode_default", "ctx_pool") + viper.SetDefault("gateway.openai_ws.client_first_message_timeout_seconds", DefaultOpenAIWSClientFirstMessageTimeoutSeconds) viper.SetDefault("gateway.openai_ws.ingress_inter_turn_idle_timeout_seconds", 300) viper.SetDefault("gateway.openai_ws.max_ingress_connections_per_api_key", 64) viper.SetDefault("gateway.openai_ws.oauth_enabled", true) @@ -2098,6 +2124,12 @@ func setDefaults() { viper.SetDefault("token_refresh.refresh_before_expiry_hours", 0.5) // 提前30分钟刷新(适配Google 1小时token) viper.SetDefault("token_refresh.max_retries", 3) // 最多重试3次 viper.SetDefault("token_refresh.retry_backoff_seconds", 2) // 重试退避基础2秒 + viper.SetDefault("token_refresh.candidate_page_size", 200) + viper.SetDefault("token_refresh.provider_concurrency", 4) + viper.SetDefault("token_refresh.provider_qps", 2) + viper.SetDefault("token_refresh.provider_failure_threshold", 3) + viper.SetDefault("token_refresh.attempt_timeout_seconds", 15) + viper.SetDefault("token_refresh.cycle_timeout_seconds", 240) // Gemini OAuth - configure via environment variables or config file // GEMINI_OAUTH_CLIENT_ID and GEMINI_OAUTH_CLIENT_SECRET @@ -2651,6 +2683,14 @@ func (c *Config) Validate() error { if c.Gateway.OpenAIResponseHeaderTimeout < 0 { return fmt.Errorf("gateway.openai_response_header_timeout must be non-negative") } + if c.Gateway.OpenAIFirstOutputTimeoutSeconds < 0 || c.Gateway.OpenAIFirstOutputTimeoutSeconds > 600 || + (c.Gateway.OpenAIFirstOutputTimeoutSeconds > 0 && c.Gateway.OpenAIFirstOutputTimeoutSeconds < 30) { + return fmt.Errorf("gateway.openai_first_output_timeout_seconds must be 0 or between 30-600 seconds") + } + if c.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds < 0 || c.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds > 1800 || + (c.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds > 0 && c.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds < 30) { + return fmt.Errorf("gateway.openai_high_effort_first_output_timeout_seconds must be 0 or between 30-1800 seconds") + } if strings.TrimSpace(c.Gateway.ConnectionPoolIsolation) != "" { switch c.Gateway.ConnectionPoolIsolation { case ConnectionPoolIsolationProxy, ConnectionPoolIsolationAccount, ConnectionPoolIsolationAccountProxy: @@ -2740,6 +2780,9 @@ func (c *Config) Validate() error { if c.Gateway.OpenAIWS.MaxConnsPerAccount <= 0 { return fmt.Errorf("gateway.openai_ws.max_conns_per_account must be positive") } + if c.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds <= 0 { + return fmt.Errorf("gateway.openai_ws.client_first_message_timeout_seconds must be positive") + } if c.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds < 0 { return fmt.Errorf("gateway.openai_ws.ingress_inter_turn_idle_timeout_seconds must be non-negative") } diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go index 2f9defb80e..9a2d725eed 100644 --- a/backend/internal/config/config_test.go +++ b/backend/internal/config/config_test.go @@ -98,6 +98,34 @@ func TestLoadDefaultSchedulingConfig(t *testing.T) { } } +func TestLoadDefaultOpenAIFirstOutputTimeoutsDisabled(t *testing.T) { + resetViperWithJWTSecret(t) + + cfg, err := Load() + require.NoError(t, err) + require.Zero(t, cfg.Gateway.OpenAIFirstOutputTimeoutSeconds) + require.Zero(t, cfg.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds) +} + +func TestLoadOpenAIFirstOutputTimeoutsFromEnv(t *testing.T) { + resetViperWithJWTSecret(t) + t.Setenv("GATEWAY_OPENAI_FIRST_OUTPUT_TIMEOUT_SECONDS", "90") + t.Setenv("GATEWAY_OPENAI_HIGH_EFFORT_FIRST_OUTPUT_TIMEOUT_SECONDS", "240") + + cfg, err := Load() + require.NoError(t, err) + require.Equal(t, 90, cfg.Gateway.OpenAIFirstOutputTimeoutSeconds) + require.Equal(t, 240, cfg.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds) +} + +func TestValidateOpenAIFirstOutputTimeoutMinimum(t *testing.T) { + resetViperWithJWTSecret(t) + cfg, err := Load() + require.NoError(t, err) + cfg.Gateway.OpenAIFirstOutputTimeoutSeconds = 30 + require.NoError(t, cfg.Validate()) +} + func TestLoadDefaultOpenAIWSConfig(t *testing.T) { resetViperWithJWTSecret(t) @@ -199,6 +227,13 @@ func TestLoadDefaultOpenAIWSConfig(t *testing.T) { if cfg.Gateway.OpenAIWS.IngressModeDefault != "ctx_pool" { t.Fatalf("Gateway.OpenAIWS.IngressModeDefault = %q, want %q", cfg.Gateway.OpenAIWS.IngressModeDefault, "ctx_pool") } + if cfg.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds != DefaultOpenAIWSClientFirstMessageTimeoutSeconds { + t.Fatalf( + "Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds = %d, want %d", + cfg.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds, + DefaultOpenAIWSClientFirstMessageTimeoutSeconds, + ) + } if cfg.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds != 300 { t.Fatalf("Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds = %d, want 300", cfg.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds) } @@ -207,6 +242,15 @@ func TestLoadDefaultOpenAIWSConfig(t *testing.T) { } } +func TestLoadOpenAIWSClientFirstMessageTimeoutFromEnv(t *testing.T) { + resetViperWithJWTSecret(t) + t.Setenv("GATEWAY_OPENAI_WS_CLIENT_FIRST_MESSAGE_TIMEOUT_SECONDS", "120") + + cfg, err := Load() + require.NoError(t, err) + require.Equal(t, 120, cfg.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds) +} + func TestLoadDefaultOpenAICompactModel(t *testing.T) { resetViperWithJWTSecret(t) @@ -1348,6 +1392,16 @@ func TestValidateConfigErrors(t *testing.T) { mutate: func(c *Config) { c.Gateway.OpenAIResponseHeaderTimeout = -1 }, wantErr: "gateway.openai_response_header_timeout", }, + { + name: "gateway openai first output timeout below minimum", + mutate: func(c *Config) { c.Gateway.OpenAIFirstOutputTimeoutSeconds = 29 }, + wantErr: "gateway.openai_first_output_timeout_seconds", + }, + { + name: "gateway openai high effort first output timeout too large", + mutate: func(c *Config) { c.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds = 1801 }, + wantErr: "gateway.openai_high_effort_first_output_timeout_seconds", + }, { name: "gateway max idle conns", mutate: func(c *Config) { c.Gateway.MaxIdleConns = 0 }, @@ -1682,6 +1736,16 @@ func TestValidateConfig_OpenAIWSRules(t *testing.T) { mutate: func(c *Config) { c.Gateway.OpenAIWS.MaxConnsPerAccount = 0 }, wantErr: "gateway.openai_ws.max_conns_per_account", }, + { + name: "client_first_message_timeout_seconds 必须为正数", + mutate: func(c *Config) { c.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds = 0 }, + wantErr: "gateway.openai_ws.client_first_message_timeout_seconds", + }, + { + name: "client_first_message_timeout_seconds 不能为负数", + mutate: func(c *Config) { c.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds = -1 }, + wantErr: "gateway.openai_ws.client_first_message_timeout_seconds", + }, { name: "ingress_inter_turn_idle_timeout_seconds 不能为负数", mutate: func(c *Config) { c.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds = -1 }, diff --git a/backend/internal/handler/admin/account_codex_agent_identity_import_test.go b/backend/internal/handler/admin/account_codex_agent_identity_import_test.go new file mode 100644 index 0000000000..db55182b6b --- /dev/null +++ b/backend/internal/handler/admin/account_codex_agent_identity_import_test.go @@ -0,0 +1,47 @@ +package admin + +import ( + "crypto/ed25519" + "crypto/rand" + "crypto/x509" + "encoding/base64" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestNormalizeCodexImportEntryAcceptsAgentIdentityAuthJSON(t *testing.T) { + _, privateKey, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + der, err := x509.MarshalPKCS8PrivateKey(privateKey) + require.NoError(t, err) + privateKeyBase64 := base64.StdEncoding.EncodeToString(der) + + item, err := normalizeCodexImportEntry(codexImportEntry{ + Index: 1, + Value: map[string]any{ + "auth_mode": "agentIdentity", + "agent_identity": map[string]any{ + "agent_runtime_id": "runtime-import", + "agent_private_key": privateKeyBase64, + "account_id": "account-import", + "chatgpt_user_id": "user-import", + "email": "agent@example.invalid", + "plan_type": "pro", + "chatgpt_account_is_fedramp": false, + }, + }, + }) + require.NoError(t, err) + require.NotNil(t, item) + require.True(t, item.IsAgentIdentity) + require.Equal(t, service.OpenAIAuthModeAgentIdentity, item.Credentials["auth_mode"]) + require.Equal(t, "runtime-import", item.Credentials["agent_runtime_id"]) + require.Equal(t, privateKeyBase64, item.Credentials["agent_private_key"]) + require.Equal(t, "account-import", item.Credentials["chatgpt_account_id"]) + require.Equal(t, "user-import", item.Credentials["chatgpt_user_id"]) + require.NotContains(t, item.Credentials, "access_token") + require.NotContains(t, item.Credentials, "refresh_token") + require.NotEmpty(t, item.WarningTexts) +} diff --git a/backend/internal/handler/admin/account_codex_import.go b/backend/internal/handler/admin/account_codex_import.go index 271bd19470..57b97f8476 100644 --- a/backend/internal/handler/admin/account_codex_import.go +++ b/backend/internal/handler/admin/account_codex_import.go @@ -72,20 +72,25 @@ type codexImportEntry struct { } type codexImportAccount struct { - Name string - AccessToken string - RefreshToken string - IDToken string - Email string - AccountID string - UserID string - PlanType string - Organization string - Credentials map[string]any - Extra map[string]any - TokenExpiresAt *time.Time - IdentityKeys []string - WarningTexts []string + Name string + AccessToken string + RefreshToken string + IDToken string + Email string + AccountID string + UserID string + PlanType string + Organization string + AgentRuntimeID string + AgentPrivateKey string + AgentTaskID string + AgentFedRAMP bool + IsAgentIdentity bool + Credentials map[string]any + Extra map[string]any + TokenExpiresAt *time.Time + IdentityKeys []string + WarningTexts []string } type codexJWTClaims struct { @@ -496,6 +501,41 @@ func normalizeCodexImportEntry(entry codexImportEntry) (*codexImportAccount, err case string: item.AccessToken = strings.TrimSpace(raw) case map[string]any: + if agentIdentity, ok := firstCodexMap(raw, []string{"agent_identity"}, []string{"agentIdentity"}); ok || strings.EqualFold(firstCodexString(raw, []string{"auth_mode"}, []string{"authMode"}), service.OpenAIAuthModeAgentIdentity) { + if !ok { + agentIdentity = raw + } + item.IsAgentIdentity = true + item.AgentRuntimeID = firstCodexString(agentIdentity, []string{"agent_runtime_id"}, []string{"agentRuntimeId"}) + item.AgentPrivateKey = firstCodexString(agentIdentity, []string{"agent_private_key"}, []string{"agentPrivateKey"}) + item.AgentTaskID = firstCodexString(agentIdentity, []string{"task_id"}, []string{"taskId"}) + item.AccountID = firstCodexString(agentIdentity, []string{"account_id"}, []string{"accountId"}) + item.UserID = firstCodexString(agentIdentity, []string{"chatgpt_user_id"}, []string{"chatgptUserId"}) + item.Email = firstCodexString(agentIdentity, []string{"email"}) + item.PlanType = firstCodexString(agentIdentity, []string{"plan_type"}, []string{"planType"}) + item.AgentFedRAMP = firstCodexBool(agentIdentity, []string{"chatgpt_account_is_fedramp"}, []string{"chatgptAccountIsFedramp"}) + if item.AgentRuntimeID == "" || item.AgentPrivateKey == "" || item.AccountID == "" || item.UserID == "" { + return nil, errors.New("agent identity 缺少必要字段") + } + if err := service.ValidateOpenAIAgentIdentityPrivateKey(item.AgentPrivateKey); err != nil { + return nil, errors.New("agent identity private key 格式无效") + } + item.Credentials["auth_mode"] = service.OpenAIAuthModeAgentIdentity + item.Credentials["agent_runtime_id"] = item.AgentRuntimeID + item.Credentials["agent_private_key"] = item.AgentPrivateKey + item.Credentials["chatgpt_account_id"] = item.AccountID + item.Credentials["chatgpt_user_id"] = item.UserID + item.Credentials["chatgpt_account_is_fedramp"] = item.AgentFedRAMP + setCodexCredentialIfNotEmpty(item.Credentials, "task_id", item.AgentTaskID) + setCodexCredentialIfNotEmpty(item.Credentials, "email", item.Email) + setCodexCredentialIfNotEmpty(item.Credentials, "plan_type", item.PlanType) + if item.AgentTaskID == "" { + item.WarningTexts = append(item.WarningTexts, "未包含 task_id,首次请求会使用现有 runtime 注册新 task") + } + item.IdentityKeys = buildCodexAgentIdentityKeys(item.AccountID, item.UserID, item.Email, item.AgentRuntimeID) + item.Name = buildCodexImportAccountName(item, entry.Index) + return item, nil + } item.AccessToken = firstCodexString(raw, []string{"tokens", "access_token"}, []string{"tokens", "accessToken"}, @@ -577,6 +617,9 @@ func normalizeCodexImportEntry(entry codexImportEntry) (*codexImportAccount, err return nil, fmt.Errorf("第 %d 条格式不支持", entry.Index) } + if item.IsAgentIdentity { + return item, nil + } if item.AccessToken == "" { return nil, errors.New("缺少 accessToken/access_token") } @@ -812,6 +855,9 @@ func sanitizeCodexImportCredentialExtras(input map[string]any) map[string]any { "openai_auth_mode": {}, "token_type": {}, "chatgpt_account_is_fedramp": {}, + "agent_runtime_id": {}, + "agent_private_key": {}, + "task_id": {}, } out := make(map[string]any, len(input)) for key, value := range input { @@ -842,6 +888,14 @@ func buildCodexImportIdentityKeys(accountID, userID, email, accessToken, refresh return buildCodexStoredIdentityKeys(accountID, userID, email, accessToken) } +func buildCodexAgentIdentityKeys(accountID, userID, email, runtimeID string) []string { + keys := buildCodexStoredIdentityKeys(accountID, userID, email, "") + if runtimeID = strings.TrimSpace(runtimeID); runtimeID != "" { + keys = append([]string{"agent:" + runtimeID}, keys...) + } + return keys +} + // buildCodexStoredIdentityKeys 生成存量账号索引键,保留 user/account 维度, // 让 accessToken-only 账号后续升级为完整 OAuth 时仍能命中并更新原账号。 func buildCodexStoredIdentityKeys(accountID, userID, email, accessToken string) []string { @@ -891,6 +945,10 @@ func (i *codexAccountIndex) Add(account service.Account) { for _, key := range keys { i.accountsByKey[key] = upsertCodexAccount(i.accountsByKey[key], account) } + if runtimeID := codexCredentialString(account.Credentials, "agent_runtime_id"); runtimeID != "" { + key := "agent:" + runtimeID + i.accountsByKey[key] = upsertCodexAccount(i.accountsByKey[key], account) + } } func (i *codexAccountIndex) remove(accountID int64) { @@ -1043,6 +1101,38 @@ func firstCodexString(obj map[string]any, paths ...[]string) string { return "" } +func firstCodexMap(obj map[string]any, paths ...[]string) (map[string]any, bool) { + for _, path := range paths { + value, ok := codexPathValue(obj, path) + if !ok || value == nil { + continue + } + if mapped, ok := value.(map[string]any); ok { + return mapped, true + } + } + return nil, false +} + +func firstCodexBool(obj map[string]any, paths ...[]string) bool { + for _, path := range paths { + value, ok := codexPathValue(obj, path) + if !ok { + continue + } + switch value := value.(type) { + case bool: + return value + case string: + parsed, err := strconv.ParseBool(strings.TrimSpace(value)) + if err == nil { + return parsed + } + } + } + return false +} + func copyCodexExtraString(obj map[string]any, extra map[string]any, key string, path []string) { value := firstCodexString(obj, path) if value != "" { diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go index b451613c3e..661647f681 100644 --- a/backend/internal/handler/admin/account_handler.go +++ b/backend/internal/handler/admin/account_handler.go @@ -863,6 +863,53 @@ func (h *AccountHandler) Create(c *gin.Context) { response.Success(c, result.Data) } +// Duplicate handles creating an independent account from an existing account's configuration. +// POST /api/v1/admin/accounts/:id/duplicate +func (h *AccountHandler) Duplicate(c *gin.Context) { + accountID, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil { + response.BadRequest(c, "Invalid account ID") + return + } + actorScope := adminActorScope(c) + + result, err := executeAdminIdempotent( + c, + "admin.accounts.duplicate", + struct { + AccountID int64 `json:"account_id"` + }{AccountID: accountID}, + service.DefaultWriteIdempotencyTTL(), + func(ctx context.Context) (any, error) { + account, execErr := h.adminService.DuplicateAccount(ctx, accountID, actorScope, c.GetHeader("Idempotency-Key")) + if execErr != nil { + return nil, execErr + } + return h.buildAccountResponseWithRuntime(ctx, account), nil + }, + ) + if err != nil { + reason := infraerrors.Reason(err) + if reason == infraerrors.Reason(service.ErrIdempotencyInProgress) || reason == infraerrors.Reason(service.ErrIdempotencyStoreUnavail) { + recovered, recoverErr := h.adminService.RecoverDuplicateAccount(c.Request.Context(), accountID, actorScope, c.GetHeader("Idempotency-Key")) + if recoverErr != nil { + slog.Warn("account_duplicate_recovery_failed", "account_id", accountID, "actor_scope", actorScope, "reason", reason, "error", recoverErr) + } else if recovered != nil { + c.Header("X-Idempotency-Recovered", "true") + response.Success(c, h.buildAccountResponseWithRuntime(c.Request.Context(), recovered)) + return + } + } + response.ErrorFrom(c, err) + return + } + + if result != nil && result.Replayed { + c.Header("X-Idempotency-Replayed", "true") + } + response.Success(c, result.Data) +} + // Update handles updating an account // PUT /api/v1/admin/accounts/:id func (h *AccountHandler) Update(c *gin.Context) { diff --git a/backend/internal/handler/admin/account_handler_duplicate_test.go b/backend/internal/handler/admin/account_handler_duplicate_test.go new file mode 100644 index 0000000000..c99e882b1c --- /dev/null +++ b/backend/internal/handler/admin/account_handler_duplicate_test.go @@ -0,0 +1,295 @@ +//go:build unit + +package admin + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type duplicateAccountAdminServiceStub struct { + service.AdminService + account *service.Account + calls int + recoverCalls int + accountID int64 + actorScope string + operationKey string + recoverScope string + recoverKey string + recoverErr error + created bool +} + +type blockingDuplicateAdminServiceStub struct { + service.AdminService + account *service.Account + started chan struct{} + release chan struct{} + calls atomic.Int32 + recoverCalls atomic.Int32 + recoverErr error +} + +type failOnceMarkSucceededRepo struct { + *memoryIdempotencyRepoStub + failNext bool +} + +func (r *failOnceMarkSucceededRepo) MarkSucceeded(ctx context.Context, id int64, responseStatus int, responseBody string, expiresAt time.Time) error { + if r.failNext { + r.failNext = false + return errors.New("mark succeeded failed") + } + return r.memoryIdempotencyRepoStub.MarkSucceeded(ctx, id, responseStatus, responseBody, expiresAt) +} + +func (s *duplicateAccountAdminServiceStub) DuplicateAccount(_ context.Context, accountID int64, actorScope, operationKey string) (*service.Account, error) { + s.calls++ + s.accountID = accountID + s.actorScope = actorScope + s.operationKey = operationKey + s.created = true + return s.account, nil +} + +func (s *duplicateAccountAdminServiceStub) RecoverDuplicateAccount(_ context.Context, _ int64, actorScope, operationKey string) (*service.Account, error) { + s.recoverCalls++ + s.recoverScope = actorScope + s.recoverKey = operationKey + if s.recoverErr != nil { + return nil, s.recoverErr + } + if !s.created { + return nil, nil + } + return s.account, nil +} + +func (s *blockingDuplicateAdminServiceStub) DuplicateAccount(_ context.Context, _ int64, _, _ string) (*service.Account, error) { + s.calls.Add(1) + close(s.started) + <-s.release + return s.account, nil +} + +func (s *blockingDuplicateAdminServiceStub) RecoverDuplicateAccount(_ context.Context, _ int64, _, _ string) (*service.Account, error) { + s.recoverCalls.Add(1) + return nil, s.recoverErr +} + +func setupDuplicateAccountRouter(t *testing.T, svc service.AdminService) *gin.Engine { + t.Helper() + previousCoordinator := service.DefaultIdempotencyCoordinator() + service.SetDefaultIdempotencyCoordinator(nil) + t.Cleanup(func() { service.SetDefaultIdempotencyCoordinator(previousCoordinator) }) + + gin.SetMode(gin.TestMode) + router := gin.New() + router.Use(func(c *gin.Context) { + c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 77}) + c.Next() + }) + handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + router.POST("/api/v1/admin/accounts/:id/duplicate", handler.Duplicate) + return router +} + +func TestDuplicateAccountHandlerRedactsCredentials(t *testing.T) { + svc := &duplicateAccountAdminServiceStub{ + account: &service.Account{ + ID: 43, + Name: "primary (Copy)", + Platform: service.PlatformAnthropic, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + Schedulable: false, + Credentials: map[string]any{"api_key": "top-secret-key"}, + }, + } + router := setupDuplicateAccountRouter(t, svc) + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/42/duplicate", nil) + + router.ServeHTTP(recorder, request) + + require.Equal(t, http.StatusOK, recorder.Code) + require.Equal(t, 1, svc.calls) + require.Contains(t, recorder.Body.String(), `"name":"primary (Copy)"`) + require.NotContains(t, recorder.Body.String(), "top-secret-key") + var responseBody struct { + Data struct { + Credentials map[string]any `json:"credentials"` + Schedulable bool `json:"schedulable"` + } `json:"data"` + } + require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &responseBody)) + require.Empty(t, responseBody.Data.Credentials) + require.False(t, responseBody.Data.Schedulable) +} + +func TestDuplicateAccountHandlerRejectsInvalidID(t *testing.T) { + svc := &duplicateAccountAdminServiceStub{} + router := setupDuplicateAccountRouter(t, svc) + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/not-a-number/duplicate", nil) + + router.ServeHTTP(recorder, request) + + require.Equal(t, http.StatusBadRequest, recorder.Code) + require.Zero(t, svc.calls) +} + +func TestDuplicateAccountHandlerReplaysSameIdempotencyKey(t *testing.T) { + svc := &duplicateAccountAdminServiceStub{ + account: &service.Account{ + ID: 43, + Name: "primary (Copy)", + Platform: service.PlatformAnthropic, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + Schedulable: false, + }, + } + router := setupDuplicateAccountRouter(t, svc) + repo := newMemoryIdempotencyRepoStub() + service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(repo, service.DefaultIdempotencyConfig())) + + call := func() *httptest.ResponseRecorder { + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/42/duplicate", nil) + request.Header.Set("Idempotency-Key", "duplicate-account-42") + router.ServeHTTP(recorder, request) + return recorder + } + + first := call() + second := call() + + require.Equal(t, http.StatusOK, first.Code) + require.Equal(t, http.StatusOK, second.Code) + require.Equal(t, 1, svc.calls) + require.Equal(t, int64(42), svc.accountID) + require.Equal(t, "admin:77", svc.actorScope) + require.Equal(t, "duplicate-account-42", svc.operationKey) + require.Equal(t, "true", second.Header().Get("X-Idempotency-Replayed")) +} + +func TestDuplicateAccountHandlerRecoversAfterMarkSucceededFailure(t *testing.T) { + svc := &duplicateAccountAdminServiceStub{ + account: &service.Account{ + ID: 43, + Name: "primary (Copy)", + Platform: service.PlatformAnthropic, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + Schedulable: false, + }, + } + router := setupDuplicateAccountRouter(t, svc) + repo := &failOnceMarkSucceededRepo{memoryIdempotencyRepoStub: newMemoryIdempotencyRepoStub(), failNext: true} + service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(repo, service.DefaultIdempotencyConfig())) + + call := func() *httptest.ResponseRecorder { + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/42/duplicate", nil) + request.Header.Set("Idempotency-Key", "duplicate-account-42-recovery") + router.ServeHTTP(recorder, request) + return recorder + } + + first := call() + second := call() + + require.Equal(t, http.StatusOK, first.Code) + require.Equal(t, http.StatusOK, second.Code) + require.Equal(t, "true", first.Header().Get("X-Idempotency-Recovered")) + require.Equal(t, "true", second.Header().Get("X-Idempotency-Recovered")) + require.Equal(t, 1, svc.calls, "ambiguous retries must not repeat the create side effect") + require.Equal(t, 2, svc.recoverCalls) + require.Equal(t, "admin:77", svc.recoverScope) + require.Equal(t, "duplicate-account-42-recovery", svc.recoverKey) + require.Contains(t, second.Body.String(), `"id":43`) +} + +func TestDuplicateAccountHandlerPreservesIdempotencyErrorWhenRecoveryLookupFails(t *testing.T) { + svc := &duplicateAccountAdminServiceStub{ + account: &service.Account{ + ID: 43, + Name: "primary (Copy)", + Platform: service.PlatformAnthropic, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + Schedulable: false, + }, + recoverErr: errors.New("recovery database unavailable"), + } + router := setupDuplicateAccountRouter(t, svc) + repo := &failOnceMarkSucceededRepo{memoryIdempotencyRepoStub: newMemoryIdempotencyRepoStub(), failNext: true} + service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(repo, service.DefaultIdempotencyConfig())) + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/42/duplicate", nil) + request.Header.Set("Idempotency-Key", "duplicate-account-42-recovery-error") + + router.ServeHTTP(recorder, request) + + require.Equal(t, http.StatusServiceUnavailable, recorder.Code) + require.Contains(t, recorder.Body.String(), "IDEMPOTENCY_STORE_UNAVAILABLE") + require.Equal(t, 1, svc.calls) + require.Equal(t, 1, svc.recoverCalls) + require.Equal(t, "admin:77", svc.recoverScope) +} + +func TestDuplicateAccountHandlerDoesNotReexecuteWhileOriginalIsProcessing(t *testing.T) { + svc := &blockingDuplicateAdminServiceStub{ + account: &service.Account{ + ID: 43, + Name: "primary (Copy)", + Platform: service.PlatformAnthropic, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + Schedulable: false, + }, + started: make(chan struct{}), + release: make(chan struct{}), + recoverErr: errors.New("recovery database unavailable"), + } + router := setupDuplicateAccountRouter(t, svc) + service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(newMemoryIdempotencyRepoStub(), service.DefaultIdempotencyConfig())) + + call := func() *httptest.ResponseRecorder { + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/42/duplicate", nil) + request.Header.Set("Idempotency-Key", "duplicate-account-42-active") + router.ServeHTTP(recorder, request) + return recorder + } + firstDone := make(chan *httptest.ResponseRecorder, 1) + go func() { firstDone <- call() }() + <-svc.started + + second := call() + require.Equal(t, http.StatusConflict, second.Code) + require.Contains(t, second.Body.String(), "IDEMPOTENCY_IN_PROGRESS") + require.Equal(t, int32(1), svc.calls.Load()) + require.Equal(t, int32(1), svc.recoverCalls.Load()) + + close(svc.release) + select { + case first := <-firstDone: + require.Equal(t, http.StatusOK, first.Code) + case <-time.After(time.Second): + t.Fatal("original duplicate request did not finish") + } +} diff --git a/backend/internal/handler/admin/admin_service_stub_test.go b/backend/internal/handler/admin/admin_service_stub_test.go index 5e9c4d517e..d93ee7111c 100644 --- a/backend/internal/handler/admin/admin_service_stub_test.go +++ b/backend/internal/handler/admin/admin_service_stub_test.go @@ -418,6 +418,15 @@ func (s *stubAdminService) CreateAccount(ctx context.Context, input *service.Cre return &account, nil } +func (s *stubAdminService) DuplicateAccount(ctx context.Context, id int64, actorScope, operationKey string) (*service.Account, error) { + account := service.Account{ID: 301, Name: "account (Copy)", Status: service.StatusActive, Schedulable: false} + return &account, nil +} + +func (s *stubAdminService) RecoverDuplicateAccount(ctx context.Context, id int64, actorScope, operationKey string) (*service.Account, error) { + return nil, nil +} + func (s *stubAdminService) UpdateAccount(ctx context.Context, id int64, input *service.UpdateAccountInput) (*service.Account, error) { s.updateAccountCalls++ if s.updateAccountErr != nil { diff --git a/backend/internal/handler/admin/grok_import_probe_handler_test.go b/backend/internal/handler/admin/grok_import_probe_handler_test.go index 8eeebb23a8..c671d2ff1c 100644 --- a/backend/internal/handler/admin/grok_import_probe_handler_test.go +++ b/backend/internal/handler/admin/grok_import_probe_handler_test.go @@ -73,7 +73,7 @@ func TestGrokSSOBatchImportKeepsCreatedAccountsWhenOneAutomaticProbeFails(t *tes defer oauthService.Stop() prober := newGrokImportProbeStub(3) prober.failures[502] = infraerrors.New(502, "GROK_TEST_PROBE_FAILED", "sensitive-upstream-body") - handler := NewGrokOAuthHandler(oauthService, adminService, nil) + handler := NewGrokOAuthHandler(oauthService, adminService, nil, nil) handler.importProber = prober router := gin.New() diff --git a/backend/internal/handler/admin/grok_oauth_handler.go b/backend/internal/handler/admin/grok_oauth_handler.go index 1a309b7c9a..258c68853d 100644 --- a/backend/internal/handler/admin/grok_oauth_handler.go +++ b/backend/internal/handler/admin/grok_oauth_handler.go @@ -7,6 +7,7 @@ import ( "strconv" "strings" "sync" + "time" "github.com/Wei-Shaw/sub2api/internal/handler/dto" infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" @@ -23,18 +24,21 @@ type GrokOAuthHandler struct { adminService service.AdminService quotaService *service.GrokQuotaService importProber grokUsageProber + reconciler service.GrokOAuthReconciler } func NewGrokOAuthHandler( grokOAuthService *service.GrokOAuthService, adminService service.AdminService, quotaService *service.GrokQuotaService, + reconciler service.GrokOAuthReconciler, ) *GrokOAuthHandler { return &GrokOAuthHandler{ grokOAuthService: grokOAuthService, adminService: adminService, quotaService: quotaService, importProber: quotaService, + reconciler: reconciler, } } @@ -160,6 +164,50 @@ func (h *GrokOAuthHandler) RefreshAccountToken(c *gin.Context) { response.Success(c, dto.AccountFromService(updatedAccount)) } +type GrokOAuthReconcileRequest struct { + DryRun *bool `json:"dry_run"` + Apply bool `json:"apply"` + AfterID int64 `json:"after_id"` + Limit int `json:"limit"` + RefreshWindowSeconds int64 `json:"refresh_window_seconds"` +} + +func (h *GrokOAuthHandler) ReconcileOAuthAccounts(c *gin.Context) { + var req GrokOAuthReconcileRequest + if err := c.ShouldBindJSON(&req); err != nil { + response.BadRequest(c, "Invalid request") + return + } + dryRun := true + if req.DryRun != nil { + dryRun = *req.DryRun + } + if req.Apply == dryRun { + response.ErrorFrom(c, service.ErrGrokOAuthReconcileMode) + return + } + if req.RefreshWindowSeconds < 0 || req.RefreshWindowSeconds > int64((24*time.Hour)/time.Second) { + response.ErrorFrom(c, service.ErrGrokOAuthReconcileWindow) + return + } + if h.reconciler == nil { + response.InternalError(c, "Grok OAuth reconciliation service is unavailable") + return + } + result, err := h.reconciler.ReconcileGrokOAuth(c.Request.Context(), service.GrokOAuthReconcileInput{ + DryRun: dryRun, + Apply: req.Apply, + AfterID: req.AfterID, + Limit: req.Limit, + RefreshWindow: time.Duration(req.RefreshWindowSeconds) * time.Second, + }) + if err != nil { + response.ErrorFrom(c, err) + return + } + response.Success(c, result) +} + func (h *GrokOAuthHandler) CreateAccountFromOAuth(c *gin.Context) { var req struct { SessionID string `json:"session_id" binding:"required"` diff --git a/backend/internal/handler/admin/grok_oauth_handler_test.go b/backend/internal/handler/admin/grok_oauth_handler_test.go index 64ea044aa3..ee7e8e5e3e 100644 --- a/backend/internal/handler/admin/grok_oauth_handler_test.go +++ b/backend/internal/handler/admin/grok_oauth_handler_test.go @@ -47,6 +47,19 @@ type grokQuotaHandlerUpstream struct { bodies [][]byte } +type grokOAuthReconcilerStub struct { + input service.GrokOAuthReconcileInput + calls int + result *service.GrokOAuthReconcileResult + err error +} + +func (s *grokOAuthReconcilerStub) ReconcileGrokOAuth(_ context.Context, input service.GrokOAuthReconcileInput) (*service.GrokOAuthReconcileResult, error) { + s.calls++ + s.input = input + return s.result, s.err +} + func (u *grokQuotaHandlerUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) { var body []byte if req.Body != nil { @@ -90,15 +103,18 @@ func TestGrokOAuthHandlerQueryQuotaProbesUpstream(t *testing.T) { ID: 42, Platform: service.PlatformGrok, Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Schedulable: true, Concurrency: 1, Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), + "access_token": "access-token", + "refresh_token": "refresh-token", + "expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339), }, }} upstream := &grokQuotaHandlerUpstream{} quotaService := service.NewGrokQuotaService(repo, nil, service.NewGrokTokenProvider(repo, nil), upstream) - handler := NewGrokOAuthHandler(nil, nil, quotaService) + handler := NewGrokOAuthHandler(nil, nil, quotaService, nil) router := gin.New() router.GET("/api/v1/admin/grok/accounts/:id/quota", handler.QueryQuota) @@ -136,7 +152,7 @@ func TestGrokOAuthHandlerResetQuotaReturnsUnsupported(t *testing.T) { Type: service.AccountTypeOAuth, }} quotaService := service.NewGrokQuotaService(repo, nil, nil, nil) - handler := NewGrokOAuthHandler(nil, nil, quotaService) + handler := NewGrokOAuthHandler(nil, nil, quotaService, nil) router := gin.New() router.POST("/api/v1/admin/grok/accounts/:id/reset-quota", handler.ResetQuota) @@ -154,7 +170,7 @@ func TestGrokOAuthHandlerRuntimeSanityDoesNotExposeSecrets(t *testing.T) { t.Setenv(xai.EnvBaseURL, "http://127.0.0.1:8080/v1?access_token=secret") t.Setenv(xai.EnvClientID, "client-secret-like-value") - handler := NewGrokOAuthHandler(nil, nil, nil) + handler := NewGrokOAuthHandler(nil, nil, nil, nil) router := gin.New() router.GET("/api/v1/admin/grok/runtime-sanity", handler.RuntimeSanity) rec := httptest.NewRecorder() @@ -216,3 +232,69 @@ func TestGrokSSOImportWorkerRecoversPanic(t *testing.T) { require.Equal(t, 2, result.item.Index) require.Contains(t, result.item.Error, "internal worker panic") } + +func TestGrokOAuthHandlerReconcileDefaultsToDryRun(t *testing.T) { + gin.SetMode(gin.TestMode) + reconciler := &grokOAuthReconcilerStub{result: &service.GrokOAuthReconcileResult{ + DryRun: true, + Scanned: 2, + Actionable: 1, + WouldBlock: 1, + Items: []service.GrokOAuthReconcileItem{{AccountID: 42, Reason: service.GrokOAuthReconcileReasonMissingRefreshToken, Action: service.GrokOAuthReconcileActionBlock, Outcome: service.GrokOAuthReconcileOutcomePlanned}}, + NextAfterID: 0, + }} + handler := NewGrokOAuthHandler(nil, nil, nil, reconciler) + router := gin.New() + router.POST("/api/v1/admin/grok/oauth/reconcile", handler.ReconcileOAuthAccounts) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/grok/oauth/reconcile", strings.NewReader(`{}`)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(rec, req) + + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, 1, reconciler.calls) + require.True(t, reconciler.input.DryRun) + require.False(t, reconciler.input.Apply) + require.Contains(t, rec.Body.String(), `"reason":"missing_refresh_token"`) + require.NotContains(t, rec.Body.String(), `"refresh_token":`) + require.NotContains(t, rec.Body.String(), `"access_token":`) +} + +func TestGrokOAuthHandlerReconcileRequiresExplicitApply(t *testing.T) { + gin.SetMode(gin.TestMode) + reconciler := &grokOAuthReconcilerStub{} + handler := NewGrokOAuthHandler(nil, nil, nil, reconciler) + router := gin.New() + router.POST("/api/v1/admin/grok/oauth/reconcile", handler.ReconcileOAuthAccounts) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/grok/oauth/reconcile", strings.NewReader(`{"dry_run":false}`)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(rec, req) + + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Zero(t, reconciler.calls) + require.NotContains(t, rec.Body.String(), "credentials") +} + +func TestGrokOAuthHandlerReconcileExplicitApply(t *testing.T) { + gin.SetMode(gin.TestMode) + reconciler := &grokOAuthReconcilerStub{result: &service.GrokOAuthReconcileResult{DryRun: false, Refreshed: 1}} + handler := NewGrokOAuthHandler(nil, nil, nil, reconciler) + router := gin.New() + router.POST("/api/v1/admin/grok/oauth/reconcile", handler.ReconcileOAuthAccounts) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/grok/oauth/reconcile", strings.NewReader(`{"apply":true,"dry_run":false,"after_id":10,"limit":25,"refresh_window_seconds":3600}`)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(rec, req) + + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, 1, reconciler.calls) + require.True(t, reconciler.input.Apply) + require.False(t, reconciler.input.DryRun) + require.Equal(t, int64(10), reconciler.input.AfterID) + require.Equal(t, 25, reconciler.input.Limit) + require.Equal(t, time.Hour, reconciler.input.RefreshWindow) +} diff --git a/backend/internal/handler/admin/idempotency_helper.go b/backend/internal/handler/admin/idempotency_helper.go index aa8eeaaf79..1894faeaae 100644 --- a/backend/internal/handler/admin/idempotency_helper.go +++ b/backend/internal/handler/admin/idempotency_helper.go @@ -37,14 +37,9 @@ func executeAdminIdempotent( return &service.IdempotencyExecuteResult{Data: data}, nil } - actorScope := "admin:0" - if subject, ok := middleware2.GetAuthSubjectFromContext(c); ok { - actorScope = "admin:" + strconv.FormatInt(subject.UserID, 10) - } - return coordinator.Execute(c.Request.Context(), service.IdempotencyExecuteOptions{ Scope: scope, - ActorScope: actorScope, + ActorScope: adminActorScope(c), Method: c.Request.Method, Route: c.FullPath(), IdempotencyKey: c.GetHeader("Idempotency-Key"), @@ -54,6 +49,14 @@ func executeAdminIdempotent( }, execute) } +func adminActorScope(c *gin.Context) string { + actorScope := "admin:0" + if subject, ok := middleware2.GetAuthSubjectFromContext(c); ok { + actorScope = "admin:" + strconv.FormatInt(subject.UserID, 10) + } + return actorScope +} + func executeAdminIdempotentJSON( c *gin.Context, scope string, diff --git a/backend/internal/handler/admin/ops_handler.go b/backend/internal/handler/admin/ops_handler.go index e820aef0c6..0284dbfd0b 100644 --- a/backend/internal/handler/admin/ops_handler.go +++ b/backend/internal/handler/admin/ops_handler.go @@ -386,8 +386,8 @@ func (h *OpsHandler) ListRequestErrorUpstreamErrors(c *gin.Context) { filter.EndTime = &endTime } filter.View = "all" - filter.Phase = "upstream" - // 上游错误列表需含 status<400 的 recovered 行,显式豁免客户端可见守卫。 + filter.ErrorPhasesAny = []string{"upstream", "account_auth"} + // Provider-health list includes recovered inference and credential rows. filter.IncludeRecoveredUpstream = true filter.Owner = "provider" filter.Source = strings.TrimSpace(c.Query("error_source")) @@ -470,8 +470,8 @@ func (h *OpsHandler) ListUpstreamErrors(c *gin.Context) { } filter.View = parseOpsViewParam(c) - filter.Phase = "upstream" - // 上游错误列表需含 status<400 的 recovered 行,显式豁免客户端可见守卫。 + filter.ErrorPhasesAny = []string{"upstream", "account_auth"} + // Provider-health list includes recovered inference and credential rows. filter.IncludeRecoveredUpstream = true filter.Owner = "provider" filter.Source = strings.TrimSpace(c.Query("error_source")) diff --git a/backend/internal/handler/dto/credentials_redact_test.go b/backend/internal/handler/dto/credentials_redact_test.go index 431078fafd..9bf4f78039 100644 --- a/backend/internal/handler/dto/credentials_redact_test.go +++ b/backend/internal/handler/dto/credentials_redact_test.go @@ -20,6 +20,7 @@ func TestRedactCredentials_StripsSensitiveKeysAndReportsStatus(t *testing.T) { "aws_secret_access_key": "aws-secret", "service_account_json": map[string]any{"private_key": "..."}, "private_key": "raw-key", + "agent_private_key": "agent-key-secret", // 非敏感 "base_url": "https://api.example.com", "model_mapping": map[string]any{"foo": "bar"}, @@ -35,6 +36,7 @@ func TestRedactCredentials_StripsSensitiveKeysAndReportsStatus(t *testing.T) { require.NotContains(t, out, "aws_secret_access_key") require.NotContains(t, out, "service_account_json") require.NotContains(t, out, "private_key") + require.NotContains(t, out, "agent_private_key") require.Equal(t, "https://api.example.com", out["base_url"]) require.Equal(t, map[string]any{"foo": "bar"}, out["model_mapping"]) @@ -47,6 +49,7 @@ func TestRedactCredentials_StripsSensitiveKeysAndReportsStatus(t *testing.T) { require.True(t, status["has_aws_secret_access_key"]) require.True(t, status["has_service_account_json"]) require.True(t, status["has_private_key"]) + require.True(t, status["has_agent_private_key"]) // 状态 map 不应携带非敏感键的 has_* require.NotContains(t, status, "has_base_url") @@ -84,6 +87,7 @@ func TestRedactCredentials_AllKnownSensitiveKeys(t *testing.T) { "api_key", "session_key", "cookie", "aws_secret_access_key", "aws_session_token", "service_account_json", "service_account", "private_key", + "agent_private_key", } in := make(map[string]any, len(keys)) for _, k := range keys { diff --git a/backend/internal/handler/failover_loop.go b/backend/internal/handler/failover_loop.go index 5838e58f48..7ce1d03a8c 100644 --- a/backend/internal/handler/failover_loop.go +++ b/backend/internal/handler/failover_loop.go @@ -5,6 +5,8 @@ import ( "net/http" "time" + "github.com/gin-gonic/gin" + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/Wei-Shaw/sub2api/internal/service" "go.uber.org/zap" @@ -71,7 +73,15 @@ func (s *FailoverState) HandleFailoverError( retryLimit int, failoverErr *service.UpstreamFailoverError, ) FailoverAction { + // 客户端已断开:failover 只会用已取消的 context 重新选号并必然失败, + // 不应再被当成账号耗尽处理(误报 502)。 + if ctx != nil && ctx.Err() != nil { + return FailoverCanceled + } s.LastFailoverErr = failoverErr + if failoverErr == nil || !failoverErr.ShouldRetryNextAccount() { + return FailoverExhausted + } // 缓存计费判断 if needForceCacheBilling(s.hasBoundSession, failoverErr) { @@ -135,6 +145,12 @@ func (s *FailoverState) HandleFailoverError( // 返回 FailoverExhausted 时,调用方应返回错误响应。 // 返回 FailoverCanceled 时,调用方应直接 return。 func (s *FailoverState) HandleSelectionExhausted(ctx context.Context) FailoverAction { + // 客户端已断开时选号失败是 context canceled 的必然结果, + // 不代表账号耗尽,直接按取消终止。 + if ctx.Err() != nil { + return FailoverCanceled + } + if s.LastFailoverErr != nil && s.LastFailoverErr.StatusCode == http.StatusServiceUnavailable && s.SwitchCount <= s.MaxSwitches { @@ -163,6 +179,28 @@ func needForceCacheBilling(hasBoundSession bool, failoverErr *service.UpstreamFa return hasBoundSession || (failoverErr != nil && failoverErr.ForceCacheBilling) } +// failoverClientGone 判断下游客户端是否已断开(请求 context 已取消)。 +// 客户端断开后 failover 必须静默终止:用已取消的 context 重新选号只会得到 +// context.Canceled,并被误报成账号耗尽(通用 502);上游 detach 的在途请求 +// 照常完成计费,但不再为无人接收的响应启动新的上游尝试。 +// 响应尚未提交时把状态码标记为 499(client closed request),供访问日志归类。 +func failoverClientGone(c *gin.Context) bool { + if c == nil || c.Request == nil || c.Request.Context().Err() == nil { + return false + } + // 先停 compact 心跳(接管 ResponseWriter,建立 happens-before),与 + // handleStreamingAwareError/errorResponse 等终结路径对齐,避免心跳 + // goroutine 与下面的状态标记并发触碰同一 writer。心跳已提交 200 时 + // 状态码已固化,不再标 499。 + if service.StopOpenAICompactSSEKeepaliveCommitted(c) { + return true + } + if !c.Writer.Written() { + c.Status(statusClientClosedRequest) + } + return true +} + // sleepWithContext 等待指定时长,返回 false 表示 context 已取消。 func sleepWithContext(ctx context.Context, d time.Duration) bool { if d <= 0 { diff --git a/backend/internal/handler/failover_loop_test.go b/backend/internal/handler/failover_loop_test.go index 9fabe75f25..8946eb5236 100644 --- a/backend/internal/handler/failover_loop_test.go +++ b/backend/internal/handler/failover_loop_test.go @@ -2,11 +2,14 @@ package handler import ( "context" + "net/http" + "net/http/httptest" "testing" "time" "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" ) @@ -128,6 +131,50 @@ func TestSleepWithContext(t *testing.T) { // --------------------------------------------------------------------------- func TestHandleFailoverError_BasicSwitch(t *testing.T) { + t.Run("显式停止不切换账号且旧错误默认仍切换", func(t *testing.T) { + mock := &mockTempUnscheduler{} + fs := NewFailoverState(3, false) + stopErr := &service.UpstreamFailoverError{ + Stage: service.GatewayFailureStageAccountAuth, + Scope: service.GatewayFailureScopeProvider, + NextAccountAction: service.NextAccountStop, + } + + action := fs.HandleFailoverError(context.Background(), mock, 100, service.PlatformGrok, maxSameAccountRetries, stopErr) + + require.Equal(t, FailoverExhausted, action) + require.Zero(t, fs.SwitchCount) + require.Empty(t, fs.FailedAccountIDs) + require.Equal(t, stopErr, fs.LastFailoverErr) + + legacyErr := newTestFailoverErr(http.StatusTooManyRequests, false, false) + action = fs.HandleFailoverError(context.Background(), mock, 100, service.PlatformGrok, maxSameAccountRetries, legacyErr) + + require.Equal(t, FailoverContinue, action) + require.Equal(t, 1, fs.SwitchCount) + require.Contains(t, fs.FailedAccountIDs, int64(100)) + }) + + t.Run("已取消的认证失败不改变切换状态", func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + mock := &mockTempUnscheduler{} + fs := NewFailoverState(3, false) + err := &service.UpstreamFailoverError{ + Stage: service.GatewayFailureStageAccountAuth, + Scope: service.GatewayFailureScopeAccount, + NextAccountAction: service.NextAccountRetry, + } + + action := fs.HandleFailoverError(ctx, mock, 101, service.PlatformGrok, maxSameAccountRetries, err) + + require.Equal(t, FailoverCanceled, action) + require.Zero(t, fs.SwitchCount) + require.Empty(t, fs.FailedAccountIDs) + require.Nil(t, fs.LastFailoverErr) + require.Empty(t, mock.calls) + }) + t.Run("非重试错误_非Antigravity_直接切换", func(t *testing.T) { mock := &mockTempUnscheduler{} fs := NewFailoverState(3, false) @@ -444,7 +491,28 @@ func TestHandleFailoverError_ContextCanceled(t *testing.T) { err := newTestFailoverErr(400, true, false) ctx, cancel := context.WithCancel(context.Background()) - cancel() // 立即取消 + go func() { + time.Sleep(30 * time.Millisecond) + cancel() // 通过入口检查后、sleep 期间取消 + }() + + start := time.Now() + action := fs.HandleFailoverError(ctx, mock, 100, "openai", maxSameAccountRetries, err) + elapsed := time.Since(start) + + require.Equal(t, FailoverCanceled, action) + require.Less(t, elapsed, 400*time.Millisecond, "sleep 应被取消打断") + // 进入重试分支后才取消:重试计数已递增 + require.Equal(t, 1, fs.SameAccountRetryCount[100]) + }) + + t.Run("入口即已取消_不改动任何failover状态", func(t *testing.T) { + mock := &mockTempUnscheduler{} + fs := NewFailoverState(3, false) + err := newTestFailoverErr(520, false, false) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() // 调用前客户端已断开 start := time.Now() action := fs.HandleFailoverError(ctx, mock, 100, "openai", maxSameAccountRetries, err) @@ -452,8 +520,12 @@ func TestHandleFailoverError_ContextCanceled(t *testing.T) { require.Equal(t, FailoverCanceled, action) require.Less(t, elapsed, 100*time.Millisecond, "应立即返回") - // 重试计数仍应递增 - require.Equal(t, 1, fs.SameAccountRetryCount[100]) + // 入口已取消时不得改变任何 failover 状态。 + require.Equal(t, 0, fs.SwitchCount, "取消的请求不应计入切换") + require.Equal(t, 0, fs.SameAccountRetryCount[100], "取消的请求不应改动重试计数") + require.NotContains(t, fs.FailedAccountIDs, int64(100)) + require.Nil(t, fs.LastFailoverErr) + require.Empty(t, mock.calls, "不应触发 TempUnschedule") }) t.Run("Antigravity延迟期间context取消", func(t *testing.T) { @@ -755,6 +827,29 @@ func TestHandleSelectionExhausted(t *testing.T) { require.Less(t, elapsed, 100*time.Millisecond, "应立即返回") }) + t.Run("context已取消_非503也返回Canceled而非Exhausted", func(t *testing.T) { + // #4257 核心场景:客户端断开后选号失败源于 context canceled, + // 不应被当成账号耗尽转成 502。 + fs := NewFailoverState(3, false) + fs.LastFailoverErr = newTestFailoverErr(520, false, false) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + action := fs.HandleSelectionExhausted(ctx) + require.Equal(t, FailoverCanceled, action) + }) + + t.Run("context已取消_无LastFailoverErr也返回Canceled", func(t *testing.T) { + fs := NewFailoverState(3, false) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + action := fs.HandleSelectionExhausted(ctx) + require.Equal(t, FailoverCanceled, action) + }) + t.Run("503且SwitchCount等于MaxSwitches_仍可重试", func(t *testing.T) { fs := NewFailoverState(2, false) fs.LastFailoverErr = newTestFailoverErr(503, false, false) @@ -764,3 +859,47 @@ func TestHandleSelectionExhausted(t *testing.T) { require.Equal(t, FailoverContinue, action) }) } + +// --------------------------------------------------------------------------- +// failoverClientGone 测试 +// --------------------------------------------------------------------------- + +func TestFailoverClientGone(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("活跃请求返回false", func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + + require.False(t, failoverClientGone(c)) + require.Equal(t, http.StatusOK, c.Writer.Status(), "不应改动状态码") + }) + + t.Run("客户端已断开_返回true并标记499", func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil).WithContext(ctx) + + require.True(t, failoverClientGone(c)) + require.Equal(t, statusClientClosedRequest, c.Writer.Status()) + }) + + t.Run("响应已提交_不改状态码", func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil).WithContext(ctx) + c.String(http.StatusOK, "partial") + + require.True(t, failoverClientGone(c)) + require.Equal(t, http.StatusOK, c.Writer.Status(), "已提交的状态码不应被覆盖") + }) + + t.Run("nil安全", func(t *testing.T) { + require.False(t, failoverClientGone(nil)) + }) +} diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index fb07b098d1..1c51713656 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -327,6 +327,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { c.Request = c.Request.WithContext(ctx) continue case FailoverCanceled: + failoverClientGone(c) return default: // FailoverExhausted if fs.LastFailoverErr != nil { @@ -456,6 +457,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { h.handleFailoverExhausted(c, fs.LastFailoverErr, service.PlatformGemini, streamStarted) return case FailoverCanceled: + failoverClientGone(c) return } } @@ -613,6 +615,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { c.Request = c.Request.WithContext(ctx) continue case FailoverCanceled: + failoverClientGone(c) return default: // FailoverExhausted if fs.LastFailoverErr != nil { @@ -876,6 +879,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { h.handleFailoverExhausted(c, fs.LastFailoverErr, account.Platform, streamStarted) return case FailoverCanceled: + failoverClientGone(c) return } } diff --git a/backend/internal/handler/gateway_handler_cancellation_test.go b/backend/internal/handler/gateway_handler_cancellation_test.go new file mode 100644 index 0000000000..d53961174a --- /dev/null +++ b/backend/internal/handler/gateway_handler_cancellation_test.go @@ -0,0 +1,98 @@ +//go:build unit + +package handler + +import ( + "bytes" + "context" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type countingGatewaySchedulerCache struct { + *fakeSchedulerCache + snapshotCalls atomic.Int64 +} + +func (c *countingGatewaySchedulerCache) GetSnapshot(ctx context.Context, bucket service.SchedulerBucket) ([]*service.Account, bool, error) { + c.snapshotCalls.Add(1) + return c.fakeSchedulerCache.GetSnapshot(ctx, bucket) +} + +func TestGatewayHandlerPreCancelledCompatibleRequestsDoNotSelectAccount(t *testing.T) { + gin.SetMode(gin.TestMode) + groupID := int64(9100) + group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive} + account := &service.Account{ + ID: 9101, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, + AccountGroups: []service.AccountGroup{{AccountID: 9101, GroupID: groupID}}, + } + schedulerCache := &countingGatewaySchedulerCache{fakeSchedulerCache: &fakeSchedulerCache{accounts: []*service.Account{account}}} + schedulerSnapshot := service.NewSchedulerSnapshotService(schedulerCache, nil, nil, nil, nil) + gatewayService := service.NewGatewayService( + nil, &fakeGroupRepo{group: group}, nil, nil, nil, nil, nil, nil, nil, + schedulerSnapshot, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + cfg := &config.Config{RunMode: config.RunModeSimple} + billingCacheService := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCacheService.Stop) + h := &GatewayHandler{ + gatewayService: gatewayService, + billingCacheService: billingCacheService, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), + maxAccountSwitches: 1, + cfg: cfg, + } + apiKey := &service.APIKey{ + ID: 9102, UserID: 9103, GroupID: &groupID, Group: group, Status: service.StatusActive, + User: &service.User{ID: 9103, Concurrency: 10, Balance: 100}, + } + + tests := []struct { + name string + path string + body string + call func(*gin.Context) + }{ + { + name: "responses", path: "/v1/responses", body: `{"model":"claude-test","input":"hello","stream":false}`, + call: h.Responses, + }, + { + name: "chat completions", path: "/v1/chat/completions", body: `{"model":"claude-test","messages":[{"role":"user","content":"hello"}],"stream":false}`, + call: h.ChatCompletions, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + schedulerCache.snapshotCalls.Store(0) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + ctx = context.WithValue(ctx, ctxkey.Group, group) + req := httptest.NewRequest(http.MethodPost, tt.path, bytes.NewBufferString(tt.body)).WithContext(ctx) + req.Header.Set("Content-Type", "application/json") + c.Request = req + c.Set(string(middleware.ContextKeyAPIKey), apiKey) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.UserID, Concurrency: 10}) + + tt.call(c) + + require.Zero(t, schedulerCache.snapshotCalls.Load(), "a cancelled request must stop before the account selector") + _, selected := c.Get(opsAccountIDKey) + require.False(t, selected) + }) + } +} diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index af9bcdb344..cc9ff14282 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -159,6 +159,9 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { } for { + if c.Request.Context().Err() != nil { + return + } selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), apiKey.GroupID, selectionSessionHash, reqModel, fs.FailedAccountIDs, "", int64(0)) if err != nil { if len(fs.FailedAccountIDs) == 0 { @@ -178,6 +181,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { case FailoverContinue: continue case FailoverCanceled: + failoverClientGone(c) return default: if fs.LastFailoverErr != nil { @@ -262,6 +266,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { h.handleCCFailoverExhausted(c, fs.LastFailoverErr, streamStarted) return case FailoverCanceled: + failoverClientGone(c) return } } @@ -328,6 +333,14 @@ func (h *GatewayHandler) handleCCFailoverExhausted(c *gin.Context, lastErr *serv if streamStarted { return } + if lastErr != nil { + copyFailoverRetryAfter(c, lastErr.ResponseHeaders) + } + if lastErr != nil && lastErr.IsCredentialFailure() { + status, message := credentialFailoverClientResponse(lastErr) + h.chatCompletionsErrorResponse(c, status, "server_error", message) + return + } statusCode := http.StatusBadGateway if lastErr != nil && lastErr.StatusCode > 0 { statusCode = lastErr.StatusCode diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 8a88d5fa57..a5060b7263 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -157,6 +157,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) { fs := NewFailoverState(h.maxAccountSwitches, false) for { + if requestCtx.Err() != nil { + return + } selection, err := h.gatewayService.SelectAccountWithLoadAwareness(requestCtx, apiKey.GroupID, sessionHash, reqModel, fs.FailedAccountIDs, "", int64(0)) if err != nil { if len(fs.FailedAccountIDs) == 0 { @@ -176,6 +179,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { case FailoverContinue: continue case FailoverCanceled: + failoverClientGone(c) return default: if fs.LastFailoverErr != nil { @@ -241,6 +245,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { h.handleResponsesFailoverExhausted(c, fs.LastFailoverErr, streamStarted) return case FailoverCanceled: + failoverClientGone(c) return } } @@ -307,6 +312,14 @@ func (h *GatewayHandler) handleResponsesFailoverExhausted(c *gin.Context, lastEr if streamStarted { return // Can't write error after stream started } + if lastErr != nil { + copyFailoverRetryAfter(c, lastErr.ResponseHeaders) + } + if lastErr != nil && lastErr.IsCredentialFailure() { + status, message := credentialFailoverClientResponse(lastErr) + h.responsesErrorResponse(c, status, "server_error", message) + return + } statusCode := http.StatusBadGateway if lastErr != nil && lastErr.StatusCode > 0 { statusCode = lastErr.StatusCode diff --git a/backend/internal/handler/gateway_handler_warmup_intercept_unit_test.go b/backend/internal/handler/gateway_handler_warmup_intercept_unit_test.go index 75e3c1aa8c..8f3362f919 100644 --- a/backend/internal/handler/gateway_handler_warmup_intercept_unit_test.go +++ b/backend/internal/handler/gateway_handler_warmup_intercept_unit_test.go @@ -31,7 +31,22 @@ type fakeSchedulerCache struct { func (f *fakeSchedulerCache) GetSnapshot(_ context.Context, _ service.SchedulerBucket) ([]*service.Account, bool, error) { return f.accounts, true, nil } -func (f *fakeSchedulerCache) SetSnapshot(_ context.Context, _ service.SchedulerBucket, _ []service.Account) error { +func (f *fakeSchedulerCache) CaptureBucketWriteToken(_ context.Context, bucket service.SchedulerBucket) (service.SchedulerBucketWriteToken, error) { + return service.SchedulerBucketWriteToken{Bucket: bucket, Epoch: 1}, nil +} +func (f *fakeSchedulerCache) SetSnapshot(_ context.Context, _ service.SchedulerBucket, _ service.SchedulerBucketWriteToken, _ []service.Account) error { + return nil +} +func (f *fakeSchedulerCache) RetireBucket(_ context.Context, _ service.SchedulerBucket) error { + return nil +} +func (f *fakeSchedulerCache) ReopenBucket(_ context.Context, bucket service.SchedulerBucket) (service.SchedulerBucketWriteToken, error) { + return service.SchedulerBucketWriteToken{Bucket: bucket, Epoch: 1}, nil +} +func (f *fakeSchedulerCache) TryAcquireGroupLifecycleLease(_ context.Context, _ int64, _ time.Duration) (service.SchedulerGroupLifecycleLease, bool, error) { + return service.SchedulerGroupLifecycleLease{}, false, nil +} +func (f *fakeSchedulerCache) ReleaseGroupLifecycleLease(_ context.Context, _ service.SchedulerGroupLifecycleLease) error { return nil } func (f *fakeSchedulerCache) GetAccount(_ context.Context, id int64) (*service.Account, error) { diff --git a/backend/internal/handler/gateway_helper.go b/backend/internal/handler/gateway_helper.go index 8489b17f6d..1f6daf5291 100644 --- a/backend/internal/handler/gateway_helper.go +++ b/backend/internal/handler/gateway_helper.go @@ -163,20 +163,15 @@ func wrapReleaseOnDone(ctx context.Context, releaseFunc func()) func() { return nil } var once sync.Once - var stop func() bool - - release := func() { - once.Do(func() { - if stop != nil { - _ = stop() - } - releaseFunc() - }) + releaseOnce := func() { + once.Do(releaseFunc) } + stop := context.AfterFunc(ctx, releaseOnce) - stop = context.AfterFunc(ctx, release) - - return release + return func() { + _ = stop() + releaseOnce() + } } // IncrementWaitCount increments the wait count for a user diff --git a/backend/internal/handler/gateway_helper_test.go b/backend/internal/handler/gateway_helper_test.go index 664258f8c9..bc0f50f0b6 100644 --- a/backend/internal/handler/gateway_helper_test.go +++ b/backend/internal/handler/gateway_helper_test.go @@ -6,6 +6,8 @@ import ( "sync/atomic" "testing" "time" + + "github.com/stretchr/testify/require" ) // TestWrapReleaseOnDone_NoGoroutineLeak 验证 wrapReleaseOnDone 修复后不会泄露 goroutine @@ -67,6 +69,21 @@ func TestWrapReleaseOnDone_ContextCancellation(t *testing.T) { } } +func TestWrapReleaseOnDone_AlreadyCancelledReleasesExactlyOnce(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + var releaseCount int32 + release := wrapReleaseOnDone(ctx, func() { + atomic.AddInt32(&releaseCount, 1) + }) + release() + + require.Eventually(t, func() bool { + return atomic.LoadInt32(&releaseCount) == 1 + }, time.Second, time.Millisecond) +} + // TestWrapReleaseOnDone_MultipleCallsOnlyReleaseOnce 验证多次调用 release 只释放一次 func TestWrapReleaseOnDone_MultipleCallsOnlyReleaseOnce(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) diff --git a/backend/internal/handler/gemini_v1beta_handler.go b/backend/internal/handler/gemini_v1beta_handler.go index b1653c6b3f..c595abfe55 100644 --- a/backend/internal/handler/gemini_v1beta_handler.go +++ b/backend/internal/handler/gemini_v1beta_handler.go @@ -368,6 +368,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { c.Request = c.Request.WithContext(ctx) continue case FailoverCanceled: + failoverClientGone(c) return default: // FailoverExhausted h.handleGeminiFailoverExhausted(c, fs.LastFailoverErr) @@ -490,6 +491,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { h.handleGeminiFailoverExhausted(c, fs.LastFailoverErr) return case FailoverCanceled: + failoverClientGone(c) return } } diff --git a/backend/internal/handler/grok_media.go b/backend/internal/handler/grok_media.go index b7092fcc42..01928028e6 100644 --- a/backend/internal/handler/grok_media.go +++ b/backend/internal/handler/grok_media.go @@ -166,6 +166,7 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service. failedAccountIDs := make(map[int64]struct{}) sameAccountRetryCount := make(map[int64]int) var lastFailoverErr *service.UpstreamFailoverError + var oauth429FailoverState service.OpenAIOAuth429FailoverState switchCount := 0 maxAccountSwitches := h.maxAccountSwitches if maxAccountSwitches <= 0 { @@ -174,6 +175,9 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service. routingStart := time.Now() for { + if failoverClientGone(c) { + return + } selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability( requestCtx, apiKey.GroupID, @@ -188,6 +192,10 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service. service.PlatformGrok, ) if err != nil { + if failoverClientGone(c) { + reqLog.Info("grok_media.account_select_aborted_client_disconnected", zap.Error(err)) + return + } reqLog.Warn("grok_media.account_select_failed", zap.Error(err), zap.Int("excluded_account_count", len(failedAccountIDs)), @@ -257,11 +265,24 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service. if err != nil { var failoverErr *service.UpstreamFailoverError if errors.As(err, &failoverErr) { - h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) + if failoverClientGone(c) { + reqLog.Info("grok_media.failover_aborted_client_disconnected", + zap.Int64("account_id", account.ID), + zap.Int("upstream_status", failoverErr.StatusCode), + ) + return + } + if failoverErr.ShouldReportAccountScheduleFailure() { + h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) + } if c.Writer.Size() != writerSizeBeforeForward { h.handleFailoverExhausted(c, failoverErr, true) return } + if !failoverErr.ShouldRetryNextAccount() { + h.handleFailoverExhausted(c, failoverErr, false) + return + } if failoverErr.RetryableOnSameAccount { retryLimit := account.GetPoolModeRetryCount() if sameAccountRetryCount[account.ID] < retryLimit { @@ -288,6 +309,10 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service. return } switchCount++ + if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) { + h.handleFailoverExhausted(c, failoverErr, false) + return + } reqLog.Warn("grok_media.upstream_failover_switching", zap.Int64("account_id", account.ID), zap.Int("upstream_status", failoverErr.StatusCode), diff --git a/backend/internal/handler/openai_alpha_search.go b/backend/internal/handler/openai_alpha_search.go index a808145235..a1d185a1cb 100644 --- a/backend/internal/handler/openai_alpha_search.go +++ b/backend/internal/handler/openai_alpha_search.go @@ -106,6 +106,7 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) { failedAccountIDs := make(map[int64]struct{}) var lastFailoverErr *service.UpstreamFailoverError switchCount := 0 + var oauth429FailoverState service.OpenAIOAuth429FailoverState routingStart := time.Now() for { @@ -123,6 +124,10 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) { service.PlatformOpenAI, ) if err != nil || selection == nil || selection.Account == nil { + if failoverClientGone(c) { + reqLog.Info("openai_alpha_search.account_select_aborted_client_disconnected", zap.Error(err)) + return + } if len(failedAccountIDs) == 0 { cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, requestedModel, requestedModel, service.PlatformOpenAI) if !cls.ModelNotFound { @@ -180,6 +185,13 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) { h.handleFailoverExhausted(c, failoverErr, true) return } + if failoverClientGone(c) { + reqLog.Info("openai_alpha_search.failover_aborted_client_disconnected", + zap.Int64("account_id", account.ID), + zap.Int("upstream_status", failoverErr.StatusCode), + ) + return + } h.gatewayService.RecordOpenAIAccountSwitch() failedAccountIDs[account.ID] = struct{}{} lastFailoverErr = failoverErr @@ -188,7 +200,7 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) { return } switchCount++ - if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) { + if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) { h.handleFailoverExhausted(c, failoverErr, false) return } diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index 636e143740..62a2b70b59 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -133,8 +133,12 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { failedAccountIDs := make(map[int64]struct{}) sameAccountRetryCount := make(map[int64]int) var lastFailoverErr *service.UpstreamFailoverError + var oauth429FailoverState service.OpenAIOAuth429FailoverState for { + if failoverClientGone(c) { + return + } reqLog.Debug("openai_chat_completions.account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs))) selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability( c.Request.Context(), @@ -150,6 +154,10 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { requestPlatform, ) if err != nil { + if failoverClientGone(c) { + reqLog.Info("openai_chat_completions.account_select_aborted_client_disconnected", zap.Error(err)) + return + } reqLog.Warn("openai_chat_completions.account_select_failed", zap.Error(openAICompatibleSelectionErrorForLog(err, requestPlatform)), zap.Int("excluded_account_count", len(failedAccountIDs)), @@ -231,11 +239,24 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { } else { var failoverErr *service.UpstreamFailoverError if errors.As(err, &failoverErr) { + if failoverClientGone(c) { + reqLog.Info("openai_chat_completions.failover_aborted_client_disconnected", + zap.Int64("account_id", account.ID), + zap.Int("upstream_status", failoverErr.StatusCode), + ) + return + } if c.Writer.Size() != writerSizeBeforeForward { h.handleFailoverExhausted(c, failoverErr, true) return } - h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) + if failoverErr.ShouldReportAccountScheduleFailure() { + h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) + } + if !failoverErr.ShouldRetryNextAccount() { + h.handleFailoverExhausted(c, failoverErr, streamStarted) + return + } // Pool mode: retry on the same account if failoverErr.RetryableOnSameAccount { retryLimit := account.GetPoolModeRetryCount() @@ -263,7 +284,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { return } switchCount++ - if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) { + if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) { h.handleFailoverExhausted(c, failoverErr, streamStarted) return } diff --git a/backend/internal/handler/openai_embeddings.go b/backend/internal/handler/openai_embeddings.go index 56d775eb7c..99f869f14c 100644 --- a/backend/internal/handler/openai_embeddings.go +++ b/backend/internal/handler/openai_embeddings.go @@ -121,6 +121,10 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) { false, ) if err != nil { + if failoverClientGone(c) { + reqLog.Info("openai_embeddings.account_select_aborted_client_disconnected", zap.Error(err)) + return + } reqLog.Warn("openai_embeddings.account_select_failed", zap.Error(err), zap.Int("excluded_account_count", len(failedAccountIDs)), @@ -189,6 +193,13 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) { return } h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) + if failoverClientGone(c) { + reqLog.Info("openai_embeddings.failover_aborted_client_disconnected", + zap.Int64("account_id", account.ID), + zap.Int("upstream_status", failoverErr.StatusCode), + ) + return + } h.gatewayService.RecordOpenAIAccountSwitch() failedAccountIDs[account.ID] = struct{}{} lastFailoverErr = failoverErr diff --git a/backend/internal/handler/openai_gateway_compact_log_test.go b/backend/internal/handler/openai_gateway_compact_log_test.go index e18509b4b3..16afd30c31 100644 --- a/backend/internal/handler/openai_gateway_compact_log_test.go +++ b/backend/internal/handler/openai_gateway_compact_log_test.go @@ -66,6 +66,20 @@ func (s *handlerInMemoryLogSink) ContainsFieldValue(field, substr string) bool { return false } +func (s *handlerInMemoryLogSink) FieldValueForMessage(message, field string) (any, bool) { + s.mu.Lock() + defer s.mu.Unlock() + for _, event := range s.events { + if event == nil || event.Message != message || event.Fields == nil { + continue + } + if value, ok := event.Fields[field]; ok { + return value, true + } + } + return nil, false +} + func captureHandlerStructuredLog(t *testing.T) (*handlerInMemoryLogSink, func()) { t.Helper() handlerStructuredLogCaptureMu.Lock() diff --git a/backend/internal/handler/openai_gateway_credential_failover_loop_test.go b/backend/internal/handler/openai_gateway_credential_failover_loop_test.go new file mode 100644 index 0000000000..42a6bf6cd3 --- /dev/null +++ b/backend/internal/handler/openai_gateway_credential_failover_loop_test.go @@ -0,0 +1,926 @@ +//go:build unit + +package handler + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/pkg/xai" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + coderws "github.com/coder/websocket" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type grokCredentialHandlerRepo struct { + service.AccountRepository + mu sync.Mutex + accounts []service.Account + setErrorIDs []int64 + setTempIDs []int64 + rateLimitIDs []int64 + updateExtraIDs []int64 + selectionCalls int + setErrorErr error + setTempErr error + missingOnGet map[int64]bool +} + +func (r *grokCredentialHandlerRepo) ListSchedulableByPlatform(_ context.Context, platform string) ([]service.Account, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.selectionCalls++ + out := make([]service.Account, 0, len(r.accounts)) + for _, account := range r.accounts { + if account.Platform == platform && account.IsSchedulable() { + out = append(out, account) + } + } + return out, nil +} + +func (r *grokCredentialHandlerRepo) ListSchedulableByGroupIDAndPlatform(ctx context.Context, _ int64, platform string) ([]service.Account, error) { + return r.ListSchedulableByPlatform(ctx, platform) +} + +func (r *grokCredentialHandlerRepo) ListSchedulableUngroupedByPlatform(ctx context.Context, platform string) ([]service.Account, error) { + return r.ListSchedulableByPlatform(ctx, platform) +} + +func (r *grokCredentialHandlerRepo) GetByID(_ context.Context, id int64) (*service.Account, error) { + r.mu.Lock() + defer r.mu.Unlock() + if r.missingOnGet[id] { + return nil, nil + } + for _, account := range r.accounts { + if account.ID == id { + copy := account + copy.Credentials = cloneCredentialMap(account.Credentials) + return ©, nil + } + } + return nil, nil +} + +func (r *grokCredentialHandlerRepo) SetError(_ context.Context, id int64, message string) error { + r.mu.Lock() + defer r.mu.Unlock() + r.setErrorIDs = append(r.setErrorIDs, id) + if r.setErrorErr != nil { + return r.setErrorErr + } + for i := range r.accounts { + if r.accounts[i].ID == id { + r.accounts[i].Status = service.StatusError + r.accounts[i].Schedulable = false + r.accounts[i].ErrorMessage = message + } + } + return nil +} + +func (r *grokCredentialHandlerRepo) SetTempUnschedulable(_ context.Context, id int64, until time.Time, _ string) error { + r.mu.Lock() + defer r.mu.Unlock() + r.setTempIDs = append(r.setTempIDs, id) + if r.setTempErr != nil { + return r.setTempErr + } + for i := range r.accounts { + if r.accounts[i].ID == id { + value := until + r.accounts[i].TempUnschedulableUntil = &value + } + } + return nil +} + +func (r *grokCredentialHandlerRepo) SetRateLimited(_ context.Context, id int64, resetAt time.Time) error { + r.mu.Lock() + defer r.mu.Unlock() + r.rateLimitIDs = append(r.rateLimitIDs, id) + for i := range r.accounts { + if r.accounts[i].ID != id { + continue + } + now := time.Now() + r.accounts[i].RateLimitedAt = &now + value := resetAt + r.accounts[i].RateLimitResetAt = &value + } + return nil +} + +func (r *grokCredentialHandlerRepo) SetRateLimitedIfLater(ctx context.Context, id int64, resetAt time.Time) error { + r.mu.Lock() + for i := range r.accounts { + if r.accounts[i].ID == id && r.accounts[i].RateLimitResetAt != nil && !resetAt.After(*r.accounts[i].RateLimitResetAt) { + r.mu.Unlock() + return nil + } + } + r.mu.Unlock() + return r.SetRateLimited(ctx, id, resetAt) +} + +func (r *grokCredentialHandlerRepo) SetGrokCredentialErrorIfMatch( + _ context.Context, + id int64, + snapshot service.GrokCredentialMutationSnapshot, + message string, +) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + for i := range r.accounts { + account := &r.accounts[i] + if account.ID != id || !handlerGrokCredentialSnapshotMatches(account, snapshot) { + continue + } + r.setErrorIDs = append(r.setErrorIDs, id) + if r.setErrorErr != nil { + return false, r.setErrorErr + } + account.Status = service.StatusError + account.Schedulable = false + account.ErrorMessage = message + return true, nil + } + return false, nil +} + +func (r *grokCredentialHandlerRepo) SetGrokCredentialTempUnschedulableIfMatch( + _ context.Context, + id int64, + snapshot service.GrokCredentialMutationSnapshot, + until time.Time, + _ string, +) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + for i := range r.accounts { + account := &r.accounts[i] + if account.ID != id || !handlerGrokCredentialSnapshotMatches(account, snapshot) { + continue + } + r.setTempIDs = append(r.setTempIDs, id) + if r.setTempErr != nil { + return false, r.setTempErr + } + value := until + account.TempUnschedulableUntil = &value + return true, nil + } + return false, nil +} + +func handlerGrokCredentialSnapshotMatches(account *service.Account, snapshot service.GrokCredentialMutationSnapshot) bool { + if account == nil { + return false + } + credentialsJSON, err := json.Marshal(account.Credentials) + return err == nil && account.IsGrokOAuth() && account.IsSchedulable() && string(credentialsJSON) == snapshot.CredentialsJSON && + handlerGrokCredentialProxyIDsEqual(account.ProxyID, snapshot.ProxyID) +} + +func handlerGrokCredentialProxyIDsEqual(left, right *int64) bool { + if left == nil || right == nil { + return left == nil && right == nil + } + return *left == *right +} + +func (r *grokCredentialHandlerRepo) UpdateExtra(_ context.Context, id int64, updates map[string]any) error { + r.mu.Lock() + defer r.mu.Unlock() + r.updateExtraIDs = append(r.updateExtraIDs, id) + for i := range r.accounts { + if r.accounts[i].ID != id { + continue + } + if r.accounts[i].Extra == nil { + r.accounts[i].Extra = map[string]any{} + } + for key, value := range updates { + r.accounts[i].Extra[key] = value + } + } + return nil +} + +func (r *grokCredentialHandlerRepo) errorIDs() []int64 { + r.mu.Lock() + defer r.mu.Unlock() + return append([]int64(nil), r.setErrorIDs...) +} + +func (r *grokCredentialHandlerRepo) selectorCalls() int { + r.mu.Lock() + defer r.mu.Unlock() + return r.selectionCalls +} + +func (r *grokCredentialHandlerRepo) rateLimitedAccountIDs() []int64 { + r.mu.Lock() + defer r.mu.Unlock() + return append([]int64(nil), r.rateLimitIDs...) +} + +type grokCredentialHandlerTokenCache struct { + service.GrokTokenCache + mu sync.Mutex + deleteErr error +} + +func (c *grokCredentialHandlerTokenCache) GetAccessToken(context.Context, string) (string, error) { + return "", errors.New("not cached") +} + +func (c *grokCredentialHandlerTokenCache) SetAccessToken(context.Context, string, string, time.Duration) error { + return nil +} + +func (c *grokCredentialHandlerTokenCache) DeleteAccessToken(context.Context, string) error { + c.mu.Lock() + defer c.mu.Unlock() + return c.deleteErr +} + +func (c *grokCredentialHandlerTokenCache) AcquireRefreshLock(context.Context, string, time.Duration) (bool, error) { + return true, nil +} + +func (c *grokCredentialHandlerTokenCache) ReleaseRefreshLock(context.Context, string) error { + return nil +} + +func cloneCredentialMap(source map[string]any) map[string]any { + cloned := make(map[string]any, len(source)) + for key, value := range source { + cloned[key] = value + } + return cloned +} + +type grokCredentialHandlerRefresher struct { + mode string + started chan struct{} + once sync.Once +} + +func (r *grokCredentialHandlerRefresher) CacheKey(account *service.Account) string { + return service.GrokTokenCacheKey(account) +} + +func (r *grokCredentialHandlerRefresher) CanRefresh(account *service.Account) bool { + return account != nil && account.IsGrokOAuth() +} + +func (r *grokCredentialHandlerRefresher) NeedsRefresh(account *service.Account, _ time.Duration) bool { + return account != nil && (account.ID == 801 || r.mode == "all_revoked") +} + +func (r *grokCredentialHandlerRefresher) Refresh(ctx context.Context, _ *service.Account) (map[string]any, error) { + switch r.mode { + case "revoked", "all_revoked", "mutation_set_error", "mutation_cache": + return nil, infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_grant") + case "provider": + return nil, infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_client") + case "cancel": + r.once.Do(func() { close(r.started) }) + <-ctx.Done() + return nil, ctx.Err() + case "transient", "mutation_temp": + return nil, errors.New("temporary refresh transport failure") + default: + return nil, nil + } +} + +type grokCredentialHandlerUpstream struct { + service.HTTPUpstream + mu sync.Mutex + hits []int64 + requestURLs []string + authorization []string + failAccountID int64 + rateLimitIDs map[int64]bool + failureStatus map[int64]int + cancelRequest context.CancelFunc +} + +func (u *grokCredentialHandlerUpstream) Do(req *http.Request, _ string, accountID int64, _ int) (*http.Response, error) { + var requestBody []byte + if req.Body != nil { + requestBody, _ = io.ReadAll(req.Body) + } + u.mu.Lock() + u.hits = append(u.hits, accountID) + u.requestURLs = append(u.requestURLs, req.URL.String()) + u.authorization = append(u.authorization, req.Header.Get("Authorization")) + failAccountID := u.failAccountID + rateLimited := u.rateLimitIDs[accountID] + failureStatus := u.failureStatus[accountID] + cancelRequest := u.cancelRequest + u.mu.Unlock() + if rateLimited { + return &http.Response{ + StatusCode: http.StatusTooManyRequests, + Header: http.Header{ + "Content-Type": []string{"application/json"}, + "Retry-After": []string{"60"}, + }, + Body: io.NopCloser(bytes.NewBufferString(`{"error":{"message":"rate limited"}}`)), + }, nil + } + if failureStatus > 0 { + return &http.Response{ + StatusCode: failureStatus, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(bytes.NewBufferString(`{"error":{"message":"upstream unavailable"}}`)), + }, nil + } + if accountID == failAccountID { + if cancelRequest != nil { + cancelRequest() + } + return &http.Response{ + StatusCode: http.StatusPaymentRequired, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(bytes.NewBufferString(`{"error":{"message":"payment required"}}`)), + }, nil + } + if bytes.Contains(requestBody, []byte(`"stream":true`)) { + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(bytes.NewBufferString( + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_healthy\",\"model\":\"grok-4.5\",\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n", + )), + }, nil + } + if strings.Contains(req.URL.Path, "/chat/completions") { + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(bytes.NewBufferString( + `{"id":"chatcmpl_healthy","object":"chat.completion","model":"grok-4.5","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`, + )), + }, nil + } + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(bytes.NewBufferString( + `{"id":"resp_healthy","object":"response","model":"grok-4.5","status":"completed","output":[],"usage":{"input_tokens":1,"output_tokens":1}}`, + )), + }, nil +} + +func (u *grokCredentialHandlerUpstream) accountHits() []int64 { + u.mu.Lock() + defer u.mu.Unlock() + return append([]int64(nil), u.hits...) +} + +func (u *grokCredentialHandlerUpstream) requests() ([]string, []string) { + u.mu.Lock() + defer u.mu.Unlock() + return append([]string(nil), u.requestURLs...), append([]string(nil), u.authorization...) +} + +func TestResponsesCredentialFailoverLoop(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("revoked account selects healthy account", func(t *testing.T) { + h, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "revoked") + defer cleanup() + _ = h + + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Contains(t, recorder.Body.String(), "resp_healthy") + require.Equal(t, []int64{801}, repo.errorIDs()) + require.Equal(t, []int64{802}, upstream.accountHits()) + requestURLs, authorization := upstream.requests() + require.Equal(t, []string{xai.DefaultCLIBaseURL + "/responses"}, requestURLs) + require.Equal(t, []string{"Bearer healthy-access"}, authorization) + }) + + t.Run("provider configuration stops before healthy account", func(t *testing.T) { + h, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "provider") + defer cleanup() + + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusServiceUnavailable, recorder.Code) + require.Contains(t, recorder.Body.String(), service.GrokCredentialUnavailableClientMessage) + require.Empty(t, repo.errorIDs()) + require.Empty(t, upstream.accountHits()) + require.Equal(t, 1, repo.selectorCalls()) + require.Zero(t, h.gatewayService.SnapshotOpenAIAccountSchedulerMetrics().RuntimeStatsAccountCount, + "provider-scoped auth failure must not penalize the selected account") + }) + + t.Run("parent cancellation stops before healthy account", func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "cancel") + defer cleanup() + + ctx, cancel := context.WithCancel(context.Background()) + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)).WithContext(ctx) + req.Header.Set("Content-Type", "application/json") + recorder := httptest.NewRecorder() + done := make(chan struct{}) + go func() { + defer close(done) + router.ServeHTTP(recorder, req) + }() + + select { + case <-time.After(2 * time.Second): + t.Fatal("credential refresh did not start") + case <-findHandlerRefresherStarted(router): + cancel() + } + select { + case <-time.After(2 * time.Second): + t.Fatal("handler did not stop after cancellation") + case <-done: + } + + require.Empty(t, repo.errorIDs()) + require.Empty(t, upstream.accountHits()) + }) + + t.Run("post-mapping cancellation stops before scheduler mutation or reselection", func(t *testing.T) { + h, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "postmap_cancel") + defer cleanup() + ctx, cancel := context.WithCancel(context.Background()) + upstream.mu.Lock() + upstream.failAccountID = 801 + upstream.cancelRequest = cancel + upstream.mu.Unlock() + + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)).WithContext(ctx) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(recorder, req) + + require.Equal(t, []int64{801}, upstream.accountHits()) + require.Empty(t, repo.errorIDs()) + require.Equal(t, 1, repo.selectorCalls()) + require.Zero(t, h.gatewayService.SnapshotOpenAIAccountSchedulerMetrics().RuntimeStatsAccountCount) + }) + + t.Run("pre-cancelled request never invokes an account selector", func(t *testing.T) { + tests := []struct { + name string + method string + path string + body string + }{ + {name: "responses", method: http.MethodPost, path: "/openai/v1/responses", body: `{"model":"grok","input":"hello","stream":false}`}, + {name: "messages", method: http.MethodPost, path: "/openai/v1/messages", body: `{"model":"grok","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`}, + {name: "chat completions", method: http.MethodPost, path: "/openai/v1/chat/completions", body: `{"model":"grok","messages":[{"role":"user","content":"hello"}],"stream":false}`}, + {name: "grok media", method: http.MethodGet, path: "/openai/v1/videos/request-1"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "revoked") + defer cleanup() + ctx, cancel := context.WithCancel(context.Background()) + cancel() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(tt.method, tt.path, bytes.NewBufferString(tt.body)).WithContext(ctx) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Zero(t, repo.selectorCalls()) + require.Empty(t, upstream.accountHits()) + }) + } + }) + + t.Run("credential state mutation failures stop before reselection", func(t *testing.T) { + for _, mode := range []string{"mutation_set_error", "mutation_temp", "mutation_cache"} { + t.Run(mode, func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, mode) + defer cleanup() + + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusServiceUnavailable, recorder.Code, recorder.Body.String()) + require.Contains(t, recorder.Body.String(), service.GrokCredentialUnavailableClientMessage) + require.Empty(t, upstream.accountHits()) + require.Equal(t, 1, repo.selectorCalls()) + }) + } + }) + + t.Run("missing credential provider stops before upstream or reselection", func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "nil_provider") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusServiceUnavailable, recorder.Code, recorder.Body.String()) + require.Contains(t, recorder.Body.String(), service.GrokCredentialUnavailableClientMessage) + require.Equal(t, 1, repo.selectorCalls()) + require.Empty(t, upstream.accountHits()) + require.Empty(t, repo.errorIDs()) + }) +} + +func TestResponsesGrok429FailoverIsBounded(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("first rate limited account selects healthy account", func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "first_429") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Contains(t, recorder.Body.String(), "resp_healthy") + require.Equal(t, []int64{801, 802}, upstream.accountHits()) + require.Equal(t, []int64{801}, repo.rateLimitedAccountIDs()) + }) + + t.Run("two rate limited accounts stop without sweeping the pool", func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "all_429") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusTooManyRequests, recorder.Code, recorder.Body.String()) + require.Equal(t, []int64{801, 802}, upstream.accountHits()) + require.Equal(t, []int64{801, 802}, repo.rateLimitedAccountIDs()) + require.NotContains(t, recorder.Body.String(), "expired") + require.NotContains(t, recorder.Body.String(), "healthy-access") + require.NotContains(t, recorder.Body.String(), "rate limited") + }) +} + +func TestResponsesGrok429FailoverHandlesMixedStatuses(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("429 then 500 stops after the bounded followup", func(t *testing.T) { + _, _, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "mixed_429_500") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusBadGateway, recorder.Code, recorder.Body.String()) + require.Equal(t, []int64{801, 802}, upstream.accountHits()) + require.NotContains(t, recorder.Body.String(), "upstream unavailable") + }) + + t.Run("500 then 429 permits one healthy followup", func(t *testing.T) { + _, _, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "mixed_500_429") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Equal(t, []int64{801, 802, 803}, upstream.accountHits()) + }) + + t.Run("OAuth 429 then API-key failure cannot bypass the bound", func(t *testing.T) { + _, _, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "oauth_429_apikey_500") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusBadGateway, recorder.Code, recorder.Body.String()) + require.Equal(t, []int64{801, 802}, upstream.accountHits()) + }) +} + +func TestGrokMedia429FailoverIsBounded(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("first 429 selects one healthy followup", func(t *testing.T) { + _, _, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "first_429") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/openai/v1/videos/request-1", nil) + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Equal(t, []int64{801, 802}, upstream.accountHits()) + }) + + t.Run("second 429 stops without sweeping a third account", func(t *testing.T) { + _, _, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "all_429") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/openai/v1/videos/request-1", nil) + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusTooManyRequests, recorder.Code, recorder.Body.String()) + require.Equal(t, []int64{801, 802}, upstream.accountHits()) + require.NotContains(t, recorder.Body.String(), "rate limited") + }) +} + +func TestGrokOAuthCredentialFailoverAcrossHTTPHandlers(t *testing.T) { + gin.SetMode(gin.TestMode) + endpoints := []struct { + name string + method string + path string + body string + }{ + {name: "messages", method: http.MethodPost, path: "/openai/v1/messages", body: `{"model":"grok","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`}, + {name: "chat completions", method: http.MethodPost, path: "/openai/v1/chat/completions", body: `{"model":"grok","messages":[{"role":"user","content":"hello"}],"stream":false}`}, + {name: "chat completions raw fallback", method: http.MethodPost, path: "/openai/v1/chat/completions", body: `{"model":"grok","messages":[{"role":"user","content":"hello"}],"stop":["END"],"stream":false}`}, + {name: "grok media", method: http.MethodGet, path: "/openai/v1/videos/request-1"}, + } + + for _, endpoint := range endpoints { + t.Run(endpoint.name+" revoked selects healthy", func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "revoked") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(endpoint.method, endpoint.path, bytes.NewBufferString(endpoint.body)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Equal(t, []int64{801}, repo.errorIDs()) + require.Equal(t, []int64{802}, upstream.accountHits()) + }) + + t.Run(endpoint.name+" all accounts exhausted safely", func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "all_revoked") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(endpoint.method, endpoint.path, bytes.NewBufferString(endpoint.body)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusServiceUnavailable, recorder.Code, recorder.Body.String()) + require.Contains(t, recorder.Body.String(), service.GrokCredentialUnavailableClientMessage) + require.NotContains(t, recorder.Body.String(), "revoked-refresh") + require.NotContains(t, recorder.Body.String(), "healthy-refresh") + require.Equal(t, []int64{801, 802}, repo.errorIDs()) + require.Empty(t, upstream.accountHits()) + }) + } +} + +func TestGrokOAuthMissingSelectedRowRetriesHealthyAccountWithoutMutation(t *testing.T) { + gin.SetMode(gin.TestMode) + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "missing_row") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Equal(t, []int64{802}, upstream.accountHits()) + require.Empty(t, repo.errorIDs()) + require.Empty(t, repo.setTempIDs) +} + +func TestResponsesWebSocketCredentialFailoverLoop(t *testing.T) { + gin.SetMode(gin.TestMode) + dial := func(t *testing.T, router *gin.Engine) (*coderws.Conn, func()) { + t.Helper() + server := httptest.NewServer(router) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + conn, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(server.URL, "http")+"/openai/v1/responses", nil) + cancel() + require.NoError(t, err) + return conn, func() { + _ = conn.CloseNow() + server.Close() + } + } + writeFirst := func(t *testing.T, conn *coderws.Conn) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + require.NoError(t, conn.Write(ctx, coderws.MessageText, []byte(`{"type":"response.create","model":"grok","input":"hello","stream":false}`))) + } + + t.Run("revoked account selects healthy account", func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "revoked") + defer cleanup() + conn, closeConn := dial(t, router) + defer closeConn() + writeFirst(t, conn) + + readCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + _, payload, err := conn.Read(readCtx) + cancel() + require.NoError(t, err) + require.Contains(t, string(payload), "resp_healthy") + require.Equal(t, []int64{801}, repo.errorIDs()) + require.Equal(t, 2, repo.selectorCalls()) + require.Equal(t, []int64{802}, upstream.accountHits()) + }) + + t.Run("provider configuration stops", func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "provider") + defer cleanup() + conn, closeConn := dial(t, router) + defer closeConn() + writeFirst(t, conn) + + readCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + _, _, err := conn.Read(readCtx) + cancel() + var closeErr coderws.CloseError + require.ErrorAs(t, err, &closeErr) + require.Contains(t, closeErr.Reason, service.GrokCredentialUnavailableClientMessage) + require.Equal(t, 1, repo.selectorCalls()) + require.Empty(t, upstream.accountHits()) + }) + + t.Run("parent cancellation prevents reselection", func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "cancel") + defer cleanup() + conn, closeConn := dial(t, router) + writeFirst(t, conn) + select { + case <-findHandlerRefresherStarted(router): + case <-time.After(2 * time.Second): + t.Fatal("credential refresh did not start") + } + closeConn() + + require.Eventually(t, func() bool { return repo.selectorCalls() == 1 }, 2*time.Second, 20*time.Millisecond) + require.Empty(t, repo.errorIDs()) + require.Empty(t, upstream.accountHits()) + }) +} + +var handlerRefresherStarted sync.Map + +func findHandlerRefresherStarted(router *gin.Engine) <-chan struct{} { + value, _ := handlerRefresherStarted.Load(router) + return value.(chan struct{}) +} + +func newGrokCredentialFailoverHandler(t *testing.T, mode string) (*OpenAIGatewayHandler, *grokCredentialHandlerRepo, *grokCredentialHandlerUpstream, *gin.Engine, func()) { + t.Helper() + groupID := int64(901) + accounts := []service.Account{ + { + ID: 801, Name: "revoked", Platform: service.PlatformGrok, Type: service.AccountTypeOAuth, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, Priority: 1, + Credentials: map[string]any{ + "access_token": "expired", "refresh_token": "revoked-refresh", + "expires_at": time.Now().Add(-time.Minute).UTC().Format(time.RFC3339), + }, + }, + { + ID: 802, Name: "healthy", Platform: service.PlatformGrok, Type: service.AccountTypeOAuth, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, Priority: 2, + Credentials: map[string]any{ + "access_token": "healthy-access", "refresh_token": "healthy-refresh", + "expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339), + }, + }, + } + if mode == "postmap_cancel" || mode == "first_429" || mode == "all_429" || mode == "mixed_429_500" || mode == "mixed_500_429" || mode == "oauth_429_apikey_500" { + accounts[0].Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + } + if mode == "all_429" || mode == "mixed_429_500" || mode == "mixed_500_429" || mode == "oauth_429_apikey_500" { + accounts = append(accounts, service.Account{ + ID: 803, Name: "untried-healthy", Platform: service.PlatformGrok, Type: service.AccountTypeOAuth, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, Priority: 3, + Credentials: map[string]any{ + "access_token": "untried-healthy-access", "refresh_token": "untried-healthy-refresh", + "expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339), + }, + }) + } + if mode == "oauth_429_apikey_500" { + accounts[1].Type = service.AccountTypeAPIKey + accounts[1].Credentials = map[string]any{"api_key": "third-party-key"} + } + if mode == "all_revoked" { + accounts[1].Credentials["expires_at"] = time.Now().Add(-time.Minute).UTC().Format(time.RFC3339) + } + repo := &grokCredentialHandlerRepo{accounts: accounts, missingOnGet: map[int64]bool{}} + if mode == "missing_row" { + repo.missingOnGet[801] = true + } + if mode == "mutation_set_error" { + repo.setErrorErr = errors.New("database write failed") + } + if mode == "mutation_temp" { + repo.setTempErr = errors.New("database write failed") + } + refresher := &grokCredentialHandlerRefresher{mode: mode, started: make(chan struct{})} + tokenCache := &grokCredentialHandlerTokenCache{} + if mode == "mutation_cache" { + tokenCache.deleteErr = errors.New("cache delete failed") + } + var provider *service.GrokTokenProvider + if mode != "nil_provider" { + provider = service.NewGrokTokenProvider(repo, tokenCache) + provider.SetRefreshAPI(service.NewOAuthRefreshAPI(repo, tokenCache), refresher) + } + upstream := &grokCredentialHandlerUpstream{} + switch mode { + case "first_429": + upstream.rateLimitIDs = map[int64]bool{801: true} + case "all_429": + upstream.rateLimitIDs = map[int64]bool{801: true, 802: true} + case "mixed_429_500": + upstream.rateLimitIDs = map[int64]bool{801: true} + upstream.failureStatus = map[int64]int{802: http.StatusInternalServerError} + case "mixed_500_429": + upstream.failureStatus = map[int64]int{801: http.StatusInternalServerError} + upstream.rateLimitIDs = map[int64]bool{802: true} + case "oauth_429_apikey_500": + upstream.rateLimitIDs = map[int64]bool{801: true} + upstream.failureStatus = map[int64]int{802: http.StatusInternalServerError} + } + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Gateway.MaxAccountSwitches = 3 + billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + gateway := service.NewOpenAIGatewayService( + repo, nil, nil, nil, nil, nil, nil, cfg, nil, nil, + service.NewBillingService(cfg, nil), nil, billingCache, upstream, + &service.DeferredService{}, nil, provider, nil, nil, nil, nil, nil, + ) + cache := &concurrencyCacheMock{ + acquireUserSlotFn: func(context.Context, int64, int, string) (bool, error) { return true, nil }, + acquireAccountSlotFn: func(context.Context, int64, int, string) (bool, error) { return true, nil }, + } + h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(cache), billingCache, &service.APIKeyService{}, nil, nil, nil, nil, cfg) + apiKey := &service.APIKey{ + ID: 902, GroupID: &groupID, + User: &service.User{ID: 903, Status: service.StatusActive}, + Group: &service.Group{ID: groupID, Platform: service.PlatformGrok, Status: service.StatusActive}, + } + router := gin.New() + router.Use(func(c *gin.Context) { + c.Set(string(middleware.ContextKeyAPIKey), apiKey) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.User.ID, Concurrency: 1}) + c.Next() + }) + router.POST("/openai/v1/responses", h.Responses) + router.GET("/openai/v1/responses", h.ResponsesWebSocket) + router.POST("/openai/v1/messages", h.Messages) + router.POST("/openai/v1/chat/completions", h.ChatCompletions) + router.GET("/openai/v1/videos/:request_id", h.GrokVideoStatus) + handlerRefresherStarted.Store(router, refresher.started) + cleanup := func() { + handlerRefresherStarted.Delete(router) + billingCache.Stop() + } + return h, repo, upstream, router, cleanup +} diff --git a/backend/internal/handler/openai_gateway_credential_failover_test.go b/backend/internal/handler/openai_gateway_credential_failover_test.go new file mode 100644 index 0000000000..07a5e4999f --- /dev/null +++ b/backend/internal/handler/openai_gateway_credential_failover_test.go @@ -0,0 +1,211 @@ +//go:build unit + +package handler + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestGatewayChatCredentialStopDoesNotSelectAnotherAccountAndReturnsSafe503(t *testing.T) { + gin.SetMode(gin.TestMode) + stopErr := &service.UpstreamFailoverError{ + Stage: service.GatewayFailureStageAccountAuth, + Scope: service.GatewayFailureScopeProvider, + Reason: service.GrokCredentialReasonProviderConfig, + NextAccountAction: service.NextAccountStop, + ClientStatusCode: http.StatusTeapot, + ClientMessage: "invalid_client client_secret=must-not-leak", + } + state := NewFailoverState(3, false) + action := state.HandleFailoverError(context.Background(), &mockTempUnscheduler{}, 71, service.PlatformGrok, 0, stopErr) + + require.Equal(t, FailoverExhausted, action) + require.Zero(t, state.SwitchCount) + require.Empty(t, state.FailedAccountIDs) + + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + (&GatewayHandler{}).handleCCFailoverExhausted(c, state.LastFailoverErr, false) + + require.Equal(t, http.StatusServiceUnavailable, recorder.Code) + require.Contains(t, recorder.Body.String(), service.GrokCredentialUnavailableClientMessage) + require.NotContains(t, recorder.Body.String(), "invalid_client") + require.NotContains(t, recorder.Body.String(), "client_secret") +} + +func TestGatewayChatInferenceExhaustionRestoresRetryAfter(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + + (&GatewayHandler{}).handleCCFailoverExhausted(c, &service.UpstreamFailoverError{ + StatusCode: http.StatusTooManyRequests, + ResponseHeaders: http.Header{"Retry-After": []string{"45"}}, + }, false) + + require.Equal(t, http.StatusTooManyRequests, recorder.Code) + require.Equal(t, "45", recorder.Header().Get("Retry-After")) +} + +func TestCredentialFailoverExhaustionReturnsFixedSafe503(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + h := &OpenAIGatewayHandler{} + + h.handleFailoverExhausted(c, &service.UpstreamFailoverError{ + Stage: service.GatewayFailureStageAccountAuth, + Scope: service.GatewayFailureScopeAccount, + Reason: service.GrokCredentialReasonRevoked, + NextAccountAction: service.NextAccountRetry, + ClientStatusCode: http.StatusTeapot, + ClientMessage: "invalid_grant refresh_token=must-not-leak", + }, false) + + require.Equal(t, http.StatusServiceUnavailable, recorder.Code) + require.Contains(t, recorder.Body.String(), service.GrokCredentialUnavailableClientMessage) + require.NotContains(t, strings.ToLower(recorder.Body.String()), "invalid_grant") + require.NotContains(t, strings.ToLower(recorder.Body.String()), "refresh_token") + require.NotContains(t, recorder.Body.String(), "must-not-leak") +} + +func TestInferenceFailoverExhaustionRestoresRetryAfter(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + h := &OpenAIGatewayHandler{} + + h.handleFailoverExhausted(c, &service.UpstreamFailoverError{ + StatusCode: http.StatusTooManyRequests, + ResponseHeaders: http.Header{"Retry-After": []string{"17"}}, + }, false) + + require.Equal(t, http.StatusTooManyRequests, recorder.Code) + require.Equal(t, "17", recorder.Header().Get("Retry-After")) +} + +func TestFailoverExhaustionRejectsSecretBearingRetryAfter(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + h := &OpenAIGatewayHandler{} + + h.handleFailoverExhausted(c, &service.UpstreamFailoverError{ + StatusCode: http.StatusTooManyRequests, + ResponseHeaders: http.Header{"Retry-After": []string{"refresh_token=must-not-leak"}}, + }, false) + + require.Equal(t, http.StatusTooManyRequests, recorder.Code) + require.Empty(t, recorder.Header().Get("Retry-After")) + require.NotContains(t, recorder.Body.String(), "must-not-leak") +} + +func TestFailoverExhaustionRejectsFarFutureRetryAfterDate(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + h := &OpenAIGatewayHandler{} + + h.handleFailoverExhausted(c, &service.UpstreamFailoverError{ + StatusCode: http.StatusTooManyRequests, + ResponseHeaders: http.Header{ + "Retry-After": []string{time.Now().Add(30 * 24 * time.Hour).UTC().Format(http.TimeFormat)}, + }, + }, false) + + require.Equal(t, http.StatusTooManyRequests, recorder.Code) + require.Empty(t, recorder.Header().Get("Retry-After")) +} + +func TestFailoverExhaustionAllowsBoundedRetryAfterDate(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + h := &OpenAIGatewayHandler{} + retryAfter := time.Now().Add(time.Hour).UTC().Format(http.TimeFormat) + + h.handleFailoverExhausted(c, &service.UpstreamFailoverError{ + StatusCode: http.StatusTooManyRequests, + ResponseHeaders: http.Header{"Retry-After": []string{retryAfter}}, + }, false) + + require.Equal(t, http.StatusTooManyRequests, recorder.Code) + require.Equal(t, retryAfter, recorder.Header().Get("Retry-After")) +} + +func TestOpsClassificationTreatsCredentialFailureAsAuthNotInference(t *testing.T) { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Set(service.OpsUpstreamStatusCodeKey, http.StatusForbidden) + c.Set(service.OpsUpstreamErrorMessageKey, "stale inference message") + c.Set(service.OpsUpstreamErrorDetailKey, "stale inference detail") + c.Set(service.OpsUpstreamErrorsKey, []*service.OpsUpstreamErrorEvent{ + {Stage: string(service.GatewayFailureStageInference), UpstreamStatusCode: http.StatusForbidden, Message: "stale inference message", Detail: "stale inference detail"}, + { + Stage: string(service.GatewayFailureStageAccountAuth), + Scope: string(service.GatewayFailureScopeAccount), + Reason: string(service.GrokCredentialReasonRevoked), + UpstreamStatusCode: 0, + Message: "Grok OAuth credentials require account action", + }, + }) + + phase, _, owner, source := classifyOpsErrorLog(c, "upstream_error", service.GrokCredentialUnavailableClientMessage, "", http.StatusServiceUnavailable) + require.Equal(t, "account_auth", phase) + require.Equal(t, "provider", owner) + require.Equal(t, "gateway", source) + + entry := &service.OpsInsertErrorLogInput{} + applyOpsUpstreamFieldsFromContext(c, entry) + require.NotNil(t, entry.UpstreamStatusCode) + require.Zero(t, *entry.UpstreamStatusCode) + require.NotNil(t, entry.UpstreamErrorMessage) + require.Equal(t, "Grok OAuth credentials require account action", *entry.UpstreamErrorMessage) + require.Nil(t, entry.UpstreamErrorDetail) + require.Len(t, entry.UpstreamErrors, 2) + require.Equal(t, http.StatusForbidden, entry.UpstreamErrors[0].UpstreamStatusCode) +} + +func TestOpsRecoveredCredentialFailoverUsesAccountAuthAttribution(t *testing.T) { + setupOpsErrorLogTestQueue(t, 2) + gin.SetMode(gin.TestMode) + ops := service.NewOpsService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + router := gin.New() + router.Use(OpsErrorLoggerMiddleware(ops)) + router.GET("/openai/v1/responses", func(c *gin.Context) { + c.Set(service.OpsUpstreamErrorsKey, []*service.OpsUpstreamErrorEvent{ + {Stage: string(service.GatewayFailureStageInference), UpstreamStatusCode: http.StatusForbidden, Message: "earlier inference failure"}, + { + Stage: string(service.GatewayFailureStageAccountAuth), Scope: string(service.GatewayFailureScopeAccount), + Reason: string(service.GrokCredentialReasonRevoked), Message: "Grok OAuth credentials require account action", + }, + }) + c.JSON(http.StatusOK, gin.H{"ok": true}) + }) + + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/openai/v1/responses", nil)) + + require.Equal(t, http.StatusOK, recorder.Code) + require.Equal(t, int64(1), OpsErrorLogQueueLength()) + job := <-opsErrorLogQueue + require.Equal(t, "account_auth", job.entry.ErrorPhase) + require.Equal(t, "provider", job.entry.ErrorOwner) + require.Equal(t, "gateway", job.entry.ErrorSource) + require.Contains(t, job.entry.ErrorMessage, "Recovered account authentication failure") + require.NotContains(t, job.entry.ErrorMessage, "403") + require.NotContains(t, job.entry.ErrorMessage, "earlier inference failure") + require.NotNil(t, job.entry.UpstreamStatusCode) + require.Zero(t, *job.entry.UpstreamStatusCode) + require.Len(t, job.entry.UpstreamErrors, 2) + require.Equal(t, http.StatusForbidden, job.entry.UpstreamErrors[0].UpstreamStatusCode) +} diff --git a/backend/internal/handler/openai_gateway_first_output_timeout_test.go b/backend/internal/handler/openai_gateway_first_output_timeout_test.go new file mode 100644 index 0000000000..bd7cc7af04 --- /dev/null +++ b/backend/internal/handler/openai_gateway_first_output_timeout_test.go @@ -0,0 +1,51 @@ +package handler + +import ( + "context" + "fmt" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestOpenAIForwardMayFailoverOnlyAfterNonSemanticWrite(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + before := service.OpenAICompactKeepaliveAdjustedWrittenSize(c) + + _, err := fmt.Fprint(c.Writer, ":\n\n") + require.NoError(t, err) + c.Writer.Flush() + + require.True(t, openAIForwardMayFailover(c, before, &service.UpstreamFailoverError{ + SafeToFailoverAfterWrite: true, + })) + require.False(t, openAIForwardMayFailover(c, before, &service.UpstreamFailoverError{})) +} + +func TestOpenAIFirstOutputFailoverStopsAfterOneAccountSwitch(t *testing.T) { + failoverErr := &service.UpstreamFailoverError{SafeToFailoverAfterWrite: true} + count := 0 + + require.False(t, openAIFirstOutputFailoverExhausted(failoverErr, &count)) + require.Equal(t, 1, count) + require.True(t, openAIFirstOutputFailoverExhausted(failoverErr, &count)) + require.Equal(t, 1, count) +} + +func TestOpenAIRequestAllowsFailoverReplayStopsCanceledClient(t *testing.T) { + require.False(t, openAIRequestAllowsFailoverReplay(nil)) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + requestCtx, cancel := context.WithCancel(context.Background()) + c.Request = httptest.NewRequest("POST", "/v1/responses", nil).WithContext(requestCtx) + + require.True(t, openAIRequestAllowsFailoverReplay(c)) + cancel() + require.False(t, openAIRequestAllowsFailoverReplay(c)) +} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 231363a8a3..83c4b4ac23 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -40,6 +40,8 @@ type OpenAIGatewayHandler struct { cfg *config.Config } +const maxOpenAIFirstOutputTimeoutSwitches = 1 + func resolveOpenAIMessagesDispatchMappedModel(apiKey *service.APIKey, requestedModel string) string { if apiKey == nil || apiKey.Group == nil { return "" @@ -56,6 +58,14 @@ func openAIModelMappedBody(body []byte, mapped bool, mappedModel string, replace return replace(body, mappedModel) } +func seedOpenAIForwardImageIntentHint(c *gin.Context, channelMapped bool, imageIntent bool) { + if channelMapped { + // 渠道映射改变了规范请求,保持 unknown,由 Forward 按映射后的 model/body 初始化。 + return + } + service.SetOpenAIImageIntentHint(c, imageIntent) +} + func newOpenAIModelMappedBodyCache(body []byte, replace openAIModelBodyReplaceFunc) func(bool, string) []byte { replacedBodies := make(map[string][]byte) return func(mapped bool, mappedModel string) []byte { @@ -282,6 +292,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { // 解析渠道级模型映射 channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel) forwardBody := openAIModelMappedBody(body, channelMapping.Mapped, channelMapping.MappedModel, h.gatewayService.ReplaceModelInBody) + seedOpenAIForwardImageIntentHint(c, channelMapping.Mapped, imageIntent) // 提前校验 function_call_output 是否具备可关联上下文,避免上游 400。 if !h.validateFunctionCallOutputRequest(c, body, reqLog) { @@ -329,11 +340,19 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { maxAccountSwitches := h.maxAccountSwitches switchCount := 0 + firstOutputTimeoutSwitchCount := 0 failedAccountIDs := make(map[int64]struct{}) sameAccountRetryCount := make(map[int64]int) var lastFailoverErr *service.UpstreamFailoverError + var oauth429FailoverState service.OpenAIOAuth429FailoverState for { + // Streaming Forward intentionally detaches the upstream request so usage can + // be drained after a disconnect. Re-check the client context before every + // account attempt so a canceled request never starts a failover replay. + if !openAIRequestAllowsFailoverReplay(c) { + return + } // Select account supporting the requested model reqLog.Debug("openai.account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs))) selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability( @@ -350,6 +369,10 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { requestPlatform, ) if err != nil { + if failoverClientGone(c) { + reqLog.Info("openai.account_select_aborted_client_disconnected", zap.Error(err)) + return + } reqLog.Warn("openai.account_select_failed", zap.Error(openAICompatibleSelectionErrorForLog(err, requestPlatform)), zap.Int("excluded_account_count", len(failedAccountIDs)), @@ -443,11 +466,31 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { } else { var failoverErr *service.UpstreamFailoverError if errors.As(err, &failoverErr) { - if service.OpenAICompactKeepaliveAdjustedWrittenSize(c) != writerSizeBeforeForward { + if failoverClientGone(c) { + reqLog.Info("openai.failover_aborted_client_disconnected", + zap.Int64("account_id", account.ID), + zap.Int("upstream_status", failoverErr.StatusCode), + ) + return + } + if !openAIForwardMayFailover(c, writerSizeBeforeForward, failoverErr) { h.handleFailoverExhausted(c, failoverErr, true) return } - h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) + if failoverErr.SafeToFailoverAfterWrite && c.Writer.Written() { + streamStarted = true + } + if failoverErr.ShouldReportAccountScheduleFailure() { + h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) + } + if !failoverErr.ShouldRetryNextAccount() { + h.handleFailoverExhausted(c, failoverErr, streamStarted) + return + } + if openAIFirstOutputFailoverExhausted(failoverErr, &firstOutputTimeoutSwitchCount) { + h.handleFailoverExhausted(c, failoverErr, streamStarted) + return + } // 池模式:同账号重试 if failoverErr.RetryableOnSameAccount { retryLimit := account.GetPoolModeRetryCount() @@ -475,16 +518,27 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { return } switchCount++ - if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) { + if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) { h.handleFailoverExhausted(c, failoverErr, streamStarted) return } - reqLog.Warn("openai.upstream_failover_switching", + failoverSwitchFields := []zap.Field{ zap.Int64("account_id", account.ID), zap.Int("upstream_status", failoverErr.StatusCode), zap.Int("switch_count", switchCount), zap.Int("max_switches", maxAccountSwitches), - ) + } + if account.Proxy != nil { + failoverSwitchFields = append(failoverSwitchFields, + zap.Int64("proxy_id", account.Proxy.ID), + zap.String("proxy_name", account.Proxy.Name), + zap.String("proxy_host", account.Proxy.Host), + zap.Int("proxy_port", account.Proxy.Port), + ) + } else if account.ProxyID != nil { + failoverSwitchFields = append(failoverSwitchFields, zap.Int64p("proxy_id", account.ProxyID)) + } + reqLog.Warn("openai.upstream_failover_switching", failoverSwitchFields...) continue } h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) @@ -832,9 +886,13 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { failedAccountIDs := make(map[int64]struct{}) sameAccountRetryCount := make(map[int64]int) var lastFailoverErr *service.UpstreamFailoverError + var oauth429FailoverState service.OpenAIOAuth429FailoverState effectiveMappedModel := preferredMappedModel for { + if failoverClientGone(c) { + return + } currentRoutingModel := routingModel if effectiveMappedModel != "" { currentRoutingModel = effectiveMappedModel @@ -854,6 +912,10 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { requestPlatform, ) if err != nil { + if failoverClientGone(c) { + reqLog.Info("openai_messages.account_select_aborted_client_disconnected", zap.Error(err)) + return + } reqLog.Warn("openai_messages.account_select_failed", zap.Error(openAICompatibleSelectionErrorForLog(err, requestPlatform)), zap.Int("excluded_account_count", len(failedAccountIDs)), @@ -935,11 +997,24 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { } else { var failoverErr *service.UpstreamFailoverError if errors.As(err, &failoverErr) { + if failoverClientGone(c) { + reqLog.Info("openai_messages.failover_aborted_client_disconnected", + zap.Int64("account_id", account.ID), + zap.Int("upstream_status", failoverErr.StatusCode), + ) + return + } if c.Writer.Size() != writerSizeBeforeForward { h.handleAnthropicFailoverExhausted(c, failoverErr, true) return } - h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) + if failoverErr.ShouldReportAccountScheduleFailure() { + h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) + } + if !failoverErr.ShouldRetryNextAccount() { + h.handleAnthropicFailoverExhausted(c, failoverErr, streamStarted) + return + } // 池模式:同账号重试 if failoverErr.RetryableOnSameAccount { retryLimit := account.GetPoolModeRetryCount() @@ -967,7 +1042,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { return } switchCount++ - if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) { + if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) { h.handleAnthropicFailoverExhausted(c, failoverErr, streamStarted) return } @@ -1093,6 +1168,14 @@ func (h *OpenAIGatewayHandler) anthropicStreamingAwareError(c *gin.Context, stat // handleAnthropicFailoverExhausted maps upstream failover errors to Anthropic format. func (h *OpenAIGatewayHandler) handleAnthropicFailoverExhausted(c *gin.Context, failoverErr *service.UpstreamFailoverError, streamStarted bool) { + if failoverErr != nil { + copyFailoverRetryAfter(c, failoverErr.ResponseHeaders) + } + if failoverErr != nil && failoverErr.IsCredentialFailure() { + status, message := credentialFailoverClientResponse(failoverErr) + h.anthropicStreamingAwareError(c, status, "api_error", message, streamStarted) + return + } status, errType, errMsg := h.mapUpstreamError(failoverErr.StatusCode) h.anthropicStreamingAwareError(c, status, errType, errMsg, streamStarted) } @@ -1320,7 +1403,8 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { c.Request = c.Request.WithContext(ctx) } - readCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + firstMessageTimeout := service.ResolveOpenAIWSClientFirstMessageTimeout(h.cfg) + readCtx, cancel := context.WithTimeout(ctx, firstMessageTimeout) msgType, firstMessage, err := wsConn.Read(readCtx) cancel() if err != nil { @@ -1335,7 +1419,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { zap.String("client_ip", clientIP), zap.String("close_status", closeStatus), zap.String("close_reason", closeReason), - zap.Duration("read_timeout", 30*time.Second), + zap.Duration("read_timeout", firstMessageTimeout), ) closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "missing first response.create message") return @@ -1464,8 +1548,50 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { switchCount := 0 failedAccountIDs := make(map[int64]struct{}) var lastFailoverErr *service.UpstreamFailoverError + var oauth429FailoverState service.OpenAIOAuth429FailoverState + handleWSFailover := func(account *service.Account, failoverErr *service.UpstreamFailoverError) bool { + if ctx.Err() != nil { + return false + } + if failoverErr.ShouldReportAccountScheduleFailure() { + h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) + } + releaseAccountSlot() + if !failoverErr.ShouldRetryNextAccount() { + closeOpenAIWSFailoverExhausted(wsConn, failoverErr) + return false + } + if ctx.Err() != nil { + return false + } + h.gatewayService.RecordOpenAIAccountSwitch() + failedAccountIDs[account.ID] = struct{}{} + lastFailoverErr = failoverErr + if switchCount >= maxAccountSwitches { + closeOpenAIWSFailoverExhausted(wsConn, failoverErr) + return false + } + switchCount++ + if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) { + closeOpenAIWSFailoverExhausted(wsConn, failoverErr) + return false + } + reqLog.Warn("openai.websocket_upstream_failover_switching", + zap.Int64("account_id", account.ID), + zap.Int("upstream_status", failoverErr.StatusCode), + zap.Int("switch_count", switchCount), + zap.Int("max_switches", maxAccountSwitches), + ) + if ctx.Err() != nil { + return false + } + return ensureUserSlotHeld() + } for { + if ctx.Err() != nil { + return + } reqLog.Debug("openai.websocket_account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs))) selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability( ctx, @@ -1533,9 +1659,19 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { reqLog.Warn("openai.websocket_bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(err)) } - token, _, err := h.gatewayService.GetAccessToken(ctx, account) + token, _, err := h.gatewayService.GetRequestCredential(ctx, c, account) if err != nil { reqLog.Warn("openai.websocket_get_access_token_failed", zap.Int64("account_id", account.ID), zap.Error(err)) + if ctx.Err() != nil { + return + } + var failoverErr *service.UpstreamFailoverError + if errors.As(err, &failoverErr) { + if handleWSFailover(account, failoverErr) { + continue + } + return + } closeOpenAIClientWS(wsConn, coderws.StatusInternalError, "failed to get access token") return } @@ -1692,30 +1828,10 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { if err := h.gatewayService.ProxyResponsesWebSocketFromClient(ctx, c, wsConn, account, token, wsFirstMessage, hooks); err != nil { var failoverErr *service.UpstreamFailoverError if errors.As(err, &failoverErr) { - h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) - releaseAccountSlot() - failedAccountIDs[account.ID] = struct{}{} - lastFailoverErr = failoverErr - if switchCount >= maxAccountSwitches { - closeOpenAIWSFailoverExhausted(wsConn, failoverErr) - return + if handleWSFailover(account, failoverErr) { + continue } - switchCount++ - if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) { - closeOpenAIWSFailoverExhausted(wsConn, failoverErr) - return - } - h.gatewayService.RecordOpenAIAccountSwitch() - reqLog.Warn("openai.websocket_upstream_failover_switching", - zap.Int64("account_id", account.ID), - zap.Int("upstream_status", failoverErr.StatusCode), - zap.Int("switch_count", switchCount), - zap.Int("max_switches", maxAccountSwitches), - ) - if !ensureUserSlotHeld() { - return - } - continue + return } if errors.Is(context.Cause(ctx), service.ErrOpenAIWSIngressLeaseLost) { @@ -1739,12 +1855,23 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) closeStatus, closeReason := summarizeWSCloseErrorForLog(err) - reqLog.Warn("openai.websocket_proxy_failed", + proxyFailedFields := []zap.Field{ zap.Int64("account_id", account.ID), zap.Error(err), zap.String("close_status", closeStatus), zap.String("close_reason", closeReason), - ) + } + if account.Proxy != nil { + proxyFailedFields = append(proxyFailedFields, + zap.Int64("proxy_id", account.Proxy.ID), + zap.String("proxy_name", account.Proxy.Name), + zap.String("proxy_host", account.Proxy.Host), + zap.Int("proxy_port", account.Proxy.Port), + ) + } else if account.ProxyID != nil { + proxyFailedFields = append(proxyFailedFields, zap.Int64p("proxy_id", account.ProxyID)) + } + reqLog.Warn("openai.websocket_proxy_failed", proxyFailedFields...) if errors.As(err, &closeErr) { closeOpenAIClientWS(wsConn, closeErr.StatusCode(), closeErr.Reason()) return @@ -1946,6 +2073,16 @@ func (h *OpenAIGatewayHandler) handleConcurrencyError(c *gin.Context, err error, } func (h *OpenAIGatewayHandler) handleFailoverExhausted(c *gin.Context, failoverErr *service.UpstreamFailoverError, streamStarted bool) { + if failoverErr == nil { + h.handleFailoverExhaustedSimple(c, http.StatusBadGateway, streamStarted) + return + } + copyFailoverRetryAfter(c, failoverErr.ResponseHeaders) + if failoverErr.IsCredentialFailure() { + status, message := credentialFailoverClientResponse(failoverErr) + h.handleStreamingAwareError(c, status, "upstream_error", message, streamStarted) + return + } statusCode := failoverErr.StatusCode responseBody := failoverErr.ResponseBody if service.IsOpenAISilentRefusalErrorBody(responseBody) { @@ -1987,6 +2124,41 @@ func (h *OpenAIGatewayHandler) handleFailoverExhausted(c *gin.Context, failoverE h.handleStreamingAwareError(c, status, errType, errMsg, streamStarted) } +func credentialFailoverClientResponse(failoverErr *service.UpstreamFailoverError) (int, string) { + _ = failoverErr + return http.StatusServiceUnavailable, service.GrokCredentialUnavailableClientMessage +} + +func copyFailoverRetryAfter(c *gin.Context, headers http.Header) { + if c == nil || headers == nil { + return + } + retryAfter := strings.TrimSpace(headers.Get("Retry-After")) + if retryAfter == "" || len(retryAfter) > 128 || strings.ContainsAny(retryAfter, "\r\n") || !isSafeRetryAfter(retryAfter) { + return + } + c.Header("Retry-After", retryAfter) +} + +func isSafeRetryAfter(value string) bool { + digitsOnly := true + for _, char := range value { + if char < '0' || char > '9' { + digitsOnly = false + break + } + } + if digitsOnly { + seconds, err := strconv.ParseUint(value, 10, 32) + return err == nil && seconds <= uint64((7*24*time.Hour)/time.Second) + } + retryAt, err := http.ParseTime(value) + if err != nil { + return false + } + return !retryAt.After(time.Now().Add(7 * 24 * time.Hour)) +} + // handleFailoverExhaustedSimple 简化版本,用于没有响应体的情况 func (h *OpenAIGatewayHandler) handleFailoverExhaustedSimple(c *gin.Context, statusCode int, streamStarted bool) { status, errType, errMsg := h.mapUpstreamError(statusCode) @@ -2051,13 +2223,23 @@ func (h *OpenAIGatewayHandler) ensureForwardErrorResponse(c *gin.Context, stream return false } // 先停 compact 心跳再读 Writer 状态,避免与心跳 goroutine 竞争。 - if service.StopOpenAICompactSSEKeepaliveCommitted(c) { + compactKeepaliveCommitted := service.StopOpenAICompactSSEKeepaliveCommitted(c) + if compactKeepaliveCommitted { streamStarted = true } - if service.IsResponseCommitted(c) { + imageKeepalivePresent := service.OpenAIImagesJSONKeepalivePresent(c) + service.StopOpenAIImagesJSONKeepaliveCommitted(c) + imageKeepalivePaddingOnly := false + imageKeepaliveResponseWritten := false + if imageKeepalivePresent { + adjustedSize := service.OpenAIImagesJSONKeepaliveAdjustedWrittenSize(c) + imageKeepalivePaddingOnly = adjustedSize < 0 + imageKeepaliveResponseWritten = adjustedSize >= 0 + } + if service.IsResponseCommitted(c) || (!compactKeepaliveCommitted && imageKeepaliveResponseWritten) { return false } - if c.Writer.Written() { + if c.Writer.Written() && !imageKeepalivePaddingOnly { streamStarted = true } h.handleStreamingAwareError(c, http.StatusBadGateway, "upstream_error", "Upstream request failed", streamStarted) @@ -2116,6 +2298,34 @@ func openAIForwardErrorAlreadyCommunicated(c *gin.Context, writerSizeBeforeForwa return false } +func openAIForwardMayFailover(c *gin.Context, writerSizeBeforeForward int, failoverErr *service.UpstreamFailoverError) bool { + if c == nil || c.Writer == nil { + return false + } + if service.OpenAICompactKeepaliveAdjustedWrittenSize(c) == writerSizeBeforeForward { + return true + } + return failoverErr != nil && failoverErr.SafeToFailoverAfterWrite +} + +func openAIRequestAllowsFailoverReplay(c *gin.Context) bool { + if c == nil || c.Request == nil { + return false + } + return !failoverClientGone(c) +} + +func openAIFirstOutputFailoverExhausted(failoverErr *service.UpstreamFailoverError, switchCount *int) bool { + if failoverErr == nil || !failoverErr.SafeToFailoverAfterWrite || switchCount == nil { + return false + } + if *switchCount >= maxOpenAIFirstOutputTimeoutSwitches { + return true + } + *switchCount = *switchCount + 1 + return false +} + // errorResponse returns OpenAI API format error response func (h *OpenAIGatewayHandler) errorResponse(c *gin.Context, status int, errType, message string) { // body-signal compact 心跳可能已把响应头提交为 200:JSON 错误体会与已 @@ -2194,6 +2404,10 @@ func closeOpenAIWSFailoverExhausted(conn *coderws.Conn, failoverErr *service.Ups closeOpenAIClientWS(conn, coderws.StatusInternalError, "upstream websocket proxy failed") return } + if failoverErr.Stage == service.GatewayFailureStageAccountAuth { + closeOpenAIClientWS(conn, coderws.StatusTryAgainLater, service.GrokCredentialUnavailableClientMessage) + return + } switch failoverErr.StatusCode { case http.StatusTooManyRequests: closeOpenAIClientWS(conn, coderws.StatusTryAgainLater, "upstream rate limit exceeded, please retry later") diff --git a/backend/internal/handler/openai_gateway_handler_test.go b/backend/internal/handler/openai_gateway_handler_test.go index e4b594c0b8..d855f364a7 100644 --- a/backend/internal/handler/openai_gateway_handler_test.go +++ b/backend/internal/handler/openai_gateway_handler_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "io" "net/http" "net/http/httptest" "strings" @@ -220,6 +221,97 @@ func TestOpenAIEnsureForwardErrorResponse_ResponsesRouteAfterWrittenEmitsRespons assert.Contains(t, body, "Upstream request failed") } +func TestOpenAIEnsureForwardErrorResponse_ImageJSONKeepaliveWritesSingleJSONFallback(t *testing.T) { + gin.SetMode(gin.TestMode) + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", nil) + + stop := service.StartOpenAIImagesJSONKeepalive(c, 5*time.Millisecond) + defer stop() + before := service.OpenAIImagesJSONKeepaliveAdjustedWrittenSize(c) + require.Eventually(t, c.Writer.Written, time.Second, time.Millisecond) + require.Equal(t, before, service.OpenAIImagesJSONKeepaliveAdjustedWrittenSize(c)) + require.False(t, openAIForwardErrorAlreadyCommunicated(c, before, errors.New("read upstream response: unexpected EOF"))) + + h := &OpenAIGatewayHandler{} + wrote := h.ensureForwardErrorResponse(c, false) + + require.True(t, wrote) + require.Equal(t, http.StatusOK, w.Code, "heartbeat already committed the status") + require.True(t, json.Valid(w.Body.Bytes()), w.Body.String()) + require.NotContains(t, w.Body.String(), "event:") + require.NotContains(t, w.Body.String(), "data:") + + decoder := json.NewDecoder(strings.NewReader(w.Body.String())) + var payload map[string]any + require.NoError(t, decoder.Decode(&payload)) + require.ErrorIs(t, decoder.Decode(&payload), io.EOF) + require.Equal(t, "upstream_error", gjson.Get(w.Body.String(), "error.type").String()) + require.Equal(t, "Upstream request failed", gjson.Get(w.Body.String(), "error.message").String()) +} + +func TestOpenAIEnsureForwardErrorResponse_ImageJSONKeepalivePreservesCompletedJSON(t *testing.T) { + gin.SetMode(gin.TestMode) + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", nil) + + stop := service.StartOpenAIImagesJSONKeepalive(c, 5*time.Millisecond) + defer stop() + before := service.OpenAIImagesJSONKeepaliveAdjustedWrittenSize(c) + require.Eventually(t, c.Writer.Written, time.Second, time.Millisecond) + c.JSON(http.StatusOK, gin.H{"data": []gin.H{{"b64_json": "aW1hZ2U="}}}) + completedBody := w.Body.String() + require.True(t, json.Valid([]byte(completedBody)), completedBody) + require.Greater(t, service.OpenAIImagesJSONKeepaliveAdjustedWrittenSize(c), before) + require.False(t, openAIForwardErrorAlreadyCommunicated(c, before, errors.New("read upstream trailer: unexpected EOF"))) + + h := &OpenAIGatewayHandler{} + wrote := h.ensureForwardErrorResponse(c, false) + + require.False(t, wrote, "the completed Images JSON already communicated the response") + require.Equal(t, completedBody, w.Body.String()) + require.NotContains(t, w.Body.String(), "event:") + require.NotContains(t, w.Body.String(), "data:") + + decoder := json.NewDecoder(strings.NewReader(w.Body.String())) + var payload map[string]any + require.NoError(t, decoder.Decode(&payload)) + require.ErrorIs(t, decoder.Decode(&payload), io.EOF) + require.Equal(t, "aW1hZ2U=", gjson.Get(w.Body.String(), "data.0.b64_json").String()) +} + +func TestOpenAIEnsureForwardErrorResponse_FastImageJSONKeepalivePreservesCompletedJSON(t *testing.T) { + gin.SetMode(gin.TestMode) + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", nil) + + stop := service.StartOpenAIImagesJSONKeepalive(c, time.Hour) + defer stop() + before := service.OpenAIImagesJSONKeepaliveAdjustedWrittenSize(c) + c.JSON(http.StatusOK, gin.H{"data": []gin.H{{"b64_json": "ZmFzdC1pbWFnZQ=="}}}) + completedBody := w.Body.String() + require.True(t, json.Valid([]byte(completedBody)), completedBody) + require.Greater(t, service.OpenAIImagesJSONKeepaliveAdjustedWrittenSize(c), before) + require.False(t, openAIForwardErrorAlreadyCommunicated(c, before, errors.New("read upstream trailer: unexpected EOF"))) + + h := &OpenAIGatewayHandler{} + wrote := h.ensureForwardErrorResponse(c, false) + + require.False(t, wrote, "fast completed Images JSON already communicated the response") + require.Equal(t, completedBody, w.Body.String()) + require.NotContains(t, w.Body.String(), "event:") + require.NotContains(t, w.Body.String(), "data:") + + decoder := json.NewDecoder(strings.NewReader(w.Body.String())) + var payload map[string]any + require.NoError(t, decoder.Decode(&payload)) + require.ErrorIs(t, decoder.Decode(&payload), io.EOF) + require.Equal(t, "ZmFzdC1pbWFnZQ==", gjson.Get(w.Body.String(), "data.0.b64_json").String()) +} + func TestShouldLogOpenAIForwardFailureAsWarn(t *testing.T) { gin.SetMode(gin.TestMode) @@ -741,6 +833,40 @@ func TestOpenAIResponsesWebSocket_IngressCapacityRejected(t *testing.T) { require.Equal(t, coderws.StatusTryAgainLater, closeErr.Code) } +func TestOpenAIResponsesWebSocket_FirstMessageTimeoutUsesConfig(t *testing.T) { + gin.SetMode(gin.TestMode) + logSink, restore := captureHandlerStructuredLog(t) + defer restore() + + h := newOpenAIHandlerForPreviousResponseIDValidation(t, nil) + h.cfg = &config.Config{} + h.cfg.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds = 1 + wsServer := newOpenAIWSHandlerTestServer(t, h, middleware.AuthSubject{UserID: 1, Concurrency: 1}) + defer wsServer.Close() + + dialCtx, cancelDial := context.WithTimeout(context.Background(), 3*time.Second) + clientConn, _, err := coderws.Dial(dialCtx, "ws"+strings.TrimPrefix(wsServer.URL, "http")+"/openai/v1/responses", nil) + cancelDial() + require.NoError(t, err) + defer func() { _ = clientConn.CloseNow() }() + + started := time.Now() + readCtx, cancelRead := context.WithTimeout(context.Background(), 5*time.Second) + _, _, err = clientConn.Read(readCtx) + cancelRead() + elapsed := time.Since(started) + + require.Error(t, err) + require.NotErrorIs(t, err, context.DeadlineExceeded) + require.GreaterOrEqual(t, elapsed, 500*time.Millisecond) + require.Less(t, elapsed, 4*time.Second) + require.Eventually(t, func() bool { + readTimeout, ok := logSink.FieldValueForMessage("openai.websocket_read_first_message_failed", "read_timeout") + return ok && readTimeout == time.Second && + logSink.ContainsMessageAtLevel("openai.websocket_read_first_message_failed", "warn") + }, time.Second, 10*time.Millisecond) +} + func TestOpenAIResponsesWebSocket_IngressLeaseReleasedOnEarlyReturn(t *testing.T) { gin.SetMode(gin.TestMode) cache := &concurrencyCacheMock{ @@ -1272,6 +1398,29 @@ type openAIWSFailoverHandlerAccountRepoStub struct { rateLimitedIDs []int64 } +type openAIHTTPPassthroughFailoverUpstream struct { + service.HTTPUpstream + mu sync.Mutex + accountIDs []int64 +} + +func (u *openAIHTTPPassthroughFailoverUpstream) Do(_ *http.Request, _ string, accountID int64, _ int) (*http.Response, error) { + u.mu.Lock() + u.accountIDs = append(u.accountIDs, accountID) + u.mu.Unlock() + return &http.Response{ + StatusCode: http.StatusBadGateway, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"temporary upstream failure"}}`)), + }, nil +} + +func (u *openAIHTTPPassthroughFailoverUpstream) calls() []int64 { + u.mu.Lock() + defer u.mu.Unlock() + return append([]int64(nil), u.accountIDs...) +} + func (s *openAIWSFailoverHandlerAccountRepoStub) ListSchedulableByPlatform(ctx context.Context, platform string) ([]service.Account, error) { out := make([]service.Account, 0, len(s.accounts)) for _, account := range s.accounts { @@ -1344,6 +1493,96 @@ func (s *openAIWSUsageHandlerChannelRepoStub) GetGroupPlatforms(ctx context.Cont return out, nil } +func TestOpenAIResponses_APIKeyPassthroughPool5xxRetriesThenExhaustsMaxSwitches(t *testing.T) { + gin.SetMode(gin.TestMode) + groupID := int64(4203) + accounts := []service.Account{ + { + ID: 9910, Name: "pool-api-key", Platform: service.PlatformOpenAI, + Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, Priority: 1, + Credentials: map[string]any{ + "api_key": "sk-pool", + "base_url": "https://api.example.test", + "pool_mode": true, + "pool_mode_retry_count": float64(1), + "pool_mode_retry_status_codes": []any{float64(http.StatusBadGateway)}, + }, + Extra: map[string]any{"openai_passthrough": true}, + }, + { + ID: 9911, Name: "fallback-api-key", Platform: service.PlatformOpenAI, + Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, Priority: 2, + Credentials: map[string]any{ + "api_key": "sk-fallback", + "base_url": "https://api.example.test", + }, + Extra: map[string]any{"openai_passthrough": true}, + }, + } + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Default.RateMultiplier = 1 + cfg.Security.URLAllowlist.Enabled = false + cfg.Gateway.MaxAccountSwitches = 1 + + accountRepo := &openAIWSFailoverHandlerAccountRepoStub{accounts: accounts} + upstream := &openAIHTTPPassthroughFailoverUpstream{} + billingCacheSvc := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCacheSvc.Stop) + gatewaySvc := service.NewOpenAIGatewayService( + accountRepo, + nil, + nil, + nil, + nil, + nil, + nil, + cfg, + nil, + nil, + service.NewBillingService(cfg, nil), + nil, + billingCacheSvc, + upstream, + &service.DeferredService{}, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + ) + h := NewOpenAIGatewayHandler( + gatewaySvc, + service.NewConcurrencyService(nil), + billingCacheSvc, + service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg), + nil, + nil, + nil, + nil, + cfg, + ) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/responses", strings.NewReader(`{"model":"gpt-5.2","input":"hello","stream":false}`)) + c.Request.Header.Set("Content-Type", "application/json") + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ + ID: 1803, GroupID: &groupID, + User: &service.User{ID: 1703, Status: service.StatusActive}, + Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive}, + }) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 1703, Concurrency: 0}) + + h.Responses(c) + + require.Equal(t, []int64{9910, 9910, 9911}, upstream.calls()) + require.Equal(t, http.StatusBadGateway, rec.Code) + require.Equal(t, "upstream_error", gjson.GetBytes(rec.Body.Bytes(), "error.type").String()) + require.Equal(t, "Upstream service temporarily unavailable", gjson.GetBytes(rec.Body.Bytes(), "error.message").String()) +} + func TestOpenAIResponsesWebSocket_FailoverOnUpstreamUsageLimitEvent(t *testing.T) { gin.SetMode(gin.TestMode) diff --git a/backend/internal/handler/openai_image_intent_hint_test.go b/backend/internal/handler/openai_image_intent_hint_test.go new file mode 100644 index 0000000000..b9b6c6e2d6 --- /dev/null +++ b/backend/internal/handler/openai_image_intent_hint_test.go @@ -0,0 +1,44 @@ +package handler + +import ( + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestSeedOpenAIForwardImageIntentHint(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + channelMapped bool + imageIntent bool + wantHint bool + }{ + {name: "seed true", imageIntent: true, wantHint: true}, + {name: "seed false", imageIntent: false, wantHint: true}, + {name: "mapped body stays unknown", channelMapped: true, imageIntent: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := &gin.Context{} + service.SetOpenAIClientTransport(c, service.OpenAIClientTransportHTTP) + + seedOpenAIForwardImageIntentHint(c, tt.channelMapped, tt.imageIntent) + + var hintValues []bool + for _, value := range c.Keys { + if hint, ok := value.(bool); ok { + hintValues = append(hintValues, hint) + } + } + if !tt.wantHint { + require.Empty(t, hintValues) + return + } + require.Equal(t, []bool{tt.imageIntent}, hintValues) + }) + } +} diff --git a/backend/internal/handler/openai_images.go b/backend/internal/handler/openai_images.go index c5982fb7d1..f5709225d1 100644 --- a/backend/internal/handler/openai_images.go +++ b/backend/internal/handler/openai_images.go @@ -145,6 +145,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { stopJSONKeepalive := func() {} jsonKeepaliveStarted := false defer func() { stopJSONKeepalive() }() + var oauth429FailoverState service.OpenAIOAuth429FailoverState for { reqLog.Debug("openai.images.account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs))) @@ -157,6 +158,10 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { parsed.RequiredCapability, ) if err != nil { + if failoverClientGone(c) { + reqLog.Info("openai.images.account_select_aborted_client_disconnected", zap.Error(err)) + return + } reqLog.Warn("openai.images.account_select_failed", zap.Error(err), zap.Int("excluded_account_count", len(failedAccountIDs)), @@ -273,6 +278,13 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { h.handleFailoverExhausted(c, failoverErr, true) return } + if failoverClientGone(c) { + reqLog.Info("openai.images.failover_aborted_client_disconnected", + zap.Int64("account_id", account.ID), + zap.Int("upstream_status", failoverErr.StatusCode), + ) + return + } if failoverErr.RetryableOnSameAccount { retryLimit := account.GetPoolModeRetryCount() if sameAccountRetryCount[account.ID] < retryLimit { @@ -299,7 +311,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { return } switchCount++ - if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) { + if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) { h.handleFailoverExhausted(c, failoverErr, streamStarted) return } diff --git a/backend/internal/handler/openai_responses_failover_cancel_test.go b/backend/internal/handler/openai_responses_failover_cancel_test.go new file mode 100644 index 0000000000..0d806e19d0 --- /dev/null +++ b/backend/internal/handler/openai_responses_failover_cancel_test.go @@ -0,0 +1,194 @@ +//go:build unit + +package handler + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "sync" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// openAIResponsesFailoverCancelUpstream 固定返回 HTTP 520,可在首次上游调用时 +// 触发回调(用于模拟“上游在途期间客户端断开”)。 +type openAIResponsesFailoverCancelUpstream struct { + service.HTTPUpstream + mu sync.Mutex + accountIDs []int64 + onFirstDo func() +} + +func (u *openAIResponsesFailoverCancelUpstream) Do(_ *http.Request, _ string, accountID int64, _ int) (*http.Response, error) { + u.mu.Lock() + u.accountIDs = append(u.accountIDs, accountID) + first := len(u.accountIDs) == 1 + u.mu.Unlock() + if first && u.onFirstDo != nil { + u.onFirstDo() + } + return &http.Response{ + StatusCode: 520, + Header: http.Header{"Content-Type": []string{"text/html"}}, + Body: io.NopCloser(bytes.NewBufferString("520: unknown error")), + }, nil +} + +func (u *openAIResponsesFailoverCancelUpstream) calls() []int64 { + u.mu.Lock() + defer u.mu.Unlock() + return append([]int64(nil), u.accountIDs...) +} + +func newOpenAIResponsesFailoverTestHandler(t *testing.T, upstream service.HTTPUpstream) *OpenAIGatewayHandler { + t.Helper() + accounts := []service.Account{ + { + ID: 1, + Name: "responses-account-1", + Platform: service.PlatformOpenAI, + Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Schedulable: true, + Concurrency: 0, + Priority: 0, + Credentials: map[string]any{"access_token": "token-1"}, + }, + { + ID: 2, + Name: "responses-account-2", + Platform: service.PlatformOpenAI, + Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Schedulable: true, + Concurrency: 0, + Priority: 1, + Credentials: map[string]any{"access_token": "token-2"}, + }, + } + accountRepo := openAIImagesFailoverAccountRepo{accounts: accounts} + cfg := &config.Config{RunMode: config.RunModeSimple} + gatewayService := service.NewOpenAIGatewayService( + accountRepo, + nil, + nil, + nil, + nil, + nil, + nil, + cfg, + nil, + nil, + nil, + nil, + nil, + upstream, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + nil, + ) + billingService := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingService.Stop) + concurrencyService := service.NewConcurrencyService(nil) + handler := NewOpenAIGatewayHandler( + gatewayService, + concurrencyService, + billingService, + service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg), + nil, + nil, + nil, + nil, + cfg, + ) + handler.maxAccountSwitches = 10 + return handler +} + +func newOpenAIResponsesFailoverTestContext(t *testing.T, ctx context.Context) (*gin.Context, *httptest.ResponseRecorder) { + t.Helper() + groupID := int64(3131) + body := []byte(`{"model":"gpt-5.1","stream":false,"input":"hello"}`) + req := httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + if ctx != nil { + req = req.WithContext(ctx) + } + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = req + c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{ + ID: 99, + GroupID: &groupID, + Group: &service.Group{ + ID: groupID, + Platform: service.PlatformOpenAI, + }, + User: &service.User{ID: 100}, + }) + c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 100, Concurrency: 0}) + return c, rec +} + +// TestOpenAIGatewayHandlerResponses_FailoverAbortsWhenClientDisconnected 复现 +// #4257:客户端在上游请求在途期间断开,上游随后返回可 failover 的 520。 +// 期望:不再用已取消的 context 重新选号(不触达账号 2)、不把取消误报成 +// 502 账号耗尽、请求按 499 归类。 +func TestOpenAIGatewayHandlerResponses_FailoverAbortsWhenClientDisconnected(t *testing.T) { + gin.SetMode(gin.TestMode) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + upstream := &openAIResponsesFailoverCancelUpstream{onFirstDo: cancel} + handler := newOpenAIResponsesFailoverTestHandler(t, upstream) + c, rec := newOpenAIResponsesFailoverTestContext(t, ctx) + + handler.Responses(c) + + require.Equal(t, []int64{1}, upstream.calls(), "客户端断开后不应再切换到账号 2") + require.Equal(t, statusClientClosedRequest, c.Writer.Status(), "应按 499 归类") + require.Zero(t, rec.Body.Len(), "不应写入 502 错误响应体") + + _, hasFinalUpstreamErr := c.Get(service.OpsUpstreamStatusCodeKey) + require.False(t, hasFinalUpstreamErr, "不应记录 failover 耗尽的上游错误终态") + + // 真实发生过的 520 应保留 failover 事件(service 层在返回 failover 错误前记录) + rawEvents, ok := c.Get(service.OpsUpstreamErrorsKey) + require.True(t, ok) + events, ok := rawEvents.([]*service.OpsUpstreamErrorEvent) + require.True(t, ok) + require.Len(t, events, 1) + require.Equal(t, "failover", events[0].Kind) + require.Equal(t, 520, events[0].UpstreamStatusCode) +} + +// TestOpenAIGatewayHandlerResponses_FailoverContinuesForConnectedClient 回归 +// 守卫:客户端在线时 failover 行为不变——切换到账号 2,两个账号都 520 后按 +// 耗尽返回 502。 +func TestOpenAIGatewayHandlerResponses_FailoverContinuesForConnectedClient(t *testing.T) { + gin.SetMode(gin.TestMode) + + upstream := &openAIResponsesFailoverCancelUpstream{} + handler := newOpenAIResponsesFailoverTestHandler(t, upstream) + c, rec := newOpenAIResponsesFailoverTestContext(t, nil) + + handler.Responses(c) + + require.Equal(t, []int64{1, 2}, upstream.calls(), "在线客户端应正常切换账号") + require.Equal(t, http.StatusBadGateway, rec.Code) + require.Equal(t, "upstream_error", gjson.GetBytes(rec.Body.Bytes(), "error.type").String()) +} diff --git a/backend/internal/handler/ops_error_logger.go b/backend/internal/handler/ops_error_logger.go index 64aa3ba495..f32ca9c054 100644 --- a/backend/internal/handler/ops_error_logger.go +++ b/backend/internal/handler/ops_error_logger.go @@ -721,10 +721,15 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { var upstreamStatusCode *int var upstreamErrorMessage *string var upstreamErrorDetail *string + finalAccountAuth := false if len(events) > 0 { last := events[len(events)-1] if last != nil { - if last.UpstreamStatusCode > 0 { + finalAccountAuth = last.Stage == string(service.GatewayFailureStageAccountAuth) + if finalAccountAuth { + code := 0 + upstreamStatusCode = &code + } else if last.UpstreamStatusCode > 0 { code := last.UpstreamStatusCode upstreamStatusCode = &code } @@ -737,7 +742,7 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { } } - if upstreamStatusCode == nil { + if !finalAccountAuth && upstreamStatusCode == nil { if v, ok := c.Get(service.OpsUpstreamStatusCodeKey); ok { switch t := v.(type) { case int: @@ -753,7 +758,7 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { } } } - if upstreamErrorMessage == nil { + if !finalAccountAuth && upstreamErrorMessage == nil { if v, ok := c.Get(service.OpsUpstreamErrorMessageKey); ok { if s, ok := v.(string); ok && strings.TrimSpace(s) != "" { msg := strings.TrimSpace(s) @@ -761,7 +766,7 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { } } } - if upstreamErrorDetail == nil { + if !finalAccountAuth && upstreamErrorDetail == nil { if v, ok := c.Get(service.OpsUpstreamErrorDetailKey); ok { if s, ok := v.(string); ok && strings.TrimSpace(s) != "" { detail := strings.TrimSpace(s) @@ -781,13 +786,18 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { } recoveredMsg := "Recovered upstream error" - if effectiveUpstreamStatus > 0 { + if finalAccountAuth { + recoveredMsg = "Recovered account authentication failure" + } else if effectiveUpstreamStatus > 0 { recoveredMsg += " " + strconvItoa(effectiveUpstreamStatus) } if upstreamErrorMessage != nil && strings.TrimSpace(*upstreamErrorMessage) != "" { recoveredMsg += ": " + strings.TrimSpace(*upstreamErrorMessage) } recoveredMsg = truncateString(recoveredMsg, 2048) + recoveredPhase, recoveredBusinessLimited, recoveredOwner, recoveredSource := classifyOpsErrorLog( + c, "upstream_error", recoveredMsg, "", effectiveUpstreamStatus, + ) entry := &service.OpsInsertErrorLogInput{ RequestID: requestID, @@ -828,19 +838,19 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { }(), UserAgent: c.GetHeader("User-Agent"), - ErrorPhase: "upstream", + ErrorPhase: recoveredPhase, ErrorType: "upstream_error", // Severity should reflect the upstream failure, not the final client status (200). Severity: classifyOpsSeverity("upstream_error", effectiveUpstreamStatus), StatusCode: status, - IsBusinessLimited: false, + IsBusinessLimited: recoveredBusinessLimited, IsCountTokens: isCountTokensRequest(c), ErrorMessage: recoveredMsg, ErrorBody: "", - ErrorSource: "upstream_http", - ErrorOwner: "provider", + ErrorSource: recoveredSource, + ErrorOwner: recoveredOwner, UpstreamStatusCode: upstreamStatusCode, UpstreamErrorMessage: upstreamErrorMessage, @@ -850,6 +860,7 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { CreatedAt: time.Now(), } applyOpsLatencyFieldsFromContext(c, entry) + applyOpsUpstreamFieldsFromContext(c, entry) if apiKey != nil { entry.APIKeyID = &apiKey.ID @@ -987,60 +998,7 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { CreatedAt: time.Now(), } applyOpsLatencyFieldsFromContext(c, entry) - - // Capture upstream error context set by gateway services (if present). - // This does NOT affect the client response; it enriches Ops troubleshooting data. - { - if v, ok := c.Get(service.OpsUpstreamStatusCodeKey); ok { - switch t := v.(type) { - case int: - if t > 0 { - code := t - entry.UpstreamStatusCode = &code - } - case int64: - if t > 0 { - code := int(t) - entry.UpstreamStatusCode = &code - } - } - } - if v, ok := c.Get(service.OpsUpstreamErrorMessageKey); ok { - if s, ok := v.(string); ok { - if msg := strings.TrimSpace(s); msg != "" { - entry.UpstreamErrorMessage = &msg - } - } - } - if v, ok := c.Get(service.OpsUpstreamErrorDetailKey); ok { - if s, ok := v.(string); ok { - if detail := strings.TrimSpace(s); detail != "" { - entry.UpstreamErrorDetail = &detail - } - } - } - if v, ok := c.Get(service.OpsUpstreamErrorsKey); ok { - if events, ok := v.([]*service.OpsUpstreamErrorEvent); ok && len(events) > 0 { - entry.UpstreamErrors = events - // Best-effort backfill the single upstream fields from the last event when missing. - last := events[len(events)-1] - if last != nil { - if entry.UpstreamStatusCode == nil && last.UpstreamStatusCode > 0 { - code := last.UpstreamStatusCode - entry.UpstreamStatusCode = &code - } - if entry.UpstreamErrorMessage == nil && strings.TrimSpace(last.Message) != "" { - msg := strings.TrimSpace(last.Message) - entry.UpstreamErrorMessage = &msg - } - if entry.UpstreamErrorDetail == nil && strings.TrimSpace(last.Detail) != "" { - detail := strings.TrimSpace(last.Detail) - entry.UpstreamErrorDetail = &detail - } - } - } - } - } + applyOpsUpstreamFieldsFromContext(c, entry) if apiKey != nil { entry.APIKeyID = &apiKey.ID @@ -1235,6 +1193,77 @@ func applyOpsLatencyFieldsFromContext(c *gin.Context, entry *service.OpsInsertEr entry.TimeToFirstTokenMs = getContextLatencyMs(c, service.OpsTimeToFirstTokenMsKey) } +// applyOpsUpstreamFieldsFromContext captures attempt-level upstream context. +// A final account_auth event owns the top-level status and forces it to zero; +// prior inference statuses remain available in UpstreamErrors. +func applyOpsUpstreamFieldsFromContext(c *gin.Context, entry *service.OpsInsertErrorLogInput) { + if c == nil || entry == nil { + return + } + if v, ok := c.Get(service.OpsUpstreamStatusCodeKey); ok { + switch t := v.(type) { + case int: + if t > 0 { + code := t + entry.UpstreamStatusCode = &code + } + case int64: + if t > 0 { + code := int(t) + entry.UpstreamStatusCode = &code + } + } + } + if v, ok := c.Get(service.OpsUpstreamErrorMessageKey); ok { + if value, ok := v.(string); ok { + if message := strings.TrimSpace(value); message != "" { + entry.UpstreamErrorMessage = &message + } + } + } + if v, ok := c.Get(service.OpsUpstreamErrorDetailKey); ok { + if value, ok := v.(string); ok { + if detail := strings.TrimSpace(value); detail != "" { + entry.UpstreamErrorDetail = &detail + } + } + } + if v, ok := c.Get(service.OpsUpstreamErrorsKey); ok { + if events, ok := v.([]*service.OpsUpstreamErrorEvent); ok && len(events) > 0 { + entry.UpstreamErrors = events + last := events[len(events)-1] + if last == nil { + return + } + if last.Stage == string(service.GatewayFailureStageAccountAuth) { + code := 0 + entry.UpstreamStatusCode = &code + entry.UpstreamErrorMessage = nil + if message := strings.TrimSpace(last.Message); message != "" { + entry.UpstreamErrorMessage = &message + } + entry.UpstreamErrorDetail = nil + if detail := strings.TrimSpace(last.Detail); detail != "" { + entry.UpstreamErrorDetail = &detail + } + } else { + if entry.UpstreamStatusCode == nil && last.UpstreamStatusCode > 0 { + code := last.UpstreamStatusCode + entry.UpstreamStatusCode = &code + } + if entry.UpstreamErrorMessage == nil && strings.TrimSpace(last.Message) != "" { + message := strings.TrimSpace(last.Message) + entry.UpstreamErrorMessage = &message + } + if entry.UpstreamErrorDetail == nil && strings.TrimSpace(last.Detail) != "" { + detail := strings.TrimSpace(last.Detail) + entry.UpstreamErrorDetail = &detail + } + } + } + } +} + func getContextLatencyMs(c *gin.Context, key string) *int64 { if c == nil || strings.TrimSpace(key) == "" { return nil @@ -1390,7 +1419,7 @@ func normalizeOpsErrorType(errType string, code string) string { func classifyOpsPhase(errType, message, code string) string { msg := strings.ToLower(message) - // Standardized phases: request|auth|routing|upstream|network|internal + // Standardized phases: request|auth|account_auth|routing|upstream|network|internal // Map billing/concurrency/response => request; scheduling => routing. if isOpsClientAuthError(code, msg) { return "auth" @@ -1445,7 +1474,10 @@ func classifyOpsErrorLog(c *gin.Context, errType, message, code string, status i routingCapacityLimited := isOpsRoutingCapacityLimited(c) clientBusinessLimited := service.HasOpsClientBusinessLimited(c) upstreamError := hasOpsUpstreamErrorContext(c) - if upstreamError && !routingCapacityLimited { + accountAuthFailure := hasOpsAccountAuthFailure(c) + if accountAuthFailure && !routingCapacityLimited { + phase = "account_auth" + } else if upstreamError && !routingCapacityLimited { phase = "upstream" } if clientBusinessLimited && !upstreamError && !routingCapacityLimited { @@ -1570,6 +1602,22 @@ func hasOpsUpstreamErrorContext(c *gin.Context) bool { return false } +func hasOpsAccountAuthFailure(c *gin.Context) bool { + if c == nil { + return false + } + if v, ok := c.Get(service.OpsUpstreamErrorsKey); ok { + if events, ok := v.([]*service.OpsUpstreamErrorEvent); ok { + for i := len(events) - 1; i >= 0; i-- { + if events[i] != nil { + return events[i].Stage == string(service.GatewayFailureStageAccountAuth) + } + } + } + } + return false +} + func isOpsNoAvailableAccountMessage(message string) bool { msg := strings.ToLower(message) return strings.Contains(msg, opsErrNoAvailableAccounts) || @@ -1584,6 +1632,8 @@ func classifyOpsErrorOwner(phase string, message string) string { switch phase { case "upstream", "network": return "provider" + case "account_auth": + return "provider" case "request", "auth": return "client" case "routing", "internal": @@ -1601,6 +1651,8 @@ func classifyOpsErrorSource(phase string, message string) string { switch phase { case "upstream": return "upstream_http" + case "account_auth": + return "gateway" case "network": return "gateway" case "request", "auth": diff --git a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go index 661b47cebe..9ca20e1cdb 100644 --- a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go +++ b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go @@ -211,8 +211,8 @@ func FinalizeAnthropicResponsesStream(state *AnthropicEventToResponsesState) []R // Close any open item events = append(events, closeCurrentResponsesItem(state)...) - // Emit response.completed - events = append(events, makeResponsesCompletedEvent(state, "completed", nil)) + status, incompleteDetails := anthropicResponsesStreamTerminalState(state.StopReason) + events = append(events, makeResponsesCompletedEvent(state, status, incompleteDetails)) state.CompletedSent = true return events } @@ -434,13 +434,7 @@ func anthToResHandleMessageStop(state *AnthropicEventToResponsesState) []Respons var events []ResponsesStreamEvent events = append(events, closeCurrentResponsesItem(state)...) - status := "completed" - var incompleteDetails *ResponsesIncompleteDetails - if state.StopReason == "max_tokens" { - status = "incomplete" - incompleteDetails = &ResponsesIncompleteDetails{Reason: "max_output_tokens"} - } - + status, incompleteDetails := anthropicResponsesStreamTerminalState(state.StopReason) events = append(events, makeResponsesCompletedEvent(state, status, incompleteDetails)) state.CompletedSent = true return events @@ -448,6 +442,13 @@ func anthToResHandleMessageStop(state *AnthropicEventToResponsesState) []Respons // --- helper functions --- +func anthropicResponsesStreamTerminalState(stopReason string) (string, *ResponsesIncompleteDetails) { + if stopReason == "max_tokens" { + return "incomplete", &ResponsesIncompleteDetails{Reason: "max_output_tokens"} + } + return "completed", nil +} + func closeCurrentResponsesItem(state *AnthropicEventToResponsesState) []ResponsesStreamEvent { if state.CurrentItemType == "" { return nil diff --git a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go new file mode 100644 index 0000000000..3713ccb782 --- /dev/null +++ b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go @@ -0,0 +1,927 @@ +package apicompat + +import ( + "encoding/json" + "fmt" + "sort" + "strings" + "time" +) + +// This file implements a DIRECT bridge between Anthropic Messages and OpenAI +// Chat Completions, skipping the Responses API intermediate representation. +// +// The existing chat-fallback path (forwardAnthropicViaRawChatCompletions) chains +// two Responses-anchored bridges — Anthropic→Responses→ChatCompletions on the +// request side and CC→Responses→Anthropic on the response side — so every +// streaming token runs through two state machines. For force-chat accounts +// (third-party OpenAI-compatible upstreams that only speak /v1/chat/completions) +// the Responses layer is pure overhead: these upstreams never see Responses +// semantics, and the clients reaching them via /v1/messages use standard +// function tools (no custom/tool_search/namespace Codex constructs). +// +// The direct bridge collapses both directions into a single conversion each: +// +// Request: Anthropic Messages → Chat Completions +// Response: CC chunk/response → Anthropic events/response +// +// Helper functions from the Responses bridges (anthropicImageToDataURI, +// extractAnthropicTextFromBlocks, fromResponsesCallID, sanitizeAnthropicToolUseInput, +// parseAnthropicSystemContentParts, isReasoningModel, mapAnthropicEffortToResponses, +// normalizeToolParameters) are reused so the conversion semantics stay identical. + +// --------------------------------------------------------------------------- +// Request: AnthropicRequest → ChatCompletionsRequest +// --------------------------------------------------------------------------- + +// AnthropicToChatCompletionsRequest converts an Anthropic Messages request +// directly into a Chat Completions request, without transiting the Responses +// API. It is semantically equivalent to composing AnthropicToResponses + +// ResponsesToChatCompletionsRequest but avoids materializing the intermediate +// ResponsesRequest and the extra marshal/unmarshal cycle. +func AnthropicToChatCompletionsRequest(req *AnthropicRequest) (*ChatCompletionsRequest, error) { + if req == nil { + return nil, fmt.Errorf("anthropic request is nil") + } + + messages, err := anthropicToChatMessages(req.System, req.Messages) + if err != nil { + return nil, err + } + + out := &ChatCompletionsRequest{ + Model: req.Model, + Messages: messages, + Stream: req.Stream, + } + + // Sampling params: reasoning models (gpt-5.x) reject temperature/top_p. + if !isReasoningModel(req.Model) { + out.Temperature = req.Temperature + out.TopP = req.TopP + } + + if req.MaxTokens > 0 { + v := req.MaxTokens + if v < minMaxOutputTokens { + v = minMaxOutputTokens + } + out.MaxCompletionTokens = &v + } + + // Tools: Anthropic input_schema is a JSON Schema, directly usable as Chat + // function parameters. Server tools (web_search_*) have no Chat Completions + // equivalent and are dropped (mirrors responsesToolsToChatTools). + if len(req.Tools) > 0 { + tools := anthropicToolsToChatTools(req.Tools) + if len(tools) > 0 { + out.Tools = tools + } + } + + // tool_choice is only forwarded when tools survived the conversion + // (upstream rejects tool_choice without tools), and a named choice only when + // it points at a declared tool — mirroring responsesToolChoiceToChatToolChoice, + // chat upstreams 400 on tool_choice referencing an unknown tool. + if len(out.Tools) > 0 && len(req.ToolChoice) > 0 { + declared := make(map[string]bool, len(out.Tools)) + for _, tool := range out.Tools { + if tool.Function != nil { + declared[tool.Function.Name] = true + } + } + tc, err := convertAnthropicToolChoiceToChat(req.ToolChoice, declared) + if err != nil { + return nil, fmt.Errorf("convert tool_choice: %w", err) + } + if len(tc) > 0 { + out.ToolChoice = tc + } + } + + // Reasoning effort: output_config.effort maps 1:1 (max→xhigh). thinking.type + // itself is ignored (the Responses bridge behaves identically). + effort := "medium" + if req.OutputConfig != nil && req.OutputConfig.Effort != "" { + effort = req.OutputConfig.Effort + } + out.ReasoningEffort = mapAnthropicEffortToResponses(effort) + + parallelToolCalls := true + out.ParallelToolCalls = ¶llelToolCalls + + return out, nil +} + +// anthropicToChatMessages converts the Anthropic system field + message list +// into Chat Completions messages. It mirrors convertAnthropicToResponsesInput + +// responsesInputToChatMessages but produces ChatMessage directly. +func anthropicToChatMessages(system json.RawMessage, msgs []AnthropicMessage) ([]ChatMessage, error) { + var messages []ChatMessage + + // System prompt → system message. parseAnthropicSystemContentParts handles + // both string and []block forms and filters the billing header. + if len(system) > 0 { + sysParts, err := parseAnthropicSystemContentParts(system) + if err != nil { + return nil, err + } + if len(sysParts) > 0 { + text := joinResponsesContentPartText(sysParts) + if text != "" { + content, _ := json.Marshal(text) + messages = append(messages, ChatMessage{Role: "system", Content: content}) + } + } + } + + for _, m := range msgs { + converted, err := anthropicMsgToChatMessages(m) + if err != nil { + return nil, err + } + messages = append(messages, converted...) + } + + return normalizeChatMessages(messages), nil +} + +// anthropicMsgToChatMessages converts one Anthropic message into one or more +// Chat messages. tool_result blocks become standalone "tool" role messages +// (the Chat Completions convention); text/image blocks stay in a user message; +// assistant tool_use blocks become tool_calls on the assistant message. +func anthropicMsgToChatMessages(m AnthropicMessage) ([]ChatMessage, error) { + switch m.Role { + case "assistant": + return anthropicAssistantToChatMessages(m.Content) + default: // "user" and any unknown role + return anthropicUserToChatMessages(m.Content) + } +} + +// anthropicUserToChatMessages handles an Anthropic user message. Content may be +// a plain string or an array of blocks. tool_result blocks are extracted into +// standalone "tool" role messages; images inside tool_results are lifted into a +// follow-up user message as image_url parts (the Responses bridge does the same +// — function_call_output only accepts strings, so images must travel separately). +func anthropicUserToChatMessages(raw json.RawMessage) ([]ChatMessage, error) { + // Plain string → single user message. + var s string + if err := json.Unmarshal(raw, &s); err == nil { + content, _ := json.Marshal(s) + return []ChatMessage{{Role: "user", Content: content}}, nil + } + + var blocks []AnthropicContentBlock + if err := json.Unmarshal(raw, &blocks); err != nil { + return nil, err + } + + var out []ChatMessage + var toolResultImageParts []ChatContentPart + + // tool_result → "tool" role messages, text extracted; images deferred. + for _, b := range blocks { + if b.Type != "tool_result" { + continue + } + text, imageParts := convertToolResultOutput(b) + content, _ := json.Marshal(text) + out = append(out, ChatMessage{ + Role: "tool", + Content: content, + ToolCallID: b.ToolUseID, + }) + for _, ip := range imageParts { + toolResultImageParts = append(toolResultImageParts, ChatContentPart{ + Type: "image_url", + ImageURL: &ChatImageURL{URL: ip.ImageURL}, + }) + } + } + + // Remaining text + image blocks → user message. The double-conversion path + // (responsesContentPartsToChatContent) folds text-only content into a single + // string joined with "\n\n" and only uses the parts-array form when an image + // is present — strict chat upstreams reject array content — so the direct + // bridge preserves that folding. + var textParts []string + var parts []ChatContentPart + hasImage := false + for _, b := range blocks { + switch b.Type { + case "text": + if b.Text != "" { + textParts = append(textParts, b.Text) + parts = append(parts, ChatContentPart{Type: "text", Text: b.Text}) + } + case "image": + if uri := anthropicImageToDataURI(b.Source); uri != "" { + hasImage = true + parts = append(parts, ChatContentPart{ + Type: "image_url", + ImageURL: &ChatImageURL{URL: uri}, + }) + } + } + } + if len(toolResultImageParts) > 0 { + hasImage = true + parts = append(parts, toolResultImageParts...) + } + + if !hasImage { + if len(textParts) > 0 { + content, _ := json.Marshal(strings.Join(textParts, "\n\n")) + out = append(out, ChatMessage{Role: "user", Content: content}) + } + return out, nil + } + + content, err := json.Marshal(parts) + if err != nil { + return nil, err + } + out = append(out, ChatMessage{Role: "user", Content: content}) + + return out, nil +} + +// anthropicAssistantToChatMessages handles an Anthropic assistant message. +// Text content → assistant message content; tool_use blocks → tool_calls on the +// same assistant message; thinking blocks are dropped (Chat Completions has no +// inbound thinking field, matching anthropicAssistantToResponses). +func anthropicAssistantToChatMessages(raw json.RawMessage) ([]ChatMessage, error) { + // Plain string → single assistant message. + var s string + if err := json.Unmarshal(raw, &s); err == nil { + content, _ := json.Marshal(s) + return []ChatMessage{{Role: "assistant", Content: content}}, nil + } + + var blocks []AnthropicContentBlock + if err := json.Unmarshal(raw, &blocks); err != nil { + return nil, err + } + + msg := ChatMessage{Role: "assistant"} + text := extractAnthropicTextFromBlocks(blocks) + if text != "" { + content, _ := json.Marshal(text) + msg.Content = content + } + + for _, b := range blocks { + if b.Type != "tool_use" { + continue + } + args := "{}" + if len(b.Input) > 0 { + args = string(b.Input) + } + msg.ToolCalls = append(msg.ToolCalls, ChatToolCall{ + ID: b.ID, + Type: "function", + Function: ChatFunctionCall{ + Name: b.Name, + Arguments: args, + }, + }) + } + + return []ChatMessage{msg}, nil +} + +// anthropicToolsToChatTools maps Anthropic tool definitions to Chat Completions +// function tools. Server-side tools (web_search_*) are dropped — they have no +// Chat Completions equivalent. +func anthropicToolsToChatTools(tools []AnthropicTool) []ChatTool { + var out []ChatTool + for _, t := range tools { + if strings.HasPrefix(t.Type, "web_search") { + continue + } + out = append(out, ChatTool{ + Type: "function", + Function: &ChatFunction{ + Name: t.Name, + Description: t.Description, + Parameters: normalizeToolParameters(t.InputSchema), + Strict: boolPtr(false), + }, + }) + } + return out +} + +// convertAnthropicToolChoiceToChat maps Anthropic tool_choice to Chat +// Completions tool_choice. A nil result means the choice is dropped: like the +// double-conversion path (responsesToolChoiceToChatToolChoice), a named choice +// pointing at an undeclared tool or an unknown choice type is not forwarded, +// because chat upstreams reject it. +// +// {"type":"auto"} → "auto" +// {"type":"any"} → "required" +// {"type":"none"} → "none" +// {"type":"tool","name":"X"} → {"type":"function","function":{"name":"X"}} (X declared) +func convertAnthropicToolChoiceToChat(raw json.RawMessage, declared map[string]bool) (json.RawMessage, error) { + var tc struct { + Type string `json:"type"` + Name string `json:"name"` + } + if err := json.Unmarshal(raw, &tc); err != nil { + return nil, err + } + + switch tc.Type { + case "auto": + return json.Marshal("auto") + case "any": + return json.Marshal("required") + case "none": + return json.Marshal("none") + case "tool": + if tc.Name == "" || !declared[tc.Name] { + return nil, nil + } + return json.Marshal(map[string]any{ + "type": "function", + "function": map[string]string{"name": tc.Name}, + }) + default: + return nil, nil + } +} + +// joinResponsesContentPartText concatenates the text of input_text parts. Used +// for the system prompt where parseAnthropicSystemContentParts returns +// ResponsesContentPart values. +func joinResponsesContentPartText(parts []ResponsesContentPart) string { + var texts []string + for _, p := range parts { + if p.Type == "input_text" && p.Text != "" { + texts = append(texts, p.Text) + } + } + return strings.Join(texts, "\n\n") +} + +// --------------------------------------------------------------------------- +// Non-streaming response: ChatCompletionsResponse → AnthropicResponse +// --------------------------------------------------------------------------- + +// ChatCompletionsResponseToAnthropic converts a Chat Completions response +// directly into an Anthropic Messages response, without materializing a +// ResponsesResponse. It is semantically equivalent to composing +// ChatCompletionsResponseToResponses + ResponsesToAnthropic. +func ChatCompletionsResponseToAnthropic(resp *ChatCompletionsResponse, model string) *AnthropicResponse { + out := &AnthropicResponse{ + Type: "message", + Role: "assistant", + Model: model, + } + + if resp != nil { + out.ID = resp.ID + if out.Model == "" { + out.Model = resp.Model + } + + if len(resp.Choices) > 0 { + choice := resp.Choices[0] + out.Content = chatMessageToAnthropicBlocks(choice.Message) + out.StopReason = chatFinishReasonToAnthropicStopReason(choice.FinishReason, out.Content) + // "length" → "max_tokens" is handled by chatFinishReasonToAnthropicStopReason; + // Anthropic conveys max-tokens via stop_reason only, no incomplete_details field. + } + if resp.Usage != nil { + out.Usage = chatUsageToAnthropicUsage(resp.Usage) + } + } + + if len(out.Content) == 0 { + out.Content = []AnthropicContentBlock{{Type: "text", Text: ""}} + } + // Empty choices / nil response never enter the choices branch above; the + // double-conversion path still reports a completed turn ("end_turn"), and + // stop_reason "" is invalid for strict Anthropic clients. + if out.StopReason == "" { + out.StopReason = chatFinishReasonToAnthropicStopReason("", out.Content) + } + // The double-conversion path generates a response id when the upstream + // omits one (ChatCompletionsResponseToResponses); clients treat it as required. + if out.ID == "" { + out.ID = generateResponsesID() + } + + return out +} + +// chatMessageToAnthropicBlocks converts a Chat Completions message into +// Anthropic content blocks. Reasoning content → thinking block; text content → +// text block; tool_calls → tool_use blocks. Mirrors chatMessageToResponsesOutput +// + the reasoning→thinking mapping in ResponsesToAnthropic. +func chatMessageToAnthropicBlocks(message ChatMessage) []AnthropicContentBlock { + var blocks []AnthropicContentBlock + + if message.ReasoningContent != "" { + blocks = append(blocks, AnthropicContentBlock{ + Type: "thinking", + Thinking: message.ReasoningContent, + }) + } + + text := chatMessageContentText(message.Content) + // DeepSeek reasoning-only fallback: when there is no text and no tool calls, + // surface the reasoning content as visible text so the turn isn't empty. + if text == "" && strings.TrimSpace(message.ReasoningContent) != "" && len(message.ToolCalls) == 0 { + text = message.ReasoningContent + } + if text != "" || len(message.ToolCalls) == 0 { + blocks = append(blocks, AnthropicContentBlock{Type: "text", Text: text}) + } + + for _, toolCall := range message.ToolCalls { + arguments := toolCall.Function.Arguments + if strings.TrimSpace(arguments) == "" { + arguments = "{}" + } + blocks = append(blocks, AnthropicContentBlock{ + Type: "tool_use", + ID: fromResponsesCallID(toolCall.ID), + Name: toolCall.Function.Name, + Input: sanitizeAnthropicToolUseInput(toolCall.Function.Name, arguments), + }) + } + + return blocks +} + +// chatFinishReasonToAnthropicStopReason maps Chat Completions finish_reason to +// Anthropic stop_reason. +// +// "length" → "max_tokens" +// "tool_calls" → "tool_use" +// other → "end_turn" (or "tool_use" if tool_use blocks present) +// +// "stop", "content_filter", and unknown reasons all map to a completed response +// in the double-conversion path, which then derives stop_reason from the blocks. +func chatFinishReasonToAnthropicStopReason(reason string, blocks []AnthropicContentBlock) string { + switch reason { + case "length": + return "max_tokens" + case "tool_calls": + return "tool_use" + default: + if containsAnthropicToolUseBlock(blocks) { + return "tool_use" + } + return "end_turn" + } +} + +// chatUsageToAnthropicUsage converts Chat Completions token usage to Anthropic +// usage shape. Mirrors ChatUsageToResponsesUsage + anthropicUsageFromResponsesUsage. +func chatUsageToAnthropicUsage(usage *ChatUsage) AnthropicUsage { + if usage == nil { + return AnthropicUsage{} + } + + cachedTokens := 0 + cacheCreationTokens := 0 + if usage.PromptTokensDetails != nil { + cachedTokens = usage.PromptTokensDetails.CachedTokens + // cache_write_tokens and cache_creation_tokens are alternate spellings of + // the same quantity, not additive; the double-conversion path + // (ChatUsageToResponsesUsage) prefers write and falls back to creation. + if usage.PromptTokensDetails.CacheWriteTokens > 0 { + cacheCreationTokens = usage.PromptTokensDetails.CacheWriteTokens + } else { + cacheCreationTokens = usage.PromptTokensDetails.CacheCreationTokens + } + } + + inputTokens := usage.PromptTokens - cachedTokens - cacheCreationTokens + if inputTokens < 0 { + inputTokens = 0 + } + + return AnthropicUsage{ + InputTokens: inputTokens, + OutputTokens: usage.CompletionTokens, + CacheReadInputTokens: cachedTokens, + CacheCreationInputTokens: cacheCreationTokens, + } +} + +// --------------------------------------------------------------------------- +// Streaming: ChatCompletionsChunk → []AnthropicStreamEvent (stateful converter) +// --------------------------------------------------------------------------- + +// ChatCompletionsToAnthropicStreamState tracks state while converting Chat +// Completions SSE chunks directly into Anthropic SSE events. It collapses the +// ChatCompletionsToResponsesStreamState + ResponsesEventToAnthropicState pair +// into one state machine. +type ChatCompletionsToAnthropicStreamState struct { + MessageStartSent bool + MessageStopSent bool + + // Current content block lifecycle. + ContentBlockIndex int + ContentBlockOpen bool + CurrentBlockType string // "text" | "thinking" | "tool_use" + CurrentToolName string + CurrentToolHadDelta bool + HasToolCall bool + + // Tool calls keyed by the upstream tool_call index. The Anthropic block + // index is assigned when the tool block is announced (content_block_start), + // which is deferred until the tool's name has arrived. Argument fragments + // and the call ID seen before the name are buffered and flushed with the + // announcement; tools whose name never arrives are announced with an empty + // name at finalize so their arguments are not lost. + toolBlockIndex map[int]int + toolAnnounced map[int]bool + toolName map[int]string + pendingToolCallID map[int]string + pendingToolArgs map[int]string + + // Reasoning (DeepSeek-style): reasoning_content streamed before content. + // No separate reasoning block index — it uses ContentBlockIndex like the + // Responses bridge's ReasoningIndex, but since blocks are sequential we + // reuse the single ContentBlockIndex counter. + + FinishReason string + + InputTokens int + OutputTokens int + CacheReadInputTokens int + CacheCreationInputTokens int + + ResponseID string + Model string + Created int64 +} + +// NewChatCompletionsToAnthropicStreamState returns an initialized stream state. +func NewChatCompletionsToAnthropicStreamState(model string) *ChatCompletionsToAnthropicStreamState { + return &ChatCompletionsToAnthropicStreamState{ + ResponseID: generateResponsesID(), + Model: model, + Created: time.Now().Unix(), + toolBlockIndex: make(map[int]int), + toolAnnounced: make(map[int]bool), + toolName: make(map[int]string), + pendingToolCallID: make(map[int]string), + pendingToolArgs: make(map[int]string), + } +} + +// ChatCompletionsChunkToAnthropicEvents converts one Chat Completions stream +// chunk into zero or more Anthropic stream events, updating state as it goes. +func ChatCompletionsChunkToAnthropicEvents( + chunk *ChatCompletionsChunk, + state *ChatCompletionsToAnthropicStreamState, +) []AnthropicStreamEvent { + if chunk == nil || state == nil { + return nil + } + if chunk.ID != "" { + state.ResponseID = chunk.ID + } + if state.Model == "" && chunk.Model != "" { + state.Model = chunk.Model + } + + // Usage in a streaming chunk (include_usage) arrives in its own chunk, + // often with empty choices. Capture it for the finalize message_delta. + if chunk.Usage != nil { + u := chatUsageToAnthropicUsage(chunk.Usage) + state.InputTokens = u.InputTokens + state.OutputTokens = u.OutputTokens + state.CacheReadInputTokens = u.CacheReadInputTokens + state.CacheCreationInputTokens = u.CacheCreationInputTokens + } + + var events []AnthropicStreamEvent + events = append(events, ensureCCAnthropicMessageStart(state)...) + + for _, choice := range chunk.Choices { + // Reasoning content → thinking block. + if choice.Delta.ReasoningContent != nil && *choice.Delta.ReasoningContent != "" { + events = append(events, ensureCCAnthropicThinkingBlock(state)...) + events = append(events, ccAnthropicDelta(state, &AnthropicDelta{ + Type: "thinking_delta", + Thinking: *choice.Delta.ReasoningContent, + })...) + } + + // Text content → text block (closes any open thinking block first). + if choice.Delta.Content != nil && *choice.Delta.Content != "" { + events = append(events, closeCCAnthropicBlockIfOpen(state, "thinking")...) + events = append(events, ensureCCAnthropicTextBlock(state)...) + events = append(events, ccAnthropicDelta(state, &AnthropicDelta{ + Type: "text_delta", + Text: *choice.Delta.Content, + })...) + } + + // Tool calls → tool_use blocks. + for _, toolCall := range choice.Delta.ToolCalls { + events = append(events, closeCCAnthropicBlockIfOpen(state, "thinking")...) + events = append(events, handleCCAnthropicToolCall(state, &toolCall)...) + } + + if choice.FinishReason != nil && *choice.FinishReason != "" { + state.FinishReason = *choice.FinishReason + } + } + + return events +} + +// FinalizeChatCompletionsAnthropicStream emits terminal Anthropic events +// (close open blocks + message_delta + message_stop) when the stream ends. +func FinalizeChatCompletionsAnthropicStream(state *ChatCompletionsToAnthropicStreamState) []AnthropicStreamEvent { + if state == nil || state.MessageStopSent { + return nil + } + + var events []AnthropicStreamEvent + if !state.MessageStartSent { + events = append(events, ensureCCAnthropicMessageStart(state)...) + } + + // Announce tools whose name never arrived so their buffered arguments are + // not silently dropped. The double-conversion path announced these + // immediately with an empty name; the deferred announcement keeps that data + // preservation while still delivering correct names when they do arrive. + if len(state.pendingToolCallID) > 0 { + idxs := make([]int, 0, len(state.pendingToolCallID)) + for idx := range state.pendingToolCallID { + idxs = append(idxs, idx) + } + sort.Ints(idxs) + for _, idx := range idxs { + callID := state.pendingToolCallID[idx] + events = append(events, closeCCAnthropicBlock(state)...) + events = append(events, announceCCAnthropicToolBlock(state, idx, callID, "")...) + } + } + + events = append(events, closeCCAnthropicBlock(state)...) + + stopReason := ccFinishReasonToAnthropicStopReason(state.FinishReason, state.HasToolCall) + + events = append(events, + AnthropicStreamEvent{ + Type: "message_delta", + Delta: &AnthropicDelta{ + StopReason: stopReason, + }, + Usage: &AnthropicUsage{ + InputTokens: state.InputTokens, + OutputTokens: state.OutputTokens, + CacheReadInputTokens: state.CacheReadInputTokens, + CacheCreationInputTokens: state.CacheCreationInputTokens, + }, + }, + AnthropicStreamEvent{Type: "message_stop"}, + ) + state.MessageStopSent = true + return events +} + +// ensureCCAnthropicMessageStart emits message_start on the first event. +func ensureCCAnthropicMessageStart(state *ChatCompletionsToAnthropicStreamState) []AnthropicStreamEvent { + if state.MessageStartSent { + return nil + } + state.MessageStartSent = true + return []AnthropicStreamEvent{{ + Type: "message_start", + Message: &AnthropicResponse{ + ID: state.ResponseID, + Type: "message", + Role: "assistant", + Content: []AnthropicContentBlock{}, + Model: state.Model, + Usage: AnthropicUsage{InputTokens: 0, OutputTokens: 0}, + }, + }} +} + +// ensureCCAnthropicThinkingBlock opens a thinking block if none is open. +func ensureCCAnthropicThinkingBlock(state *ChatCompletionsToAnthropicStreamState) []AnthropicStreamEvent { + if state.ContentBlockOpen && state.CurrentBlockType == "thinking" { + return nil + } + events := closeCCAnthropicBlock(state) + idx := state.ContentBlockIndex + state.ContentBlockOpen = true + state.CurrentBlockType = "thinking" + events = append(events, AnthropicStreamEvent{ + Type: "content_block_start", + Index: &idx, + ContentBlock: &AnthropicContentBlock{ + Type: "thinking", + Thinking: "", + }, + }) + return events +} + +// ensureCCAnthropicTextBlock opens a text block if none is open. +func ensureCCAnthropicTextBlock(state *ChatCompletionsToAnthropicStreamState) []AnthropicStreamEvent { + if state.ContentBlockOpen && state.CurrentBlockType == "text" { + return nil + } + events := closeCCAnthropicBlock(state) + idx := state.ContentBlockIndex + state.ContentBlockOpen = true + state.CurrentBlockType = "text" + events = append(events, AnthropicStreamEvent{ + Type: "content_block_start", + Index: &idx, + ContentBlock: &AnthropicContentBlock{ + Type: "text", + Text: "", + }, + }) + return events +} + +// handleCCAnthropicToolCall processes one upstream tool_call delta. The +// content_block_start for a tool is deferred until its name has arrived (some +// upstreams stream id/arguments before the name); argument fragments seen +// before the announcement are buffered and flushed with it, later fragments +// stream as input_json_delta on the tool's block. +func handleCCAnthropicToolCall(state *ChatCompletionsToAnthropicStreamState, toolCall *ChatToolCall) []AnthropicStreamEvent { + idx := 0 + if toolCall.Index != nil { + idx = *toolCall.Index + } + + var events []AnthropicStreamEvent + + if _, seen := state.toolAnnounced[idx]; !seen { + // New tool call: it ends whatever block is currently streaming. + events = append(events, closeCCAnthropicBlock(state)...) + state.HasToolCall = true + + callID := toolCall.ID + if callID == "" { + callID = generateItemID() + } + if name := toolCall.Function.Name; name != "" { + events = append(events, announceCCAnthropicToolBlock(state, idx, callID, name)...) + } else { + state.toolAnnounced[idx] = false + state.pendingToolCallID[idx] = callID + } + } else if !state.toolAnnounced[idx] && toolCall.Function.Name != "" { + // Deferred announcement: the name has arrived. + callID := state.pendingToolCallID[idx] + if toolCall.ID != "" { + callID = toolCall.ID + } + events = append(events, closeCCAnthropicBlock(state)...) + events = append(events, announceCCAnthropicToolBlock(state, idx, callID, toolCall.Function.Name)...) + } + + // Argument fragment → input_json_delta on the tool's block once announced, + // buffered until the deferred announcement otherwise. + if toolCall.Function.Arguments != "" { + if state.toolAnnounced[idx] { + blockIdx := state.toolBlockIndex[idx] + if state.ContentBlockOpen && blockIdx == state.ContentBlockIndex { + state.CurrentToolHadDelta = true + } + events = append(events, AnthropicStreamEvent{ + Type: "content_block_delta", + Index: &blockIdx, + Delta: &AnthropicDelta{ + Type: "input_json_delta", + PartialJSON: toolCall.Function.Arguments, + }, + }) + } else { + state.pendingToolArgs[idx] += toolCall.Function.Arguments + } + } + + return events +} + +// announceCCAnthropicToolBlock assigns the next Anthropic block index to the +// tool, emits its content_block_start, and flushes any argument fragments +// buffered while the announcement was deferred. +func announceCCAnthropicToolBlock(state *ChatCompletionsToAnthropicStreamState, idx int, callID, name string) []AnthropicStreamEvent { + blockIdx := state.ContentBlockIndex + state.toolBlockIndex[idx] = blockIdx + state.toolAnnounced[idx] = true + state.toolName[idx] = name + state.CurrentToolName = name + state.CurrentToolHadDelta = false + state.ContentBlockOpen = true + state.CurrentBlockType = "tool_use" + delete(state.pendingToolCallID, idx) + + events := []AnthropicStreamEvent{{ + Type: "content_block_start", + Index: &blockIdx, + ContentBlock: &AnthropicContentBlock{ + Type: "tool_use", + ID: fromResponsesCallID(callID), + Name: name, + Input: json.RawMessage("{}"), + }, + }} + if pending := state.pendingToolArgs[idx]; pending != "" { + delete(state.pendingToolArgs, idx) + state.CurrentToolHadDelta = true + events = append(events, AnthropicStreamEvent{ + Type: "content_block_delta", + Index: &blockIdx, + Delta: &AnthropicDelta{ + Type: "input_json_delta", + PartialJSON: pending, + }, + }) + } + return events +} + +// ccAnthropicDelta emits a content_block_delta on the current block. +func ccAnthropicDelta(state *ChatCompletionsToAnthropicStreamState, delta *AnthropicDelta) []AnthropicStreamEvent { + if !state.ContentBlockOpen { + return nil + } + idx := state.ContentBlockIndex + return []AnthropicStreamEvent{{ + Type: "content_block_delta", + Index: &idx, + Delta: delta, + }} +} + +// closeCCAnthropicBlockIfOpen closes the current block only if it matches the +// given type (used to close a thinking block before opening text/tool). +func closeCCAnthropicBlockIfOpen(state *ChatCompletionsToAnthropicStreamState, blockType string) []AnthropicStreamEvent { + if !state.ContentBlockOpen || state.CurrentBlockType != blockType { + return nil + } + return closeCCAnthropicBlock(state) +} + +// closeCCAnthropicBlock closes the currently open content block. A tool_use +// block that streamed no argument delta gets a final input_json_delta "{}" +// first — the double-conversion path normalizes empty tool arguments to "{}", +// and some clients assemble tool input exclusively from deltas. +func closeCCAnthropicBlock(state *ChatCompletionsToAnthropicStreamState) []AnthropicStreamEvent { + if !state.ContentBlockOpen { + return nil + } + idx := state.ContentBlockIndex + var events []AnthropicStreamEvent + if state.CurrentBlockType == "tool_use" && !state.CurrentToolHadDelta { + events = append(events, AnthropicStreamEvent{ + Type: "content_block_delta", + Index: &idx, + Delta: &AnthropicDelta{ + Type: "input_json_delta", + PartialJSON: "{}", + }, + }) + } + state.ContentBlockOpen = false + state.ContentBlockIndex++ + state.CurrentBlockType = "" + state.CurrentToolName = "" + state.CurrentToolHadDelta = false + return append(events, AnthropicStreamEvent{ + Type: "content_block_stop", + Index: &idx, + }) +} + +// ccFinishReasonToAnthropicStopReason maps a Chat Completions finish_reason +// (captured during streaming) to an Anthropic stop_reason for message_delta. +func ccFinishReasonToAnthropicStopReason(reason string, hasToolCall bool) string { + switch reason { + case "length": + return "max_tokens" + case "tool_calls": + return "tool_use" + case "stop": + if hasToolCall { + return "tool_use" + } + return "end_turn" + default: + if hasToolCall { + return "tool_use" + } + return "end_turn" + } +} diff --git a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge_test.go b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge_test.go new file mode 100644 index 0000000000..7d769d0bb5 --- /dev/null +++ b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge_test.go @@ -0,0 +1,1090 @@ +package apicompat + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +// collectAnthropicStreamEvents feeds CC chunks through the direct bridge and +// appends finalize events, returning the full Anthropic event sequence. +func collectAnthropicStreamEvents(t *testing.T, chunks []string) []AnthropicStreamEvent { + t.Helper() + state := NewChatCompletionsToAnthropicStreamState("deepseek-v4-pro") + var events []AnthropicStreamEvent + for _, payload := range chunks { + var chunk ChatCompletionsChunk + require.NoError(t, json.Unmarshal([]byte(payload), &chunk)) + events = append(events, ChatCompletionsChunkToAnthropicEvents(&chunk, state)...) + } + events = append(events, FinalizeChatCompletionsAnthropicStream(state)...) + return events +} + +// anthropicEventTypes extracts the sequence of event types for concise assertions. +func anthropicEventTypes(events []AnthropicStreamEvent) []string { + out := make([]string, 0, len(events)) + for _, e := range events { + out = append(out, e.Type) + } + return out +} + +// --------------------------------------------------------------------------- +// Request: AnthropicToChatCompletionsRequest +// --------------------------------------------------------------------------- + +func TestAnthropicToChatCompletionsRequest_BasicText(t *testing.T) { + req := &AnthropicRequest{ + Model: "claude-sonnet-4-20250514", + MaxTokens: 1024, + Messages: []AnthropicMessage{ + {Role: "user", Content: json.RawMessage(`"hello"`)}, + }, + } + + out, err := AnthropicToChatCompletionsRequest(req) + require.NoError(t, err) + require.Equal(t, "claude-sonnet-4-20250514", out.Model) + require.Len(t, out.Messages, 1) + require.Equal(t, "user", out.Messages[0].Role) + require.Equal(t, `"hello"`, string(out.Messages[0].Content)) + require.NotNil(t, out.MaxCompletionTokens) + require.Equal(t, 1024, *out.MaxCompletionTokens) +} + +func TestAnthropicToChatCompletionsRequest_SystemPrompt(t *testing.T) { + req := &AnthropicRequest{ + Model: "claude-sonnet-4-20250514", + MaxTokens: 100, + System: json.RawMessage(`"You are helpful"`), + Messages: []AnthropicMessage{ + {Role: "user", Content: json.RawMessage(`"hi"`)}, + }, + } + + out, err := AnthropicToChatCompletionsRequest(req) + require.NoError(t, err) + require.Len(t, out.Messages, 2) + require.Equal(t, "system", out.Messages[0].Role) + require.Equal(t, `"You are helpful"`, string(out.Messages[0].Content)) +} + +func TestAnthropicToChatCompletionsRequest_ToolUseInAssistant(t *testing.T) { + req := &AnthropicRequest{ + Model: "claude-sonnet-4-20250514", + MaxTokens: 100, + Messages: []AnthropicMessage{ + {Role: "user", Content: json.RawMessage(`"check weather"`)}, + {Role: "assistant", Content: json.RawMessage(`[{"type":"text","text":"Let me check."},{"type":"tool_use","id":"toolu_1","name":"get_weather","input":{"city":"SF"}}]`)}, + {Role: "user", Content: json.RawMessage(`[{"type":"tool_result","tool_use_id":"toolu_1","content":"sunny"}]`)}, + }, + } + + out, err := AnthropicToChatCompletionsRequest(req) + require.NoError(t, err) + // user + assistant(with tool_calls) + tool reply + require.GreaterOrEqual(t, len(out.Messages), 2) + // Find the assistant message with tool_calls + var assistant *ChatMessage + for i := range out.Messages { + if out.Messages[i].Role == "assistant" && len(out.Messages[i].ToolCalls) > 0 { + assistant = &out.Messages[i] + } + } + require.NotNil(t, assistant, "assistant message with tool_calls should survive normalization") + require.Len(t, assistant.ToolCalls, 1) + require.Equal(t, "toolu_1", assistant.ToolCalls[0].ID) + require.Equal(t, "function", assistant.ToolCalls[0].Type) + require.Equal(t, "get_weather", assistant.ToolCalls[0].Function.Name) + require.Equal(t, `{"city":"SF"}`, assistant.ToolCalls[0].Function.Arguments) +} + +func TestAnthropicToChatCompletionsRequest_ToolResultBecomesToolMessage(t *testing.T) { + req := &AnthropicRequest{ + Model: "claude-sonnet-4-20250514", + MaxTokens: 100, + Messages: []AnthropicMessage{ + {Role: "user", Content: json.RawMessage(`"check weather"`)}, + {Role: "assistant", Content: json.RawMessage(`[{"type":"tool_use","id":"toolu_1","name":"get_weather","input":{"city":"SF"}}]`)}, + {Role: "user", Content: json.RawMessage(`[{"type":"tool_result","tool_use_id":"toolu_1","content":"sunny, 72F"}]`)}, + }, + } + + out, err := AnthropicToChatCompletionsRequest(req) + require.NoError(t, err) + // Find the tool reply message + var toolMsg *ChatMessage + for i := range out.Messages { + if out.Messages[i].Role == "tool" { + toolMsg = &out.Messages[i] + } + } + require.NotNil(t, toolMsg, "tool_result should become a tool role message") + require.Equal(t, "toolu_1", toolMsg.ToolCallID) + require.Equal(t, `"sunny, 72F"`, string(toolMsg.Content)) +} + +func TestAnthropicToChatCompletionsRequest_ThinkingDropped(t *testing.T) { + req := &AnthropicRequest{ + Model: "claude-sonnet-4-20250514", + MaxTokens: 100, + Messages: []AnthropicMessage{ + {Role: "assistant", Content: json.RawMessage(`[{"type":"thinking","thinking":"secret thoughts"},{"type":"text","text":"answer"}]`)}, + }, + } + + out, err := AnthropicToChatCompletionsRequest(req) + require.NoError(t, err) + require.Len(t, out.Messages, 1) + // Only text survives; thinking is dropped + require.Equal(t, `"answer"`, string(out.Messages[0].Content)) +} + +func TestAnthropicToChatCompletionsRequest_ToolChoiceAuto(t *testing.T) { + req := &AnthropicRequest{ + Model: "claude-sonnet-4-20250514", + MaxTokens: 100, + Tools: []AnthropicTool{ + {Name: "get_weather", InputSchema: json.RawMessage(`{"type":"object","properties":{}}`)}, + }, + ToolChoice: json.RawMessage(`{"type":"auto"}`), + Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}}, + } + + out, err := AnthropicToChatCompletionsRequest(req) + require.NoError(t, err) + require.Len(t, out.Tools, 1) + require.Equal(t, `"auto"`, string(out.ToolChoice)) +} + +func TestAnthropicToChatCompletionsRequest_ToolChoiceAny(t *testing.T) { + req := &AnthropicRequest{ + Model: "claude-sonnet-4-20250514", + MaxTokens: 100, + Tools: []AnthropicTool{ + {Name: "get_weather", InputSchema: json.RawMessage(`{"type":"object","properties":{}}`)}, + }, + ToolChoice: json.RawMessage(`{"type":"any"}`), + Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}}, + } + + out, err := AnthropicToChatCompletionsRequest(req) + require.NoError(t, err) + require.Equal(t, `"required"`, string(out.ToolChoice)) +} + +func TestAnthropicToChatCompletionsRequest_ToolChoiceSpecificTool(t *testing.T) { + req := &AnthropicRequest{ + Model: "claude-sonnet-4-20250514", + MaxTokens: 100, + Tools: []AnthropicTool{ + {Name: "get_weather", InputSchema: json.RawMessage(`{"type":"object","properties":{}}`)}, + }, + ToolChoice: json.RawMessage(`{"type":"tool","name":"get_weather"}`), + Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}}, + } + + out, err := AnthropicToChatCompletionsRequest(req) + require.NoError(t, err) + var tc map[string]any + require.NoError(t, json.Unmarshal(out.ToolChoice, &tc)) + require.Equal(t, "function", tc["type"]) + fn, ok := tc["function"].(map[string]any) + require.True(t, ok, "tool_choice function should be a map") + require.Equal(t, "get_weather", fn["name"]) +} + +func TestAnthropicToChatCompletionsRequest_TemperatureStrippedForReasoningModel(t *testing.T) { + temp := 0.7 + topP := 0.9 + req := &AnthropicRequest{ + Model: "gpt-5.4", + MaxTokens: 100, + Temperature: &temp, + TopP: &topP, + Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}}, + } + + out, err := AnthropicToChatCompletionsRequest(req) + require.NoError(t, err) + require.Nil(t, out.Temperature, "temperature should be stripped for reasoning models") + require.Nil(t, out.TopP, "top_p should be stripped for reasoning models") +} + +func TestAnthropicToChatCompletionsRequest_TemperaturePreservedForNonReasoningModel(t *testing.T) { + temp := 0.7 + topP := 0.9 + req := &AnthropicRequest{ + Model: "deepseek-v4-pro", + MaxTokens: 100, + Temperature: &temp, + TopP: &topP, + Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}}, + } + + out, err := AnthropicToChatCompletionsRequest(req) + require.NoError(t, err) + require.NotNil(t, out.Temperature) + require.Equal(t, 0.7, *out.Temperature) + require.NotNil(t, out.TopP) + require.Equal(t, 0.9, *out.TopP) +} + +func TestAnthropicToChatCompletionsRequest_MaxTokensFloor(t *testing.T) { + req := &AnthropicRequest{ + Model: "claude-sonnet-4-20250514", + MaxTokens: 10, // below minMaxOutputTokens (128) + Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}}, + } + + out, err := AnthropicToChatCompletionsRequest(req) + require.NoError(t, err) + require.NotNil(t, out.MaxCompletionTokens) + require.Equal(t, minMaxOutputTokens, *out.MaxCompletionTokens) +} + +func TestAnthropicToChatCompletionsRequest_ReasoningEffortMapping(t *testing.T) { + req := &AnthropicRequest{ + Model: "gpt-5.4", + MaxTokens: 100, + OutputConfig: &AnthropicOutputConfig{Effort: "max"}, + Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}}, + } + + out, err := AnthropicToChatCompletionsRequest(req) + require.NoError(t, err) + require.Equal(t, "xhigh", out.ReasoningEffort) +} + +func TestAnthropicToChatCompletionsRequest_ReasoningEffortDefaultMedium(t *testing.T) { + req := &AnthropicRequest{ + Model: "gpt-5.4", + MaxTokens: 100, + Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}}, + } + + out, err := AnthropicToChatCompletionsRequest(req) + require.NoError(t, err) + require.Equal(t, "medium", out.ReasoningEffort) +} + +func TestAnthropicToChatCompletionsRequest_ServerToolDropped(t *testing.T) { + req := &AnthropicRequest{ + Model: "claude-sonnet-4-20250514", + MaxTokens: 100, + Tools: []AnthropicTool{ + {Type: "web_search_20250305", Name: "web_search"}, + {Name: "get_weather", InputSchema: json.RawMessage(`{"type":"object","properties":{}}`)}, + }, + Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}}, + } + + out, err := AnthropicToChatCompletionsRequest(req) + require.NoError(t, err) + require.Len(t, out.Tools, 1, "web_search server tool should be dropped") + require.Equal(t, "get_weather", out.Tools[0].Function.Name) +} + +// --------------------------------------------------------------------------- +// Non-streaming response: ChatCompletionsResponseToAnthropic +// --------------------------------------------------------------------------- + +func TestChatCompletionsResponseToAnthropic_TextOnly(t *testing.T) { + resp := &ChatCompletionsResponse{ + ID: "chatcmpl-1", + Model: "deepseek-v4-pro", + Choices: []ChatChoice{{ + Index: 0, + Message: ChatMessage{Role: "assistant", Content: json.RawMessage(`"hello world"`)}, + FinishReason: "stop", + }}, + Usage: &ChatUsage{PromptTokens: 5, CompletionTokens: 2, TotalTokens: 7}, + } + + out := ChatCompletionsResponseToAnthropic(resp, "claude-sonnet-4-20250514") + require.Equal(t, "chatcmpl-1", out.ID) + require.Equal(t, "claude-sonnet-4-20250514", out.Model) + require.Len(t, out.Content, 1) + require.Equal(t, "text", out.Content[0].Type) + require.Equal(t, "hello world", out.Content[0].Text) + require.Equal(t, "end_turn", out.StopReason) + require.Equal(t, 5, out.Usage.InputTokens) + require.Equal(t, 2, out.Usage.OutputTokens) +} + +func TestChatCompletionsResponseToAnthropic_ToolUse(t *testing.T) { + resp := &ChatCompletionsResponse{ + ID: "chatcmpl-2", + Model: "deepseek-v4-pro", + Choices: []ChatChoice{{ + Index: 0, + Message: ChatMessage{ + Role: "assistant", + ToolCalls: []ChatToolCall{{ + ID: "call_1", + Type: "function", + Function: ChatFunctionCall{ + Name: "get_weather", + Arguments: `{"city":"SF"}`, + }, + }}, + }, + FinishReason: "tool_calls", + }}, + } + + out := ChatCompletionsResponseToAnthropic(resp, "claude-sonnet-4-20250514") + require.Len(t, out.Content, 1) + require.Equal(t, "tool_use", out.Content[0].Type) + require.Equal(t, "call_1", out.Content[0].ID) + require.Equal(t, "get_weather", out.Content[0].Name) + require.Equal(t, `{"city":"SF"}`, string(out.Content[0].Input)) + require.Equal(t, "tool_use", out.StopReason) +} + +func TestChatCompletionsResponseToAnthropic_ReasoningOnlyFallback(t *testing.T) { + resp := &ChatCompletionsResponse{ + ID: "chatcmpl-3", + Model: "deepseek-v4-pro", + Choices: []ChatChoice{{ + Index: 0, + Message: ChatMessage{ + Role: "assistant", + ReasoningContent: "I should think about this", + }, + FinishReason: "stop", + }}, + } + + out := ChatCompletionsResponseToAnthropic(resp, "claude-sonnet-4-20250514") + // thinking block + text block (fallback uses reasoning as visible text) + require.Len(t, out.Content, 2) + require.Equal(t, "thinking", out.Content[0].Type) + require.Equal(t, "I should think about this", out.Content[0].Thinking) + require.Equal(t, "text", out.Content[1].Type) + require.Equal(t, "I should think about this", out.Content[1].Text) +} + +func TestChatCompletionsResponseToAnthropic_FinishReasonLength(t *testing.T) { + resp := &ChatCompletionsResponse{ + ID: "chatcmpl-4", + Model: "deepseek-v4-pro", + Choices: []ChatChoice{{ + Index: 0, + Message: ChatMessage{Role: "assistant", Content: json.RawMessage(`"truncated"`)}, + FinishReason: "length", + }}, + } + + out := ChatCompletionsResponseToAnthropic(resp, "claude-sonnet-4-20250514") + require.Equal(t, "max_tokens", out.StopReason) +} + +func TestChatCompletionsResponseToAnthropic_EmptyChoices(t *testing.T) { + resp := &ChatCompletionsResponse{ + ID: "chatcmpl-5", + Model: "deepseek-v4-pro", + Choices: []ChatChoice{}, + } + + out := ChatCompletionsResponseToAnthropic(resp, "claude-sonnet-4-20250514") + require.Len(t, out.Content, 1) + require.Equal(t, "text", out.Content[0].Type) + require.Equal(t, "", out.Content[0].Text) + require.Equal(t, "end_turn", out.StopReason, "empty choices must not produce an empty stop_reason") +} + +func TestChatCompletionsResponseToAnthropic_CacheTokens(t *testing.T) { + resp := &ChatCompletionsResponse{ + ID: "chatcmpl-6", + Model: "deepseek-v4-pro", + Choices: []ChatChoice{{ + Index: 0, + Message: ChatMessage{Role: "assistant", Content: json.RawMessage(`"hi"`)}, + FinishReason: "stop", + }}, + Usage: &ChatUsage{ + PromptTokens: 100, + CompletionTokens: 5, + TotalTokens: 105, + PromptTokensDetails: &ChatTokenDetails{ + CachedTokens: 30, + CacheCreationTokens: 10, + }, + }, + } + + out := ChatCompletionsResponseToAnthropic(resp, "claude-sonnet-4-20250514") + // input = prompt(100) - cached(30) - cacheCreation(10) = 60 + require.Equal(t, 60, out.Usage.InputTokens) + require.Equal(t, 5, out.Usage.OutputTokens) + require.Equal(t, 30, out.Usage.CacheReadInputTokens) + require.Equal(t, 10, out.Usage.CacheCreationInputTokens) +} + +func TestChatCompletionsResponseToAnthropic_NilResponse(t *testing.T) { + out := ChatCompletionsResponseToAnthropic(nil, "claude-sonnet-4-20250514") + require.Len(t, out.Content, 1) + require.Equal(t, "text", out.Content[0].Type) + require.Equal(t, "end_turn", out.StopReason, "nil response must not produce an empty stop_reason") + require.NotEmpty(t, out.ID) +} + +// --------------------------------------------------------------------------- +// Streaming: ChatCompletionsChunkToAnthropicEvents +// --------------------------------------------------------------------------- + +func TestChatCompletionsChunkToAnthropicEvents_TextOnly(t *testing.T) { + events := collectAnthropicStreamEvents(t, []string{ + `{"choices":[{"index":0,"delta":{"role":"assistant","content":"hello"}}]}`, + `{"choices":[{"index":0,"delta":{"content":" world"}}]}`, + `{"choices":[{"index":0,"delta":{"content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":2,"total_tokens":7}}`, + }) + + types := anthropicEventTypes(events) + // message_start → content_block_start(text) → 2× content_block_delta → content_block_stop → message_delta → message_stop + require.Equal(t, []string{ + "message_start", + "content_block_start", + "content_block_delta", + "content_block_delta", + "content_block_stop", + "message_delta", + "message_stop", + }, types) + + // Verify deltas + var texts []string + for _, e := range events { + if e.Type == "content_block_delta" && e.Delta != nil { + texts = append(texts, e.Delta.Text) + } + } + require.Equal(t, []string{"hello", " world"}, texts) + + // Verify stop reason + for _, e := range events { + if e.Type == "message_delta" { + require.Equal(t, "end_turn", e.Delta.StopReason) + require.Equal(t, 5, e.Usage.InputTokens) + require.Equal(t, 2, e.Usage.OutputTokens) + } + } +} + +func TestChatCompletionsChunkToAnthropicEvents_ReasoningThenContent(t *testing.T) { + events := collectAnthropicStreamEvents(t, []string{ + `{"choices":[{"index":0,"delta":{"reasoning_content":"thinking..."}}]}`, + `{"choices":[{"index":0,"delta":{"content":"answer"}}]}`, + `{"choices":[{"index":0,"delta":{"content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":2,"total_tokens":3}}`, + }) + + types := anthropicEventTypes(events) + // message_start → thinking block start → thinking_delta → thinking block stop + // → text block start → text_delta → text block stop → message_delta → message_stop + require.Equal(t, []string{ + "message_start", + "content_block_start", + "content_block_delta", + "content_block_stop", + "content_block_start", + "content_block_delta", + "content_block_stop", + "message_delta", + "message_stop", + }, types) + + // First content_block_start should be thinking, second text + var blockTypes []string + for _, e := range events { + if e.Type == "content_block_start" && e.ContentBlock != nil { + blockTypes = append(blockTypes, e.ContentBlock.Type) + } + } + require.Equal(t, []string{"thinking", "text"}, blockTypes) +} + +func TestChatCompletionsChunkToAnthropicEvents_ToolCallAggregation(t *testing.T) { + events := collectAnthropicStreamEvents(t, []string{ + `{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"get_weather","arguments":""}}]}}]}`, + `{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"city\":"}}]}}]}`, + `{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"SF\"}"}}]}}]}`, + `{"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}}`, + }) + + types := anthropicEventTypes(events) + // message_start → content_block_start(tool_use) → 2× input_json_delta (empty first arg skipped) → content_block_stop → message_delta(tool_use) → message_stop + require.Equal(t, []string{ + "message_start", + "content_block_start", + "content_block_delta", + "content_block_delta", + "content_block_stop", + "message_delta", + "message_stop", + }, types) + + // Verify tool_use block + for _, e := range events { + if e.Type == "content_block_start" && e.ContentBlock != nil { + require.Equal(t, "tool_use", e.ContentBlock.Type) + require.Equal(t, "call_1", e.ContentBlock.ID) + require.Equal(t, "get_weather", e.ContentBlock.Name) + } + if e.Type == "message_delta" { + require.Equal(t, "tool_use", e.Delta.StopReason) + } + } + + // Verify arguments assembled (empty first fragment skipped) + var partials []string + for _, e := range events { + if e.Type == "content_block_delta" && e.Delta != nil { + partials = append(partials, e.Delta.PartialJSON) + } + } + require.Equal(t, []string{`{"city":`, `"SF"}`}, partials) +} + +func TestChatCompletionsChunkToAnthropicEvents_LengthMapsToMaxTokens(t *testing.T) { + events := collectAnthropicStreamEvents(t, []string{ + `{"choices":[{"index":0,"delta":{"content":"partial"}}]}`, + `{"choices":[{"index":0,"delta":{"content":""},"finish_reason":"length"}],"usage":{"prompt_tokens":1,"completion_tokens":2,"total_tokens":3}}`, + }) + + for _, e := range events { + if e.Type == "message_delta" { + require.Equal(t, "max_tokens", e.Delta.StopReason) + } + } +} + +func TestChatCompletionsChunkToAnthropicEvents_EmptyStream(t *testing.T) { + events := collectAnthropicStreamEvents(t, []string{ + `{"choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":0,"total_tokens":1}}`, + }) + + types := anthropicEventTypes(events) + // Even with no content, message_start + message_delta + message_stop should fire. + require.Contains(t, types, "message_start") + require.Contains(t, types, "message_stop") +} + +func TestChatCompletionsChunkToAnthropicEvents_MessageStartEmittedOnce(t *testing.T) { + events := collectAnthropicStreamEvents(t, []string{ + `{"choices":[{"index":0,"delta":{"content":"a"}}]}`, + `{"choices":[{"index":0,"delta":{"content":"b"}}]}`, + `{"choices":[{"index":0,"delta":{"content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":2,"total_tokens":3}}`, + }) + + count := 0 + for _, e := range events { + if e.Type == "message_start" { + count++ + } + } + require.Equal(t, 1, count, "message_start should only be emitted once") +} + +func TestChatCompletionsChunkToAnthropicEvents_ParallelToolCalls(t *testing.T) { + events := collectAnthropicStreamEvents(t, []string{ + `{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"tool_a","arguments":"{}"}}]}}]}`, + `{"choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"id":"call_2","type":"function","function":{"name":"tool_b","arguments":"{}"}}]}}]}`, + `{"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":1,"completion_tokens":2,"total_tokens":3}}`, + }) + + // Two tool_use blocks should be opened + var toolBlocks []string + for _, e := range events { + if e.Type == "content_block_start" && e.ContentBlock != nil && e.ContentBlock.Type == "tool_use" { + toolBlocks = append(toolBlocks, e.ContentBlock.Name) + } + } + require.Equal(t, []string{"tool_a", "tool_b"}, toolBlocks) + + for _, e := range events { + if e.Type == "message_delta" { + require.Equal(t, "tool_use", e.Delta.StopReason) + } + } +} + +func TestFinalizeChatCompletionsAnthropicStream_NoOpAfterStop(t *testing.T) { + state := NewChatCompletionsToAnthropicStreamState("test") + state.MessageStopSent = true + + events := FinalizeChatCompletionsAnthropicStream(state) + require.Nil(t, events, "finalize should be a no-op after message_stop") +} + +func TestFinalizeChatCompletionsAnthropicStream_EmitsMessageStartIfMissing(t *testing.T) { + state := NewChatCompletionsToAnthropicStreamState("test") + // Never fed any chunks — message_start not yet sent + + events := FinalizeChatCompletionsAnthropicStream(state) + types := anthropicEventTypes(events) + require.Contains(t, types, "message_start") + require.Contains(t, types, "message_stop") +} + +// --------------------------------------------------------------------------- +// Equivalence: direct bridge matches the double-conversion bridge +// --------------------------------------------------------------------------- + +// TestDirectBridge_NonStreamingMatchesDoubleConversion verifies that +// ChatCompletionsResponseToAnthropic produces the same Anthropic response as the +// existing ChatCompletionsResponseToResponses + ResponsesToAnthropic chain. +func TestDirectBridge_NonStreamingMatchesDoubleConversion(t *testing.T) { + resp := &ChatCompletionsResponse{ + ID: "chatcmpl-eq", + Model: "deepseek-v4-pro", + Choices: []ChatChoice{{ + Index: 0, + Message: ChatMessage{ + Role: "assistant", + Content: json.RawMessage(`"hello"`), + ReasoningContent: "reasoning text", + ToolCalls: []ChatToolCall{{ + ID: "call_eq", + Type: "function", + Function: ChatFunctionCall{ + Name: "search", + Arguments: `{"q":"test"}`, + }, + }}, + }, + FinishReason: "tool_calls", + }}, + Usage: &ChatUsage{ + PromptTokens: 50, + CompletionTokens: 10, + TotalTokens: 60, + PromptTokensDetails: &ChatTokenDetails{CachedTokens: 5}, + }, + } + + // Direct bridge + direct := ChatCompletionsResponseToAnthropic(resp, "claude-sonnet-4-20250514") + + // Double-conversion bridge + responsesResp := ChatCompletionsResponseToResponses(resp, "claude-sonnet-4-20250514", nil, false, nil) + double := ResponsesToAnthropic(responsesResp, "claude-sonnet-4-20250514") + + // Compare key fields + require.Equal(t, direct.StopReason, double.StopReason) + require.Equal(t, direct.Model, double.Model) + require.Len(t, direct.Content, len(double.Content)) + for i := range direct.Content { + require.Equal(t, double.Content[i].Type, direct.Content[i].Type, "block %d type mismatch", i) + require.Equal(t, double.Content[i].Text, direct.Content[i].Text, "block %d text mismatch", i) + require.Equal(t, double.Content[i].Thinking, direct.Content[i].Thinking, "block %d thinking mismatch", i) + require.Equal(t, double.Content[i].Name, direct.Content[i].Name, "block %d name mismatch", i) + require.Equal(t, double.Content[i].ID, direct.Content[i].ID, "block %d id mismatch", i) + require.Equal(t, string(double.Content[i].Input), string(direct.Content[i].Input), "block %d input mismatch", i) + } + require.Equal(t, double.Usage.InputTokens, direct.Usage.InputTokens) + require.Equal(t, double.Usage.OutputTokens, direct.Usage.OutputTokens) + require.Equal(t, double.Usage.CacheReadInputTokens, direct.Usage.CacheReadInputTokens) + require.Equal(t, double.Usage.CacheCreationInputTokens, direct.Usage.CacheCreationInputTokens) +} + +// TestDirectBridge_RequestMatchesDoubleConversion verifies that +// AnthropicToChatCompletionsRequest produces an equivalent Chat Completions +// request as the AnthropicToResponses + ResponsesToChatCompletionsRequest chain. +func TestDirectBridge_RequestMatchesDoubleConversion(t *testing.T) { + temp := 0.5 + req := &AnthropicRequest{ + Model: "deepseek-v4-pro", + MaxTokens: 500, + Temperature: &temp, + System: json.RawMessage(`"be helpful"`), + Tools: []AnthropicTool{ + {Name: "get_weather", InputSchema: json.RawMessage(`{"type":"object","properties":{"city":{"type":"string"}}}`)}, + }, + ToolChoice: json.RawMessage(`{"type":"auto"}`), + Messages: []AnthropicMessage{ + {Role: "user", Content: json.RawMessage(`"what's the weather?"`)}, + {Role: "assistant", Content: json.RawMessage(`[{"type":"text","text":"checking"},{"type":"tool_use","id":"toolu_1","name":"get_weather","input":{"city":"SF"}}]`)}, + {Role: "user", Content: json.RawMessage(`[{"type":"tool_result","tool_use_id":"toolu_1","content":"sunny"}]`)}, + }, + } + + // Direct bridge + direct, err := AnthropicToChatCompletionsRequest(req) + require.NoError(t, err) + + // Double-conversion bridge + responsesReq, err := AnthropicToResponses(req) + require.NoError(t, err) + double, err := ResponsesToChatCompletionsRequest(responsesReq) + require.NoError(t, err) + + // Compare key fields + require.Equal(t, double.Model, direct.Model) + require.Equal(t, double.Temperature, direct.Temperature) + require.Equal(t, double.MaxCompletionTokens, direct.MaxCompletionTokens) + require.Equal(t, double.ReasoningEffort, direct.ReasoningEffort) + require.Equal(t, string(double.ToolChoice), string(direct.ToolChoice)) + require.Len(t, direct.Tools, len(double.Tools)) + + // Compare messages — same count, same roles, same content + require.Len(t, direct.Messages, len(double.Messages), "message count mismatch") + for i := range direct.Messages { + require.Equal(t, double.Messages[i].Role, direct.Messages[i].Role, "msg %d role mismatch", i) + // Normalize content for comparison (both should be valid JSON) + var dContent, dblContent any + _ = json.Unmarshal(double.Messages[i].Content, &dblContent) + _ = json.Unmarshal(direct.Messages[i].Content, &dContent) + require.Equal(t, dblContent, dContent, "msg %d content mismatch", i) + require.Equal(t, double.Messages[i].ToolCallID, direct.Messages[i].ToolCallID, "msg %d tool_call_id mismatch", i) + require.Len(t, direct.Messages[i].ToolCalls, len(double.Messages[i].ToolCalls), "msg %d tool_calls count mismatch", i) + for j := range direct.Messages[i].ToolCalls { + require.Equal(t, double.Messages[i].ToolCalls[j].ID, direct.Messages[i].ToolCalls[j].ID, "msg %d tool %d id mismatch", i, j) + require.Equal(t, double.Messages[i].ToolCalls[j].Function.Name, direct.Messages[i].ToolCalls[j].Function.Name, "msg %d tool %d name mismatch", i, j) + require.Equal(t, double.Messages[i].ToolCalls[j].Function.Arguments, direct.Messages[i].ToolCalls[j].Function.Arguments, "msg %d tool %d arguments mismatch", i, j) + } + } +} + +// --------------------------------------------------------------------------- +// Edge cases +// --------------------------------------------------------------------------- + +func TestChatCompletionsChunkToAnthropicEvents_ImageInToolResult(t *testing.T) { + // A multi-turn conversation: assistant calls a tool, user replies with a + // tool_result containing text + an image. The image should be lifted into + // a follow-up user message as an image_url part. + req := &AnthropicRequest{ + Model: "claude-sonnet-4-20250514", + MaxTokens: 100, + Messages: []AnthropicMessage{ + {Role: "user", Content: json.RawMessage(`"check this image"`)}, + {Role: "assistant", Content: json.RawMessage(`[{"type":"text","text":"let me look"},{"type":"tool_use","id":"toolu_1","name":"analyze","input":{"x":1}}]`)}, + {Role: "user", Content: json.RawMessage(`[{"type":"tool_result","tool_use_id":"toolu_1","content":[{"type":"text","text":"result"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aGVsbG8="}}]}]`)}, + }, + } + + out, err := AnthropicToChatCompletionsRequest(req) + require.NoError(t, err) + // user + assistant(tool_use) + tool + user(image) + require.GreaterOrEqual(t, len(out.Messages), 3) + + // Find the user message with image content + var foundImage bool + for _, m := range out.Messages { + if m.Role != "user" { + continue + } + var parts []ChatContentPart + if err := json.Unmarshal(m.Content, &parts); err == nil { + for _, p := range parts { + if p.Type == "image_url" && p.ImageURL != nil { + foundImage = true + require.True(t, strings.HasPrefix(p.ImageURL.URL, "data:image/png;base64,")) + } + } + } + } + require.True(t, foundImage, "image from tool_result should appear in user message") +} + +func TestChatCompletionsToAnthropicStreamState_ToolCallNameArrivesLate(t *testing.T) { + // Some upstreams send the tool_call index + arguments before the name. + events := collectAnthropicStreamEvents(t, []string{ + `{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_late"}]}}]}`, + `{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"name":"late_tool"}}]}}]}`, + `{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{}"}}]}}]}`, + `{"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`, + }) + + // The tool_use block should still be opened with the correct name. + var toolName string + for _, e := range events { + if e.Type == "content_block_start" && e.ContentBlock != nil && e.ContentBlock.Type == "tool_use" { + toolName = e.ContentBlock.Name + } + } + require.Equal(t, "late_tool", toolName) +} + +// assembleToolUseBlocks rebuilds tool_use blocks from a stream the way an +// Anthropic client does: content_block_start announces id/name, input_json_delta +// fragments concatenate into the input JSON. +type assembledToolUse struct { + ID string + Name string + Input string +} + +func assembleToolUseBlocks(events []AnthropicStreamEvent) []assembledToolUse { + blockByIdx := map[int]int{} // anthropic block index → position in out + var out []assembledToolUse + for _, e := range events { + switch e.Type { + case "content_block_start": + if e.ContentBlock != nil && e.ContentBlock.Type == "tool_use" && e.Index != nil { + blockByIdx[*e.Index] = len(out) + out = append(out, assembledToolUse{ID: e.ContentBlock.ID, Name: e.ContentBlock.Name}) + } + case "content_block_delta": + if e.Delta != nil && e.Delta.Type == "input_json_delta" && e.Index != nil { + if pos, ok := blockByIdx[*e.Index]; ok { + out[pos].Input += e.Delta.PartialJSON + } + } + } + } + return out +} + +func TestChatCompletionsToAnthropicStreamState_ToolCallArgsArriveBeforeName(t *testing.T) { + // Some upstreams stream argument fragments before the tool name. The + // fragments buffered while the announcement is deferred must be flushed + // with the content_block_start, so the client rebuilds complete JSON. + events := collectAnthropicStreamEvents(t, []string{ + `{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_early","function":{"arguments":"{\"city\":"}}]}}]}`, + `{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"SF\""}}]}}]}`, + `{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"name":"get_weather","arguments":"}"}}]}}]}`, + `{"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`, + }) + + tools := assembleToolUseBlocks(events) + require.Len(t, tools, 1) + require.Equal(t, "call_early", tools[0].ID) + require.Equal(t, "get_weather", tools[0].Name) + require.JSONEq(t, `{"city":"SF"}`, tools[0].Input) + + // No delta may precede the block's content_block_start. + started := map[int]bool{} + for _, e := range events { + switch e.Type { + case "content_block_start": + started[*e.Index] = true + case "content_block_delta": + require.True(t, started[*e.Index], "delta before content_block_start on index %d", *e.Index) + } + } +} + +func TestChatCompletionsToAnthropicStreamState_ToolCallNameNeverArrives(t *testing.T) { + // If the name never arrives, the tool is announced at finalize with an + // empty name (like the double-conversion path) so its arguments are not + // silently dropped — stop_reason still reports tool_use. + events := collectAnthropicStreamEvents(t, []string{ + `{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_anon","function":{"arguments":"{\"a\":1}"}}]}}]}`, + `{"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`, + }) + + tools := assembleToolUseBlocks(events) + require.Len(t, tools, 1) + require.Equal(t, "call_anon", tools[0].ID) + require.Equal(t, "", tools[0].Name) + require.JSONEq(t, `{"a":1}`, tools[0].Input) + + // Block lifecycle must stay balanced and terminate before message_stop. + types := anthropicEventTypes(events) + require.Equal(t, []string{ + "message_start", + "content_block_start", + "content_block_delta", + "content_block_stop", + "message_delta", + "message_stop", + }, types) +} + +func TestChatCompletionsToAnthropicStreamState_EmptyArgsToolEmitsPlaceholderDelta(t *testing.T) { + // A tool call whose arguments never arrive gets a final input_json_delta + // "{}" before its stop — the double-conversion path normalizes empty + // arguments to "{}", and some clients assemble input only from deltas. + events := collectAnthropicStreamEvents(t, []string{ + `{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_empty","type":"function","function":{"name":"noop","arguments":""}}]}}]}`, + `{"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`, + }) + + tools := assembleToolUseBlocks(events) + require.Len(t, tools, 1) + require.Equal(t, "noop", tools[0].Name) + require.JSONEq(t, `{}`, tools[0].Input) +} + +func TestAnthropicToChatCompletionsRequest_UserArrayContentFoldsToString(t *testing.T) { + // Text-only array content folds into a single string joined with "\n\n", + // like the double-conversion path — strict chat upstreams reject array + // content when no image forces the parts form. + req := &AnthropicRequest{ + Model: "deepseek-v4-pro", + MaxTokens: 100, + Messages: []AnthropicMessage{ + {Role: "user", Content: json.RawMessage(`[{"type":"text","text":"first"},{"type":"text","text":"second"}]`)}, + }, + } + + out, err := AnthropicToChatCompletionsRequest(req) + require.NoError(t, err) + require.Len(t, out.Messages, 1) + require.Equal(t, `"first\n\nsecond"`, string(out.Messages[0].Content)) +} + +func TestDirectBridge_RequestMatchesDoubleConversion_ArrayUserContent(t *testing.T) { + // Array-form user content: text-only folds to a string, image-bearing stays + // in parts form — both must match the double-conversion chain exactly. + req := &AnthropicRequest{ + Model: "deepseek-v4-pro", + MaxTokens: 100, + Messages: []AnthropicMessage{ + {Role: "user", Content: json.RawMessage(`[{"type":"text","text":"first"},{"type":"text","text":"second"}]`)}, + {Role: "assistant", Content: json.RawMessage(`"ok"`)}, + {Role: "user", Content: json.RawMessage(`[{"type":"text","text":"look"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aGVsbG8="}}]`)}, + }, + } + + direct, err := AnthropicToChatCompletionsRequest(req) + require.NoError(t, err) + + responsesReq, err := AnthropicToResponses(req) + require.NoError(t, err) + double, err := ResponsesToChatCompletionsRequest(responsesReq) + require.NoError(t, err) + + require.Len(t, direct.Messages, len(double.Messages), "message count mismatch") + for i := range direct.Messages { + require.Equal(t, double.Messages[i].Role, direct.Messages[i].Role, "msg %d role mismatch", i) + var dContent, dblContent any + require.NoError(t, json.Unmarshal(double.Messages[i].Content, &dblContent)) + require.NoError(t, json.Unmarshal(direct.Messages[i].Content, &dContent)) + require.Equal(t, dblContent, dContent, "msg %d content mismatch", i) + } +} + +func TestDirectBridge_NonStreamingMatchesDoubleConversion_CacheWriteTokens(t *testing.T) { + // cache_write_tokens and cache_creation_tokens are alternate spellings, not + // additive — when both are set, the double-conversion path prefers write. + resp := &ChatCompletionsResponse{ + ID: "chatcmpl-cache", + Model: "deepseek-v4-pro", + Choices: []ChatChoice{{ + Message: ChatMessage{Role: "assistant", Content: json.RawMessage(`"hi"`)}, + FinishReason: "stop", + }}, + Usage: &ChatUsage{ + PromptTokens: 100, + CompletionTokens: 10, + TotalTokens: 110, + PromptTokensDetails: &ChatTokenDetails{ + CachedTokens: 20, + CacheCreationTokens: 7, + CacheWriteTokens: 9, + }, + }, + } + + direct := ChatCompletionsResponseToAnthropic(resp, "claude-sonnet-4-20250514") + + responsesResp := ChatCompletionsResponseToResponses(resp, "claude-sonnet-4-20250514", nil, false, nil) + double := ResponsesToAnthropic(responsesResp, "claude-sonnet-4-20250514") + + require.Equal(t, double.Usage.InputTokens, direct.Usage.InputTokens) + require.Equal(t, double.Usage.OutputTokens, direct.Usage.OutputTokens) + require.Equal(t, double.Usage.CacheReadInputTokens, direct.Usage.CacheReadInputTokens) + require.Equal(t, double.Usage.CacheCreationInputTokens, direct.Usage.CacheCreationInputTokens) + require.Equal(t, 9, direct.Usage.CacheCreationInputTokens) +} + +func TestChatCompletionsResponseToAnthropic_GeneratesIDWhenMissing(t *testing.T) { + resp := &ChatCompletionsResponse{ + Model: "deepseek-v4-pro", + Choices: []ChatChoice{{ + Message: ChatMessage{Role: "assistant", Content: json.RawMessage(`"hi"`)}, + FinishReason: "stop", + }}, + } + + out := ChatCompletionsResponseToAnthropic(resp, "claude-sonnet-4-20250514") + require.NotEmpty(t, out.ID, "response id must be generated when the upstream omits one") +} + +func TestAnthropicToChatCompletionsRequest_ToolChoiceUndeclaredDropped(t *testing.T) { + // A named tool_choice pointing at a dropped/unknown tool is not forwarded — + // chat upstreams 400 on tool_choice referencing an undeclared tool. + base := AnthropicRequest{ + Model: "deepseek-v4-pro", + MaxTokens: 100, + Tools: []AnthropicTool{ + {Name: "get_weather", InputSchema: json.RawMessage(`{"type":"object"}`)}, + {Name: "web_search_20250305", Type: "web_search_20250305", InputSchema: json.RawMessage(`{"type":"object"}`)}, + }, + Messages: []AnthropicMessage{ + {Role: "user", Content: json.RawMessage(`"hi"`)}, + }, + } + + undeclared := base + undeclared.ToolChoice = json.RawMessage(`{"type":"tool","name":"nonexistent"}`) + out, err := AnthropicToChatCompletionsRequest(&undeclared) + require.NoError(t, err) + require.Empty(t, out.ToolChoice, "tool_choice for an undeclared tool must be dropped") + + droppedServerTool := base + droppedServerTool.ToolChoice = json.RawMessage(`{"type":"tool","name":"web_search_20250305"}`) + out, err = AnthropicToChatCompletionsRequest(&droppedServerTool) + require.NoError(t, err) + require.Empty(t, out.ToolChoice, "tool_choice for a dropped server tool must be dropped") + + unknownType := base + unknownType.ToolChoice = json.RawMessage(`{"type":"mystery"}`) + out, err = AnthropicToChatCompletionsRequest(&unknownType) + require.NoError(t, err) + require.Empty(t, out.ToolChoice, "unknown tool_choice types must be dropped") + + declared := base + declared.ToolChoice = json.RawMessage(`{"type":"tool","name":"get_weather"}`) + out, err = AnthropicToChatCompletionsRequest(&declared) + require.NoError(t, err) + require.JSONEq(t, `{"type":"function","function":{"name":"get_weather"}}`, string(out.ToolChoice)) +} + +func TestDirectBridge_NonStreamingMatchesDoubleConversion_EmptyChoices(t *testing.T) { + // An upstream 200 with empty choices must still report a valid stop_reason, + // matching the double-conversion chain ("end_turn"). + resp := &ChatCompletionsResponse{ID: "chatcmpl-empty", Model: "deepseek-v4-pro"} + + direct := ChatCompletionsResponseToAnthropic(resp, "claude-sonnet-4-20250514") + + responsesResp := ChatCompletionsResponseToResponses(resp, "claude-sonnet-4-20250514", nil, false, nil) + double := ResponsesToAnthropic(responsesResp, "claude-sonnet-4-20250514") + + require.Equal(t, double.StopReason, direct.StopReason) + require.Equal(t, "end_turn", direct.StopReason) +} + +func TestChatCompletionsResponseToAnthropic_ContentFilterWithToolUse(t *testing.T) { + // content_filter (and unknown finish reasons) derive stop_reason from the + // blocks, like the double-conversion path. + resp := &ChatCompletionsResponse{ + ID: "chatcmpl-cf", + Model: "deepseek-v4-pro", + Choices: []ChatChoice{{ + Message: ChatMessage{ + Role: "assistant", + Content: json.RawMessage(`"partial"`), + ToolCalls: []ChatToolCall{{ + ID: "call_cf", + Type: "function", + Function: ChatFunctionCall{Name: "search", Arguments: `{"q":"x"}`}, + }}, + }, + FinishReason: "content_filter", + }}, + } + + out := ChatCompletionsResponseToAnthropic(resp, "claude-sonnet-4-20250514") + require.Equal(t, "tool_use", out.StopReason) +} diff --git a/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go b/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go index 8aa9eab60a..0d2de969dd 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go +++ b/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go @@ -91,16 +91,22 @@ func EffectiveResponsesTools(req *ResponsesRequest) ([]ResponsesTool, error) { if len(raw) == 0 || raw[0] != '{' { continue } + var discriminator struct { + Type string `json:"type"` + } + if err := json.Unmarshal(raw, &discriminator); err != nil { + return nil, fmt.Errorf("parse responses additional tools item: %w", err) + } + if discriminator.Type != "additional_tools" { + continue + } var item struct { - Type string `json:"type"` Tools []ResponsesTool `json:"tools"` } if err := json.Unmarshal(raw, &item); err != nil { return nil, fmt.Errorf("parse responses additional tools item: %w", err) } - if item.Type == "additional_tools" { - tools = append(tools, item.Tools...) - } + tools = append(tools, item.Tools...) } return tools, nil } diff --git a/backend/internal/pkg/apicompat/chatcompletions_responses_bridge_custom_tools_test.go b/backend/internal/pkg/apicompat/chatcompletions_responses_bridge_custom_tools_test.go index 5b1d994eb3..6265a64d0a 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_responses_bridge_custom_tools_test.go +++ b/backend/internal/pkg/apicompat/chatcompletions_responses_bridge_custom_tools_test.go @@ -79,6 +79,31 @@ func TestEffectiveResponsesTools_SkipsStringInputItems(t *testing.T) { assert.Equal(t, "exec", tools[0].Name) } +func TestEffectiveResponsesTools_IgnoresMalformedToolsOnNonAdditionalItem(t *testing.T) { + req := &ResponsesRequest{ + Input: json.RawMessage(`[ + {"type":"message","role":"user","tools":"not-an-array","content":[{"type":"input_text","text":"hello"}]}, + {"type":"additional_tools","tools":[{"type":"custom","name":"exec"}]} + ]`), + } + + tools, err := EffectiveResponsesTools(req) + require.NoError(t, err) + require.Len(t, tools, 1) + assert.Equal(t, "exec", tools[0].Name) +} + +func TestEffectiveResponsesTools_RejectsMalformedAdditionalTools(t *testing.T) { + req := &ResponsesRequest{ + Input: json.RawMessage(`[{"type":"additional_tools","tools":"not-an-array"}]`), + } + + tools, err := EffectiveResponsesTools(req) + require.Error(t, err) + assert.Contains(t, err.Error(), "parse responses additional tools item") + assert.Empty(t, tools) +} + func TestResponsesToChatCompletionsRequest_DropsToolChoiceWhenNoConvertibleTools(t *testing.T) { req := &ResponsesRequest{ Model: "glm-5.2", diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 376f0d97da..455dd1a444 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -413,6 +413,28 @@ func resToAnthHandleFuncArgsDelta(evt *ResponsesStreamEvent, state *ResponsesEve return nil } + if state.CurrentBlockType == "tool_use" && state.CurrentToolName == "Read" { + state.CurrentToolArgs += evt.Delta + if state.CurrentToolHadDelta || !json.Valid([]byte(state.CurrentToolArgs)) { + return nil + } + + blockIdx, ok := state.OutputIndexToBlockIdx[evt.OutputIndex] + if !ok { + return nil + } + state.CurrentToolHadDelta = true + sanitized := sanitizeAnthropicToolUseInput(state.CurrentToolName, state.CurrentToolArgs) + return []AnthropicStreamEvent{{ + Type: "content_block_delta", + Index: &blockIdx, + Delta: &AnthropicDelta{ + Type: "input_json_delta", + PartialJSON: string(sanitized), + }, + }} + } + if state.CurrentBlockType == "tool_use" { state.CurrentToolHadDelta = true } @@ -433,6 +455,9 @@ func resToAnthHandleFuncArgsDelta(evt *ResponsesStreamEvent, state *ResponsesEve } func resToAnthHandleFuncArgsDone(evt *ResponsesStreamEvent, state *ResponsesEventToAnthropicState) []AnthropicStreamEvent { + if !state.ContentBlockOpen { + return nil + } if state.CurrentBlockType != "tool_use" { return resToAnthHandleBlockDone(state) } @@ -452,10 +477,20 @@ func resToAnthHandleFuncArgsDone(evt *ResponsesStreamEvent, state *ResponsesEven raw = string(sanitized) } - idx := state.ContentBlockIndex + // 从事件的 OutputIndex 解析正确的 block index,与 resToAnthHandleFuncArgsDelta 对齐 + blockIdx, ok := state.OutputIndexToBlockIdx[evt.OutputIndex] + if !ok { + blockIdx = state.ContentBlockIndex + } + + // 如果 block 已关闭(ContentBlockIndex 已越过它),说明 arguments 已通过 delta 流式发完,不再补发 + if !state.ContentBlockOpen || blockIdx != state.ContentBlockIndex { + return nil + } + events := []AnthropicStreamEvent{{ Type: "content_block_delta", - Index: &idx, + Index: &blockIdx, Delta: &AnthropicDelta{ Type: "input_json_delta", PartialJSON: raw, diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic_parallel_tool_test.go b/backend/internal/pkg/apicompat/responses_to_anthropic_parallel_tool_test.go new file mode 100644 index 0000000000..c3171adbfa --- /dev/null +++ b/backend/internal/pkg/apicompat/responses_to_anthropic_parallel_tool_test.go @@ -0,0 +1,277 @@ +package apicompat + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func intPtr(v int) *int { return &v } +func strPtr(s string) *string { return &s } + +// TestStreamingParallelToolUseNoGhostDelta reproduces the bug from issue #4193: +// when the CC→Responses→Anthropic bridge finalizes parallel tool calls whose +// arguments arrived packed in function_call_arguments.done (no prior delta), +// resToAnthHandleFuncArgsDone used state.ContentBlockIndex directly instead of +// looking up OutputIndexToBlockIdx. After the first tool's block was closed +// (ContentBlockIndex++), the second tool's .done emitted a content_block_delta +// on an index that was never content_block_start'ed — Claude Code reports +// "Content block not found". +// +// This test drives the full finalize path: CC chunks with two parallel +// tool_calls → ChatCompletionsChunkToResponsesEvents → FinalizeChatCompletionsResponsesStream +// → ResponsesEventToAnthropicEvents, and asserts every content_block_delta +// targets a block that was previously content_block_start'ed. +func TestStreamingParallelToolUseNoGhostDelta(t *testing.T) { + ccState := NewChatCompletionsToResponsesStreamState("glm-5.2") + anthropicState := NewResponsesEventToAnthropicState() + anthropicState.Model = "glm-5.2" + + // Chunk 1: first tool_call arrives with id + name + packed arguments. + chatChunk1 := &ChatCompletionsChunk{ + ID: "chatcmpl-1", + Model: "glm-5.2", + Choices: []ChatChunkChoice{{ + Index: 0, + Delta: ChatDelta{ + ToolCalls: []ChatToolCall{{ + Index: intPtr(0), + ID: "call_weather", + Type: "function", + Function: ChatFunctionCall{ + Name: "get_weather", + Arguments: `{"city":"Tokyo"}`, + }, + }}, + }, + }}, + } + + // Chunk 2: second tool_call arrives with id + name + packed arguments. + chatChunk2 := &ChatCompletionsChunk{ + ID: "chatcmpl-1", + Model: "glm-5.2", + Choices: []ChatChunkChoice{{ + Index: 0, + Delta: ChatDelta{ + ToolCalls: []ChatToolCall{{ + Index: intPtr(1), + ID: "call_time", + Type: "function", + Function: ChatFunctionCall{ + Name: "get_time", + Arguments: `{}`, + }, + }}, + }, + }}, + } + + // Chunk 3: finish. + chatChunk3 := &ChatCompletionsChunk{ + ID: "chatcmpl-1", + Model: "glm-5.2", + Choices: []ChatChunkChoice{{ + Index: 0, + Delta: ChatDelta{}, + FinishReason: strPtr("tool_calls"), + }}, + } + + // Feed chunks through the CC→Responses bridge, then through Responses→Anthropic. + var allAnthropicEvents []AnthropicStreamEvent + for _, chunk := range []*ChatCompletionsChunk{chatChunk1, chatChunk2, chatChunk3} { + responsesEvents := ChatCompletionsChunkToResponsesEvents(chunk, ccState) + for _, rEvent := range responsesEvents { + allAnthropicEvents = append(allAnthropicEvents, ResponsesEventToAnthropicEvents(&rEvent, anthropicState)...) + } + } + + // Finalize: closeChatToolItems emits function_call_arguments.done for each tool. + finalResponsesEvents := FinalizeChatCompletionsResponsesStream(ccState) + for _, rEvent := range finalResponsesEvents { + allAnthropicEvents = append(allAnthropicEvents, ResponsesEventToAnthropicEvents(&rEvent, anthropicState)...) + } + + // Build the set of block indices that were content_block_start'ed. + startedBlocks := make(map[int]string) // index → block type + for _, e := range allAnthropicEvents { + if e.Type == "content_block_start" && e.ContentBlock != nil { + startedBlocks[*e.Index] = e.ContentBlock.Type + } + } + + // Assert: every content_block_delta targets a started block (no ghost deltas). + for _, e := range allAnthropicEvents { + if e.Type != "content_block_delta" || e.Index == nil { + continue + } + idx := *e.Index + _, ok := startedBlocks[idx] + require.Truef(t, ok, + "content_block_delta on index %d which was never content_block_start'ed (ghost delta bug #4193)", idx) + } + + // Assert: every content_block_stop targets a started block. + for _, e := range allAnthropicEvents { + if e.Type != "content_block_stop" || e.Index == nil { + continue + } + idx := *e.Index + _, ok := startedBlocks[idx] + require.Truef(t, ok, + "content_block_stop on index %d which was never content_block_start'ed", idx) + } + + // Assert: both tool_use blocks were opened. + var toolUseBlocks []int + for idx, blockType := range startedBlocks { + if blockType == "tool_use" { + toolUseBlocks = append(toolUseBlocks, idx) + } + } + assert.Len(t, toolUseBlocks, 2, "both parallel tool_use blocks should be opened") + + // Assert: stop_reason is tool_use. + var sawMessageDelta bool + for _, e := range allAnthropicEvents { + if e.Type == "message_delta" { + sawMessageDelta = true + assert.Equal(t, "tool_use", e.Delta.StopReason) + } + } + assert.True(t, sawMessageDelta, "message_delta should be emitted") +} + +// TestStreamingParallelToolUseSecondToolPackedArgsDone is a focused unit test +// for the exact bug: two tools, the first streams its arguments via deltas +// (CurrentToolHadDelta=true → closeCurrentBlock), the second has arguments +// packed only in .done (CurrentToolHadDelta=false). Before the fix, the second +// tool's .done emitted content_block_delta on state.ContentBlockIndex which +// had already been incremented past the second tool's block. +func TestStreamingParallelToolUseSecondToolPackedArgsDone(t *testing.T) { + state := NewResponsesEventToAnthropicState() + + // response.created + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.created", + Response: &ResponsesResponse{ID: "resp_par", Model: "glm-5.2"}, + }, state) + + // Tool 1: output_item.added (index 0) + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.output_item.added", + OutputIndex: 0, + Item: &ResponsesOutput{Type: "function_call", CallID: "call_a", Name: "tool_a"}, + }, state) + + // Tool 1: arguments streamed via delta (CurrentToolHadDelta = true) + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.function_call_arguments.delta", + OutputIndex: 0, + Delta: `{"x":1}`, + }, state) + + // Tool 1: arguments.done → CurrentToolHadDelta=true → closeCurrentBlock + // ContentBlockIndex goes from 0 → 1 + eventsTool1Done := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.function_call_arguments.done", + OutputIndex: 0, + Arguments: `{"x":1}`, + }, state) + // Should only emit content_block_stop (delta already streamed) + for _, e := range eventsTool1Done { + assert.NotEqual(t, "content_block_delta", e.Type, + "tool 1 .done should not re-emit delta (args already streamed)") + } + + // Tool 2: output_item.added (index 1) → opens block at ContentBlockIndex=1 + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.output_item.added", + OutputIndex: 1, + Item: &ResponsesOutput{Type: "function_call", CallID: "call_b", Name: "tool_b"}, + }, state) + + // Tool 2: NO delta — arguments arrive packed in .done only. + // This is the exact scenario that triggered the ghost delta bug. + eventsTool2Done := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.function_call_arguments.done", + OutputIndex: 1, + Arguments: `{"y":2}`, + }, state) + + // The fix ensures the delta targets index 1 (the tool 2 block), not + // state.ContentBlockIndex (which would be 1 before close, matching by + // luck in this 2-tool case, but wrong in 3+ tool cases or when the + // block is already closed). + // + // The critical assertion: the delta must be on index 1 and must be + // followed by content_block_stop on the same index. + var sawDelta, sawStop bool + var deltaIndex, stopIndex int + for _, e := range eventsTool2Done { + if e.Type == "content_block_delta" && e.Index != nil { + sawDelta = true + deltaIndex = *e.Index + assert.Equal(t, "input_json_delta", e.Delta.Type) + assert.Equal(t, `{"y":2}`, e.Delta.PartialJSON) + } + if e.Type == "content_block_stop" && e.Index != nil { + sawStop = true + stopIndex = *e.Index + } + } + assert.True(t, sawDelta, "tool 2 .done with packed args should emit content_block_delta") + assert.True(t, sawStop, "tool 2 .done should close the block") + assert.Equal(t, 1, deltaIndex, "delta must target the tool 2 block (index 1)") + assert.Equal(t, deltaIndex, stopIndex, "delta and stop must be on the same block") +} + +// TestStreamingThreeParallelToolsAllPackedDone tests the most extreme case: +// three parallel tools, ALL with arguments packed in .done (no deltas at all). +// Before the fix, tool 2 and tool 3 would emit ghost deltas on wrong indices. +func TestStreamingThreeParallelToolsAllPackedDone(t *testing.T) { + state := NewResponsesEventToAnthropicState() + + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.created", + Response: &ResponsesResponse{ID: "resp_3par", Model: "glm-5.2"}, + }, state) + + // Open three tool blocks at indices 0, 1, 2. + for i, name := range []string{"tool_a", "tool_b", "tool_c"} { + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.output_item.added", + OutputIndex: i, + Item: &ResponsesOutput{Type: "function_call", CallID: "call_" + name, Name: name}, + }, state) + } + + // Track started blocks. + started := map[int]bool{0: true, 1: true, 2: true} + + // All three .done events with packed arguments (no prior delta). + for i, args := range []string{`{"a":1}`, `{"b":2}`, `{"c":3}`} { + events := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.function_call_arguments.done", + OutputIndex: i, + Arguments: args, + }, state) + + for _, e := range events { + if e.Type == "content_block_delta" && e.Index != nil { + idx := *e.Index + require.Truef(t, started[idx], + "ghost delta: tool %d .done emitted content_block_delta on index %d (never started)", i, idx) + require.Equal(t, i, idx, + "tool %d .done delta should target its own block index %d, got %d", i, i, idx) + } + if e.Type == "content_block_stop" && e.Index != nil { + idx := *e.Index + require.Truef(t, started[idx], + "ghost stop: tool %d .done emitted content_block_stop on index %d (never started)", i, idx) + } + } + } +} diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic_read_tool_test.go b/backend/internal/pkg/apicompat/responses_to_anthropic_read_tool_test.go index 72b60099fe..0fc45b7249 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic_read_tool_test.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic_read_tool_test.go @@ -7,63 +7,93 @@ import ( "github.com/stretchr/testify/require" ) -func TestResToAnthFuncArgsDelta_ReadToolStreamsDeltas(t *testing.T) { +func TestResToAnthFuncArgsDelta_ReadToolWaitsForCompleteJSON(t *testing.T) { state := NewResponsesEventToAnthropicState() state.MessageStartSent = true - state.CurrentBlockType = "tool_use" - state.CurrentToolName = "Read" - state.OutputIndexToBlockIdx = map[int]int{0: 0} - - evt := &ResponsesStreamEvent{ - Type: "response.function_call_arguments.delta", - OutputIndex: 0, - Delta: `{"file_path":"/tmp/test.go"}`, - } - - events := ResponsesEventToAnthropicEvents(evt, state) - - require.Len(t, events, 1, "Read tool delta must produce content_block_delta") - assert.Equal(t, "content_block_delta", events[0].Type) - assert.Equal(t, "input_json_delta", events[0].Delta.Type) - assert.Equal(t, `{"file_path":"/tmp/test.go"}`, events[0].Delta.PartialJSON) - assert.True(t, state.CurrentToolHadDelta, "Read deltas should set CurrentToolHadDelta") -} - -func TestResToAnthFuncArgsDelta_ReadToolWithoutDone(t *testing.T) { - state := NewResponsesEventToAnthropicState() - state.MessageStartSent = true - state.ContentBlockIndex = 0 state.ContentBlockOpen = true state.CurrentBlockType = "tool_use" state.CurrentToolName = "Read" state.OutputIndexToBlockIdx = map[int]int{0: 0} - delta := &ResponsesStreamEvent{ + events := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ Type: "response.function_call_arguments.delta", OutputIndex: 0, - Delta: `{"file_path":"/tmp/test.go"}`, - } - events := ResponsesEventToAnthropicEvents(delta, state) - require.Len(t, events, 1, "delta should be streamed") + Delta: `{"file_path":"/tmp/te`, + }, state) + assert.Empty(t, events, "partial Read JSON must wait for sanitization") + assert.False(t, state.CurrentToolHadDelta) - completed := &ResponsesStreamEvent{ + events = ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.function_call_arguments.delta", + OutputIndex: 0, + Delta: `st.go","pages":""}`, + }, state) + require.Len(t, events, 1) + assert.Equal(t, "content_block_delta", events[0].Type) + assert.Equal(t, "input_json_delta", events[0].Delta.Type) + assert.JSONEq(t, `{"file_path":"/tmp/test.go"}`, events[0].Delta.PartialJSON) + assert.Equal(t, `{"file_path":"/tmp/test.go","pages":""}`, state.CurrentToolArgs) + assert.True(t, state.CurrentToolHadDelta) + + events = ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.function_call_arguments.done", + OutputIndex: 0, + Arguments: `{"file_path":"/tmp/test.go","pages":""}`, + }, state) + require.Len(t, events, 1) + assert.Equal(t, "content_block_stop", events[0].Type) + + events = ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.function_call_arguments.done", + OutputIndex: 0, + Arguments: `{"file_path":"/tmp/test.go","pages":""}`, + }, state) + assert.Empty(t, events, "duplicate done must be idempotent") +} + +func TestResponsesEventToAnthropicEvents_ReadToolWithoutArgumentsDoneClosesOnCompleted(t *testing.T) { + state := NewResponsesEventToAnthropicState() + + events := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.created", + Response: &ResponsesResponse{ID: "resp_read", Model: "gpt-5.5"}, + }, state) + require.Len(t, events, 1) + assert.Equal(t, "message_start", events[0].Type) + + events = ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.output_item.added", + OutputIndex: 0, + Item: &ResponsesOutput{Type: "function_call", CallID: "call_read", Name: "Read"}, + }, state) + require.Len(t, events, 1) + assert.Equal(t, "content_block_start", events[0].Type) + + events = ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.function_call_arguments.delta", + OutputIndex: 0, + Delta: `{"file_path":"/tmp/test.go","pages":""}`, + }, state) + require.Len(t, events, 1) + assert.Equal(t, "content_block_delta", events[0].Type) + assert.Equal(t, "input_json_delta", events[0].Delta.Type) + assert.JSONEq(t, `{"file_path":"/tmp/test.go"}`, events[0].Delta.PartialJSON) + + events = ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ Type: "response.completed", Response: &ResponsesResponse{ Status: "completed", }, - } - events = ResponsesEventToAnthropicEvents(completed, state) - - hasStop := false - for _, e := range events { - if e.Type == "content_block_stop" { - hasStop = true - } - } - assert.True(t, hasStop, "block should be closed even without .done event") + }, state) + require.Len(t, events, 3) + assert.Equal(t, "content_block_stop", events[0].Type) + assert.Equal(t, "message_delta", events[1].Type) + assert.Equal(t, "tool_use", events[1].Delta.StopReason) + assert.Equal(t, "message_stop", events[2].Type) + assert.Empty(t, FinalizeResponsesAnthropicStream(state), "terminal event already finalized the stream") } -func TestResToAnthFuncArgsDelta_NonReadToolUnchanged(t *testing.T) { +func TestResToAnthFuncArgsDelta_NonReadToolStreamsPartialJSONImmediately(t *testing.T) { state := NewResponsesEventToAnthropicState() state.MessageStartSent = true state.CurrentBlockType = "tool_use" @@ -73,12 +103,13 @@ func TestResToAnthFuncArgsDelta_NonReadToolUnchanged(t *testing.T) { evt := &ResponsesStreamEvent{ Type: "response.function_call_arguments.delta", OutputIndex: 0, - Delta: `{"file_path":"/tmp/out.txt","content":"hello"}`, + Delta: `{"file_path":"/tmp/out`, } events := ResponsesEventToAnthropicEvents(evt, state) require.Len(t, events, 1) assert.Equal(t, "content_block_delta", events[0].Type) + assert.Equal(t, `{"file_path":"/tmp/out`, events[0].Delta.PartialJSON) assert.True(t, state.CurrentToolHadDelta) } diff --git a/backend/internal/pkg/apicompat/streaming_stop_reason_test.go b/backend/internal/pkg/apicompat/streaming_stop_reason_test.go index c2889f0251..7147e90105 100644 --- a/backend/internal/pkg/apicompat/streaming_stop_reason_test.go +++ b/backend/internal/pkg/apicompat/streaming_stop_reason_test.go @@ -44,6 +44,29 @@ func TestAnthropicStreamingMaxTokens_MapsToIncomplete(t *testing.T) { assert.Equal(t, "max_output_tokens", completed.Response.IncompleteDetails.Reason) } +func TestAnthropicStreamingMaxTokens_FinalizeMapsToIncompleteWithoutMessageStop(t *testing.T) { + state := NewAnthropicEventToResponsesState() + + AnthropicEventToResponsesEvents(&AnthropicStreamEvent{ + Type: "message_start", + Message: &AnthropicResponse{ID: "msg_test", Model: "claude-opus-4-6", Role: "assistant"}, + }, state) + AnthropicEventToResponsesEvents(&AnthropicStreamEvent{ + Type: "message_delta", + Delta: &AnthropicDelta{StopReason: "max_tokens"}, + Usage: &AnthropicUsage{OutputTokens: 4096}, + }, state) + + events := FinalizeAnthropicResponsesStream(state) + require.Len(t, events, 1) + assert.Equal(t, "response.incomplete", events[0].Type) + require.NotNil(t, events[0].Response) + assert.Equal(t, "incomplete", events[0].Response.Status) + require.NotNil(t, events[0].Response.IncompleteDetails) + assert.Equal(t, "max_output_tokens", events[0].Response.IncompleteDetails.Reason) + assert.Empty(t, FinalizeAnthropicResponsesStream(state), "repeated finalization must be idempotent") +} + func TestAnthropicStreamingEndTurn_MapsToCompleted(t *testing.T) { state := NewAnthropicEventToResponsesState() diff --git a/backend/internal/pkg/servertiming/collector.go b/backend/internal/pkg/servertiming/collector.go index 553edede31..060d4458cb 100644 --- a/backend/internal/pkg/servertiming/collector.go +++ b/backend/internal/pkg/servertiming/collector.go @@ -13,6 +13,7 @@ import ( const ( HeaderName = "Server-Timing" AdminUIHeader = "X-Admin-UI-Request" + UserUIHeader = "X-User-UI-Request" MetricDatabase = "db" MetricRedis = "redis" dependencyPrefix = "dep_" diff --git a/backend/internal/pkg/xai/oauth.go b/backend/internal/pkg/xai/oauth.go index a8a549c9dc..3d32bb963d 100644 --- a/backend/internal/pkg/xai/oauth.go +++ b/backend/internal/pkg/xai/oauth.go @@ -5,6 +5,7 @@ import ( "crypto/sha256" "encoding/base64" "encoding/hex" + "errors" "fmt" "net/url" "os" @@ -164,6 +165,24 @@ func ValidatedBaseURL(override string) (string, error) { return ValidateBaseURL(EffectiveBaseURL(override)) } +// BaseURLValidator applies the caller's outbound URL trust policy before xAI +// endpoint paths are appended. The service layer uses this for API-key accounts +// so the global security.url_allowlist policy remains the single source of +// truth; OAuth callers keep using the strict trusted-host validator. +type BaseURLValidator func(string) (string, error) + +func validatedBaseURLWithValidator(override string, validator BaseURLValidator) (string, error) { + if validator == nil { + return ValidatedBaseURL(override) + } + raw := EffectiveBaseURL(override) + validated, err := validator(raw) + if err != nil { + return "", err + } + return normalizeKnownBaseURLPath(validated) +} + type RuntimeSanityCheck struct { Value string `json:"value"` Valid bool `json:"valid"` @@ -282,7 +301,16 @@ func ValidateTrustedBaseURL(raw string) (string, error) { func normalizeKnownBaseURLPath(raw string) (string, error) { parsed, err := url.Parse(raw) if err != nil || parsed.Scheme == "" || parsed.Host == "" { - return "", fmt.Errorf("invalid url: %s", raw) + return "", errors.New("invalid base URL") + } + if parsed.User != nil { + return "", errors.New("base URL must not include userinfo") + } + if parsed.ForceQuery || parsed.RawQuery != "" { + return "", errors.New("base URL must not include a query") + } + if parsed.Fragment != "" { + return "", errors.New("base URL must not include a fragment") } path := strings.TrimRight(parsed.Path, "/") if path == "" { @@ -435,7 +463,11 @@ func ParseAuthorizationInput(raw string) AuthorizationInput { } func BuildResponsesURL(baseURL string) (string, error) { - validatedBaseURL, err := ValidatedBaseURL(baseURL) + return BuildResponsesURLWithValidator(baseURL, nil) +} + +func BuildResponsesURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) { + validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator) if err != nil { return "", fmt.Errorf("invalid base url: %w", err) } @@ -443,7 +475,11 @@ func BuildResponsesURL(baseURL string) (string, error) { } func BuildChatCompletionsURL(baseURL string) (string, error) { - validatedBaseURL, err := ValidatedBaseURL(baseURL) + return BuildChatCompletionsURLWithValidator(baseURL, nil) +} + +func BuildChatCompletionsURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) { + validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator) if err != nil { return "", fmt.Errorf("invalid base url: %w", err) } @@ -451,7 +487,11 @@ func BuildChatCompletionsURL(baseURL string) (string, error) { } func BuildImagesGenerationsURL(baseURL string) (string, error) { - validatedBaseURL, err := ValidatedBaseURL(baseURL) + return BuildImagesGenerationsURLWithValidator(baseURL, nil) +} + +func BuildImagesGenerationsURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) { + validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator) if err != nil { return "", fmt.Errorf("invalid base url: %w", err) } @@ -459,7 +499,11 @@ func BuildImagesGenerationsURL(baseURL string) (string, error) { } func BuildImagesEditsURL(baseURL string) (string, error) { - validatedBaseURL, err := ValidatedBaseURL(baseURL) + return BuildImagesEditsURLWithValidator(baseURL, nil) +} + +func BuildImagesEditsURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) { + validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator) if err != nil { return "", fmt.Errorf("invalid base url: %w", err) } @@ -467,7 +511,11 @@ func BuildImagesEditsURL(baseURL string) (string, error) { } func BuildVideosGenerationsURL(baseURL string) (string, error) { - validatedBaseURL, err := ValidatedBaseURL(baseURL) + return BuildVideosGenerationsURLWithValidator(baseURL, nil) +} + +func BuildVideosGenerationsURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) { + validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator) if err != nil { return "", fmt.Errorf("invalid base url: %w", err) } @@ -475,7 +523,11 @@ func BuildVideosGenerationsURL(baseURL string) (string, error) { } func BuildVideosEditsURL(baseURL string) (string, error) { - validatedBaseURL, err := ValidatedBaseURL(baseURL) + return BuildVideosEditsURLWithValidator(baseURL, nil) +} + +func BuildVideosEditsURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) { + validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator) if err != nil { return "", fmt.Errorf("invalid base url: %w", err) } @@ -483,7 +535,11 @@ func BuildVideosEditsURL(baseURL string) (string, error) { } func BuildVideosExtensionsURL(baseURL string) (string, error) { - validatedBaseURL, err := ValidatedBaseURL(baseURL) + return BuildVideosExtensionsURLWithValidator(baseURL, nil) +} + +func BuildVideosExtensionsURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) { + validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator) if err != nil { return "", fmt.Errorf("invalid base url: %w", err) } @@ -491,7 +547,11 @@ func BuildVideosExtensionsURL(baseURL string) (string, error) { } func BuildVideoURL(baseURL, requestID string) (string, error) { - validatedBaseURL, err := ValidatedBaseURL(baseURL) + return BuildVideoURLWithValidator(baseURL, requestID, nil) +} + +func BuildVideoURLWithValidator(baseURL, requestID string, validator BaseURLValidator) (string, error) { + validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator) if err != nil { return "", fmt.Errorf("invalid base url: %w", err) } diff --git a/backend/internal/pkg/xai/oauth_test.go b/backend/internal/pkg/xai/oauth_test.go index 39200ffc39..f91b5d4937 100644 --- a/backend/internal/pkg/xai/oauth_test.go +++ b/backend/internal/pkg/xai/oauth_test.go @@ -6,6 +6,7 @@ import ( "net/url" "testing" + "github.com/Wei-Shaw/sub2api/internal/util/urlvalidator" "github.com/stretchr/testify/require" ) @@ -165,6 +166,53 @@ func TestValidateBaseURLAllowsPublicThirdPartyGrokAPI(t *testing.T) { require.Error(t, err) } +func TestValidateBaseURLsRejectEmptyQueryDelimiter(t *testing.T) { + _, err := ValidateBaseURL("https://grok.example.test/v1?") + require.Error(t, err) + + _, err = ValidateTrustedBaseURL("https://api.x.ai/v1?") + require.Error(t, err) +} + +func TestBuildResponsesURLWithValidatorUsesCallerPolicy(t *testing.T) { + validator := func(raw string) (string, error) { + return urlvalidator.ValidateURLFormat(raw, true) + } + + target, err := BuildResponsesURLWithValidator("http://grok.example.test/v1/", validator) + require.NoError(t, err) + require.Equal(t, "http://grok.example.test/v1/responses", target) +} + +func TestBuildResponsesURLPreservesUnsafeOverrideCustomPath(t *testing.T) { + t.Setenv(EnvAllowUnsafeURLOverrides, "true") + + target, err := BuildResponsesURL("http://localhost:8080/custom") + require.NoError(t, err) + require.Equal(t, "http://localhost:8080/custom/responses", target) +} + +func TestBuildResponsesURLWithValidatorRejectsBaseURLComponents(t *testing.T) { + permissive := func(raw string) (string, error) { return raw, nil } + tests := []struct { + name string + raw string + }{ + {name: "userinfo", raw: "https://user:secret@grok.example.test/v1"}, + {name: "query", raw: "https://grok.example.test/v1?token=secret"}, + {name: "empty query delimiter", raw: "https://grok.example.test/v1?"}, + {name: "fragment", raw: "https://grok.example.test/v1#secret"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := BuildResponsesURLWithValidator(tt.raw, permissive) + require.Error(t, err) + require.NotContains(t, err.Error(), "secret") + }) + } +} + func TestValidateXAIURLsAllowUnsafeDevOverride(t *testing.T) { t.Setenv(EnvAllowUnsafeURLOverrides, "true") diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index 8eb819aeab..04beff8c62 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -73,6 +73,12 @@ func NewAccountRepository(client *dbent.Client, sqlDB *sql.DB, schedulerCache se return newAccountRepositoryWithSQL(client, sqlDB, schedulerCache) } +// NewAdminAccountRepository exposes the account repository's atomic duplication capability +// as an explicit dependency of the admin service. +func NewAdminAccountRepository(client *dbent.Client, sqlDB *sql.DB, schedulerCache service.SchedulerCache) service.AdminAccountRepository { + return newAccountRepositoryWithSQL(client, sqlDB, schedulerCache) +} + // newAccountRepositoryWithSQL 是内部构造函数,支持依赖注入 SQL 执行器。 // 这种设计便于单元测试时注入 mock 对象。 func newAccountRepositoryWithSQL(client *dbent.Client, sqlq sqlExecutor, schedulerCache service.SchedulerCache) *accountRepository { @@ -80,11 +86,21 @@ func newAccountRepositoryWithSQL(client *dbent.Client, sqlq sqlExecutor, schedul } func (r *accountRepository) Create(ctx context.Context, account *service.Account) error { + if err := createAccountRecord(ctx, r.client, account); err != nil { + return err + } + if err := enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventAccountChanged, &account.ID, nil, buildSchedulerGroupPayload(account.GroupIDs)); err != nil { + logger.LegacyPrintf("repository.account", "[SchedulerOutbox] enqueue account create failed: account=%d err=%v", account.ID, err) + } + return nil +} + +func createAccountRecord(ctx context.Context, client *dbent.Client, account *service.Account) error { if account == nil { return service.ErrAccountNilInput } - builder := r.client.Account.Create(). + builder := client.Account.Create(). SetName(account.Name). SetNillableNotes(account.Notes). SetPlatform(account.Platform). @@ -146,8 +162,58 @@ func (r *accountRepository) Create(ctx context.Context, account *service.Account account.ID = created.ID account.CreatedAt = created.CreatedAt account.UpdatedAt = created.UpdatedAt - if err := enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventAccountChanged, &account.ID, nil, buildSchedulerGroupPayload(account.GroupIDs)); err != nil { - logger.LegacyPrintf("repository.account", "[SchedulerOutbox] enqueue account create failed: account=%d err=%v", account.ID, err) + return nil +} + +// CreateWithAccountGroups atomically persists an account, its exact per-group priorities, +// and the scheduler outbox event used to publish the new routing snapshot. +func (r *accountRepository) CreateWithAccountGroups(ctx context.Context, account *service.Account, groups []service.AccountGroup) error { + if account == nil { + return service.ErrAccountNilInput + } + tx, err := r.client.Tx(ctx) + if err != nil && !errors.Is(err, dbent.ErrTxStarted) { + return err + } + + var txClient *dbent.Client + if err == nil { + defer func() { _ = tx.Rollback() }() + txClient = tx.Client() + } else { + // Reuse a caller-owned transaction when this repository is already transactional. + txClient = r.client + } + + if err := createAccountRecord(ctx, txClient, account); err != nil { + return err + } + groupIDs := make([]int64, 0, len(groups)) + if len(groups) > 0 { + builders := make([]*dbent.AccountGroupCreate, 0, len(groups)) + for i := range groups { + groups[i].AccountID = account.ID + groupIDs = append(groupIDs, groups[i].GroupID) + builders = append(builders, txClient.AccountGroup.Create(). + SetAccountID(account.ID). + SetGroupID(groups[i].GroupID). + SetPriority(groups[i].Priority), + ) + } + if _, err := txClient.AccountGroup.CreateBulk(builders...).Save(ctx); err != nil { + return err + } + } + account.GroupIDs = groupIDs + account.AccountGroups = append([]service.AccountGroup(nil), groups...) + if err := enqueueSchedulerOutbox(ctx, txClient, service.SchedulerOutboxEventAccountChanged, &account.ID, nil, buildSchedulerGroupPayload(groupIDs)); err != nil { + return err + } + + if tx != nil { + if err := tx.Commit(); err != nil { + return err + } } return nil } @@ -433,6 +499,9 @@ func (r *accountRepository) UpdateCredentials(ctx context.Context, id int64, cre if err != nil { return translatePersistenceError(err, service.ErrAccountNotFound, nil) } + if err := enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventAccountChanged, &id, nil, nil); err != nil { + logger.LegacyPrintf("repository.account", "[SchedulerOutbox] enqueue credentials update failed: account=%d err=%v", id, err) + } r.syncSchedulerAccountSnapshot(ctx, id) return nil } @@ -717,29 +786,55 @@ func (r *accountRepository) ListActive(ctx context.Context) ([]service.Account, return r.accountsToService(ctx, accounts) } -func (r *accountRepository) ListOAuthRefreshCandidates(ctx context.Context) ([]service.Account, error) { +func (r *accountRepository) ListOAuthRefreshCandidatePage(ctx context.Context, options service.OAuthRefreshPageOptions) (*service.OAuthRefreshCandidatePage, error) { if r.sql == nil { return nil, errors.New("account repository SQL executor not configured") } + if len(options.Platforms) == 0 { + return nil, errors.New("oauth refresh candidate platforms cannot be empty") + } + if options.Limit <= 0 || options.Limit > 1000 { + return nil, errors.New("oauth refresh candidate page limit must be between 1 and 1000") + } + // (cond) IS NOT TRUE 把 NULL 和 FALSE 都视为"可被刷新"。直接写 // NOT (a AND b) 在 PG 三值逻辑下会把 a 或 b 为 NULL 的行(即绝大多数 // 健康账号:temp_unschedulable_until=NULL)也排除,导致后台 token // 刷新工作器漏掉所有正常账号 → access_token 到期后请求开始 401。 - rows, err := r.sql.QueryContext(ctx, ` + query := ` SELECT id FROM accounts WHERE deleted_at IS NULL - AND status = 'active' - AND type IN ('oauth', 'setup-token') - AND platform IN ('anthropic', 'openai', 'gemini', 'antigravity') + AND platform = ANY($1) + AND id > $2` + if options.ActiveOnly { + query += ` + AND status = 'active'` + } + if options.IncludeSetupToken { + query += ` + AND type IN ('oauth', 'setup-token')` + } else { + query += ` + AND type = 'oauth'` + } + if options.RequireRefreshToken { + query += ` AND credentials ? 'refresh_token' - AND btrim(credentials->>'refresh_token') <> '' + AND btrim(credentials->>'refresh_token') <> ''` + } + if options.ExcludeRetryCooldown { + query += ` AND ( temp_unschedulable_until > NOW() AND temp_unschedulable_reason LIKE 'token refresh retry exhausted:%' - ) IS NOT TRUE - ORDER BY priority ASC, id ASC - `) + ) IS NOT TRUE` + } + query += ` + ORDER BY id ASC + LIMIT $3` + + rows, err := r.sql.QueryContext(ctx, query, pq.Array(options.Platforms), options.AfterID, options.Limit) if err != nil { return nil, err } @@ -757,20 +852,33 @@ func (r *accountRepository) ListOAuthRefreshCandidates(ctx context.Context) ([]s return nil, err } if len(ids) == 0 { - return []service.Account{}, nil + return &service.OAuthRefreshCandidatePage{Accounts: []service.Account{}}, nil } accounts, err := r.GetByIDs(ctx, ids) if err != nil { return nil, err } - out := make([]service.Account, 0, len(accounts)) + accountsByID := make(map[int64]*service.Account, len(accounts)) for _, account := range accounts { if account != nil { + accountsByID[account.ID] = account + } + } + out := make([]service.Account, 0, len(accounts)) + for _, id := range ids { + if account := accountsByID[id]; account != nil { out = append(out, *account) } } - return out, nil + page := &service.OAuthRefreshCandidatePage{ + Accounts: out, + HasMore: len(ids) == options.Limit, + } + if len(ids) > 0 { + page.NextAfterID = ids[len(ids)-1] + } + return page, nil } func (r *accountRepository) ListByPlatform(ctx context.Context, platform string) ([]service.Account, error) { @@ -859,6 +967,297 @@ func (r *accountRepository) SetError(ctx context.Context, id int64, errorMsg str return nil } +func (r *accountRepository) SetGrokCredentialErrorIfMatch( + ctx context.Context, + id int64, + snapshot service.GrokCredentialMutationSnapshot, + errorMsg string, +) (bool, error) { + result, err := r.sql.ExecContext(ctx, ` + WITH updated AS ( + UPDATE accounts AS a + SET status = $1, + error_message = $2, + schedulable = false, + updated_at = NOW() + WHERE a.id = $3 + AND a.deleted_at IS NULL + AND a.status = $4 + AND a.platform = $5 + AND a.type = $6 + AND a.schedulable IS TRUE + AND (a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until <= NOW()) + AND (a.rate_limit_reset_at IS NULL OR a.rate_limit_reset_at <= NOW()) + AND (a.overload_until IS NULL OR a.overload_until <= NOW()) + AND (a.auto_pause_on_expired IS NOT TRUE OR a.expires_at IS NULL OR a.expires_at > NOW()) + AND a.credentials = $7::jsonb + AND a.proxy_id IS NOT DISTINCT FROM $8 + AND ($2 <> $9 OR ( + a.proxy_id IS NOT NULL AND NOT EXISTS ( + SELECT 1 FROM proxies p WHERE p.id = a.proxy_id AND p.deleted_at IS NULL + ) + )) + RETURNING a.id + ) + INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload) + SELECT $10, updated.id, NULL, NULL FROM updated + `, service.StatusError, errorMsg, id, service.StatusActive, service.PlatformGrok, service.AccountTypeOAuth, + snapshot.CredentialsJSON, snapshot.ProxyID, string(service.GrokCredentialReasonProxyInvalid), + service.SchedulerOutboxEventAccountChanged) + if err != nil { + return false, err + } + affected, err := result.RowsAffected() + if err != nil || affected == 0 { + return false, err + } + r.syncSchedulerAccountSnapshotDetached(ctx, id) + return true, nil +} + +// SetGrokOAuthErrorIfCredentialsUnchanged atomically quarantines a structurally +// invalid Grok OAuth account only if it is still active and its complete JSONB +// credential document matches the state observed by reconciliation. Exact +// JSONB equality includes _token_version when present and prevents a concurrent +// reauthorization from being overwritten by a stale check-then-mutate path. +func (r *accountRepository) SetGrokOAuthErrorIfCredentialsUnchanged( + ctx context.Context, + id int64, + expectedCredentials map[string]any, + errorMsg string, +) (bool, error) { + if r == nil || r.sql == nil { + return false, errors.New("account repository SQL executor is not configured") + } + expectedJSON, err := json.Marshal(normalizeJSONMap(expectedCredentials)) + if err != nil { + return false, err + } + result, err := r.sql.ExecContext(ctx, ` + WITH updated AS ( + UPDATE accounts AS a + SET status = $1, + error_message = $2, + schedulable = FALSE, + updated_at = NOW() + WHERE a.id = $3 + AND a.deleted_at IS NULL + AND a.platform = $4 + AND a.type = $5 + AND a.status = $6 + AND a.credentials = $7::jsonb + AND NULLIF(BTRIM(a.credentials->>'refresh_token'), '') IS NULL + RETURNING a.id + ) + INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload) + SELECT $8, updated.id, NULL, NULL FROM updated + `, + service.StatusError, + errorMsg, + id, + service.PlatformGrok, + service.AccountTypeOAuth, + service.StatusActive, + string(expectedJSON), + service.SchedulerOutboxEventAccountChanged, + ) + if err != nil { + return false, err + } + rowsAffected, err := result.RowsAffected() + if err != nil { + return false, err + } + if rowsAffected == 0 { + return false, nil + } + r.syncSchedulerAccountSnapshotDetached(ctx, id) + return true, nil +} + +// UpdateGrokOAuthCredentialsIfUnchanged persists provider-issued replacement +// credentials only while the complete Grok OAuth credential document and +// proxy still match the fresh snapshot used by the upstream refresh call. The +// scheduler outbox insert is part of the same PostgreSQL statement, so a +// durable invalidation failure rolls the credential update back as well. +func (r *accountRepository) UpdateGrokOAuthCredentialsIfUnchanged( + ctx context.Context, + id int64, + expectedCredentials map[string]any, + expectedProxyID *int64, + credentials map[string]any, +) (bool, error) { + if r == nil || r.sql == nil { + return false, errors.New("account repository SQL executor is not configured") + } + expectedJSON, err := json.Marshal(normalizeJSONMap(expectedCredentials)) + if err != nil { + return false, err + } + credentialsJSON, err := json.Marshal(normalizeJSONMap(credentials)) + if err != nil { + return false, err + } + result, err := r.sql.ExecContext(ctx, ` + WITH updated AS ( + UPDATE accounts AS a + SET credentials = $1::jsonb, + updated_at = NOW() + WHERE a.id = $2 + AND a.deleted_at IS NULL + AND a.platform = $3 + AND a.type = $4 + AND a.credentials = $5::jsonb + AND a.proxy_id IS NOT DISTINCT FROM $6 + RETURNING a.id + ) + INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload) + SELECT $7, updated.id, NULL, NULL FROM updated + `, + string(credentialsJSON), + id, + service.PlatformGrok, + service.AccountTypeOAuth, + string(expectedJSON), + expectedProxyID, + service.SchedulerOutboxEventAccountChanged, + ) + if err != nil { + return false, err + } + rowsAffected, err := result.RowsAffected() + if err != nil { + return false, err + } + if rowsAffected == 0 { + return false, nil + } + r.syncSchedulerAccountSnapshotDetached(ctx, id) + return true, nil +} + +// SetGrokOAuthRefreshErrorIfCredentialsUnchanged is the background-refresh +// counterpart to reconciliation's stricter missing-refresh-token mutation. It +// matches the complete credential document used by the failed upstream attempt +// but deliberately does not require the refresh token to be absent. +func (r *accountRepository) SetGrokOAuthRefreshErrorIfCredentialsUnchanged( + ctx context.Context, + id int64, + expectedCredentials map[string]any, + expectedProxyID *int64, + errorMsg string, +) (bool, error) { + if r == nil || r.sql == nil { + return false, errors.New("account repository SQL executor is not configured") + } + expectedJSON, err := json.Marshal(normalizeJSONMap(expectedCredentials)) + if err != nil { + return false, err + } + result, err := r.sql.ExecContext(ctx, ` + WITH updated AS ( + UPDATE accounts AS a + SET status = $1, + error_message = $2, + schedulable = FALSE, + updated_at = NOW() + WHERE a.id = $3 + AND a.deleted_at IS NULL + AND a.platform = $4 + AND a.type = $5 + AND a.status = $6 + AND a.credentials = $7::jsonb + AND a.proxy_id IS NOT DISTINCT FROM $8 + RETURNING a.id + ) + INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload) + SELECT $9, updated.id, NULL, NULL FROM updated + `, + service.StatusError, + errorMsg, + id, + service.PlatformGrok, + service.AccountTypeOAuth, + service.StatusActive, + string(expectedJSON), + expectedProxyID, + service.SchedulerOutboxEventAccountChanged, + ) + if err != nil { + return false, err + } + rowsAffected, err := result.RowsAffected() + if err != nil { + return false, err + } + if rowsAffected == 0 { + return false, nil + } + r.syncSchedulerAccountSnapshotDetached(ctx, id) + return true, nil +} + +// SetGrokOAuthRefreshTempUnschedulableIfCredentialsUnchanged applies a bounded +// transient refresh quarantine only while the active Grok OAuth credential +// document still matches the exact upstream attempt. +func (r *accountRepository) SetGrokOAuthRefreshTempUnschedulableIfCredentialsUnchanged( + ctx context.Context, + id int64, + expectedCredentials map[string]any, + expectedProxyID *int64, + until time.Time, + reason string, +) (bool, error) { + if r == nil || r.sql == nil { + return false, errors.New("account repository SQL executor is not configured") + } + expectedJSON, err := json.Marshal(normalizeJSONMap(expectedCredentials)) + if err != nil { + return false, err + } + result, err := r.sql.ExecContext(ctx, ` + WITH updated AS ( + UPDATE accounts AS a + SET temp_unschedulable_until = $1, + temp_unschedulable_reason = $2, + updated_at = NOW() + WHERE a.id = $3 + AND a.deleted_at IS NULL + AND a.platform = $4 + AND a.type = $5 + AND a.status = $6 + AND a.credentials = $7::jsonb + AND a.proxy_id IS NOT DISTINCT FROM $8 + AND (a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until < $1) + RETURNING a.id + ) + INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload) + SELECT $9, updated.id, NULL, NULL FROM updated + `, + until, + reason, + id, + service.PlatformGrok, + service.AccountTypeOAuth, + service.StatusActive, + string(expectedJSON), + expectedProxyID, + service.SchedulerOutboxEventAccountChanged, + ) + if err != nil { + return false, err + } + rowsAffected, err := result.RowsAffected() + if err != nil { + return false, err + } + if rowsAffected == 0 { + return false, nil + } + r.syncSchedulerAccountSnapshotDetached(ctx, id) + return true, nil +} + // syncSchedulerAccountSnapshot 在账号状态变更时主动同步快照到调度器缓存。 // 当账号被设置为错误、禁用、不可调度或临时不可调度时调用, // 确保调度器和粘性会话逻辑能及时感知账号的最新状态,避免继续使用不可用账号。 @@ -881,6 +1280,16 @@ func (r *accountRepository) syncSchedulerAccountSnapshot(ctx context.Context, ac } } +func (r *accountRepository) syncSchedulerAccountSnapshotDetached(ctx context.Context, accountID int64) { + base := context.Background() + if ctx != nil { + base = context.WithoutCancel(ctx) + } + propagationCtx, cancel := context.WithTimeout(base, 2*time.Second) + defer cancel() + r.syncSchedulerAccountSnapshot(propagationCtx, accountID) +} + func (r *accountRepository) deleteSchedulerAccountSnapshot(ctx context.Context, accountID int64) { if r == nil || r.schedulerCache == nil || accountID <= 0 { return @@ -1050,8 +1459,42 @@ func (r *accountRepository) BindGroups(ctx context.Context, accountID int64, gro } func (r *accountRepository) ListSchedulable(ctx context.Context) ([]service.Account, error) { - now := time.Now() - accounts, err := r.client.Account.Query(). + accounts, err := r.schedulableAccountsQuery(time.Now()).All(ctx) + if err != nil { + return nil, err + } + return r.accountsToService(ctx, accounts) +} + +func (r *accountRepository) ListSchedulableAccountLoads(ctx context.Context) ([]service.AccountWithConcurrency, error) { + accounts, err := r.schedulableAccountsQuery(time.Now()). + Select( + dbaccount.FieldID, + dbaccount.FieldConcurrency, + dbaccount.FieldLoadFactor, + ). + All(ctx) + if err != nil { + return nil, err + } + + loads := make([]service.AccountWithConcurrency, 0, len(accounts)) + for _, account := range accounts { + projection := service.Account{ + ID: account.ID, + Concurrency: account.Concurrency, + LoadFactor: account.LoadFactor, + } + loads = append(loads, service.AccountWithConcurrency{ + ID: account.ID, + MaxConcurrency: projection.EffectiveLoadFactor(), + }) + } + return loads, nil +} + +func (r *accountRepository) schedulableAccountsQuery(now time.Time) *dbent.AccountQuery { + return r.client.Account.Query(). Where( dbaccount.StatusEQ(service.StatusActive), dbaccount.SchedulableEQ(true), @@ -1060,12 +1503,7 @@ func (r *accountRepository) ListSchedulable(ctx context.Context) ([]service.Acco dbaccount.Or(dbaccount.OverloadUntilIsNil(), dbaccount.OverloadUntilLTE(now)), dbaccount.Or(dbaccount.RateLimitResetAtIsNil(), dbaccount.RateLimitResetAtLTE(now)), ). - Order(dbent.Asc(dbaccount.FieldPriority)). - All(ctx) - if err != nil { - return nil, err - } - return r.accountsToService(ctx, accounts) + Order(dbent.Asc(dbaccount.FieldPriority)) } func (r *accountRepository) ListSchedulableByGroupID(ctx context.Context, groupID int64) ([]service.Account, error) { @@ -1319,6 +1757,35 @@ func (r *accountRepository) SetRateLimitedIfLater(ctx context.Context, id int64, return nil } +// ClearRateLimitIfObserved clears exactly the Grok rate-limit generation seen +// by a successful request. Matching both timestamps prevents a stale success +// from erasing a later clear/re-arm generation with an equal or shorter reset. +func (r *accountRepository) ClearRateLimitIfObserved(ctx context.Context, id int64, observedLimitedAt, observedResetAt time.Time) (bool, error) { + updated, err := r.client.Account.Update(). + Where( + dbaccount.IDEQ(id), + dbaccount.PlatformEQ(service.PlatformGrok), + dbaccount.TypeEQ(service.AccountTypeOAuth), + dbaccount.RateLimitedAtEQ(observedLimitedAt), + dbaccount.RateLimitResetAtEQ(observedResetAt), + ). + ClearRateLimitedAt(). + ClearRateLimitResetAt(). + Save(ctx) + if err != nil { + return false, err + } + if updated == 0 { + r.syncSchedulerAccountSnapshot(ctx, id) + return false, nil + } + if err := enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventAccountChanged, &id, nil, nil); err != nil { + logger.LegacyPrintf("repository.account", "[SchedulerOutbox] enqueue observed rate-limit clear failed: account=%d err=%v", id, err) + } + r.syncSchedulerAccountSnapshot(ctx, id) + return true, nil +} + func (r *accountRepository) SetModelRateLimit(ctx context.Context, id int64, scope string, resetAt time.Time, reason ...string) error { if scope == "" { return nil @@ -1414,6 +1881,51 @@ func (r *accountRepository) SetTempUnschedulable(ctx context.Context, id int64, return nil } +func (r *accountRepository) SetGrokCredentialTempUnschedulableIfMatch( + ctx context.Context, + id int64, + snapshot service.GrokCredentialMutationSnapshot, + until time.Time, + reason string, +) (bool, error) { + result, err := r.sql.ExecContext(ctx, ` + WITH updated AS ( + UPDATE accounts AS a + SET temp_unschedulable_until = CASE + WHEN a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until < $1 THEN $1 + ELSE a.temp_unschedulable_until + END, + temp_unschedulable_reason = $2, + updated_at = NOW() + WHERE a.id = $3 + AND a.deleted_at IS NULL + AND a.status = $4 + AND a.platform = $5 + AND a.type = $6 + AND a.schedulable IS TRUE + AND (a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until <= NOW()) + AND (a.rate_limit_reset_at IS NULL OR a.rate_limit_reset_at <= NOW()) + AND (a.overload_until IS NULL OR a.overload_until <= NOW()) + AND (a.auto_pause_on_expired IS NOT TRUE OR a.expires_at IS NULL OR a.expires_at > NOW()) + AND a.credentials = $7::jsonb + AND a.proxy_id IS NOT DISTINCT FROM $8 + RETURNING a.id + ) + INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload) + SELECT $9, updated.id, NULL, NULL FROM updated + `, until, reason, id, service.StatusActive, service.PlatformGrok, service.AccountTypeOAuth, + snapshot.CredentialsJSON, snapshot.ProxyID, service.SchedulerOutboxEventAccountChanged) + if err != nil { + return false, err + } + affected, err := result.RowsAffected() + if err != nil || affected == 0 { + return false, err + } + r.syncSchedulerAccountSnapshotDetached(ctx, id) + return true, nil +} + func (r *accountRepository) ClearTempUnschedulable(ctx context.Context, id int64) error { _, err := r.sql.ExecContext(ctx, ` UPDATE accounts diff --git a/backend/internal/repository/account_repo_duplicate_integration_test.go b/backend/internal/repository/account_repo_duplicate_integration_test.go new file mode 100644 index 0000000000..f36ee1d45e --- /dev/null +++ b/backend/internal/repository/account_repo_duplicate_integration_test.go @@ -0,0 +1,73 @@ +//go:build integration + +package repository + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestCreateWithAccountGroupsPersistsPausedCopyAtomically(t *testing.T) { + ctx := context.Background() + client := testEntClient(t) + repo := newAccountRepositoryWithSQL(client, integrationDB, nil) + suffix := time.Now().UnixNano() + + group, err := client.Group.Create(). + SetName(fmt.Sprintf("duplicate-atomic-%d", suffix)). + SetPlatform(service.PlatformAnthropic). + Save(ctx) + require.NoError(t, err) + + success := &service.Account{ + Name: fmt.Sprintf("duplicate-success-%d", suffix), + Platform: service.PlatformAnthropic, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + Schedulable: false, + Credentials: map[string]any{"api_key": "secret"}, + Extra: map[string]any{}, + } + require.NoError(t, repo.CreateWithAccountGroups(ctx, success, []service.AccountGroup{{GroupID: group.ID, Priority: 37}})) + t.Cleanup(func() { + _, _ = integrationDB.ExecContext(context.Background(), "DELETE FROM scheduler_outbox WHERE account_id = $1", success.ID) + _, _ = integrationDB.ExecContext(context.Background(), "DELETE FROM account_groups WHERE account_id = $1", success.ID) + _, _ = integrationDB.ExecContext(context.Background(), "DELETE FROM accounts WHERE id = $1", success.ID) + _, _ = integrationDB.ExecContext(context.Background(), "DELETE FROM groups WHERE id = $1", group.ID) + }) + + var schedulable bool + require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT schedulable FROM accounts WHERE id = $1", success.ID).Scan(&schedulable)) + require.False(t, schedulable) + var priority int + require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT priority FROM account_groups WHERE account_id = $1 AND group_id = $2", success.ID, group.ID).Scan(&priority)) + require.Equal(t, 37, priority) + var outboxCount int + require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM scheduler_outbox WHERE account_id = $1", success.ID).Scan(&outboxCount)) + require.Equal(t, 1, outboxCount) + + failure := &service.Account{ + Name: fmt.Sprintf("duplicate-failure-%d", suffix), + Platform: service.PlatformAnthropic, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + Schedulable: false, + Credentials: map[string]any{"api_key": "secret"}, + Extra: map[string]any{}, + } + err = repo.CreateWithAccountGroups(ctx, failure, []service.AccountGroup{{GroupID: int64(^uint64(0) >> 1), Priority: 1}}) + require.Error(t, err) + + var accountCount, groupCount, failedOutboxCount int + require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM accounts WHERE name = $1", failure.Name).Scan(&accountCount)) + require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM account_groups WHERE account_id = $1", failure.ID).Scan(&groupCount)) + require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM scheduler_outbox WHERE account_id = $1", failure.ID).Scan(&failedOutboxCount)) + require.Zero(t, accountCount) + require.Zero(t, groupCount) + require.Zero(t, failedOutboxCount) +} diff --git a/backend/internal/repository/account_repo_integration_test.go b/backend/internal/repository/account_repo_integration_test.go index f82ad4ca28..fa4eed7f5c 100644 --- a/backend/internal/repository/account_repo_integration_test.go +++ b/backend/internal/repository/account_repo_integration_test.go @@ -4,6 +4,8 @@ package repository import ( "context" + "database/sql" + "strings" "testing" "time" @@ -11,6 +13,7 @@ import ( "github.com/Wei-Shaw/sub2api/ent/accountgroup" "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" ) @@ -25,13 +28,34 @@ type schedulerCacheRecorder struct { setAccounts []*service.Account deleteIDs []int64 accounts map[int64]*service.Account + setCtxErr error } func (s *schedulerCacheRecorder) GetSnapshot(ctx context.Context, bucket service.SchedulerBucket) ([]*service.Account, bool, error) { return nil, false, nil } -func (s *schedulerCacheRecorder) SetSnapshot(ctx context.Context, bucket service.SchedulerBucket, accounts []service.Account) error { +func (s *schedulerCacheRecorder) CaptureBucketWriteToken(ctx context.Context, bucket service.SchedulerBucket) (service.SchedulerBucketWriteToken, error) { + return service.SchedulerBucketWriteToken{Bucket: bucket, Epoch: 1}, nil +} + +func (s *schedulerCacheRecorder) SetSnapshot(ctx context.Context, bucket service.SchedulerBucket, token service.SchedulerBucketWriteToken, accounts []service.Account) error { + return nil +} + +func (s *schedulerCacheRecorder) RetireBucket(ctx context.Context, bucket service.SchedulerBucket) error { + return nil +} + +func (s *schedulerCacheRecorder) ReopenBucket(ctx context.Context, bucket service.SchedulerBucket) (service.SchedulerBucketWriteToken, error) { + return service.SchedulerBucketWriteToken{Bucket: bucket, Epoch: 1}, nil +} + +func (s *schedulerCacheRecorder) TryAcquireGroupLifecycleLease(_ context.Context, groupID int64, _ time.Duration) (service.SchedulerGroupLifecycleLease, bool, error) { + return service.SchedulerGroupLifecycleLease{GroupID: groupID, OwnerToken: "scheduler-cache-recorder"}, true, nil +} + +func (s *schedulerCacheRecorder) ReleaseGroupLifecycleLease(context.Context, service.SchedulerGroupLifecycleLease) error { return nil } @@ -43,6 +67,7 @@ func (s *schedulerCacheRecorder) GetAccount(ctx context.Context, accountID int64 } func (s *schedulerCacheRecorder) SetAccount(ctx context.Context, account *service.Account) error { + s.setCtxErr = ctx.Err() s.setAccounts = append(s.setAccounts, account) if s.accounts == nil { s.accounts = make(map[int64]*service.Account) @@ -53,6 +78,31 @@ func (s *schedulerCacheRecorder) SetAccount(ctx context.Context, account *servic return nil } +type failAtomicSchedulerOutboxSQLExecutor struct { + sqlExecutor +} + +func (e *failAtomicSchedulerOutboxSQLExecutor) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) { + if strings.Contains(query, "WITH updated AS") && strings.Contains(query, "INSERT INTO scheduler_outbox") && len(args) > 0 { + args = append([]any(nil), args...) + args[len(args)-1] = nil // event_type is NOT NULL; the whole statement must roll back. + } + return e.sqlExecutor.ExecContext(ctx, query, args...) +} + +type cancelAfterAtomicMutationSQLExecutor struct { + sqlExecutor + cancel context.CancelFunc +} + +func (e *cancelAfterAtomicMutationSQLExecutor) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) { + result, err := e.sqlExecutor.ExecContext(ctx, query, args...) + if err == nil && strings.Contains(query, "WITH updated AS") && strings.Contains(query, "INSERT INTO scheduler_outbox") { + e.cancel() + } + return result, err +} + func (s *schedulerCacheRecorder) DeleteAccount(ctx context.Context, accountID int64) error { s.deleteIDs = append(s.deleteIDs, accountID) if s.accounts != nil { @@ -180,6 +230,34 @@ func (s *AccountRepoSuite) TestUpdate_SyncSchedulerSnapshotOnCredentialsChange() s.Require().Equal("gpt-5.2", mapping["gpt-5"]) } +func (s *AccountRepoSuite) TestUpdateCredentials_SyncsSnapshotAndDurableOutbox() { + account := mustCreateAccount(s.T(), s.client, &service.Account{ + Name: "sync-refresh-credentials", + Status: service.StatusActive, + Schedulable: true, + Credentials: map[string]any{"access_token": "old-token"}, + }) + cacheRecorder := &schedulerCacheRecorder{} + s.repo.schedulerCache = cacheRecorder + _, err := s.repo.sql.ExecContext(s.ctx, "TRUNCATE scheduler_outbox") + s.Require().NoError(err) + + s.Require().NoError(s.repo.UpdateCredentials(s.ctx, account.ID, map[string]any{"access_token": "new-token"})) + + s.Require().Len(cacheRecorder.setAccounts, 1) + s.Require().Equal("new-token", cacheRecorder.setAccounts[0].GetCredential("access_token")) + var outboxCount int + err = scanSingleRow( + s.ctx, + s.repo.sql, + "SELECT COUNT(*) FROM scheduler_outbox WHERE event_type = $1 AND account_id = $2", + []any{service.SchedulerOutboxEventAccountChanged, account.ID}, + &outboxCount, + ) + s.Require().NoError(err) + s.Require().Equal(1, outboxCount) +} + func (s *AccountRepoSuite) TestDelete() { account := mustCreateAccount(s.T(), s.client, &service.Account{Name: "to-delete"}) @@ -236,6 +314,88 @@ func (s *AccountRepoSuite) TestList() { s.Require().Equal(int64(2), page.Total) } +func (s *AccountRepoSuite) TestListOAuthRefreshCandidatePage_GrokCursorAndExclusions() { + now := time.Now().UTC() + valid1 := mustCreateAccount(s.T(), s.client, &service.Account{ + Name: "grok-oauth-page-1", + Platform: service.PlatformGrok, + Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Credentials: map[string]any{ + "access_token": "access-1", + "refresh_token": "refresh-1", + "expires_at": now.Add(30 * time.Minute).Format(time.RFC3339), + }, + }) + mustCreateAccount(s.T(), s.client, &service.Account{ + Name: "grok-api-key-excluded", + Platform: service.PlatformGrok, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + Credentials: map[string]any{ + "api_key": "api-key", + "refresh_token": "must-not-make-api-key-eligible", + }, + }) + valid2 := mustCreateAccount(s.T(), s.client, &service.Account{ + Name: "grok-oauth-page-2", + Platform: service.PlatformGrok, + Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Credentials: map[string]any{"refresh_token": "refresh-2"}, + }) + mustCreateAccount(s.T(), s.client, &service.Account{ + Name: "grok-oauth-blank-refresh-excluded", + Platform: service.PlatformGrok, + Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Credentials: map[string]any{"refresh_token": " "}, + }) + valid3 := mustCreateAccount(s.T(), s.client, &service.Account{ + Name: "grok-oauth-page-3", + Platform: service.PlatformGrok, + Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Credentials: map[string]any{"refresh_token": "refresh-3"}, + }) + cooldown := mustCreateAccount(s.T(), s.client, &service.Account{ + Name: "grok-oauth-retry-cooldown-excluded", + Platform: service.PlatformGrok, + Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Credentials: map[string]any{"refresh_token": "refresh-cooldown"}, + }) + s.Require().NoError(s.repo.SetTempUnschedulable(s.ctx, cooldown.ID, now.Add(10*time.Minute), "token refresh retry exhausted: timeout")) + mustCreateAccount(s.T(), s.client, &service.Account{ + Name: "openai-oauth-excluded", + Platform: service.PlatformOpenAI, + Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Credentials: map[string]any{"refresh_token": "refresh-openai"}, + }) + + options := service.OAuthRefreshPageOptions{ + Platforms: []string{service.PlatformGrok}, + Limit: 2, + ActiveOnly: true, + RequireRefreshToken: true, + ExcludeRetryCooldown: true, + } + firstPage, err := s.repo.ListOAuthRefreshCandidatePage(s.ctx, options) + s.Require().NoError(err) + first := firstPage.Accounts + s.Require().Len(first, 2) + s.Require().Equal([]int64{valid1.ID, valid2.ID}, []int64{first[0].ID, first[1].ID}) + + options.AfterID = first[len(first)-1].ID + secondPage, err := s.repo.ListOAuthRefreshCandidatePage(s.ctx, options) + s.Require().NoError(err) + second := secondPage.Accounts + s.Require().Len(second, 1) + s.Require().Equal(valid3.ID, second[0].ID) + s.Require().NotContains([]int64{first[0].ID, first[1].ID}, second[0].ID) +} + func (s *AccountRepoSuite) TestListWithFilters() { tests := []struct { name string @@ -722,6 +882,56 @@ func (s *AccountRepoSuite) TestSetRateLimitedIfLaterDoesNotShortenReset() { s.Require().WithinDuration(later, *cacheRecorder.setAccounts[1].RateLimitResetAt, time.Second) } +func (s *AccountRepoSuite) TestClearRateLimitIfObservedProtectsRearmed429Generation() { + account := mustCreateAccount(s.T(), s.client, &service.Account{ + Name: "acc-rl-conditional-clear", + Platform: service.PlatformGrok, + Type: service.AccountTypeOAuth, + }) + firstReset := time.Now().Add(30 * time.Minute).UTC().Truncate(time.Second) + rearmedReset := time.Now().Add(5 * time.Minute).UTC().Truncate(time.Second) + + s.Require().NoError(s.repo.SetRateLimitedIfLater(s.ctx, account.ID, firstReset)) + staleGeneration, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + s.Require().NotNil(staleGeneration.RateLimitedAt) + s.Require().NotNil(staleGeneration.RateLimitResetAt) + cleared, err := s.repo.ClearRateLimitIfObserved(s.ctx, account.ID, *staleGeneration.RateLimitedAt, *staleGeneration.RateLimitResetAt) + s.Require().NoError(err) + s.Require().True(cleared) + + // A newer generation may legitimately re-arm a shorter boundary after the + // first generation was cleared. The stale success must not erase it. + s.Require().NoError(s.repo.SetRateLimitedIfLater(s.ctx, account.ID, rearmedReset)) + cleared, err = s.repo.ClearRateLimitIfObserved(s.ctx, account.ID, *staleGeneration.RateLimitedAt, *staleGeneration.RateLimitResetAt) + s.Require().NoError(err) + s.Require().False(cleared) + + got, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + s.Require().NotNil(got.RateLimitedAt) + s.Require().NotNil(got.RateLimitResetAt) + s.Require().WithinDuration(rearmedReset, *got.RateLimitResetAt, time.Second) + + // An admin can retype the row while the successful OAuth request is still + // in flight. The stale OAuth recovery must not cross into API-key state even + // when both observed timestamps still match. + _, err = s.client.Account.UpdateOneID(account.ID). + SetType(service.AccountTypeAPIKey). + Save(s.ctx) + s.Require().NoError(err) + cleared, err = s.repo.ClearRateLimitIfObserved(s.ctx, account.ID, *got.RateLimitedAt, *got.RateLimitResetAt) + s.Require().NoError(err) + s.Require().False(cleared) + + retyped, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + s.Require().Equal(service.AccountTypeAPIKey, retyped.Type) + s.Require().NotNil(retyped.RateLimitedAt) + s.Require().NotNil(retyped.RateLimitResetAt) + s.Require().WithinDuration(rearmedReset, *retyped.RateLimitResetAt, time.Second) +} + func (s *AccountRepoSuite) TestClearRateLimit() { account := mustCreateAccount(s.T(), s.client, &service.Account{Name: "acc-clear"}) until := time.Now().Add(1 * time.Hour) @@ -848,6 +1058,10 @@ func (s *AccountRepoSuite) TestUpdateLastUsed() { func (s *AccountRepoSuite) TestSetError() { account := mustCreateAccount(s.T(), s.client, &service.Account{Name: "acc-err", Status: service.StatusActive, Schedulable: true}) + cacheRecorder := &schedulerCacheRecorder{} + s.repo.schedulerCache = cacheRecorder + _, err := s.repo.sql.ExecContext(s.ctx, "TRUNCATE scheduler_outbox") + s.Require().NoError(err) s.Require().NoError(s.repo.SetError(s.ctx, account.ID, "something went wrong")) @@ -856,6 +1070,296 @@ func (s *AccountRepoSuite) TestSetError() { s.Require().Equal(service.StatusError, got.Status) s.Require().Equal("something went wrong", got.ErrorMessage) s.Require().False(got.Schedulable) + s.Require().Len(cacheRecorder.setAccounts, 1) + s.Require().Equal(account.ID, cacheRecorder.setAccounts[0].ID) + s.Require().Equal(service.StatusError, cacheRecorder.setAccounts[0].Status) + s.Require().False(cacheRecorder.setAccounts[0].Schedulable) + + var outboxCount int + err = scanSingleRow( + s.ctx, + s.repo.sql, + "SELECT COUNT(*) FROM scheduler_outbox WHERE event_type = $1 AND account_id = $2", + []any{service.SchedulerOutboxEventAccountChanged, account.ID}, + &outboxCount, + ) + s.Require().NoError(err) + s.Require().Equal(1, outboxCount) +} + +func (s *AccountRepoSuite) TestSetGrokOAuthErrorIfCredentialsUnchanged_AppliesAndSyncsSchedulerState() { + account := mustCreateAccount(s.T(), s.client, &service.Account{ + Name: "grok-conditional-error-applied", + Platform: service.PlatformGrok, + Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Schedulable: true, + Credentials: map[string]any{"access_token": "observed", "_token_version": int64(7)}, + }) + observed, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + cacheRecorder := &schedulerCacheRecorder{} + s.repo.schedulerCache = cacheRecorder + _, err = s.repo.sql.ExecContext(s.ctx, "TRUNCATE scheduler_outbox") + s.Require().NoError(err) + + applied, err := s.repo.SetGrokOAuthErrorIfCredentialsUnchanged( + s.ctx, + account.ID, + observed.Credentials, + "missing refresh token", + ) + + s.Require().NoError(err) + s.Require().True(applied) + got, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + s.Require().Equal(service.StatusError, got.Status) + s.Require().False(got.Schedulable) + s.Require().Equal("missing refresh token", got.ErrorMessage) + s.Require().Len(cacheRecorder.setAccounts, 1) + s.Require().Equal(service.StatusError, cacheRecorder.setAccounts[0].Status) + + var outboxCount int + err = scanSingleRow( + s.ctx, + s.repo.sql, + "SELECT COUNT(*) FROM scheduler_outbox WHERE event_type = $1 AND account_id = $2", + []any{service.SchedulerOutboxEventAccountChanged, account.ID}, + &outboxCount, + ) + s.Require().NoError(err) + s.Require().Equal(1, outboxCount) +} + +func (s *AccountRepoSuite) TestSetGrokOAuthErrorIfCredentialsUnchanged_SkipsConcurrentReauthorization() { + account := mustCreateAccount(s.T(), s.client, &service.Account{ + Name: "grok-conditional-error-reauthorized", + Platform: service.PlatformGrok, + Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Schedulable: true, + Credentials: map[string]any{"access_token": "observed", "_token_version": int64(7)}, + }) + observed, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + s.Require().NoError(s.repo.UpdateCredentials(s.ctx, account.ID, map[string]any{ + "access_token": "fresh-access", + "refresh_token": "fresh-refresh", + "expires_at": time.Now().UTC().Add(4 * time.Hour).Format(time.RFC3339), + "_token_version": int64(8), + })) + cacheRecorder := &schedulerCacheRecorder{} + s.repo.schedulerCache = cacheRecorder + _, err = s.repo.sql.ExecContext(s.ctx, "TRUNCATE scheduler_outbox") + s.Require().NoError(err) + + applied, err := s.repo.SetGrokOAuthErrorIfCredentialsUnchanged( + s.ctx, + account.ID, + observed.Credentials, + "stale reconciliation", + ) + + s.Require().NoError(err) + s.Require().False(applied) + got, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + s.Require().Equal(service.StatusActive, got.Status) + s.Require().True(got.Schedulable) + s.Require().Equal("fresh-refresh", got.GetGrokRefreshToken()) + s.Require().Empty(cacheRecorder.setAccounts, "a lost compare-and-set race must not rewrite the scheduler snapshot") + + var outboxCount int + err = scanSingleRow( + s.ctx, + s.repo.sql, + "SELECT COUNT(*) FROM scheduler_outbox WHERE event_type = $1 AND account_id = $2", + []any{service.SchedulerOutboxEventAccountChanged, account.ID}, + &outboxCount, + ) + s.Require().NoError(err) + s.Require().Zero(outboxCount, "a lost compare-and-set race must not enqueue a stale account change") +} + +func (s *AccountRepoSuite) TestUpdateGrokOAuthCredentialsIfUnchanged_AppliesAndPublishesSchedulerState() { + account := mustCreateAccount(s.T(), s.client, &service.Account{ + Name: "grok-refresh-success-cas-applied", + Platform: service.PlatformGrok, + Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Schedulable: true, + Credentials: map[string]any{ + "access_token": "attempted-access", + "refresh_token": "attempted-refresh", + "_token_version": int64(10), + }, + }) + observed, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + cacheRecorder := &schedulerCacheRecorder{} + s.repo.schedulerCache = cacheRecorder + _, err = s.repo.sql.ExecContext(s.ctx, "TRUNCATE scheduler_outbox") + s.Require().NoError(err) + + applied, err := s.repo.UpdateGrokOAuthCredentialsIfUnchanged( + s.ctx, + account.ID, + observed.Credentials, + observed.ProxyID, + map[string]any{ + "access_token": "rotated-access", + "refresh_token": "rotated-refresh", + "_token_version": int64(11), + }, + ) + + s.Require().NoError(err) + s.Require().True(applied) + got, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + s.Require().Equal("rotated-refresh", got.GetGrokRefreshToken()) + s.Require().Len(cacheRecorder.setAccounts, 1) + s.Require().Equal("rotated-refresh", cacheRecorder.setAccounts[0].GetGrokRefreshToken()) + s.Require().NoError(cacheRecorder.setCtxErr) + + var outboxCount int + err = scanSingleRow( + s.ctx, + s.repo.sql, + "SELECT COUNT(*) FROM scheduler_outbox WHERE event_type = $1 AND account_id = $2", + []any{service.SchedulerOutboxEventAccountChanged, account.ID}, + &outboxCount, + ) + s.Require().NoError(err) + s.Require().Equal(1, outboxCount) +} + +func (s *AccountRepoSuite) TestUpdateGrokOAuthCredentialsIfUnchanged_SkipsConcurrentReauthorization() { + account := mustCreateAccount(s.T(), s.client, &service.Account{ + Name: "grok-refresh-success-cas-reauthorized", + Platform: service.PlatformGrok, + Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Schedulable: true, + Credentials: map[string]any{ + "access_token": "attempted-access", + "refresh_token": "attempted-refresh", + "_token_version": int64(20), + }, + }) + observed, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + s.Require().NoError(s.repo.UpdateCredentials(s.ctx, account.ID, map[string]any{ + "access_token": "reauthorized-access", + "refresh_token": "reauthorized-refresh", + "_token_version": int64(21), + })) + cacheRecorder := &schedulerCacheRecorder{} + s.repo.schedulerCache = cacheRecorder + _, err = s.repo.sql.ExecContext(s.ctx, "TRUNCATE scheduler_outbox") + s.Require().NoError(err) + + applied, err := s.repo.UpdateGrokOAuthCredentialsIfUnchanged( + s.ctx, + account.ID, + observed.Credentials, + observed.ProxyID, + map[string]any{ + "access_token": "provider-access", + "refresh_token": "provider-refresh", + "_token_version": int64(22), + }, + ) + + s.Require().NoError(err) + s.Require().False(applied) + got, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + s.Require().Equal("reauthorized-refresh", got.GetGrokRefreshToken()) + s.Require().Empty(cacheRecorder.setAccounts) + + var outboxCount int + err = scanSingleRow( + s.ctx, + s.repo.sql, + "SELECT COUNT(*) FROM scheduler_outbox WHERE event_type = $1 AND account_id = $2", + []any{service.SchedulerOutboxEventAccountChanged, account.ID}, + &outboxCount, + ) + s.Require().NoError(err) + s.Require().Zero(outboxCount) +} + +func (s *AccountRepoSuite) TestGrokOAuthConditionalMutation_DetachesBoundedSnapshotSync() { + account := mustCreateAccount(s.T(), s.client, &service.Account{ + Name: "grok-conditional-detached-sync", + Platform: service.PlatformGrok, + Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Schedulable: true, + Credentials: map[string]any{"access_token": "observed"}, + }) + observed, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + ctx, cancel := context.WithCancel(context.Background()) + cacheRecorder := &schedulerCacheRecorder{} + repo := newAccountRepositoryWithSQL(s.client, &cancelAfterAtomicMutationSQLExecutor{ + sqlExecutor: s.repo.sql, + cancel: cancel, + }, cacheRecorder) + + applied, err := repo.SetGrokOAuthErrorIfCredentialsUnchanged( + ctx, + account.ID, + observed.Credentials, + "missing refresh token", + ) + + s.Require().NoError(err) + s.Require().True(applied) + s.Require().ErrorIs(ctx.Err(), context.Canceled) + s.Require().Len(cacheRecorder.setAccounts, 1) + s.Require().NoError(cacheRecorder.setCtxErr, "immediate scheduler propagation must use a bounded detached context") +} + +func TestGrokOAuthConditionalMutationRollsBackWhenOutboxInsertFails(t *testing.T) { + client := testEntClient(t) + account := mustCreateAccount(t, client, &service.Account{ + Name: "grok-conditional-atomic-outbox-failure", + Platform: service.PlatformGrok, + Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Schedulable: true, + Credentials: map[string]any{"access_token": "observed"}, + }) + t.Cleanup(func() { + _, _ = integrationDB.ExecContext(context.Background(), "DELETE FROM scheduler_outbox WHERE account_id = $1", account.ID) + _ = client.Account.DeleteOneID(account.ID).Exec(context.Background()) + }) + repo := newAccountRepositoryWithSQL(client, &failAtomicSchedulerOutboxSQLExecutor{sqlExecutor: integrationDB}, nil) + + applied, err := repo.SetGrokOAuthErrorIfCredentialsUnchanged( + context.Background(), + account.ID, + account.Credentials, + "missing refresh token", + ) + + require.Error(t, err) + require.False(t, applied) + got, readErr := repo.GetByID(context.Background(), account.ID) + require.NoError(t, readErr) + require.Equal(t, service.StatusActive, got.Status) + require.True(t, got.Schedulable) + require.Empty(t, got.ErrorMessage) + var outboxCount int + require.NoError(t, integrationDB.QueryRowContext( + context.Background(), + "SELECT COUNT(*) FROM scheduler_outbox WHERE account_id = $1", + account.ID, + ).Scan(&outboxCount)) + require.Zero(t, outboxCount) } func (s *AccountRepoSuite) TestUpdateErrorStatusUnschedulesAccount() { diff --git a/backend/internal/repository/account_repo_schedulable_projection_integration_test.go b/backend/internal/repository/account_repo_schedulable_projection_integration_test.go new file mode 100644 index 0000000000..82d62a1448 --- /dev/null +++ b/backend/internal/repository/account_repo_schedulable_projection_integration_test.go @@ -0,0 +1,107 @@ +//go:build integration + +package repository + +import ( + "context" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestListSchedulableAccountLoadsMatchesListSchedulable(t *testing.T) { + ctx := context.Background() + tx := testEntTx(t) + client := tx.Client() + repo := newAccountRepositoryWithSQL(client, tx, nil) + now := time.Now() + past := now.Add(-time.Hour) + future := now.Add(time.Hour) + + create := func(name string) *service.Account { + return mustCreateAccount(t, client, &service.Account{Name: name, Schedulable: true}) + } + + positiveLoad := create("projection-positive-load") + _, err := client.Account.UpdateOneID(positiveLoad.ID).SetConcurrency(2).SetLoadFactor(9).SetPriority(30).Save(ctx) + require.NoError(t, err) + concurrencyFallback := create("projection-concurrency-fallback") + _, err = client.Account.UpdateOneID(concurrencyFallback.ID).SetConcurrency(4).SetPriority(10).Save(ctx) + require.NoError(t, err) + zeroFallback := create("projection-zero-fallback") + _, err = client.Account.UpdateOneID(zeroFallback.ID).SetConcurrency(0).SetLoadFactor(0).SetPriority(20).Save(ctx) + require.NoError(t, err) + + disabled := create("projection-disabled") + _, err = client.Account.UpdateOneID(disabled.ID).SetStatus(service.StatusDisabled).Save(ctx) + require.NoError(t, err) + unschedulable := create("projection-unschedulable") + _, err = client.Account.UpdateOneID(unschedulable.ID).SetSchedulable(false).Save(ctx) + require.NoError(t, err) + expired := create("projection-expired") + _, err = client.Account.UpdateOneID(expired.ID).SetExpiresAt(past).SetAutoPauseOnExpired(true).Save(ctx) + require.NoError(t, err) + expiredAllowed := create("projection-expired-allowed") + _, err = client.Account.UpdateOneID(expiredAllowed.ID).SetExpiresAt(past).SetAutoPauseOnExpired(false).Save(ctx) + require.NoError(t, err) + overloaded := create("projection-overloaded") + _, err = client.Account.UpdateOneID(overloaded.ID).SetOverloadUntil(future).Save(ctx) + require.NoError(t, err) + overloadCleared := create("projection-overload-cleared") + _, err = client.Account.UpdateOneID(overloadCleared.ID).SetOverloadUntil(past).Save(ctx) + require.NoError(t, err) + rateLimited := create("projection-rate-limited") + _, err = client.Account.UpdateOneID(rateLimited.ID).SetRateLimitResetAt(future).Save(ctx) + require.NoError(t, err) + rateLimitCleared := create("projection-rate-limit-cleared") + _, err = client.Account.UpdateOneID(rateLimitCleared.ID).SetRateLimitResetAt(past).Save(ctx) + require.NoError(t, err) + tempBlocked := create("projection-temp-blocked") + _, err = client.Account.UpdateOneID(tempBlocked.ID).SetTempUnschedulableUntil(future).Save(ctx) + require.NoError(t, err) + tempCleared := create("projection-temp-cleared") + _, err = client.Account.UpdateOneID(tempCleared.ID).SetTempUnschedulableUntil(past).Save(ctx) + require.NoError(t, err) + + accounts, err := repo.ListSchedulable(ctx) + require.NoError(t, err) + loads, err := repo.ListSchedulableAccountLoads(ctx) + require.NoError(t, err) + + accountIDs := make([]int64, 0, len(accounts)) + wantByID := make(map[int64]int, len(accounts)) + for i := range accounts { + accountIDs = append(accountIDs, accounts[i].ID) + wantByID[accounts[i].ID] = accounts[i].EffectiveLoadFactor() + } + + loadIDs := make([]int64, 0, len(loads)) + byID := make(map[int64]int, len(loads)) + for _, load := range loads { + loadIDs = append(loadIDs, load.ID) + byID[load.ID] = load.MaxConcurrency + } + require.Equal(t, accountIDs, loadIDs) + targetIDs := map[int64]struct{}{ + positiveLoad.ID: {}, concurrencyFallback.ID: {}, zeroFallback.ID: {}, + } + targetOrder := make([]int64, 0, len(targetIDs)) + for _, id := range loadIDs { + if _, ok := targetIDs[id]; ok { + targetOrder = append(targetOrder, id) + } + } + require.Equal(t, []int64{concurrencyFallback.ID, zeroFallback.ID, positiveLoad.ID}, targetOrder) + require.Equal(t, wantByID, byID) + require.Equal(t, 9, byID[positiveLoad.ID]) + require.Equal(t, 4, byID[concurrencyFallback.ID]) + require.Equal(t, 1, byID[zeroFallback.ID]) + for _, included := range []*service.Account{expiredAllowed, overloadCleared, rateLimitCleared, tempCleared} { + require.Contains(t, byID, included.ID) + } + for _, excluded := range []*service.Account{disabled, unschedulable, expired, overloaded, rateLimited, tempBlocked} { + require.NotContains(t, byID, excluded.ID) + } +} diff --git a/backend/internal/repository/account_repo_schedulable_projection_test.go b/backend/internal/repository/account_repo_schedulable_projection_test.go new file mode 100644 index 0000000000..76d7e0bdc5 --- /dev/null +++ b/backend/internal/repository/account_repo_schedulable_projection_test.go @@ -0,0 +1,82 @@ +package repository + +import ( + "context" + "fmt" + "strings" + "testing" + + "github.com/DATA-DOG/go-sqlmock" + dbent "github.com/Wei-Shaw/sub2api/ent" + _ "github.com/Wei-Shaw/sub2api/ent/runtime" + "github.com/stretchr/testify/require" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" +) + +type captureEntQueryMatcher struct { + actual *string +} + +func (m captureEntQueryMatcher) Match(_, actual string) error { + if m.actual == nil { + return fmt.Errorf("query capture target is nil") + } + *m.actual = actual + return nil +} + +func TestListSchedulableAccountLoadsUsesSingleProjectionQuery(t *testing.T) { + var capturedSQL string + db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(captureEntQueryMatcher{actual: &capturedSQL})) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + driver := entsql.OpenDB(dialect.Postgres, db) + client := dbent.NewClient(dbent.Driver(driver)) + t.Cleanup(func() { _ = client.Close() }) + repo := newAccountRepositoryWithSQL(client, db, nil) + + mock.ExpectQuery("schedulable account load projection"). + WillReturnRows(sqlmock.NewRows([]string{"id", "concurrency", "load_factor"}). + AddRow(int64(11), 3, nil). + AddRow(int64(12), 2, 7)) + + loads, err := repo.ListSchedulableAccountLoads(context.Background()) + require.NoError(t, err) + require.Len(t, loads, 2) + require.Equal(t, int64(11), loads[0].ID) + require.Equal(t, 3, loads[0].MaxConcurrency) + require.Equal(t, int64(12), loads[1].ID) + require.Equal(t, 7, loads[1].MaxConcurrency) + require.NoError(t, mock.ExpectationsWereMet(), "projection path must execute exactly one query") + + normalized := normalizeSQLWhitespace(capturedSQL) + selectClause, _, found := strings.Cut(normalized, " FROM ") + require.True(t, found, "unexpected projection SQL: %s", normalized) + require.Equal(t, 2, strings.Count(selectClause, ","), "projection must select exactly three columns: %s", selectClause) + require.Contains(t, selectClause, `"id"`) + require.Contains(t, selectClause, `"concurrency"`) + require.Contains(t, selectClause, `"load_factor"`) + require.NotContains(t, selectClause, "credentials") + require.NotContains(t, selectClause, "extra") + require.NotContains(t, selectClause, "proxy_id") + require.NotContains(t, normalized, "account_groups") + require.NotContains(t, normalized, "proxies") + for _, predicateColumn := range []string{ + "status", + "schedulable", + "temp_unschedulable_until", + "expires_at", + "auto_pause_on_expired", + "overload_until", + "rate_limit_reset_at", + "deleted_at", + } { + require.Contains(t, normalized, predicateColumn) + } + _, orderClause, hasOrder := strings.Cut(normalized, " ORDER BY ") + require.True(t, hasOrder, "projection query must preserve schedulable account order: %s", normalized) + require.Contains(t, orderClause, `"priority" ASC`) +} diff --git a/backend/internal/repository/account_repo_temp_unsched_test.go b/backend/internal/repository/account_repo_temp_unsched_test.go index 9c3e4cbdf5..df1e7abf3b 100644 --- a/backend/internal/repository/account_repo_temp_unsched_test.go +++ b/backend/internal/repository/account_repo_temp_unsched_test.go @@ -3,12 +3,14 @@ package repository import ( "context" "database/sql" + "database/sql/driver" "regexp" "strings" "testing" "time" sqlmock "github.com/DATA-DOG/go-sqlmock" + "github.com/Wei-Shaw/sub2api/internal/service" "github.com/stretchr/testify/require" ) @@ -24,28 +26,262 @@ func TestAccountRepository_SetTempUnschedulable_NoRowsAffectedDoesNotWriteOutbox require.NotContains(t, strings.Join(exec.execQueries, "\n"), "scheduler_outbox") } -func TestAccountRepository_ListOAuthRefreshCandidates_SQLFilter(t *testing.T) { +func TestAccountRepository_GrokCredentialConditionalMutationsAreEligibleAndAtomicallyPropagated(t *testing.T) { + proxyID := int64(77) + snapshot := service.GrokCredentialMutationSnapshot{ + CredentialsJSON: `{"access_token":"access","refresh_token":"refresh","_token_version":123}`, + ProxyID: &proxyID, + } + + t.Run("permanent", func(t *testing.T) { + exec := &recordingSQLExecutor{result: rowsAffectedResult(0)} + repo := newAccountRepositoryWithSQL(nil, exec, nil) + + updated, err := repo.SetGrokCredentialErrorIfMatch(context.Background(), 42, snapshot, "revoked") + + require.NoError(t, err) + require.False(t, updated) + require.Len(t, exec.execQueries, 1) + normalized := normalizeSQLWhitespace(exec.execQueries[0]) + require.Contains(t, normalized, "WITH updated AS ( UPDATE accounts AS a") + require.Contains(t, normalized, "a.schedulable IS TRUE") + require.Contains(t, normalized, "a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until <= NOW()") + require.Contains(t, normalized, "a.rate_limit_reset_at IS NULL OR a.rate_limit_reset_at <= NOW()") + require.Contains(t, normalized, "a.overload_until IS NULL OR a.overload_until <= NOW()") + require.Contains(t, normalized, "a.credentials = $7::jsonb") + require.Contains(t, normalized, "a.proxy_id IS NOT DISTINCT FROM $8") + require.Contains(t, normalized, "NOT EXISTS ( SELECT 1 FROM proxies p") + require.Contains(t, normalized, "INSERT INTO scheduler_outbox") + require.Len(t, exec.execArgs[0], 10) + require.Equal(t, snapshot.CredentialsJSON, exec.execArgs[0][6]) + require.Equal(t, &proxyID, exec.execArgs[0][7]) + require.Equal(t, string(service.GrokCredentialReasonProxyInvalid), exec.execArgs[0][8]) + require.Equal(t, service.SchedulerOutboxEventAccountChanged, exec.execArgs[0][9]) + }) + + t.Run("transient", func(t *testing.T) { + exec := &recordingSQLExecutor{result: rowsAffectedResult(0)} + repo := newAccountRepositoryWithSQL(nil, exec, nil) + + updated, err := repo.SetGrokCredentialTempUnschedulableIfMatch( + context.Background(), 42, snapshot, time.Now().Add(time.Minute), "temporary", + ) + + require.NoError(t, err) + require.False(t, updated) + require.Len(t, exec.execQueries, 1) + normalized := normalizeSQLWhitespace(exec.execQueries[0]) + require.Contains(t, normalized, "WITH updated AS ( UPDATE accounts AS a") + require.Contains(t, normalized, "a.schedulable IS TRUE") + require.Contains(t, normalized, "a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until <= NOW()") + require.Contains(t, normalized, "a.rate_limit_reset_at IS NULL OR a.rate_limit_reset_at <= NOW()") + require.Contains(t, normalized, "a.overload_until IS NULL OR a.overload_until <= NOW()") + require.Contains(t, normalized, "a.credentials = $7::jsonb") + require.Contains(t, normalized, "a.proxy_id IS NOT DISTINCT FROM $8") + require.Contains(t, normalized, "INSERT INTO scheduler_outbox") + require.Len(t, exec.execArgs[0], 9) + require.Equal(t, snapshot.CredentialsJSON, exec.execArgs[0][6]) + require.Equal(t, &proxyID, exec.execArgs[0][7]) + require.Equal(t, service.SchedulerOutboxEventAccountChanged, exec.execArgs[0][8]) + }) +} + +func TestAccountRepository_GrokCredentialCommitCarriesOutboxAcrossCallerCancellation(t *testing.T) { + snapshot := service.GrokCredentialMutationSnapshot{CredentialsJSON: `{"access_token":"access","refresh_token":"refresh"}`} + tests := []struct { + name string + mutate func(context.Context, *accountRepository) (bool, error) + }{ + { + name: "permanent", + mutate: func(ctx context.Context, repo *accountRepository) (bool, error) { + return repo.SetGrokCredentialErrorIfMatch(ctx, 42, snapshot, string(service.GrokCredentialReasonRevoked)) + }, + }, + { + name: "transient", + mutate: func(ctx context.Context, repo *accountRepository) (bool, error) { + return repo.SetGrokCredentialTempUnschedulableIfMatch(ctx, 42, snapshot, time.Now().Add(time.Minute), string(service.GrokCredentialReasonRefreshTransient)) + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + exec := &recordingSQLExecutor{result: rowsAffectedResult(1), afterExec: cancel} + repo := newAccountRepositoryWithSQL(nil, exec, nil) + + updated, err := tt.mutate(ctx, repo) + + require.NoError(t, err) + require.True(t, updated) + require.ErrorIs(t, ctx.Err(), context.Canceled) + require.Len(t, exec.execQueries, 1, "state update and scheduler outbox must share one atomic SQL statement") + require.Contains(t, normalizeSQLWhitespace(exec.execQueries[0]), "INSERT INTO scheduler_outbox") + }) + } +} + +func TestAccountRepository_SetGrokOAuthErrorIfCredentialsUnchanged_RequiresActiveExactCredentialMatch(t *testing.T) { + exec := &recordingSQLExecutor{result: rowsAffectedResult(0)} + repo := newAccountRepositoryWithSQL(nil, exec, nil) + + applied, err := repo.SetGrokOAuthErrorIfCredentialsUnchanged( + context.Background(), + 42, + map[string]any{"access_token": "observed", "_token_version": int64(7)}, + "missing refresh token", + ) + + require.NoError(t, err) + require.False(t, applied) + require.Len(t, exec.execQueries, 1, "the account mutation and conditional outbox insert must be one statement") + normalized := normalizeSQLWhitespace(exec.execQueries[0]) + require.Contains(t, normalized, "WITH updated AS") + require.Contains(t, normalized, "INSERT INTO scheduler_outbox") + require.Contains(t, normalized, "FROM updated") + require.Contains(t, normalized, "platform = $4") + require.Contains(t, normalized, "type = $5") + require.Contains(t, normalized, "status = $6") + require.Contains(t, normalized, "credentials = $7::jsonb") + require.Contains(t, normalized, "NULLIF(BTRIM(a.credentials->>'refresh_token'), '') IS NULL") + require.Len(t, exec.execArgs, 1) + require.Equal(t, service.StatusActive, exec.execArgs[0][5]) + require.Contains(t, exec.execArgs[0][6], `"_token_version":7`) +} + +func TestAccountRepository_SetGrokOAuthErrorIfCredentialsUnchanged_AppliedWritesOutbox(t *testing.T) { + exec := &recordingSQLExecutor{result: rowsAffectedResult(1)} + repo := newAccountRepositoryWithSQL(nil, exec, nil) + + applied, err := repo.SetGrokOAuthErrorIfCredentialsUnchanged( + context.Background(), + 42, + map[string]any{"access_token": "observed"}, + "missing refresh token", + ) + + require.NoError(t, err) + require.True(t, applied) + require.Len(t, exec.execQueries, 1) + normalized := normalizeSQLWhitespace(exec.execQueries[0]) + require.Contains(t, normalized, "WITH updated AS") + require.Contains(t, normalized, "INSERT INTO scheduler_outbox") + require.Contains(t, normalized, "SELECT $8, updated.id, NULL, NULL FROM updated") +} + +func TestAccountRepository_SetGrokOAuthRefreshErrorIfCredentialsUnchanged_UsesAttemptCredentialsAndProxy(t *testing.T) { + exec := &recordingSQLExecutor{result: rowsAffectedResult(0)} + repo := newAccountRepositoryWithSQL(nil, exec, nil) + proxyID := int64(17) + + applied, err := repo.SetGrokOAuthRefreshErrorIfCredentialsUnchanged( + context.Background(), + 42, + map[string]any{"refresh_token": "attempted", "_token_version": int64(7)}, + &proxyID, + "revoked", + ) + + require.NoError(t, err) + require.False(t, applied) + require.Len(t, exec.execQueries, 1) + normalized := normalizeSQLWhitespace(exec.execQueries[0]) + require.Contains(t, normalized, "credentials = $7::jsonb") + require.Contains(t, normalized, "proxy_id IS NOT DISTINCT FROM $8") + require.NotContains(t, normalized, "credentials->>'refresh_token'", + "background invalid_grant CAS must accept the attempted refresh token; only reconciliation requires it missing") + require.Equal(t, &proxyID, exec.execArgs[0][7]) + require.Contains(t, normalized, "INSERT INTO scheduler_outbox") + require.Len(t, exec.execArgs[0], 9) +} + +func TestAccountRepository_SetGrokOAuthRefreshTempUnschedulableIfCredentialsUnchanged_UsesAttemptCredentialsAndProxy(t *testing.T) { + exec := &recordingSQLExecutor{result: rowsAffectedResult(0)} + repo := newAccountRepositoryWithSQL(nil, exec, nil) + proxyID := int64(19) + + applied, err := repo.SetGrokOAuthRefreshTempUnschedulableIfCredentialsUnchanged( + context.Background(), + 42, + map[string]any{"refresh_token": "attempted", "_token_version": int64(8)}, + &proxyID, + time.Now().Add(10*time.Minute), + "retry exhausted", + ) + + require.NoError(t, err) + require.False(t, applied) + require.Len(t, exec.execQueries, 1) + normalized := normalizeSQLWhitespace(exec.execQueries[0]) + require.Contains(t, normalized, "credentials = $7::jsonb") + require.Contains(t, normalized, "proxy_id IS NOT DISTINCT FROM $8") + require.Contains(t, normalized, "a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until < $1") + require.Len(t, exec.execArgs[0], 9) + require.Equal(t, &proxyID, exec.execArgs[0][7]) + require.Contains(t, normalized, "INSERT INTO scheduler_outbox") +} + +func TestAccountRepository_UpdateGrokOAuthCredentialsIfUnchanged_UsesExactAttemptStateAndAtomicOutbox(t *testing.T) { + exec := &recordingSQLExecutor{result: rowsAffectedResult(1)} + repo := newAccountRepositoryWithSQL(nil, exec, nil) + proxyID := int64(29) + + applied, err := repo.UpdateGrokOAuthCredentialsIfUnchanged( + context.Background(), + 42, + map[string]any{"refresh_token": "attempted", "_token_version": int64(9)}, + &proxyID, + map[string]any{"refresh_token": "rotated", "_token_version": int64(10)}, + ) + + require.NoError(t, err) + require.True(t, applied) + require.Len(t, exec.execQueries, 1) + normalized := normalizeSQLWhitespace(exec.execQueries[0]) + require.Contains(t, normalized, "WITH updated AS") + require.Contains(t, normalized, "credentials = $1::jsonb") + require.Contains(t, normalized, "credentials = $5::jsonb") + require.Contains(t, normalized, "proxy_id IS NOT DISTINCT FROM $6") + require.Contains(t, normalized, "INSERT INTO scheduler_outbox") + require.Len(t, exec.execArgs[0], 7) + require.Equal(t, &proxyID, exec.execArgs[0][5]) +} + +func TestAccountRepository_ListOAuthRefreshCandidatePage_SQLFilter(t *testing.T) { db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp)) require.NoError(t, err) defer func() { _ = db.Close() }() var capturedSQL string + var capturedArgs []any mock.ExpectQuery("SELECT id"). WillReturnRows(sqlmock.NewRows([]string{"id"})). WillDelayFor(0) - repo := newAccountRepositoryWithSQL(nil, captureQuerySQL{db: db, captured: &capturedSQL}, nil) + repo := newAccountRepositoryWithSQL(nil, captureQuerySQL{db: db, captured: &capturedSQL, args: &capturedArgs}, nil) - accounts, err := repo.ListOAuthRefreshCandidates(context.Background()) + page, err := repo.ListOAuthRefreshCandidatePage(context.Background(), service.OAuthRefreshPageOptions{ + Platforms: []string{service.PlatformAnthropic, service.PlatformOpenAI, service.PlatformGemini, service.PlatformAntigravity, service.PlatformGrok}, + AfterID: 100, + Limit: 200, + ActiveOnly: true, + IncludeSetupToken: true, + RequireRefreshToken: true, + ExcludeRetryCooldown: true, + }) require.NoError(t, err) - require.Empty(t, accounts) + require.Empty(t, page.Accounts) normalized := normalizeSQLWhitespace(capturedSQL) require.Contains(t, normalized, "deleted_at IS NULL") require.Contains(t, normalized, "status = 'active'") // setup-token 的 access_token 同为 8h 短期令牌,必须与 oauth 一起纳入后台刷新候选 require.Contains(t, normalized, "type IN ('oauth', 'setup-token')") - require.Contains(t, normalized, "platform IN ('anthropic', 'openai', 'gemini', 'antigravity')") + require.Contains(t, normalized, "platform = ANY($1)") + require.NotContains(t, normalized, "platform IN ('anthropic'", + "candidate platforms must come from the refresher registry instead of a second hard-coded list") require.Contains(t, normalized, "credentials ? 'refresh_token'") require.Contains(t, normalized, "btrim(credentials->>'refresh_token') <> ''") require.Contains(t, normalized, "temp_unschedulable_until > NOW()") @@ -54,14 +290,52 @@ func TestAccountRepository_ListOAuthRefreshCandidates_SQLFilter(t *testing.T) { "must use IS NOT TRUE so accounts with NULL temp_unschedulable_until are not silently excluded by PG 3-valued logic") require.NotContains(t, normalized, "AND NOT (", "plain NOT (...) excludes NULL temp_unschedulable_until rows (the common healthy case)") - require.Contains(t, normalized, "ORDER BY priority ASC, id ASC") + require.Contains(t, normalized, "id > $2") + require.Contains(t, normalized, "ORDER BY id ASC") + require.Contains(t, normalized, "LIMIT $3") require.NotContains(t, normalized, "credentials->>'expires_at'") + require.Len(t, capturedArgs, 3) + require.Equal(t, int64(100), capturedArgs[1]) + require.Equal(t, 200, capturedArgs[2]) + valuer, ok := capturedArgs[0].(interface{ Value() (driver.Value, error) }) + require.True(t, ok) + platforms, err := valuer.Value() + require.NoError(t, err) + require.Contains(t, platforms, service.PlatformGrok) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestAccountRepository_ListOAuthRefreshCandidatePage_ReconciliationExcludesAPIKeys(t *testing.T) { + db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp)) + require.NoError(t, err) + defer func() { _ = db.Close() }() + + var capturedSQL string + mock.ExpectQuery("SELECT id").WillReturnRows(sqlmock.NewRows([]string{"id"})) + repo := newAccountRepositoryWithSQL(nil, captureQuerySQL{db: db, captured: &capturedSQL}, nil) + + page, err := repo.ListOAuthRefreshCandidatePage(context.Background(), service.OAuthRefreshPageOptions{ + Platforms: []string{service.PlatformGrok}, + AfterID: 0, + Limit: 50, + }) + require.NoError(t, err) + require.Empty(t, page.Accounts) + + normalized := normalizeSQLWhitespace(capturedSQL) + require.Contains(t, normalized, "type = 'oauth'") + require.NotContains(t, normalized, "type IN ('oauth', 'setup-token')") + require.NotContains(t, normalized, "type = 'api-key'") + require.NotContains(t, normalized, "credentials ? 'refresh_token'", + "reconciliation must be able to find structurally invalid OAuth rows") + require.Contains(t, normalized, "ORDER BY id ASC") require.NoError(t, mock.ExpectationsWereMet()) } type captureQuerySQL struct { db *sql.DB captured *string + args *[]any } func (c captureQuerySQL) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) { @@ -72,6 +346,9 @@ func (c captureQuerySQL) QueryContext(ctx context.Context, query string, args .. if c.captured != nil { *c.captured = query } + if c.args != nil { + *c.args = append([]any(nil), args...) + } return c.db.QueryContext(ctx, query, args...) } @@ -87,14 +364,20 @@ func (r rowsAffectedResult) RowsAffected() (int64, error) { return int64(r), nil type recordingSQLExecutor struct { result sql.Result err error + afterExec func() execQueries []string + execArgs [][]any } func (e *recordingSQLExecutor) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) { e.execQueries = append(e.execQueries, query) + e.execArgs = append(e.execArgs, append([]any(nil), args...)) if e.err != nil { return nil, e.err } + if e.afterExec != nil { + e.afterExec() + } return e.result, nil } diff --git a/backend/internal/repository/grok_oauth_client.go b/backend/internal/repository/grok_oauth_client.go index 6c9c2c407f..38f6cfb96e 100644 --- a/backend/internal/repository/grok_oauth_client.go +++ b/backend/internal/repository/grok_oauth_client.go @@ -153,14 +153,29 @@ func grokOAuthStatusError(code, message string, resp *req.Response) error { statusCode := http.StatusBadGateway errorCode := code upstreamStatus := 0 - if resp != nil && resp.StatusCode == http.StatusForbidden { - statusCode = http.StatusForbidden - errorCode = "GROK_OAUTH_ENTITLEMENT_DENIED" - } body := "" if resp != nil { upstreamStatus = resp.StatusCode body = logredact.RedactText(resp.String()) + if resp.StatusCode == http.StatusForbidden && grokOAuthHasExplicitEntitlementDenial(body) { + statusCode = http.StatusForbidden + errorCode = "GROK_OAUTH_ENTITLEMENT_DENIED" + } } return infraerrors.Newf(statusCode, errorCode, "%s: status %d, body: %s", message, upstreamStatus, body) } + +func grokOAuthHasExplicitEntitlementDenial(body string) bool { + lower := strings.ToLower(body) + compact := strings.NewReplacer(" ", "", "\n", "", "\r", "", "\t", "").Replace(lower) + for _, field := range []string{"error", "code", "reason"} { + for _, value := range []string{"access_denied", "entitlement_denied", "subscription_required", "no_active_subscription"} { + if strings.Contains(compact, `"`+field+`":"`+value+`"`) { + return true + } + } + } + return strings.Contains(lower, "entitlement denied") || + strings.Contains(lower, "subscription required") || + strings.Contains(lower, "no active grok subscription") +} diff --git a/backend/internal/repository/grok_oauth_client_test.go b/backend/internal/repository/grok_oauth_client_test.go index eabeb641c7..690a8e2139 100644 --- a/backend/internal/repository/grok_oauth_client_test.go +++ b/backend/internal/repository/grok_oauth_client_test.go @@ -50,15 +50,7 @@ func TestGrokOAuthClientExchangeAndRefreshUseFormFields(t *testing.T) { t.Setenv(xai.EnvTokenURL, server.URL) client := NewGrokOAuthClient() - - exchanged, err := client.ExchangeCode( - context.Background(), - "auth-code", - "verifier", - "http://127.0.0.1:56121/callback", - "", - "client-id", - ) + exchanged, err := client.ExchangeCode(context.Background(), "auth-code", "verifier", "http://127.0.0.1:56121/callback", "", "client-id") require.NoError(t, err) require.Equal(t, "exchange-access", exchanged.AccessToken) require.Equal(t, "exchange-refresh", exchanged.RefreshToken) @@ -72,18 +64,30 @@ func TestGrokOAuthClientExchangeAndRefreshUseFormFields(t *testing.T) { require.Equal(t, int64(7200), refreshed.ExpiresIn) } -func TestGrokOAuthClientRefreshForbiddenClassifiesEntitlement(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusForbidden) - _, _ = w.Write([]byte(`{"error":"subscription required"}`)) - })) - defer server.Close() - t.Setenv(xai.EnvTokenURL, server.URL) +func TestGrokOAuthClientRefreshForbiddenClassifiesOnlyExplicitEntitlement(t *testing.T) { + tests := []struct { + name string + body string + wantReason string + }{ + {name: "explicit entitlement", body: `{"error":"access_denied"}`, wantReason: "GROK_OAUTH_ENTITLEMENT_DENIED"}, + {name: "generic forbidden", body: `{"error":"forbidden"}`, wantReason: "GROK_OAUTH_TOKEN_REFRESH_FAILED"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusForbidden) + _, _ = w.Write([]byte(tt.body)) + })) + defer server.Close() + t.Setenv(xai.EnvTokenURL, server.URL) - client := NewGrokOAuthClient() - _, err := client.RefreshToken(context.Background(), "refresh-token", "", "client-id") - require.Error(t, err) - require.Contains(t, strings.ToUpper(err.Error()), "GROK_OAUTH_ENTITLEMENT_DENIED") + client := NewGrokOAuthClient() + _, err := client.RefreshToken(context.Background(), "refresh-token", "", "client-id") + require.Error(t, err) + require.Contains(t, strings.ToUpper(err.Error()), tt.wantReason) + }) + } } func TestGrokOAuthClientStatusErrorRedactsSensitiveResponseBody(t *testing.T) { @@ -105,3 +109,13 @@ func TestGrokOAuthClientStatusErrorRedactsSensitiveResponseBody(t *testing.T) { require.NotContains(t, errText, "refresh-secret") require.NotContains(t, errText, "verifier-secret") } + +func TestGrokOAuthEntitlementDenialRequiresExplicitEvidence(t *testing.T) { + t.Parallel() + + require.True(t, grokOAuthHasExplicitEntitlementDenial(`{"error":"access_denied"}`)) + require.True(t, grokOAuthHasExplicitEntitlementDenial(`{"code":"entitlement_denied"}`)) + require.True(t, grokOAuthHasExplicitEntitlementDenial(`{"message":"no active Grok subscription"}`)) + require.False(t, grokOAuthHasExplicitEntitlementDenial(`{"error":"forbidden","message":"request forbidden"}`)) + require.False(t, grokOAuthHasExplicitEntitlementDenial(`403 Forbidden`)) +} diff --git a/backend/internal/repository/ops_error_where_test.go b/backend/internal/repository/ops_error_where_test.go index c997865ba4..c52461e8ff 100644 --- a/backend/internal/repository/ops_error_where_test.go +++ b/backend/internal/repository/ops_error_where_test.go @@ -101,6 +101,40 @@ func TestBuildOpsErrorLogsWhere_CyberPolicyStatusExemption(t *testing.T) { if strings.Contains(whereRecovered, "status_code") { t.Fatalf("upstream phase with IncludeRecoveredUpstream must not add any status_code clause\nfull: %s", whereRecovered) } + + // account_auth uses the same explicit provider-health opt-in but remains a + // distinct phase from inference upstream errors. + whereAccountAuth, _ := buildOpsErrorLogsWhere(&service.OpsErrorLogFilter{Phase: "account_auth", IncludeRecoveredUpstream: true}) + if strings.Contains(whereAccountAuth, "status_code") { + t.Fatalf("account_auth phase with IncludeRecoveredUpstream must expose recovered rows\nfull: %s", whereAccountAuth) + } + if !strings.Contains(whereAccountAuth, "e.error_phase = $") { + t.Fatalf("account_auth recovered filter must retain its explicit phase\nfull: %s", whereAccountAuth) + } + + whereProviderHealth, _ := buildOpsErrorLogsWhere(&service.OpsErrorLogFilter{ + ErrorPhasesAny: []string{"upstream", "account_auth"}, + IncludeRecoveredUpstream: true, + }) + if strings.Contains(whereProviderHealth, "status_code") { + t.Fatalf("provider-health ANY filter must expose recovered inference and credential rows\nfull: %s", whereProviderHealth) + } + if !strings.Contains(whereProviderHealth, "e.error_phase = ANY($") { + t.Fatalf("provider-health filter must preserve distinct phase values\nfull: %s", whereProviderHealth) + } + + whereUserAccountAuth, _ := buildOpsErrorLogsWhere(&service.OpsErrorLogFilter{ErrorPhasesAny: []string{"account_auth"}}) + if !strings.Contains(whereUserAccountAuth, "COALESCE(e.status_code, 0) >= 400") { + t.Fatalf("request-error account_auth filters must exclude recovered successes\nfull: %s", whereUserAccountAuth) + } + + whereMixed, _ := buildOpsErrorLogsWhere(&service.OpsErrorLogFilter{ + ErrorPhasesAny: []string{"account_auth", "request"}, + IncludeRecoveredUpstream: true, + }) + if !strings.Contains(whereMixed, "COALESCE(e.status_code, 0) >= 400") { + t.Fatalf("recovered opt-in must not bypass the guard for non-provider phases\nfull: %s", whereMixed) + } } func TestBuildOpsErrorLogsWhere_MatchDeletedKeyOwner(t *testing.T) { diff --git a/backend/internal/repository/ops_repo.go b/backend/internal/repository/ops_repo.go index 900abcf212..635bcd1a1f 100644 --- a/backend/internal/repository/ops_repo.go +++ b/backend/internal/repository/ops_repo.go @@ -160,7 +160,7 @@ func opsInsertErrorLogArgs(input *service.OpsInsertErrorLogInput) []any { opsNullString(input.ErrorBody), opsNullString(input.ErrorSource), opsNullString(input.ErrorOwner), - opsNullInt(input.UpstreamStatusCode), + opsNullableIntPointer(input.UpstreamStatusCode), opsNullString(input.UpstreamErrorMessage), opsNullString(input.UpstreamErrorDetail), opsNullString(input.UpstreamErrorsJSON), @@ -582,7 +582,7 @@ LIMIT 1` s := clientIP.String out.ClientIP = &s } - if upstreamStatusCode.Valid && upstreamStatusCode.Int64 > 0 { + if upstreamStatusCode.Valid { v := int(upstreamStatusCode.Int64) out.UpstreamStatusCode = &v } @@ -978,13 +978,13 @@ func buildOpsErrorLogsWhere(filter *service.OpsErrorLogFilter) (string, []any) { resolvedFilter = filter.Resolved } // Keep list endpoints scoped to client errors unless the caller explicitly opts - // into recovered upstream rows (Phase=="upstream" + IncludeRecoveredUpstream, - // ops 专用上游列表)。请求错误语义的端点即便过滤 phase=upstream 也保留该守卫。 + // into recovered provider-health rows (upstream/account_auth). Request-error + // endpoints never set the opt-in and retain this guard. // cyber_policy is exempt from the status >= 400 guard: streaming cyber hits arrive with // status 200 (the SSE stream opened successfully before upstream returned response.failed), // but they are always client-visible blocked requests that belong in admin + user error // lists. Without the exemption the entire streaming-path cyber sink would be invisible. - if phaseFilter != "upstream" || filter == nil || !filter.IncludeRecoveredUpstream { + if !opsFilterIncludesRecoveredProviderRows(filter, phaseFilter) { clauses = append(clauses, "(COALESCE(e.status_code, 0) >= 400 OR e.error_type = 'cyber_policy')") } @@ -1117,6 +1117,28 @@ func buildOpsErrorLogsWhere(filter *service.OpsErrorLogFilter) (string, []any) { return "WHERE " + strings.Join(clauses, " AND "), args } +func opsFilterIncludesRecoveredProviderRows(filter *service.OpsErrorLogFilter, phaseFilter string) bool { + if filter == nil || !filter.IncludeRecoveredUpstream { + return false + } + if phaseFilter != "" { + return phaseFilter == "upstream" || phaseFilter == "account_auth" + } + if len(filter.ErrorPhasesAny) == 0 { + return false + } + sawProviderPhase := false + for _, rawPhase := range filter.ErrorPhasesAny { + switch strings.TrimSpace(strings.ToLower(rawPhase)) { + case "upstream", "account_auth": + sawProviderPhase = true + default: + return false + } + } + return sawProviderPhase +} + func buildOpsSystemLogsWhere(filter *service.OpsSystemLogFilter) (string, []any, bool) { clauses := make([]string, 0, 10) args := make([]any, 0, 10) @@ -1269,6 +1291,16 @@ func opsNullInt(v any) any { } } +// opsNullableIntPointer distinguishes an absent value from an explicitly +// observed zero. Credential-stage failures intentionally persist upstream +// status 0 because no inference request was sent. +func opsNullableIntPointer(v *int) any { + if v == nil { + return sql.NullInt64{} + } + return sql.NullInt64{Int64: int64(*v), Valid: true} +} + func opsNullInt16(v *int16) any { if v == nil { return sql.NullInt64{} diff --git a/backend/internal/repository/ops_repo_args_test.go b/backend/internal/repository/ops_repo_args_test.go new file mode 100644 index 0000000000..5a88758f0a --- /dev/null +++ b/backend/internal/repository/ops_repo_args_test.go @@ -0,0 +1,37 @@ +//go:build unit + +package repository + +import ( + "database/sql" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestOpsInsertErrorLogArgsPreservesExplicitZeroUpstreamStatus(t *testing.T) { + zero := 0 + args := opsInsertErrorLogArgs(&service.OpsInsertErrorLogInput{UpstreamStatusCode: &zero}) + + require.Len(t, args, 41) + encoded, ok := args[27].(sql.NullInt64) + require.True(t, ok) + require.True(t, encoded.Valid) + require.Zero(t, encoded.Int64) +} + +func TestOpsNullableIntPointerDistinguishesNilZeroAndStatus(t *testing.T) { + missing := opsNullableIntPointer(nil).(sql.NullInt64) + require.False(t, missing.Valid) + + zeroValue := 0 + zero := opsNullableIntPointer(&zeroValue).(sql.NullInt64) + require.True(t, zero.Valid) + require.Zero(t, zero.Int64) + + statusValue := 503 + status := opsNullableIntPointer(&statusValue).(sql.NullInt64) + require.True(t, status.Valid) + require.EqualValues(t, 503, status.Int64) +} diff --git a/backend/internal/repository/ops_repo_get_error_log_by_id_integration_test.go b/backend/internal/repository/ops_repo_get_error_log_by_id_integration_test.go index 470b1c0d0b..1411002be0 100644 --- a/backend/internal/repository/ops_repo_get_error_log_by_id_integration_test.go +++ b/backend/internal/repository/ops_repo_get_error_log_by_id_integration_test.go @@ -91,4 +91,21 @@ func TestGetErrorLogByID_DeletedKeyOwner(t *testing.T) { require.Equal(t, "sk-valid", valid.APIKeyPrefix) require.Empty(t, valid.AttemptedKeyPrefix, "attempted prefix and api key prefix are mutually exclusive") require.Nil(t, valid.DeletedKeyOwnerUserID, "valid key error has no deleted owner") + + // ── Case 4: account_auth with no inference attempt preserves explicit 0 ── + zero := 0 + credentialFailureID, err := repo.InsertErrorLog(ctx, &service.OpsInsertErrorLogInput{ + ErrorPhase: "account_auth", + ErrorType: "upstream_error", + Severity: "error", + StatusCode: 503, + UpstreamStatusCode: &zero, + CreatedAt: time.Now(), + }) + require.NoError(t, err) + + credentialFailure, err := repo.GetErrorLogByID(ctx, credentialFailureID) + require.NoError(t, err) + require.NotNil(t, credentialFailure.UpstreamStatusCode) + require.Zero(t, *credentialFailure.UpstreamStatusCode) } diff --git a/backend/internal/repository/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go index c68bcf96e6..b3cccefff9 100644 --- a/backend/internal/repository/scheduler_cache.go +++ b/backend/internal/repository/scheduler_cache.go @@ -2,6 +2,8 @@ package repository import ( "context" + "crypto/rand" + "encoding/hex" "encoding/json" "fmt" "log/slog" @@ -20,6 +22,8 @@ const ( schedulerActivePrefix = "sched:active:" schedulerReadyPrefix = "sched:ready:" schedulerVersionPrefix = "sched:ver:" + schedulerEpochPrefix = "sched:epoch:" + schedulerRetiredPrefix = "sched:retired:" schedulerSnapshotPrefix = "sched:" schedulerLockPrefix = "sched:lock:" @@ -31,7 +35,116 @@ const ( snapshotGraceTTLSeconds = 60 ) +const ( + schedulerGroupLifecycleLockPrefix = "sched:group:lifecycle-lock:" + schedulerGroupLifecycleOwnerTokenBytes = 16 +) + var ( + // epoch 标识 bucket writer 的代际,retired key 是持久退休标记。 + // Capture、allocate、activate 都在 Lua 内同时校验两者:-1 表示已退休,-2 表示 epoch 无效或与 token 代际不匹配; + // allocate 与 activate 的双重校验可拦截快照写入期间发生的 Retire。 + // Retire 仅在首次退休时推进 epoch,Reopen 只清除标记并沿用该代际,因此重复调用保持幂等。 + captureBucketWriteTokenScript = redis.NewScript(` +if redis.call('EXISTS', KEYS[2]) == 1 then + return -1 +end + +local currentEpoch = redis.call('GET', KEYS[1]) +if currentEpoch == false then + redis.call('SET', KEYS[1], '1') + return 1 +end + +local parsedEpoch = tonumber(currentEpoch) +if parsedEpoch == nil or parsedEpoch < 1 then + return -2 +end +return parsedEpoch +`) + + allocateSnapshotVersionScript = redis.NewScript(` +if redis.call('EXISTS', KEYS[2]) == 1 then + return -1 +end + +local currentEpoch = tonumber(redis.call('GET', KEYS[1])) +local expectedEpoch = tonumber(ARGV[1]) +if currentEpoch == nil or expectedEpoch == nil or currentEpoch ~= expectedEpoch then + return -2 +end + +return redis.call('INCR', KEYS[3]) +`) + + retireBucketScript = redis.NewScript(` +local retired = redis.call('GET', KEYS[2]) +local currentEpoch = tonumber(redis.call('GET', KEYS[1])) or 0 + +if retired == false then + currentEpoch = currentEpoch + 1 + if currentEpoch < 1 then + currentEpoch = 1 + end + redis.call('SET', KEYS[1], tostring(currentEpoch)) + redis.call('SET', KEYS[2], tostring(currentEpoch)) +elseif currentEpoch < 1 then + currentEpoch = tonumber(retired) or 1 + redis.call('SET', KEYS[1], tostring(currentEpoch)) +end + +redis.call('SREM', KEYS[3], ARGV[1]) +local currentActive = redis.call('GET', KEYS[5]) +if currentActive ~= false then + redis.call('EXPIRE', ARGV[2] .. currentActive, tonumber(ARGV[3])) +end +redis.call('DEL', KEYS[4], KEYS[5]) +return currentEpoch +`) + + reopenBucketScript = redis.NewScript(` +local currentEpochRaw = redis.call('GET', KEYS[1]) +local currentEpoch = tonumber(currentEpochRaw) +local retiredEpochRaw = redis.call('GET', KEYS[2]) + +if retiredEpochRaw == false then + if currentEpochRaw == false then + redis.call('SET', KEYS[1], '1') + return 1 + end + if currentEpoch == nil or currentEpoch < 1 then + return -2 + end + return currentEpoch +end + +local retiredEpoch = tonumber(retiredEpochRaw) +if retiredEpoch == nil or retiredEpoch < 1 then + return -2 +end +if currentEpoch == nil or currentEpoch < retiredEpoch then + currentEpoch = retiredEpoch +end + +redis.call('SET', KEYS[1], tostring(currentEpoch)) +redis.call('DEL', KEYS[2]) +redis.call('SREM', KEYS[3], ARGV[1]) +local currentActive = redis.call('GET', KEYS[5]) +if currentActive ~= false then + redis.call('EXPIRE', ARGV[2] .. currentActive, tonumber(ARGV[3])) +end +redis.call('DEL', KEYS[4], KEYS[5]) +return currentEpoch +`) + + // 释放租约必须先比较所有者令牌再删除,过期持有者的延迟释放不能误删继任租约。 + releaseGroupLifecycleLeaseScript = redis.NewScript(` +if redis.call('GET', KEYS[1]) == ARGV[1] then + return redis.call('DEL', KEYS[1]) +end +return 0 +`) + // activateSnapshotScript 原子 CAS 切换快照版本。 // 仅当新版本号 >= 当前激活版本时才切换,防止并发写入导致版本回滚。 // 旧快照使用 EXPIRE 设置宽限期而非立即 DEL,避免与 reader 竞态。 @@ -40,13 +153,28 @@ var ( // KEYS[2] = readyKey (sched:ready:{bucket}) // KEYS[3] = bucketSetKey (sched:buckets) // KEYS[4] = snapshotKey (新写入的快照 key) + // KEYS[5] = epochKey + // KEYS[6] = retiredKey // ARGV[1] = 新版本号字符串 // ARGV[2] = bucket 字符串 (用于 SADD) // ARGV[3] = 快照 key 前缀 (用于构造旧快照 key) // ARGV[4] = 宽限期 TTL 秒数 + // ARGV[5] = writer epoch // // 返回 1 = 已激活, 0 = 版本过旧未激活 activateSnapshotScript = redis.NewScript(` +if redis.call('EXISTS', KEYS[6]) == 1 then + redis.call('DEL', KEYS[4]) + return -1 +end + +local currentEpoch = tonumber(redis.call('GET', KEYS[5])) +local expectedEpoch = tonumber(ARGV[5]) +if currentEpoch == nil or expectedEpoch == nil or currentEpoch ~= expectedEpoch then + redis.call('DEL', KEYS[4]) + return -2 +end + local currentActive = redis.call('GET', KEYS[1]) local newVersion = tonumber(ARGV[1]) @@ -151,19 +279,139 @@ func (c *schedulerCache) GetSnapshot(ctx context.Context, bucket service.Schedul return accounts, true, nil } -func (c *schedulerCache) SetSnapshot(ctx context.Context, bucket service.SchedulerBucket, accounts []service.Account) error { - // Phase 1: 分配新版本号并写入快照数据。 - // INCR 保证每个调用方获得唯一递增版本号。 - // 写入的 snapshotKey 是新的版本化 key,reader 尚不知晓,因此无竞态。 - versionKey := schedulerBucketKey(schedulerVersionPrefix, bucket) - version, err := c.rdb.Incr(ctx, versionKey).Result() +func (c *schedulerCache) CaptureBucketWriteToken(ctx context.Context, bucket service.SchedulerBucket) (service.SchedulerBucketWriteToken, error) { + result, err := captureBucketWriteTokenScript.Run(ctx, c.rdb, []string{ + schedulerBucketKey(schedulerEpochPrefix, bucket), + schedulerBucketKey(schedulerRetiredPrefix, bucket), + }).Int64() + if err != nil { + return service.SchedulerBucketWriteToken{}, err + } + if err := schedulerBucketWriteResultError(result, bucket); err != nil { + return service.SchedulerBucketWriteToken{}, err + } + return service.SchedulerBucketWriteToken{Bucket: bucket, Epoch: result}, nil +} + +func (c *schedulerCache) RetireBucket(ctx context.Context, bucket service.SchedulerBucket) error { + snapshotKeyPrefix := fmt.Sprintf("%s%d:%s:%s:v", schedulerSnapshotPrefix, bucket.GroupID, bucket.Platform, bucket.Mode) + result, err := retireBucketScript.Run(ctx, c.rdb, []string{ + schedulerBucketKey(schedulerEpochPrefix, bucket), + schedulerBucketKey(schedulerRetiredPrefix, bucket), + schedulerBucketSetKey, + schedulerBucketKey(schedulerReadyPrefix, bucket), + schedulerBucketKey(schedulerActivePrefix, bucket), + }, bucket.String(), snapshotKeyPrefix, snapshotGraceTTLSeconds).Int64() if err != nil { return err } + if result < 1 { + return fmt.Errorf("retire scheduler bucket %s returned invalid epoch %d", bucket.String(), result) + } + return nil +} - versionStr := strconv.FormatInt(version, 10) - snapshotKey := schedulerSnapshotKey(bucket, versionStr) +func (c *schedulerCache) ReopenBucket(ctx context.Context, bucket service.SchedulerBucket) (service.SchedulerBucketWriteToken, error) { + snapshotKeyPrefix := fmt.Sprintf("%s%d:%s:%s:v", schedulerSnapshotPrefix, bucket.GroupID, bucket.Platform, bucket.Mode) + result, err := reopenBucketScript.Run(ctx, c.rdb, []string{ + schedulerBucketKey(schedulerEpochPrefix, bucket), + schedulerBucketKey(schedulerRetiredPrefix, bucket), + schedulerBucketSetKey, + schedulerBucketKey(schedulerReadyPrefix, bucket), + schedulerBucketKey(schedulerActivePrefix, bucket), + }, bucket.String(), snapshotKeyPrefix, snapshotGraceTTLSeconds).Int64() + if err != nil { + return service.SchedulerBucketWriteToken{}, err + } + if err := schedulerBucketWriteResultError(result, bucket); err != nil { + return service.SchedulerBucketWriteToken{}, err + } + return service.SchedulerBucketWriteToken{Bucket: bucket, Epoch: result}, nil +} +func (c *schedulerCache) TryAcquireGroupLifecycleLease(ctx context.Context, groupID int64, ttl time.Duration) (service.SchedulerGroupLifecycleLease, bool, error) { + if groupID <= 0 { + return service.SchedulerGroupLifecycleLease{}, false, fmt.Errorf("%w: group id must be positive", service.ErrSchedulerGroupLifecycleLeaseInvalid) + } + if ttl <= 0 { + return service.SchedulerGroupLifecycleLease{}, false, fmt.Errorf("%w: ttl must be positive", service.ErrSchedulerGroupLifecycleLeaseInvalid) + } + ownerToken, err := newSchedulerGroupLifecycleOwnerToken() + if err != nil { + return service.SchedulerGroupLifecycleLease{}, false, err + } + acquired, err := c.rdb.SetNX(ctx, schedulerGroupLifecycleLockKey(groupID), ownerToken, ttl).Result() + if err != nil { + return service.SchedulerGroupLifecycleLease{}, false, err + } + if !acquired { + return service.SchedulerGroupLifecycleLease{}, false, nil + } + return service.SchedulerGroupLifecycleLease{GroupID: groupID, OwnerToken: ownerToken}, true, nil +} + +func (c *schedulerCache) ReleaseGroupLifecycleLease(ctx context.Context, lease service.SchedulerGroupLifecycleLease) error { + if !lease.ValidFor(lease.GroupID) { + return service.ErrSchedulerGroupLifecycleLeaseInvalid + } + result, err := releaseGroupLifecycleLeaseScript.Run( + ctx, + c.rdb, + []string{schedulerGroupLifecycleLockKey(lease.GroupID)}, + lease.OwnerToken, + ).Int64() + if err != nil { + return err + } + if result == 0 { + return fmt.Errorf("%w: group=%d", service.ErrSchedulerGroupLifecycleLeaseLost, lease.GroupID) + } + if result != 1 { + return fmt.Errorf("release scheduler group lifecycle lease returned %d", result) + } + return nil +} + +func newSchedulerGroupLifecycleOwnerToken() (string, error) { + raw := make([]byte, schedulerGroupLifecycleOwnerTokenBytes) + if _, err := rand.Read(raw); err != nil { + return "", fmt.Errorf("generate scheduler group lifecycle owner token: %w", err) + } + return hex.EncodeToString(raw), nil +} + +func (c *schedulerCache) SetSnapshot(ctx context.Context, bucket service.SchedulerBucket, token service.SchedulerBucketWriteToken, accounts []service.Account) error { + if !token.ValidFor(bucket) { + return fmt.Errorf("%w: bucket=%s", service.ErrSchedulerBucketWriteFenced, bucket.String()) + } + // 分配版本与激活指针是两个 fencing 边界;中间写入的数据只有通过第二次校验才能发布。 + version, err := c.allocateSnapshotVersion(ctx, bucket, token) + if err != nil { + return err + } + if err := c.writeSnapshotVersion(ctx, bucket, version, accounts); err != nil { + return err + } + return c.activateSnapshotVersion(ctx, bucket, token, version) +} + +func (c *schedulerCache) allocateSnapshotVersion(ctx context.Context, bucket service.SchedulerBucket, token service.SchedulerBucketWriteToken) (string, error) { + result, err := allocateSnapshotVersionScript.Run(ctx, c.rdb, []string{ + schedulerBucketKey(schedulerEpochPrefix, bucket), + schedulerBucketKey(schedulerRetiredPrefix, bucket), + schedulerBucketKey(schedulerVersionPrefix, bucket), + }, token.Epoch).Int64() + if err != nil { + return "", err + } + if err := schedulerBucketWriteResultError(result, bucket); err != nil { + return "", err + } + return strconv.FormatInt(result, 10), nil +} + +func (c *schedulerCache) writeSnapshotVersion(ctx context.Context, bucket service.SchedulerBucket, version string, accounts []service.Account) error { + snapshotKey := schedulerSnapshotKey(bucket, version) cacheableAccounts, err := c.writeAccounts(ctx, accounts) if err != nil { return err @@ -191,7 +439,12 @@ func (c *schedulerCache) SetSnapshot(ctx context.Context, bucket service.Schedul } } - // Phase 2: 原子 CAS 激活版本。 + return nil +} + +func (c *schedulerCache) activateSnapshotVersion(ctx context.Context, bucket service.SchedulerBucket, token service.SchedulerBucketWriteToken, version string) error { + snapshotKey := schedulerSnapshotKey(bucket, version) + // Phase 2: 原子 CAS 切换版本,同时再次校验退休状态与 writer epoch。 // Lua 脚本保证:仅当新版本 >= 当前激活版本时才切换 active 指针, // 防止并发写入导致版本回滚。 // 旧快照使用 EXPIRE 宽限期而非立即 DEL,避免 reader 竞态。 @@ -199,15 +452,32 @@ func (c *schedulerCache) SetSnapshot(ctx context.Context, bucket service.Schedul readyKey := schedulerBucketKey(schedulerReadyPrefix, bucket) snapshotKeyPrefix := fmt.Sprintf("%s%d:%s:%s:v", schedulerSnapshotPrefix, bucket.GroupID, bucket.Platform, bucket.Mode) - keys := []string{activeKey, readyKey, schedulerBucketSetKey, snapshotKey} - args := []any{versionStr, bucket.String(), snapshotKeyPrefix, snapshotGraceTTLSeconds} + keys := []string{ + activeKey, + readyKey, + schedulerBucketSetKey, + snapshotKey, + schedulerBucketKey(schedulerEpochPrefix, bucket), + schedulerBucketKey(schedulerRetiredPrefix, bucket), + } + args := []any{version, bucket.String(), snapshotKeyPrefix, snapshotGraceTTLSeconds, token.Epoch} - _, err = activateSnapshotScript.Run(ctx, c.rdb, keys, args...).Result() + result, err := activateSnapshotScript.Run(ctx, c.rdb, keys, args...).Int64() if err != nil { return err } + return schedulerBucketWriteResultError(result, bucket) +} - return nil +func schedulerBucketWriteResultError(result int64, bucket service.SchedulerBucket) error { + switch result { + case -1: + return fmt.Errorf("%w: bucket=%s", service.ErrSchedulerBucketRetired, bucket.String()) + case -2: + return fmt.Errorf("%w: bucket=%s", service.ErrSchedulerBucketWriteFenced, bucket.String()) + default: + return nil + } } func (c *schedulerCache) GetAccount(ctx context.Context, accountID int64) (*service.Account, error) { @@ -336,6 +606,10 @@ func schedulerBucketKey(prefix string, bucket service.SchedulerBucket) string { return fmt.Sprintf("%s%d:%s:%s", prefix, bucket.GroupID, bucket.Platform, bucket.Mode) } +func schedulerGroupLifecycleLockKey(groupID int64) string { + return schedulerGroupLifecycleLockPrefix + strconv.FormatInt(groupID, 10) +} + func schedulerSnapshotKey(bucket service.SchedulerBucket, version string) string { return fmt.Sprintf("%s%d:%s:%s:v%s", schedulerSnapshotPrefix, bucket.GroupID, bucket.Platform, bucket.Mode, version) } diff --git a/backend/internal/repository/scheduler_cache_integration_test.go b/backend/internal/repository/scheduler_cache_integration_test.go index 948c2c73e0..52673315c8 100644 --- a/backend/internal/repository/scheduler_cache_integration_test.go +++ b/backend/internal/repository/scheduler_cache_integration_test.go @@ -67,7 +67,9 @@ func TestSchedulerCacheSnapshotUsesSlimMetadataButKeepsFullAccount(t *testing.T) }, } - require.NoError(t, cache.SetSnapshot(ctx, bucket, []service.Account{account})) + token, err := cache.CaptureBucketWriteToken(ctx, bucket) + require.NoError(t, err) + require.NoError(t, cache.SetSnapshot(ctx, bucket, token, []service.Account{account})) snapshot, hit, err := cache.GetSnapshot(ctx, bucket) require.NoError(t, err) @@ -102,3 +104,73 @@ func TestSchedulerCacheSnapshotUsesSlimMetadataButKeepsFullAccount(t *testing.T) require.Len(t, full.AccountGroups, 1) require.NotNil(t, full.AccountGroups[0].Group) } + +func TestSchedulerCacheRetireAndReopenFencesOldEpochIntegration(t *testing.T) { + ctx := context.Background() + rdb := testRedis(t) + cache := NewSchedulerCache(rdb) + bucket := service.SchedulerBucket{GroupID: 77, Platform: service.PlatformAntigravity, Mode: service.SchedulerModeForced} + account := service.Account{ID: 7701, Platform: service.PlatformAntigravity, Type: service.AccountTypeOAuth} + + oldToken, err := cache.CaptureBucketWriteToken(ctx, bucket) + require.NoError(t, err) + require.NoError(t, cache.SetSnapshot(ctx, bucket, oldToken, []service.Account{account})) + require.NoError(t, cache.RetireBucket(ctx, bucket)) + require.NoError(t, cache.RetireBucket(ctx, bucket)) + + _, hit, err := cache.GetSnapshot(ctx, bucket) + require.NoError(t, err) + require.False(t, hit) + _, err = cache.CaptureBucketWriteToken(ctx, bucket) + require.ErrorIs(t, err, service.ErrSchedulerBucketRetired) + require.ErrorIs(t, cache.SetSnapshot(ctx, bucket, oldToken, []service.Account{account}), service.ErrSchedulerBucketRetired) + + newToken, err := cache.ReopenBucket(ctx, bucket) + require.NoError(t, err) + require.Greater(t, newToken.Epoch, oldToken.Epoch) + require.ErrorIs(t, cache.SetSnapshot(ctx, bucket, oldToken, []service.Account{account}), service.ErrSchedulerBucketWriteFenced) + require.NoError(t, cache.SetSnapshot(ctx, bucket, newToken, []service.Account{account})) + + snapshot, hit, err := cache.GetSnapshot(ctx, bucket) + require.NoError(t, err) + require.True(t, hit) + require.Len(t, snapshot, 1) + require.Equal(t, account.ID, snapshot[0].ID) +} + +func TestSchedulerCacheGroupLifecycleLeaseOwnerAndTTLIntegration(t *testing.T) { + ctx := context.Background() + rdb := testRedis(t) + cache := NewSchedulerCache(rdb) + const groupID int64 = 78 + const ttl = 500 * time.Millisecond + + first, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, groupID, ttl) + require.NoError(t, err) + require.True(t, acquired) + pttl, err := rdb.PTTL(ctx, schedulerGroupLifecycleLockKey(groupID)).Result() + require.NoError(t, err) + require.Positive(t, pttl) + require.LessOrEqual(t, pttl, ttl) + + var second service.SchedulerGroupLifecycleLease + require.Eventually(t, func() bool { + var acquireErr error + second, acquired, acquireErr = cache.TryAcquireGroupLifecycleLease(ctx, groupID, time.Minute) + return acquireErr == nil && acquired + }, 5*time.Second, 20*time.Millisecond) + require.NotEqual(t, first.OwnerToken, second.OwnerToken) + + require.ErrorIs(t, cache.ReleaseGroupLifecycleLease(ctx, first), service.ErrSchedulerGroupLifecycleLeaseLost) + _, acquired, err = cache.TryAcquireGroupLifecycleLease(ctx, groupID, time.Minute) + require.NoError(t, err) + require.False(t, acquired, "a stale release must not delete the successor lease") + + require.NoError(t, cache.ReleaseGroupLifecycleLease(ctx, second)) + require.ErrorIs(t, cache.ReleaseGroupLifecycleLease(ctx, second), service.ErrSchedulerGroupLifecycleLeaseLost) + third, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, groupID, time.Minute) + require.NoError(t, err) + require.True(t, acquired) + require.True(t, third.ValidFor(groupID)) + require.NoError(t, cache.ReleaseGroupLifecycleLease(ctx, third)) +} diff --git a/backend/internal/repository/scheduler_cache_unit_test.go b/backend/internal/repository/scheduler_cache_unit_test.go index ecca7f3892..f933603c47 100644 --- a/backend/internal/repository/scheduler_cache_unit_test.go +++ b/backend/internal/repository/scheduler_cache_unit_test.go @@ -4,6 +4,8 @@ package repository import ( "context" + "encoding/hex" + "strings" "testing" "time" @@ -14,13 +16,18 @@ import ( ) func newSchedulerCacheUnit(t *testing.T) *schedulerCache { + cache, _ := newSchedulerCacheUnitWithRedis(t) + return cache +} + +func newSchedulerCacheUnitWithRedis(t *testing.T) (*schedulerCache, *miniredis.Miniredis) { t.Helper() mr := miniredis.RunT(t) rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()}) t.Cleanup(func() { _ = rdb.Close() }) cache, ok := newSchedulerCacheWithChunkSizes(rdb, defaultSchedulerSnapshotMGetChunkSize, defaultSchedulerSnapshotWriteChunkSize).(*schedulerCache) require.True(t, ok) - return cache + return cache, mr } func TestSchedulerCacheWriteAccountsSkipsUnencodableTimes(t *testing.T) { @@ -229,3 +236,378 @@ func TestBuildSchedulerMetadataAccount_KeepsSparkShadowRoutingIdentity(t *testin require.Equal(t, map[string]any{"gpt-5.4": "gpt-5.4-openai-compact"}, got.Credentials["compact_model_mapping"]) require.Nil(t, got.Credentials["access_token"]) } + +func TestSchedulerCacheBucketRetirementFencesWritersAndReopen(t *testing.T) { + ctx := context.Background() + cache, mr := newSchedulerCacheUnitWithRedis(t) + bucket := service.SchedulerBucket{GroupID: 41, Platform: service.PlatformOpenAI, Mode: service.SchedulerModeSingle} + otherBucket := service.SchedulerBucket{GroupID: 42, Platform: service.PlatformOpenAI, Mode: service.SchedulerModeSingle} + account := service.Account{ID: 4101, Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey} + + token, err := cache.CaptureBucketWriteToken(ctx, bucket) + require.NoError(t, err) + require.True(t, token.ValidFor(bucket)) + require.NoError(t, cache.SetSnapshot(ctx, bucket, token, []service.Account{account})) + + // A token is bound to the full bucket identity, not just an epoch number. + err = cache.SetSnapshot(ctx, otherBucket, token, []service.Account{account}) + require.ErrorIs(t, err, service.ErrSchedulerBucketWriteFenced) + _, err = cache.rdb.Get(ctx, schedulerBucketKey(schedulerVersionPrefix, otherBucket)).Result() + require.ErrorIs(t, err, redis.Nil) + otherAccount := service.Account{ID: 4201, Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey} + otherToken, err := cache.CaptureBucketWriteToken(ctx, otherBucket) + require.NoError(t, err) + require.NoError(t, cache.SetSnapshot(ctx, otherBucket, otherToken, []service.Account{otherAccount})) + otherEpoch := otherToken.Epoch + + activeVersion, err := cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucket)).Result() + require.NoError(t, err) + require.NoError(t, cache.RetireBucket(ctx, bucket)) + retiredEpoch, err := cache.rdb.Get(ctx, schedulerBucketKey(schedulerEpochPrefix, bucket)).Int64() + require.NoError(t, err) + require.Greater(t, retiredEpoch, token.Epoch) + + // Retirement is idempotent and does not advance the epoch again. + require.NoError(t, cache.RetireBucket(ctx, bucket)) + retiredEpochAgain, err := cache.rdb.Get(ctx, schedulerBucketKey(schedulerEpochPrefix, bucket)).Int64() + require.NoError(t, err) + require.Equal(t, retiredEpoch, retiredEpochAgain) + + // New readers miss because ready/active were removed atomically. A reader that + // captured activeVersion before retirement may still finish against that version. + _, hit, err := cache.GetSnapshot(ctx, bucket) + require.NoError(t, err) + require.False(t, hit) + ids, err := cache.rdb.ZRange(ctx, schedulerSnapshotKey(bucket, activeVersion), 0, -1).Result() + require.NoError(t, err) + require.Equal(t, []string{"4101"}, ids) + ttl, err := cache.rdb.TTL(ctx, schedulerSnapshotKey(bucket, activeVersion)).Result() + require.NoError(t, err) + require.Positive(t, ttl) + require.LessOrEqual(t, ttl, time.Duration(snapshotGraceTTLSeconds)*time.Second) + + buckets, err := cache.ListBuckets(ctx) + require.NoError(t, err) + require.NotContains(t, buckets, bucket) + require.Contains(t, buckets, otherBucket) + otherSnapshot, otherHit, err := cache.GetSnapshot(ctx, otherBucket) + require.NoError(t, err) + require.True(t, otherHit) + require.Len(t, otherSnapshot, 1) + require.Equal(t, otherAccount.ID, otherSnapshot[0].ID) + otherEpochAfter, err := cache.rdb.Get(ctx, schedulerBucketKey(schedulerEpochPrefix, otherBucket)).Int64() + require.NoError(t, err) + require.Equal(t, otherEpoch, otherEpochAfter) + + _, err = cache.CaptureBucketWriteToken(ctx, bucket) + require.ErrorIs(t, err, service.ErrSchedulerBucketRetired) + versionBeforeRejectedWrite, err := cache.rdb.Get(ctx, schedulerBucketKey(schedulerVersionPrefix, bucket)).Int64() + require.NoError(t, err) + err = cache.SetSnapshot(ctx, bucket, token, []service.Account{account}) + require.ErrorIs(t, err, service.ErrSchedulerBucketRetired) + versionAfterRejectedWrite, err := cache.rdb.Get(ctx, schedulerBucketKey(schedulerVersionPrefix, bucket)).Int64() + require.NoError(t, err) + require.Equal(t, versionBeforeRejectedWrite, versionAfterRejectedWrite, "fenced writers must not allocate a new version") + retired, err := cache.rdb.Exists(ctx, schedulerBucketKey(schedulerRetiredPrefix, bucket)).Result() + require.NoError(t, err) + require.EqualValues(t, 1, retired, "ordinary writers must never clear the tombstone") + mr.FastForward(time.Duration(snapshotGraceTTLSeconds+1) * time.Second) + exists, err := cache.rdb.Exists(ctx, schedulerSnapshotKey(bucket, activeVersion)).Result() + require.NoError(t, err) + require.Zero(t, exists, "retired active snapshot must expire after the in-flight grace period") + + newToken, err := cache.ReopenBucket(ctx, bucket) + require.NoError(t, err) + require.True(t, newToken.ValidFor(bucket)) + require.Equal(t, retiredEpoch, newToken.Epoch) + reopenedAgain, err := cache.ReopenBucket(ctx, bucket) + require.NoError(t, err) + require.Equal(t, newToken, reopenedAgain, "reopen must be idempotent within one retirement generation") + err = cache.SetSnapshot(ctx, bucket, token, []service.Account{account}) + require.ErrorIs(t, err, service.ErrSchedulerBucketWriteFenced) + require.NoError(t, cache.SetSnapshot(ctx, bucket, newToken, []service.Account{account})) + reopenedWhileOpen, err := cache.ReopenBucket(ctx, bucket) + require.NoError(t, err) + require.Equal(t, newToken, reopenedWhileOpen) + + snapshot, hit, err := cache.GetSnapshot(ctx, bucket) + require.NoError(t, err) + require.True(t, hit) + require.Len(t, snapshot, 1) + require.Equal(t, account.ID, snapshot[0].ID) +} + +func TestSchedulerCacheActivationIsFencedAfterRetire(t *testing.T) { + ctx := context.Background() + cache := newSchedulerCacheUnit(t) + bucket := service.SchedulerBucket{GroupID: 51, Platform: service.PlatformAnthropic, Mode: service.SchedulerModeMixed} + account := service.Account{ID: 5101, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey} + + token, err := cache.CaptureBucketWriteToken(ctx, bucket) + require.NoError(t, err) + version, err := cache.allocateSnapshotVersion(ctx, bucket, token) + require.NoError(t, err) + require.NoError(t, cache.writeSnapshotVersion(ctx, bucket, version, []service.Account{account})) + + // Deterministic race C: retirement and authoritative reopen both happen after + // INCR/write but before the old writer activates. + require.NoError(t, cache.RetireBucket(ctx, bucket)) + _, err = cache.ReopenBucket(ctx, bucket) + require.NoError(t, err) + err = cache.activateSnapshotVersion(ctx, bucket, token, version) + require.ErrorIs(t, err, service.ErrSchedulerBucketWriteFenced) + + exists, err := cache.rdb.Exists(ctx, schedulerSnapshotKey(bucket, version)).Result() + require.NoError(t, err) + require.Zero(t, exists, "fenced activation must delete its unpublished snapshot") + exists, err = cache.rdb.Exists( + ctx, + schedulerBucketKey(schedulerReadyPrefix, bucket), + schedulerBucketKey(schedulerActivePrefix, bucket), + ).Result() + require.NoError(t, err) + require.Zero(t, exists) + buckets, err := cache.ListBuckets(ctx) + require.NoError(t, err) + require.NotContains(t, buckets, bucket) +} + +func TestSchedulerCacheConcurrentReopenReturnsSameToken(t *testing.T) { + ctx := context.Background() + cache := newSchedulerCacheUnit(t) + bucket := service.SchedulerBucket{GroupID: 53, Platform: service.PlatformOpenAI, Mode: service.SchedulerModeForced} + account := service.Account{ID: 5301, Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey} + + oldToken, err := cache.CaptureBucketWriteToken(ctx, bucket) + require.NoError(t, err) + require.NoError(t, cache.RetireBucket(ctx, bucket)) + + type reopenResult struct { + token service.SchedulerBucketWriteToken + err error + } + start := make(chan struct{}) + results := make(chan reopenResult, 2) + for range 2 { + go func() { + <-start + token, err := cache.ReopenBucket(ctx, bucket) + results <- reopenResult{token: token, err: err} + }() + } + close(start) + first := <-results + second := <-results + require.NoError(t, first.err) + require.NoError(t, second.err) + require.Equal(t, first.token, second.token) + require.Greater(t, first.token.Epoch, oldToken.Epoch) + + require.ErrorIs(t, cache.SetSnapshot(ctx, bucket, oldToken, []service.Account{account}), service.ErrSchedulerBucketWriteFenced) + require.NoError(t, cache.SetSnapshot(ctx, bucket, first.token, []service.Account{account})) +} + +func TestSchedulerCacheReopenExpiresPreviousActiveSnapshot(t *testing.T) { + ctx := context.Background() + cache, mr := newSchedulerCacheUnitWithRedis(t) + bucket := service.SchedulerBucket{GroupID: 52, Platform: service.PlatformGemini, Mode: service.SchedulerModeForced} + account := service.Account{ID: 5201, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey} + + oldToken, err := cache.CaptureBucketWriteToken(ctx, bucket) + require.NoError(t, err) + require.NoError(t, cache.SetSnapshot(ctx, bucket, oldToken, []service.Account{account})) + oldVersion, err := cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucket)).Result() + require.NoError(t, err) + retiredEpoch := oldToken.Epoch + 1 + require.NoError(t, cache.rdb.Set(ctx, schedulerBucketKey(schedulerEpochPrefix, bucket), retiredEpoch, 0).Err()) + require.NoError(t, cache.rdb.Set(ctx, schedulerBucketKey(schedulerRetiredPrefix, bucket), retiredEpoch, 0).Err()) + + newToken, err := cache.ReopenBucket(ctx, bucket) + require.NoError(t, err) + require.Equal(t, retiredEpoch, newToken.Epoch) + _, hit, err := cache.GetSnapshot(ctx, bucket) + require.NoError(t, err) + require.False(t, hit) + ttl, err := cache.rdb.TTL(ctx, schedulerSnapshotKey(bucket, oldVersion)).Result() + require.NoError(t, err) + require.Positive(t, ttl) + require.LessOrEqual(t, ttl, time.Duration(snapshotGraceTTLSeconds)*time.Second) + + require.ErrorIs(t, cache.SetSnapshot(ctx, bucket, oldToken, []service.Account{account}), service.ErrSchedulerBucketWriteFenced) + mr.FastForward(time.Duration(snapshotGraceTTLSeconds+1) * time.Second) + exists, err := cache.rdb.Exists(ctx, schedulerSnapshotKey(bucket, oldVersion)).Result() + require.NoError(t, err) + require.Zero(t, exists) + require.NoError(t, cache.SetSnapshot(ctx, bucket, newToken, []service.Account{account})) +} + +func TestSchedulerCacheGroupLifecycleLeaseConcurrentAcquireSingleOwner(t *testing.T) { + ctx := context.Background() + cache := newSchedulerCacheUnit(t) + const groupID int64 = 71 + + type result struct { + lease service.SchedulerGroupLifecycleLease + acquired bool + err error + } + start := make(chan struct{}) + results := make(chan result, 32) + for range 32 { + go func() { + <-start + lease, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, groupID, time.Minute) + results <- result{lease: lease, acquired: acquired, err: err} + }() + } + close(start) + + var owner service.SchedulerGroupLifecycleLease + acquiredCount := 0 + for range 32 { + got := <-results + require.NoError(t, got.err) + if got.acquired { + acquiredCount++ + owner = got.lease + require.True(t, got.lease.ValidFor(groupID)) + } else { + require.Equal(t, service.SchedulerGroupLifecycleLease{}, got.lease) + } + } + require.Equal(t, 1, acquiredCount) + require.Len(t, owner.OwnerToken, schedulerGroupLifecycleOwnerTokenBytes*2) + require.Equal(t, strings.ToLower(owner.OwnerToken), owner.OwnerToken) + decodedOwner, err := hex.DecodeString(owner.OwnerToken) + require.NoError(t, err) + require.Len(t, decodedOwner, schedulerGroupLifecycleOwnerTokenBytes) + + require.NoError(t, cache.ReleaseGroupLifecycleLease(ctx, owner)) + next, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, groupID, time.Minute) + require.NoError(t, err) + require.True(t, acquired) + require.True(t, next.ValidFor(groupID)) + require.NotEqual(t, owner.OwnerToken, next.OwnerToken) + require.NoError(t, cache.ReleaseGroupLifecycleLease(ctx, next)) +} + +func TestSchedulerCacheGroupLifecycleLeaseStaleReleaseCannotDeleteSuccessor(t *testing.T) { + ctx := context.Background() + cache, mr := newSchedulerCacheUnitWithRedis(t) + const groupID int64 = 72 + const ttl = time.Minute + + first, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, groupID, ttl) + require.NoError(t, err) + require.True(t, acquired) + + mr.FastForward(ttl + time.Second) + second, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, groupID, ttl) + require.NoError(t, err) + require.True(t, acquired) + require.NotEqual(t, first.OwnerToken, second.OwnerToken) + + require.ErrorIs(t, cache.ReleaseGroupLifecycleLease(ctx, first), service.ErrSchedulerGroupLifecycleLeaseLost) + owner, err := cache.rdb.Get(ctx, schedulerGroupLifecycleLockKey(groupID)).Result() + require.NoError(t, err) + require.Equal(t, second.OwnerToken, owner) + + _, acquired, err = cache.TryAcquireGroupLifecycleLease(ctx, groupID, ttl) + require.NoError(t, err) + require.False(t, acquired) + require.NoError(t, cache.ReleaseGroupLifecycleLease(ctx, second)) + require.ErrorIs(t, cache.ReleaseGroupLifecycleLease(ctx, second), service.ErrSchedulerGroupLifecycleLeaseLost) +} + +func TestSchedulerCacheGroupLifecycleLeaseExpiredReleaseIsLost(t *testing.T) { + ctx := context.Background() + cache, mr := newSchedulerCacheUnitWithRedis(t) + const groupID int64 = 73 + const ttl = time.Minute + + lease, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, groupID, ttl) + require.NoError(t, err) + require.True(t, acquired) + mr.FastForward(ttl + time.Second) + + require.ErrorIs(t, cache.ReleaseGroupLifecycleLease(ctx, lease), service.ErrSchedulerGroupLifecycleLeaseLost) +} + +func TestSchedulerCacheGroupLifecycleLeaseWrongOwnerAndCrossGroupAreLost(t *testing.T) { + ctx := context.Background() + cache := newSchedulerCacheUnit(t) + const firstGroupID int64 = 74 + const secondGroupID int64 = 75 + + first, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, firstGroupID, time.Minute) + require.NoError(t, err) + require.True(t, acquired) + second, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, secondGroupID, time.Minute) + require.NoError(t, err) + require.True(t, acquired, "different groups must acquire independently") + require.NotEqual(t, first.OwnerToken, second.OwnerToken) + + wrongOwner := first + wrongOwner.OwnerToken = strings.Repeat("0", schedulerGroupLifecycleOwnerTokenBytes*2) + if wrongOwner.OwnerToken == first.OwnerToken { + wrongOwner.OwnerToken = strings.Repeat("1", schedulerGroupLifecycleOwnerTokenBytes*2) + } + require.ErrorIs(t, cache.ReleaseGroupLifecycleLease(ctx, wrongOwner), service.ErrSchedulerGroupLifecycleLeaseLost) + + crossGroup := first + crossGroup.GroupID = secondGroupID + require.ErrorIs(t, cache.ReleaseGroupLifecycleLease(ctx, crossGroup), service.ErrSchedulerGroupLifecycleLeaseLost) + + firstOwner, err := cache.rdb.Get(ctx, schedulerGroupLifecycleLockKey(firstGroupID)).Result() + require.NoError(t, err) + require.Equal(t, first.OwnerToken, firstOwner) + secondOwner, err := cache.rdb.Get(ctx, schedulerGroupLifecycleLockKey(secondGroupID)).Result() + require.NoError(t, err) + require.Equal(t, second.OwnerToken, secondOwner) + + require.NoError(t, cache.ReleaseGroupLifecycleLease(ctx, first)) + require.NoError(t, cache.ReleaseGroupLifecycleLease(ctx, second)) +} + +func TestSchedulerCacheGroupLifecycleLeaseCanceledContextFailsClosed(t *testing.T) { + cache := newSchedulerCacheUnit(t) + canceledCtx, cancel := context.WithCancel(context.Background()) + cancel() + + lease, acquired, err := cache.TryAcquireGroupLifecycleLease(canceledCtx, 76, time.Minute) + require.ErrorIs(t, err, context.Canceled) + require.False(t, acquired) + require.Equal(t, service.SchedulerGroupLifecycleLease{}, lease) + + ctx := context.Background() + lease, acquired, err = cache.TryAcquireGroupLifecycleLease(ctx, 76, time.Minute) + require.NoError(t, err) + require.True(t, acquired) + require.ErrorIs(t, cache.ReleaseGroupLifecycleLease(canceledCtx, lease), context.Canceled) + owner, err := cache.rdb.Get(ctx, schedulerGroupLifecycleLockKey(lease.GroupID)).Result() + require.NoError(t, err) + require.Equal(t, lease.OwnerToken, owner) + require.NoError(t, cache.ReleaseGroupLifecycleLease(ctx, lease)) +} + +func TestSchedulerCacheGroupLifecycleLeaseRejectsInvalidInput(t *testing.T) { + ctx := context.Background() + cache := newSchedulerCacheUnit(t) + + lease, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, 0, time.Minute) + require.ErrorIs(t, err, service.ErrSchedulerGroupLifecycleLeaseInvalid) + require.False(t, acquired) + require.Equal(t, service.SchedulerGroupLifecycleLease{}, lease) + + lease, acquired, err = cache.TryAcquireGroupLifecycleLease(ctx, 73, 0) + require.ErrorIs(t, err, service.ErrSchedulerGroupLifecycleLeaseInvalid) + require.False(t, acquired) + require.Equal(t, service.SchedulerGroupLifecycleLease{}, lease) + + canceledCtx, cancel := context.WithCancel(ctx) + cancel() + require.ErrorIs(t, cache.ReleaseGroupLifecycleLease(canceledCtx, service.SchedulerGroupLifecycleLease{}), service.ErrSchedulerGroupLifecycleLeaseInvalid) + keys, err := cache.rdb.DBSize(ctx).Result() + require.NoError(t, err) + require.Zero(t, keys) +} diff --git a/backend/internal/repository/wire.go b/backend/internal/repository/wire.go index ec5078eac8..0ee91d146b 100644 --- a/backend/internal/repository/wire.go +++ b/backend/internal/repository/wire.go @@ -68,6 +68,7 @@ var ProviderSet = wire.NewSet( NewAPIKeyRepository, NewGroupRepository, NewAccountRepository, + NewAdminAccountRepository, NewScheduledTestPlanRepository, // 定时测试计划仓储 NewScheduledTestResultRepository, // 定时测试结果仓储 NewProxyRepository, diff --git a/backend/internal/server/api_contract_test.go b/backend/internal/server/api_contract_test.go index fc6b48d6db..da766a753b 100644 --- a/backend/internal/server/api_contract_test.go +++ b/backend/internal/server/api_contract_test.go @@ -1721,6 +1721,10 @@ func (s *stubAccountRepo) Create(ctx context.Context, account *service.Account) return errors.New("not implemented") } +func (s *stubAccountRepo) CreateWithAccountGroups(ctx context.Context, account *service.Account, groups []service.AccountGroup) error { + return errors.New("not implemented") +} + func (s *stubAccountRepo) GetByID(ctx context.Context, id int64) (*service.Account, error) { return nil, service.ErrAccountNotFound } diff --git a/backend/internal/server/middleware/cors.go b/backend/internal/server/middleware/cors.go index 0283d53115..fcf6d332bc 100644 --- a/backend/internal/server/middleware/cors.go +++ b/backend/internal/server/middleware/cors.go @@ -52,7 +52,7 @@ func CORS(cfg config.CORSConfig) gin.HandlerFunc { } allowHeaders := []string{ "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization", - "accept", "origin", "Cache-Control", "X-Requested-With", "X-API-Key", "X-Admin-UI-Request", + "accept", "origin", "Cache-Control", "X-Requested-With", "X-API-Key", "X-Admin-UI-Request", "X-User-UI-Request", } // OpenAI Node SDK 会发送 x-stainless-* 请求头,需在 CORS 中显式放行。 openAIProperties := []string{ diff --git a/backend/internal/server/middleware/cors_test.go b/backend/internal/server/middleware/cors_test.go index 6a61f696df..8828389860 100644 --- a/backend/internal/server/middleware/cors_test.go +++ b/backend/internal/server/middleware/cors_test.go @@ -104,6 +104,7 @@ func TestCORS_AllowedOrigin_HasAllowHeaders(t *testing.T) { assert.NotEmpty(t, w.Header().Get("Access-Control-Allow-Headers"), "允许的 origin 应收到 Allow-Headers") assert.Contains(t, w.Header().Get("Access-Control-Allow-Headers"), "X-Admin-UI-Request") + assert.Contains(t, w.Header().Get("Access-Control-Allow-Headers"), "X-User-UI-Request") assert.NotEmpty(t, w.Header().Get("Access-Control-Allow-Methods"), "允许的 origin 应收到 Allow-Methods") assert.Contains(t, w.Header().Get("Access-Control-Expose-Headers"), "Server-Timing") diff --git a/backend/internal/server/middleware/server_timing.go b/backend/internal/server/middleware/server_timing.go index 2bb21071e0..2301e23893 100644 --- a/backend/internal/server/middleware/server_timing.go +++ b/backend/internal/server/middleware/server_timing.go @@ -25,7 +25,7 @@ func (w *serverTimingResponseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } -// ServerTiming collects timing only for requests made by the Admin web UI. +// ServerTiming collects timing for Admin and User web UI requests when enabled. func ServerTiming(enabled bool) gin.HandlerFunc { if !enabled { return func(c *gin.Context) { @@ -33,7 +33,7 @@ func ServerTiming(enabled bool) gin.HandlerFunc { } } return func(c *gin.Context) { - if !isAdminUIRequest(c) || c.Request == nil { + if !shouldCollectServerTiming(c) || c.Request == nil { c.Next() return } @@ -85,13 +85,19 @@ func (w *serverTimingResponseWriter) finalize() { }) } -// ServerTimingHeaderValue returns a timing value only for an authenticated admin. +// ServerTimingHeaderValue returns a timing value only for authorized UI scopes. +// Admins may receive timing for any collected Admin/User UI request. Non-admin +// authenticated users may receive timing only on allowlisted user-facing paths. +// X-User-UI-Request is a scope signal and is never used as authorization. func ServerTimingHeaderValue(c *gin.Context) string { if c == nil || c.Request == nil { return "" } role, ok := GetUserRoleFromContext(c) - if !ok || role != "admin" { + if !ok || role == "" { + return "" + } + if role != "admin" && !isUserTimingPath(c.Request.URL.Path) { return "" } return servertiming.HeaderValue(c.Request.Context(), time.Now(), responseCacheStatus(c.Writer.Header())) @@ -106,6 +112,10 @@ func ServerTimingResponseHeader(c *gin.Context) http.Header { return http.Header{servertiming.HeaderName: []string{value}} } +func shouldCollectServerTiming(c *gin.Context) bool { + return isAdminUIRequest(c) || isUserUIRequest(c) +} + func isAdminUIRequest(c *gin.Context) bool { if c == nil || c.Request == nil || c.Request.URL == nil { return false @@ -117,6 +127,69 @@ func isAdminUIRequest(c *gin.Context) bool { return path == "/api/v1/admin" || strings.HasPrefix(path, "/api/v1/admin/") } +func isUserUIRequest(c *gin.Context) bool { + if c == nil || c.Request == nil || c.Request.URL == nil { + return false + } + if strings.TrimSpace(c.GetHeader(servertiming.UserUIHeader)) == "1" { + return true + } + return isUserTimingPath(c.Request.URL.Path) +} + +// isUserTimingPath reports whether the path is a user-facing web API that may +// emit Server-Timing for authenticated callers (excluding public payment routes). +func isUserTimingPath(path string) bool { + path = strings.TrimSpace(path) + if path == "" { + return false + } + const prefix = "/api/v1" + if !strings.HasPrefix(path, prefix) { + return false + } + rest := strings.TrimPrefix(path, prefix) + if rest == "" { + return false + } + if !strings.HasPrefix(rest, "/") { + rest = "/" + rest + } + + switch { + case rest == "/auth/me", + rest == "/auth/revoke-all-sessions", + rest == "/auth/oauth/bind-token": + return true + case rest == "/user", strings.HasPrefix(rest, "/user/"): + return true + case rest == "/keys", strings.HasPrefix(rest, "/keys/"): + return true + case rest == "/groups/available", rest == "/groups/rates": + return true + case rest == "/channels/available": + return true + case rest == "/usage", strings.HasPrefix(rest, "/usage/"): + return true + case rest == "/announcements", strings.HasPrefix(rest, "/announcements/"): + return true + case rest == "/redeem", strings.HasPrefix(rest, "/redeem/"): + return true + case rest == "/subscriptions", strings.HasPrefix(rest, "/subscriptions/"): + return true + case rest == "/channel-monitors", strings.HasPrefix(rest, "/channel-monitors/"): + return true + case strings.HasPrefix(rest, "/payment/"): + // Exclude public and webhook payment surfaces. + if strings.HasPrefix(rest, "/payment/public") || strings.HasPrefix(rest, "/payment/webhook") { + return false + } + return true + default: + return false + } +} + func responseCacheStatus(header http.Header) string { for _, name := range []string{snapshotCacheHeader, usageCacheHeader} { switch strings.ToLower(strings.TrimSpace(header.Get(name))) { diff --git a/backend/internal/server/middleware/server_timing_test.go b/backend/internal/server/middleware/server_timing_test.go index c064840ece..435890ccc6 100644 --- a/backend/internal/server/middleware/server_timing_test.go +++ b/backend/internal/server/middleware/server_timing_test.go @@ -15,7 +15,8 @@ func runServerTimingRequest( t *testing.T, enabled bool, path string, - marker string, + adminMarker string, + userMarker string, role string, handler gin.HandlerFunc, ) *httptest.ResponseRecorder { @@ -32,8 +33,11 @@ func runServerTimingRequest( recorder := httptest.NewRecorder() request := httptest.NewRequest(http.MethodGet, path, nil) - if marker != "" { - request.Header.Set(servertiming.AdminUIHeader, marker) + if adminMarker != "" { + request.Header.Set(servertiming.AdminUIHeader, adminMarker) + } + if userMarker != "" { + request.Header.Set(servertiming.UserUIHeader, userMarker) } engine.ServeHTTP(recorder, request) return recorder @@ -41,26 +45,36 @@ func runServerTimingRequest( func TestServerTimingScopesAndRoleGate(t *testing.T) { tests := []struct { - name string - enabled bool - path string - marker string - role string - wantHeader bool + name string + enabled bool + path string + adminMarker string + userMarker string + role string + wantHeader bool }{ {name: "disabled", enabled: false, path: "/api/v1/admin/users", role: "admin"}, {name: "admin API path", enabled: true, path: "/api/v1/admin/users", role: "admin", wantHeader: true}, - {name: "shared API marked by admin UI", enabled: true, path: "/api/v1/groups/available", marker: "1", role: "admin", wantHeader: true}, - {name: "non admin role", enabled: true, path: "/api/v1/groups/available", marker: "1", role: "user"}, - {name: "unauthenticated public request", enabled: true, path: "/api/v1/settings/public", marker: "1"}, - {name: "unmarked shared API", enabled: true, path: "/api/v1/groups/available", role: "admin"}, - {name: "invalid marker", enabled: true, path: "/api/v1/groups/available", marker: "true", role: "admin"}, + {name: "shared API marked by admin UI", enabled: true, path: "/api/v1/groups/available", adminMarker: "1", role: "admin", wantHeader: true}, + {name: "user role on allowlisted path", enabled: true, path: "/api/v1/groups/available", role: "user", wantHeader: true}, + {name: "user role with user UI marker on allowlisted path", enabled: true, path: "/api/v1/keys", userMarker: "1", role: "user", wantHeader: true}, + {name: "user role cannot use admin marker on non-user path", enabled: true, path: "/api/v1/settings/public", adminMarker: "1", role: "user"}, + {name: "user marker alone does not authorize non-user path", enabled: true, path: "/api/v1/settings/public", userMarker: "1", role: "user"}, + {name: "unauthenticated public request", enabled: true, path: "/api/v1/settings/public", adminMarker: "1"}, + {name: "unauthenticated user path", enabled: true, path: "/api/v1/keys"}, + {name: "unmarked shared API still scopes by path for admin", enabled: true, path: "/api/v1/groups/available", role: "admin", wantHeader: true}, + {name: "invalid admin marker on non-scoped path", enabled: true, path: "/api/v1/settings/public", adminMarker: "true", role: "admin"}, {name: "admin prefix boundary", enabled: true, path: "/api/v1/administrator", role: "admin"}, + {name: "auth me path", enabled: true, path: "/api/v1/auth/me", role: "user", wantHeader: true}, + {name: "payment user path", enabled: true, path: "/api/v1/payment/plans", role: "user", wantHeader: true}, + {name: "payment public excluded", enabled: true, path: "/api/v1/payment/public/orders/verify", userMarker: "1", role: "user"}, + {name: "payment webhook excluded", enabled: true, path: "/api/v1/payment/webhook/stripe", userMarker: "1", role: "user"}, + {name: "channel monitors path", enabled: true, path: "/api/v1/channel-monitors/1/status", role: "user", wantHeader: true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - recorder := runServerTimingRequest(t, tt.enabled, tt.path, tt.marker, tt.role, func(c *gin.Context) { + recorder := runServerTimingRequest(t, tt.enabled, tt.path, tt.adminMarker, tt.userMarker, tt.role, func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"ok": true}) }) header := recorder.Header().Get(servertiming.HeaderName) @@ -77,9 +91,49 @@ func TestServerTimingScopesAndRoleGate(t *testing.T) { } } +func TestIsUserTimingPath(t *testing.T) { + tests := []struct { + path string + want bool + }{ + {"/api/v1/auth/me", true}, + {"/api/v1/auth/revoke-all-sessions", true}, + {"/api/v1/auth/oauth/bind-token", true}, + {"/api/v1/auth/login", false}, + {"/api/v1/user", true}, + {"/api/v1/user/profile", true}, + {"/api/v1/user/totp/status", true}, + {"/api/v1/keys", true}, + {"/api/v1/keys/12", true}, + {"/api/v1/groups/available", true}, + {"/api/v1/groups/rates", true}, + {"/api/v1/groups", false}, + {"/api/v1/channels/available", true}, + {"/api/v1/channels", false}, + {"/api/v1/usage/stats", true}, + {"/api/v1/announcements", true}, + {"/api/v1/redeem/history", true}, + {"/api/v1/subscriptions/active", true}, + {"/api/v1/channel-monitors", true}, + {"/api/v1/payment/config", true}, + {"/api/v1/payment/orders/my", true}, + {"/api/v1/payment/public/orders/verify", false}, + {"/api/v1/payment/webhook/easypay", false}, + {"/api/v1/admin/users", false}, + {"/api/v1/settings/public", false}, + } + for _, tt := range tests { + t.Run(tt.path, func(t *testing.T) { + if got := isUserTimingPath(tt.path); got != tt.want { + t.Fatalf("isUserTimingPath(%q) = %v, want %v", tt.path, got, tt.want) + } + }) + } +} + func TestServerTimingCollectorIsRequestScoped(t *testing.T) { active := false - recorder := runServerTimingRequest(t, true, "/api/v1/keys", "1", "admin", func(c *gin.Context) { + recorder := runServerTimingRequest(t, true, "/api/v1/keys", "1", "", "admin", func(c *gin.Context) { active = servertiming.Active(c.Request.Context()) c.Status(http.StatusNoContent) }) @@ -91,8 +145,24 @@ func TestServerTimingCollectorIsRequestScoped(t *testing.T) { } } +func TestServerTimingCollectorForUserUIMarker(t *testing.T) { + active := false + // Use a non-allowlisted path so collection depends on the user UI marker. + recorder := runServerTimingRequest(t, true, "/api/v1/settings/public", "", "1", "admin", func(c *gin.Context) { + active = servertiming.Active(c.Request.Context()) + c.JSON(http.StatusOK, gin.H{"ok": true}) + }) + if !active { + t.Fatal("collector was not attached for user UI marker") + } + // Admin role may emit even when the path is not user-allowlisted. + if recorder.Header().Get(servertiming.HeaderName) == "" { + t.Fatal("admin timing header missing for user-UI-marked request") + } +} + func TestServerTimingFinalizesBeforeEarlyCommit(t *testing.T) { - recorder := runServerTimingRequest(t, true, "/api/v1/admin/stream", "", "admin", func(c *gin.Context) { + recorder := runServerTimingRequest(t, true, "/api/v1/admin/stream", "", "", "admin", func(c *gin.Context) { c.Status(http.StatusAccepted) c.Writer.WriteHeaderNow() }) @@ -102,7 +172,7 @@ func TestServerTimingFinalizesBeforeEarlyCommit(t *testing.T) { } func TestServerTimingFinalizesOnFlush(t *testing.T) { - recorder := runServerTimingRequest(t, true, "/api/v1/admin/export", "", "admin", func(c *gin.Context) { + recorder := runServerTimingRequest(t, true, "/api/v1/admin/export", "", "", "admin", func(c *gin.Context) { c.Writer.Flush() }) if got := recorder.Header().Get(servertiming.HeaderName); got == "" { @@ -120,7 +190,7 @@ func TestServerTimingStatusResponses(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - recorder := runServerTimingRequest(t, true, "/api/v1/admin/test", "", "admin", func(c *gin.Context) { + recorder := runServerTimingRequest(t, true, "/api/v1/admin/test", "", "", "admin", func(c *gin.Context) { c.Status(tt.status) }) if recorder.Code != tt.status { @@ -156,7 +226,7 @@ func TestServerTimingCacheOutcome(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - recorder := runServerTimingRequest(t, true, "/api/v1/admin/dashboard", "", "admin", func(c *gin.Context) { + recorder := runServerTimingRequest(t, true, "/api/v1/admin/dashboard", "", "", "admin", func(c *gin.Context) { c.Header(tt.headerName, tt.value) c.JSON(http.StatusOK, gin.H{"ok": true}) }) diff --git a/backend/internal/server/routes/admin.go b/backend/internal/server/routes/admin.go index 5132022d4a..a60adb1826 100644 --- a/backend/internal/server/routes/admin.go +++ b/backend/internal/server/routes/admin.go @@ -297,6 +297,7 @@ func registerAccountRoutes(admin *gin.RouterGroup, h *handler.Handlers) { accounts.GET("", h.Admin.Account.List) accounts.GET("/:id", h.Admin.Account.GetByID) accounts.POST("", h.Admin.Account.Create) + accounts.POST("/:id/duplicate", h.Admin.Account.Duplicate) accounts.POST("/check-mixed-channel", h.Admin.Account.CheckMixedChannel) accounts.POST("/import/codex-session", h.Admin.Account.ImportCodexSession) accounts.POST("/sync/crs", h.Admin.Account.SyncFromCRS) @@ -400,6 +401,7 @@ func registerGrokOAuthRoutes(admin *gin.RouterGroup, h *handler.Handlers) { grok.POST("/oauth/refresh-token", h.Admin.GrokOAuth.RefreshToken) grok.POST("/oauth/create-from-oauth", h.Admin.GrokOAuth.CreateAccountFromOAuth) grok.POST("/sso-to-oauth", h.Admin.GrokOAuth.CreateAccountsFromSSO) + grok.POST("/oauth/reconcile", h.Admin.GrokOAuth.ReconcileOAuthAccounts) grok.POST("/accounts/:id/refresh", h.Admin.GrokOAuth.RefreshAccountToken) grok.GET("/accounts/:id/quota", h.Admin.GrokOAuth.QueryQuota) grok.POST("/accounts/:id/reset-quota", h.Admin.GrokOAuth.ResetQuota) diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index 45db227e58..f73379981e 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -42,6 +42,13 @@ func RegisterGatewayRoutes( isOpenAIGatewayPlatform := func(c *gin.Context) bool { return getGroupPlatform(c) == service.PlatformOpenAI } + modelsHandler := func(c *gin.Context) { + if isOpenAIGatewayPlatform(c) && c.Query("client_version") != "" { + h.OpenAIGateway.CodexModels(c) + return + } + h.Gateway.Models(c) + } imagesHandler := func(c *gin.Context) { switch getGroupPlatform(c) { case service.PlatformOpenAI: @@ -140,13 +147,7 @@ func RegisterGatewayRoutes( // Codex CLI / Codex app refresh their model picker from the provider's // /models endpoint with a client_version query and expect the ChatGPT // Codex manifest format; other clients keep the OpenAI-style list. - gateway.GET("/models", func(c *gin.Context) { - if isOpenAIGatewayPlatform(c) && c.Query("client_version") != "" { - h.OpenAIGateway.CodexModels(c) - return - } - h.Gateway.Models(c) - }) + gateway.GET("/models", modelsHandler) gateway.GET("/usage", h.Gateway.Usage) // OpenAI Responses API: auto-route based on group platform gateway.POST("/responses", func(c *gin.Context) { @@ -235,6 +236,7 @@ func RegisterGatewayRoutes( r.GET("/responses", bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), requireGroupAnthropic, func(c *gin.Context) { h.OpenAIGateway.ResponsesWebSocket(c) }) + r.GET("/models", bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), requireGroupAnthropic, modelsHandler) codexDirect := r.Group("/backend-api/codex") codexDirect.Use(bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), requireGroupAnthropic) { diff --git a/backend/internal/server/routes/gateway_codex_models_test.go b/backend/internal/server/routes/gateway_codex_models_test.go index 74af755919..04a8b8fa67 100644 --- a/backend/internal/server/routes/gateway_codex_models_test.go +++ b/backend/internal/server/routes/gateway_codex_models_test.go @@ -10,13 +10,15 @@ import ( func TestGatewayRoutesCodexModelsManifestPathIsRegistered(t *testing.T) { router := newGatewayRoutesTestRouter() - registered := make(map[string]bool) + registered := make(map[string]string) for _, route := range router.Routes() { if route.Method == http.MethodGet { - registered[route.Path] = true + registered[route.Path] = route.Handler } } - require.True(t, registered["/backend-api/codex/models"], "GET /backend-api/codex/models should be registered") - require.True(t, registered["/v1/models"], "GET /v1/models should be registered") + require.NotEmpty(t, registered["/backend-api/codex/models"], "GET /backend-api/codex/models should be registered") + require.NotEmpty(t, registered["/v1/models"], "GET /v1/models should be registered") + require.NotEmpty(t, registered["/models"], "GET /models should be registered") + require.Equal(t, registered["/v1/models"], registered["/models"], "root alias should use the same platform-aware handler") } diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 3e67fa5982..5214518fb5 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -6,7 +6,6 @@ import ( "errors" "hash/fnv" "log/slog" - "net/url" "reflect" "sort" "strconv" @@ -1268,16 +1267,13 @@ func (a *Account) GetGrokBaseURL() string { if !a.IsGrok() { return "" } - baseURL := a.GetCredential("base_url") if a.IsGrokOAuth() { - if strings.TrimSpace(baseURL) == "" || isOfficialGrokAPIBaseURL(baseURL) { - return xai.DefaultCLIBaseURL - } - if _, err := xai.ValidateTrustedBaseURL(baseURL); err == nil { - return baseURL - } + // OAuth bearer credentials are subscription credentials and may only be + // sent to the supported CLI gateway. Stored base_url values and unsafe + // development overrides apply exclusively to API-key accounts. return xai.DefaultCLIBaseURL } + baseURL := a.GetCredential("base_url") if baseURL != "" { return baseURL } @@ -1286,57 +1282,17 @@ func (a *Account) GetGrokBaseURL() string { // GetGrokMediaBaseURL selects the upstream used by Grok Imagine APIs. // -// OAuth text requests need the CLI subscription proxy, but that proxy has a -// smaller request-body limit than the official Imagine API. Media requests can -// contain large base64 inputs, so default OAuth accounts must use api.x.ai. -// API-key accounts and explicit unsafe development overrides retain their -// configured base URL. +// OAuth media credentials have the same trust boundary as OAuth text traffic: +// they are pinned to the supported CLI gateway even for large request bodies. +// API-key accounts retain their configured public/custom upstream behavior. func (a *Account) GetGrokMediaBaseURL() string { if !a.IsGrok() { return "" } - if !a.IsGrokOAuth() { - return a.GetGrokBaseURL() + if a.IsGrokOAuth() { + return xai.DefaultCLIBaseURL } - - baseURL := a.GetCredential("base_url") - if strings.TrimSpace(baseURL) == "" || isOfficialGrokAPIBaseURL(baseURL) || isOfficialGrokCLIBaseURL(baseURL) { - return xai.DefaultBaseURL - } - if _, err := xai.ValidateTrustedBaseURL(baseURL); err == nil { - return baseURL - } - return xai.DefaultBaseURL -} - -func isOfficialGrokAPIBaseURL(raw string) bool { - return isOfficialGrokBaseURL(raw, xai.DefaultBaseURL) -} - -func isOfficialGrokCLIBaseURL(raw string) bool { - return isOfficialGrokBaseURL(raw, xai.DefaultCLIBaseURL) -} - -func isOfficialGrokBaseURL(raw, expected string) bool { - parsed, err := url.Parse(strings.TrimSpace(raw)) - if err != nil || parsed == nil || parsed.Opaque != "" || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" { - return false - } - defaultURL, err := url.Parse(expected) - if err != nil { - return false - } - if !strings.EqualFold(parsed.Scheme, defaultURL.Scheme) || !strings.EqualFold(parsed.Hostname(), defaultURL.Hostname()) { - return false - } - if port := parsed.Port(); port != "" { - portNumber, err := strconv.Atoi(port) - if err != nil || portNumber != 443 { - return false - } - } - path := strings.TrimRight(parsed.Path, "/") - return path == "" || path == strings.TrimRight(defaultURL.Path, "/") + return a.GetGrokBaseURL() } func (a *Account) GetGrokAccessToken() string { diff --git a/backend/internal/service/account_base_url_test.go b/backend/internal/service/account_base_url_test.go index 59f53db3db..701a37e131 100644 --- a/backend/internal/service/account_base_url_test.go +++ b/backend/internal/service/account_base_url_test.go @@ -255,7 +255,7 @@ func TestGetGrokBaseURLUsesSubscriptionProxyForOAuth(t *testing.T) { expected: xai.DefaultCLIBaseURL, }, { - name: "oauth non-default API port remains an explicit override", + name: "oauth non-default API port remains pinned to CLI proxy", account: Account{ Type: AccountTypeOAuth, Platform: PlatformGrok, @@ -263,7 +263,7 @@ func TestGetGrokBaseURLUsesSubscriptionProxyForOAuth(t *testing.T) { "base_url": "https://api.x.ai:8443/v1", }, }, - expected: "https://api.x.ai:8443/v1", + expected: xai.DefaultCLIBaseURL, }, { name: "oauth explicit custom base_url stays pinned to CLI proxy by default", @@ -294,7 +294,7 @@ func TestGetGrokBaseURLUsesSubscriptionProxyForOAuth(t *testing.T) { } } -func TestGetGrokBaseURLAllowsExplicitOAuthOverrideWhenUnsafeOverridesEnabled(t *testing.T) { +func TestGetGrokBaseURLPinsOAuthWhenUnsafeOverridesEnabled(t *testing.T) { t.Setenv(xai.EnvAllowUnsafeURLOverrides, "true") account := Account{ Type: AccountTypeOAuth, @@ -304,26 +304,26 @@ func TestGetGrokBaseURLAllowsExplicitOAuthOverrideWhenUnsafeOverridesEnabled(t * }, } - require.Equal(t, "https://custom.example.com/v1", account.GetGrokBaseURL()) + require.Equal(t, xai.DefaultCLIBaseURL, account.GetGrokBaseURL()) } -func TestGetGrokMediaBaseURLSeparatesOAuthMediaFromCLIProxy(t *testing.T) { +func TestGetGrokMediaBaseURLPinsOAuthMediaToCLIProxy(t *testing.T) { tests := []struct { name string account Account expected string }{ { - name: "oauth without base_url uses official media API", + name: "oauth without base_url uses CLI subscription proxy", account: Account{ Type: AccountTypeOAuth, Platform: PlatformGrok, Credentials: map[string]any{}, }, - expected: xai.DefaultBaseURL, + expected: xai.DefaultCLIBaseURL, }, { - name: "oauth stored CLI proxy uses official media API", + name: "oauth stored CLI proxy stays on CLI subscription proxy", account: Account{ Type: AccountTypeOAuth, Platform: PlatformGrok, @@ -331,10 +331,10 @@ func TestGetGrokMediaBaseURLSeparatesOAuthMediaFromCLIProxy(t *testing.T) { "base_url": xai.DefaultCLIBaseURL, }, }, - expected: xai.DefaultBaseURL, + expected: xai.DefaultCLIBaseURL, }, { - name: "oauth stored CLI proxy variant uses official media API", + name: "oauth stored CLI proxy variant is canonicalized to CLI proxy", account: Account{ Type: AccountTypeOAuth, Platform: PlatformGrok, @@ -342,10 +342,10 @@ func TestGetGrokMediaBaseURLSeparatesOAuthMediaFromCLIProxy(t *testing.T) { "base_url": "HTTPS://CLI-CHAT-PROXY.GROK.COM:443/%76%31/", }, }, - expected: xai.DefaultBaseURL, + expected: xai.DefaultCLIBaseURL, }, { - name: "oauth legacy official API remains on official media API", + name: "oauth legacy official API is pinned to CLI proxy", account: Account{ Type: AccountTypeOAuth, Platform: PlatformGrok, @@ -353,10 +353,10 @@ func TestGetGrokMediaBaseURLSeparatesOAuthMediaFromCLIProxy(t *testing.T) { "base_url": xai.DefaultBaseURL, }, }, - expected: xai.DefaultBaseURL, + expected: xai.DefaultCLIBaseURL, }, { - name: "oauth untrusted custom base_url is pinned to official media API", + name: "oauth untrusted custom base_url is pinned to CLI proxy", account: Account{ Type: AccountTypeOAuth, Platform: PlatformGrok, @@ -364,7 +364,7 @@ func TestGetGrokMediaBaseURLSeparatesOAuthMediaFromCLIProxy(t *testing.T) { "base_url": "https://custom.example.com/v1", }, }, - expected: xai.DefaultBaseURL, + expected: xai.DefaultCLIBaseURL, }, { name: "API key retains its configured media API", @@ -395,7 +395,7 @@ func TestGetGrokMediaBaseURLSeparatesOAuthMediaFromCLIProxy(t *testing.T) { } } -func TestGetGrokMediaBaseURLAllowsExplicitOAuthOverrideWhenUnsafeOverridesEnabled(t *testing.T) { +func TestGetGrokMediaBaseURLPinsOAuthWhenUnsafeOverridesEnabled(t *testing.T) { t.Setenv(xai.EnvAllowUnsafeURLOverrides, "true") account := Account{ Type: AccountTypeOAuth, @@ -405,5 +405,5 @@ func TestGetGrokMediaBaseURLAllowsExplicitOAuthOverrideWhenUnsafeOverridesEnable }, } - require.Equal(t, "https://custom.example.com/v1", account.GetGrokMediaBaseURL()) + require.Equal(t, xai.DefaultCLIBaseURL, account.GetGrokMediaBaseURL()) } diff --git a/backend/internal/service/account_credentials_redact.go b/backend/internal/service/account_credentials_redact.go index 76c2d1de5b..8eb70513ba 100644 --- a/backend/internal/service/account_credentials_redact.go +++ b/backend/internal/service/account_credentials_redact.go @@ -4,7 +4,7 @@ package service // dto 层做响应脱敏、service 层做更新合并都引用此清单——新增凭证类型时务必同步。 var SensitiveCredentialKeys = []string{ // OAuth - "access_token", "refresh_token", "id_token", + "access_token", "refresh_token", "id_token", "agent_private_key", // API Key 类 "api_key", "session_key", "cookie", // 云服务凭据 diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go index 5956684f98..b7fe0a68cc 100644 --- a/backend/internal/service/account_service.go +++ b/backend/internal/service/account_service.go @@ -18,6 +18,35 @@ var ( const AccountListGroupUngrouped int64 = -1 const AccountPrivacyModeUnsetFilter = "__unset__" +// OAuthRefreshPageOptions describes one bounded, cursor-stable scan of OAuth +// accounts. Candidate platforms are supplied by TokenRefreshService's refresher +// registry so repository eligibility cannot drift from registered providers. +type OAuthRefreshPageOptions struct { + Platforms []string + AfterID int64 + Limit int + ActiveOnly bool + IncludeSetupToken bool + RequireRefreshToken bool + ExcludeRetryCooldown bool +} + +// OAuthRefreshCandidatePage keeps cursor metadata from the raw SQL ID page. +// Hydration may legitimately lose a concurrently deleted row, but callers can +// still advance past the raw page without truncating or duplicating the scan. +type OAuthRefreshCandidatePage struct { + Accounts []Account + NextAfterID int64 + HasMore bool +} + +// OAuthRefreshCandidatePager is intentionally narrower than AccountRepository. +// Production refresh cycles fail closed when the repository does not implement +// this bounded contract instead of silently falling back to an unpaged scan. +type OAuthRefreshCandidatePager interface { + ListOAuthRefreshCandidatePage(ctx context.Context, options OAuthRefreshPageOptions) (*OAuthRefreshCandidatePage, error) +} + type AccountRepository interface { Create(ctx context.Context, account *Account) error GetByID(ctx context.Context, id int64) (*Account, error) @@ -44,7 +73,6 @@ type AccountRepository interface { ListAllWithFilters(ctx context.Context, platform, accountType, status, search string, groupID int64, privacyMode string) ([]Account, error) ListByGroup(ctx context.Context, groupID int64) ([]Account, error) ListActive(ctx context.Context) ([]Account, error) - ListOAuthRefreshCandidates(ctx context.Context) ([]Account, error) ListByPlatform(ctx context.Context, platform string) ([]Account, error) UpdateLastUsed(ctx context.Context, id int64) error @@ -90,6 +118,19 @@ type AccountRepository interface { ListShadowsByParent(ctx context.Context, parentID int64) ([]*Account, error) } +type AccountDuplicateRepository interface { + // CreateWithAccountGroups atomically persists an account, its exact group priorities, + // and the scheduler outbox event for the new routing snapshot. + CreateWithAccountGroups(ctx context.Context, account *Account, groups []AccountGroup) error +} + +// AdminAccountRepository makes the account-duplication write capability an explicit +// construction dependency without forcing read-only gateway test doubles to implement it. +type AdminAccountRepository interface { + AccountRepository + AccountDuplicateRepository +} + // AccountBulkUpdate describes the fields that can be updated in a bulk operation. // Nil pointers mean "do not change". type AccountBulkUpdate struct { diff --git a/backend/internal/service/account_stats_pricing.go b/backend/internal/service/account_stats_pricing.go index 221021d85c..1098fff9e5 100644 --- a/backend/internal/service/account_stats_pricing.go +++ b/backend/internal/service/account_stats_pricing.go @@ -65,6 +65,13 @@ func tryModelFilePricing(billingService *BillingService, model string, tokens Us if err != nil || pricing == nil { return nil } + if billingService.shouldApplySessionLongContextPricing(tokens, pricing) { + breakdown, err := billingService.CalculateCost(model, tokens, 1) + if err != nil || breakdown == nil || breakdown.TotalCost <= 0 { + return nil + } + return &breakdown.TotalCost + } cost := float64(tokens.InputTokens)*pricing.InputPricePerToken + float64(tokens.OutputTokens)*pricing.OutputPricePerToken + float64(tokens.CacheCreationTokens)*pricing.CacheCreationPricePerToken + diff --git a/backend/internal/service/account_stats_pricing_test.go b/backend/internal/service/account_stats_pricing_test.go index 36e5eb7400..57ace01c22 100644 --- a/backend/internal/service/account_stats_pricing_test.go +++ b/backend/internal/service/account_stats_pricing_test.go @@ -459,6 +459,26 @@ func TestTryModelFilePricing_Success(t *testing.T) { require.InDelta(t, 0.2, *result, 1e-12) } +func TestTryModelFilePricing_AppliesLongContextPricing(t *testing.T) { + bs := newTestBillingServiceWithPrices(map[string]*ModelPricing{ + "gpt-5.6-sol": { + InputPricePerToken: 0.001, + OutputPricePerToken: 0.002, + CacheReadPricePerToken: 0.0001, + LongContextInputThreshold: 100, + LongContextInputMultiplier: 2, + LongContextOutputMultiplier: 1.5, + }, + }) + tokens := UsageTokens{InputTokens: 101, OutputTokens: 10, CacheReadTokens: 5} + + result := tryModelFilePricing(bs, "gpt-5.6-sol", tokens) + + require.NotNil(t, result) + // Input and cache-read use the 2x input tier; output uses the 1.5x tier. + require.InDelta(t, 0.233, *result, 1e-12) +} + func TestTryModelFilePricing_PricingNotFound(t *testing.T) { // "nonexistent-model" does not match any fallback pattern bs := newTestBillingServiceWithPrices(map[string]*ModelPricing{}) diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index 222b3f8a4d..f34cc909b3 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -15,6 +15,7 @@ import ( "net/http/httptest" "regexp" "strings" + "sync" "time" "github.com/Wei-Shaw/sub2api/internal/config" @@ -72,6 +73,8 @@ type AccountTestService struct { httpUpstream HTTPUpstream cfg *config.Config tlsFPProfileService *TLSFingerprintProfileService + agentIdentityTaskMu sync.Mutex + agentIdentityWS agentIdentityWSConnectionInvalidator } // NewAccountTestService creates a new AccountTestService @@ -544,9 +547,11 @@ func (s *AccountTestService) testOpenAIAccountConnection(c *gin.Context, account if credentialAccount.IsOAuth() { isOAuth = true - // OAuth - use Bearer token with ChatGPT internal API - authToken = credentialAccount.GetOpenAIAccessToken() - if authToken == "" { + // Agent Identity signs each request and does not retain the OAuth token. + if !credentialAccount.IsOpenAIAgentIdentity() { + authToken = credentialAccount.GetOpenAIAccessToken() + } + if authToken == "" && !credentialAccount.IsOpenAIAgentIdentity() { return s.sendErrorAndEnd(c, "No access token available") } @@ -591,8 +596,11 @@ func (s *AccountTestService) testOpenAIAccountConnection(c *gin.Context, account payload := createOpenAITestPayload(upstreamTestModelID, isOAuth) payloadBytes, _ := json.Marshal(payload) - // Send test_start event - s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID}) + // Send test_start event once. A task-invalid Agent Identity response may + // restart this probe after registering a replacement task. + if !agentIdentityTaskRecoveryWasTried(ctx) { + s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID}) + } req, err := http.NewRequestWithContext(ctx, "POST", apiURL, bytes.NewReader(payloadBytes)) if err != nil { @@ -602,7 +610,19 @@ func (s *AccountTestService) testOpenAIAccountConnection(c *gin.Context, account // Set common headers req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", "Bearer "+authToken) + if credentialAccount.IsOpenAIAgentIdentity() { + authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, credentialAccount) + if authErr != nil { + return s.sendErrorAndEnd(c, "Failed to build Agent Identity authentication") + } + for key, values := range authHeaders { + for _, value := range values { + req.Header.Add(key, value) + } + } + } else { + req.Header.Set("Authorization", "Bearer "+authToken) + } // Set OAuth-specific headers for ChatGPT internal API if isOAuth { @@ -644,6 +664,15 @@ func (s *AccountTestService) testOpenAIAccountConnection(c *gin.Context, account if resp.StatusCode != http.StatusOK { body, _ := io.ReadAll(resp.Body) + body = redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, credentialAccount, body) + if !agentIdentityTaskRecoveryWasTried(ctx) && credentialAccount.IsOpenAIAgentIdentity() && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, body) { + expectedTaskID := credentialAccount.GetCredential("task_id") + if err := ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, credentialAccount, expectedTaskID); err != nil { + return s.sendErrorAndEnd(c, fmt.Sprintf("Agent Identity task recovery failed: %s", err.Error())) + } + c.Request = c.Request.WithContext(markAgentIdentityTaskRecoveryTried(ctx)) + return s.testOpenAIAccountConnection(c, account, modelID, prompt, mode) + } if resp.StatusCode == http.StatusTooManyRequests { s.reconcileOpenAI429State(ctx, account, resp.Header, body) } @@ -695,7 +724,7 @@ func (s *AccountTestService) testGrokAccountConnection(c *gin.Context, account * return s.sendErrorAndEnd(c, fmt.Sprintf("Unsupported Grok account type: %s", account.Type)) } - apiURL, err := xai.BuildResponsesURL(account.GetGrokBaseURL()) + apiURL, err := buildGrokResponsesURL(account, s.cfg) if err != nil { return s.sendErrorAndEnd(c, fmt.Sprintf("Invalid Grok base URL: %s", err.Error())) } @@ -715,7 +744,9 @@ func (s *AccountTestService) testGrokAccountConnection(c *gin.Context, account * return s.sendErrorAndEnd(c, "Failed to create Grok test payload") } - s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID}) + if !agentIdentityTaskRecoveryWasTried(ctx) { + s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID}) + } req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(payloadBytes)) if err != nil { @@ -724,7 +755,9 @@ func (s *AccountTestService) testGrokAccountConnection(c *gin.Context, account * req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json, text/event-stream") req.Header.Set("Authorization", "Bearer "+authToken) - applyGrokCLIHeaders(req.Header) + if account.IsGrokOAuth() { + applyGrokCLIHeaders(req.Header) + } proxyURL := "" if account.ProxyID != nil && account.Proxy != nil { @@ -740,7 +773,7 @@ func (s *AccountTestService) testGrokAccountConnection(c *gin.Context, account * now := time.Now() snapshot := parseGrokQuotaSnapshot(resp.Header, resp.StatusCode, now) if snapshot != nil && s.accountRepo != nil { - resetAt, limited := grokRateLimitResetAt(snapshot, now) + resetAt, limited := grokRateLimitResetAtForAccount(account, snapshot, now) if limited { normalizeGrokExhaustedWindowResets(snapshot, resetAt, now) } @@ -749,7 +782,11 @@ func (s *AccountTestService) testGrokAccountConnection(c *gin.Context, account * }) if limited { persistGrokRateLimit(ctx, s.accountRepo, account, resetAt) + } else if isSuccessfulGrokRateLimitRecovery(account, snapshot) { + clearGrokRateLimitAfterRecovery(ctx, s.accountRepo, account) } + } else if s.accountRepo != nil && isSuccessfulGrokRateLimitRecovery(account, &xai.QuotaSnapshot{StatusCode: resp.StatusCode}) { + clearGrokRateLimitAfterRecovery(ctx, s.accountRepo, account) } if resp.StatusCode != http.StatusOK { @@ -827,16 +864,26 @@ func (s *AccountTestService) testOpenAIChatCompletionsConnection( // resulting capability state on the account. func (s *AccountTestService) testOpenAICompactConnection(c *gin.Context, account *Account, testModelID string) error { ctx := c.Request.Context() + credentialAccount := account + if account.IsShadow() { + resolved, err := resolveCredentialAccount(ctx, s.accountRepo, account) + if err != nil { + return s.sendErrorAndEnd(c, "Failed to resolve account credentials") + } + credentialAccount = resolved + } authToken := "" apiURL := "" isOAuth := false switch { - case account.IsOAuth(): + case credentialAccount.IsOAuth(): isOAuth = true - authToken = account.GetOpenAIAccessToken() - if authToken == "" { + if !credentialAccount.IsOpenAIAgentIdentity() { + authToken = credentialAccount.GetOpenAIAccessToken() + } + if authToken == "" && !credentialAccount.IsOpenAIAgentIdentity() { return s.sendErrorAndEnd(c, "No access token available") } apiURL = chatgptCodexAPIURL + "/compact" @@ -865,7 +912,9 @@ func (s *AccountTestService) testOpenAICompactConnection(c *gin.Context, account c.Writer.Flush() payloadBytes, _ := json.Marshal(createOpenAICompactProbePayload(testModelID)) - s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID}) + if !agentIdentityTaskRecoveryWasTried(ctx) { + s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID}) + } req, err := http.NewRequestWithContext(ctx, "POST", apiURL, bytes.NewReader(payloadBytes)) if err != nil { @@ -875,7 +924,19 @@ func (s *AccountTestService) testOpenAICompactConnection(c *gin.Context, account req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") - req.Header.Set("Authorization", "Bearer "+authToken) + if credentialAccount.IsOpenAIAgentIdentity() { + authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, credentialAccount) + if authErr != nil { + return s.sendErrorAndEnd(c, "Failed to build Agent Identity authentication") + } + for key, values := range authHeaders { + for _, value := range values { + req.Header.Add(key, value) + } + } + } else { + req.Header.Set("Authorization", "Bearer "+authToken) + } req.Header.Set("OpenAI-Beta", "responses=experimental") req.Header.Set("Originator", "codex_cli_rs") req.Header.Set("User-Agent", codexCLIUserAgent) @@ -886,7 +947,7 @@ func (s *AccountTestService) testOpenAICompactConnection(c *gin.Context, account if isOAuth { req.Host = "chatgpt.com" - setOpenAIChatGPTAccountHeaders(req.Header, account) + setOpenAIChatGPTAccountHeaders(req.Header, credentialAccount) } // 账号级请求头覆写:测试请求与真实转发保持一致的最终头 @@ -909,6 +970,15 @@ func (s *AccountTestService) testOpenAICompactConnection(c *gin.Context, account defer func() { _ = resp.Body.Close() }() body, _ := io.ReadAll(io.LimitReader(resp.Body, 2<<20)) + body = redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, credentialAccount, body) + if !agentIdentityTaskRecoveryWasTried(ctx) && credentialAccount.IsOpenAIAgentIdentity() && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, body) { + expectedTaskID := credentialAccount.GetCredential("task_id") + if err := ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, credentialAccount, expectedTaskID); err != nil { + return s.sendErrorAndEnd(c, fmt.Sprintf("Agent Identity task recovery failed: %s", err.Error())) + } + c.Request = c.Request.WithContext(markAgentIdentityTaskRecoveryTried(ctx)) + return s.testOpenAICompactConnection(c, account, testModelID) + } if s.accountRepo != nil { updates := buildOpenAICompactProbeExtraUpdates(resp, body, nil, time.Now()) @@ -1700,8 +1770,19 @@ func (s *AccountTestService) testOpenAIImageAPIKey(c *gin.Context, ctx context.C // testOpenAIImageOAuth tests OpenAI image generation using an OAuth account via Codex /responses API. func (s *AccountTestService) testOpenAIImageOAuth(c *gin.Context, ctx context.Context, account *Account, modelID, prompt string) error { - authToken := account.GetOpenAIAccessToken() - if authToken == "" { + credentialAccount := account + if account.IsShadow() { + resolved, err := resolveCredentialAccount(ctx, s.accountRepo, account) + if err != nil { + return s.sendErrorAndEnd(c, "Failed to resolve account credentials") + } + credentialAccount = resolved + } + authToken := "" + if !credentialAccount.IsOpenAIAgentIdentity() { + authToken = credentialAccount.GetOpenAIAccessToken() + } + if authToken == "" && !credentialAccount.IsOpenAIAgentIdentity() { return s.sendErrorAndEnd(c, "No access token available") } @@ -1733,17 +1814,29 @@ func (s *AccountTestService) testOpenAIImageOAuth(c *gin.Context, ctx context.Co } req = req.WithContext(WithHTTPUpstreamProfile(req.Context(), HTTPUpstreamProfileOpenAI)) req.Host = "chatgpt.com" - req.Header.Set("Authorization", "Bearer "+authToken) + if credentialAccount.IsOpenAIAgentIdentity() { + authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, credentialAccount) + if authErr != nil { + return s.sendErrorAndEnd(c, "Failed to build Agent Identity authentication") + } + for key, values := range authHeaders { + for _, value := range values { + req.Header.Add(key, value) + } + } + } else { + req.Header.Set("Authorization", "Bearer "+authToken) + } req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "text/event-stream") req.Header.Set("OpenAI-Beta", "responses=experimental") req.Header.Set("originator", "codex_cli_rs") - if customUA := strings.TrimSpace(account.GetOpenAIUserAgent()); customUA != "" { + if customUA := strings.TrimSpace(credentialAccount.GetOpenAIUserAgent()); customUA != "" { req.Header.Set("User-Agent", customUA) } else { req.Header.Set("User-Agent", codexCLIUserAgent) } - setOpenAIChatGPTAccountHeaders(req.Header, account) + setOpenAIChatGPTAccountHeaders(req.Header, credentialAccount) // 与真实转发一致:originator 与最终 User-Agent 首段配套(原 opencode 与 Codex UA 错配会 404,issue #3901)。 enforceCodexIdentityHeaders(req.Header) @@ -1762,6 +1855,7 @@ func (s *AccountTestService) testOpenAIImageOAuth(c *gin.Context, ctx context.Co }() if resp.StatusCode >= 400 { body, _ := io.ReadAll(io.LimitReader(resp.Body, 2<<20)) + body = redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, credentialAccount, body) message := strings.TrimSpace(extractUpstreamErrorMessage(body)) if message == "" { message = fmt.Sprintf("Responses API returned %d", resp.StatusCode) @@ -1773,6 +1867,7 @@ func (s *AccountTestService) testOpenAIImageOAuth(c *gin.Context, ctx context.Co if err != nil { return s.sendErrorAndEnd(c, fmt.Sprintf("Failed to read image response: %s", err.Error())) } + body = redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, credentialAccount, body) results, _, _, _, _, err := collectOpenAIImagesFromResponsesBody(body) if err != nil { diff --git a/backend/internal/service/account_test_service_grok_test.go b/backend/internal/service/account_test_service_grok_test.go index 4b0890ff44..72f995a0c7 100644 --- a/backend/internal/service/account_test_service_grok_test.go +++ b/backend/internal/service/account_test_service_grok_test.go @@ -40,8 +40,9 @@ func TestAccountTestService_TestAccountConnection_GrokUsesXAIResponses(t *testin Schedulable: true, Concurrency: 1, Credentials: map[string]any{ - "access_token": "grok-access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), + "access_token": "grok-access-token", + "refresh_token": "grok-refresh-token", + "expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339), "model_mapping": map[string]any{ "grok": "grok-4.3", }, @@ -92,8 +93,9 @@ func TestAccountTestService_TestAccountConnection_GrokDefaultsEmptyModelTo45(t * Schedulable: true, Concurrency: 1, Credentials: map[string]any{ - "access_token": "grok-access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), + "access_token": "grok-access-token", + "refresh_token": "grok-refresh-token", + "expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339), }, } repo := &mockAccountRepoForGemini{accountsByID: map[int64]*Account{account.ID: account}} @@ -133,8 +135,9 @@ func TestAccountTestService_Grok429PersistsRateLimitReset(t *testing.T) { Schedulable: true, Concurrency: 1, Credentials: map[string]any{ - "access_token": "grok-access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), + "access_token": "grok-access-token", + "refresh_token": "grok-refresh-token", + "expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339), }, } baseRepo := &mockAccountRepoForGemini{accountsByID: map[int64]*Account{account.ID: account}} @@ -166,8 +169,9 @@ func TestAccountTestService_Grok429WithoutQuotaHeadersUsesFallback(t *testing.T) ID: 15, Name: "grok-oauth-limited-no-headers", Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, Concurrency: 1, Credentials: map[string]any{ - "access_token": "grok-access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), + "access_token": "grok-access-token", + "refresh_token": "grok-refresh-token", + "expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339), }, } baseRepo := &mockAccountRepoForGemini{accountsByID: map[int64]*Account{account.ID: account}} diff --git a/backend/internal/service/account_usage_service.go b/backend/internal/service/account_usage_service.go index 7b42a1d1c5..12dc25a673 100644 --- a/backend/internal/service/account_usage_service.go +++ b/backend/internal/service/account_usage_service.go @@ -299,6 +299,8 @@ type AccountUsageService struct { cache *UsageCache identityCache IdentityCache tlsFPProfileService *TLSFingerprintProfileService + agentIdentityTaskMu sync.Mutex + agentIdentityWS agentIdentityWSConnectionInvalidator } // NewAccountUsageService 创建AccountUsageService实例 @@ -692,8 +694,11 @@ func (s *AccountUsageService) probeOpenAICodexSnapshot(ctx context.Context, acco if account == nil || !account.IsOAuth() { return nil, nil } - accessToken := account.GetOpenAIAccessToken() - if accessToken == "" { + accessToken := "" + if !account.IsOpenAIAgentIdentity() { + accessToken = account.GetOpenAIAccessToken() + } + if accessToken == "" && !account.IsOpenAIAgentIdentity() { return nil, fmt.Errorf("no access token available") } modelID := openaipkg.DefaultTestModel @@ -711,7 +716,19 @@ func (s *AccountUsageService) probeOpenAICodexSnapshot(ctx context.Context, acco } req.Host = "chatgpt.com" req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", "Bearer "+accessToken) + if account.IsOpenAIAgentIdentity() { + authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, account) + if authErr != nil { + return nil, fmt.Errorf("build Agent Identity authentication: %w", authErr) + } + for key, values := range authHeaders { + for _, value := range values { + req.Header.Add(key, value) + } + } + } else { + req.Header.Set("Authorization", "Bearer "+accessToken) + } req.Header.Set("Accept", "text/event-stream") req.Header.Set("OpenAI-Beta", "responses=experimental") req.Header.Set("Originator", "codex_cli_rs") diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go index 8cb6d8e63b..f4c3375650 100644 --- a/backend/internal/service/admin_account.go +++ b/backend/internal/service/admin_account.go @@ -2,6 +2,8 @@ package service import ( "context" + "crypto/sha256" + "encoding/json" "errors" "fmt" "log/slog" @@ -60,6 +62,275 @@ func (s *adminServiceImpl) GetAccountsByIDs(ctx context.Context, ids []int64) ([ return accounts, nil } +const maxAccountNameRunes = 100 +const duplicateAccountOperationIDExtraKey = "duplicate_operation_id" + +func duplicateAccountName(sourceName string) string { + const suffix = " (Copy)" + nameRunes := []rune(strings.TrimSpace(sourceName)) + maxBaseRunes := maxAccountNameRunes - len([]rune(suffix)) + if len(nameRunes) > maxBaseRunes { + nameRunes = nameRunes[:maxBaseRunes] + } + return string(nameRunes) + suffix +} + +func cloneAccountJSONMap(value map[string]any) (map[string]any, error) { + if value == nil { + return nil, nil + } + payload, err := json.Marshal(value) + if err != nil { + return nil, err + } + cloned := make(map[string]any, len(value)) + if err := json.Unmarshal(payload, &cloned); err != nil { + return nil, err + } + return cloned, nil +} + +var duplicateAccountDiscardedExtraKeys = map[string]struct{}{ + // A retry identity belongs to the operation that created one copy, not to later copies. + duplicateAccountOperationIDExtraKey: {}, + // External sync identity belongs to one local account only. + "crs_account_id": {}, + "crs_kind": {}, + "crs_synced_at": {}, + // Local quota usage and derived window timestamps must start fresh. + "quota_used": {}, + "quota_daily_used": {}, + "quota_weekly_used": {}, + "quota_daily_start": {}, + "quota_weekly_start": {}, + "quota_daily_reset_at": {}, + "quota_weekly_reset_at": {}, + // Provider observations, capability probes, and transient scheduling state. + "model_rate_limits": {}, + "session_window_utilization": {}, + "passive_usage_7d_utilization": {}, + "passive_usage_7d_reset": {}, + "passive_usage_7d_oi_utilization": {}, + "passive_usage_7d_oi_reset": {}, + "passive_usage_sampled_at": {}, + "grok_usage_snapshot": {}, + "grok_billing_snapshot": {}, + "openai_responses_supported": {}, + "openai_compact_supported": {}, + "openai_compact_checked_at": {}, + "openai_compact_last_status": {}, + "openai_compact_last_error": {}, + "antigravity_credits_overages": {}, + "antigravity_force_token_refresh": {}, + "antigravity_force_token_refresh_at": {}, + "antigravity_force_token_refresh_reason": {}, + "drive_storage_limit": {}, + "drive_storage_usage": {}, + "drive_tier_updated_at": {}, + "codex_primary_used_percent": {}, + "codex_primary_reset_after_seconds": {}, + "codex_primary_window_minutes": {}, + "codex_secondary_used_percent": {}, + "codex_secondary_reset_after_seconds": {}, + "codex_secondary_window_minutes": {}, + "codex_primary_over_secondary_percent": {}, + "codex_usage_updated_at": {}, + "codex_5h_used_percent": {}, + "codex_5h_reset_after_seconds": {}, + "codex_5h_window_minutes": {}, + "codex_5h_reset_at": {}, + "codex_7d_used_percent": {}, + "codex_7d_reset_after_seconds": {}, + "codex_7d_window_minutes": {}, + "codex_7d_reset_at": {}, +} + +func duplicateAccountExtra(value map[string]any) (map[string]any, error) { + cloned, err := cloneAccountJSONMap(value) + if err != nil { + return nil, err + } + for key := range duplicateAccountDiscardedExtraKeys { + delete(cloned, key) + } + return cloned, nil +} + +func canDuplicateAccountType(accountType string) bool { + switch accountType { + case AccountTypeAPIKey, AccountTypeUpstream, AccountTypeBedrock, AccountTypeServiceAccount: + return true + default: + return false + } +} + +func duplicateAccountGroups(source *Account) ([]AccountGroup, []int64) { + if len(source.AccountGroups) > 0 { + groups := make([]AccountGroup, 0, len(source.AccountGroups)) + groupIDs := make([]int64, 0, len(source.AccountGroups)) + for _, sourceGroup := range source.AccountGroups { + groups = append(groups, AccountGroup{GroupID: sourceGroup.GroupID, Priority: sourceGroup.Priority}) + groupIDs = append(groupIDs, sourceGroup.GroupID) + } + return groups, groupIDs + } + + groups := make([]AccountGroup, 0, len(source.GroupIDs)) + groupIDs := append([]int64(nil), source.GroupIDs...) + for i, groupID := range groupIDs { + groups = append(groups, AccountGroup{GroupID: groupID, Priority: i + 1}) + } + return groups, groupIDs +} + +func duplicateAccountOperationID(sourceID int64, actorScope, operationKey string) string { + operationKey = strings.TrimSpace(operationKey) + if operationKey == "" { + return "" + } + actorScope = strings.TrimSpace(actorScope) + if actorScope == "" { + actorScope = "admin:0" + } + payload := "admin.accounts.duplicate\x00" + actorScope + "\x00" + strconv.FormatInt(sourceID, 10) + "\x00" + operationKey + digest := sha256.Sum256([]byte(payload)) + return fmt.Sprintf("%x", digest) +} + +func (s *adminServiceImpl) findDuplicateByOperationID(ctx context.Context, operationID string) (*Account, error) { + if operationID == "" { + return nil, nil + } + accounts, err := s.accountRepo.FindByExtraField(ctx, duplicateAccountOperationIDExtraKey, operationID) + if err != nil { + return nil, fmt.Errorf("find duplicate account operation: %w", err) + } + if len(accounts) == 0 { + return nil, nil + } + account := accounts[0] + return &account, nil +} + +// RecoverDuplicateAccount performs a read-only lookup for an already committed duplicate. +// It is used when the idempotency coordinator cannot confirm whether response persistence +// succeeded, and deliberately never repeats the create side effect. +func (s *adminServiceImpl) RecoverDuplicateAccount(ctx context.Context, id int64, actorScope, operationKey string) (*Account, error) { + return s.findDuplicateByOperationID(ctx, duplicateAccountOperationID(id, actorScope, operationKey)) +} + +func cloneAccountValuePointer[T any](value *T) *T { + if value == nil { + return nil + } + cloned := *value + return &cloned +} + +// DuplicateAccount creates a paused account from source configuration without carrying first-class +// runtime state. Credentials and extra configuration are deep-copied so normalization of the new +// account cannot mutate the in-memory source. Linked credential shadows are excluded because they +// intentionally do not own credentials and must be created through CreateShadow. +func (s *adminServiceImpl) DuplicateAccount(ctx context.Context, id int64, actorScope, operationKey string) (*Account, error) { + operationID := duplicateAccountOperationID(id, actorScope, operationKey) + existing, err := s.RecoverDuplicateAccount(ctx, id, actorScope, operationKey) + if err != nil { + return nil, err + } + if existing != nil { + return existing, nil + } + + source, err := s.accountRepo.GetByID(ctx, id) + if err != nil { + return nil, err + } + if source.IsCredentialShadow() { + return nil, infraerrors.BadRequest( + "ACCOUNT_DUPLICATE_SHADOW_UNSUPPORTED", + "linked credential shadow accounts cannot be duplicated; duplicate the parent account instead", + ) + } + if !canDuplicateAccountType(source.Type) { + return nil, infraerrors.BadRequest( + "ACCOUNT_DUPLICATE_CREDENTIAL_TYPE_UNSUPPORTED", + "accounts with rotating or unsupported credential types cannot be duplicated", + ) + } + + credentials, err := cloneAccountJSONMap(source.Credentials) + if err != nil { + return nil, fmt.Errorf("clone account credentials: %w", err) + } + extra, err := duplicateAccountExtra(source.Extra) + if err != nil { + return nil, fmt.Errorf("clone account extra configuration: %w", err) + } + if operationID != "" { + if extra == nil { + extra = make(map[string]any, 1) + } + extra[duplicateAccountOperationIDExtraKey] = operationID + } + + var expiresAt *int64 + if source.ExpiresAt != nil { + unix := source.ExpiresAt.Unix() + expiresAt = &unix + } + autoPauseOnExpired := source.AutoPauseOnExpired + groups, groupIDs := duplicateAccountGroups(source) + proxyID := source.ProxyID + if source.ProxyFallbackOriginID != nil { + // Proxy fallback is transient runtime state; duplicate the configured origin. + proxyID = source.ProxyFallbackOriginID + } + input := &CreateAccountInput{ + Name: duplicateAccountName(source.Name), + Notes: cloneAccountValuePointer(source.Notes), + Platform: source.Platform, + Type: source.Type, + Credentials: credentials, + Extra: extra, + ProxyID: cloneAccountValuePointer(proxyID), + Concurrency: source.Concurrency, + Priority: source.Priority, + RateMultiplier: cloneAccountValuePointer(source.RateMultiplier), + LoadFactor: cloneAccountValuePointer(source.LoadFactor), + GroupIDs: groupIDs, + ExpiresAt: expiresAt, + AutoPauseOnExpired: &autoPauseOnExpired, + SkipDefaultGroupBind: true, + SkipMixedChannelCheck: true, + } + accountExtra, err := normalizeOpenAILongContextBillingExtra(input.Platform, input.Extra) + if err != nil { + return nil, fmt.Errorf("normalize duplicate account extra: %w", err) + } + if err := NormalizeHeaderOverrideCredentials(input.Credentials); err != nil { + return nil, err + } + duplicate, err := buildAccountForCreate(input, accountExtra) + if err != nil { + return nil, err + } + // A copied credential must be reviewed before it can share live traffic with its source. + duplicate.Schedulable = false + if s.accountDuplicateRepo == nil { + return nil, errors.New("account duplicate repository is not configured") + } + if err := s.accountDuplicateRepo.CreateWithAccountGroups(ctx, duplicate, groups); err != nil { + return nil, fmt.Errorf("create duplicate account: %w", err) + } + for i := range groups { + groups[i].AccountID = duplicate.ID + } + duplicate.AccountGroups = groups + duplicate.GroupIDs = groupIDs + return duplicate, nil +} + func normalizeAccountConcurrency(platform, accountType string, concurrency int) int { if platform == PlatformGrok && accountType == AccountTypeOAuth { if concurrency <= 0 { @@ -122,40 +393,7 @@ func normalizeOpenAILongContextBillingUpdateExtra(account *Account, input *Updat return normalized, nil } -func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccountInput) (*Account, error) { - accountExtra, err := normalizeOpenAILongContextBillingExtra(input.Platform, input.Extra) - if err != nil { - return nil, err - } - - // 绑定分组 - groupIDs := input.GroupIDs - // 如果没有指定分组,自动绑定对应平台的默认分组 - if len(groupIDs) == 0 && !input.SkipDefaultGroupBind { - defaultGroupName := input.Platform + "-default" - groups, err := s.groupRepo.ListActiveByPlatform(ctx, input.Platform) - if err == nil { - for _, g := range groups { - if g.Name == defaultGroupName { - groupIDs = []int64{g.ID} - break - } - } - } - } - - // 检查混合渠道风险(除非用户已确认) - if len(groupIDs) > 0 && !input.SkipMixedChannelCheck { - if err := s.checkMixedChannelRisk(ctx, 0, input.Platform, groupIDs); err != nil { - return nil, err - } - } - - // 校验并规范化请求头覆写配置(header 名小写化、格式检查) - if err := NormalizeHeaderOverrideCredentials(input.Credentials); err != nil { - return nil, err - } - +func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]any) (*Account, error) { account := &Account{ Name: input.Name, Notes: normalizeAccountNotes(input.Notes), @@ -198,6 +436,47 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou } account.LoadFactor = input.LoadFactor } + return account, nil +} + +func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccountInput) (*Account, error) { + accountExtra, err := normalizeOpenAILongContextBillingExtra(input.Platform, input.Extra) + if err != nil { + return nil, err + } + + // 绑定分组 + groupIDs := input.GroupIDs + // 如果没有指定分组,自动绑定对应平台的默认分组 + if len(groupIDs) == 0 && !input.SkipDefaultGroupBind { + defaultGroupName := input.Platform + "-default" + groups, err := s.groupRepo.ListActiveByPlatform(ctx, input.Platform) + if err == nil { + for _, g := range groups { + if g.Name == defaultGroupName { + groupIDs = []int64{g.ID} + break + } + } + } + } + + // 检查混合渠道风险(除非用户已确认) + if len(groupIDs) > 0 && !input.SkipMixedChannelCheck { + if err := s.checkMixedChannelRisk(ctx, 0, input.Platform, groupIDs); err != nil { + return nil, err + } + } + + // 校验并规范化请求头覆写配置(header 名小写化、格式检查) + if err := NormalizeHeaderOverrideCredentials(input.Credentials); err != nil { + return nil, err + } + + account, err := buildAccountForCreate(input, accountExtra) + if err != nil { + return nil, err + } if err := s.accountRepo.Create(ctx, account); err != nil { return nil, err } diff --git a/backend/internal/service/admin_service.go b/backend/internal/service/admin_service.go index 2a7125f51f..964566a80c 100644 --- a/backend/internal/service/admin_service.go +++ b/backend/internal/service/admin_service.go @@ -67,6 +67,12 @@ type AdminService interface { GetAccount(ctx context.Context, id int64) (*Account, error) GetAccountsByIDs(ctx context.Context, ids []int64) ([]*Account, error) CreateAccount(ctx context.Context, input *CreateAccountInput) (*Account, error) + // DuplicateAccount creates an independent account from an existing account's configuration. + // First-class runtime columns are intentionally reset by the normal account creation path. + DuplicateAccount(ctx context.Context, id int64, actorScope, operationKey string) (*Account, error) + // RecoverDuplicateAccount returns a previously committed duplicate for an ambiguous retry. + // It never creates an account. + RecoverDuplicateAccount(ctx context.Context, id int64, actorScope, operationKey string) (*Account, error) UpdateAccount(ctx context.Context, id int64, input *UpdateAccountInput) (*Account, error) // UpdateAccountExtra 仅对 Extra 做 JSONB 增量合并(key 级覆盖),不会影响其它字段或运行态键。 // 用于刷新流程持久化 account_uuid / org_uuid 等少量键,避免被全量快照覆盖。 @@ -577,6 +583,7 @@ type adminServiceImpl struct { userRepo UserRepository groupRepo GroupRepository accountRepo AccountRepository + accountDuplicateRepo AccountDuplicateRepository proxyRepo ProxyRepository apiKeyRepo APIKeyRepository redeemCodeRepo RedeemCodeRepository @@ -602,7 +609,7 @@ type userGroupRateBatchReader interface { func NewAdminService( userRepo UserRepository, groupRepo GroupRepository, - accountRepo AccountRepository, + accountRepo AdminAccountRepository, proxyRepo ProxyRepository, apiKeyRepo APIKeyRepository, redeemCodeRepo RedeemCodeRepository, @@ -623,6 +630,7 @@ func NewAdminService( userRepo: userRepo, groupRepo: groupRepo, accountRepo: accountRepo, + accountDuplicateRepo: accountRepo, proxyRepo: proxyRepo, apiKeyRepo: apiKeyRepo, redeemCodeRepo: redeemCodeRepo, diff --git a/backend/internal/service/admin_service_duplicate_account_test.go b/backend/internal/service/admin_service_duplicate_account_test.go new file mode 100644 index 0000000000..f89d887035 --- /dev/null +++ b/backend/internal/service/admin_service_duplicate_account_test.go @@ -0,0 +1,322 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "net/http" + "strings" + "testing" + "time" + "unicode/utf8" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/stretchr/testify/require" +) + +type duplicateAccountRepoStub struct { + *sparkShadowRepoStub + atomicCreateErr error + accountGroupsOf map[int64][]AccountGroup +} + +func newDuplicateAccountRepoStub() *duplicateAccountRepoStub { + return &duplicateAccountRepoStub{ + sparkShadowRepoStub: newSparkShadowRepoStub(), + accountGroupsOf: make(map[int64][]AccountGroup), + } +} + +func (s *duplicateAccountRepoStub) CreateWithAccountGroups(ctx context.Context, account *Account, groups []AccountGroup) error { + if s.atomicCreateErr != nil { + return s.atomicCreateErr + } + groupIDs := make([]int64, 0, len(groups)) + for _, group := range groups { + groupIDs = append(groupIDs, group.GroupID) + } + account.GroupIDs = groupIDs + if err := s.Create(ctx, account); err != nil { + return err + } + clonedGroups := make([]AccountGroup, len(groups)) + copy(clonedGroups, groups) + for i := range clonedGroups { + clonedGroups[i].AccountID = account.ID + } + account.AccountGroups = clonedGroups + s.accountGroupsOf[account.ID] = clonedGroups + if len(groupIDs) > 0 { + s.groupsOf[account.ID] = append([]int64(nil), groupIDs...) + } + stored := *account + s.accounts[account.ID] = &stored + s.mockAccountRepoForGemini.accountsByID[account.ID] = &stored + return nil +} + +func (s *duplicateAccountRepoStub) FindByExtraField(_ context.Context, key string, value any) ([]Account, error) { + wanted, ok := value.(string) + if !ok { + return nil, nil + } + var matches []Account + for _, account := range s.accounts { + if actual, ok := account.Extra[key].(string); ok && actual == wanted { + matches = append(matches, *account) + } + } + return matches, nil +} + +func TestDuplicateAccountCopiesConfigurationAndResetsRuntimeState(t *testing.T) { + ctx := context.Background() + repo := newDuplicateAccountRepoStub() + svc := &adminServiceImpl{accountRepo: repo, accountDuplicateRepo: repo} + + notes := "keep this note" + proxyID := int64(17) + originalProxyID := int64(11) + rateMultiplier := 1.25 + loadFactor := 9 + expiresAt := time.Date(2027, time.March, 4, 5, 6, 7, 0, time.UTC) + rateLimitedAt := time.Now().Add(-time.Minute) + rateLimitResetAt := time.Now().Add(time.Hour) + overloadUntil := time.Now().Add(2 * time.Hour) + tempUnschedulableUntil := time.Now().Add(3 * time.Hour) + sessionWindowStart := time.Now().Add(-2 * time.Hour) + sessionWindowEnd := time.Now().Add(2 * time.Hour) + + source := &Account{ + Name: "primary", + Notes: ¬es, + Platform: PlatformAnthropic, + Type: AccountTypeAPIKey, + ProxyID: &proxyID, + ProxyFallbackOriginID: &originalProxyID, + Concurrency: 6, + Priority: 40, + RateMultiplier: &rateMultiplier, + LoadFactor: &loadFactor, + Status: StatusError, + Schedulable: true, + ErrorMessage: "upstream unavailable", + ExpiresAt: &expiresAt, + AutoPauseOnExpired: false, + Credentials: map[string]any{ + "api_key": "secret", + "nested": map[string]any{"token": "source-token"}, + }, + Extra: map[string]any{ + "config": map[string]any{"region": "us-east-1"}, + "items": []any{map[string]any{"enabled": true}}, + "quota_limit": 1000, + "quota_used": 450, + "quota_daily_used": 25, + "quota_daily_start": "2026-07-15T00:00:00Z", + "model_rate_limits": map[string]any{"gpt-5": "2099-01-01T00:00:00Z"}, + "codex_5h_used_percent": 80, + "codex_cli_only": true, + "grok_usage_snapshot": map[string]any{"status_code": 429}, + "openai_responses_supported": false, + "openai_compact_checked_at": "2026-07-15T00:00:00Z", + "session_window_utilization": 0.8, + "passive_usage_sampled_at": "2026-07-15T00:00:00Z", + "antigravity_force_token_refresh": true, + "antigravity_credits_overages": map[string]any{"enabled": true}, + "crs_account_id": "remote-42", + "crs_kind": "openai-api-key", + "crs_synced_at": "2026-07-15T00:00:00Z", + }, + GroupIDs: []int64{7, 3}, + AccountGroups: []AccountGroup{{GroupID: 7, Priority: 50}, {GroupID: 3, Priority: 7}}, + RateLimitedAt: &rateLimitedAt, + RateLimitResetAt: &rateLimitResetAt, + OverloadUntil: &overloadUntil, + TempUnschedulableUntil: &tempUnschedulableUntil, + TempUnschedulableReason: "maintenance", + SessionWindowStart: &sessionWindowStart, + SessionWindowEnd: &sessionWindowEnd, + SessionWindowStatus: "active", + } + require.NoError(t, repo.Create(ctx, source)) + + duplicate, err := svc.DuplicateAccount(ctx, source.ID, "admin:1", "") + + require.NoError(t, err) + require.NotEqual(t, source.ID, duplicate.ID) + require.Equal(t, "primary (Copy)", duplicate.Name) + require.Equal(t, source.Platform, duplicate.Platform) + require.Equal(t, source.Type, duplicate.Type) + require.Equal(t, source.Concurrency, duplicate.Concurrency) + require.Equal(t, source.Priority, duplicate.Priority) + require.Equal(t, source.AutoPauseOnExpired, duplicate.AutoPauseOnExpired) + require.Equal(t, source.GroupIDs, duplicate.GroupIDs) + require.Equal(t, source.Credentials, duplicate.Credentials) + require.Equal(t, map[string]any{ + "config": map[string]any{"region": "us-east-1"}, + "items": []any{map[string]any{"enabled": true}}, + "quota_limit": float64(1000), + "codex_cli_only": true, + }, duplicate.Extra) + require.NotNil(t, duplicate.ExpiresAt) + require.True(t, source.ExpiresAt.Equal(*duplicate.ExpiresAt)) + require.Equal(t, source.Notes, duplicate.Notes) + require.Equal(t, source.ProxyFallbackOriginID, duplicate.ProxyID) + require.Equal(t, source.RateMultiplier, duplicate.RateMultiplier) + require.Equal(t, source.LoadFactor, duplicate.LoadFactor) + require.Equal(t, source.GroupIDs, repo.groupsOf[duplicate.ID]) + require.Equal(t, []AccountGroup{ + {AccountID: duplicate.ID, GroupID: 7, Priority: 50}, + {AccountID: duplicate.ID, GroupID: 3, Priority: 7}, + }, repo.accountGroupsOf[duplicate.ID]) + + require.Equal(t, StatusActive, duplicate.Status) + require.False(t, duplicate.Schedulable) + require.Empty(t, duplicate.ErrorMessage) + require.Nil(t, duplicate.LastUsedAt) + require.Nil(t, duplicate.RateLimitedAt) + require.Nil(t, duplicate.RateLimitResetAt) + require.Nil(t, duplicate.OverloadUntil) + require.Nil(t, duplicate.TempUnschedulableUntil) + require.Empty(t, duplicate.TempUnschedulableReason) + require.Nil(t, duplicate.SessionWindowStart) + require.Nil(t, duplicate.SessionWindowEnd) + require.Empty(t, duplicate.SessionWindowStatus) + + duplicate.Credentials["nested"].(map[string]any)["token"] = "changed" + duplicate.Extra["config"].(map[string]any)["region"] = "changed" + duplicate.Extra["items"].([]any)[0].(map[string]any)["enabled"] = false + storedSource, getErr := repo.GetByID(ctx, source.ID) + require.NoError(t, getErr) + require.Equal(t, "source-token", storedSource.Credentials["nested"].(map[string]any)["token"]) + require.Equal(t, "us-east-1", storedSource.Extra["config"].(map[string]any)["region"]) + require.Equal(t, true, storedSource.Extra["items"].([]any)[0].(map[string]any)["enabled"]) + require.Equal(t, "remote-42", storedSource.Extra["crs_account_id"]) +} + +func TestDuplicateAccountRejectsCredentialShadow(t *testing.T) { + ctx := context.Background() + repo := newDuplicateAccountRepoStub() + svc := &adminServiceImpl{accountRepo: repo, accountDuplicateRepo: repo} + parentID := int64(99) + shadow := &Account{ + Name: "shadow", + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + ParentAccountID: &parentID, + QuotaDimension: QuotaDimensionSpark, + } + require.NoError(t, repo.Create(ctx, shadow)) + + _, err := svc.DuplicateAccount(ctx, shadow.ID, "admin:1", "") + + require.Error(t, err) + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) + require.Equal(t, "ACCOUNT_DUPLICATE_SHADOW_UNSUPPORTED", infraerrors.Reason(err)) + require.Len(t, repo.accounts, 1) +} + +func TestDuplicateAccountRejectsRotatingOrUnknownCredentialTypes(t *testing.T) { + for _, accountType := range []string{AccountTypeOAuth, AccountTypeSetupToken, "legacy-cookie"} { + t.Run(accountType, func(t *testing.T) { + ctx := context.Background() + repo := newDuplicateAccountRepoStub() + svc := &adminServiceImpl{accountRepo: repo, accountDuplicateRepo: repo} + source := &Account{ + Name: "rotating-credential-account", + Platform: PlatformOpenAI, + Type: accountType, + Credentials: map[string]any{"refresh_token": "shared-token"}, + } + require.NoError(t, repo.Create(ctx, source)) + + _, err := svc.DuplicateAccount(ctx, source.ID, "admin:1", "") + + require.Error(t, err) + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) + require.Equal(t, "ACCOUNT_DUPLICATE_CREDENTIAL_TYPE_UNSUPPORTED", infraerrors.Reason(err)) + require.Len(t, repo.accounts, 1) + }) + } +} + +func TestDuplicateAccountPreservesUngroupedState(t *testing.T) { + ctx := context.Background() + repo := newDuplicateAccountRepoStub() + svc := &adminServiceImpl{accountRepo: repo, accountDuplicateRepo: repo} + source := &Account{ + Name: "ungrouped", + Platform: PlatformAnthropic, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "secret"}, + GroupIDs: nil, + } + require.NoError(t, repo.Create(ctx, source)) + + duplicate, err := svc.DuplicateAccount(ctx, source.ID, "admin:1", "") + + require.NoError(t, err) + require.Empty(t, duplicate.GroupIDs) + require.NotContains(t, repo.groupsOf, duplicate.ID) +} + +func TestDuplicateAccountAtomicCreateFailureLeavesNoOrphan(t *testing.T) { + ctx := context.Background() + repo := newDuplicateAccountRepoStub() + svc := &adminServiceImpl{accountRepo: repo, accountDuplicateRepo: repo} + source := &Account{ + Name: "source", + Platform: PlatformAnthropic, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "secret"}, + GroupIDs: []int64{7}, + AccountGroups: []AccountGroup{{GroupID: 7, Priority: 25}}, + } + require.NoError(t, repo.Create(ctx, source)) + repo.atomicCreateErr = errors.New("group binding failed") + + _, err := svc.DuplicateAccount(ctx, source.ID, "admin:1", "") + + require.ErrorContains(t, err, "group binding failed") + require.Len(t, repo.accounts, 1) +} + +func TestDuplicateAccountNamePreservesSuffixWithinSchemaLimit(t *testing.T) { + name := duplicateAccountName(strings.Repeat("界", 100)) + + require.Equal(t, 100, utf8.RuneCountInString(name)) + require.True(t, strings.HasSuffix(name, " (Copy)")) +} + +func TestDuplicateAccountReturnsExistingCopyForSameOperationKey(t *testing.T) { + ctx := context.Background() + repo := newDuplicateAccountRepoStub() + svc := &adminServiceImpl{accountRepo: repo, accountDuplicateRepo: repo} + source := &Account{ + Name: "source", + Platform: PlatformAnthropic, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "secret"}, + } + require.NoError(t, repo.Create(ctx, source)) + + first, err := svc.DuplicateAccount(ctx, source.ID, "admin:7", "stable-operation-key") + require.NoError(t, err) + second, err := svc.DuplicateAccount(ctx, source.ID, "admin:7", "stable-operation-key") + require.NoError(t, err) + recovered, err := svc.RecoverDuplicateAccount(ctx, source.ID, "admin:7", "stable-operation-key") + require.NoError(t, err) + otherAdminRecovery, err := svc.RecoverDuplicateAccount(ctx, source.ID, "admin:8", "stable-operation-key") + require.NoError(t, err) + otherAdminCopy, err := svc.DuplicateAccount(ctx, source.ID, "admin:8", "stable-operation-key") + require.NoError(t, err) + + require.Equal(t, first.ID, second.ID) + require.Equal(t, first.ID, recovered.ID) + require.Nil(t, otherAdminRecovery, "durable recovery identity must remain scoped to the initiating admin") + require.NotEqual(t, first.ID, otherAdminCopy.ID) + require.Len(t, repo.accounts, 3) + require.NotEmpty(t, first.Extra[duplicateAccountOperationIDExtraKey]) +} diff --git a/backend/internal/service/content_moderation.go b/backend/internal/service/content_moderation.go index f633c8ad17..8102f34a90 100644 --- a/backend/internal/service/content_moderation.go +++ b/backend/internal/service/content_moderation.go @@ -92,6 +92,9 @@ const ( contentModerationCleanupInterval = 24 * time.Hour contentModerationCleanupTimeout = 30 * time.Minute contentModerationCleanupDelay = 5 * time.Minute + + contentModerationRuntimeCacheTTL = time.Second + contentModerationRuntimeRefreshTimeout = 5 * time.Second ) var contentModerationCategoryOrder = []string{ @@ -512,10 +515,22 @@ type ContentModerationService struct { lastCleanupUnix atomic.Int64 lastCleanupDeletedHit atomic.Int64 lastCleanupDeletedNonHit atomic.Int64 + runtimeSnapshot atomic.Pointer[contentModerationRuntimeSnapshot] + runtimeRefreshMu sync.Mutex + runtimeCacheTTL time.Duration + runtimeRefreshRetryAt atomic.Int64 keyHealthMu sync.Mutex keyHealth map[string]*contentModerationKeyHealth } +type contentModerationRuntimeSnapshot struct { + riskControlEnabled bool + config *ContentModerationConfig + keywordMatcher *contentModerationKeywordMatcher + configDigest [sha256.Size]byte + loadedAt time.Time +} + type contentModerationTask struct { input ContentModerationCheckInput content ContentModerationInput @@ -700,6 +715,7 @@ func (s *ContentModerationService) UpdateConfig(ctx context.Context, input Updat if err := s.settingRepo.Set(ctx, SettingKeyContentModerationConfig, string(raw)); err != nil { return nil, fmt.Errorf("save content moderation config: %w", err) } + s.replaceRuntimeConfig(cfg, raw) return s.configView(cfg), nil } @@ -776,16 +792,7 @@ func (s *ContentModerationService) Check(ctx context.Context, input ContentModer "protocol", input.Protocol) return allow, nil } - if !s.isRiskControlEnabled(ctx) { - slog.Info("content_moderation.skip_feature_disabled", - "user_id", input.UserID, - "api_key_id", input.APIKeyID, - "group_id", contentModerationLogGroupID(input.GroupID), - "endpoint", input.Endpoint, - "protocol", input.Protocol) - return allow, nil - } - cfg, err := s.loadConfig(ctx) + runtimeSnapshot, err := s.loadRuntimeSnapshot(ctx) if err != nil { slog.Warn("content_moderation.skip_config_load_failed", "user_id", input.UserID, @@ -796,6 +803,16 @@ func (s *ContentModerationService) Check(ctx context.Context, input ContentModer "error", err) return allow, nil } + if !runtimeSnapshot.riskControlEnabled { + slog.Info("content_moderation.skip_feature_disabled", + "user_id", input.UserID, + "api_key_id", input.APIKeyID, + "group_id", contentModerationLogGroupID(input.GroupID), + "endpoint", input.Endpoint, + "protocol", input.Protocol) + return allow, nil + } + cfg := runtimeSnapshot.config inGroupScope := cfg.includesGroup(input.GroupID) inModelScope := cfg.includesModel(input.Model) slog.Info("content_moderation.config_loaded", @@ -885,7 +902,7 @@ func (s *ContentModerationService) Check(ctx context.Context, input ContentModer hashText := content.Hash() if cfg.Mode == ContentModerationModePreBlock { if cfg.KeywordBlockingMode != ContentModerationKeywordModeAPIOnly && len(cfg.BlockedKeywords) > 0 { - if keyword, hit := matchBlockedKeyword(content.Text, cfg.BlockedKeywords); hit { + if keyword, hit := runtimeSnapshot.matchBlockedKeyword(content.Text); hit { s.recordPreBlockSyncMetric(0, ContentModerationActionKeywordBlock) slog.Info("content_moderation.keyword_block", "user_id", input.UserID, @@ -1178,12 +1195,13 @@ func (s *ContentModerationService) enqueueRecord(input ContentModerationCheckInp func (s *ContentModerationService) worker(id int) { for { ctx, cancel := context.WithTimeout(context.Background(), maxContentModerationTimeoutMS*time.Millisecond+10*time.Second) - cfg, err := s.loadConfig(ctx) - if err != nil || id >= cfg.WorkerCount { + runtimeSnapshot, err := s.loadRuntimeSnapshot(ctx) + if err != nil || runtimeSnapshot == nil || runtimeSnapshot.config == nil || id >= runtimeSnapshot.config.WorkerCount { cancel() time.Sleep(time.Second) continue } + cfg := runtimeSnapshot.config task, ok := s.dequeueAsyncTask(ctx, time.Second) if !ok { cancel() @@ -1438,15 +1456,18 @@ func (s *ContentModerationService) runCleanupOnce() { } func (s *ContentModerationService) loadConfig(ctx context.Context) (*ContentModerationConfig, error) { - cfg := defaultContentModerationConfig() raw, err := s.settingRepo.GetValue(ctx, SettingKeyContentModerationConfig) if err != nil { if errors.Is(err, ErrSettingNotFound) { - cfg.normalize() - return cfg, nil + return parseContentModerationConfig("") } return nil, fmt.Errorf("get content moderation config: %w", err) } + return parseContentModerationConfig(raw) +} + +func parseContentModerationConfig(raw string) (*ContentModerationConfig, error) { + cfg := defaultContentModerationConfig() if strings.TrimSpace(raw) == "" { cfg.normalize() return cfg, nil @@ -1458,6 +1479,137 @@ func (s *ContentModerationService) loadConfig(ctx context.Context) (*ContentMode return cfg, nil } +func (s *ContentModerationService) loadRuntimeSnapshot(ctx context.Context) (*contentModerationRuntimeSnapshot, error) { + if s == nil || s.settingRepo == nil { + return nil, errors.New("content moderation setting repository unavailable") + } + now := time.Now() + if snapshot := s.runtimeSnapshot.Load(); snapshot != nil { + if now.Sub(snapshot.loadedAt) < s.runtimeSnapshotTTL() { + return snapshot, nil + } + s.triggerRuntimeSnapshotRefresh() + return snapshot, nil + } + + s.runtimeRefreshMu.Lock() + defer s.runtimeRefreshMu.Unlock() + if snapshot := s.runtimeSnapshot.Load(); snapshot != nil { + return snapshot, nil + } + return s.refreshRuntimeSnapshot(ctx) +} + +func (s *ContentModerationService) runtimeSnapshotTTL() time.Duration { + if s != nil && s.runtimeCacheTTL > 0 { + return s.runtimeCacheTTL + } + return contentModerationRuntimeCacheTTL +} + +func (s *ContentModerationService) triggerRuntimeSnapshotRefresh() { + if s == nil || s.runtimeRefreshDeferred() || !s.runtimeRefreshMu.TryLock() { + return + } + if s.runtimeRefreshDeferred() { + s.runtimeRefreshMu.Unlock() + return + } + go func() { + defer s.runtimeRefreshMu.Unlock() + ctx, cancel := context.WithTimeout(context.Background(), contentModerationRuntimeRefreshTimeout) + defer cancel() + if _, err := s.refreshRuntimeSnapshot(ctx); err != nil { + s.runtimeRefreshRetryAt.Store(time.Now().Add(s.runtimeSnapshotTTL()).UnixNano()) + slog.Warn("content_moderation.runtime_snapshot_refresh_failed", "error", err) + } + }() +} + +func (s *ContentModerationService) runtimeRefreshDeferred() bool { + if s == nil { + return false + } + return time.Now().UnixNano() < s.runtimeRefreshRetryAt.Load() +} + +func (s *ContentModerationService) refreshRuntimeSnapshot(ctx context.Context) (*contentModerationRuntimeSnapshot, error) { + values, err := s.settingRepo.GetMultiple(ctx, []string{ + SettingKeyRiskControlEnabled, + SettingKeyContentModerationConfig, + }) + if err != nil { + return nil, fmt.Errorf("get content moderation runtime settings: %w", err) + } + rawConfig := values[SettingKeyContentModerationConfig] + configDigest := sha256.Sum256([]byte(rawConfig)) + if current := s.runtimeSnapshot.Load(); current != nil && current.configDigest == configDigest { + snapshot := &contentModerationRuntimeSnapshot{ + riskControlEnabled: values[SettingKeyRiskControlEnabled] == "true", + config: current.config, + keywordMatcher: current.keywordMatcher, + configDigest: configDigest, + loadedAt: time.Now(), + } + s.runtimeSnapshot.Store(snapshot) + s.runtimeRefreshRetryAt.Store(0) + return snapshot, nil + } + cfg, err := parseContentModerationConfig(rawConfig) + if err != nil { + return nil, err + } + snapshot := &contentModerationRuntimeSnapshot{ + riskControlEnabled: values[SettingKeyRiskControlEnabled] == "true", + config: cfg, + keywordMatcher: newContentModerationKeywordMatcher(cfg.BlockedKeywords), + configDigest: configDigest, + loadedAt: time.Now(), + } + s.runtimeSnapshot.Store(snapshot) + s.runtimeRefreshRetryAt.Store(0) + return snapshot, nil +} + +func (s *ContentModerationService) replaceRuntimeConfig(cfg *ContentModerationConfig, raw []byte) { + if s == nil || cfg == nil { + return + } + s.runtimeRefreshMu.Lock() + hasSnapshot := s.runtimeSnapshot.Load() != nil + s.runtimeRefreshMu.Unlock() + if !hasSnapshot { + return + } + config := cloneContentModerationConfig(cfg) + keywordMatcher := newContentModerationKeywordMatcher(cfg.BlockedKeywords) + configDigest := sha256.Sum256(raw) + + s.runtimeRefreshMu.Lock() + defer s.runtimeRefreshMu.Unlock() + current := s.runtimeSnapshot.Load() + if current == nil { + return + } + s.runtimeSnapshot.Store(&contentModerationRuntimeSnapshot{ + riskControlEnabled: current.riskControlEnabled, + config: config, + keywordMatcher: keywordMatcher, + configDigest: configDigest, + loadedAt: time.Now(), + }) +} + +func (s *contentModerationRuntimeSnapshot) matchBlockedKeyword(text string) (string, bool) { + if s == nil || s.config == nil { + return "", false + } + if s.keywordMatcher != nil { + return s.keywordMatcher.Match(text) + } + return matchBlockedKeyword(text, s.config.BlockedKeywords) +} + func (s *ContentModerationService) isRiskControlEnabled(ctx context.Context) bool { raw, err := s.settingRepo.GetValue(ctx, SettingKeyRiskControlEnabled) if err != nil { diff --git a/backend/internal/service/content_moderation_keyword_matcher.go b/backend/internal/service/content_moderation_keyword_matcher.go new file mode 100644 index 0000000000..4628d3b70a --- /dev/null +++ b/backend/internal/service/content_moderation_keyword_matcher.go @@ -0,0 +1,222 @@ +package service + +import ( + "strings" +) + +type contentModerationKeywordMatcher struct { + nodes []contentModerationKeywordNode + edges []contentModerationKeywordEdge + rootTransitions [256]int32 + keywords []string +} + +type contentModerationKeywordNode struct { + failure int32 + bestKeyword int32 + edgeStart uint32 + edgeCount uint16 +} + +type contentModerationKeywordEdge struct { + target int32 + label byte +} + +type contentModerationKeywordBuildEdge struct { + target int32 + nextSibling int32 + label byte +} + +func newContentModerationKeywordMatcher(keywords []string) *contentModerationKeywordMatcher { + if len(keywords) == 0 { + return nil + } + + buildNodes := []contentModerationKeywordNode{newContentModerationKeywordNode()} + buildEdges := make([]contentModerationKeywordBuildEdge, 0) + originalKeywords := append([]string(nil), keywords...) + + for keywordIndex, keyword := range keywords { + if keyword == "" { + continue + } + state := int32(0) + for _, label := range []byte(strings.ToLower(keyword)) { + next := contentModerationKeywordBuildTransition(buildNodes, buildEdges, state, label) + if next < 0 { + next = int32(len(buildNodes)) + buildNodes = append(buildNodes, newContentModerationKeywordNode()) + buildEdges = append(buildEdges, contentModerationKeywordBuildEdge{ + target: next, + nextSibling: contentModerationKeywordBuildFirstEdge(buildNodes[state]), + label: label, + }) + buildNodes[state].edgeStart = uint32(len(buildEdges)) + } + state = next + } + if current := buildNodes[state].bestKeyword; current < 0 || int32(keywordIndex) < current { + buildNodes[state].bestKeyword = int32(keywordIndex) + } + } + + if len(buildNodes) == 1 { + return nil + } + + queue := make([]int32, 0, len(buildNodes)-1) + var rootTransitions [256]int32 + for edgeIndex := contentModerationKeywordBuildFirstEdge(buildNodes[0]); edgeIndex >= 0; edgeIndex = buildEdges[edgeIndex].nextSibling { + edge := buildEdges[edgeIndex] + rootTransitions[edge.label] = edge.target + queue = append(queue, edge.target) + } + + for queueIndex := 0; queueIndex < len(queue); queueIndex++ { + state := queue[queueIndex] + for edgeIndex := contentModerationKeywordBuildFirstEdge(buildNodes[state]); edgeIndex >= 0; edgeIndex = buildEdges[edgeIndex].nextSibling { + edge := buildEdges[edgeIndex] + failure := buildNodes[state].failure + fallback := contentModerationKeywordBuildTransition(buildNodes, buildEdges, failure, edge.label) + for fallback < 0 && failure != 0 { + failure = buildNodes[failure].failure + fallback = contentModerationKeywordBuildTransition(buildNodes, buildEdges, failure, edge.label) + } + if fallback >= 0 { + buildNodes[edge.target].failure = fallback + } + buildNodes[edge.target].bestKeyword = minKeywordIndex( + buildNodes[edge.target].bestKeyword, + buildNodes[buildNodes[edge.target].failure].bestKeyword, + ) + queue = append(queue, edge.target) + } + } + + edges := make([]contentModerationKeywordEdge, 0, len(buildEdges)) + var outgoing [256]contentModerationKeywordEdge + for nodeIndex := range buildNodes { + count := 0 + for edgeIndex := contentModerationKeywordBuildFirstEdge(buildNodes[nodeIndex]); edgeIndex >= 0; edgeIndex = buildEdges[edgeIndex].nextSibling { + edge := buildEdges[edgeIndex] + outgoing[count] = contentModerationKeywordEdge{target: edge.target, label: edge.label} + count++ + } + for index := 1; index < count; index++ { + current := outgoing[index] + insertAt := index + for insertAt > 0 && current.label < outgoing[insertAt-1].label { + outgoing[insertAt] = outgoing[insertAt-1] + insertAt-- + } + outgoing[insertAt] = current + } + buildNodes[nodeIndex].edgeStart = uint32(len(edges)) + buildNodes[nodeIndex].edgeCount = uint16(count) + edges = append(edges, outgoing[:count]...) + } + + return &contentModerationKeywordMatcher{ + nodes: buildNodes, + edges: edges, + rootTransitions: rootTransitions, + keywords: originalKeywords, + } +} + +func newContentModerationKeywordNode() contentModerationKeywordNode { + return contentModerationKeywordNode{bestKeyword: -1} +} + +func contentModerationKeywordBuildFirstEdge(node contentModerationKeywordNode) int32 { + if node.edgeStart == 0 { + return -1 + } + return int32(node.edgeStart - 1) +} + +func contentModerationKeywordBuildTransition( + nodes []contentModerationKeywordNode, + edges []contentModerationKeywordBuildEdge, + state int32, + label byte, +) int32 { + if state < 0 || int(state) >= len(nodes) { + return -1 + } + for edgeIndex := contentModerationKeywordBuildFirstEdge(nodes[state]); edgeIndex >= 0; edgeIndex = edges[edgeIndex].nextSibling { + if edges[edgeIndex].label == label { + return edges[edgeIndex].target + } + } + return -1 +} + +func minKeywordIndex(left, right int32) int32 { + if left < 0 { + return right + } + if right < 0 || left < right { + return left + } + return right +} + +func (m *contentModerationKeywordMatcher) Match(text string) (string, bool) { + if m == nil || text == "" || len(m.nodes) == 0 || len(m.keywords) == 0 { + return "", false + } + lower := strings.ToLower(text) + state := int32(0) + bestKeyword := int32(-1) + for index := 0; index < len(lower); index++ { + label := lower[index] + for { + next := m.next(state, label) + if next != 0 { + state = next + break + } + if state == 0 { + break + } + state = m.nodes[state].failure + } + bestKeyword = minKeywordIndex(bestKeyword, m.nodes[state].bestKeyword) + if bestKeyword == 0 { + return m.keywords[0], true + } + } + if bestKeyword < 0 || int(bestKeyword) >= len(m.keywords) { + return "", false + } + return m.keywords[bestKeyword], true +} + +func (m *contentModerationKeywordMatcher) next(state int32, label byte) int32 { + if state == 0 { + return m.rootTransitions[label] + } + if state < 0 || int(state) >= len(m.nodes) { + return 0 + } + node := m.nodes[state] + left := int(node.edgeStart) + right := left + int(node.edgeCount) + for left < right { + middle := left + (right-left)/2 + edge := m.edges[middle] + if edge.label < label { + left = middle + 1 + continue + } + right = middle + } + end := int(node.edgeStart) + int(node.edgeCount) + if left < end && m.edges[left].label == label { + return m.edges[left].target + } + return 0 +} diff --git a/backend/internal/service/content_moderation_keyword_matcher_test.go b/backend/internal/service/content_moderation_keyword_matcher_test.go new file mode 100644 index 0000000000..4be70dca3e --- /dev/null +++ b/backend/internal/service/content_moderation_keyword_matcher_test.go @@ -0,0 +1,59 @@ +package service + +import ( + "math/rand" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestContentModerationKeywordMatcherMatchesLegacyBehavior(t *testing.T) { + tests := []struct { + name string + text string + keywords []string + }{ + {name: "miss", text: "clean prompt", keywords: []string{"blocked", "secret"}}, + {name: "case insensitive", text: "contains SECRET value", keywords: []string{"secret"}}, + {name: "configured order wins", text: "early appears before later", keywords: []string{"later", "early"}}, + {name: "overlap uses configured order", text: "abc", keywords: []string{"bc", "abc"}}, + {name: "unicode", text: "这里包含敏感词和世界", keywords: []string{"世界", "敏感词"}}, + {name: "duplicates", text: "duplicate", keywords: []string{"duplicate", "DUPLICATE"}}, + {name: "empty entries", text: "blocked", keywords: []string{"", "blocked"}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + wantKeyword, wantHit := matchBlockedKeyword(tt.text, tt.keywords) + gotKeyword, gotHit := newContentModerationKeywordMatcher(tt.keywords).Match(tt.text) + require.Equal(t, wantHit, gotHit) + require.Equal(t, wantKeyword, gotKeyword) + }) + } +} + +func TestContentModerationKeywordMatcherRandomizedParity(t *testing.T) { + rng := rand.New(rand.NewSource(20260714)) + const alphabet = "abcXYZ" + for iteration := 0; iteration < 1000; iteration++ { + keywords := make([]string, 1+rng.Intn(30)) + for index := range keywords { + length := 1 + rng.Intn(8) + var value strings.Builder + for range length { + _ = value.WriteByte(alphabet[rng.Intn(len(alphabet))]) + } + keywords[index] = value.String() + } + var text strings.Builder + for range 20 + rng.Intn(100) { + _ = text.WriteByte(alphabet[rng.Intn(len(alphabet))]) + } + + wantKeyword, wantHit := matchBlockedKeyword(text.String(), keywords) + gotKeyword, gotHit := newContentModerationKeywordMatcher(keywords).Match(text.String()) + require.Equal(t, wantHit, gotHit, "iteration %d", iteration) + require.Equal(t, wantKeyword, gotKeyword, "iteration %d", iteration) + } +} diff --git a/backend/internal/service/content_moderation_runtime_cache_test.go b/backend/internal/service/content_moderation_runtime_cache_test.go new file mode 100644 index 0000000000..2b34d1fa57 --- /dev/null +++ b/backend/internal/service/content_moderation_runtime_cache_test.go @@ -0,0 +1,451 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +type contentModerationRuntimeSettingRepo struct { + mu sync.Mutex + values map[string]string + getValueCalls int + getMultipleCalls int + getMultipleErr error + getMultipleStart chan<- struct{} + getMultipleWait <-chan struct{} +} + +func (r *contentModerationRuntimeSettingRepo) Get(_ context.Context, key string) (*Setting, error) { + r.mu.Lock() + defer r.mu.Unlock() + value, ok := r.values[key] + if !ok { + return nil, ErrSettingNotFound + } + return &Setting{Key: key, Value: value}, nil +} + +func (r *contentModerationRuntimeSettingRepo) GetValue(_ context.Context, key string) (string, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.getValueCalls++ + value, ok := r.values[key] + if !ok { + return "", ErrSettingNotFound + } + return value, nil +} + +func (r *contentModerationRuntimeSettingRepo) Set(_ context.Context, key, value string) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.values == nil { + r.values = make(map[string]string) + } + r.values[key] = value + return nil +} + +func (r *contentModerationRuntimeSettingRepo) GetMultiple(_ context.Context, keys []string) (map[string]string, error) { + r.mu.Lock() + r.getMultipleCalls++ + if err := r.getMultipleErr; err != nil { + r.mu.Unlock() + return nil, err + } + out := make(map[string]string, len(keys)) + for _, key := range keys { + if value, ok := r.values[key]; ok { + out[key] = value + } + } + start := r.getMultipleStart + wait := r.getMultipleWait + r.getMultipleStart = nil + r.getMultipleWait = nil + r.mu.Unlock() + if start != nil { + start <- struct{}{} + } + if wait != nil { + <-wait + } + return out, nil +} + +func (r *contentModerationRuntimeSettingRepo) SetMultiple(_ context.Context, values map[string]string) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.values == nil { + r.values = make(map[string]string) + } + for key, value := range values { + r.values[key] = value + } + return nil +} + +func (r *contentModerationRuntimeSettingRepo) GetAll(_ context.Context) (map[string]string, error) { + r.mu.Lock() + defer r.mu.Unlock() + out := make(map[string]string, len(r.values)) + for key, value := range r.values { + out[key] = value + } + return out, nil +} + +func (r *contentModerationRuntimeSettingRepo) Delete(_ context.Context, key string) error { + r.mu.Lock() + defer r.mu.Unlock() + delete(r.values, key) + return nil +} + +func (r *contentModerationRuntimeSettingRepo) calls() (getValue, getMultiple int) { + r.mu.Lock() + defer r.mu.Unlock() + return r.getValueCalls, r.getMultipleCalls +} + +func (r *contentModerationRuntimeSettingRepo) failMultiple(err error) { + r.mu.Lock() + defer r.mu.Unlock() + r.getMultipleErr = err +} + +func (r *contentModerationRuntimeSettingRepo) blockNextMultiple(start chan<- struct{}, wait <-chan struct{}) { + r.mu.Lock() + defer r.mu.Unlock() + r.getMultipleStart = start + r.getMultipleWait = wait +} + +func runtimeCacheTestConfig(t *testing.T, keywords ...string) string { + t.Helper() + cfg := defaultContentModerationConfig() + cfg.Enabled = true + cfg.Mode = ContentModerationModePreBlock + cfg.KeywordBlockingMode = ContentModerationKeywordModeKeywordOnly + cfg.BlockedKeywords = keywords + raw, err := json.Marshal(cfg) + require.NoError(t, err) + return string(raw) +} + +func runtimeCacheTestService(repo *contentModerationRuntimeSettingRepo, ttl time.Duration) *ContentModerationService { + return &ContentModerationService{ + settingRepo: repo, + repo: &contentModerationTestRepo{}, + runtimeCacheTTL: ttl, + } +} + +func runtimeCacheTestInput(text string) ContentModerationCheckInput { + return ContentModerationCheckInput{ + Protocol: ContentModerationProtocolOpenAIChat, + Model: "risk-cache-test", + Body: []byte(`{"messages":[{"role":"user","content":"` + text + `"}]}`), + } +} + +func TestContentModerationRuntimeSnapshotCachesSettings(t *testing.T) { + repo := &contentModerationRuntimeSettingRepo{values: map[string]string{ + SettingKeyRiskControlEnabled: "true", + SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked"), + }} + svc := runtimeCacheTestService(repo, time.Hour) + + for range 20 { + decision, err := svc.Check(context.Background(), runtimeCacheTestInput("clean prompt")) + require.NoError(t, err) + require.True(t, decision.Allowed) + } + + getValue, getMultiple := repo.calls() + require.Zero(t, getValue) + require.Equal(t, 1, getMultiple) +} + +func TestContentModerationRuntimeSnapshotUpdateConfigIsImmediate(t *testing.T) { + repo := &contentModerationRuntimeSettingRepo{values: map[string]string{ + SettingKeyRiskControlEnabled: "true", + SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "old-keyword"), + }} + svc := runtimeCacheTestService(repo, time.Hour) + + decision, err := svc.Check(context.Background(), runtimeCacheTestInput("new-keyword")) + require.NoError(t, err) + require.True(t, decision.Allowed) + + keywords := []string{"new-keyword"} + _, err = svc.UpdateConfig(context.Background(), UpdateContentModerationConfigInput{ + BlockedKeywords: &keywords, + }) + require.NoError(t, err) + + decision, err = svc.Check(context.Background(), runtimeCacheTestInput("new-keyword")) + require.NoError(t, err) + require.True(t, decision.Blocked) + + _, getMultiple := repo.calls() + require.Equal(t, 1, getMultiple) +} + +func TestContentModerationRuntimeSnapshotUpdateWinsOverInitialLoad(t *testing.T) { + repo := &contentModerationRuntimeSettingRepo{values: map[string]string{ + SettingKeyRiskControlEnabled: "true", + SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "old-keyword"), + }} + svc := runtimeCacheTestService(repo, time.Hour) + + refreshStarted := make(chan struct{}, 1) + releaseRefresh := make(chan struct{}) + released := false + defer func() { + if !released { + close(releaseRefresh) + } + }() + repo.blockNextMultiple(refreshStarted, releaseRefresh) + + initialCheckDone := make(chan error, 1) + go func() { + decision, err := svc.Check(context.Background(), runtimeCacheTestInput("clean prompt")) + if err == nil && (decision == nil || !decision.Allowed) { + err = errors.New("unexpected initial moderation decision") + } + initialCheckDone <- err + }() + require.Eventually(t, func() bool { + select { + case <-refreshStarted: + return true + default: + return false + } + }, time.Second, time.Millisecond) + + updateDone := make(chan error, 1) + go func() { + keywords := []string{"new-keyword"} + _, updateErr := svc.UpdateConfig(context.Background(), UpdateContentModerationConfigInput{ + BlockedKeywords: &keywords, + }) + updateDone <- updateErr + }() + select { + case updateErr := <-updateDone: + require.NoError(t, updateErr) + t.Fatal("configuration update completed before the initial load released its lock") + case <-time.After(10 * time.Millisecond): + } + + close(releaseRefresh) + released = true + require.NoError(t, <-initialCheckDone) + require.NoError(t, <-updateDone) + + decision, err := svc.Check(context.Background(), runtimeCacheTestInput("new-keyword")) + require.NoError(t, err) + require.True(t, decision.Blocked) + decision, err = svc.Check(context.Background(), runtimeCacheTestInput("old-keyword")) + require.NoError(t, err) + require.True(t, decision.Allowed) +} + +func TestContentModerationRuntimeSnapshotRefreshFailureKeepsStaleConfig(t *testing.T) { + repo := &contentModerationRuntimeSettingRepo{values: map[string]string{ + SettingKeyRiskControlEnabled: "true", + SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked"), + }} + svc := runtimeCacheTestService(repo, time.Nanosecond) + input := runtimeCacheTestInput("blocked") + + decision, err := svc.Check(context.Background(), input) + require.NoError(t, err) + require.True(t, decision.Blocked) + + repo.failMultiple(errors.New("database unavailable")) + decision, err = svc.Check(context.Background(), input) + require.NoError(t, err) + require.True(t, decision.Blocked) + require.Eventually(t, func() bool { + _, calls := repo.calls() + return calls >= 2 + }, time.Second, time.Millisecond) +} + +func TestContentModerationRuntimeSnapshotRefreshFailureBacksOff(t *testing.T) { + repo := &contentModerationRuntimeSettingRepo{values: map[string]string{ + SettingKeyRiskControlEnabled: "true", + SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked"), + }} + svc := runtimeCacheTestService(repo, time.Minute) + input := runtimeCacheTestInput("blocked") + + decision, err := svc.Check(context.Background(), input) + require.NoError(t, err) + require.True(t, decision.Blocked) + + current := svc.runtimeSnapshot.Load() + require.NotNil(t, current) + expired := *current + expired.loadedAt = time.Now().Add(-2 * time.Minute) + svc.runtimeSnapshot.Store(&expired) + repo.failMultiple(errors.New("database unavailable")) + + decision, err = svc.Check(context.Background(), input) + require.NoError(t, err) + require.True(t, decision.Blocked) + require.Eventually(t, func() bool { + _, calls := repo.calls() + return calls == 2 + }, time.Second, time.Millisecond) + + for range 100 { + decision, err = svc.Check(context.Background(), input) + require.NoError(t, err) + require.True(t, decision.Blocked) + } + _, calls := repo.calls() + require.Equal(t, 2, calls) +} + +func TestContentModerationRuntimeSnapshotRefreshReusesUnchangedMatcher(t *testing.T) { + repo := &contentModerationRuntimeSettingRepo{values: map[string]string{ + SettingKeyRiskControlEnabled: "true", + SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked"), + }} + svc := runtimeCacheTestService(repo, time.Minute) + input := runtimeCacheTestInput("blocked") + + decision, err := svc.Check(context.Background(), input) + require.NoError(t, err) + require.True(t, decision.Blocked) + + current := svc.runtimeSnapshot.Load() + require.NotNil(t, current) + expired := *current + expired.loadedAt = time.Now().Add(-2 * time.Minute) + svc.runtimeSnapshot.Store(&expired) + + decision, err = svc.Check(context.Background(), input) + require.NoError(t, err) + require.True(t, decision.Blocked) + require.Eventually(t, func() bool { + refreshed := svc.runtimeSnapshot.Load() + return refreshed != nil && refreshed.loadedAt.After(expired.loadedAt) + }, time.Second, time.Millisecond) + + refreshed := svc.runtimeSnapshot.Load() + require.Same(t, current.config, refreshed.config) + require.Same(t, current.keywordMatcher, refreshed.keywordMatcher) + _, calls := repo.calls() + require.Equal(t, 2, calls) +} + +func TestContentModerationRuntimeSnapshotUpdateWinsOverInFlightRefresh(t *testing.T) { + repo := &contentModerationRuntimeSettingRepo{values: map[string]string{ + SettingKeyRiskControlEnabled: "true", + SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "old-keyword"), + }} + svc := runtimeCacheTestService(repo, time.Minute) + + decision, err := svc.Check(context.Background(), runtimeCacheTestInput("old-keyword")) + require.NoError(t, err) + require.True(t, decision.Blocked) + + current := svc.runtimeSnapshot.Load() + require.NotNil(t, current) + expired := *current + expired.loadedAt = time.Now().Add(-2 * time.Minute) + svc.runtimeSnapshot.Store(&expired) + + refreshStarted := make(chan struct{}, 1) + releaseRefresh := make(chan struct{}) + repo.blockNextMultiple(refreshStarted, releaseRefresh) + decision, err = svc.Check(context.Background(), runtimeCacheTestInput("clean prompt")) + require.NoError(t, err) + require.True(t, decision.Allowed) + require.Eventually(t, func() bool { + select { + case <-refreshStarted: + return true + default: + return false + } + }, time.Second, time.Millisecond) + + updateDone := make(chan error, 1) + go func() { + keywords := []string{"new-keyword"} + _, updateErr := svc.UpdateConfig(context.Background(), UpdateContentModerationConfigInput{ + BlockedKeywords: &keywords, + }) + updateDone <- updateErr + }() + select { + case updateErr := <-updateDone: + require.NoError(t, updateErr) + t.Fatal("configuration update completed before the in-flight refresh released its lock") + case <-time.After(10 * time.Millisecond): + } + + close(releaseRefresh) + require.NoError(t, <-updateDone) + decision, err = svc.Check(context.Background(), runtimeCacheTestInput("new-keyword")) + require.NoError(t, err) + require.True(t, decision.Blocked) + decision, err = svc.Check(context.Background(), runtimeCacheTestInput("old-keyword")) + require.NoError(t, err) + require.True(t, decision.Allowed) +} + +func TestContentModerationRuntimeSnapshotConcurrentReadAndReplace(t *testing.T) { + repo := &contentModerationRuntimeSettingRepo{values: map[string]string{ + SettingKeyRiskControlEnabled: "true", + SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked-0"), + }} + svc := runtimeCacheTestService(repo, time.Hour) + _, err := svc.Check(context.Background(), runtimeCacheTestInput("clean prompt")) + require.NoError(t, err) + + var wg sync.WaitGroup + errs := make(chan error, 8) + for range 8 { + wg.Add(1) + go func() { + defer wg.Done() + for range 100 { + decision, checkErr := svc.Check(context.Background(), runtimeCacheTestInput("clean prompt")) + if checkErr != nil { + errs <- checkErr + return + } + if decision == nil || !decision.Allowed { + errs <- errors.New("unexpected moderation decision") + return + } + } + }() + } + for i := 1; i <= 20; i++ { + keywords := []string{"blocked-" + time.Duration(i).String()} + _, err := svc.UpdateConfig(context.Background(), UpdateContentModerationConfigInput{ + BlockedKeywords: &keywords, + }) + require.NoError(t, err) + } + wg.Wait() + close(errs) + for err := range errs { + require.NoError(t, err) + } +} diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index c151375623..73c59c4ece 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -558,19 +558,80 @@ type ForwardResult struct { ImageSizeBreakdown map[string]int } -// UpstreamFailoverError indicates an upstream error that should trigger account failover. +// GatewayFailureStage identifies which request stage failed. The zero value is +// intentionally treated as inference so existing UpstreamFailoverError callers +// retain their current behavior. +type GatewayFailureStage string + +const ( + GatewayFailureStageInference GatewayFailureStage = "inference" + GatewayFailureStageAccountAuth GatewayFailureStage = "account_auth" +) + +// GatewayFailureScope identifies whether selecting another account can help. +type GatewayFailureScope string + +const ( + GatewayFailureScopeAccount GatewayFailureScope = "account" + GatewayFailureScopeProvider GatewayFailureScope = "provider" + GatewayFailureScopeRequest GatewayFailureScope = "request" +) + +// NextAccountAction is tri-state for backwards compatibility. The zero value +// means legacy retry behavior; only NextAccountStop explicitly short-circuits. +type NextAccountAction uint8 + +const ( + NextAccountLegacyRetry NextAccountAction = iota + NextAccountRetry + NextAccountStop +) + +type GatewayFailureReason string + +// UpstreamFailoverError indicates an upstream or credential error that may +// trigger account failover. Additive metadata keeps existing composite literals +// source-compatible and preserves their legacy retry-next-account behavior. type UpstreamFailoverError struct { - StatusCode int - ResponseBody []byte // 上游响应体,用于错误透传规则匹配 - ResponseHeaders http.Header // 上游响应头,用于透传 cf-ray/cf-mitigated/content-type 等诊断信息 - ForceCacheBilling bool // Antigravity 粘性会话切换时设为 true - RetryableOnSameAccount bool // 临时性错误(如 Google 间歇性 400、空响应),应在同一账号上重试 N 次再切换 + StatusCode int + ResponseBody []byte // 上游响应体,用于错误透传规则匹配 + ResponseHeaders http.Header // 上游响应头,用于透传 cf-ray/cf-mitigated/content-type 等诊断信息 + ForceCacheBilling bool // Antigravity 粘性会话切换时设为 true + RetryableOnSameAccount bool // 临时性错误(如 Google 间歇性 400、空响应),应在同一账号上重试 N 次再切换 + SafeToFailoverAfterWrite bool // 仅写出 SSE 注释等非语义字节时,仍可在同一客户端流中切换账号 + Stage GatewayFailureStage + Scope GatewayFailureScope + Reason GatewayFailureReason + NextAccountAction NextAccountAction + ClientStatusCode int + ClientMessage string } func (e *UpstreamFailoverError) Error() string { + if e != nil && e.Stage == GatewayFailureStageAccountAuth { + return fmt.Sprintf("credential failure: %s (failover)", e.Reason) + } return fmt.Sprintf("upstream error: %d (failover)", e.StatusCode) } +func (e *UpstreamFailoverError) ShouldRetryNextAccount() bool { + return e != nil && e.NextAccountAction != NextAccountStop +} + +func (e *UpstreamFailoverError) IsCredentialFailure() bool { + return e != nil && e.Stage == GatewayFailureStageAccountAuth +} + +// ShouldReportAccountScheduleFailure prevents provider- and request-scoped +// credential failures from being misattributed to the selected account. Legacy +// and inference failures retain their existing scheduler-health behavior. +func (e *UpstreamFailoverError) ShouldReportAccountScheduleFailure() bool { + if e == nil { + return false + } + return !e.IsCredentialFailure() || e.Scope == GatewayFailureScopeAccount +} + // sseStreamErrorEventError 表示上游 SSE 流体内出现 event:error 帧。 // RawData 是该事件 data: 行的原始 JSON 字符串 // (Anthropic 标准结构 {"type":"error","error":{"type":"...","message":"..."}})。 diff --git a/backend/internal/service/grok_credential_failure.go b/backend/internal/service/grok_credential_failure.go new file mode 100644 index 0000000000..4ac4aec084 --- /dev/null +++ b/backend/internal/service/grok_credential_failure.go @@ -0,0 +1,661 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/http" + "strings" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/gin-gonic/gin" +) + +const ( + grokCredentialFailoverDeadlineKey = "grok_credential_failover_deadline" + grokCredentialFailoverBudget = 15 * time.Second + grokCredentialMutationTimeout = 5 * time.Second + grokCredentialMutationConfirmWait = 250 * time.Millisecond + grokCredentialCacheCleanupTimeout = 500 * time.Millisecond + + GrokCredentialUnavailableClientMessage = "No healthy Grok OAuth account is currently available" + + GrokCredentialReasonRevoked GatewayFailureReason = "grok_oauth_credential_revoked" + GrokCredentialReasonMissing GatewayFailureReason = "grok_oauth_credentials_missing" + GrokCredentialReasonEntitlement GatewayFailureReason = "grok_oauth_entitlement_action_required" + GrokCredentialReasonProxyInvalid GatewayFailureReason = "grok_oauth_proxy_invalid" + GrokCredentialReasonRefreshTransient GatewayFailureReason = "grok_oauth_refresh_transient" + GrokCredentialReasonProviderConfig GatewayFailureReason = "grok_oauth_provider_config" + GrokCredentialReasonProviderDown GatewayFailureReason = "grok_oauth_provider_unavailable" + GrokCredentialReasonAccountChanged GatewayFailureReason = "grok_oauth_account_state_changed" + GrokCredentialReasonStateUpdate GatewayFailureReason = "grok_oauth_account_state_update_failed" + GrokCredentialReasonFailoverTimeout GatewayFailureReason = "grok_oauth_failover_timeout" +) + +var errGrokCredentialStateUpdateFailed = errors.New("grok oauth account state update failed") + +type grokCredentialFailureClass struct { + scope GatewayFailureScope + reason GatewayFailureReason + action NextAccountAction + permanent bool + transient bool + message string + snapshot *GrokCredentialMutationSnapshot +} + +// GrokCredentialMutationSnapshot is the credential identity observed when the +// request selected an account. Repository mutations compare all fields before +// quarantining that account so a concurrent refresh cannot be overwritten. +type GrokCredentialMutationSnapshot struct { + CredentialsJSON string + AccessToken string + RefreshToken string + TokenVersion int64 + ProxyID *int64 +} + +type grokCredentialFailureSnapshotError struct { + cause error + snapshot GrokCredentialMutationSnapshot +} + +func (e *grokCredentialFailureSnapshotError) Error() string { return e.cause.Error() } +func (e *grokCredentialFailureSnapshotError) Unwrap() error { return e.cause } + +func withGrokCredentialFailureSnapshot(err error, account *Account) error { + if err == nil || account == nil || !account.IsGrokOAuth() { + return err + } + var existing *grokCredentialFailureSnapshotError + if errors.As(err, &existing) { + return err + } + return &grokCredentialFailureSnapshotError{cause: err, snapshot: grokCredentialMutationSnapshot(account)} +} + +func grokCredentialFailureSnapshot(err error) (GrokCredentialMutationSnapshot, bool) { + var snapshotErr *grokCredentialFailureSnapshotError + if !errors.As(err, &snapshotErr) || snapshotErr == nil { + return GrokCredentialMutationSnapshot{}, false + } + return snapshotErr.snapshot, true +} + +type grokCredentialConditionalStateRepository interface { + SetGrokCredentialErrorIfMatch(context.Context, int64, GrokCredentialMutationSnapshot, string) (bool, error) + SetGrokCredentialTempUnschedulableIfMatch(context.Context, int64, GrokCredentialMutationSnapshot, time.Time, string) (bool, error) +} + +// GetRequestCredential applies the request-path credential and failover contract +// before any upstream transport is opened. +func (s *OpenAIGatewayService) GetRequestCredential(ctx context.Context, c *gin.Context, account *Account) (string, string, error) { + return s.getRequestCredential(ctx, c, account) +} + +func (s *OpenAIGatewayService) getRequestCredential(ctx context.Context, c *gin.Context, account *Account) (string, string, error) { + if ctx == nil { + ctx = context.Background() + } + if account == nil { + return "", "", errors.New("account is nil") + } + if !account.IsGrokOAuth() { + return s.GetAccessToken(ctx, account) + } + if err := ctx.Err(); err != nil { + return "", "", err + } + if s == nil || s.grokTokenProvider == nil { + return "", "", s.newGrokCredentialFailover(c, account, grokCredentialFailureClass{ + scope: GatewayFailureScopeProvider, + reason: GrokCredentialReasonProviderConfig, + action: NextAccountStop, + message: "Grok OAuth credential provider is unavailable", + }) + } + if s.isOpenAIAccountRuntimeBlocked(account) { + return "", "", s.newGrokCredentialFailover(c, account, grokCredentialFailureClass{ + scope: GatewayFailureScopeAccount, + reason: GrokCredentialReasonAccountChanged, + action: NextAccountRetry, + message: "Grok OAuth account is not currently schedulable", + }) + } + + credentialCtx, cancel, budgetExpired := grokCredentialAcquisitionContext(ctx, c) + if cancel != nil { + defer cancel() + } + if budgetExpired { + return "", "", s.newGrokCredentialFailover(c, account, grokCredentialFailureClass{ + scope: GatewayFailureScopeRequest, + reason: GrokCredentialReasonFailoverTimeout, + action: NextAccountStop, + message: "Grok OAuth credential failover budget exhausted", + }) + } + + token, kind, err := s.GetAccessToken(credentialCtx, account) + if err == nil { + if s.isOpenAIAccountRuntimeBlocked(account) { + return "", "", s.newGrokCredentialFailover(c, account, grokCredentialFailureClass{ + scope: GatewayFailureScopeAccount, + reason: GrokCredentialReasonAccountChanged, + action: NextAccountRetry, + message: "Grok OAuth account is not currently schedulable", + }) + } + return token, kind, nil + } + if parentErr := ctx.Err(); parentErr != nil { + return "", "", parentErr + } + if credentialCtx.Err() != nil { + return "", "", s.newGrokCredentialFailover(c, account, grokCredentialFailureClass{ + scope: GatewayFailureScopeRequest, + reason: GrokCredentialReasonFailoverTimeout, + action: NextAccountStop, + message: "Grok OAuth credential failover budget exhausted", + }) + } + + class := classifyGrokCredentialFailure(account, err) + if snapshot, ok := grokCredentialFailureSnapshot(err); ok { + class.snapshot = &snapshot + } + if ctx.Err() != nil { + return "", "", ctx.Err() + } + if class.permanent || class.transient { + freshToken, mutationErr := s.applyGrokCredentialAccountFailure(credentialCtx, account, class) + if freshToken != "" { + return freshToken, "oauth", nil + } + if mutationErr != nil { + if ctx.Err() != nil { + return "", "", ctx.Err() + } + if credentialCtx.Err() != nil { + return "", "", s.newGrokCredentialFailover(c, account, grokCredentialFailureClass{ + scope: GatewayFailureScopeRequest, + reason: GrokCredentialReasonFailoverTimeout, + action: NextAccountStop, + message: "Grok OAuth credential failover budget exhausted", + }) + } + if errors.Is(mutationErr, errOAuthRefreshAccountStateChanged) { + class = grokCredentialFailureClass{ + scope: GatewayFailureScopeAccount, + reason: GrokCredentialReasonAccountChanged, + action: NextAccountRetry, + message: "Grok OAuth account eligibility changed", + } + } else if errors.Is(mutationErr, errOAuthRefreshAccountRereadFailed) { + class = grokCredentialFailureClass{ + scope: GatewayFailureScopeProvider, + reason: GrokCredentialReasonProviderDown, + action: NextAccountStop, + message: "Grok OAuth account state is temporarily unavailable", + } + } else { + class = grokCredentialFailureClass{ + scope: GatewayFailureScopeProvider, + reason: GrokCredentialReasonStateUpdate, + action: NextAccountStop, + message: "Grok OAuth account state could not be updated safely", + } + } + } + } + return "", "", s.newGrokCredentialFailover(c, account, class) +} + +func grokCredentialAcquisitionContext(ctx context.Context, c *gin.Context) (context.Context, context.CancelFunc, bool) { + if c == nil { + return ctx, nil, false + } + deadline := time.Time{} + if raw, ok := c.Get(grokCredentialFailoverDeadlineKey); ok { + deadline, _ = raw.(time.Time) + } + if deadline.IsZero() { + deadline = time.Now().Add(grokCredentialFailoverBudget) + c.Set(grokCredentialFailoverDeadlineKey, deadline) + } + if !time.Now().Before(deadline) { + return ctx, nil, true + } + acquireCtx, cancel := context.WithDeadline(ctx, deadline) + return acquireCtx, cancel, false +} + +func classifyGrokCredentialFailure(account *Account, err error) grokCredentialFailureClass { + stableReason := strings.ToLower(strings.TrimSpace(infraerrors.Reason(err))) + message := "" + if err != nil { + message = strings.ToLower(err.Error()) + } + contains := func(values ...string) bool { + for _, value := range values { + if strings.Contains(stableReason, value) || strings.Contains(message, value) { + return true + } + } + return false + } + var providerConfigErr *providerConfigurationRefreshError + var containmentErr *providerCycleContainmentRefreshError + + switch { + case errors.Is(err, errGrokOAuthRefreshTokenMissing), errors.Is(err, errGrokOAuthAccessTokenMissing), errors.Is(err, errGrokOAuthAccessTokenExpired): + return grokCredentialFailureClass{scope: GatewayFailureScopeAccount, reason: GrokCredentialReasonMissing, action: NextAccountRetry, permanent: true, message: "Grok OAuth credentials are missing or expired"} + case contains("invalid_grant", "invalid_refresh_token", "token_expired", "refresh_token_reused", "refresh_token_invalidated", "app_session_terminated"): + return grokCredentialFailureClass{scope: GatewayFailureScopeAccount, reason: GrokCredentialReasonRevoked, action: NextAccountRetry, permanent: true, message: "Grok OAuth credentials require account action"} + case contains("grok_oauth_entitlement_denied", "entitlement_denied", "access_denied", "subscription required", "no active grok subscription"): + return grokCredentialFailureClass{scope: GatewayFailureScopeAccount, reason: GrokCredentialReasonEntitlement, action: NextAccountRetry, permanent: true, message: "Grok OAuth entitlement requires account action"} + case errors.Is(err, errGrokOAuthConfiguredProxyMiss), contains("grok_oauth_proxy_not_found"): + return grokCredentialFailureClass{scope: GatewayFailureScopeAccount, reason: GrokCredentialReasonProxyInvalid, action: NextAccountRetry, permanent: true, message: "Grok OAuth account proxy configuration is invalid"} + case errors.Is(err, errOAuthRefreshAccountRereadFailed): + return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderDown, action: NextAccountStop, message: "Grok OAuth account state is temporarily unavailable"} + case errors.Is(err, errOAuthRefreshCredentialPersist): + return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderDown, action: NextAccountStop, message: "Grok OAuth shared credential state is temporarily unavailable"} + case errors.As(err, &containmentErr): + return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderDown, action: NextAccountStop, message: "Grok OAuth provider state is temporarily unavailable"} + case errors.Is(err, errOAuthRefreshAccountStateChanged): + return grokCredentialFailureClass{scope: GatewayFailureScopeAccount, reason: GrokCredentialReasonAccountChanged, action: NextAccountRetry, message: "Grok OAuth account eligibility changed"} + case errors.As(err, &providerConfigErr): + return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderConfig, action: NextAccountStop, message: "Grok OAuth provider configuration is unavailable"} + case errors.Is(err, errGrokOAuthRefreshNotConfigured), contains("invalid_client", "unauthorized_client", "invalid_scope", "unknown scope", "grok oauth service is not configured", "grok_oauth_proxy_not_available"): + return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderConfig, action: NextAccountStop, message: "Grok OAuth provider configuration is unavailable"} + case contains("grok_oauth_proxy_lookup_failed"), + contains("grok_oauth_token_refresh_failed") && contains("status 403") && (account == nil || account.ProxyID == nil): + return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderDown, action: NextAccountStop, message: "Grok OAuth provider is temporarily unavailable"} + case contains("grok_oauth_client_init_failed") && (account == nil || account.ProxyID == nil): + return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderConfig, action: NextAccountStop, message: "Grok OAuth provider configuration is unavailable"} + case contains("grok_oauth_request_failed") && (account == nil || account.ProxyID == nil): + return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderDown, action: NextAccountStop, message: "Grok OAuth provider is temporarily unavailable"} + case contains("status 429", "status 500", "status 502", "status 503", "status 504") && (account == nil || account.ProxyID == nil): + return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderDown, action: NextAccountStop, message: "Grok OAuth provider is temporarily unavailable"} + default: + return grokCredentialFailureClass{scope: GatewayFailureScopeAccount, reason: GrokCredentialReasonRefreshTransient, action: NextAccountRetry, transient: true, message: "Grok OAuth credential refresh is temporarily unavailable"} + } +} + +func (s *OpenAIGatewayService) applyGrokCredentialAccountFailure(ctx context.Context, account *Account, class grokCredentialFailureClass) (string, error) { + if s == nil || account == nil || ctx == nil || ctx.Err() != nil { + if ctx != nil { + return "", ctx.Err() + } + return "", context.Canceled + } + mutationMu := s.grokCredentialMutationLock(account.ID) + if err := mutationMu.Lock(ctx); err != nil { + return "", err + } + defer mutationMu.Unlock() + stateRepo, hasConditionalStateRepo := s.accountRepo.(grokCredentialConditionalStateRepository) + snapshot := grokCredentialMutationSnapshot(account) + if class.snapshot != nil { + snapshot = *class.snapshot + } + if token, err := s.validateCurrentGrokCredentialFailure(ctx, account.ID, snapshot, class); err != nil || token != "" { + return token, err + } + + if class.permanent { + if token, ok := s.grokCredentialConcurrentlyRefreshedToken(ctx, account.ID, snapshot); ok { + return token, nil + } + if ctx.Err() != nil { + return "", ctx.Err() + } + rollbackRuntime := s.blockGrokCredentialRuntime(account, time.Time{}, string(class.reason)) + keepRuntimeBlock := false + runtimeRollbackDone := false + defer func() { + if !keepRuntimeBlock && !runtimeRollbackDone { + rollbackRuntime() + } + }() + if s.accountRepo == nil { + keepRuntimeBlock = true + return "", fmt.Errorf("%w: account repository is not configured", errGrokCredentialStateUpdateFailed) + } + if !hasConditionalStateRepo { + keepRuntimeBlock = true + return "", fmt.Errorf("%w: conditional account repository is not configured", errGrokCredentialStateUpdateFailed) + } + stateCtx, cancel := context.WithTimeout(ctx, grokCredentialMutationTimeout) + if err := ctx.Err(); err != nil { + cancel() + return "", err + } + updated, err := stateRepo.SetGrokCredentialErrorIfMatch(stateCtx, account.ID, snapshot, string(class.reason)) + requestErr := ctx.Err() + cancel() + if err != nil { + slog.Warn("grok_credential_failure.set_error_failed", "account_id", account.ID, "reason", class.reason, "error", err) + if requestErr != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + if s.grokCredentialMutationCommitted(account.ID, class, time.Time{}) { + updated = true + } else if requestErr != nil { + return "", requestErr + } else { + keepRuntimeBlock = true + return "", fmt.Errorf("%w: permanent state commit could not be confirmed: %v", errGrokCredentialStateUpdateFailed, err) + } + } else { + keepRuntimeBlock = true + return "", fmt.Errorf("%w: persist permanent state: %v", errGrokCredentialStateUpdateFailed, err) + } + } + if !updated { + rollbackRuntime() + runtimeRollbackDone = true + return s.resolveGrokCredentialCASMiss(ctx, account.ID, snapshot) + } + // SetError is the linearization point: the durable quarantine is now + // committed and this node's runtime block must not be rolled back. + keepRuntimeBlock = true + if s.grokTokenProvider == nil { + if ctx.Err() != nil { + return "", ctx.Err() + } + return "", fmt.Errorf("%w: token provider is not configured", errGrokCredentialStateUpdateFailed) + } + invalidateCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), grokCredentialCacheCleanupTimeout) + err = s.grokTokenProvider.InvalidateToken(invalidateCtx, account) + cancel() + if err != nil { + slog.Warn("grok_credential_failure.invalidate_token_failed", "account_id", account.ID, "reason", class.reason, "error", err) + if ctx.Err() != nil { + return "", ctx.Err() + } + return "", fmt.Errorf("%w: invalidate cached credential: %v", errGrokCredentialStateUpdateFailed, err) + } + if ctx.Err() != nil { + return "", ctx.Err() + } + return "", nil + } + + if class.transient { + until := time.Now().Add(tokenRefreshTempUnschedDuration) + if ctx.Err() != nil { + return "", ctx.Err() + } + rollbackRuntime := s.blockGrokCredentialRuntime(account, until, string(class.reason)) + keepRuntimeBlock := false + runtimeRollbackDone := false + defer func() { + if !keepRuntimeBlock && !runtimeRollbackDone { + rollbackRuntime() + } + }() + stateCtx, cancel := context.WithTimeout(ctx, grokCredentialMutationTimeout) + if s.accountRepo == nil { + cancel() + keepRuntimeBlock = true + return "", fmt.Errorf("%w: account repository is not configured", errGrokCredentialStateUpdateFailed) + } + if !hasConditionalStateRepo { + cancel() + keepRuntimeBlock = true + return "", fmt.Errorf("%w: conditional account repository is not configured", errGrokCredentialStateUpdateFailed) + } + if err := ctx.Err(); err != nil { + cancel() + return "", err + } + updated, err := stateRepo.SetGrokCredentialTempUnschedulableIfMatch(stateCtx, account.ID, snapshot, until, string(class.reason)) + requestErr := ctx.Err() + cancel() + if err != nil { + slog.Warn("grok_credential_failure.set_temp_unschedulable_failed", "account_id", account.ID, "reason", class.reason, "error", err) + if requestErr != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + if s.grokCredentialMutationCommitted(account.ID, class, until) { + updated = true + } else if requestErr != nil { + return "", requestErr + } else { + keepRuntimeBlock = true + return "", fmt.Errorf("%w: transient state commit could not be confirmed: %v", errGrokCredentialStateUpdateFailed, err) + } + } else { + keepRuntimeBlock = true + return "", fmt.Errorf("%w: persist transient state: %v", errGrokCredentialStateUpdateFailed, err) + } + } + if !updated { + rollbackRuntime() + runtimeRollbackDone = true + return s.resolveGrokCredentialCASMiss(ctx, account.ID, snapshot) + } + // The temporary quarantine is durable after SetTempUnschedulable succeeds. + keepRuntimeBlock = true + if ctx.Err() != nil { + return "", ctx.Err() + } + return "", nil + } + + return "", nil +} + +func (s *OpenAIGatewayService) validateCurrentGrokCredentialFailure( + ctx context.Context, + accountID int64, + snapshot GrokCredentialMutationSnapshot, + class grokCredentialFailureClass, +) (string, error) { + if s == nil || s.accountRepo == nil || accountID <= 0 || ctx == nil || ctx.Err() != nil { + if ctx != nil { + return "", ctx.Err() + } + return "", context.Canceled + } + checkCtx, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + latest, err := s.accountRepo.GetByID(checkCtx, accountID) + if err != nil { + if errors.Is(err, ErrAccountNotFound) { + return "", errOAuthRefreshAccountStateChanged + } + return "", fmt.Errorf("%w: %v", errOAuthRefreshAccountRereadFailed, err) + } + if latest == nil || !latest.IsGrokOAuth() || !latest.IsSchedulable() || s.isOpenAIAccountRuntimeBlocked(latest) { + return "", errOAuthRefreshAccountStateChanged + } + latestSnapshot := grokCredentialMutationSnapshot(latest) + if latestSnapshot.CredentialsJSON != snapshot.CredentialsJSON || + !grokCredentialProxyIDsEqual(latestSnapshot.ProxyID, snapshot.ProxyID) { + if token, ok := s.grokCredentialConcurrentlyRefreshedToken(ctx, accountID, snapshot); ok { + return token, nil + } + return "", errOAuthRefreshAccountStateChanged + } + + // A configured proxy is external to the account-row CAS identity. Recheck + // the hydrated proxy object so restoring a deleted row under the same ID + // wins over a stale proxy-invalid failure. + if class.reason == GrokCredentialReasonProxyInvalid { + if latest.ProxyID == nil || latest.Proxy != nil { + return "", errOAuthRefreshAccountStateChanged + } + } else if latest.ProxyID != nil && latest.Proxy == nil { + return "", errOAuthRefreshAccountStateChanged + } + + if class.reason == GrokCredentialReasonMissing { + expiresAt := latest.GetCredentialAsTime("expires_at") + credentialsStillMissing := strings.TrimSpace(latest.GetGrokAccessToken()) == "" || + strings.TrimSpace(latest.GetGrokRefreshToken()) == "" || expiresAt == nil || !time.Now().Before(*expiresAt) + if !credentialsStillMissing { + return "", errOAuthRefreshAccountStateChanged + } + } + return "", nil +} + +func (s *OpenAIGatewayService) grokCredentialMutationLock(accountID int64) *oauthRefreshLocalLock { + actual, _ := s.grokCredentialMutationLocks.LoadOrStore(accountID, newOAuthRefreshLocalLock()) + mu, ok := actual.(*oauthRefreshLocalLock) + if !ok { + mu = newOAuthRefreshLocalLock() + s.grokCredentialMutationLocks.Store(accountID, mu) + } + return mu +} + +func (s *OpenAIGatewayService) grokCredentialMutationCommitted(accountID int64, class grokCredentialFailureClass, until time.Time) bool { + if s == nil || s.accountRepo == nil || accountID <= 0 { + return false + } + confirmCtx, cancel := context.WithTimeout(context.Background(), grokCredentialMutationConfirmWait) + defer cancel() + latest, err := s.accountRepo.GetByID(confirmCtx, accountID) + if err != nil || latest == nil { + return false + } + if class.permanent { + return latest.Status == StatusError && !latest.Schedulable && latest.ErrorMessage == string(class.reason) + } + if class.transient { + return latest.TempUnschedulableUntil != nil && !latest.TempUnschedulableUntil.Before(until) && + latest.TempUnschedulableReason == string(class.reason) + } + return false +} + +func grokCredentialMutationSnapshot(account *Account) GrokCredentialMutationSnapshot { + if account == nil { + return GrokCredentialMutationSnapshot{} + } + credentialsJSON := "null" + if encoded, err := json.Marshal(account.Credentials); err == nil { + credentialsJSON = string(encoded) + } + snapshot := GrokCredentialMutationSnapshot{ + CredentialsJSON: credentialsJSON, + AccessToken: strings.TrimSpace(account.GetGrokAccessToken()), + RefreshToken: strings.TrimSpace(account.GetGrokRefreshToken()), + TokenVersion: account.GetCredentialAsInt64("_token_version"), + } + if account.ProxyID != nil { + proxyID := *account.ProxyID + snapshot.ProxyID = &proxyID + } + return snapshot +} + +func (s *OpenAIGatewayService) resolveGrokCredentialCASMiss(ctx context.Context, accountID int64, snapshot GrokCredentialMutationSnapshot) (string, error) { + if ctx.Err() != nil { + return "", ctx.Err() + } + if token, ok := s.grokCredentialConcurrentlyRefreshedToken(ctx, accountID, snapshot); ok { + return token, nil + } + return "", errOAuthRefreshAccountStateChanged +} + +func (s *OpenAIGatewayService) blockGrokCredentialRuntime(account *Account, until time.Time, reason string) func() { + if s == nil || account == nil { + return func() {} + } + mu := s.openAIAccountRuntimeBlockLock(account.ID) + mu.Lock() + before, hadBefore := s.openaiAccountRuntimeBlockUntil.Load(account.ID) + installedGeneration, changed := s.blockAccountSchedulingLocked(account, until, reason) + installed, installedOK := s.openaiAccountRuntimeBlockUntil.Load(account.ID) + installedUntil, isTime := installed.(time.Time) + mu.Unlock() + if !changed || !installedOK || !isTime { + return func() {} + } + if hadBefore { + if beforeUntil, ok := before.(time.Time); ok && beforeUntil.Equal(installedUntil) { + return func() {} + } + } + return func() { + mu.Lock() + defer mu.Unlock() + generation, ok := s.openaiAccountRuntimeBlockGeneration.Load(account.ID) + if !ok || generation != installedGeneration { + return + } + current, ok := s.openaiAccountRuntimeBlockUntil.Load(account.ID) + currentUntil, isTime := current.(time.Time) + if !ok || !isTime || !currentUntil.Equal(installedUntil) { + return + } + if hadBefore { + s.openaiAccountRuntimeBlockUntil.Store(account.ID, before) + s.openaiAccountRuntimeBlockGeneration.Store(account.ID, s.openaiAccountRuntimeBlockSequence.Add(1)) + return + } + s.openaiAccountRuntimeBlockUntil.Delete(account.ID) + s.openaiAccountRuntimeBlockGeneration.Store(account.ID, s.openaiAccountRuntimeBlockSequence.Add(1)) + } +} + +func (s *OpenAIGatewayService) grokCredentialConcurrentlyRefreshedToken(ctx context.Context, accountID int64, baseline GrokCredentialMutationSnapshot) (string, bool) { + if s == nil || s.accountRepo == nil || accountID <= 0 || ctx == nil || ctx.Err() != nil { + return "", false + } + checkCtx, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + latest, err := s.accountRepo.GetByID(checkCtx, accountID) + if err != nil || latest == nil { + return "", false + } + latestSnapshot := grokCredentialMutationSnapshot(latest) + if !grokCredentialProxyIDsEqual(latestSnapshot.ProxyID, baseline.ProxyID) || + latestSnapshot.CredentialsJSON == baseline.CredentialsJSON || !latest.IsSchedulable() || + (latest.ProxyID != nil && latest.Proxy == nil) || s.isOpenAIAccountRuntimeBlocked(latest) { + return "", false + } + latestToken := strings.TrimSpace(latest.GetGrokAccessToken()) + if latestToken == "" || strings.TrimSpace(latest.GetGrokRefreshToken()) == "" { + return "", false + } + expiresAt := latest.GetCredentialAsTime("expires_at") + if expiresAt == nil || !time.Now().Before(*expiresAt) { + return "", false + } + return latestToken, true +} + +func grokCredentialProxyIDsEqual(left, right *int64) bool { + if left == nil || right == nil { + return left == nil && right == nil + } + return *left == *right +} + +func (s *OpenAIGatewayService) newGrokCredentialFailover(c *gin.Context, account *Account, class grokCredentialFailureClass) error { + if strings.TrimSpace(class.message) == "" { + class.message = "Grok OAuth credentials are unavailable" + } + appendOpsUpstreamError(c, OpsUpstreamErrorEvent{ + Platform: PlatformGrok, + AccountID: account.ID, + Stage: string(GatewayFailureStageAccountAuth), + Scope: string(class.scope), + Reason: string(class.reason), + Kind: "credential_failover", + Message: class.message, + }) + return &UpstreamFailoverError{ + Stage: GatewayFailureStageAccountAuth, + Scope: class.scope, + Reason: class.reason, + NextAccountAction: class.action, + ClientStatusCode: http.StatusServiceUnavailable, + ClientMessage: GrokCredentialUnavailableClientMessage, + } +} diff --git a/backend/internal/service/grok_credential_failure_test.go b/backend/internal/service/grok_credential_failure_test.go new file mode 100644 index 0000000000..b493092927 --- /dev/null +++ b/backend/internal/service/grok_credential_failure_test.go @@ -0,0 +1,1623 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/pkg/xai" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type grokCredentialPersistingRepo struct { + *tokenRefreshAccountRepo +} + +func (r *grokCredentialPersistingRepo) SetError(ctx context.Context, id int64, message string) error { + if err := ctx.Err(); err != nil { + return err + } + if err := r.tokenRefreshAccountRepo.SetError(ctx, id, message); err != nil { + return err + } + if account := r.accountsByID[id]; account != nil { + account.Status = StatusError + account.Schedulable = false + account.ErrorMessage = message + } + return nil +} + +type grokCredentialProxyRepoStub struct { + ProxyRepository + proxy *Proxy + err error +} + +func (r *grokCredentialProxyRepoStub) GetByID(context.Context, int64) (*Proxy, error) { + return r.proxy, r.err +} + +type grokCredentialBlockingRepo struct { + *tokenRefreshAccountRepo + setErrorStarted chan struct{} + setTempStarted chan struct{} + onceError sync.Once + onceTemp sync.Once +} + +type grokCredentialCommitThenCancelRepo struct { + *tokenRefreshAccountRepo + returnErr error +} + +type grokCredentialUncommittedDeadlineRepo struct { + *tokenRefreshAccountRepo +} + +func (r *grokCredentialUncommittedDeadlineRepo) SetGrokCredentialErrorIfMatch( + context.Context, + int64, + GrokCredentialMutationSnapshot, + string, +) (bool, error) { + return false, context.DeadlineExceeded +} + +func (r *grokCredentialUncommittedDeadlineRepo) SetGrokCredentialTempUnschedulableIfMatch( + context.Context, + int64, + GrokCredentialMutationSnapshot, + time.Time, + string, +) (bool, error) { + return false, context.DeadlineExceeded +} + +func (r *grokCredentialCommitThenCancelRepo) SetGrokCredentialErrorIfMatch( + ctx context.Context, + id int64, + _ GrokCredentialMutationSnapshot, + reason string, +) (bool, error) { + account := r.accountsByID[id] + account.Status = StatusError + account.Schedulable = false + account.ErrorMessage = reason + if r.returnErr != nil { + return false, r.returnErr + } + <-ctx.Done() + return false, ctx.Err() +} + +func (r *grokCredentialCommitThenCancelRepo) SetGrokCredentialTempUnschedulableIfMatch( + ctx context.Context, + id int64, + _ GrokCredentialMutationSnapshot, + until time.Time, + reason string, +) (bool, error) { + account := r.accountsByID[id] + account.TempUnschedulableUntil = &until + account.TempUnschedulableReason = reason + if r.returnErr != nil { + return false, r.returnErr + } + <-ctx.Done() + return false, ctx.Err() +} + +func (r *grokCredentialBlockingRepo) SetError(ctx context.Context, _ int64, _ string) error { + r.onceError.Do(func() { close(r.setErrorStarted) }) + <-ctx.Done() + return ctx.Err() +} + +func (r *grokCredentialBlockingRepo) SetTempUnschedulable(ctx context.Context, _ int64, _ time.Time, _ string) error { + r.onceTemp.Do(func() { close(r.setTempStarted) }) + <-ctx.Done() + return ctx.Err() +} + +func (r *grokCredentialBlockingRepo) SetGrokCredentialErrorIfMatch( + ctx context.Context, + _ int64, + _ GrokCredentialMutationSnapshot, + _ string, +) (bool, error) { + r.onceError.Do(func() { close(r.setErrorStarted) }) + <-ctx.Done() + return false, ctx.Err() +} + +func (r *grokCredentialBlockingRepo) SetGrokCredentialTempUnschedulableIfMatch( + ctx context.Context, + _ int64, + _ GrokCredentialMutationSnapshot, + _ time.Time, + _ string, +) (bool, error) { + r.onceTemp.Do(func() { close(r.setTempStarted) }) + <-ctx.Done() + return false, ctx.Err() +} + +type grokCredentialBlockingCache struct { + GrokTokenCache + deleteStarted chan struct{} + releaseDelete chan struct{} + once sync.Once + mu sync.Mutex + deleted bool +} + +type grokCredentialSequencedRepo struct { + *tokenRefreshAccountRepo + mu sync.Mutex + latest *Account + getCall int +} + +type grokCredentialRereadFailureRepo struct { + *tokenRefreshAccountRepo + account *Account + err error +} + +type grokCredentialCountingRefresher struct { + refreshCalls int +} + +func (r *grokCredentialCountingRefresher) CacheKey(account *Account) string { + return GrokTokenCacheKey(account) +} + +func (r *grokCredentialCountingRefresher) CanRefresh(*Account) bool { return true } + +func (r *grokCredentialCountingRefresher) NeedsRefresh(*Account, time.Duration) bool { return true } + +func (r *grokCredentialCountingRefresher) Refresh(context.Context, *Account) (map[string]any, error) { + r.refreshCalls++ + return map[string]any{"access_token": "must-not-be-used"}, nil +} + +func (r *grokCredentialRereadFailureRepo) GetByID(context.Context, int64) (*Account, error) { + return r.account, r.err +} + +func (r *grokCredentialSequencedRepo) GetByID(ctx context.Context, id int64) (*Account, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.getCall++ + if r.getCall > 1 && r.latest != nil { + return r.latest, nil + } + return r.tokenRefreshAccountRepo.GetByID(ctx, id) +} + +func (c *grokCredentialBlockingCache) DeleteAccessToken(ctx context.Context, _ string) error { + c.once.Do(func() { close(c.deleteStarted) }) + select { + case <-c.releaseDelete: + c.mu.Lock() + c.deleted = true + c.mu.Unlock() + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func (c *grokCredentialBlockingCache) wasDeleted() bool { + c.mu.Lock() + defer c.mu.Unlock() + return c.deleted +} + +func TestUpstreamFailoverErrorNextAccountActionPreservesLegacyRetry(t *testing.T) { + t.Parallel() + + require.True(t, (&UpstreamFailoverError{}).ShouldRetryNextAccount()) + require.True(t, (&UpstreamFailoverError{NextAccountAction: NextAccountRetry}).ShouldRetryNextAccount()) + require.False(t, (&UpstreamFailoverError{NextAccountAction: NextAccountStop}).ShouldRetryNextAccount()) +} + +func TestGetRequestCredentialMapsPermanentGrokOAuthFailureAndRedactsSecrets(t *testing.T) { + gin.SetMode(gin.TestMode) + account := expiredGrokOAuthAccountForCredentialTest(701) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{ + err: infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_grant access_token=leaked-access refresh_token=leaked-refresh"), + }) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + token, kind, err := svc.getRequestCredential(context.Background(), c, account) + require.Error(t, err) + require.Empty(t, token) + require.Empty(t, kind) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureStageAccountAuth, failoverErr.Stage) + require.Equal(t, GatewayFailureScopeAccount, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonRevoked, failoverErr.Reason) + require.True(t, failoverErr.ShouldRetryNextAccount()) + require.Equal(t, 0, failoverErr.StatusCode) + require.Equal(t, http.StatusServiceUnavailable, failoverErr.ClientStatusCode) + require.NotContains(t, err.Error(), "leaked-access") + require.NotContains(t, err.Error(), "leaked-refresh") + + require.Equal(t, 1, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + require.Equal(t, []string{GrokTokenCacheKey(account)}, cache.deletedKeys) + require.NotContains(t, repo.lastErrorMessage, "leaked-access") + require.NotContains(t, repo.lastErrorMessage, "leaked-refresh") + + rawEvents, ok := c.Get(OpsUpstreamErrorsKey) + require.True(t, ok) + events, ok := rawEvents.([]*OpsUpstreamErrorEvent) + require.True(t, ok) + require.Len(t, events, 1) + require.Equal(t, string(GatewayFailureStageAccountAuth), events[0].Stage) + require.Equal(t, string(GatewayFailureScopeAccount), events[0].Scope) + require.Equal(t, string(GrokCredentialReasonRevoked), events[0].Reason) + require.Zero(t, events[0].UpstreamStatusCode) + require.NotContains(t, events[0].Message, "leaked-access") + require.NotContains(t, events[0].Message, "leaked-refresh") +} + +func TestGetRequestCredentialPermanentMappingsPersistAndInvalidate(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + prepare func(*Account) + refreshErr error + wantReason GatewayFailureReason + cachedToken string + }{ + { + name: "missing refresh credential", + prepare: func(account *Account) { + delete(account.Credentials, "refresh_token") + }, + wantReason: GrokCredentialReasonMissing, + }, + { + name: "missing access credential", + prepare: func(account *Account) { + delete(account.Credentials, "access_token") + account.Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + }, + wantReason: GrokCredentialReasonMissing, + cachedToken: "stale-cached-access", + }, + { + name: "explicit entitlement action required", + prepare: func(*Account) {}, + refreshErr: infraerrors.New(http.StatusForbidden, "GROK_OAUTH_ENTITLEMENT_DENIED", "access_denied"), + wantReason: GrokCredentialReasonEntitlement, + }, + } + + for index, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(720 + index)) + account.Status = StatusActive + account.Schedulable = true + tt.prepare(account) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialPersistingRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{lockResult: true, token: tt.cachedToken} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{err: tt.refreshErr}) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, tt.wantReason, failoverErr.Reason) + require.Equal(t, GatewayFailureScopeAccount, failoverErr.Scope) + require.Equal(t, 1, baseRepo.setErrorCalls) + require.Equal(t, StatusError, account.Status) + require.False(t, account.Schedulable) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + require.Equal(t, []string{GrokTokenCacheKey(account)}, cache.deletedKeys) + }) + } +} + +func TestGetRequestCredentialMissingAccessNeverRefreshesAndPermanentlyFailsOver(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + expiresAt *time.Time + }{ + {name: "expiry missing"}, + {name: "expired", expiresAt: func() *time.Time { value := time.Now().Add(-time.Minute); return &value }()}, + {name: "near expiry", expiresAt: func() *time.Time { value := time.Now().Add(30 * time.Minute); return &value }()}, + } + + for index, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(760 + index)) + account.Schedulable = true + delete(account.Credentials, "access_token") + if tt.expiresAt == nil { + delete(account.Credentials, "expires_at") + } else { + account.Credentials["expires_at"] = tt.expiresAt.UTC().Format(time.RFC3339) + } + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialPersistingRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{lockResult: true, token: "stale-cache-must-not-win"} + refresher := &grokCredentialCountingRefresher{} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), refresher) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + token, kind, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Empty(t, token) + require.Empty(t, kind) + require.Equal(t, GrokCredentialReasonMissing, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Zero(t, refresher.refreshCalls, "structurally missing access credentials must not reach the token endpoint") + require.Equal(t, 1, baseRepo.setErrorCalls) + require.Equal(t, StatusError, account.Status) + require.False(t, account.Schedulable) + require.Equal(t, []string{GrokTokenCacheKey(account)}, cache.deletedKeys) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + } +} + +func TestGetRequestCredentialWarmCachedAccessWithMissingRefreshPermanentlyFailsOver(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(764) + account.Credentials["access_token"] = "valid-access" + account.Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + delete(account.Credentials, "refresh_token") + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialPersistingRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{lockResult: true, token: "valid-access"} + refresher := &grokCredentialCountingRefresher{} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), refresher) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GrokCredentialReasonMissing, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Zero(t, refresher.refreshCalls) + require.Equal(t, 1, baseRepo.setErrorCalls) + require.Equal(t, []string{GrokTokenCacheKey(account)}, cache.deletedKeys) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestGetRequestCredentialMapsTransientAndProviderFailuresSeparately(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("account transient temporarily unschedules", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(702) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{err: errors.New("temporary refresh transport failure")}) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeAccount, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonRefreshTransient, failoverErr.Reason) + require.True(t, failoverErr.ShouldRetryNextAccount()) + require.Zero(t, repo.setErrorCalls) + require.Equal(t, 1, repo.setTempUnschedCalls) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + + t.Run("shared provider configuration stops without mutation", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(703) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + provider := NewGrokTokenProvider(repo, nil) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeProvider, failoverErr.Scope) + require.Equal(t, NextAccountStop, failoverErr.NextAccountAction) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + + t.Run("account reread failures preserve shared versus missing-row scope", func(t *testing.T) { + for _, tt := range []struct { + name string + account *Account + err error + }{ + {name: "repository error", err: errors.New("database temporarily unavailable")}, + {name: "missing row"}, + } { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(712) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialRereadFailureRepo{tokenRefreshAccountRepo: baseRepo, account: tt.account, err: tt.err} + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), NewGrokTokenRefresher(nil)) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + if tt.err != nil { + require.Equal(t, GatewayFailureScopeProvider, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonProviderDown, failoverErr.Reason) + require.Equal(t, NextAccountStop, failoverErr.NextAccountAction) + } else { + require.Equal(t, GatewayFailureScopeAccount, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonAccountChanged, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + } + require.Zero(t, baseRepo.setErrorCalls) + require.Zero(t, baseRepo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + } + }) + + t.Run("fresh account eligibility changes retry without mutating stale state", func(t *testing.T) { + for _, tt := range []struct { + name string + mutate func(*Account) + }{ + { + name: "account disabled", + mutate: func(account *Account) { + account.Status = StatusDisabled + }, + }, + { + name: "account converted", + mutate: func(account *Account) { + account.Type = AccountTypeUpstream + }, + }, + { + name: "account manually unschedulable", + mutate: func(account *Account) { + account.Schedulable = false + }, + }, + { + name: "account temporarily unschedulable", + mutate: func(account *Account) { + until := time.Now().Add(time.Minute) + account.TempUnschedulableUntil = &until + }, + }, + } { + t.Run(tt.name, func(t *testing.T) { + staleAccount := expiredGrokOAuthAccountForCredentialTest(713) + freshAccount := *staleAccount + freshAccount.Credentials = shallowCopyMap(staleAccount.Credentials) + tt.mutate(&freshAccount) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{staleAccount.ID: &freshAccount} + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), NewGrokTokenRefresher(nil)) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, staleAccount) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeAccount, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonAccountChanged, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(staleAccount)) + }) + } + }) + + t.Run("fresh missing refresh credential permanently blocks the account", func(t *testing.T) { + staleAccount := expiredGrokOAuthAccountForCredentialTest(714) + staleAccount.Schedulable = true + freshAccount := *staleAccount + freshAccount.Credentials = shallowCopyMap(staleAccount.Credentials) + delete(freshAccount.Credentials, "refresh_token") + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{staleAccount.ID: &freshAccount} + repo := &grokCredentialPersistingRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), NewGrokTokenRefresher(nil)) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, staleAccount) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeAccount, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonMissing, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Equal(t, 1, baseRepo.setErrorCalls) + require.Zero(t, baseRepo.setTempUnschedCalls) + require.Equal(t, StatusError, freshAccount.Status) + require.False(t, freshAccount.Schedulable) + require.Equal(t, []string{GrokTokenCacheKey(staleAccount)}, cache.deletedKeys) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(staleAccount)) + }) + + t.Run("refresh added after locked structural failure wins conditional mutation", func(t *testing.T) { + staleAccount := expiredGrokOAuthAccountForCredentialTest(717) + freshAccount := *staleAccount + freshAccount.Credentials = shallowCopyMap(staleAccount.Credentials) + delete(freshAccount.Credentials, "refresh_token") + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{staleAccount.ID: &freshAccount} + repo.beforeConditionalState = func() { + repaired := freshAccount + repaired.Credentials = shallowCopyMap(freshAccount.Credentials) + repaired.Credentials["refresh_token"] = "repaired-refresh-token" + repaired.Credentials["expires_at"] = time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + repo.accountsByID[staleAccount.ID] = &repaired + } + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), NewGrokTokenRefresher(nil)) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + token, kind, err := svc.getRequestCredential(context.Background(), c, staleAccount) + + require.NoError(t, err) + require.Equal(t, "expired-access-token", token) + require.Equal(t, "oauth", kind) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(staleAccount)) + }) + + t.Run("expiry-only repair wins full credential fingerprint CAS", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(718) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + repo.beforeConditionalState = func() { + repaired := *account + repaired.Credentials = shallowCopyMap(account.Credentials) + repaired.Credentials["expires_at"] = time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + repo.accountsByID[account.ID] = &repaired + } + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{ + err: infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_grant"), + }) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + token, kind, err := svc.getRequestCredential(context.Background(), c, account) + + require.NoError(t, err) + require.Equal(t, "expired-access-token", token) + require.Equal(t, "oauth", kind) + require.Zero(t, repo.setErrorCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + + t.Run("generic token endpoint 403 stops as shared provider failure", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(708) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{ + err: infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "token refresh failed: status 403, body: forbidden"), + }) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeProvider, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonProviderDown, failoverErr.Reason) + require.Equal(t, NextAccountStop, failoverErr.NextAccountAction) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + + t.Run("account proxy generic 403 remains bounded account transient", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(711) + proxyID := int64(43) + account.ProxyID = &proxyID + account.Proxy = &Proxy{} + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{ + err: infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "token refresh failed: status 403, body: forbidden"), + }) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeAccount, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonRefreshTransient, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Zero(t, repo.setErrorCalls) + require.Equal(t, 1, repo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + + t.Run("proxy repository read failure stops without account mutation", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(709) + proxyID := int64(41) + account.ProxyID = &proxyID + account.Proxy = &Proxy{} + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokTokenCacheForProviderTest{lockResult: true} + oauthSvc := NewGrokOAuthService(&grokCredentialProxyRepoStub{err: errors.New("database temporarily unavailable")}, &grokOAuthClientStub{}) + defer oauthSvc.Stop() + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), NewGrokTokenRefresher(oauthSvc)) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeProvider, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonProviderDown, failoverErr.Reason) + require.Equal(t, NextAccountStop, failoverErr.NextAccountAction) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + + t.Run("structurally missing configured proxy permanently blocks only that account", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(710) + account.Status = StatusActive + account.Schedulable = true + proxyID := int64(42) + account.ProxyID = &proxyID + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialPersistingRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{lockResult: true} + oauthSvc := NewGrokOAuthService(&grokCredentialProxyRepoStub{err: ErrProxyNotFound}, &grokOAuthClientStub{}) + defer oauthSvc.Stop() + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), NewGrokTokenRefresher(oauthSvc)) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeAccount, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonProxyInvalid, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Equal(t, 1, baseRepo.setErrorCalls) + require.Equal(t, StatusError, account.Status) + require.False(t, account.Schedulable) + require.Equal(t, []string{GrokTokenCacheKey(account)}, cache.deletedKeys) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) +} + +func TestGetRequestCredentialRuntimeBlockWinsBeforeWarmTokenCache(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(716) + account.Credentials["access_token"] = "valid-access" + account.Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokTokenCacheForProviderTest{token: "valid-access"} + provider := NewGrokTokenProvider(repo, cache) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + svc.BlockAccountScheduling(account, time.Now().Add(time.Minute), "independent") + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GrokCredentialReasonAccountChanged, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Zero(t, cache.getCalls) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) +} + +func TestGetRequestCredentialWarmCachedAccessWithMissingConfiguredProxyPermanentlyFailsOver(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(715) + account.Credentials["access_token"] = "valid-access" + account.Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + proxyID := int64(44) + account.ProxyID = &proxyID + account.Proxy = nil + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialPersistingRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{lockResult: true, token: "valid-access"} + refresher := &grokCredentialCountingRefresher{} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), refresher) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GrokCredentialReasonProxyInvalid, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Zero(t, refresher.refreshCalls) + require.Equal(t, 1, baseRepo.setErrorCalls) + require.Equal(t, []string{GrokTokenCacheKey(account)}, cache.deletedKeys) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestGetRequestCredentialCancellationAndBudgetDoNotMutateAccount(t *testing.T) { + gin.SetMode(gin.TestMode) + account := expiredGrokOAuthAccountForCredentialTest(704) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + provider := NewGrokTokenProvider(repo, nil) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + + t.Run("parent cancellation is returned directly", func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(ctx, c, account) + require.ErrorIs(t, err, context.Canceled) + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr)) + }) + + t.Run("request credential budget stops safely", func(t *testing.T) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Set(grokCredentialFailoverDeadlineKey, time.Now().Add(-time.Second)) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeRequest, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonFailoverTimeout, failoverErr.Reason) + require.False(t, failoverErr.ShouldRetryNextAccount()) + }) + + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestGetRequestCredentialStateMutationFailureStopsAndKeepsRuntimeBlock(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + refreshErr error + configure func(*tokenRefreshAccountRepo, *grokTokenCacheForProviderTest) + wantSetError int + wantSetTemp int + wantCacheDelete int + }{ + { + name: "permanent state persistence", + refreshErr: infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_grant"), + configure: func(repo *tokenRefreshAccountRepo, _ *grokTokenCacheForProviderTest) { + repo.setErrorErr = errors.New("database write failed") + }, + wantSetError: 1, + }, + { + name: "transient state persistence", + refreshErr: errors.New("temporary refresh transport failure"), + configure: func(repo *tokenRefreshAccountRepo, _ *grokTokenCacheForProviderTest) { + repo.setTempUnschedErr = errors.New("database write failed") + }, + wantSetTemp: 1, + }, + { + name: "permanent token cache invalidation", + refreshErr: infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_grant"), + configure: func(_ *tokenRefreshAccountRepo, cache *grokTokenCacheForProviderTest) { + cache.deleteErr = errors.New("cache delete failed") + }, + wantSetError: 1, + wantCacheDelete: 1, + }, + } + + for index, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(740 + index)) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokTokenCacheForProviderTest{lockResult: true} + tt.configure(repo, cache) + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{err: tt.refreshErr}) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeProvider, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonStateUpdate, failoverErr.Reason) + require.Equal(t, NextAccountStop, failoverErr.NextAccountAction) + require.Equal(t, tt.wantSetError, repo.setErrorCalls) + require.Equal(t, tt.wantSetTemp, repo.setTempUnschedCalls) + require.Len(t, cache.deletedKeys, tt.wantCacheDelete) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account), "failed mutation must retain the immediate local block") + }) + } +} + +func TestGrokCredentialMutationBoundariesHonorParentCancellation(t *testing.T) { + t.Run("blocked SetError cancellation prevents cache and runtime mutation", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(730) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialBlockingRepo{ + tokenRefreshAccountRepo: baseRepo, + setErrorStarted: make(chan struct{}), + setTempStarted: make(chan struct{}), + } + cache := &grokTokenCacheForProviderTest{} + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: NewGrokTokenProvider(repo, cache)} + ctx, cancel := context.WithCancel(context.Background()) + result := make(chan error, 1) + go func() { + _, err := svc.applyGrokCredentialAccountFailure(ctx, account, grokCredentialFailureClass{ + reason: GrokCredentialReasonRevoked, permanent: true, + }) + result <- err + }() + <-repo.setErrorStarted + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account), "runtime block must precede persistent SetError") + cancel() + + require.ErrorIs(t, <-result, context.Canceled) + require.Zero(t, baseRepo.setErrorCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + + t.Run("blocked temporary unschedule cancellation prevents runtime mutation", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(731) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialBlockingRepo{ + tokenRefreshAccountRepo: baseRepo, + setErrorStarted: make(chan struct{}), + setTempStarted: make(chan struct{}), + } + svc := &OpenAIGatewayService{accountRepo: repo} + ctx, cancel := context.WithCancel(context.Background()) + result := make(chan error, 1) + go func() { + _, err := svc.applyGrokCredentialAccountFailure(ctx, account, grokCredentialFailureClass{ + reason: GrokCredentialReasonRefreshTransient, transient: true, + }) + result <- err + }() + <-repo.setTempStarted + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account), "runtime block must precede temporary unscheduling") + cancel() + + require.ErrorIs(t, <-result, context.Canceled) + require.Zero(t, baseRepo.setTempUnschedCalls) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + + t.Run("post-commit cancellation finishes cache cleanup and retains quarantine", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(732) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokCredentialBlockingCache{deleteStarted: make(chan struct{}), releaseDelete: make(chan struct{})} + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: NewGrokTokenProvider(repo, cache)} + ctx, cancel := context.WithCancel(context.Background()) + result := make(chan error, 1) + go func() { + _, err := svc.applyGrokCredentialAccountFailure(ctx, account, grokCredentialFailureClass{ + reason: GrokCredentialReasonRevoked, permanent: true, + }) + result <- err + }() + <-cache.deleteStarted + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account), "runtime block must precede cache invalidation") + cancel() + close(cache.releaseDelete) + + require.ErrorIs(t, <-result, context.Canceled) + require.Equal(t, 1, repo.setErrorCalls) + require.True(t, cache.wasDeleted()) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) +} + +func TestGrokCredentialMutationLockWaitHonorsCredentialBudget(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(735) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: NewGrokTokenProvider(repo, &grokTokenCacheForProviderTest{})} + mutationLock := svc.grokCredentialMutationLock(account.ID) + require.NoError(t, mutationLock.Lock(context.Background())) + defer mutationLock.Unlock() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) + defer cancel() + + startedAt := time.Now() + token, err := svc.applyGrokCredentialAccountFailure(ctx, account, grokCredentialFailureClass{ + reason: GrokCredentialReasonRevoked, permanent: true, + }) + + require.ErrorIs(t, err, context.DeadlineExceeded) + require.Empty(t, token) + require.Less(t, time.Since(startedAt), 500*time.Millisecond) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestGetRequestCredentialBudgetBoundsBlockedConditionalMutation(t *testing.T) { + gin.SetMode(gin.TestMode) + account := expiredGrokOAuthAccountForCredentialTest(736) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialBlockingRepo{ + tokenRefreshAccountRepo: baseRepo, + setErrorStarted: make(chan struct{}), + setTempStarted: make(chan struct{}), + } + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{ + err: infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_grant"), + }) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Set(grokCredentialFailoverDeadlineKey, time.Now().Add(40*time.Millisecond)) + + startedAt := time.Now() + token, kind, err := svc.getRequestCredential(context.Background(), c, account) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeRequest, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonFailoverTimeout, failoverErr.Reason) + require.Equal(t, NextAccountStop, failoverErr.NextAccountAction) + require.Empty(t, token) + require.Empty(t, kind) + require.Less(t, time.Since(startedAt), 500*time.Millisecond) + require.Zero(t, baseRepo.setErrorCalls) + require.Zero(t, baseRepo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestGetRequestCredentialLockHeldTimeoutDoesNotQuarantineAccount(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + buildRepo func(*Account) AccountRepository + wantScope GatewayFailureScope + wantReason GatewayFailureReason + wantAction NextAccountAction + }{ + { + name: "authoritative row unchanged", + buildRepo: func(account *Account) AccountRepository { + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + return repo + }, + wantScope: GatewayFailureScopeAccount, + wantReason: GrokCredentialReasonAccountChanged, + wantAction: NextAccountRetry, + }, + { + name: "selected account was deleted", + buildRepo: func(account *Account) AccountRepository { + base := &tokenRefreshAccountRepo{} + base.accountsByID = map[int64]*Account{account.ID: account} + return &grokCredentialRereadFailureRepo{tokenRefreshAccountRepo: base} + }, + wantScope: GatewayFailureScopeAccount, + wantReason: GrokCredentialReasonAccountChanged, + wantAction: NextAccountRetry, + }, + { + name: "shared account store unavailable", + buildRepo: func(account *Account) AccountRepository { + base := &tokenRefreshAccountRepo{} + base.accountsByID = map[int64]*Account{account.ID: account} + return &grokCredentialRereadFailureRepo{tokenRefreshAccountRepo: base, err: errors.New("database unavailable")} + }, + wantScope: GatewayFailureScopeProvider, + wantReason: GrokCredentialReasonProviderDown, + wantAction: NextAccountStop, + }, + } + + for index, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(7400 + index)) + repo := tt.buildRepo(account) + cache := &grokTokenCacheForProviderTest{lockResult: false} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{}) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + startedAt := time.Now() + _, _, err := svc.getRequestCredential(context.Background(), c, account) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, tt.wantScope, failoverErr.Scope) + require.Equal(t, tt.wantReason, failoverErr.Reason) + require.Equal(t, tt.wantAction, failoverErr.NextAccountAction) + require.Less(t, time.Since(startedAt), 3*time.Second) + switch countingRepo := repo.(type) { + case *tokenRefreshAccountRepo: + require.Zero(t, countingRepo.setErrorCalls) + require.Zero(t, countingRepo.setTempUnschedCalls) + case *grokCredentialRereadFailureRepo: + require.Zero(t, countingRepo.tokenRefreshAccountRepo.setErrorCalls) + require.Zero(t, countingRepo.tokenRefreshAccountRepo.setTempUnschedCalls) + } + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + } +} + +func TestGrokCredentialMutationCancellationAmbiguityConfirmsDurableCommit(t *testing.T) { + tests := []struct { + name string + class grokCredentialFailureClass + committed func(*Account) bool + }{ + { + name: "permanent quarantine", + class: grokCredentialFailureClass{reason: GrokCredentialReasonRevoked, permanent: true}, + committed: func(account *Account) bool { + return account.Status == StatusError && !account.Schedulable && account.ErrorMessage == string(GrokCredentialReasonRevoked) + }, + }, + { + name: "temporary quarantine", + class: grokCredentialFailureClass{reason: GrokCredentialReasonRefreshTransient, transient: true}, + committed: func(account *Account) bool { + return account.TempUnschedulableUntil != nil && account.TempUnschedulableReason == string(GrokCredentialReasonRefreshTransient) + }, + }, + } + + for index, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(737 + index)) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialCommitThenCancelRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{} + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: NewGrokTokenProvider(repo, cache)} + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) + defer cancel() + + token, err := svc.applyGrokCredentialAccountFailure(ctx, account, tt.class) + + require.ErrorIs(t, err, context.DeadlineExceeded) + require.Empty(t, token) + require.True(t, tt.committed(account), "the detached confirmation must recognize the durable mutation") + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account), "a confirmed durable quarantine must retain its runtime block") + if tt.class.permanent { + require.Equal(t, []string{GrokTokenCacheKey(account)}, cache.deletedKeys) + } else { + require.Empty(t, cache.deletedKeys) + } + }) + } +} + +func TestGrokCredentialInnerStateDeadlineAmbiguityConfirmsDurableCommit(t *testing.T) { + tests := []struct { + name string + class grokCredentialFailureClass + }{ + {name: "permanent quarantine", class: grokCredentialFailureClass{reason: GrokCredentialReasonRevoked, permanent: true}}, + {name: "temporary quarantine", class: grokCredentialFailureClass{reason: GrokCredentialReasonRefreshTransient, transient: true}}, + } + + for index, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(7500 + index)) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialCommitThenCancelRepo{ + tokenRefreshAccountRepo: baseRepo, + returnErr: context.DeadlineExceeded, + } + cache := &grokTokenCacheForProviderTest{} + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: NewGrokTokenProvider(repo, cache)} + + token, err := svc.applyGrokCredentialAccountFailure(context.Background(), account, tt.class) + + require.NoError(t, err, "the detached readback must resolve the inner timeout's commit ambiguity") + require.Empty(t, token) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + if tt.class.permanent { + require.Equal(t, StatusError, account.Status) + require.False(t, account.Schedulable) + require.Equal(t, []string{GrokTokenCacheKey(account)}, cache.deletedKeys) + } else { + require.NotNil(t, account.TempUnschedulableUntil) + require.Equal(t, string(GrokCredentialReasonRefreshTransient), account.TempUnschedulableReason) + require.Empty(t, cache.deletedKeys) + } + }) + } +} + +func TestGrokCredentialUnconfirmedInnerStateDeadlineStopsAndRetainsSafetyBlock(t *testing.T) { + tests := []struct { + name string + class grokCredentialFailureClass + }{ + {name: "permanent quarantine", class: grokCredentialFailureClass{reason: GrokCredentialReasonRevoked, permanent: true}}, + {name: "temporary quarantine", class: grokCredentialFailureClass{reason: GrokCredentialReasonRefreshTransient, transient: true}}, + } + + for index, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(7600 + index)) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialUncommittedDeadlineRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{} + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: NewGrokTokenProvider(repo, cache)} + + token, err := svc.applyGrokCredentialAccountFailure(context.Background(), account, tt.class) + + require.ErrorIs(t, err, errGrokCredentialStateUpdateFailed) + require.Empty(t, token) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account), "an unknown commit outcome must retain the local safety block") + require.Equal(t, StatusActive, account.Status) + require.True(t, account.Schedulable) + require.Nil(t, account.TempUnschedulableUntil) + require.Empty(t, cache.deletedKeys) + }) + } +} + +func TestGrokCredentialRuntimeRollbackOwnership(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(734) + t.Run("later extending block survives", func(t *testing.T) { + svc := &OpenAIGatewayService{} + until := time.Now().Add(time.Minute) + rollbackFirst := svc.blockGrokCredentialRuntime(account, until, "first") + + secondInstalled := make(chan struct{}) + go func() { + svc.BlockAccountScheduling(account, until.Add(time.Minute), "independent") + close(secondInstalled) + }() + <-secondInstalled + rollbackFirst() + + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account), + "rollback owned by the first invocation must not remove a later extending block") + }) + + t.Run("independent shorter block steals rollback ownership", func(t *testing.T) { + svc := &OpenAIGatewayService{} + until := time.Now().Add(2 * time.Minute) + rollbackFirst := svc.blockGrokCredentialRuntime(account, until, "first") + svc.BlockAccountScheduling(account, until.Add(-time.Minute), "shorter-no-op") + + rollbackFirst() + + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + + t.Run("serialized tentative rollbacks leave no block", func(t *testing.T) { + svc := &OpenAIGatewayService{} + for i := 0; i < 2; i++ { + mu := svc.grokCredentialMutationLock(account.ID) + require.NoError(t, mu.Lock(context.Background())) + rollback := svc.blockGrokCredentialRuntime(account, time.Now().Add(time.Minute), "tentative") + rollback() + mu.Unlock() + } + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) +} + +func TestGetRequestCredentialAPIKeyBypassesOAuthFailureMapping(t *testing.T) { + gin.SetMode(gin.TestMode) + account := &Account{ + ID: 705, + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "third-party-key", + "base_url": "https://grok.example.test/v1", + }, + } + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + svc := &OpenAIGatewayService{} + + token, kind, err := svc.getRequestCredential(context.Background(), c, account) + require.NoError(t, err) + require.Equal(t, "third-party-key", token) + require.Equal(t, "apikey", kind) + _, hasEvents := c.Get(OpsUpstreamErrorsKey) + require.False(t, hasEvents) +} + +func TestPermanentCredentialFailureDoesNotDisableConcurrentlyRefreshedAccount(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(707) + latest := *account + latest.Credentials = shallowCopyMap(account.Credentials) + latest.Credentials["access_token"] = "fresh-access-token" + latest.Credentials["refresh_token"] = "rotated-refresh-token" + latest.Credentials["expires_at"] = time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + latest.Credentials["_token_version"] = time.Now().UnixMilli() + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: &latest} + cache := &grokTokenCacheForProviderTest{} + svc := &OpenAIGatewayService{ + accountRepo: repo, + grokTokenProvider: NewGrokTokenProvider(repo, cache), + } + + _, mutationErr := svc.applyGrokCredentialAccountFailure(context.Background(), account, grokCredentialFailureClass{ + scope: GatewayFailureScopeAccount, + reason: GrokCredentialReasonRevoked, + action: NextAccountRetry, + permanent: true, + }) + + require.NoError(t, mutationErr) + require.Zero(t, repo.setErrorCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestCredentialFailureConditionalMutationLosesToConcurrentRefresh(t *testing.T) { + for index, tt := range []struct { + name string + refreshErr error + }{ + {name: "permanent", refreshErr: infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_grant")}, + {name: "transient", refreshErr: errors.New("temporary refresh transport failure")}, + } { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(770 + index)) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + repo.beforeConditionalState = func() { + fresh := *account + fresh.Credentials = shallowCopyMap(account.Credentials) + fresh.Credentials["access_token"] = "refresh-won-token" + fresh.Credentials["refresh_token"] = "refresh-won-refresh" + fresh.Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + fresh.Credentials["_token_version"] = time.Now().UnixMilli() + repo.accountsByID[account.ID] = &fresh + } + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{err: tt.refreshErr}) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + token, kind, err := svc.getRequestCredential(context.Background(), c, account) + + require.NoError(t, err) + require.Equal(t, "refresh-won-token", token) + require.Equal(t, "oauth", kind) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + } +} + +func TestCredentialFailureConditionalMutationLosesToConcurrentProxyRepair(t *testing.T) { + for index, tt := range []struct { + name string + refreshErr error + }{ + {name: "permanent", refreshErr: infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_grant")}, + {name: "transient", refreshErr: errors.New("temporary refresh transport failure")}, + } { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(780 + index)) + oldProxyID := int64(10) + account.ProxyID = &oldProxyID + account.Proxy = &Proxy{} + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + repo.beforeConditionalState = func() { + fresh := *account + fresh.Credentials = shallowCopyMap(account.Credentials) + repairedProxyID := int64(11) + fresh.ProxyID = &repairedProxyID + repo.accountsByID[account.ID] = &fresh + } + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{err: tt.refreshErr}) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GrokCredentialReasonAccountChanged, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + } +} + +func TestCredentialFailureConditionalMutationLosesToSameIDProxyRestoration(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(790) + proxyID := int64(10) + account.ProxyID = &proxyID + account.Proxy = nil + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + repo.beforeConditionalState = func() { + account.Proxy = &Proxy{ID: proxyID} + } + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GrokCredentialReasonAccountChanged, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestCredentialFailureConditionalMutationLosesToConcurrentUnschedulableState(t *testing.T) { + future := time.Now().Add(time.Hour) + states := []struct { + name string + mutate func(*Account) + }{ + {name: "admin schedulable false", mutate: func(account *Account) { account.Schedulable = false }}, + {name: "temporary cooldown", mutate: func(account *Account) { account.TempUnschedulableUntil = &future }}, + {name: "rate limit cooldown", mutate: func(account *Account) { account.RateLimitResetAt = &future }}, + {name: "overload cooldown", mutate: func(account *Account) { account.OverloadUntil = &future }}, + } + classes := []struct { + name string + class grokCredentialFailureClass + }{ + {name: "permanent", class: grokCredentialFailureClass{reason: GrokCredentialReasonRevoked, permanent: true}}, + {name: "transient", class: grokCredentialFailureClass{reason: GrokCredentialReasonRefreshTransient, transient: true}}, + } + + for classIndex, classCase := range classes { + for stateIndex, stateCase := range states { + t.Run(classCase.name+"/"+stateCase.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(791 + classIndex*10 + stateIndex)) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + repo.beforeConditionalState = func() { stateCase.mutate(account) } + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: NewGrokTokenProvider(repo, &grokTokenCacheForProviderTest{})} + + token, err := svc.applyGrokCredentialAccountFailure(context.Background(), account, classCase.class) + + require.ErrorIs(t, err, errOAuthRefreshAccountStateChanged) + require.Empty(t, token) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + } + } +} + +func TestCredentialFailureCASMissDoesNotRecoverIneligibleLatestCredential(t *testing.T) { + future := time.Now().Add(time.Hour) + states := []struct { + name string + mutate func(*OpenAIGatewayService, *Account) + wantRuntimeBlocked bool + }{ + {name: "disabled", mutate: func(_ *OpenAIGatewayService, account *Account) { account.Status = StatusDisabled }}, + {name: "not schedulable", mutate: func(_ *OpenAIGatewayService, account *Account) { account.Schedulable = false }}, + {name: "temporarily unschedulable", mutate: func(_ *OpenAIGatewayService, account *Account) { account.TempUnschedulableUntil = &future }}, + {name: "rate limited", mutate: func(_ *OpenAIGatewayService, account *Account) { account.RateLimitResetAt = &future }}, + {name: "overloaded", mutate: func(_ *OpenAIGatewayService, account *Account) { account.OverloadUntil = &future }}, + { + name: "independently runtime blocked", + mutate: func(svc *OpenAIGatewayService, account *Account) { + svc.BlockAccountScheduling(account, time.Now().Add(24*time.Hour), "independent") + }, + wantRuntimeBlocked: true, + }, + } + classes := []struct { + name string + class grokCredentialFailureClass + }{ + {name: "permanent", class: grokCredentialFailureClass{reason: GrokCredentialReasonRevoked, permanent: true}}, + {name: "transient", class: grokCredentialFailureClass{reason: GrokCredentialReasonRefreshTransient, transient: true}}, + } + + for classIndex, classCase := range classes { + for stateIndex, stateCase := range states { + t.Run(classCase.name+"/"+stateCase.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(800 + classIndex*20 + stateIndex)) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: NewGrokTokenProvider(repo, &grokTokenCacheForProviderTest{})} + repo.beforeConditionalState = func() { + latest := *account + latest.Credentials = shallowCopyMap(account.Credentials) + latest.Credentials["access_token"] = "fresh-but-ineligible-token" + latest.Credentials["refresh_token"] = "fresh-but-ineligible-refresh" + latest.Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + latest.Credentials["_token_version"] = time.Now().UnixMilli() + stateCase.mutate(svc, &latest) + repo.accountsByID[account.ID] = &latest + } + + token, err := svc.applyGrokCredentialAccountFailure(context.Background(), account, classCase.class) + + require.ErrorIs(t, err, errOAuthRefreshAccountStateChanged) + require.Empty(t, token) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Equal(t, stateCase.wantRuntimeBlocked, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + } + } +} + +func TestGetRequestCredentialSharedCredentialPersistenceFailureStopsWithoutAccountMutation(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(782) + repo := &tokenRefreshAccountRepo{conditionalSuccessErr: errors.New("database unavailable")} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{credentials: map[string]any{ + "access_token": "new-access-token", + "refresh_token": "new-refresh-token", + "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), + }}) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeProvider, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonProviderDown, failoverErr.Reason) + require.Equal(t, NextAccountStop, failoverErr.NextAccountAction) + require.Equal(t, 1, repo.conditionalSuccessCalls) + require.Zero(t, repo.updateCredentialsCalls) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestGetRequestCredentialRecoversConcurrentRefreshWithoutFailover(t *testing.T) { + gin.SetMode(gin.TestMode) + account := expiredGrokOAuthAccountForCredentialTest(733) + latest := *account + latest.Credentials = shallowCopyMap(account.Credentials) + latest.Credentials["access_token"] = "fresh-concurrent-access" + latest.Credentials["refresh_token"] = "fresh-concurrent-refresh" + latest.Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + latest.Credentials["_token_version"] = time.Now().UnixMilli() + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialSequencedRepo{tokenRefreshAccountRepo: baseRepo, latest: &latest} + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{ + err: infraerrors.New(http.StatusForbidden, "GROK_OAUTH_ENTITLEMENT_DENIED", "access_denied"), + }) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + token, kind, err := svc.getRequestCredential(context.Background(), c, account) + + require.NoError(t, err) + require.Equal(t, "fresh-concurrent-access", token) + require.Equal(t, "oauth", kind) + require.Zero(t, baseRepo.setErrorCalls) + require.Zero(t, baseRepo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + _, hasEvents := c.Get(OpsUpstreamErrorsKey) + require.False(t, hasEvents) +} + +func expiredGrokOAuthAccountForCredentialTest(id int64) *Account { + return &Account{ + ID: id, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{ + "access_token": "expired-access-token", + "refresh_token": "refresh-token", + "expires_at": time.Now().Add(-time.Minute).UTC().Format(time.RFC3339), + "base_url": xai.DefaultCLIBaseURL, + }, + } +} diff --git a/backend/internal/service/grok_media.go b/backend/internal/service/grok_media.go index 100d720659..f7c6bd8153 100644 --- a/backend/internal/service/grok_media.go +++ b/backend/internal/service/grok_media.go @@ -13,7 +13,6 @@ import ( "strings" "time" - "github.com/Wei-Shaw/sub2api/internal/pkg/xai" "github.com/Wei-Shaw/sub2api/internal/util/responseheaders" "github.com/gin-gonic/gin" "github.com/tidwall/gjson" @@ -268,25 +267,6 @@ func (s *OpenAIGatewayService) BindGrokMediaVideoRequestAccount(ctx context.Cont return s.BindStickySession(ctx, groupID, GrokMediaVideoRequestSessionHash(requestID), accountID) } -func (e GrokMediaEndpoint) upstreamURL(baseURL, requestID string) (string, error) { - switch e { - case GrokMediaEndpointImagesGenerations: - return xai.BuildImagesGenerationsURL(baseURL) - case GrokMediaEndpointImagesEdits: - return xai.BuildImagesEditsURL(baseURL) - case GrokMediaEndpointVideosGenerations: - return xai.BuildVideosGenerationsURL(baseURL) - case GrokMediaEndpointVideosEdits: - return xai.BuildVideosEditsURL(baseURL) - case GrokMediaEndpointVideosExtensions: - return xai.BuildVideosExtensionsURL(baseURL) - case GrokMediaEndpointVideoStatus: - return xai.BuildVideoURL(baseURL, requestID) - default: - return "", fmt.Errorf("unsupported grok media endpoint: %s", e) - } -} - func (s *OpenAIGatewayService) ForwardGrokMedia( ctx context.Context, c *gin.Context, @@ -304,11 +284,11 @@ func (s *OpenAIGatewayService) ForwardGrokMedia( return nil, fmt.Errorf("account platform %s is not supported for grok media", account.Platform) } - token, _, err := s.GetAccessToken(ctx, account) + token, _, err := s.getRequestCredential(ctx, c, account) if err != nil { return nil, err } - targetURL, err := endpoint.upstreamURL(account.GetGrokMediaBaseURL(), requestID) + targetURL, err := buildGrokMediaURL(account, s.cfg, endpoint, requestID) if err != nil { return nil, err } @@ -339,7 +319,9 @@ func (s *OpenAIGatewayService) ForwardGrokMedia( } upstreamReq.Header.Set("Authorization", "Bearer "+token) upstreamReq.Header.Set("Accept", "application/json") - applyGrokCLIHeaders(upstreamReq.Header) + if account.IsGrokOAuth() { + applyGrokCLIHeaders(upstreamReq.Header) + } if endpoint.RequiresRequestBody() { contentType = strings.TrimSpace(contentType) if contentType == "" { @@ -366,7 +348,7 @@ func (s *OpenAIGatewayService) ForwardGrokMedia( return s.handleGrokMediaErrorResponse(ctx, resp, c, account, requestIDHeader, requestModel) } - s.updateGrokUsageSnapshot(ctx, account, xai.ParseQuotaHeaders(resp.Header, resp.StatusCode)) + s.updateGrokUsageFromResponse(ctx, account, resp.Header, resp.StatusCode) respBody, err := ReadUpstreamResponseBody(resp.Body, s.cfg, c, openAITooLargeError) if err != nil { return nil, err @@ -635,6 +617,7 @@ func (s *OpenAIGatewayService) handleGrokMediaErrorResponse( return nil, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: body, + ResponseHeaders: resp.Header.Clone(), RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode), } } diff --git a/backend/internal/service/grok_oauth_reconciliation.go b/backend/internal/service/grok_oauth_reconciliation.go new file mode 100644 index 0000000000..ca7611191f --- /dev/null +++ b/backend/internal/service/grok_oauth_reconciliation.go @@ -0,0 +1,345 @@ +package service + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +const ( + defaultGrokOAuthReconcilePageSize = 50 + maxGrokOAuthReconcilePageSize = 500 + maxGrokOAuthReconcileWindow = 24 * time.Hour + + GrokOAuthReconcileReasonMissingRefreshToken = "missing_refresh_token" + GrokOAuthReconcileReasonMissingAccessToken = "missing_access_token" + GrokOAuthReconcileReasonMissingExpiry = "missing_expiry" + GrokOAuthReconcileReasonInvalidExpiry = "invalid_expiry" + GrokOAuthReconcileReasonNearExpiry = "near_expiry" + GrokOAuthReconcileReasonCredentialRejected = "credential_rejected" + + GrokOAuthReconcileActionBlock = "block_account" + GrokOAuthReconcileActionRefresh = "refresh_credentials" + + GrokOAuthReconcileOutcomePlanned = "planned" + GrokOAuthReconcileOutcomeApplied = "applied" + GrokOAuthReconcileOutcomeSkipped = "skipped" + GrokOAuthReconcileOutcomeFailed = "failed" + GrokOAuthReconcileOutcomePartial = "partial" +) + +var ( + ErrGrokOAuthReconcileMode = infraerrors.BadRequest( + "GROK_OAUTH_RECONCILE_MODE_INVALID", + "apply requires dry_run=false and apply=true", + ) + ErrGrokOAuthReconcileCursor = infraerrors.BadRequest( + "GROK_OAUTH_RECONCILE_CURSOR_INVALID", + "after_id must be non-negative", + ) + ErrGrokOAuthReconcileLimit = infraerrors.BadRequest( + "GROK_OAUTH_RECONCILE_LIMIT_INVALID", + "limit is outside the allowed reconciliation page range", + ) + ErrGrokOAuthReconcileWindow = infraerrors.BadRequest( + "GROK_OAUTH_RECONCILE_WINDOW_INVALID", + "refresh_window_seconds is outside the allowed range", + ) +) + +// GrokOAuthReconciler is the narrow admin-facing reconciliation port. +type GrokOAuthReconciler interface { + ReconcileGrokOAuth(ctx context.Context, input GrokOAuthReconcileInput) (*GrokOAuthReconcileResult, error) +} + +// GrokOAuthConditionalErrorRepository is the narrow compare-and-set mutation +// used by reconciliation. The repository must only transition an active Grok +// OAuth account when its credential document still exactly matches the state +// observed immediately before the mutation. +type GrokOAuthConditionalErrorRepository interface { + SetGrokOAuthErrorIfCredentialsUnchanged(ctx context.Context, id int64, expectedCredentials map[string]any, errorMsg string) (bool, error) +} + +type GrokOAuthReconcileInput struct { + DryRun bool + Apply bool + AfterID int64 + Limit int + RefreshWindow time.Duration +} + +// GrokOAuthReconcileItem is deliberately metadata-only. Credentials, account +// identity fields, provider response bodies, and raw errors never cross this API. +type GrokOAuthReconcileItem struct { + AccountID int64 `json:"account_id"` + Reason string `json:"reason"` + Action string `json:"action"` + Outcome string `json:"outcome"` +} + +type GrokOAuthReconcileResult struct { + DryRun bool `json:"dry_run"` + Scanned int `json:"scanned"` + Actionable int `json:"actionable"` + WouldBlock int `json:"would_block"` + WouldRefresh int `json:"would_refresh"` + Blocked int `json:"blocked"` + Refreshed int `json:"refreshed"` + Skipped int `json:"skipped"` + Failed int `json:"failed"` + Partial int `json:"partial"` + Items []GrokOAuthReconcileItem `json:"items"` + NextAfterID int64 `json:"next_after_id"` + HasMore bool `json:"has_more"` +} + +func (s *TokenRefreshService) ReconcileGrokOAuth(ctx context.Context, input GrokOAuthReconcileInput) (*GrokOAuthReconcileResult, error) { + if ctx == nil { + ctx = context.Background() + } + if input.Apply && input.DryRun { + return nil, ErrGrokOAuthReconcileMode + } + if input.AfterID < 0 { + return nil, ErrGrokOAuthReconcileCursor + } + limit := input.Limit + maxPageSize := s.grokOAuthReconcileMaxPageSize() + if limit == 0 { + limit = min(defaultGrokOAuthReconcilePageSize, maxPageSize) + } + if limit < 1 || limit > maxPageSize { + return nil, ErrGrokOAuthReconcileLimit + } + refreshWindow := input.RefreshWindow + if refreshWindow == 0 { + refreshWindow = grokTokenRefreshSkew + } + if refreshWindow < 0 || refreshWindow > maxGrokOAuthReconcileWindow { + return nil, ErrGrokOAuthReconcileWindow + } + if refreshWindow < grokTokenRefreshSkew { + refreshWindow = grokTokenRefreshSkew + } + dryRun := !input.Apply + + pager := s.candidatePager + if pager == nil { + pager, _ = s.accountRepo.(OAuthRefreshCandidatePager) + } + if pager == nil { + return nil, errors.New("OAuth refresh candidate pager is not configured") + } + page, err := pager.ListOAuthRefreshCandidatePage(ctx, OAuthRefreshPageOptions{ + Platforms: []string{PlatformGrok}, + AfterID: input.AfterID, + Limit: limit, + ActiveOnly: true, + // Reconciliation scans OAuth only and intentionally does not require a + // refresh token so structurally invalid rows remain discoverable. + IncludeSetupToken: false, + RequireRefreshToken: false, + }) + if err != nil { + return nil, err + } + if page == nil { + return nil, errors.New("OAuth reconciliation repository returned a nil cursor page") + } + accounts := page.Accounts + if !isStrictlyIncreasingAccountPage(accounts, input.AfterID) { + return nil, errors.New("OAuth reconciliation repository returned an invalid cursor page") + } + + result := &GrokOAuthReconcileResult{ + DryRun: dryRun, + Scanned: len(accounts), + Items: make([]GrokOAuthReconcileItem, 0, len(accounts)), + HasMore: page.HasMore, + } + if result.HasMore { + if page.NextAfterID <= input.AfterID { + return nil, errors.New("OAuth reconciliation repository returned invalid cursor metadata") + } + result.NextAfterID = page.NextAfterID + } + + registration, ok := s.grokRegistration() + if !ok { + return nil, errors.New("grok OAuth refresher is not registered") + } + conditionalErrorRepo, supportsConditionalError := s.accountRepo.(GrokOAuthConditionalErrorRepository) + if input.Apply && !supportsConditionalError { + return nil, errors.New("grok OAuth conditional error mutation is not configured") + } + providerState := &tokenRefreshProviderState{ + service: s, + registration: registration, + rateGate: s.providerRateGate(PlatformGrok), + poolGate: s.providerConcurrencyGate(PlatformGrok), + } + + for i := range accounts { + if err := ctx.Err(); err != nil { + return nil, err + } + account := &accounts[i] + reason, action, actionable := classifyGrokOAuthReconcileAccount(account, refreshWindow) + if !actionable { + result.Skipped++ + continue + } + result.Actionable++ + item := GrokOAuthReconcileItem{ + AccountID: account.ID, + Reason: reason, + Action: action, + Outcome: GrokOAuthReconcileOutcomePlanned, + } + if action == GrokOAuthReconcileActionBlock { + result.WouldBlock++ + } else { + result.WouldRefresh++ + } + if dryRun { + result.Items = append(result.Items, item) + continue + } + + switch action { + case GrokOAuthReconcileActionBlock: + latest, err := s.accountRepo.GetByID(ctx, account.ID) + if err != nil || latest == nil { + item.Outcome = GrokOAuthReconcileOutcomeFailed + result.Failed++ + break + } + latestReason, latestAction, stillActionable := classifyGrokOAuthReconcileAccount(latest, refreshWindow) + if !stillActionable || latestAction != GrokOAuthReconcileActionBlock { + // The account changed after page hydration (for example, an admin + // reauthorized it). Never apply a stale destructive action; the next + // resumable scan can plan the fresh state. + item.Outcome = GrokOAuthReconcileOutcomeSkipped + result.Skipped++ + break + } + account = latest + item.Reason = latestReason + applied, err := conditionalErrorRepo.SetGrokOAuthErrorIfCredentialsUnchanged( + ctx, + account.ID, + account.Credentials, + "Grok OAuth credential reconciliation: missing refresh token", + ) + if err != nil { + item.Outcome = GrokOAuthReconcileOutcomeFailed + result.Failed++ + break + } + if !applied { + // Reauthorization won the compare-and-set race after the final + // reread. The runtime fast path is installed only after the CAS + // succeeds, so the fresh active account remains untouched. + item.Outcome = GrokOAuthReconcileOutcomeSkipped + result.Skipped++ + break + } + s.notifyAccountSchedulingBlocked(account, time.Time{}, "grok_oauth_reconcile_invalid") + account.Status = StatusError + account.Schedulable = false + cacheInvalidationFailed := s.cacheInvalidator == nil + if s.cacheInvalidator != nil { + if err := s.cacheInvalidator.InvalidateToken(ctx, account); err != nil { + cacheInvalidationFailed = true + } + } + result.Blocked++ + if cacheInvalidationFailed { + item.Outcome = GrokOAuthReconcileOutcomePartial + result.Partial++ + } else { + item.Outcome = GrokOAuthReconcileOutcomeApplied + } + case GrokOAuthReconcileActionRefresh: + if providerState.isTripped() { + item.Outcome = GrokOAuthReconcileOutcomeSkipped + result.Skipped++ + break + } + if providerState.isTripped() { + item.Outcome = GrokOAuthReconcileOutcomeSkipped + result.Skipped++ + break + } + refreshErr := s.refreshWithRetryWithRateGate(ctx, account, registration.refresher, registration.executor, refreshWindow, providerState) + providerState.recordResult(refreshErr) + var permanentErr *accountPermanentRefreshError + switch { + case refreshErr == nil: + item.Outcome = GrokOAuthReconcileOutcomeApplied + result.Refreshed++ + case errors.Is(refreshErr, errRefreshSkipped): + item.Outcome = GrokOAuthReconcileOutcomeSkipped + result.Skipped++ + case errors.As(refreshErr, &permanentErr) && permanentErr.persistentlyBlocked: + item.Reason = GrokOAuthReconcileReasonCredentialRejected + item.Action = GrokOAuthReconcileActionBlock + result.Blocked++ + if permanentErr.cacheInvalidationFailed { + item.Outcome = GrokOAuthReconcileOutcomePartial + result.Partial++ + } else { + item.Outcome = GrokOAuthReconcileOutcomeApplied + } + default: + item.Outcome = GrokOAuthReconcileOutcomeFailed + result.Failed++ + } + default: + return nil, fmt.Errorf("unsupported Grok OAuth reconciliation action") + } + result.Items = append(result.Items, item) + } + return result, nil +} + +func (s *TokenRefreshService) grokOAuthReconcileMaxPageSize() int { + return maxGrokOAuthReconcilePageSize +} + +func (s *TokenRefreshService) grokRegistration() (tokenRefreshRegistration, bool) { + for _, registration := range s.registrations { + if registration.platform == PlatformGrok && registration.refresher != nil { + return registration, true + } + } + return tokenRefreshRegistration{}, false +} + +func classifyGrokOAuthReconcileAccount(account *Account, refreshWindow time.Duration) (reason, action string, actionable bool) { + if account == nil || !account.IsGrokOAuth() || account.Status != StatusActive { + return "", "", false + } + if strings.TrimSpace(account.GetGrokRefreshToken()) == "" { + return GrokOAuthReconcileReasonMissingRefreshToken, GrokOAuthReconcileActionBlock, true + } + if strings.TrimSpace(account.GetGrokAccessToken()) == "" { + return GrokOAuthReconcileReasonMissingAccessToken, GrokOAuthReconcileActionRefresh, true + } + rawExpiry := strings.TrimSpace(account.GetCredential("expires_at")) + if rawExpiry == "" { + return GrokOAuthReconcileReasonMissingExpiry, GrokOAuthReconcileActionRefresh, true + } + expiresAt := account.GetCredentialAsTime("expires_at") + if expiresAt == nil { + return GrokOAuthReconcileReasonInvalidExpiry, GrokOAuthReconcileActionRefresh, true + } + if time.Until(*expiresAt) <= refreshWindow { + return GrokOAuthReconcileReasonNearExpiry, GrokOAuthReconcileActionRefresh, true + } + return "", "", false +} diff --git a/backend/internal/service/grok_oauth_reconciliation_test.go b/backend/internal/service/grok_oauth_reconciliation_test.go new file mode 100644 index 0000000000..8de04a1b5d --- /dev/null +++ b/backend/internal/service/grok_oauth_reconciliation_test.go @@ -0,0 +1,578 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "reflect" + "sort" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +type grokReconcileRepo struct { + AccountRepository + + mu sync.Mutex + accounts []Account + requests []OAuthRefreshPageOptions + setErrorIDs []int64 + updatedCredIDs []int64 + setErrorMessage []string + getByIDOverrides map[int64]Account + pageOverride *OAuthRefreshCandidatePage + reauthorizeOnCAS bool + reauthorizeOnRefreshCAS bool + conditionalCalls int +} + +func (r *grokReconcileRepo) GetByID(_ context.Context, id int64) (*Account, error) { + r.mu.Lock() + defer r.mu.Unlock() + if override, ok := r.getByIDOverrides[id]; ok { + account := override + return &account, nil + } + for i := range r.accounts { + if r.accounts[i].ID == id { + account := r.accounts[i] + return &account, nil + } + } + return nil, ErrAccountNotFound +} + +func (r *grokReconcileRepo) ListOAuthRefreshCandidatePage(_ context.Context, options OAuthRefreshPageOptions) (*OAuthRefreshCandidatePage, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.requests = append(r.requests, options) + if r.pageOverride != nil { + page := *r.pageOverride + page.Accounts = append([]Account(nil), r.pageOverride.Accounts...) + return &page, nil + } + accounts := append([]Account(nil), r.accounts...) + sort.Slice(accounts, func(i, j int) bool { return accounts[i].ID < accounts[j].ID }) + page := make([]Account, 0, options.Limit) + for _, account := range accounts { + if account.ID <= options.AfterID { + continue + } + platformAllowed := false + for _, platform := range options.Platforms { + if account.Platform == platform { + platformAllowed = true + break + } + } + if !platformAllowed || options.ActiveOnly && account.Status != StatusActive { + continue + } + if options.IncludeSetupToken { + if account.Type != AccountTypeOAuth && account.Type != AccountTypeSetupToken { + continue + } + } else if account.Type != AccountTypeOAuth { + continue + } + if options.RequireRefreshToken && strings.TrimSpace(account.GetGrokRefreshToken()) == "" { + continue + } + page = append(page, account) + if len(page) == options.Limit { + break + } + } + result := &OAuthRefreshCandidatePage{Accounts: page, HasMore: len(page) == options.Limit} + if len(page) > 0 { + result.NextAfterID = page[len(page)-1].ID + } + return result, nil +} + +func (r *grokReconcileRepo) UpdateCredentials(_ context.Context, id int64, credentials map[string]any) error { + r.mu.Lock() + defer r.mu.Unlock() + r.updatedCredIDs = append(r.updatedCredIDs, id) + for i := range r.accounts { + if r.accounts[i].ID == id { + r.accounts[i].Credentials = MergeCredentials(r.accounts[i].Credentials, credentials) + } + } + return nil +} + +func (r *grokReconcileRepo) SetError(_ context.Context, id int64, message string) error { + r.mu.Lock() + defer r.mu.Unlock() + r.setErrorIDs = append(r.setErrorIDs, id) + r.setErrorMessage = append(r.setErrorMessage, message) + for i := range r.accounts { + if r.accounts[i].ID == id { + r.accounts[i].Status = StatusError + r.accounts[i].Schedulable = false + r.accounts[i].ErrorMessage = message + } + } + return nil +} + +func (r *grokReconcileRepo) SetGrokOAuthErrorIfCredentialsUnchanged( + _ context.Context, + id int64, + expectedCredentials map[string]any, + message string, +) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.conditionalCalls++ + for i := range r.accounts { + account := &r.accounts[i] + if account.ID != id { + continue + } + if r.reauthorizeOnCAS { + r.reauthorizeOnCAS = false + account.Credentials = map[string]any{ + "access_token": "fresh-access", + "refresh_token": "fresh-refresh", + "expires_at": time.Now().UTC().Add(4 * time.Hour).Format(time.RFC3339), + "_token_version": int64(2), + } + } + if account.Platform != PlatformGrok || account.Type != AccountTypeOAuth || account.Status != StatusActive || + strings.TrimSpace(account.GetGrokRefreshToken()) != "" || !reflect.DeepEqual(account.Credentials, expectedCredentials) { + return false, nil + } + r.setErrorIDs = append(r.setErrorIDs, id) + r.setErrorMessage = append(r.setErrorMessage, message) + account.Status = StatusError + account.Schedulable = false + account.ErrorMessage = message + return true, nil + } + return false, nil +} + +func (r *grokReconcileRepo) SetGrokOAuthRefreshErrorIfCredentialsUnchanged( + _ context.Context, + id int64, + expectedCredentials map[string]any, + expectedProxyID *int64, + message string, +) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + for i := range r.accounts { + account := &r.accounts[i] + if account.ID != id { + continue + } + if r.reauthorizeOnRefreshCAS { + r.reauthorizeOnRefreshCAS = false + account.Credentials = map[string]any{ + "access_token": "fresh-access", + "refresh_token": "fresh-refresh", + "expires_at": time.Now().UTC().Add(4 * time.Hour).Format(time.RFC3339), + "_token_version": int64(3), + } + } + if account.Platform != PlatformGrok || account.Type != AccountTypeOAuth || account.Status != StatusActive || + !reflect.DeepEqual(account.ProxyID, expectedProxyID) || + !reflect.DeepEqual(account.Credentials, expectedCredentials) { + return false, nil + } + r.setErrorIDs = append(r.setErrorIDs, id) + r.setErrorMessage = append(r.setErrorMessage, message) + account.Status = StatusError + account.Schedulable = false + account.ErrorMessage = message + return true, nil + } + return false, nil +} + +func (r *grokReconcileRepo) SetGrokOAuthRefreshTempUnschedulableIfCredentialsUnchanged( + _ context.Context, + id int64, + expectedCredentials map[string]any, + expectedProxyID *int64, + until time.Time, + reason string, +) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + for i := range r.accounts { + account := &r.accounts[i] + if account.ID != id { + continue + } + if account.Platform != PlatformGrok || account.Type != AccountTypeOAuth || account.Status != StatusActive || + !reflect.DeepEqual(account.ProxyID, expectedProxyID) || + !reflect.DeepEqual(account.Credentials, expectedCredentials) { + return false, nil + } + account.TempUnschedulableUntil = &until + account.TempUnschedulableReason = reason + return true, nil + } + return false, nil +} + +func (r *grokReconcileRepo) snapshot() ([]OAuthRefreshPageOptions, []int64, []int64, []string) { + r.mu.Lock() + defer r.mu.Unlock() + return append([]OAuthRefreshPageOptions(nil), r.requests...), append([]int64(nil), r.setErrorIDs...), append([]int64(nil), r.updatedCredIDs...), append([]string(nil), r.setErrorMessage...) +} + +type reconcileInvalidator struct { + mu sync.Mutex + ids []int64 + err error +} + +type reconcileRuntimeBlocker struct { + mu sync.Mutex + blocked []int64 + cleared []int64 +} + +func (b *reconcileRuntimeBlocker) BlockAccountScheduling(account *Account, _ time.Time, _ string) { + b.mu.Lock() + defer b.mu.Unlock() + if account != nil { + b.blocked = append(b.blocked, account.ID) + } +} + +func (b *reconcileRuntimeBlocker) ClearAccountSchedulingBlock(accountID int64) { + b.mu.Lock() + defer b.mu.Unlock() + b.cleared = append(b.cleared, accountID) +} + +func (b *reconcileRuntimeBlocker) snapshot() (blocked, cleared []int64) { + b.mu.Lock() + defer b.mu.Unlock() + return append([]int64(nil), b.blocked...), append([]int64(nil), b.cleared...) +} + +func (i *reconcileInvalidator) InvalidateToken(_ context.Context, account *Account) error { + i.mu.Lock() + defer i.mu.Unlock() + i.ids = append(i.ids, account.ID) + return i.err +} + +func (i *reconcileInvalidator) count() int { + i.mu.Lock() + defer i.mu.Unlock() + return len(i.ids) +} + +func newGrokReconcileService(repo *grokReconcileRepo, refresher *poolHealthRefresher, invalidator TokenCacheInvalidator) *TokenRefreshService { + return &TokenRefreshService{ + accountRepo: repo, + candidatePager: repo, + cacheInvalidator: invalidator, + registrations: []tokenRefreshRegistration{{ + platform: PlatformGrok, + refresher: refresher, + executor: refresher, + }}, + refreshPolicy: DefaultBackgroundRefreshPolicy(), + cfg: &config.TokenRefreshConfig{ + MaxRetries: 1, + CandidatePageSize: 50, + ProviderConcurrency: 2, + ProviderQPS: 100, + ProviderFailureThreshold: 3, + AttemptTimeoutSeconds: 1, + }, + } +} + +func grokReconcileFixtures() []Account { + now := time.Now().UTC() + return []Account{ + { + ID: 1, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{"access_token": "access-secret"}, + }, + { + ID: 2, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{"refresh_token": "refresh-secret", "expires_at": now.Add(10 * time.Minute).Format(time.RFC3339)}, + }, + { + ID: 3, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{"access_token": "access-secret", "refresh_token": "refresh-secret", "expires_at": now.Add(30 * time.Minute).Format(time.RFC3339)}, + }, + { + ID: 4, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{"access_token": "access-secret", "refresh_token": "refresh-secret", "expires_at": now.Add(4 * time.Hour).Format(time.RFC3339)}, + }, + { + ID: 5, + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{"api_key": "api-key-secret"}, + }, + } +} + +func TestTokenRefreshService_ReconcileGrokOAuthDefaultsToDryRunAndSanitizedPlan(t *testing.T) { + repo := &grokReconcileRepo{accounts: grokReconcileFixtures()} + refresher := &poolHealthRefresher{} + svc := newGrokReconcileService(repo, refresher, nil) + + result, err := svc.ReconcileGrokOAuth(context.Background(), GrokOAuthReconcileInput{}) + + require.NoError(t, err) + require.True(t, result.DryRun) + require.Equal(t, 4, result.Scanned, "Grok API-key rows must not enter the OAuth reconciliation page") + require.Equal(t, 3, result.Actionable) + require.Equal(t, 1, result.WouldBlock) + require.Equal(t, 2, result.WouldRefresh) + require.Zero(t, result.Blocked) + require.Zero(t, result.Refreshed) + require.Zero(t, refresher.calls.Load()) + _, setErrorIDs, updatedIDs, _ := repo.snapshot() + require.Empty(t, setErrorIDs) + require.Empty(t, updatedIDs) + + payload, err := json.Marshal(result) + require.NoError(t, err) + text := string(payload) + require.NotContains(t, text, "access-secret") + require.NotContains(t, text, "refresh-secret") + require.NotContains(t, text, "api-key-secret") + require.NotContains(t, text, `"credentials":`) +} + +func TestGrokTokenRefresher_NeedsRefreshWhenAccessTokenMissingDespiteFarFutureExpiry(t *testing.T) { + refresher := NewGrokTokenRefresher(nil) + account := grokPoolAccount(99) + delete(account.Credentials, "access_token") + account.Credentials["expires_at"] = time.Now().UTC().Add(12 * time.Hour).Format(time.RFC3339) + + require.True(t, refresher.NeedsRefresh(&account, time.Hour)) +} + +func TestTokenRefreshService_ReconcileGrokOAuthApplyIsIdempotent(t *testing.T) { + repo := &grokReconcileRepo{accounts: grokReconcileFixtures()} + invalidator := &reconcileInvalidator{} + refresher := &poolHealthRefresher{newCredentials: map[string]any{ + "access_token": "rotated-access-secret", + "refresh_token": "rotated-refresh-secret", + "expires_at": time.Now().UTC().Add(4 * time.Hour).Format(time.RFC3339), + }} + svc := newGrokReconcileService(repo, refresher, invalidator) + + first, err := svc.ReconcileGrokOAuth(context.Background(), GrokOAuthReconcileInput{Apply: true, Limit: 50}) + require.NoError(t, err) + require.False(t, first.DryRun) + require.Equal(t, 1, first.Blocked) + require.Equal(t, 2, first.Refreshed) + require.Zero(t, first.Failed) + requests, setErrorIDs, updatedIDs, messages := repo.snapshot() + require.Equal(t, []int64{1}, setErrorIDs) + sort.Slice(updatedIDs, func(i, j int) bool { return updatedIDs[i] < updatedIDs[j] }) + require.Equal(t, []int64{2, 3}, updatedIDs) + require.Len(t, messages, 1) + require.NotContains(t, messages[0], "secret") + require.False(t, requests[0].RequireRefreshToken, "structurally invalid rows must remain discoverable") + require.False(t, requests[0].IncludeSetupToken) + require.Equal(t, 3, invalidator.count(), "block and refresh actions must invalidate token cache state") + + second, err := svc.ReconcileGrokOAuth(context.Background(), GrokOAuthReconcileInput{Apply: true, Limit: 50}) + require.NoError(t, err) + require.Zero(t, second.Actionable) + require.Equal(t, int64(2), refresher.calls.Load(), "already refreshed rows must not be refreshed again") + _, setErrorIDs, updatedIDs, _ = repo.snapshot() + require.Equal(t, []int64{1}, setErrorIDs, "already blocked invalid rows must not transition twice") + require.Len(t, updatedIDs, 2) +} + +func TestTokenRefreshService_ReconcileGrokOAuthCursorResumesWithoutDuplicates(t *testing.T) { + fixtures := grokReconcileFixtures()[:3] + repo := &grokReconcileRepo{accounts: fixtures} + svc := newGrokReconcileService(repo, &poolHealthRefresher{}, nil) + + first, err := svc.ReconcileGrokOAuth(context.Background(), GrokOAuthReconcileInput{Limit: 2}) + require.NoError(t, err) + require.True(t, first.HasMore) + require.Equal(t, int64(2), first.NextAfterID) + require.Len(t, first.Items, 2) + + second, err := svc.ReconcileGrokOAuth(context.Background(), GrokOAuthReconcileInput{AfterID: first.NextAfterID, Limit: 2}) + require.NoError(t, err) + require.False(t, second.HasMore) + require.Zero(t, second.NextAfterID) + require.Len(t, second.Items, 1) + require.NotEqual(t, first.Items[0].AccountID, second.Items[0].AccountID) + require.NotEqual(t, first.Items[1].AccountID, second.Items[0].AccountID) +} + +func TestTokenRefreshService_ReconcileGrokOAuthCursorUsesRawPageAfterHydrationGap(t *testing.T) { + account := grokReconcileFixtures()[0] + repo := &grokReconcileRepo{pageOverride: &OAuthRefreshCandidatePage{ + Accounts: []Account{account}, + NextAfterID: account.ID + 1, + HasMore: true, + }} + svc := newGrokReconcileService(repo, &poolHealthRefresher{}, nil) + + result, err := svc.ReconcileGrokOAuth(context.Background(), GrokOAuthReconcileInput{Limit: 2}) + + require.NoError(t, err) + require.True(t, result.HasMore) + require.Equal(t, account.ID+1, result.NextAfterID, + "cursor must advance past a raw selected ID that disappeared during hydration") +} + +func TestTokenRefreshService_ReconcileGrokOAuthRejectsConflictingApplyMode(t *testing.T) { + svc := newGrokReconcileService(&grokReconcileRepo{}, &poolHealthRefresher{}, nil) + + _, err := svc.ReconcileGrokOAuth(context.Background(), GrokOAuthReconcileInput{Apply: true, DryRun: true}) + + require.ErrorIs(t, err, ErrGrokOAuthReconcileMode) +} + +func TestTokenRefreshService_ReconcileGrokOAuthSkipsStaleBlockAfterConcurrentReauthorization(t *testing.T) { + stale := grokReconcileFixtures()[0] + latest := stale + latest.Credentials = map[string]any{ + "access_token": "fresh-access", + "refresh_token": "fresh-refresh", + "expires_at": time.Now().UTC().Add(4 * time.Hour).Format(time.RFC3339), + } + repo := &grokReconcileRepo{ + accounts: []Account{stale}, + getByIDOverrides: map[int64]Account{stale.ID: latest}, + } + svc := newGrokReconcileService(repo, &poolHealthRefresher{}, &reconcileInvalidator{}) + + result, err := svc.ReconcileGrokOAuth(context.Background(), GrokOAuthReconcileInput{Apply: true, Limit: 50}) + + require.NoError(t, err) + require.Zero(t, result.Blocked) + require.Equal(t, 1, result.Skipped) + require.Equal(t, GrokOAuthReconcileOutcomeSkipped, result.Items[0].Outcome) + _, setErrorIDs, _, _ := repo.snapshot() + require.Empty(t, setErrorIDs, "a concurrently reauthorized account must not be disabled from stale page state") +} + +func TestTokenRefreshService_ReconcileGrokOAuthDoesNotRuntimeBlockWhenReauthorizationWinsConditionalMutation(t *testing.T) { + account := grokReconcileFixtures()[0] + account.Credentials["_token_version"] = int64(1) + repo := &grokReconcileRepo{ + accounts: []Account{account}, + reauthorizeOnCAS: true, + } + invalidator := &reconcileInvalidator{} + blocker := &reconcileRuntimeBlocker{} + svc := newGrokReconcileService(repo, &poolHealthRefresher{}, invalidator) + svc.SetAccountRuntimeBlocker(blocker) + + result, err := svc.ReconcileGrokOAuth(context.Background(), GrokOAuthReconcileInput{Apply: true, Limit: 50}) + + require.NoError(t, err) + require.Zero(t, result.Blocked) + require.Equal(t, 1, result.Skipped) + require.Equal(t, GrokOAuthReconcileOutcomeSkipped, result.Items[0].Outcome) + require.Zero(t, invalidator.count(), "a lost compare-and-set race must not invalidate fresh credentials") + _, setErrorIDs, _, _ := repo.snapshot() + require.Empty(t, setErrorIDs) + require.Equal(t, 1, repo.conditionalCalls) + blocked, cleared := blocker.snapshot() + require.Empty(t, blocked, "a lost compare-and-set race must never install a runtime block") + require.Empty(t, cleared, "reconciliation must not clear a block it does not own") + + latest, getErr := repo.GetByID(context.Background(), account.ID) + require.NoError(t, getErr) + require.Equal(t, StatusActive, latest.Status) + require.True(t, latest.Schedulable) + require.Equal(t, "fresh-refresh", latest.GetGrokRefreshToken()) +} + +func TestTokenRefreshService_ReconcileGrokOAuthReportsPermanentRefreshMutationAsBlocked(t *testing.T) { + account := grokReconcileFixtures()[2] + repo := &grokReconcileRepo{accounts: []Account{account}} + refresher := &poolHealthRefresher{err: errors.New(`GROK_OAUTH_ENTITLEMENT_DENIED: subscription required`)} + svc := newGrokReconcileService(repo, refresher, &reconcileInvalidator{}) + + result, err := svc.ReconcileGrokOAuth(context.Background(), GrokOAuthReconcileInput{Apply: true, Limit: 50}) + + require.NoError(t, err) + require.Equal(t, 1, result.Blocked) + require.Zero(t, result.Failed) + require.Zero(t, result.Partial) + require.Equal(t, GrokOAuthReconcileActionBlock, result.Items[0].Action) + require.Equal(t, GrokOAuthReconcileReasonCredentialRejected, result.Items[0].Reason) + require.Equal(t, GrokOAuthReconcileOutcomeApplied, result.Items[0].Outcome) + _, setErrorIDs, _, _ := repo.snapshot() + require.Equal(t, []int64{account.ID}, setErrorIDs) +} + +func TestTokenRefreshService_ReconcileGrokOAuthReportsConcurrentRefreshReauthorizationAsSkipped(t *testing.T) { + account := grokReconcileFixtures()[2] + repo := &grokReconcileRepo{ + accounts: []Account{account}, + reauthorizeOnRefreshCAS: true, + } + invalidator := &reconcileInvalidator{} + refresher := &poolHealthRefresher{err: errors.New("invalid_grant: revoked")} + svc := newGrokReconcileService(repo, refresher, invalidator) + + result, err := svc.ReconcileGrokOAuth(context.Background(), GrokOAuthReconcileInput{Apply: true, Limit: 50}) + + require.NoError(t, err) + require.Equal(t, 1, result.Skipped) + require.Zero(t, result.Failed) + require.Zero(t, result.Blocked) + require.Equal(t, GrokOAuthReconcileOutcomeSkipped, result.Items[0].Outcome) + require.Zero(t, invalidator.count()) + _, setErrorIDs, _, _ := repo.snapshot() + require.Empty(t, setErrorIDs) + latest, getErr := repo.GetByID(context.Background(), account.ID) + require.NoError(t, getErr) + require.Equal(t, StatusActive, latest.Status) + require.Equal(t, "fresh-refresh", latest.GetGrokRefreshToken()) +} + +func TestTokenRefreshService_ReconcileGrokOAuthReportsInvalidationFailureAsPartial(t *testing.T) { + account := grokReconcileFixtures()[0] + repo := &grokReconcileRepo{accounts: []Account{account}} + svc := newGrokReconcileService(repo, &poolHealthRefresher{}, &reconcileInvalidator{err: errors.New("cache unavailable")}) + + result, err := svc.ReconcileGrokOAuth(context.Background(), GrokOAuthReconcileInput{Apply: true, Limit: 50}) + + require.NoError(t, err) + require.Equal(t, 1, result.Blocked) + require.Equal(t, 1, result.Partial) + require.Zero(t, result.Failed) + require.Equal(t, GrokOAuthReconcileOutcomePartial, result.Items[0].Outcome) +} diff --git a/backend/internal/service/grok_oauth_service.go b/backend/internal/service/grok_oauth_service.go index 136e5e3b21..92f3937967 100644 --- a/backend/internal/service/grok_oauth_service.go +++ b/backend/internal/service/grok_oauth_service.go @@ -3,6 +3,7 @@ package service import ( "context" "crypto/subtle" + "errors" "net/http" "strings" "time" @@ -314,10 +315,13 @@ func (s *GrokOAuthService) proxyURL(ctx context.Context, proxyID *int64) (string } proxy, err := s.proxyRepo.GetByID(ctx, *proxyID) if err != nil { - return "", infraerrors.Newf(http.StatusBadRequest, "GROK_OAUTH_PROXY_NOT_FOUND", "proxy not found: %v", err) + if errors.Is(err, ErrProxyNotFound) { + return "", infraerrors.New(http.StatusBadRequest, "GROK_OAUTH_PROXY_NOT_FOUND", "configured proxy was not found") + } + return "", infraerrors.New(http.StatusServiceUnavailable, "GROK_OAUTH_PROXY_LOOKUP_FAILED", "proxy lookup is temporarily unavailable") } if proxy == nil { - return "", nil + return "", infraerrors.New(http.StatusBadRequest, "GROK_OAUTH_PROXY_NOT_FOUND", "configured proxy was not found") } return proxy.URL(), nil } diff --git a/backend/internal/service/grok_quota_service.go b/backend/internal/service/grok_quota_service.go index 2219a75c15..a95b778707 100644 --- a/backend/internal/service/grok_quota_service.go +++ b/backend/internal/service/grok_quota_service.go @@ -135,7 +135,7 @@ func (s *GrokQuotaService) probeUsage(ctx context.Context, accountID int64) (*Gr if err != nil { return nil, infraerrors.Newf(http.StatusBadRequest, "GROK_QUOTA_PROBE_BODY_ERROR", "failed to build probe body: %v", err) } - targetURL, err := xai.BuildResponsesURL(account.GetGrokBaseURL()) + targetURL, err := buildGrokResponsesURL(account, nil) if err != nil { return nil, infraerrors.Newf(http.StatusBadRequest, "GROK_QUOTA_BASE_URL_INVALID", "invalid Grok base_url: %v", err) } @@ -149,7 +149,9 @@ func (s *GrokQuotaService) probeUsage(ctx context.Context, accountID int64) (*Gr req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") - applyGrokCLIHeaders(req.Header) + if account.IsGrokOAuth() { + applyGrokCLIHeaders(req.Header) + } resp, err := s.httpUpstream.Do(req, proxyURL, account.ID, maxInt(account.Concurrency, 1)) if err != nil { @@ -158,7 +160,7 @@ func (s *GrokQuotaService) probeUsage(ctx context.Context, accountID int64) (*Gr defer func() { _ = resp.Body.Close() }() snapshot := xai.ObserveQuotaHeaders(resp.Header, resp.StatusCode, "active_probe") - resetAt, limited := grokRateLimitResetAt(snapshot, time.Now()) + resetAt, limited := grokRateLimitResetAtForAccount(account, snapshot, time.Now()) if limited { normalizeGrokExhaustedWindowResets(snapshot, resetAt, time.Now()) } @@ -167,6 +169,8 @@ func (s *GrokQuotaService) probeUsage(ctx context.Context, accountID int64) (*Gr }) if limited { persistGrokRateLimit(ctx, s.accountRepo, account, resetAt) + } else if isSuccessfulGrokRateLimitRecovery(account, snapshot) { + clearGrokRateLimitAfterRecovery(ctx, s.accountRepo, account) } result := &GrokQuotaProbeResult{ @@ -387,6 +391,7 @@ func (s *GrokQuotaService) prepareProbe(ctx context.Context, accountID int64) (* if err != nil { return nil, "", "", err } + proxyURL := s.resolveProxyURL(ctx, account) token, err := s.tokenProvider.GetAccessToken(ctx, account) if err != nil { @@ -396,7 +401,7 @@ func (s *GrokQuotaService) prepareProbe(ctx context.Context, accountID int64) (* return nil, "", "", infraerrors.New(http.StatusBadGateway, "GROK_QUOTA_TOKEN_UNAVAILABLE", "access token is empty") } - return account, token, s.resolveProxyURL(ctx, account), nil + return account, token, proxyURL, nil } func (s *GrokQuotaService) resolveProxyURL(ctx context.Context, account *Account) string { @@ -408,6 +413,7 @@ func (s *GrokQuotaService) resolveProxyURL(ctx context.Context, account *Account return account.Proxy.URL() case s != nil && s.proxyRepo != nil: if proxy, err := s.proxyRepo.GetByID(ctx, *account.ProxyID); err == nil && proxy != nil { + account.Proxy = proxy return proxy.URL() } } diff --git a/backend/internal/service/grok_quota_service_test.go b/backend/internal/service/grok_quota_service_test.go index ba9b6cbcb8..52def9f101 100644 --- a/backend/internal/service/grok_quota_service_test.go +++ b/backend/internal/service/grok_quota_service_test.go @@ -32,6 +32,10 @@ type grokQuotaAccountRepo struct { lastTempUnschedID int64 lastTempUnschedUntil time.Time lastTempUnschedReason string + recoveryClearCalls int + recoveryObservedAt time.Time + recoveryObservedReset time.Time + recoveryClearResult bool } func (r *grokQuotaAccountRepo) UpdateExtra(_ context.Context, id int64, updates map[string]any) error { @@ -54,6 +58,13 @@ func (r *grokQuotaAccountRepo) SetRateLimitedIfLater(ctx context.Context, id int return r.SetRateLimited(ctx, id, resetAt) } +func (r *grokQuotaAccountRepo) ClearRateLimitIfObserved(_ context.Context, _ int64, observedLimitedAt, observedResetAt time.Time) (bool, error) { + r.recoveryClearCalls++ + r.recoveryObservedAt = observedLimitedAt + r.recoveryObservedReset = observedResetAt + return r.recoveryClearResult, nil +} + func (r *grokQuotaAccountRepo) SetTempUnschedulable(_ context.Context, id int64, until time.Time, reason string) error { r.tempUnschedCalls++ r.lastTempUnschedID = id @@ -180,19 +191,26 @@ func (r *grokQuotaProxyRepo) GetByID(_ context.Context, id int64) (*Proxy, error return r.proxies[id], nil } +func healthyGrokQuotaOAuthAccount(id int64) *Account { + return &Account{ + ID: id, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{ + "access_token": "access-token", + "refresh_token": "refresh-token", + "expires_at": time.Now().Add(2 * grokTokenRefreshSkew).UTC().Format(time.RFC3339), + }, + } +} + func TestGrokQuotaServiceProbeUsageStoresHeaders(t *testing.T) { t.Parallel() - account := &Account{ - ID: 42, - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(42) repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{42: account}, @@ -236,19 +254,10 @@ func TestGrokQuotaServiceProbeUsageStoresHeaders(t *testing.T) { func TestGrokQuotaServiceProbeUsageIgnoresAccountGrokMapping(t *testing.T) { t.Parallel() - account := &Account{ - ID: 47, - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "model_mapping": map[string]any{ - "grok": "grok-composer", - "grok-composer": "grok-composer-2.5-fast", - }, - }, + account := healthyGrokQuotaOAuthAccount(47) + account.Credentials["model_mapping"] = map[string]any{ + "grok": "grok-composer", + "grok-composer": "grok-composer-2.5-fast", } repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ @@ -272,16 +281,7 @@ func TestGrokQuotaServiceProbeUsageIgnoresAccountGrokMapping(t *testing.T) { func TestGrokQuotaServiceProbeUsageReportsProbeModelOnUpstreamError(t *testing.T) { t.Parallel() - account := &Account{ - ID: 48, - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(48) repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{48: account}, @@ -302,16 +302,7 @@ func TestGrokQuotaServiceProbeUsageReportsProbeModelOnUpstreamError(t *testing.T func TestGrokQuotaServiceProbeUsageRedactsUpstreamErrorBodyFromErrorAndLogs(t *testing.T) { const upstreamSecret = "upstream-secret-refresh-token" - account := &Account{ - ID: 49, - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(49) repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{49: account}, @@ -352,17 +343,8 @@ func TestGrokQuotaServiceProbeUsageLoadsProxyWhenAccountEdgeMissing(t *testing.T t.Parallel() proxyID := int64(7) - account := &Account{ - ID: 46, - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - ProxyID: &proxyID, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(46) + account.ProxyID = &proxyID repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{46: account}, @@ -394,20 +376,16 @@ func TestGrokQuotaServiceProbeUsageLoadsProxyWhenAccountEdgeMissing(t *testing.T func TestGrokQuotaServiceProbeUsageStoresNoHeadersState(t *testing.T) { t.Parallel() - account := &Account{ - ID: 45, - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(45) + observedResetAt := time.Now().Add(-time.Second).UTC().Truncate(time.Second) + observedLimitedAt := observedResetAt.Add(-grokRateLimitRepeatCooldown) + account.RateLimitedAt = &observedLimitedAt + account.RateLimitResetAt = &observedResetAt repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{45: account}, }, + recoveryClearResult: true, } upstream := &httpUpstreamRecorder{resp: &http.Response{ StatusCode: http.StatusOK, @@ -430,20 +408,15 @@ func TestGrokQuotaServiceProbeUsageStoresNoHeadersState(t *testing.T) { require.True(t, ok) require.False(t, stored.HeadersObserved) require.Equal(t, http.StatusOK, stored.StatusCode) + require.Equal(t, 1, repo.recoveryClearCalls) + require.Equal(t, observedLimitedAt, repo.recoveryObservedAt) + require.Equal(t, observedResetAt, repo.recoveryObservedReset) } func TestGrokQuotaServiceProbeUsageReturnsRateLimitedSnapshot(t *testing.T) { t.Parallel() - account := &Account{ - ID: 43, - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(43) repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{43: account}, @@ -471,13 +444,7 @@ func TestGrokQuotaServiceProbeUsageReturnsRateLimitedSnapshot(t *testing.T) { func TestGrokQuotaServiceQueryQuotaFreeFallsBackToGrok45(t *testing.T) { t.Parallel() - account := &Account{ - ID: 51, Platform: PlatformGrok, Type: AccountTypeOAuth, Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(51) repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{account.ID: account}, }} @@ -518,13 +485,7 @@ func TestGrokQuotaServiceQueryQuotaFreeFallsBackToGrok45(t *testing.T) { func TestGrokQuotaServiceQueryQuotaPaidBillingSkipsActiveProbe(t *testing.T) { t.Parallel() - account := &Account{ - ID: 52, Platform: PlatformGrok, Type: AccountTypeOAuth, Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(52) repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{account.ID: account}, }} @@ -552,13 +513,7 @@ func TestGrokQuotaServiceQueryQuotaPaidBillingSkipsActiveProbe(t *testing.T) { func TestGrokQuotaServiceQueryQuotaCustomPaidMonthlyLimitSkipsActiveProbe(t *testing.T) { t.Parallel() - account := &Account{ - ID: 57, Platform: PlatformGrok, Type: AccountTypeOAuth, Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(57) repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{account.ID: account}, }} @@ -691,13 +646,7 @@ func TestGrokLocalUsageForBillingOnlyReturnsAvailableWindows(t *testing.T) { func TestAccountUsageServiceGrokRefreshUsesBillingOnly(t *testing.T) { t.Parallel() - account := &Account{ - ID: 54, Platform: PlatformGrok, Type: AccountTypeOAuth, Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(54) repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{account.ID: account}, }} @@ -732,13 +681,7 @@ func TestAccountUsageServiceGrokRefreshUsesBillingOnly(t *testing.T) { func TestGrokQuotaServiceProbeFlightsDeduplicateBillingAndSeparateActive(t *testing.T) { t.Parallel() - account := &Account{ - ID: 55, Platform: PlatformGrok, Type: AccountTypeOAuth, Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(55) repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{account.ID: account}, }} @@ -794,13 +737,7 @@ func TestGrokQuotaServiceProbeFlightsDeduplicateBillingAndSeparateActive(t *test func TestGrokQuotaServiceBilling429DoesNotPauseModelScheduling(t *testing.T) { t.Parallel() - account := &Account{ - ID: 56, Platform: PlatformGrok, Type: AccountTypeOAuth, Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(56) repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{account.ID: account}, }} @@ -820,13 +757,7 @@ func TestGrokQuotaServiceBilling429DoesNotPauseModelScheduling(t *testing.T) { func TestGrokQuotaServiceQueryQuotaFree429PersistsLimitAndKeepsBilling(t *testing.T) { t.Parallel() - account := &Account{ - ID: 53, Platform: PlatformGrok, Type: AccountTypeOAuth, Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(53) repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{account.ID: account}, }} diff --git a/backend/internal/service/grok_token_provider.go b/backend/internal/service/grok_token_provider.go index f19ee42b88..ae57cdc59e 100644 --- a/backend/internal/service/grok_token_provider.go +++ b/backend/internal/service/grok_token_provider.go @@ -3,19 +3,25 @@ package service import ( "context" "errors" - "log/slog" + "fmt" "strconv" "strings" "time" - - "github.com/Wei-Shaw/sub2api/internal/util/logredact" ) const ( - grokTokenCacheSkew = 5 * time.Minute - grokRequestRefreshTimeout = 8 * time.Second - grokTokenProviderLogComponent = "grok_token_provider" - grokTempUnschedulableErrorCode = "token_refresh_failed" + grokTokenCacheSkew = 5 * time.Minute + grokRequestRefreshTimeout = 8 * time.Second + grokRefreshLockWaitTimeout = 2 * time.Second + grokRefreshLockPollInterval = 25 * time.Millisecond +) + +var ( + errGrokOAuthRefreshNotConfigured = errors.New("grok oauth refresh is not configured") + errGrokOAuthRefreshTokenMissing = errors.New("grok oauth refresh token is missing") + errGrokOAuthAccessTokenMissing = errors.New("grok oauth access token is missing") + errGrokOAuthAccessTokenExpired = errors.New("grok oauth access token is expired") + errGrokOAuthConfiguredProxyMiss = errors.New("grok oauth configured proxy is missing") ) type GrokTokenCache = GeminiTokenCache @@ -36,7 +42,7 @@ func NewGrokTokenProvider( return &GrokTokenProvider{ accountRepo: accountRepo, tokenCache: tokenCache, - refreshPolicy: AntigravityProviderRefreshPolicy(), + refreshPolicy: GrokProviderRefreshPolicy(), } } @@ -60,32 +66,57 @@ func (p *GrokTokenProvider) GetAccessToken(ctx context.Context, account *Account if account.Platform != PlatformGrok || account.Type != AccountTypeOAuth { return "", errors.New("not a grok oauth account") } - - cacheKey := GrokTokenCacheKey(account) - if p.tokenCache != nil { - if token, err := p.tokenCache.GetAccessToken(ctx, cacheKey); err == nil && strings.TrimSpace(token) != "" { - return token, nil - } + selectedProxyID := cloneGrokProxyID(account.ProxyID) + if eligibilityErr := grokOAuthRequestAccountEligibilityError(account); eligibilityErr != nil { + return "", withGrokCredentialFailureSnapshot(eligibilityErr, account) } expiresAt := account.GetCredentialAsTime("expires_at") - needsRefresh := expiresAt == nil || time.Until(*expiresAt) <= grokTokenRefreshSkew - if needsRefresh && strings.TrimSpace(account.GetGrokRefreshToken()) == "" { - if expiresAt == nil || !time.Now().Before(*expiresAt) { - return "", errors.New("grok access_token expired and refresh_token is missing") - } - needsRefresh = false + accountAccessToken := strings.TrimSpace(account.GetGrokAccessToken()) + if accountAccessToken == "" { + return "", withGrokCredentialFailureSnapshot(errGrokOAuthAccessTokenMissing, account) } - if needsRefresh && p.refreshAPI != nil && p.executor != nil { + if strings.TrimSpace(account.GetGrokRefreshToken()) == "" { + return "", withGrokCredentialFailureSnapshot(errGrokOAuthRefreshTokenMissing, account) + } + cacheKey := GrokTokenCacheKey(account) + if p.tokenCache != nil { + if token, err := p.tokenCache.GetAccessToken(ctx, cacheKey); err == nil { + cachedToken := strings.TrimSpace(token) + if cachedToken != "" && accountAccessToken != "" && cachedToken == accountAccessToken && + expiresAt != nil && time.Until(*expiresAt) > grokTokenRefreshSkew { + return cachedToken, nil + } + } + } + + needsRefresh := expiresAt == nil || time.Until(*expiresAt) <= grokTokenRefreshSkew + if needsRefresh { + if p.refreshAPI == nil || p.executor == nil { + return "", errGrokOAuthRefreshNotConfigured + } refreshCtx, cancel := context.WithTimeout(ctx, grokRequestRefreshTimeout) defer cancel() - result, err := p.refreshAPI.RefreshIfNeeded(refreshCtx, account, p.executor, grokTokenRefreshSkew) + result, err := p.refreshAPI.RefreshIfNeeded(withOAuthRefreshRequestPath(refreshCtx), account, p.executor, grokTokenRefreshSkew) if err != nil { - p.markTempUnschedulable(account, err) if p.refreshPolicy.OnRefreshError == ProviderRefreshErrorReturn { return "", err } - } else if !result.LockHeld && result.Account != nil { + } else if result != nil && result.LockHeld { + if p.refreshPolicy.OnLockHeld == ProviderLockHeldWaitForCache { + token, waitErr := p.waitForRefreshedToken(refreshCtx, account, cacheKey) + return token, withGrokCredentialFailureSnapshot(waitErr, account) + } + if expiresAt == nil || !time.Now().Before(*expiresAt) { + return "", withGrokCredentialFailureSnapshot(errGrokOAuthAccessTokenExpired, account) + } + } else if result != nil && result.Account != nil { + if eligibilityErr := grokOAuthRequestAccountEligibilityError(result.Account); eligibilityErr != nil { + return "", withGrokCredentialFailureSnapshot(eligibilityErr, result.Account) + } + if !grokCredentialProxyIDsEqual(result.Account.ProxyID, selectedProxyID) { + return "", withGrokCredentialFailureSnapshot(errOAuthRefreshAccountStateChanged, result.Account) + } account = result.Account expiresAt = account.GetCredentialAsTime("expires_at") } @@ -93,15 +124,28 @@ func (p *GrokTokenProvider) GetAccessToken(ctx context.Context, account *Account accessToken := account.GetGrokAccessToken() if strings.TrimSpace(accessToken) == "" { - return "", errors.New("access_token not found in credentials") + return "", withGrokCredentialFailureSnapshot(errGrokOAuthAccessTokenMissing, account) + } + if expiresAt != nil && !time.Now().Before(*expiresAt) { + return "", withGrokCredentialFailureSnapshot(errGrokOAuthAccessTokenExpired, account) } if p.tokenCache != nil { latestAccount, isStale := CheckTokenVersion(ctx, account, p.accountRepo) if isStale && latestAccount != nil { + if eligibilityErr := grokOAuthRequestAccountEligibilityError(latestAccount); eligibilityErr != nil { + return "", withGrokCredentialFailureSnapshot(eligibilityErr, latestAccount) + } + if !grokCredentialProxyIDsEqual(latestAccount.ProxyID, selectedProxyID) { + return "", withGrokCredentialFailureSnapshot(errOAuthRefreshAccountStateChanged, latestAccount) + } accessToken = latestAccount.GetGrokAccessToken() if strings.TrimSpace(accessToken) == "" { - return "", errors.New("access_token not found after version check") + return "", withGrokCredentialFailureSnapshot(errGrokOAuthAccessTokenMissing, latestAccount) + } + latestExpiry := latestAccount.GetCredentialAsTime("expires_at") + if latestExpiry == nil || !time.Now().Before(*latestExpiry) { + return "", withGrokCredentialFailureSnapshot(errGrokOAuthAccessTokenExpired, latestAccount) } } else { ttl := 30 * time.Minute @@ -123,40 +167,105 @@ func (p *GrokTokenProvider) GetAccessToken(ctx context.Context, account *Account return accessToken, nil } -func (p *GrokTokenProvider) markTempUnschedulable(account *Account, refreshErr error) { - if p == nil || p.accountRepo == nil || account == nil { - return - } - now := time.Now() - until := now.Add(tokenRefreshTempUnschedDuration) - redactedErr := "unknown error" - if refreshErr != nil { - redactedErr = logredact.RedactText(refreshErr.Error()) - } - if isNonRetryableRefreshError(refreshErr) { - if err := p.accountRepo.SetError(context.Background(), account.ID, "grok token refresh failed (non-retryable): "+redactedErr); err != nil { - slog.Warn(grokTokenProviderLogComponent+".set_error_status_failed", "account_id", account.ID, "error", err) +func (p *GrokTokenProvider) waitForRefreshedToken(ctx context.Context, account *Account, cacheKey string) (string, error) { + waitCtx, cancel := context.WithTimeout(ctx, grokRefreshLockWaitTimeout) + defer cancel() + + initialToken := strings.TrimSpace(account.GetGrokAccessToken()) + initialVersion := account.GetCredentialAsInt64("_token_version") + selectedProxyID := cloneGrokProxyID(account.ProxyID) + sawAuthoritativeState := false + var lastAccountReadErr error + ticker := time.NewTicker(grokRefreshLockPollInterval) + defer ticker.Stop() + + for { + cachedToken := "" + if p.tokenCache != nil { + if token, err := p.tokenCache.GetAccessToken(waitCtx, cacheKey); err == nil { + cachedToken = strings.TrimSpace(token) + } } - return - } - reason := "grok token refresh failed on request path: " + redactedErr - bgCtx := context.Background() - if err := p.accountRepo.SetTempUnschedulable(bgCtx, account.ID, until, reason); err != nil { - slog.Warn(grokTokenProviderLogComponent+".set_temp_unschedulable_failed", "account_id", account.ID, "error", err) - return - } - if p.tempUnschedCache != nil { - state := &TempUnschedState{ - UntilUnix: until.Unix(), - TriggeredAtUnix: now.Unix(), - ErrorMessage: grokTempUnschedulableErrorCode + ": " + reason, + + if p.accountRepo != nil { + latest, err := p.accountRepo.GetByID(waitCtx, account.ID) + if err != nil { + lastAccountReadErr = err + } else if latest == nil { + return "", errOAuthRefreshAccountStateChanged + } else { + sawAuthoritativeState = true + if eligibilityErr := grokOAuthRequestAccountEligibilityError(latest); eligibilityErr != nil { + return "", withGrokCredentialFailureSnapshot(eligibilityErr, latest) + } + if !grokCredentialProxyIDsEqual(latest.ProxyID, selectedProxyID) { + return "", withGrokCredentialFailureSnapshot(errOAuthRefreshAccountStateChanged, latest) + } + token := strings.TrimSpace(latest.GetGrokAccessToken()) + version := latest.GetCredentialAsInt64("_token_version") + expiresAt := latest.GetCredentialAsTime("expires_at") + changed := token != initialToken || (version > 0 && version > initialVersion) + valid := expiresAt != nil && time.Now().Before(*expiresAt) + if token != "" && changed && valid { + // The versioned DB credential is authoritative. A stale cache must + // not hold the request on the old expired token; repair it best-effort. + if cachedToken != "" && cachedToken != token { + ttl := time.Until(*expiresAt) + if ttl > grokTokenCacheSkew { + ttl -= grokTokenCacheSkew + } + _ = p.tokenCache.SetAccessToken(waitCtx, cacheKey, token, ttl) + } + return token, nil + } + } } - if err := p.tempUnschedCache.SetTempUnsched(bgCtx, account.ID, state); err != nil { - slog.Warn(grokTokenProviderLogComponent+".temp_unsched_cache_set_failed", "account_id", account.ID, "error", err) + + select { + case <-waitCtx.Done(): + if ctx.Err() != nil { + return "", ctx.Err() + } + if !sawAuthoritativeState { + if lastAccountReadErr == nil { + lastAccountReadErr = waitCtx.Err() + } + return "", fmt.Errorf("%w: %v", errOAuthRefreshAccountRereadFailed, lastAccountReadErr) + } + // Another worker still owns the refresh and the authoritative row is + // unchanged. Do not quarantine the old credential: its refresh may + // commit immediately after this bounded wait. + return "", errOAuthRefreshAccountStateChanged + case <-ticker.C: } } } +func grokOAuthRequestAccountEligibilityError(account *Account) error { + if account == nil || !account.IsGrokOAuth() || !account.IsSchedulable() { + return errOAuthRefreshAccountStateChanged + } + if account.ProxyID != nil && account.Proxy == nil { + return errGrokOAuthConfiguredProxyMiss + } + return nil +} + +func cloneGrokProxyID(proxyID *int64) *int64 { + if proxyID == nil { + return nil + } + value := *proxyID + return &value +} + +func (p *GrokTokenProvider) InvalidateToken(ctx context.Context, account *Account) error { + if p == nil || p.tokenCache == nil || account == nil { + return nil + } + return p.tokenCache.DeleteAccessToken(ctx, GrokTokenCacheKey(account)) +} + func GrokTokenCacheKey(account *Account) string { if account == nil { return "grok:account:0" diff --git a/backend/internal/service/grok_token_provider_test.go b/backend/internal/service/grok_token_provider_test.go index 1f7e2d8e0e..7c68e55455 100644 --- a/backend/internal/service/grok_token_provider_test.go +++ b/backend/internal/service/grok_token_provider_test.go @@ -5,6 +5,7 @@ package service import ( "context" "errors" + "sync" "testing" "time" @@ -19,9 +20,33 @@ type grokTokenCacheForProviderTest struct { setTTL time.Duration lockResult bool releaseCalls int + deletedKeys []string + deleteErr error + getCalls int + mu sync.Mutex +} + +type grokCredentialRaceRepo struct { + *tokenRefreshAccountRepo + mu sync.RWMutex +} + +func (r *grokCredentialRaceRepo) GetByID(ctx context.Context, id int64) (*Account, error) { + r.mu.RLock() + defer r.mu.RUnlock() + return r.tokenRefreshAccountRepo.GetByID(ctx, id) +} + +func (r *grokCredentialRaceRepo) setAccount(account *Account) { + r.mu.Lock() + defer r.mu.Unlock() + r.accountsByID[account.ID] = account } func (c *grokTokenCacheForProviderTest) GetAccessToken(context.Context, string) (string, error) { + c.mu.Lock() + defer c.mu.Unlock() + c.getCalls++ if c.token == "" { return "", errors.New("not cached") } @@ -29,14 +54,19 @@ func (c *grokTokenCacheForProviderTest) GetAccessToken(context.Context, string) } func (c *grokTokenCacheForProviderTest) SetAccessToken(_ context.Context, key string, token string, ttl time.Duration) error { + c.mu.Lock() + defer c.mu.Unlock() c.setKey = key c.setToken = token c.setTTL = ttl return nil } -func (c *grokTokenCacheForProviderTest) DeleteAccessToken(context.Context, string) error { - return nil +func (c *grokTokenCacheForProviderTest) DeleteAccessToken(_ context.Context, key string) error { + c.mu.Lock() + defer c.mu.Unlock() + c.deletedKeys = append(c.deletedKeys, key) + return c.deleteErr } func (c *grokTokenCacheForProviderTest) AcquireRefreshLock(context.Context, string, time.Duration) (bool, error) { @@ -53,9 +83,11 @@ func TestGrokTokenProviderRefreshesExpiredTokenOnRequestPath(t *testing.T) { expiredAt := time.Now().Add(-time.Minute).UTC().Format(time.RFC3339) account := &Account{ - ID: 54, - Platform: PlatformGrok, - Type: AccountTypeOAuth, + ID: 54, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, Credentials: map[string]any{ "access_token": "expired-access-token", "refresh_token": "refresh-token", @@ -95,9 +127,11 @@ func TestGrokTokenProviderRefreshesExpiredTokenOnRequestPath(t *testing.T) { func TestGrokTokenProviderRefreshFailureUnschedulesWithRedactedReason(t *testing.T) { expiredAt := time.Now().Add(-time.Minute).UTC().Format(time.RFC3339) account := &Account{ - ID: 55, - Platform: PlatformGrok, - Type: AccountTypeOAuth, + ID: 55, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, Credentials: map[string]any{ "access_token": "expired-access-token", "refresh_token": "refresh-token", @@ -108,24 +142,178 @@ func TestGrokTokenProviderRefreshFailureUnschedulesWithRedactedReason(t *testing repo := &tokenRefreshAccountRepo{} repo.accountsByID = map[int64]*Account{55: account} cache := &grokTokenCacheForProviderTest{lockResult: true} - tempCache := &tempUnschedCacheStub{} provider := NewGrokTokenProvider(repo, cache) provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{ err: errors.New("temporary refresh failure access_token=leaked-access refresh_token=leaked-refresh"), }) - provider.SetTempUnschedCache(tempCache) token, err := provider.GetAccessToken(context.Background(), account) require.Error(t, err) require.Empty(t, token) - require.Equal(t, 1, repo.setTempUnschedCalls) + require.Equal(t, 0, repo.setTempUnschedCalls) require.Equal(t, 0, repo.setErrorCalls) - require.Contains(t, repo.lastTempUnschedReason, "access_token=***") - require.Contains(t, repo.lastTempUnschedReason, "refresh_token=***") - require.NotContains(t, repo.lastTempUnschedReason, "leaked-access") - require.NotContains(t, repo.lastTempUnschedReason, "leaked-refresh") - require.Equal(t, 1, tempCache.setCalls) - require.NotNil(t, tempCache.lastState) - require.NotContains(t, tempCache.lastState.ErrorMessage, "leaked-access") - require.NotContains(t, tempCache.lastState.ErrorMessage, "leaked-refresh") +} + +func TestGrokTokenProviderLockHeldWaitsForRefreshedCacheAndNeverUsesExpiredToken(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(56) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialRaceRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{lockResult: false, token: "expired-access-token"} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{}) + + go func() { + time.Sleep(40 * time.Millisecond) + refreshed := *account + refreshed.Credentials = shallowCopyMap(account.Credentials) + refreshed.Credentials["access_token"] = "refreshed-after-lock" + refreshed.Credentials["expires_at"] = time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + refreshed.Credentials["_token_version"] = time.Now().UnixMilli() + repo.setAccount(&refreshed) + cache.mu.Lock() + cache.token = "refreshed-after-lock" + cache.mu.Unlock() + }() + + startedAt := time.Now() + token, err := provider.GetAccessToken(context.Background(), account) + require.NoError(t, err) + require.Equal(t, "refreshed-after-lock", token) + require.NotEqual(t, "expired-access-token", token) + require.GreaterOrEqual(t, time.Since(startedAt), 25*time.Millisecond, + "expired account metadata must prevent returning the old cached token") +} + +func TestGrokTokenProviderLockHeldTimeoutDoesNotReturnExpiredToken(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(57) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokTokenCacheForProviderTest{lockResult: false} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{}) + ctx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancel() + + token, err := provider.GetAccessToken(ctx, account) + require.Error(t, err) + require.Empty(t, token) +} + +func TestGrokTokenProviderLockHeldRejectsChangedTokenWithoutExpiry(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(58) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialRaceRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{lockResult: false, token: "expired-access-token"} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{}) + + go func() { + time.Sleep(30 * time.Millisecond) + refreshed := *account + refreshed.Credentials = shallowCopyMap(account.Credentials) + refreshed.Credentials["access_token"] = "changed-without-expiry" + delete(refreshed.Credentials, "expires_at") + refreshed.Credentials["_token_version"] = time.Now().UnixMilli() + repo.setAccount(&refreshed) + cache.mu.Lock() + cache.token = "changed-without-expiry" + cache.mu.Unlock() + }() + + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + token, err := provider.GetAccessToken(ctx, account) + + require.Error(t, err) + require.Empty(t, token, "an unbounded credential must not win the lock-held race") +} + +func TestGrokTokenProviderLockHeldUsesVersionedDBTokenAndRepairsStaleCache(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(60) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialRaceRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{lockResult: false, token: "expired-access-token"} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{}) + + go func() { + time.Sleep(30 * time.Millisecond) + refreshed := *account + refreshed.Credentials = shallowCopyMap(account.Credentials) + refreshed.Credentials["access_token"] = "db-authoritative-token" + refreshed.Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + refreshed.Credentials["_token_version"] = time.Now().UnixMilli() + repo.setAccount(&refreshed) + }() + + token, err := provider.GetAccessToken(context.Background(), account) + + require.NoError(t, err) + require.Equal(t, "db-authoritative-token", token) + require.Equal(t, "db-authoritative-token", cache.setToken) + require.Greater(t, cache.setTTL, time.Duration(0)) +} + +func TestGrokTokenProviderRejectsStaleDBTokenWithoutExpiry(t *testing.T) { + expiresAt := time.Now().Add(2 * grokTokenRefreshSkew).UTC().Format(time.RFC3339) + account := &Account{ + ID: 59, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{ + "access_token": "old-access-token", + "refresh_token": "refresh-token", + "expires_at": expiresAt, + }, + } + latest := *account + latest.Credentials = shallowCopyMap(account.Credentials) + latest.Credentials["access_token"] = "new-access-token-without-expiry" + latest.Credentials["_token_version"] = time.Now().UnixMilli() + delete(latest.Credentials, "expires_at") + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: &latest} + cache := &grokTokenCacheForProviderTest{} + provider := NewGrokTokenProvider(repo, cache) + + token, err := provider.GetAccessToken(context.Background(), account) + + require.ErrorIs(t, err, errGrokOAuthAccessTokenExpired) + require.Empty(t, token) +} + +func TestGrokTokenProviderRejectsIneligibleSelectedAccountBeforeWarmCache(t *testing.T) { + future := time.Now().Add(time.Hour) + tests := []struct { + name string + mutate func(*Account) + }{ + {name: "disabled", mutate: func(account *Account) { account.Status = StatusDisabled }}, + {name: "not schedulable", mutate: func(account *Account) { account.Schedulable = false }}, + {name: "temporarily unschedulable", mutate: func(account *Account) { account.TempUnschedulableUntil = &future }}, + {name: "rate limited", mutate: func(account *Account) { account.RateLimitResetAt = &future }}, + {name: "overloaded", mutate: func(account *Account) { account.OverloadUntil = &future }}, + } + + for index, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(90 + index)) + account.Credentials["access_token"] = "warm-cache-token" + account.Credentials["expires_at"] = time.Now().Add(2 * grokTokenRefreshSkew).UTC().Format(time.RFC3339) + tt.mutate(account) + cache := &grokTokenCacheForProviderTest{token: "warm-cache-token"} + provider := NewGrokTokenProvider(&tokenRefreshAccountRepo{}, cache) + + token, err := provider.GetAccessToken(context.Background(), account) + + require.ErrorIs(t, err, errOAuthRefreshAccountStateChanged) + require.Empty(t, token) + require.Zero(t, cache.getCalls, "an ineligible selected account must be rejected before cache lookup") + }) + } } diff --git a/backend/internal/service/grok_token_refresher.go b/backend/internal/service/grok_token_refresher.go index 92d88cc058..d2d4d534fc 100644 --- a/backend/internal/service/grok_token_refresher.go +++ b/backend/internal/service/grok_token_refresher.go @@ -22,13 +22,17 @@ func (r *GrokTokenRefresher) CacheKey(account *Account) string { } func (r *GrokTokenRefresher) CanRefresh(account *Account) bool { - return account != nil && account.Platform == PlatformGrok && account.Type == AccountTypeOAuth + return account != nil && account.Platform == PlatformGrok && account.Type == AccountTypeOAuth && + strings.TrimSpace(account.GetGrokRefreshToken()) != "" } func (r *GrokTokenRefresher) NeedsRefresh(account *Account, refreshWindow time.Duration) bool { if account == nil || strings.TrimSpace(account.GetGrokRefreshToken()) == "" { return false } + if strings.TrimSpace(account.GetGrokAccessToken()) == "" { + return true + } expiresAt := account.GetCredentialAsTime("expires_at") if expiresAt == nil { return true diff --git a/backend/internal/service/grok_upstream_url.go b/backend/internal/service/grok_upstream_url.go new file mode 100644 index 0000000000..ca2ba6b64d --- /dev/null +++ b/backend/internal/service/grok_upstream_url.go @@ -0,0 +1,90 @@ +package service + +import ( + "errors" + "fmt" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/xai" + "github.com/Wei-Shaw/sub2api/internal/util/urlvalidator" +) + +func grokBaseURLValidator(account *Account, cfg *config.Config) (xai.BaseURLValidator, error) { + if account == nil || !account.IsGrok() { + return nil, fmt.Errorf("grok account is required") + } + switch account.Type { + case AccountTypeOAuth: + // Subscription credentials are never governed by the operator's API-key + // URL policy. They stay pinned to the supported CLI gateway. + return redactedGrokBaseURLValidator(xai.ValidateTrustedBaseURL), nil + case AccountTypeAPIKey: + if cfg == nil { + return redactedGrokBaseURLValidator(xai.ValidateBaseURL), nil + } + if !cfg.Security.URLAllowlist.Enabled { + return redactedGrokBaseURLValidator(func(raw string) (string, error) { + return urlvalidator.ValidateURLFormat(raw, cfg.Security.URLAllowlist.AllowInsecureHTTP) + }), nil + } + return redactedGrokBaseURLValidator(func(raw string) (string, error) { + return urlvalidator.ValidateHTTPSURL(raw, urlvalidator.ValidationOptions{ + AllowedHosts: cfg.Security.URLAllowlist.UpstreamHosts, + RequireAllowlist: true, + AllowPrivate: cfg.Security.URLAllowlist.AllowPrivateHosts, + }) + }), nil + default: + return nil, fmt.Errorf("unsupported grok account type: %s", account.Type) + } +} + +func redactedGrokBaseURLValidator(validator xai.BaseURLValidator) xai.BaseURLValidator { + return func(raw string) (string, error) { + validated, err := validator(raw) + if err != nil { + return "", errors.New("base URL rejected by URL security policy") + } + return validated, nil + } +} + +func buildGrokResponsesURL(account *Account, cfg *config.Config) (string, error) { + validator, err := grokBaseURLValidator(account, cfg) + if err != nil { + return "", err + } + return xai.BuildResponsesURLWithValidator(account.GetGrokBaseURL(), validator) +} + +func buildGrokChatCompletionsURL(account *Account, cfg *config.Config) (string, error) { + validator, err := grokBaseURLValidator(account, cfg) + if err != nil { + return "", err + } + return xai.BuildChatCompletionsURLWithValidator(account.GetGrokBaseURL(), validator) +} + +func buildGrokMediaURL(account *Account, cfg *config.Config, endpoint GrokMediaEndpoint, requestID string) (string, error) { + validator, err := grokBaseURLValidator(account, cfg) + if err != nil { + return "", err + } + baseURL := account.GetGrokMediaBaseURL() + switch endpoint { + case GrokMediaEndpointImagesGenerations: + return xai.BuildImagesGenerationsURLWithValidator(baseURL, validator) + case GrokMediaEndpointImagesEdits: + return xai.BuildImagesEditsURLWithValidator(baseURL, validator) + case GrokMediaEndpointVideosGenerations: + return xai.BuildVideosGenerationsURLWithValidator(baseURL, validator) + case GrokMediaEndpointVideosEdits: + return xai.BuildVideosEditsURLWithValidator(baseURL, validator) + case GrokMediaEndpointVideosExtensions: + return xai.BuildVideosExtensionsURLWithValidator(baseURL, validator) + case GrokMediaEndpointVideoStatus: + return xai.BuildVideoURLWithValidator(baseURL, requestID, validator) + default: + return "", fmt.Errorf("unsupported grok media endpoint: %s", endpoint) + } +} diff --git a/backend/internal/service/grok_upstream_url_test.go b/backend/internal/service/grok_upstream_url_test.go new file mode 100644 index 0000000000..7919e47202 --- /dev/null +++ b/backend/internal/service/grok_upstream_url_test.go @@ -0,0 +1,122 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/xai" + "github.com/stretchr/testify/require" +) + +func TestGrokAPIKeyURLPolicyFollowsGlobalSecurityConfig(t *testing.T) { + account := &Account{ + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "base_url": "http://grok.example.test/v1", + }, + } + + t.Run("insecure HTTP enabled with allowlist disabled", func(t *testing.T) { + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = false + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + + responsesURL, err := buildGrokResponsesURL(account, cfg) + require.NoError(t, err) + require.Equal(t, "http://grok.example.test/v1/responses", responsesURL) + + chatURL, err := buildGrokChatCompletionsURL(account, cfg) + require.NoError(t, err) + require.Equal(t, "http://grok.example.test/v1/chat/completions", chatURL) + + mediaURL, err := buildGrokMediaURL(account, cfg, GrokMediaEndpointImagesGenerations, "") + require.NoError(t, err) + require.Equal(t, "http://grok.example.test/v1/images/generations", mediaURL) + }) + + t.Run("insecure HTTP disabled", func(t *testing.T) { + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = false + cfg.Security.URLAllowlist.AllowInsecureHTTP = false + + _, err := buildGrokResponsesURL(account, cfg) + require.EqualError(t, err, "invalid base url: base URL rejected by URL security policy") + }) + + t.Run("enabled allowlist remains HTTPS only", func(t *testing.T) { + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = true + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + cfg.Security.URLAllowlist.UpstreamHosts = []string{"grok.example.test"} + + _, err := buildGrokResponsesURL(account, cfg) + require.EqualError(t, err, "invalid base url: base URL rejected by URL security policy") + }) +} + +func TestGrokAPIKeyURLPolicyAppliesAllowlistAndPrivateHostControls(t *testing.T) { + account := &Account{ + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "base_url": "https://grok.example.test/v1", + }, + } + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = true + cfg.Security.URLAllowlist.UpstreamHosts = []string{"grok.example.test"} + + target, err := buildGrokResponsesURL(account, cfg) + require.NoError(t, err) + require.Equal(t, "https://grok.example.test/v1/responses", target) + + cfg.Security.URLAllowlist.UpstreamHosts = []string{"other.example.test"} + _, err = buildGrokResponsesURL(account, cfg) + require.EqualError(t, err, "invalid base url: base URL rejected by URL security policy") + + account.Credentials["base_url"] = "https://127.0.0.1/v1" + cfg.Security.URLAllowlist.UpstreamHosts = []string{"127.0.0.1"} + _, err = buildGrokResponsesURL(account, cfg) + require.EqualError(t, err, "invalid base url: base URL rejected by URL security policy") + + cfg.Security.URLAllowlist.AllowPrivateHosts = true + target, err = buildGrokResponsesURL(account, cfg) + require.NoError(t, err) + require.Equal(t, "https://127.0.0.1/v1/responses", target) +} + +func TestGrokAPIKeyURLPolicyRedactsMalformedConfiguredURL(t *testing.T) { + account := &Account{ + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "base_url": "https://%zz:secret@grok.example.test/v1", + }, + } + cfg := &config.Config{} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + + _, err := buildGrokResponsesURL(account, cfg) + require.EqualError(t, err, "invalid base url: base URL rejected by URL security policy") + require.NotContains(t, err.Error(), "secret") +} + +func TestGrokOAuthURLPolicyIgnoresAPIKeyOverrides(t *testing.T) { + account := &Account{ + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "base_url": "http://attacker.example.test/v1", + }, + } + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = false + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + + target, err := buildGrokResponsesURL(account, cfg) + require.NoError(t, err) + require.Equal(t, xai.DefaultCLIBaseURL+"/responses", target) +} diff --git a/backend/internal/service/image_generation_intent.go b/backend/internal/service/image_generation_intent.go index 613f11d048..72f3be7db6 100644 --- a/backend/internal/service/image_generation_intent.go +++ b/backend/internal/service/image_generation_intent.go @@ -47,16 +47,36 @@ func IsImageGenerationIntent(endpoint string, requestedModel string, body []byte if len(body) == 0 || !gjson.ValidBytes(body) { return false } - if model := strings.TrimSpace(gjson.GetBytes(body, "model").String()); isOpenAIImageGenerationModel(model) { - return true - } - if openAIJSONToolsContainImageGeneration(gjson.GetBytes(body, "tools")) { - return true - } - if openAIJSONInputContainsImageGenTool(gjson.GetBytes(body, "input")) { - return true - } - return openAIJSONToolChoiceSelectsImageGeneration(gjson.GetBytes(body, "tool_choice")) + + var modelSeen, toolsSeen, inputSeen, toolChoiceSeen bool + imageIntent := false + parseRawJSONView(body).ForEach(func(key, value gjson.Result) bool { + // GetBytes returns the first duplicate key; retain that behavior while walking the root once. + switch key.Str { + case "model": + if !modelSeen { + modelSeen = true + imageIntent = isOpenAIImageGenerationModel(strings.TrimSpace(value.String())) + } + case "tools": + if !toolsSeen { + toolsSeen = true + imageIntent = openAIJSONToolsContainImageGeneration(value) + } + case "input": + if !inputSeen { + inputSeen = true + imageIntent = openAIJSONInputContainsImageGenTool(value) + } + case "tool_choice": + if !toolChoiceSeen { + toolChoiceSeen = true + imageIntent = openAIJSONToolChoiceSelectsImageGeneration(value) + } + } + return !imageIntent && (!modelSeen || !toolsSeen || !inputSeen || !toolChoiceSeen) + }) + return imageIntent } // IsImageGenerationIntentMap is the map-backed variant used after service-side request mutation. diff --git a/backend/internal/service/image_generation_intent_benchmark_test.go b/backend/internal/service/image_generation_intent_benchmark_test.go new file mode 100644 index 0000000000..d0df0c28af --- /dev/null +++ b/backend/internal/service/image_generation_intent_benchmark_test.go @@ -0,0 +1,59 @@ +package service + +import ( + "strings" + "testing" +) + +var imageGenerationIntentBenchmarkResult bool + +func BenchmarkIsImageGenerationIntent(b *testing.B) { + largeInput := strings.Repeat("x", 1<<20) + benchmarks := []struct { + name string + body []byte + want bool + }{ + { + name: "1MiBInputNoImage", + body: []byte(`{"model":"gpt-5.5","tools":[],"input":"` + largeInput + `","tool_choice":"auto"}`), + want: false, + }, + { + name: "1MiBInputLeadingImageTool", + body: []byte(`{"model":"gpt-5.5","tools":[{"type":"image_generation"}],"input":"` + largeInput + `"}`), + want: true, + }, + { + name: "1MiBInputTrailingToolChoice", + body: []byte(`{"model":"gpt-5.5","tools":[],"input":"` + largeInput + `","tool_choice":{"type":"image_generation"}}`), + want: true, + }, + { + name: "Invalid1MiBJSON", + body: []byte(`{"model":"gpt-5.5","input":"` + largeInput), + want: false, + }, + { + name: "DuplicateKeysFirstWins", + body: []byte(`{"model":"gpt-5.5","model":"gpt-image-2","tools":[],"tools":[{"type":"image_generation"}],"input":"` + largeInput + `","tool_choice":"auto","tool_choice":{"type":"image_generation"}}`), + want: false, + }, + } + + for _, benchmark := range benchmarks { + b.Run(benchmark.name, func(b *testing.B) { + if got := IsImageGenerationIntent("/v1/responses", "gpt-5.5", benchmark.body); got != benchmark.want { + b.Fatalf("IsImageGenerationIntent() = %v, want %v", got, benchmark.want) + } + b.ReportAllocs() + b.SetBytes(int64(len(benchmark.body))) + b.ResetTimer() + var result bool + for i := 0; i < b.N; i++ { + result = IsImageGenerationIntent("/v1/responses", "gpt-5.5", benchmark.body) + } + imageGenerationIntentBenchmarkResult = result + }) + } +} diff --git a/backend/internal/service/image_generation_intent_test.go b/backend/internal/service/image_generation_intent_test.go index 7f3ac8a611..c7c7f9db4e 100644 --- a/backend/internal/service/image_generation_intent_test.go +++ b/backend/internal/service/image_generation_intent_test.go @@ -1,6 +1,7 @@ package service import ( + "strings" "testing" "github.com/stretchr/testify/require" @@ -106,6 +107,77 @@ func TestIsImageGenerationIntent(t *testing.T) { } } +func TestIsImageGenerationIntentJSONSemantics(t *testing.T) { + largeInput := strings.Repeat("x", 1<<20) + tests := []struct { + name string + endpoint string + body []byte + want bool + }{ + { + name: "chat body image model", + endpoint: "/v1/chat/completions", + body: []byte(`{"model":"gpt-image-2"}`), + want: true, + }, + { + name: "large responses input with trailing namespace tool choice", + endpoint: "/v1/responses", + body: []byte(`{"model":"gpt-5.5","input":"` + largeInput + `","tool_choice":{"type":"namespace","name":"image_gen"}}`), + want: true, + }, + { + name: "invalid json with image tool", + endpoint: "/v1/responses", + body: []byte(`{"tools":[{"type":"image_generation"}]`), + want: false, + }, + { + name: "duplicate model uses first value", + endpoint: "/v1/responses", + body: []byte(`{"model":"gpt-5.5","model":"gpt-image-2"}`), + want: false, + }, + { + name: "duplicate null model still uses first value", + endpoint: "/v1/responses", + body: []byte(`{"model":null,"model":"gpt-image-2"}`), + want: false, + }, + { + name: "duplicate tools uses first value", + endpoint: "/v1/responses", + body: []byte(`{"tools":[],"tools":[{"type":"image_generation"}]}`), + want: false, + }, + { + name: "duplicate input uses first value", + endpoint: "/v1/responses", + body: []byte(`{"input":[],"input":[{"type":"additional_tools","tools":[{"type":"namespace","name":"image_gen"}]}]}`), + want: false, + }, + { + name: "duplicate tool choice uses first value", + endpoint: "/v1/responses", + body: []byte(`{"tool_choice":"required","tool_choice":{"type":"image_generation"}}`), + want: false, + }, + { + name: "escaped top level key", + endpoint: "/v1/responses", + body: []byte(`{"tool_\u0063hoice":{"type":"image_generation"}}`), + want: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + require.Equal(t, tt.want, IsImageGenerationIntent(tt.endpoint, "gpt-5.5", tt.body)) + }) + } +} + func TestIsImageGenerationIntentMap_NamespaceImageGen(t *testing.T) { tests := []struct { name string diff --git a/backend/internal/service/oauth_refresh_api.go b/backend/internal/service/oauth_refresh_api.go index 571e9ecdb7..c940bd335a 100644 --- a/backend/internal/service/oauth_refresh_api.go +++ b/backend/internal/service/oauth_refresh_api.go @@ -2,6 +2,7 @@ package service import ( "context" + "errors" "fmt" "log/slog" "strconv" @@ -19,23 +20,115 @@ type OAuthRefreshExecutor interface { CacheKey(account *Account) string } -const defaultRefreshLockTTL = 60 * time.Second +// GrokOAuthRefreshSuccessRepository is the persistence boundary for a +// provider-issued Grok credential rotation. Implementations must compare the +// complete credential document and proxy used by the upstream attempt, and +// atomically publish scheduler invalidation with a successful update. +type GrokOAuthRefreshSuccessRepository interface { + UpdateGrokOAuthCredentialsIfUnchanged( + ctx context.Context, + id int64, + expectedCredentials map[string]any, + expectedProxyID *int64, + credentials map[string]any, + ) (bool, error) +} + +const ( + defaultRefreshLockTTL = 60 * time.Second + defaultRefreshLockReleaseTimeout = 2 * time.Second + defaultRefreshPostPersistCleanupTimeout = 2 * time.Second +) + +var ( + errOAuthRefreshAccountRereadFailed = errors.New("oauth refresh account reread failed") + errOAuthRefreshAccountStateChanged = errors.New("oauth refresh account state changed") + errOAuthRefreshCredentialPersist = errors.New("oauth refresh credential persistence failed") +) + +type oauthRefreshRequestPathKey struct{} + +func withOAuthRefreshRequestPath(ctx context.Context) context.Context { + return context.WithValue(ctx, oauthRefreshRequestPathKey{}, true) +} + +func isOAuthRefreshRequestPath(ctx context.Context) bool { + requestPath, _ := ctx.Value(oauthRefreshRequestPathKey{}).(bool) + return requestPath +} + +type contextMutex struct { + token chan struct{} +} + +// Keep the request-path credential mutation lock API introduced by #4212 +// while sharing the context-aware mutex implementation used by pool refresh. +type oauthRefreshLocalLock = contextMutex + +func newOAuthRefreshLocalLock() *oauthRefreshLocalLock { + return newContextMutex() +} + +type oauthRefreshStateUnavailableError struct { + err error +} + +func (e *oauthRefreshStateUnavailableError) Error() string { + return "OAuth refresh account state is unavailable" +} + +func (e *oauthRefreshStateUnavailableError) Unwrap() error { + if e == nil { + return nil + } + return e.err +} + +func newContextMutex() *contextMutex { + return &contextMutex{token: make(chan struct{}, 1)} +} + +func (m *contextMutex) Lock(ctx context.Context) error { + select { + case m.token <- struct{}{}: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func (m *contextMutex) Unlock() { + <-m.token +} // OAuthRefreshResult 统一刷新结果 type OAuthRefreshResult struct { Refreshed bool // 实际执行了刷新 NewCredentials map[string]any // 刷新后的 credentials(nil 表示未刷新) - Account *Account // 从 DB 重新读取的最新 account + Account *Account // 成功时为最新 account;刷新错误时为实际尝试的凭据快照 LockHeld bool // 锁被其他 worker 持有(未执行刷新) } +func snapshotOAuthRefreshAccount(account *Account) *Account { + if account == nil { + return nil + } + snapshot := *account + snapshot.Credentials = shallowCopyMap(account.Credentials) + if account.ProxyID != nil { + proxyID := *account.ProxyID + snapshot.ProxyID = &proxyID + } + return &snapshot +} + // OAuthRefreshAPI 统一的 OAuth Token 刷新入口 // 封装分布式锁、进程内互斥锁、DB 重读、已刷新检查、竞争恢复等通用逻辑 type OAuthRefreshAPI struct { accountRepo AccountRepository tokenCache GeminiTokenCache // 可选,nil = 无分布式锁 lockTTL time.Duration - localLocks sync.Map // key: cacheKey string -> value: *sync.Mutex + localLocks sync.Map // key: cacheKey string -> value: *contextMutex } // NewOAuthRefreshAPI 创建统一刷新 API @@ -53,11 +146,11 @@ func NewOAuthRefreshAPI(accountRepo AccountRepository, tokenCache GeminiTokenCac } // getLocalLock 返回指定 cacheKey 的进程内互斥锁 -func (api *OAuthRefreshAPI) getLocalLock(cacheKey string) *sync.Mutex { - actual, _ := api.localLocks.LoadOrStore(cacheKey, &sync.Mutex{}) - mu, ok := actual.(*sync.Mutex) +func (api *OAuthRefreshAPI) getLocalLock(cacheKey string) *contextMutex { + actual, _ := api.localLocks.LoadOrStore(cacheKey, newContextMutex()) + mu, ok := actual.(*contextMutex) if !ok { - mu = &sync.Mutex{} + mu = newContextMutex() api.localLocks.Store(cacheKey, mu) } return mu @@ -78,15 +171,26 @@ func (api *OAuthRefreshAPI) RefreshIfNeeded( executor OAuthRefreshExecutor, refreshWindow time.Duration, ) (*OAuthRefreshResult, error) { + if api == nil || api.accountRepo == nil { + return nil, errors.New("oauth refresh account repository is not configured") + } + if account == nil { + return nil, errors.New("oauth refresh account is nil") + } + if executor == nil { + return nil, errors.New("oauth refresh executor is nil") + } + requestPath := isOAuthRefreshRequestPath(ctx) cacheKey := executor.CacheKey(account) // 0. 获取进程内互斥锁(防止同一进程内的并发刷新竞争) localMu := api.getLocalLock(cacheKey) - localMu.Lock() + if err := localMu.Lock(ctx); err != nil { + return nil, fmt.Errorf("oauth refresh local lock: %w", err) + } defer localMu.Unlock() // 1. 获取分布式锁 - lockAcquired := false if api.tokenCache != nil { acquired, lockErr := api.tokenCache.AcquireRefreshLock(ctx, cacheKey, api.lockTTL) if lockErr != nil { @@ -100,22 +204,46 @@ func (api *OAuthRefreshAPI) RefreshIfNeeded( // 锁被其他 worker 持有 return &OAuthRefreshResult{LockHeld: true}, nil } else { - lockAcquired = true - defer func() { _ = api.tokenCache.ReleaseRefreshLock(ctx, cacheKey) }() + defer api.releaseRefreshLock(ctx, cacheKey) } } // 2. 从 DB 重读最新 account(锁保护下,确保使用最新的 refresh_token) freshAccount, err := api.accountRepo.GetByID(ctx, account.ID) if err != nil { - slog.Warn("oauth_refresh_db_reread_failed", - "account_id", account.ID, - "error", err, - ) - // 降级使用传入的 account - freshAccount = account - } else if freshAccount == nil { - freshAccount = account + if requestPath { + return nil, fmt.Errorf("%w: %v", errOAuthRefreshAccountRereadFailed, err) + } + return nil, &oauthRefreshStateUnavailableError{err: err} + } + if freshAccount == nil { + if requestPath { + return nil, fmt.Errorf("%w: account not found", errOAuthRefreshAccountStateChanged) + } + return nil, &oauthRefreshStateUnavailableError{err: fmt.Errorf("account not found")} + } + if freshAccount.ID != account.ID { + return nil, fmt.Errorf("%w: account identity mismatch", errOAuthRefreshAccountRereadFailed) + } + if !freshAccount.IsActive() { + if requestPath { + return nil, fmt.Errorf("%w: account is not active", errOAuthRefreshAccountStateChanged) + } + return &OAuthRefreshResult{Account: freshAccount}, nil + } + if requestPath && freshAccount.Platform == PlatformGrok { + if eligibilityErr := grokOAuthRequestAccountEligibilityError(freshAccount); eligibilityErr != nil { + return nil, withGrokCredentialFailureSnapshot(eligibilityErr, freshAccount) + } + } + if !executor.CanRefresh(freshAccount) { + if requestPath && freshAccount.IsGrokOAuth() && strings.TrimSpace(freshAccount.GetGrokRefreshToken()) == "" { + return nil, withGrokCredentialFailureSnapshot(errGrokOAuthRefreshTokenMissing, freshAccount) + } + if requestPath { + return nil, fmt.Errorf("%w: account is no longer refreshable", errOAuthRefreshAccountStateChanged) + } + return &OAuthRefreshResult{Account: freshAccount}, nil } // 3. 二次检查是否仍需刷新(另一条路径可能已刷新) @@ -126,12 +254,23 @@ func (api *OAuthRefreshAPI) RefreshIfNeeded( } // 4. 执行平台特定刷新逻辑 + attemptedAccount := snapshotOAuthRefreshAccount(freshAccount) newCredentials, refreshErr := executor.Refresh(ctx, freshAccount) + if ctxErr := ctx.Err(); ctxErr != nil { + // A provider implementation may ignore cancellation and return late + // credentials. Never persist them after the attempt/cycle boundary. + return nil, ctxErr + } if refreshErr != nil { // 竞争恢复:invalid_grant 可能是另一个 worker 已消费了旧 refresh_token // 重新读取 DB,如果 refresh_token 已更新则说明是竞争,返回成功 if isInvalidGrantError(refreshErr) { if recoveredAccount, recovered := api.tryRecoverFromRefreshRace(ctx, freshAccount); recovered { + if requestPath && recoveredAccount.Platform == PlatformGrok { + if eligibilityErr := grokOAuthRequestAccountEligibilityError(recoveredAccount); eligibilityErr != nil { + return nil, withGrokCredentialFailureSnapshot(eligibilityErr, recoveredAccount) + } + } slog.Info("oauth_refresh_race_recovered", "account_id", freshAccount.ID, "platform", freshAccount.Platform, @@ -141,22 +280,90 @@ func (api *OAuthRefreshAPI) RefreshIfNeeded( }, nil } } - return nil, refreshErr + // Preserve the exact account snapshot used by the failed upstream call. + // Callers can then conditionally mutate only that credential version and + // avoid quarantining a concurrently reauthorized account. + result := &OAuthRefreshResult{Account: attemptedAccount} + if requestPath && attemptedAccount.Platform == PlatformGrok { + return result, withGrokCredentialFailureSnapshot(refreshErr, attemptedAccount) + } + return result, refreshErr } // 5. 设置版本号 + 更新 DB if newCredentials != nil { newCredentials["_token_version"] = time.Now().UnixMilli() - if updateErr := persistAccountCredentials(ctx, api.accountRepo, freshAccount, newCredentials); updateErr != nil { + if freshAccount.IsGrokOAuth() { + conditionalRepo, ok := api.accountRepo.(GrokOAuthRefreshSuccessRepository) + if !ok { + return nil, &providerConfigurationRefreshError{ + err: fmt.Errorf("grok OAuth refresh success CAS repository is not configured"), + } + } + applied, updateErr := conditionalRepo.UpdateGrokOAuthCredentialsIfUnchanged( + ctx, + freshAccount.ID, + attemptedAccount.Credentials, + attemptedAccount.ProxyID, + newCredentials, + ) + if updateErr != nil { + slog.Error("oauth_refresh_update_failed", + "account_id", freshAccount.ID, + "platform", freshAccount.Platform, + "error", updateErr, + ) + // The provider may have rotated and consumed the refresh token. + // Retrying after an ambiguous local persistence result can turn a + // healthy account into invalid_grant, so contain this provider cycle. + return nil, &providerCycleContainmentRefreshError{ + err: fmt.Errorf("OAuth refresh succeeded but credential persistence failed: %w", updateErr), + } + } + if !applied { + currentAccount, readErr := api.accountRepo.GetByID(ctx, freshAccount.ID) + if readErr != nil || currentAccount == nil { + if readErr == nil { + readErr = fmt.Errorf("account not found after Grok OAuth success CAS miss") + } + return nil, &providerCycleContainmentRefreshError{ + err: fmt.Errorf("grok OAuth success CAS lost and current state is unavailable: %w", readErr), + } + } + slog.Info("oauth_refresh_success_cas_skipped_stale_credentials", + "account_id", freshAccount.ID, + "platform", freshAccount.Platform, + ) + return &OAuthRefreshResult{Account: currentAccount}, nil + } + durableAccount, readErr := api.loadGrokDurableAccountAfterPersist(ctx, cacheKey, freshAccount.ID) + if readErr != nil || durableAccount == nil { + if readErr == nil { + readErr = fmt.Errorf("account not found after Grok OAuth success CAS") + } + return nil, &providerCycleContainmentRefreshError{ + err: fmt.Errorf("grok OAuth success persisted but durable account state is unavailable: %w", readErr), + } + } + // The CAS changes credentials only. A concurrent admin or scheduler + // mutation may have changed status, schedulability, or cooldown fields + // while the provider call was in flight. Return the durable row so + // post-refresh cache publication cannot restore that stale snapshot. + freshAccount = durableAccount + } else if updateErr := persistAccountCredentials(ctx, api.accountRepo, freshAccount, newCredentials); updateErr != nil { slog.Error("oauth_refresh_update_failed", "account_id", freshAccount.ID, "error", updateErr, ) - return nil, fmt.Errorf("oauth refresh succeeded but DB update failed: %w", updateErr) + return nil, fmt.Errorf("%w: %v", errOAuthRefreshCredentialPersist, updateErr) } } - _ = lockAcquired // suppress unused warning when tokenCache is nil + if requestPath && freshAccount.Platform == PlatformGrok { + if eligibilityErr := grokOAuthRequestAccountEligibilityError(freshAccount); eligibilityErr != nil { + return nil, withGrokCredentialFailureSnapshot(eligibilityErr, freshAccount) + } + } return &OAuthRefreshResult{ Refreshed: true, @@ -165,6 +372,42 @@ func (api *OAuthRefreshAPI) RefreshIfNeeded( }, nil } +func (api *OAuthRefreshAPI) releaseRefreshLock(parent context.Context, cacheKey string) { + cleanupParent := context.Background() + if parent != nil { + cleanupParent = context.WithoutCancel(parent) + } + ctx, cancel := context.WithTimeout(cleanupParent, defaultRefreshLockReleaseTimeout) + defer cancel() + if err := api.tokenCache.ReleaseRefreshLock(ctx, cacheKey); err != nil { + slog.Warn("oauth_refresh_lock_release_failed", "cache_key", cacheKey, "error", err) + } +} + +func (api *OAuthRefreshAPI) loadGrokDurableAccountAfterPersist(parent context.Context, cacheKey string, accountID int64) (*Account, error) { + cleanupParent := context.Background() + if parent != nil { + cleanupParent = context.WithoutCancel(parent) + } + ctx, cancel := context.WithTimeout(cleanupParent, defaultRefreshPostPersistCleanupTimeout) + defer cancel() + + // A successful rotation can revoke the access token still cached from the + // pre-rotation credential document. Trigger deletion at the commit boundary, + // even if the attempt/parent context was canceled immediately after CAS. + if api.tokenCache != nil { + if err := api.tokenCache.DeleteAccessToken(ctx, cacheKey); err != nil { + slog.Warn("oauth_refresh_post_persist_cache_delete_failed", + "account_id", accountID, + "cache_key", cacheKey, + "error", err, + ) + } + } + + return api.accountRepo.GetByID(ctx, accountID) +} + // isInvalidGrantError 检查错误是否为 invalid_grant func isInvalidGrantError(err error) bool { return err != nil && strings.Contains(strings.ToLower(err.Error()), "invalid_grant") diff --git a/backend/internal/service/oauth_refresh_api_test.go b/backend/internal/service/oauth_refresh_api_test.go index cacffddc59..e92bd99f02 100644 --- a/backend/internal/service/oauth_refresh_api_test.go +++ b/backend/internal/service/oauth_refresh_api_test.go @@ -5,6 +5,7 @@ package service import ( "context" "errors" + "reflect" "sync" "testing" "time" @@ -17,18 +18,38 @@ import ( // refreshAPIAccountRepo implements AccountRepository for OAuthRefreshAPI tests. type refreshAPIAccountRepo struct { mockAccountRepoForGemini - account *Account // returned by GetByID - getByIDErr error - updateErr error - updateCalls int - updateCredentialsCalls int + account *Account // returned by GetByID + getByIDErr error + getByIDCalls int + getByIDErrAfterCall int + getByIDErrAfterCallErr error + updateErr error + updateCalls int + updateCredentialsCalls int + successCASCalls int + beforeSuccessCAS func(*refreshAPIAccountRepo) + lastExpectedCredentials map[string]any + lastExpectedProxyID *int64 } func (r *refreshAPIAccountRepo) GetByID(_ context.Context, _ int64) (*Account, error) { + r.getByIDCalls++ + if r.getByIDErrAfterCall > 0 && r.getByIDCalls >= r.getByIDErrAfterCall { + return nil, r.getByIDErrAfterCallErr + } if r.getByIDErr != nil { return nil, r.getByIDErr } - return r.account, nil + return activeRefreshAPITestAccount(r.account), nil +} + +func activeRefreshAPITestAccount(account *Account) *Account { + if account == nil || account.Status != "" { + return account + } + copy := *account + copy.Status = StatusActive + return © } func (r *refreshAPIAccountRepo) Update(_ context.Context, _ *Account) error { @@ -49,15 +70,60 @@ func (r *refreshAPIAccountRepo) UpdateCredentials(_ context.Context, id int64, c return nil } -// refreshAPIExecutorStub implements OAuthRefreshExecutor for tests. -type refreshAPIExecutorStub struct { - needsRefresh bool - credentials map[string]any - err error - refreshCalls int +func (r *refreshAPIAccountRepo) UpdateGrokOAuthCredentialsIfUnchanged( + _ context.Context, + id int64, + expectedCredentials map[string]any, + expectedProxyID *int64, + credentials map[string]any, +) (bool, error) { + r.successCASCalls++ + r.lastExpectedCredentials = shallowCopyMap(expectedCredentials) + if expectedProxyID != nil { + proxyID := *expectedProxyID + r.lastExpectedProxyID = &proxyID + } else { + r.lastExpectedProxyID = nil + } + if r.beforeSuccessCAS != nil { + r.beforeSuccessCAS(r) + } + if r.updateErr != nil { + return false, r.updateErr + } + if r.account == nil || r.account.ID != id || r.account.Platform != PlatformGrok || + r.account.Type != AccountTypeOAuth || + !reflect.DeepEqual(r.account.Credentials, expectedCredentials) || + !reflect.DeepEqual(r.account.ProxyID, expectedProxyID) { + return false, nil + } + r.updateCalls++ + r.updateCredentialsCalls++ + r.account.Credentials = shallowCopyMap(credentials) + return true, nil } -func (e *refreshAPIExecutorStub) CanRefresh(_ *Account) bool { return true } +// refreshAPIExecutorStub implements OAuthRefreshExecutor for tests. +type refreshAPIExecutorStub struct { + needsRefresh bool + cannotRefresh bool + credentials map[string]any + err error + refreshCalls int + canRefresh func(*Account) bool + onRefresh func() + delay time.Duration +} + +func (e *refreshAPIExecutorStub) CanRefresh(account *Account) bool { + if e.cannotRefresh { + return false + } + if e.canRefresh != nil { + return e.canRefresh(account) + } + return true +} func (e *refreshAPIExecutorStub) NeedsRefresh(_ *Account, _ time.Duration) bool { return e.needsRefresh @@ -65,6 +131,12 @@ func (e *refreshAPIExecutorStub) NeedsRefresh(_ *Account, _ time.Duration) bool func (e *refreshAPIExecutorStub) Refresh(_ context.Context, _ *Account) (map[string]any, error) { e.refreshCalls++ + if e.delay > 0 { + time.Sleep(e.delay) + } + if e.onRefresh != nil { + e.onRefresh() + } if e.err != nil { return nil, e.err } @@ -77,9 +149,13 @@ func (e *refreshAPIExecutorStub) CacheKey(account *Account) string { // refreshAPICacheStub implements GeminiTokenCache for OAuthRefreshAPI tests. type refreshAPICacheStub struct { - lockResult bool - lockErr error - releaseCalls int + lockResult bool + lockErr error + releaseCalls int + releaseCtxErr error + deleteCalls int + deleteKey string + deleteCtxErr error } func (c *refreshAPICacheStub) GetAccessToken(context.Context, string) (string, error) { @@ -90,21 +166,27 @@ func (c *refreshAPICacheStub) SetAccessToken(context.Context, string, string, ti return nil } -func (c *refreshAPICacheStub) DeleteAccessToken(context.Context, string) error { return nil } +func (c *refreshAPICacheStub) DeleteAccessToken(ctx context.Context, key string) error { + c.deleteCalls++ + c.deleteKey = key + c.deleteCtxErr = ctx.Err() + return nil +} func (c *refreshAPICacheStub) AcquireRefreshLock(context.Context, string, time.Duration) (bool, error) { return c.lockResult, c.lockErr } -func (c *refreshAPICacheStub) ReleaseRefreshLock(context.Context, string) error { +func (c *refreshAPICacheStub) ReleaseRefreshLock(ctx context.Context, _ string) error { c.releaseCalls++ + c.releaseCtxErr = ctx.Err() return nil } // ========== RefreshIfNeeded tests ========== func TestRefreshIfNeeded_Success(t *testing.T) { - account := &Account{ID: 1, Platform: PlatformAnthropic, Type: AccountTypeOAuth} + account := &Account{ID: 1, Platform: PlatformAnthropic, Type: AccountTypeOAuth, Status: StatusActive} repo := &refreshAPIAccountRepo{account: account} cache := &refreshAPICacheStub{lockResult: true} executor := &refreshAPIExecutorStub{ @@ -132,6 +214,7 @@ func TestRefreshIfNeeded_UpdateCredentialsPreservesRateLimitState(t *testing.T) ID: 11, Platform: PlatformGemini, Type: AccountTypeOAuth, + Status: StatusActive, RateLimitResetAt: &resetAt, } repo := &refreshAPIAccountRepo{account: account} @@ -152,7 +235,7 @@ func TestRefreshIfNeeded_UpdateCredentialsPreservesRateLimitState(t *testing.T) } func TestRefreshIfNeeded_LockHeld(t *testing.T) { - account := &Account{ID: 2, Platform: PlatformAnthropic} + account := &Account{ID: 2, Platform: PlatformAnthropic, Status: StatusActive} repo := &refreshAPIAccountRepo{account: account} cache := &refreshAPICacheStub{lockResult: false} // lock not acquired executor := &refreshAPIExecutorStub{needsRefresh: true} @@ -168,7 +251,7 @@ func TestRefreshIfNeeded_LockHeld(t *testing.T) { } func TestRefreshIfNeeded_LockErrorDegrades(t *testing.T) { - account := &Account{ID: 3, Platform: PlatformGemini, Type: AccountTypeOAuth} + account := &Account{ID: 3, Platform: PlatformGemini, Type: AccountTypeOAuth, Status: StatusActive} repo := &refreshAPIAccountRepo{account: account} cache := &refreshAPICacheStub{lockErr: errors.New("redis down")} // lock error executor := &refreshAPIExecutorStub{ @@ -187,7 +270,7 @@ func TestRefreshIfNeeded_LockErrorDegrades(t *testing.T) { } func TestRefreshIfNeeded_NoCacheNoLock(t *testing.T) { - account := &Account{ID: 4, Platform: PlatformGemini, Type: AccountTypeOAuth} + account := &Account{ID: 4, Platform: PlatformGemini, Type: AccountTypeOAuth, Status: StatusActive} repo := &refreshAPIAccountRepo{account: account} executor := &refreshAPIExecutorStub{ needsRefresh: true, @@ -203,7 +286,7 @@ func TestRefreshIfNeeded_NoCacheNoLock(t *testing.T) { } func TestRefreshIfNeeded_AlreadyRefreshed(t *testing.T) { - account := &Account{ID: 5, Platform: PlatformAnthropic} + account := &Account{ID: 5, Platform: PlatformAnthropic, Status: StatusActive} repo := &refreshAPIAccountRepo{account: account} cache := &refreshAPICacheStub{lockResult: true} executor := &refreshAPIExecutorStub{needsRefresh: false} // already refreshed @@ -220,7 +303,7 @@ func TestRefreshIfNeeded_AlreadyRefreshed(t *testing.T) { } func TestRefreshIfNeeded_RefreshError(t *testing.T) { - account := &Account{ID: 6, Platform: PlatformAnthropic} + account := &Account{ID: 6, Platform: PlatformAnthropic, Status: StatusActive} repo := &refreshAPIAccountRepo{account: account} cache := &refreshAPICacheStub{lockResult: true} executor := &refreshAPIExecutorStub{ @@ -232,14 +315,16 @@ func TestRefreshIfNeeded_RefreshError(t *testing.T) { result, err := api.RefreshIfNeeded(context.Background(), account, executor, 3*time.Minute) require.Error(t, err) - require.Nil(t, result) + require.NotNil(t, result) + require.NotNil(t, result.Account) + require.Equal(t, account.ID, result.Account.ID) require.Contains(t, err.Error(), "invalid_grant") require.Equal(t, 0, repo.updateCalls) // no DB update on refresh error require.Equal(t, 1, cache.releaseCalls) // lock still released via defer } func TestRefreshIfNeeded_DBUpdateError(t *testing.T) { - account := &Account{ID: 7, Platform: PlatformGemini, Type: AccountTypeOAuth} + account := &Account{ID: 7, Platform: PlatformGemini, Type: AccountTypeOAuth, Status: StatusActive} repo := &refreshAPIAccountRepo{ account: account, updateErr: errors.New("db connection lost"), @@ -255,12 +340,129 @@ func TestRefreshIfNeeded_DBUpdateError(t *testing.T) { require.Error(t, err) require.Nil(t, result) - require.Contains(t, err.Error(), "DB update failed") + require.ErrorIs(t, err, errOAuthRefreshCredentialPersist) require.Equal(t, 1, repo.updateCalls) // attempted } +func TestRefreshIfNeeded_GrokSuccessCASLetsConcurrentReauthorizationWin(t *testing.T) { + proxyID := int64(17) + account := &Account{ + ID: 70, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + ProxyID: &proxyID, + Credentials: map[string]any{ + "access_token": "attempted-access", + "refresh_token": "attempted-refresh", + "_token_version": int64(1), + }, + } + repo := &refreshAPIAccountRepo{account: account} + repo.beforeSuccessCAS = func(r *refreshAPIAccountRepo) { + repairedProxyID := int64(23) + r.account.ProxyID = &repairedProxyID + r.account.Credentials = map[string]any{ + "access_token": "reauthorized-access", + "refresh_token": "reauthorized-refresh", + "_token_version": int64(2), + } + } + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + credentials: map[string]any{ + "access_token": "provider-access", + "refresh_token": "provider-refresh", + }, + } + + result, err := NewOAuthRefreshAPI(repo, nil).RefreshIfNeeded(context.Background(), account, executor, time.Hour) + + require.NoError(t, err) + require.NotNil(t, result) + require.False(t, result.Refreshed, "a lost success CAS is an already-refreshed skip") + require.Nil(t, result.NewCredentials) + require.Equal(t, "reauthorized-refresh", result.Account.GetGrokRefreshToken()) + require.NotNil(t, result.Account.ProxyID) + require.Equal(t, int64(23), *result.Account.ProxyID) + require.Equal(t, 1, repo.successCASCalls) + require.Equal(t, "attempted-refresh", repo.lastExpectedCredentials["refresh_token"]) + require.NotNil(t, repo.lastExpectedProxyID) + require.Equal(t, proxyID, *repo.lastExpectedProxyID) + require.Zero(t, repo.updateCredentialsCalls, "the provider result must not overwrite a concurrent repair") +} + +func TestRefreshIfNeeded_GrokSuccessPersistenceFailureIsProviderContainment(t *testing.T) { + account := &Account{ + ID: 71, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Credentials: map[string]any{ + "access_token": "attempted-access", + "refresh_token": "attempted-refresh", + }, + } + repo := &refreshAPIAccountRepo{account: account, updateErr: errors.New("database unavailable")} + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + credentials: map[string]any{ + "access_token": "provider-access", + "refresh_token": "provider-refresh", + }, + } + + result, err := NewOAuthRefreshAPI(repo, nil).RefreshIfNeeded(context.Background(), account, executor, time.Hour) + + require.Error(t, err) + require.Nil(t, result) + var containmentErr *providerCycleContainmentRefreshError + require.ErrorAs(t, err, &containmentErr) + require.Equal(t, "attempted-refresh", account.GetGrokRefreshToken(), + "an ambiguous persistence result must not mutate the in-memory account") + require.Equal(t, 1, repo.successCASCalls) + require.Zero(t, repo.updateCredentialsCalls) +} + +func TestRefreshIfNeeded_GrokSuccessDurableRereadFailureIsProviderContainment(t *testing.T) { + account := &Account{ + ID: 72, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Credentials: map[string]any{ + "access_token": "attempted-access", + "refresh_token": "attempted-refresh", + }, + } + repo := &refreshAPIAccountRepo{ + account: account, + getByIDErrAfterCall: 2, + getByIDErrAfterCallErr: errors.New("durable state unavailable"), + } + cache := &refreshAPICacheStub{lockResult: true} + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + credentials: map[string]any{ + "access_token": "provider-access", + "refresh_token": "provider-refresh", + }, + } + + result, err := NewOAuthRefreshAPI(repo, cache).RefreshIfNeeded(context.Background(), account, executor, time.Hour) + + require.Error(t, err) + require.Nil(t, result) + var containmentErr *providerCycleContainmentRefreshError + require.ErrorAs(t, err, &containmentErr) + require.Equal(t, 2, repo.getByIDCalls) + require.Equal(t, 1, repo.successCASCalls) + require.Equal(t, 1, cache.deleteCalls, "a committed credential rotation must invalidate the pre-rotation access-token cache") + require.NoError(t, cache.deleteCtxErr) +} + func TestRefreshIfNeeded_DBRereadFails(t *testing.T) { - account := &Account{ID: 8, Platform: PlatformAnthropic, Type: AccountTypeOAuth} + account := &Account{ID: 8, Platform: PlatformAnthropic, Type: AccountTypeOAuth, Status: StatusActive} repo := &refreshAPIAccountRepo{ account: nil, // GetByID returns nil getByIDErr: errors.New("db timeout"), @@ -274,13 +476,184 @@ func TestRefreshIfNeeded_DBRereadFails(t *testing.T) { api := NewOAuthRefreshAPI(repo, cache) result, err := api.RefreshIfNeeded(context.Background(), account, executor, 3*time.Minute) - require.NoError(t, err) - require.True(t, result.Refreshed) - require.Equal(t, 1, executor.refreshCalls) // still refreshes using passed-in account + require.Error(t, err) + var stateUnavailable *oauthRefreshStateUnavailableError + require.ErrorAs(t, err, &stateUnavailable) + require.Nil(t, result) + require.Zero(t, executor.refreshCalls, "a failed DB reread must not refresh stale credentials") + require.Zero(t, repo.updateCalls) + require.Equal(t, 1, cache.releaseCalls) +} + +func TestRefreshIfNeeded_RequestPathDBRereadNilFailsClosed(t *testing.T) { + account := &Account{ID: 81, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true} + repo := &refreshAPIAccountRepo{} + cache := &refreshAPICacheStub{lockResult: true} + executor := &refreshAPIExecutorStub{needsRefresh: true} + + api := NewOAuthRefreshAPI(repo, cache) + result, err := api.RefreshIfNeeded(withOAuthRefreshRequestPath(context.Background()), account, executor, 3*time.Minute) + + require.ErrorIs(t, err, errOAuthRefreshAccountStateChanged) + require.Nil(t, result) + require.Zero(t, executor.refreshCalls) + require.Zero(t, repo.updateCalls) + require.Equal(t, 1, cache.releaseCalls) +} + +func TestRefreshIfNeeded_RequestPathDBRereadInactiveFailsClosed(t *testing.T) { + account := &Account{ID: 82, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true} + freshAccount := &Account{ID: account.ID, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusDisabled} + repo := &refreshAPIAccountRepo{account: freshAccount} + executor := &refreshAPIExecutorStub{needsRefresh: true} + + api := NewOAuthRefreshAPI(repo, nil) + result, err := api.RefreshIfNeeded(withOAuthRefreshRequestPath(context.Background()), account, executor, 3*time.Minute) + + require.ErrorContains(t, err, "account is not active") + require.Nil(t, result) + require.Zero(t, executor.refreshCalls) + require.Zero(t, repo.updateCalls) +} + +func TestRefreshIfNeeded_RequestPathDBRereadRevalidatesExecutorContract(t *testing.T) { + tests := []struct { + name string + freshPlatform string + freshType string + }{ + {name: "platform changed", freshPlatform: PlatformAnthropic, freshType: AccountTypeOAuth}, + {name: "type changed", freshPlatform: PlatformGrok, freshType: AccountTypeUpstream}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := &Account{ID: 83, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true} + freshAccount := &Account{ID: account.ID, Platform: tt.freshPlatform, Type: tt.freshType, Status: StatusActive, Schedulable: true} + repo := &refreshAPIAccountRepo{account: freshAccount} + executor := NewGrokTokenRefresher(nil) + + api := NewOAuthRefreshAPI(repo, nil) + result, err := api.RefreshIfNeeded(withOAuthRefreshRequestPath(context.Background()), account, executor, 3*time.Minute) + + require.ErrorIs(t, err, errOAuthRefreshAccountStateChanged) + require.Nil(t, result) + require.Zero(t, repo.updateCalls) + }) + } +} + +func TestRefreshIfNeeded_LocalLockWaitHonorsContext(t *testing.T) { + account := &Account{ID: 80, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusActive} + repo := &refreshAPIAccountRepo{account: account} + executor := &refreshAPIExecutorStub{needsRefresh: true} + api := NewOAuthRefreshAPI(repo, nil) + lock := api.getLocalLock(executor.CacheKey(account)) + require.NoError(t, lock.Lock(context.Background())) + defer lock.Unlock() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + + result, err := api.RefreshIfNeeded(ctx, account, executor, time.Hour) + + require.ErrorIs(t, err, context.DeadlineExceeded) + require.Nil(t, result) + require.Zero(t, executor.refreshCalls) +} + +func TestRefreshIfNeeded_ReleasesDistributedLockAfterParentCancellation(t *testing.T) { + account := &Account{ID: 81, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusActive} + repo := &refreshAPIAccountRepo{account: account} + cache := &refreshAPICacheStub{lockResult: true} + ctx, cancel := context.WithCancel(context.Background()) + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + err: errors.New("temporary provider error"), + onRefresh: cancel, + } + api := NewOAuthRefreshAPI(repo, cache) + + _, err := api.RefreshIfNeeded(ctx, account, executor, time.Hour) + + require.Error(t, err) + require.Equal(t, 1, cache.releaseCalls) + require.NoError(t, cache.releaseCtxErr, "lock cleanup must not reuse the canceled attempt context") +} + +func TestRefreshIfNeeded_RevalidatesFreshAccountBeforeRefresh(t *testing.T) { + selected := &Account{ID: 82, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusActive} + tests := []struct { + name string + fresh *Account + }{ + {name: "converted to API key", fresh: &Account{ID: 82, Platform: PlatformGrok, Type: AccountTypeAPIKey, Status: StatusActive}}, + {name: "disabled", fresh: &Account{ID: 82, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusDisabled}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + repo := &refreshAPIAccountRepo{account: tt.fresh} + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + canRefresh: func(account *Account) bool { + return account.Platform == PlatformGrok && account.Type == AccountTypeOAuth + }, + } + api := NewOAuthRefreshAPI(repo, nil) + + result, err := api.RefreshIfNeeded(context.Background(), selected, executor, time.Hour) + + require.NoError(t, err) + require.False(t, result.Refreshed) + require.Zero(t, executor.refreshCalls) + require.Zero(t, repo.updateCalls) + }) + } +} + +func TestRefreshIfNeeded_RequestPathDBRereadMissingGrokRefreshCredentialReturnsPermanentSignal(t *testing.T) { + account := &Account{ + ID: 84, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{ + "refresh_token": "caller-snapshot-refresh-token", + }, + } + freshAccount := &Account{ID: account.ID, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true} + repo := &refreshAPIAccountRepo{account: freshAccount} + executor := NewGrokTokenRefresher(nil) + + api := NewOAuthRefreshAPI(repo, nil) + result, err := api.RefreshIfNeeded(withOAuthRefreshRequestPath(context.Background()), account, executor, 3*time.Minute) + + require.ErrorIs(t, err, errGrokOAuthRefreshTokenMissing) + require.Nil(t, result) + require.Zero(t, repo.updateCalls) +} + +func TestRefreshIfNeeded_LateSuccessAfterDeadlineDoesNotPersist(t *testing.T) { + account := &Account{ID: 85, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusActive} + repo := &refreshAPIAccountRepo{account: account} + executor := &refreshAPIExecutorStub{ + needsRefresh: true, + credentials: map[string]any{"access_token": "late-token"}, + delay: 30 * time.Millisecond, + } + api := NewOAuthRefreshAPI(repo, nil) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) + defer cancel() + + result, err := api.RefreshIfNeeded(ctx, account, executor, time.Hour) + + require.ErrorIs(t, err, context.DeadlineExceeded) + require.Nil(t, result) + require.Zero(t, repo.updateCredentialsCalls, "late credentials must not cross the unified API persistence boundary") } func TestRefreshIfNeeded_NilCredentials(t *testing.T) { - account := &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeOAuth} + account := &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeOAuth, Status: StatusActive} repo := &refreshAPIAccountRepo{account: account} cache := &refreshAPICacheStub{lockResult: true} executor := &refreshAPIExecutorStub{ @@ -397,12 +770,12 @@ type refreshAPIAccountRepoWithRace struct { func (r *refreshAPIAccountRepoWithRace) GetByID(_ context.Context, _ int64) (*Account, error) { r.getByIDCalls++ if r.getByIDCalls > 1 && r.raceAccount != nil { - return r.raceAccount, nil + return activeRefreshAPITestAccount(r.raceAccount), nil } if r.getByIDErr != nil { return nil, r.getByIDErr } - return r.account, nil + return activeRefreshAPITestAccount(r.account), nil } // ========== Race recovery tests ========== @@ -413,6 +786,7 @@ func TestRefreshIfNeeded_InvalidGrantRaceRecovered(t *testing.T) { ID: 10, Platform: PlatformAnthropic, Type: AccountTypeOAuth, + Status: StatusActive, Credentials: map[string]any{"refresh_token": "old-rt", "access_token": "old-at"}, } // After race, DB has new refresh token from another worker @@ -420,6 +794,7 @@ func TestRefreshIfNeeded_InvalidGrantRaceRecovered(t *testing.T) { ID: 10, Platform: PlatformAnthropic, Type: AccountTypeOAuth, + Status: StatusActive, Credentials: map[string]any{"refresh_token": "new-rt", "access_token": "new-at"}, } repo := &refreshAPIAccountRepoWithRace{ @@ -449,6 +824,7 @@ func TestRefreshIfNeeded_InvalidGrantGenuine(t *testing.T) { ID: 11, Platform: PlatformAnthropic, Type: AccountTypeOAuth, + Status: StatusActive, Credentials: map[string]any{"refresh_token": "revoked-rt", "access_token": "old-at"}, } repo := &refreshAPIAccountRepoWithRace{ @@ -465,7 +841,9 @@ func TestRefreshIfNeeded_InvalidGrantGenuine(t *testing.T) { result, err := api.RefreshIfNeeded(context.Background(), account, executor, 3*time.Minute) require.Error(t, err, "genuine invalid_grant should propagate error") - require.Nil(t, result) + require.NotNil(t, result) + require.NotNil(t, result.Account) + require.Equal(t, "revoked-rt", result.Account.GetCredential("refresh_token")) require.Contains(t, err.Error(), "invalid_grant") } @@ -474,6 +852,7 @@ func TestRefreshIfNeeded_InvalidGrantDBRereadFailsOnRecovery(t *testing.T) { ID: 12, Platform: PlatformAnthropic, Type: AccountTypeOAuth, + Status: StatusActive, Credentials: map[string]any{"refresh_token": "old-rt"}, } repo := &refreshAPIAccountRepoWithRace{ @@ -490,7 +869,9 @@ func TestRefreshIfNeeded_InvalidGrantDBRereadFailsOnRecovery(t *testing.T) { result, err := api.RefreshIfNeeded(context.Background(), account, executor, 3*time.Minute) require.Error(t, err, "should propagate error when recovery DB re-read fails") - require.Nil(t, result) + require.NotNil(t, result) + require.NotNil(t, result.Account) + require.Equal(t, "old-rt", result.Account.GetCredential("refresh_token")) } func TestRefreshIfNeeded_LocalMutexSerializesConcurrent(t *testing.T) { @@ -500,6 +881,7 @@ func TestRefreshIfNeeded_LocalMutexSerializesConcurrent(t *testing.T) { ID: 20, Platform: PlatformAnthropic, Type: AccountTypeOAuth, + Status: StatusActive, Credentials: map[string]any{"refresh_token": "new-rt", "access_token": "new-at"}, } callCount := 0 @@ -507,6 +889,7 @@ func TestRefreshIfNeeded_LocalMutexSerializesConcurrent(t *testing.T) { ID: 20, Platform: PlatformAnthropic, Type: AccountTypeOAuth, + Status: StatusActive, Credentials: map[string]any{"refresh_token": "old-rt"}, }} @@ -556,6 +939,78 @@ func TestRefreshIfNeeded_LocalMutexSerializesConcurrent(t *testing.T) { mu.Unlock() } +func TestRefreshIfNeeded_LocalLockWaitHonorsContextCancellation(t *testing.T) { + account := &Account{ID: 21, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusActive} + repo := &refreshAPIAccountRepo{account: account} + refreshStarted := make(chan struct{}) + releaseRefresh := make(chan struct{}) + var once sync.Once + executor := &dynamicRefreshExecutor{ + canRefresh: true, + cacheKey: "test:context-lock:grok", + needsRefreshFunc: func() bool { return true }, + refreshFunc: func(context.Context, *Account) (map[string]any, error) { + once.Do(func() { close(refreshStarted) }) + <-releaseRefresh + return map[string]any{"access_token": "new-at"}, nil + }, + } + api := NewOAuthRefreshAPI(repo, nil) + firstDone := make(chan error, 1) + go func() { + _, err := api.RefreshIfNeeded(context.Background(), account, executor, 3*time.Minute) + firstDone <- err + }() + <-refreshStarted + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) + defer cancel() + startedAt := time.Now() + result, err := api.RefreshIfNeeded(ctx, account, executor, 3*time.Minute) + + require.Nil(t, result) + require.ErrorIs(t, err, context.DeadlineExceeded) + require.Less(t, time.Since(startedAt), 500*time.Millisecond) + close(releaseRefresh) + require.NoError(t, <-firstDone) +} + +func TestRefreshIfNeeded_ReleasesDistributedLockWithCleanupContext(t *testing.T) { + account := &Account{ + ID: 22, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Credentials: map[string]any{ + "access_token": "old-access", + "refresh_token": "old-refresh", + }, + } + repo := &refreshAPIAccountRepo{account: account} + cache := &refreshAPICacheStub{lockResult: true} + ctx, cancel := context.WithCancel(context.Background()) + executor := &dynamicRefreshExecutor{ + canRefresh: true, + cacheKey: "test:cleanup:grok", + needsRefreshFunc: func() bool { return true }, + refreshFunc: func(context.Context, *Account) (map[string]any, error) { + cancel() + return map[string]any{"access_token": "new-at"}, nil + }, + } + api := NewOAuthRefreshAPI(repo, cache) + + result, err := api.RefreshIfNeeded(ctx, account, executor, 3*time.Minute) + + require.ErrorIs(t, err, context.Canceled) + require.Nil(t, result) + require.Zero(t, repo.updateCalls) + require.Equal(t, "old-access", account.GetGrokAccessToken()) + require.Zero(t, account.GetCredentialAsInt64("_token_version")) + require.Equal(t, 1, cache.releaseCalls) + require.NoError(t, cache.releaseCtxErr) +} + // dynamicRefreshExecutor is a test helper with function-based NeedsRefresh and Refresh. type dynamicRefreshExecutor struct { canRefresh bool diff --git a/backend/internal/service/openai_account_runtime_block_fastpath.go b/backend/internal/service/openai_account_runtime_block_fastpath.go index a3f60fee2f..00d971ba22 100644 --- a/backend/internal/service/openai_account_runtime_block_fastpath.go +++ b/backend/internal/service/openai_account_runtime_block_fastpath.go @@ -3,6 +3,7 @@ package service import ( "context" "net/http" + "sync" "time" ) @@ -15,6 +16,13 @@ const ( openAIOAuth429StormMaxAccountSwitches = 1 ) +// OpenAIOAuth429FailoverState tracks the request-local follow-up budget after +// the first Grok OAuth 429. Once that 429 occurs, exactly one different account +// may be attempted; any failure from that follow-up account ends failover. +type OpenAIOAuth429FailoverState struct { + grokOAuth429FollowupPending bool +} + func openAIAccountStateContext(ctx context.Context) (context.Context, context.CancelFunc) { base := context.Background() if ctx != nil { @@ -96,6 +104,25 @@ func (s *OpenAIGatewayService) BlockAccountScheduling(account *Account, until ti if s == nil || !isOpenAIAccount(account) { return } + mu := s.openAIAccountRuntimeBlockLock(account.ID) + mu.Lock() + defer mu.Unlock() + _, _ = s.blockAccountSchedulingLocked(account, until, reason) +} + +func (s *OpenAIGatewayService) openAIAccountRuntimeBlockLock(accountID int64) *sync.Mutex { + actual, _ := s.openaiAccountRuntimeBlockLocks.LoadOrStore(accountID, &sync.Mutex{}) + mu, ok := actual.(*sync.Mutex) + if !ok { + mu = &sync.Mutex{} + s.openaiAccountRuntimeBlockLocks.Store(accountID, mu) + } + return mu +} + +func (s *OpenAIGatewayService) blockAccountSchedulingLocked(account *Account, until time.Time, _ string) (uint64, bool) { + generation := s.openaiAccountRuntimeBlockSequence.Add(1) + s.openaiAccountRuntimeBlockGeneration.Store(account.ID, generation) now := time.Now() blockUntil := until if blockUntil.IsZero() || !blockUntil.After(now) { @@ -107,7 +134,7 @@ func (s *OpenAIGatewayService) BlockAccountScheduling(account *Account, until ti if !loaded { actual, stored := s.openaiAccountRuntimeBlockUntil.LoadOrStore(account.ID, blockUntil) if !stored { - return + return generation, true } current = actual } @@ -115,15 +142,15 @@ func (s *OpenAIGatewayService) BlockAccountScheduling(account *Account, until ti currentUntil, ok := current.(time.Time) if !ok || currentUntil.IsZero() { if s.openaiAccountRuntimeBlockUntil.CompareAndSwap(account.ID, current, blockUntil) { - return + return generation, true } continue } - if currentUntil.After(blockUntil) { - return + if !blockUntil.After(currentUntil) { + return generation, false } if s.openaiAccountRuntimeBlockUntil.CompareAndSwap(account.ID, current, blockUntil) { - return + return generation, true } } } @@ -132,13 +159,20 @@ func (s *OpenAIGatewayService) ClearAccountSchedulingBlock(accountID int64) { if s == nil || accountID <= 0 { return } + mu := s.openAIAccountRuntimeBlockLock(accountID) + mu.Lock() + defer mu.Unlock() s.openaiAccountRuntimeBlockUntil.Delete(accountID) + s.openaiAccountRuntimeBlockGeneration.Store(accountID, s.openaiAccountRuntimeBlockSequence.Add(1)) } func (s *OpenAIGatewayService) isOpenAIAccountRuntimeBlocked(account *Account) bool { if s == nil || !isOpenAIAccount(account) { return false } + mu := s.openAIAccountRuntimeBlockLock(account.ID) + mu.Lock() + defer mu.Unlock() value, ok := s.openaiAccountRuntimeBlockUntil.Load(account.ID) if !ok { return false @@ -146,12 +180,14 @@ func (s *OpenAIGatewayService) isOpenAIAccountRuntimeBlocked(account *Account) b cooldownUntil, ok := value.(time.Time) if !ok || cooldownUntil.IsZero() { s.openaiAccountRuntimeBlockUntil.Delete(account.ID) + s.openaiAccountRuntimeBlockGeneration.Store(account.ID, s.openaiAccountRuntimeBlockSequence.Add(1)) return false } if time.Now().Before(cooldownUntil) { return true } s.openaiAccountRuntimeBlockUntil.Delete(account.ID) + s.openaiAccountRuntimeBlockGeneration.Store(account.ID, s.openaiAccountRuntimeBlockSequence.Add(1)) return false } @@ -181,14 +217,28 @@ func (s *OpenAIGatewayService) isOpenAIOAuth429Storm() bool { return s.openaiOAuth429WindowCount.Load() >= openAIOAuth429StormThreshold } -func (s *OpenAIGatewayService) ShouldStopOpenAIOAuth429Failover(account *Account, statusCode int, failedSwitches int) bool { - if statusCode != http.StatusTooManyRequests || failedSwitches < openAIOAuth429StormMaxAccountSwitches { +func (s *OpenAIGatewayService) ShouldStopOpenAIOAuth429Failover(account *Account, statusCode int, failedSwitches int, state *OpenAIOAuth429FailoverState) bool { + if failedSwitches < openAIOAuth429StormMaxAccountSwitches { return false } - if isGrokOAuthAccount(account) { + if state != nil && state.grokOAuth429FollowupPending { + // The follow-up budget was armed by a Grok OAuth 429. Consume it on + // any failing follow-up account, even if a mixed pool selected an API-key + // account next. return true } - if !isOpenAIOAuthAccount(account) { + if isGrokOAuthAccount(account) { + if state == nil { + // Preserve the old threshold for callers that have not adopted the + // request-local state contract yet. + return statusCode == http.StatusTooManyRequests && failedSwitches >= 2 + } + if statusCode == http.StatusTooManyRequests { + state.grokOAuth429FollowupPending = true + } + return false + } + if statusCode != http.StatusTooManyRequests || !isOpenAIOAuthAccount(account) { return false } return s.isOpenAIOAuth429Storm() diff --git a/backend/internal/service/openai_account_runtime_block_fastpath_test.go b/backend/internal/service/openai_account_runtime_block_fastpath_test.go index a51c13c531..7d7cfbda50 100644 --- a/backend/internal/service/openai_account_runtime_block_fastpath_test.go +++ b/backend/internal/service/openai_account_runtime_block_fastpath_test.go @@ -135,26 +135,45 @@ func TestShouldStopOpenAIOAuth429Failover_OnlyDuringStorm(t *testing.T) { svc := &OpenAIGatewayService{} account := &Account{ID: 42, Platform: PlatformOpenAI, Type: AccountTypeOAuth} apiKeyAccount := &Account{ID: 43, Platform: PlatformOpenAI, Type: AccountTypeAPIKey} + var state OpenAIOAuth429FailoverState - require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 1)) + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 1, &state)) for i := 0; i < openAIOAuth429StormThreshold; i++ { svc.recordOpenAIOAuth429() } - require.True(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 1)) - require.False(t, svc.ShouldStopOpenAIOAuth429Failover(apiKeyAccount, http.StatusTooManyRequests, 1)) - require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusInternalServerError, 1)) - require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 0)) + require.True(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 1, &state)) + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(apiKeyAccount, http.StatusTooManyRequests, 1, &state)) + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusInternalServerError, 1, &state)) + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 0, &state)) } -func TestShouldStopOpenAIOAuth429Failover_StopsGrokAfterFirst429Switch(t *testing.T) { +func TestShouldStopOpenAIOAuth429Failover_TracksOneGrokFollowupAttempt(t *testing.T) { svc := &OpenAIGatewayService{} account := &Account{ID: 44, Platform: PlatformGrok, Type: AccountTypeOAuth} apiKeyAccount := &Account{ID: 45, Platform: PlatformGrok, Type: AccountTypeAPIKey} - require.True(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 1)) - require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 0)) - require.False(t, svc.ShouldStopOpenAIOAuth429Failover(apiKeyAccount, http.StatusTooManyRequests, 1)) - require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusInternalServerError, 1)) + t.Run("429 then 500 stops after one followup", func(t *testing.T) { + var state OpenAIOAuth429FailoverState + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 1, &state)) + require.True(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusInternalServerError, 2, &state)) + }) + + t.Run("500 then 429 still allows one followup", func(t *testing.T) { + var state OpenAIOAuth429FailoverState + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusInternalServerError, 1, &state)) + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 2, &state)) + require.True(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusBadGateway, 3, &state)) + }) + + t.Run("OAuth 429 then API-key failure consumes the same followup", func(t *testing.T) { + var state OpenAIOAuth429FailoverState + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 1, &state)) + require.True(t, svc.ShouldStopOpenAIOAuth429Failover(apiKeyAccount, http.StatusInternalServerError, 2, &state)) + }) + + var state OpenAIOAuth429FailoverState + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 0, &state)) + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(apiKeyAccount, http.StatusTooManyRequests, 2, &state)) } diff --git a/backend/internal/service/openai_agent_identity.go b/backend/internal/service/openai_agent_identity.go new file mode 100644 index 0000000000..aa96227f3d --- /dev/null +++ b/backend/internal/service/openai_agent_identity.go @@ -0,0 +1,522 @@ +package service + +import ( + "context" + "crypto" + "crypto/ed25519" + "crypto/sha512" + "crypto/x509" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "sync" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/httpclient" + "golang.org/x/crypto/curve25519" + "golang.org/x/crypto/nacl/box" +) + +const ( + OpenAIAuthModeAgentIdentity = "agentIdentity" + agentIdentityAuthAPIBaseURL = "https://auth.openai.com/api/accounts" + agentIdentityTaskRegistrationTimeout = 30 * time.Second +) + +var openAIAgentIdentityAuthAPIBaseURL = agentIdentityAuthAPIBaseURL + +var agentIdentityTaskLocks sync.Map // map[int64]*sync.Mutex + +type agentIdentityWSConnectionInvalidator interface { + InvalidateAgentIdentityWSConnections(accountID int64) +} + +type agentIdentityKey struct { + runtimeID string + privateKey ed25519.PrivateKey + taskID string +} + +type agentIdentityTaskRegistrationResponse struct { + TaskID string `json:"task_id"` + TaskIDCamel string `json:"taskId"` + EncryptedTaskID string `json:"encrypted_task_id"` + EncryptedTaskIDCamel string `json:"encryptedTaskId"` +} + +type agentIdentityTaskRecoveredError struct{} + +func (e *agentIdentityTaskRecoveredError) Error() string { + return "agent identity task recovered" +} + +func (a *Account) IsOpenAIAgentIdentity() bool { + if a == nil || !a.IsOpenAIOAuth() { + return false + } + return strings.EqualFold(strings.TrimSpace(a.GetCredential(openAIAuthModeCredentialKey)), OpenAIAuthModeAgentIdentity) +} + +func agentIdentityPrivateKey(account *Account) (ed25519.PrivateKey, error) { + if account == nil { + return nil, errors.New("agent identity account is nil") + } + raw := strings.TrimSpace(account.GetCredential("agent_private_key")) + if raw == "" { + return nil, errors.New("agent identity private key is missing") + } + der, err := base64.StdEncoding.DecodeString(raw) + if err != nil { + return nil, errors.New("agent identity private key is not valid base64") + } + key, err := x509.ParsePKCS8PrivateKey(der) + if err != nil { + return nil, errors.New("agent identity private key is not valid PKCS#8") + } + privateKey, ok := key.(ed25519.PrivateKey) + if !ok || len(privateKey) != ed25519.PrivateKeySize { + return nil, errors.New("agent identity private key is not Ed25519") + } + return privateKey, nil +} + +// ValidateOpenAIAgentIdentityPrivateKey validates the stored PKCS#8 Ed25519 +// form without returning or logging the key material. +func ValidateOpenAIAgentIdentityPrivateKey(encoded string) error { + account := &Account{Credentials: map[string]any{"agent_private_key": encoded}} + _, err := agentIdentityPrivateKey(account) + return err +} + +func agentIdentityKeyFromAccount(account *Account) (agentIdentityKey, error) { + privateKey, err := agentIdentityPrivateKey(account) + if err != nil { + return agentIdentityKey{}, err + } + runtimeID := strings.TrimSpace(account.GetCredential("agent_runtime_id")) + if runtimeID == "" { + return agentIdentityKey{}, errors.New("agent identity runtime id is missing") + } + return agentIdentityKey{ + runtimeID: runtimeID, + privateKey: privateKey, + taskID: strings.TrimSpace(account.GetCredential("task_id")), + }, nil +} + +func buildAgentAssertion(key agentIdentityKey, now time.Time) (string, error) { + if key.runtimeID == "" || key.taskID == "" { + return "", errors.New("agent identity runtime or task id is missing") + } + timestamp := now.UTC().Format(time.RFC3339) + payload := []byte(key.runtimeID + ":" + key.taskID + ":" + timestamp) + signature, err := key.privateKey.Sign(nil, payload, crypto.Hash(0)) + if err != nil { + return "", errors.New("failed to sign agent assertion") + } + envelope := map[string]string{ + "agent_runtime_id": key.runtimeID, + "task_id": key.taskID, + "timestamp": timestamp, + "signature": base64.StdEncoding.EncodeToString(signature), + } + encoded, err := json.Marshal(envelope) + if err != nil { + return "", errors.New("failed to serialize agent assertion") + } + return "AgentAssertion " + base64.RawURLEncoding.EncodeToString(encoded), nil +} + +func signAgentTaskRegistration(key agentIdentityKey, timestamp time.Time) (string, string, error) { + if key.runtimeID == "" { + return "", "", errors.New("agent identity runtime id is missing") + } + formatted := timestamp.UTC().Format(time.RFC3339) + signature, err := key.privateKey.Sign(nil, []byte(key.runtimeID+":"+formatted), crypto.Hash(0)) + if err != nil { + return "", "", errors.New("failed to sign agent task registration") + } + return formatted, base64.StdEncoding.EncodeToString(signature), nil +} + +func decryptAgentTaskID(key agentIdentityKey, encoded string) (string, error) { + ciphertext, err := base64.StdEncoding.DecodeString(strings.TrimSpace(encoded)) + if err != nil { + return "", errors.New("encrypted agent task id is not valid base64") + } + seed := key.privateKey.Seed() + digest := sha512.Sum512(seed) + var curvePrivate [32]byte + copy(curvePrivate[:], digest[:32]) + curvePrivate[0] &= 248 + curvePrivate[31] &= 127 + curvePrivate[31] |= 64 + curvePublicBytes, err := curve25519.X25519(curvePrivate[:], curve25519.Basepoint) + if err != nil { + return "", errors.New("failed to derive agent identity decryption key") + } + var curvePublic [32]byte + copy(curvePublic[:], curvePublicBytes) + plaintext, ok := box.OpenAnonymous(nil, ciphertext, &curvePublic, &curvePrivate) + if !ok { + return "", errors.New("failed to decrypt encrypted agent task id") + } + taskID := strings.TrimSpace(string(plaintext)) + if taskID == "" { + return "", errors.New("decrypted agent task id is empty") + } + return taskID, nil +} + +func registerAgentIdentityTask(ctx context.Context, account *Account) (string, error) { + key, err := agentIdentityKeyFromAccount(account) + if err != nil { + return "", err + } + timestamp, signature, err := signAgentTaskRegistration(key, time.Now()) + if err != nil { + return "", err + } + proxyURL := "" + if account.ProxyID != nil && account.Proxy != nil { + proxyURL = account.Proxy.URL() + } + client, err := httpclient.GetClient(httpclient.Options{ + ProxyURL: proxyURL, + Timeout: agentIdentityTaskRegistrationTimeout, + ResponseHeaderTimeout: 15 * time.Second, + }) + if err != nil { + return "", errors.New("invalid proxy configuration for agent task registration") + } + body, err := json.Marshal(map[string]string{ + "timestamp": timestamp, + "signature": signature, + }) + if err != nil { + return "", errors.New("failed to serialize agent task registration") + } + url := strings.TrimRight(strings.TrimSpace(openAIAgentIdentityAuthAPIBaseURL), "/") + "/v1/agent/" + key.runtimeID + "/task/register" + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader(string(body))) + if err != nil { + return "", errors.New("failed to build agent task registration request") + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json") + resp, err := client.Do(req) + if err != nil { + return "", errors.New("agent task registration request failed") + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { + return "", fmt.Errorf("agent task registration returned status %d", resp.StatusCode) + } + var result agentIdentityTaskRegistrationResponse + if err := json.NewDecoder(io.LimitReader(resp.Body, 64*1024)).Decode(&result); err != nil { + return "", errors.New("agent task registration response is invalid") + } + if taskID := strings.TrimSpace(result.TaskID); taskID != "" { + return taskID, nil + } + if taskID := strings.TrimSpace(result.TaskIDCamel); taskID != "" { + return taskID, nil + } + encrypted := strings.TrimSpace(result.EncryptedTaskID) + if encrypted == "" { + encrypted = strings.TrimSpace(result.EncryptedTaskIDCamel) + } + if encrypted == "" { + return "", errors.New("agent task registration response omitted task id") + } + return decryptAgentTaskID(key, encrypted) +} + +func ensureAgentIdentityTaskForAccount(ctx context.Context, repo AccountRepository, wsInvalidator agentIdentityWSConnectionInvalidator, taskMu *sync.Mutex, account *Account, expectedTaskID string) error { + if account == nil || !account.IsOpenAIAgentIdentity() { + return nil + } + credAccount := account + if account.IsShadow() { + resolved, err := resolveCredentialAccount(ctx, repo, account) + if err != nil { + return err + } + credAccount = resolved + } + if credAccount == nil || !credAccount.IsOpenAIAgentIdentity() { + return errors.New("agent identity credentials are unavailable") + } + currentTaskID := strings.TrimSpace(credAccount.GetCredential("task_id")) + if currentTaskID != "" && (expectedTaskID == "" || currentTaskID != expectedTaskID) { + return nil + } + if taskMu == nil { + return errors.New("agent identity task lock is unavailable") + } + sharedTaskMu := taskMu + if credAccount.ID > 0 { + candidate := &sync.Mutex{} + actual, _ := agentIdentityTaskLocks.LoadOrStore(credAccount.ID, candidate) + loadedTaskMu, ok := actual.(*sync.Mutex) + if !ok { + return errors.New("agent identity task lock has invalid type") + } + sharedTaskMu = loadedTaskMu + } + sharedTaskMu.Lock() + defer sharedTaskMu.Unlock() + // Re-read inside the shared lock. Different request paths often receive + // independent repository snapshots; checking only the caller's snapshot + // would allow sequential duplicate registrations after the first writer + // has already persisted a new task. + if repo != nil && credAccount.ID > 0 { + if refreshed, refreshErr := repo.GetByID(ctx, credAccount.ID); refreshErr == nil && refreshed != nil { + if refreshed.IsShadow() { + if resolved, resolveErr := resolveCredentialAccount(ctx, repo, refreshed); resolveErr == nil && resolved != nil { + refreshed = resolved + } + } + if refreshed.IsOpenAIAgentIdentity() { + credAccount = refreshed + if !account.IsShadow() { + account.Credentials = shallowCopyMap(credAccount.Credentials) + } + } + } + } + currentTaskID = strings.TrimSpace(credAccount.GetCredential("task_id")) + if currentTaskID != "" && (expectedTaskID == "" || currentTaskID != expectedTaskID) { + return nil + } + newTaskID, err := registerAgentIdentityTask(ctx, credAccount) + if err != nil { + return err + } + credentials := make(map[string]any, len(credAccount.Credentials)+1) + for key, value := range credAccount.Credentials { + credentials[key] = value + } + credentials["task_id"] = newTaskID + if err := persistAccountCredentials(ctx, repo, credAccount, credentials); err != nil { + return err + } + if !account.IsShadow() && account != credAccount { + account.Credentials = shallowCopyMap(credAccount.Credentials) + } + if wsInvalidator != nil { + wsInvalidator.InvalidateAgentIdentityWSConnections(credAccount.ID) + } + return nil +} + +func (s *OpenAIGatewayService) ensureAgentIdentityTask(ctx context.Context, account *Account, expectedTaskID string) error { + if s == nil { + return errors.New("openai gateway service is nil") + } + return ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, s, &s.agentIdentityTaskMu, account, expectedTaskID) +} + +func isAgentIdentityTaskInvalidHTTPResponse(statusCode int, body []byte) bool { + if statusCode != http.StatusUnauthorized { + return false + } + lower := strings.ToLower(string(body)) + compact := strings.NewReplacer(" ", "", "\t", "", "\r", "", "\n", "").Replace(lower) + for _, marker := range []string{ + `"code":"invalid_task_id"`, + `"code":"task_not_found"`, + `"code":"task_expired"`, + `"error":"invalid_task_id"`, + } { + if strings.Contains(compact, marker) { + return true + } + } + for _, marker := range []string{ + "invalid task_id", + "invalid task id", + "task_id is invalid", + "task id is invalid", + "task not found", + "task expired", + "unknown task_id", + "unknown task id", + } { + if strings.Contains(lower, marker) { + return true + } + } + return false +} + +type agentIdentityTaskRecoveryContextKey struct{} + +func markAgentIdentityTaskRecoveryTried(ctx context.Context) context.Context { + return context.WithValue(ctx, agentIdentityTaskRecoveryContextKey{}, true) +} + +func agentIdentityTaskRecoveryWasTried(ctx context.Context) bool { + tried, _ := ctx.Value(agentIdentityTaskRecoveryContextKey{}).(bool) + return tried +} + +func isAgentIdentityTaskInvalidWSDialError(err *openAIWSDialError) bool { + return err != nil && isAgentIdentityTaskInvalidHTTPResponse(err.StatusCode, err.ResponseBody) +} + +func (s *OpenAIGatewayService) buildOpenAIAuthenticationHeaders(ctx context.Context, account *Account, token string) (http.Header, error) { + if account == nil { + return nil, errors.New("account is nil") + } + credAccount := account + if account.IsShadow() { + resolved, err := resolveCredentialAccount(ctx, s.accountRepo, account) + if err != nil { + return nil, err + } + credAccount = resolved + } + headers := make(http.Header) + if credAccount != nil && credAccount.IsOpenAIAgentIdentity() { + agentHeaders, err := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s, &s.agentIdentityTaskMu, credAccount) + if err != nil { + return nil, err + } + return agentHeaders, nil + } + headers.Set("Authorization", "Bearer "+token) + return headers, nil +} + +func buildAgentIdentityAuthenticationHeaders(ctx context.Context, repo AccountRepository, wsInvalidator agentIdentityWSConnectionInvalidator, taskMu *sync.Mutex, account *Account) (http.Header, error) { + if account == nil || !account.IsOpenAIAgentIdentity() { + return nil, errors.New("agent identity account is required") + } + if err := ensureAgentIdentityTaskForAccount(ctx, repo, wsInvalidator, taskMu, account, ""); err != nil { + return nil, err + } + key, err := agentIdentityKeyFromAccount(account) + if err != nil { + return nil, err + } + assertion, err := buildAgentAssertion(key, time.Now()) + if err != nil { + return nil, err + } + headers := make(http.Header) + headers.Set("Authorization", assertion) + return headers, nil +} + +func (s *OpenAIGatewayService) refreshOpenAIAgentIdentityHeaders(ctx context.Context, account *Account, headers http.Header) (http.Header, error) { + if account == nil { + return cloneHeader(headers), nil + } + credAccount := account + if account.IsShadow() { + resolved, err := resolveCredentialAccount(ctx, s.accountRepo, account) + if err != nil { + return nil, err + } + credAccount = resolved + } + if !credAccount.IsOpenAIAgentIdentity() { + return cloneHeader(headers), nil + } + refreshed := cloneHeader(headers) + if refreshed == nil { + refreshed = make(http.Header) + } + authHeaders, err := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s, &s.agentIdentityTaskMu, credAccount) + if err != nil { + return nil, err + } + refreshed.Set("Authorization", authHeaders.Get("Authorization")) + return refreshed, nil +} + +func (s *OpenAIGatewayService) recoverAgentIdentityTask(ctx context.Context, account *Account, expectedTaskID string) error { + if account != nil && account.IsShadow() { + if resolved, err := resolveCredentialAccount(ctx, s.accountRepo, account); err == nil && resolved != nil && strings.TrimSpace(expectedTaskID) == "" { + expectedTaskID = strings.TrimSpace(resolved.GetCredential("task_id")) + } + } + return s.ensureAgentIdentityTask(ctx, account, expectedTaskID) +} + +func (s *OpenAIGatewayService) isAgentIdentityAccount(ctx context.Context, account *Account) bool { + if account == nil { + return false + } + credAccount := account + if account.IsShadow() { + resolved, err := resolveCredentialAccount(ctx, s.accountRepo, account) + if err != nil { + return false + } + credAccount = resolved + } + return credAccount != nil && credAccount.IsOpenAIAgentIdentity() +} + +// redactAgentIdentitySensitiveBody removes credential values before an +// upstream error can reach logs, ops events, or returned error text. Agent +// Identity responses should not echo these values, but keeping this boundary +// defensive prevents accidental disclosure if an upstream error does. +func redactAgentIdentitySensitiveBodyForAccount(ctx context.Context, repo AccountRepository, account *Account, body []byte) []byte { + if account == nil || len(body) == 0 { + return body + } + credAccount := account + if account != nil && account.IsShadow() { + if resolved, err := resolveCredentialAccount(ctx, repo, account); err == nil && resolved != nil { + credAccount = resolved + } + } + if credAccount == nil || !credAccount.IsOpenAIAgentIdentity() { + return body + } + redacted := string(body) + for _, key := range []string{ + "agent_private_key", + "agent_runtime_id", + "task_id", + "access_token", + "refresh_token", + "id_token", + "api_key", + "session_key", + "cookie", + } { + if value := strings.TrimSpace(credAccount.GetCredential(key)); value != "" { + redacted = strings.ReplaceAll(redacted, value, "[redacted]") + } + } + const assertionPrefix = "AgentAssertion " + for offset := 0; offset < len(redacted); { + relativeStart := strings.Index(redacted[offset:], assertionPrefix) + if relativeStart < 0 { + break + } + start := offset + relativeStart + valueStart := start + len(assertionPrefix) + end := valueStart + for end < len(redacted) && !strings.ContainsRune(" \t\r\n\"',}", rune(redacted[end])) { + end++ + } + redacted = redacted[:valueStart] + "[redacted]" + redacted[end:] + offset = valueStart + len("[redacted]") + } + return []byte(redacted) +} + +func (s *OpenAIGatewayService) redactAgentIdentitySensitiveBody(ctx context.Context, account *Account, body []byte) []byte { + if !s.isAgentIdentityAccount(ctx, account) { + return body + } + return redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, account, body) +} diff --git a/backend/internal/service/openai_agent_identity_compat_test.go b/backend/internal/service/openai_agent_identity_compat_test.go new file mode 100644 index 0000000000..5dad35887b --- /dev/null +++ b/backend/internal/service/openai_agent_identity_compat_test.go @@ -0,0 +1,500 @@ +package service + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestAccountTestServiceOpenAICompactAgentIdentityUsesFreshAssertion(t *testing.T) { + gin.SetMode(gin.TestMode) + key, privateKey := newTestAgentIdentityKey(t) + account := Account{ + ID: 21, + Name: "agent-identity", + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": key.runtimeID, + "agent_private_key": privateKey, + "task_id": key.taskID, + "chatgpt_account_id": "account-agent-test", + "chatgpt_account_is_fedramp": true, + }, + } + repo := &snapshotUpdateAccountRepo{stubOpenAIAccountRepo: stubOpenAIAccountRepo{accounts: []Account{account}}} + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"id":"compact-agent","status":"completed"}`)), + }} + svc := &AccountTestService{accountRepo: repo, httpUpstream: upstream} + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/21/test", bytes.NewReader(nil)) + + require.NoError(t, svc.TestAccountConnection(c, account.ID, "gpt-5.4", "", AccountTestModeCompact)) + require.Equal(t, "AgentAssertion", strings.SplitN(upstream.lastReq.Header.Get("Authorization"), " ", 2)[0]) + require.Equal(t, "account-agent-test", upstream.lastReq.Header.Get("chatgpt-account-id")) + require.Equal(t, "true", upstream.lastReq.Header.Get("x-openai-fedramp")) + require.NotContains(t, upstream.lastReq.Header.Get("Authorization"), privateKey) +} + +func TestAccountTestServiceOpenAICompactAgentIdentityRecoversInvalidTaskOnce(t *testing.T) { + gin.SetMode(gin.TestMode) + key, privateKey := newTestAgentIdentityKey(t) + account := &Account{ + ID: 22, + Name: "agent-identity-recovery", + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": key.runtimeID, + "agent_private_key": privateKey, + "task_id": "task-compact-old", + "chatgpt_account_id": "account-agent-compact-recovery", + }, + } + repo := &accountTestAgentIdentityRepo{account: account} + registerCalls := 0 + registerServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + registerCalls++ + _, _ = io.WriteString(w, `{"task_id":"task-compact-new"}`) + })) + defer registerServer.Close() + oldBase := openAIAgentIdentityAuthAPIBaseURL + openAIAgentIdentityAuthAPIBaseURL = registerServer.URL + t.Cleanup(func() { openAIAgentIdentityAuthAPIBaseURL = oldBase }) + + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + {StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"invalid_task_id"}}`))}, + {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"id":"compact-agent","status":"completed"}`))}, + }} + invalidator := &agentIdentityWSInvalidationRecorder{} + svc := &AccountTestService{accountRepo: repo, httpUpstream: upstream, agentIdentityWS: invalidator} + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/22/test", bytes.NewReader(nil)) + + require.NoError(t, svc.TestAccountConnection(c, account.ID, "gpt-5.4", "", AccountTestModeCompact)) + require.Equal(t, 1, registerCalls) + require.Len(t, upstream.requests, 2) + require.Equal(t, "task-compact-new", account.GetCredential("task_id")) + require.Equal(t, 0, repo.setErrorCalls) + require.Equal(t, []int64{account.ID}, invalidator.accountIDs) +} + +func TestOpenAIAgentIdentityPassthroughKeepsSessionAndPromptCacheHeaders(t *testing.T) { + gin.SetMode(gin.TestMode) + key, privateKey := newTestAgentIdentityKey(t) + account := &Account{ + ID: 24, + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": key.runtimeID, + "agent_private_key": privateKey, + "task_id": key.taskID, + "chatgpt_account_id": "account-agent-passthrough", + }, + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"gpt-5.4","instructions":"Reply OK","input":[],"stream":true,"prompt_cache_key":"cache-agent"}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + c.Request.Header.Set("session_id", "client-session") + c.Request.Header.Set("conversation_id", "client-conversation") + c.Request.Header.Set("Authorization", "Bearer inbound-must-not-forward") + + svc := &OpenAIGatewayService{} + req, err := svc.buildUpstreamRequestOpenAIPassthrough(context.Background(), c, account, body, "") + require.NoError(t, err) + require.Equal(t, "AgentAssertion", strings.SplitN(req.Header.Get("Authorization"), " ", 2)[0]) + require.Equal(t, "account-agent-passthrough", req.Header.Get("chatgpt-account-id")) + require.NotEqual(t, "client-session", req.Header.Get("session_id")) + require.NotEqual(t, "client-conversation", req.Header.Get("conversation_id")) + require.Equal(t, isolateOpenAISessionID(0, "client-session"), req.Header.Get("session_id")) + require.Equal(t, isolateOpenAISessionID(0, "client-conversation"), req.Header.Get("conversation_id")) + requestBody, err := io.ReadAll(req.Body) + require.NoError(t, err) + require.Contains(t, string(requestBody), `"prompt_cache_key":"cache-agent"`) + + // Authentication mode must not affect session isolation or prompt-cache + // behavior. Compare the same request with the existing OAuth path instead + // of pinning this test to an implementation-specific hash. + oauthAccount := &Account{ + ID: 26, + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "chatgpt_account_id": "account-oauth-passthrough", + }, + } + oauthRecorder := httptest.NewRecorder() + oauthContext, _ := gin.CreateTestContext(oauthRecorder) + oauthContext.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + oauthContext.Request.Header.Set("session_id", "client-session") + oauthContext.Request.Header.Set("conversation_id", "client-conversation") + oauthReq, err := svc.buildUpstreamRequestOpenAIPassthrough(context.Background(), oauthContext, oauthAccount, body, "oauth-token") + require.NoError(t, err) + require.Equal(t, oauthReq.Header.Get("session_id"), req.Header.Get("session_id")) + require.Equal(t, oauthReq.Header.Get("conversation_id"), req.Header.Get("conversation_id")) +} + +func TestOpenAIAgentIdentityErrorRedactionDoesNotLeakCredentialValues(t *testing.T) { + key, privateKey := newTestAgentIdentityKey(t) + account := &Account{ + ID: 25, + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": key.runtimeID, + "agent_private_key": privateKey, + "task_id": key.taskID, + "access_token": key.runtimeID + "-oauth-value", + }, + } + svc := &OpenAIGatewayService{} + oauthValue := account.GetCredential("access_token") + redacted := svc.redactAgentIdentitySensitiveBody(context.Background(), account, []byte(`{"message":"runtime-test task-test `+oauthValue+` AgentAssertion abc123"}`)) + require.NotContains(t, string(redacted), key.runtimeID) + require.NotContains(t, string(redacted), key.taskID) + require.NotContains(t, string(redacted), oauthValue) + require.NotContains(t, string(redacted), "AgentAssertion abc123") + require.Contains(t, string(redacted), "[redacted]") +} + +func TestOpenAIAuthenticationHeadersPreserveOAuthPATAndAPIKeyBearerModes(t *testing.T) { + svc := &OpenAIGatewayService{} + tests := []struct { + name string + account *Account + token string + }{ + {name: "oauth", account: &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth}, token: "oauth-runtime-token"}, + {name: "personal access token", account: &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"auth_mode": OpenAIAuthModePersonalAccessToken}}, token: "pat-runtime-token"}, + {name: "api key", account: &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, token: "api-key-runtime-token"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + headers, err := svc.buildOpenAIAuthenticationHeaders(context.Background(), tt.account, tt.token) + require.NoError(t, err) + require.Equal(t, "Bearer "+tt.token, headers.Get("Authorization")) + }) + } +} + +func TestOpenAIWSAgentIdentityRecoveryRequiresTaskInvalidBody(t *testing.T) { + require.False(t, isAgentIdentityTaskInvalidWSDialError(&openAIWSDialError{ + StatusCode: http.StatusUnauthorized, + ResponseBody: []byte(`{"error":{"code":"invalid_signature"}}`), + })) + require.True(t, isAgentIdentityTaskInvalidWSDialError(&openAIWSDialError{ + StatusCode: http.StatusUnauthorized, + ResponseBody: []byte(`{"error":{"code":"invalid_task_id"}}`), + })) +} + +func TestValidateOpenAIWSBearerTokenAllowsAgentIdentityWithoutStoredToken(t *testing.T) { + t.Run("Given Agent Identity When a WS path receives no bearer token Then dial-time assertion auth is allowed", func(t *testing.T) { + account := &Account{ + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + }, + } + + require.NoError(t, validateOpenAIWSBearerToken(account, "")) + }) + + t.Run("Given bearer credentials When a WS path receives no token Then the request is rejected", func(t *testing.T) { + accounts := []*Account{ + {Platform: PlatformOpenAI, Type: AccountTypeOAuth}, + {Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"auth_mode": OpenAIAuthModePersonalAccessToken}}, + {Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, + } + + for _, account := range accounts { + require.EqualError(t, validateOpenAIWSBearerToken(account, ""), "token is empty") + } + }) +} + +func TestOpenAIWSConnPoolHeadersFactoryRunsAtDialAndStalePrewarmIsDiscarded(t *testing.T) { + cfg := &config.Config{} + cfg.Gateway.OpenAIWS.MaxConnsPerAccount = 1 + pool := newOpenAIWSConnPool(cfg) + defer pool.Close() + pool.setClientDialerForTest(&openAIWSFakeDialer{}) + + accountID := int64(22) + ap := pool.getOrCreateAccountPool(accountID) + factoryCalls := 0 + latestHeader := "" + req := openAIWSAcquireRequest{ + Account: &Account{ID: accountID, Platform: PlatformOpenAI, Type: AccountTypeOAuth}, + WSURL: "wss://example.com/v1/responses", + HeadersFactory: func(_ context.Context, headers http.Header) (http.Header, error) { + factoryCalls++ + latestHeader = "AgentAssertion dial-" + string(rune('0'+factoryCalls)) + if headers == nil { + headers = make(http.Header) + } + headers.Set("Authorization", latestHeader) + return headers, nil + }, + } + ap.mu.Lock() + ap.lastAcquire = &req + generation := ap.generation + ap.mu.Unlock() + + pool.prewarmConns(accountID, req, 1, generation) + require.Equal(t, 1, factoryCalls, "prewarm must generate authorization inside the actual dial") + require.Equal(t, "AgentAssertion dial-1", latestHeader) + + pool.ClearAccount(accountID) + ap.mu.Lock() + require.Empty(t, ap.conns, "credential recovery must remove pooled connections") + require.Nil(t, ap.lastAcquire, "credential recovery must discard delayed acquire state") + require.Equal(t, generation+1, ap.generation) + ap.mu.Unlock() + + // A prewarm captured before ClearAccount must not be admitted after recovery. + pool.prewarmConns(accountID, req, 1, generation) + ap.mu.Lock() + require.Empty(t, ap.conns) + ap.mu.Unlock() +} + +func TestOpenAIAgentIdentityTaskInvalidRetriesExactlyOnce(t *testing.T) { + gin.SetMode(gin.TestMode) + key, privateKey := newTestAgentIdentityKey(t) + account := &Account{ + ID: 23, + Name: "agent-identity", + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": key.runtimeID, + "agent_private_key": privateKey, + "task_id": "task-old", + "chatgpt_account_id": "account-agent-retry", + }, + } + repo := &agentIdentityForwardRepo{account: account} + registerCalls := 0 + registerServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + registerCalls++ + _, _ = io.WriteString(w, `{"task_id":"task-new"}`) + })) + defer registerServer.Close() + oldBase := openAIAgentIdentityAuthAPIBaseURL + openAIAgentIdentityAuthAPIBaseURL = registerServer.URL + t.Cleanup(func() { openAIAgentIdentityAuthAPIBaseURL = oldBase }) + + successBody := `{"id":"resp-agent-retry","object":"response","model":"gpt-5.4","output":[],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}` + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + {StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"invalid_task_id"}}`))}, + {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(successBody))}, + }} + require.True(t, isAgentIdentityTaskInvalidHTTPResponse(http.StatusUnauthorized, []byte(`{"error":{"code":"invalid_task_id"}}`))) + svc := &OpenAIGatewayService{cfg: &config.Config{}, accountRepo: repo, httpUpstream: upstream} + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"gpt-5.4","instructions":"Reply OK","input":[],"stream":false}`)) + + _, err := svc.Forward(context.Background(), c, account, []byte(`{"model":"gpt-5.4","instructions":"Reply OK","input":[],"stream":false}`)) + require.NoError(t, err) + require.Equal(t, 1, registerCalls) + require.Len(t, upstream.requests, 2) + require.NotEqual(t, upstream.requests[0].Header.Get("Authorization"), upstream.requests[1].Header.Get("Authorization")) + require.Equal(t, "task-new", decodeAgentAssertionTask(t, upstream.requests[1].Header.Get("Authorization"))) + + // Two consecutive invalid responses still produce only one retry for this + // request; the recovery path must not loop indefinitely. + upstream.responses = []*http.Response{ + {StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"invalid_task_id"}}`))}, + {StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"invalid_task_id"}}`))}, + } + rec2 := httptest.NewRecorder() + c2, _ := gin.CreateTestContext(rec2) + c2.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"gpt-5.4","instructions":"Reply OK","input":[],"stream":false}`)) + _, err = svc.Forward(context.Background(), c2, account, []byte(`{"model":"gpt-5.4","instructions":"Reply OK","input":[],"stream":false}`)) + require.Error(t, err) + require.Equal(t, 2, registerCalls) + require.Len(t, upstream.requests, 4) + + // Passthrough uses the same one-shot task recovery contract. + account.Extra = map[string]any{"openai_passthrough": true} + account.Credentials["task_id"] = "task-old-passthrough" + upstream.responses = []*http.Response{ + {StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"invalid_task_id"}}`))}, + {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader("data: {\"type\":\"response.completed\",\"response\":{\"usage\":{\"input_tokens\":1,\"output_tokens\":1,\"total_tokens\":2}}}\n\ndata: [DONE]\n\n"))}, + } + rec3 := httptest.NewRecorder() + c3, _ := gin.CreateTestContext(rec3) + c3.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"gpt-5.4","instructions":"Reply OK","input":[],"stream":false}`)) + _, err = svc.Forward(context.Background(), c3, account, []byte(`{"model":"gpt-5.4","instructions":"Reply OK","input":[],"stream":false}`)) + require.NoError(t, err) + require.Equal(t, 3, registerCalls) + require.Len(t, upstream.requests, 6) +} + +func TestOpenAIAgentIdentityCompatRoutesRecoverInvalidTaskOnce(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + path string + body []byte + call func(*OpenAIGatewayService, context.Context, *gin.Context, *Account, []byte) (*OpenAIForwardResult, error) + }{ + { + name: "chat completions", + path: "/v1/chat/completions", + body: []byte(`{"model":"gpt-5.4","stream":false,"messages":[{"role":"user","content":"hi"}]}`), + call: func(s *OpenAIGatewayService, ctx context.Context, c *gin.Context, account *Account, body []byte) (*OpenAIForwardResult, error) { + return s.ForwardAsChatCompletions(ctx, c, account, body, "", "gpt-5.4") + }, + }, + { + name: "anthropic messages", + path: "/v1/messages", + body: []byte(`{"model":"gpt-5.4","stream":false,"max_tokens":32,"messages":[{"role":"user","content":"hi"}]}`), + call: func(s *OpenAIGatewayService, ctx context.Context, c *gin.Context, account *Account, body []byte) (*OpenAIForwardResult, error) { + return s.ForwardAsAnthropic(ctx, c, account, body, "", "gpt-5.4") + }, + }, + } + + for index, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key, privateKey := newTestAgentIdentityKey(t) + account := &Account{ + ID: int64(40 + index), + Name: "agent-identity-compat", + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": key.runtimeID, + "agent_private_key": privateKey, + "task_id": "task-compat-old", + "chatgpt_account_id": "account-compat-recovery", + }, + } + repo := &agentIdentityForwardRepo{account: account} + registerCalls := 0 + registerServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + registerCalls++ + _, _ = io.WriteString(w, `{"task_id":"task-compat-new"}`) + })) + defer registerServer.Close() + oldBase := openAIAgentIdentityAuthAPIBaseURL + openAIAgentIdentityAuthAPIBaseURL = registerServer.URL + t.Cleanup(func() { openAIAgentIdentityAuthAPIBaseURL = oldBase }) + + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + {StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"invalid_task_id"}}`))}, + {StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"invalid_task_id"}}`))}, + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, accountRepo: repo, httpUpstream: upstream} + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, tt.path, bytes.NewReader(tt.body)) + + _, err := tt.call(svc, context.Background(), c, account, tt.body) + require.Error(t, err) + require.Equal(t, 1, registerCalls) + require.Len(t, upstream.requests, 2) + require.Equal(t, "task-compat-new", account.GetCredential("task_id")) + }) + } +} + +func decodeAgentAssertionTask(t *testing.T, header string) string { + t.Helper() + encoded := strings.TrimPrefix(header, "AgentAssertion ") + decoded, err := base64.RawURLEncoding.DecodeString(encoded) + require.NoError(t, err) + var envelope struct { + TaskID string `json:"task_id"` + } + require.NoError(t, json.Unmarshal(decoded, &envelope)) + return envelope.TaskID +} + +type agentIdentityForwardRepo struct { + AccountRepository + account *Account +} + +type agentIdentityWSInvalidationRecorder struct { + accountIDs []int64 +} + +func (r *agentIdentityWSInvalidationRecorder) InvalidateAgentIdentityWSConnections(accountID int64) { + r.accountIDs = append(r.accountIDs, accountID) +} + +type accountTestAgentIdentityRepo struct { + AccountRepository + account *Account + setErrorCalls int +} + +func (r *accountTestAgentIdentityRepo) GetByID(_ context.Context, _ int64) (*Account, error) { + return r.account, nil +} + +func (r *accountTestAgentIdentityRepo) UpdateCredentials(_ context.Context, _ int64, credentials map[string]any) error { + r.account.Credentials = credentials + return nil +} + +func (r *accountTestAgentIdentityRepo) UpdateExtra(_ context.Context, _ int64, _ map[string]any) error { + return nil +} + +func (r *accountTestAgentIdentityRepo) SetError(_ context.Context, _ int64, _ string) error { + r.setErrorCalls++ + return nil +} + +func (r *agentIdentityForwardRepo) GetByID(_ context.Context, _ int64) (*Account, error) { + return r.account, nil +} + +func (r *agentIdentityForwardRepo) UpdateCredentials(_ context.Context, _ int64, credentials map[string]any) error { + r.account.Credentials = credentials + return nil +} diff --git a/backend/internal/service/openai_agent_identity_test.go b/backend/internal/service/openai_agent_identity_test.go new file mode 100644 index 0000000000..a906f044f0 --- /dev/null +++ b/backend/internal/service/openai_agent_identity_test.go @@ -0,0 +1,229 @@ +package service + +import ( + "context" + "crypto/ed25519" + "crypto/rand" + "crypto/sha512" + "crypto/x509" + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" + "golang.org/x/crypto/curve25519" + "golang.org/x/crypto/nacl/box" +) + +func newTestAgentIdentityKey(t *testing.T) (agentIdentityKey, string) { + t.Helper() + _, privateKey, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + der, err := x509.MarshalPKCS8PrivateKey(privateKey) + require.NoError(t, err) + return agentIdentityKey{ + runtimeID: "runtime-test", + privateKey: privateKey, + taskID: "task-test", + }, base64.StdEncoding.EncodeToString(der) +} + +func TestBuildAgentAssertionMatchesCodexEnvelopeAndSignature(t *testing.T) { + key, _ := newTestAgentIdentityKey(t) + now := time.Date(2026, 7, 14, 8, 9, 10, 0, time.FixedZone("UTC+8", 8*60*60)) + assertion, err := buildAgentAssertion(key, now) + require.NoError(t, err) + require.True(t, strings.HasPrefix(assertion, "AgentAssertion ")) + + encoded := strings.TrimPrefix(assertion, "AgentAssertion ") + decoded, err := base64.RawURLEncoding.DecodeString(encoded) + require.NoError(t, err) + var envelope struct { + AgentRuntimeID string `json:"agent_runtime_id"` + TaskID string `json:"task_id"` + Timestamp string `json:"timestamp"` + Signature string `json:"signature"` + } + require.NoError(t, json.Unmarshal(decoded, &envelope)) + require.Equal(t, "runtime-test", envelope.AgentRuntimeID) + require.Equal(t, "task-test", envelope.TaskID) + require.Equal(t, "2026-07-14T00:09:10Z", envelope.Timestamp) + signature, err := base64.StdEncoding.DecodeString(envelope.Signature) + require.NoError(t, err) + publicKey, ok := key.privateKey.Public().(ed25519.PublicKey) + require.True(t, ok) + require.True(t, ed25519.Verify(publicKey, []byte("runtime-test:task-test:2026-07-14T00:09:10Z"), signature)) +} + +func TestDecryptAgentTaskIDSupportsCodexSealedBoxResponse(t *testing.T) { + key, _ := newTestAgentIdentityKey(t) + digest := sha512.Sum512(key.privateKey.Seed()) + var curvePrivate [32]byte + copy(curvePrivate[:], digest[:32]) + curvePrivate[0] &= 248 + curvePrivate[31] &= 127 + curvePrivate[31] |= 64 + curvePublicBytes, err := curve25519.X25519(curvePrivate[:], curve25519.Basepoint) + require.NoError(t, err) + var curvePublic [32]byte + copy(curvePublic[:], curvePublicBytes) + ciphertext, err := box.SealAnonymous(nil, []byte("task-sealed"), &curvePublic, rand.Reader) + require.NoError(t, err) + got, err := decryptAgentTaskID(key, base64.StdEncoding.EncodeToString(ciphertext)) + require.NoError(t, err) + require.Equal(t, "task-sealed", got) +} + +func TestRegisterAgentIdentityTaskAcceptsPlaintextAndEncryptedResponses(t *testing.T) { + key, privateKey := newTestAgentIdentityKey(t) + requestCount := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.Equal(t, http.MethodPost, r.Method) + require.Equal(t, "/v1/agent/runtime-test/task/register", r.URL.Path) + var request map[string]string + require.NoError(t, json.NewDecoder(r.Body).Decode(&request)) + require.NotEmpty(t, request["timestamp"]) + require.NotEmpty(t, request["signature"]) + requestCount++ + if requestCount == 2 { + digest := sha512.Sum512(key.privateKey.Seed()) + var curvePrivate [32]byte + copy(curvePrivate[:], digest[:32]) + curvePrivate[0] &= 248 + curvePrivate[31] &= 127 + curvePrivate[31] |= 64 + curvePublicBytes, curveErr := curve25519.X25519(curvePrivate[:], curve25519.Basepoint) + require.NoError(t, curveErr) + var curvePublic [32]byte + copy(curvePublic[:], curvePublicBytes) + ciphertext, sealErr := box.SealAnonymous(nil, []byte("task-encrypted"), &curvePublic, rand.Reader) + require.NoError(t, sealErr) + _, _ = fmt.Fprintf(w, `{"encrypted_task_id":%q}`, base64.StdEncoding.EncodeToString(ciphertext)) + return + } + _, _ = w.Write([]byte(`{"task_id":"task-plain"}`)) + })) + defer server.Close() + oldBase := openAIAgentIdentityAuthAPIBaseURL + openAIAgentIdentityAuthAPIBaseURL = server.URL + t.Cleanup(func() { openAIAgentIdentityAuthAPIBaseURL = oldBase }) + + account := &Account{ID: 1, Type: AccountTypeOAuth, Platform: PlatformOpenAI, Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": key.runtimeID, + "agent_private_key": privateKey, + }} + taskID, err := registerAgentIdentityTask(context.Background(), account) + require.NoError(t, err) + require.Equal(t, "task-plain", taskID) + taskID, err = registerAgentIdentityTask(context.Background(), account) + require.NoError(t, err) + require.Equal(t, "task-encrypted", taskID) +} + +func TestEnsureAgentIdentityTaskPersistsAndRedactsCredentials(t *testing.T) { + key, privateKey := newTestAgentIdentityKey(t) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(`{"task_id":"task-persisted"}`)) + })) + defer server.Close() + oldBase := openAIAgentIdentityAuthAPIBaseURL + openAIAgentIdentityAuthAPIBaseURL = server.URL + t.Cleanup(func() { openAIAgentIdentityAuthAPIBaseURL = oldBase }) + + repo := &agentIdentityCredentialsRepo{} + account := &Account{ID: 7, Type: AccountTypeOAuth, Platform: PlatformOpenAI, Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": key.runtimeID, + "agent_private_key": privateKey, + "chatgpt_account_id": "account-test", + }} + service := &OpenAIGatewayService{accountRepo: repo} + require.NoError(t, service.ensureAgentIdentityTask(context.Background(), account, "")) + require.Equal(t, "task-persisted", account.GetCredential("task_id")) + require.Equal(t, "task-persisted", repo.credentials["task_id"]) + require.True(t, IsSensitiveCredentialKey("agent_private_key")) + redacted := make(map[string]any) + for key, value := range account.Credentials { + if !IsSensitiveCredentialKey(key) { + redacted[key] = value + } + } + require.NotContains(t, string(mustAgentIdentityJSON(t, redacted)), privateKey) +} + +func TestEnsureAgentIdentityTaskSharesLockAcrossServicesForSameAccount(t *testing.T) { + key, privateKey := newTestAgentIdentityKey(t) + account := &Account{ID: 9001, Type: AccountTypeOAuth, Platform: PlatformOpenAI, Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": key.runtimeID, + "agent_private_key": privateKey, + }} + repo := &agentIdentityCredentialsRepo{account: account} + registerCalls := 0 + var registerMu sync.Mutex + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + registerMu.Lock() + registerCalls++ + registerMu.Unlock() + _, _ = w.Write([]byte(`{"task_id":"task-shared"}`)) + })) + defer server.Close() + oldBase := openAIAgentIdentityAuthAPIBaseURL + openAIAgentIdentityAuthAPIBaseURL = server.URL + t.Cleanup(func() { openAIAgentIdentityAuthAPIBaseURL = oldBase }) + + start := make(chan struct{}) + errors := make(chan error, 2) + requests := []*Account{cloneAgentIdentityTestAccount(account), cloneAgentIdentityTestAccount(account)} + for _, request := range requests { + go func() { + <-start + errors <- ensureAgentIdentityTaskForAccount(context.Background(), repo, nil, &sync.Mutex{}, request, "") + }() + } + close(start) + require.NoError(t, <-errors) + require.NoError(t, <-errors) + registerMu.Lock() + defer registerMu.Unlock() + require.Equal(t, 1, registerCalls) + require.Equal(t, "task-shared", repo.account.GetCredential("task_id")) +} + +func cloneAgentIdentityTestAccount(account *Account) *Account { + copy := *account + copy.Credentials = shallowCopyMap(account.Credentials) + return © +} + +type agentIdentityCredentialsRepo struct { + AccountRepository + credentials map[string]any + account *Account + mu sync.Mutex +} + +func (r *agentIdentityCredentialsRepo) GetByID(_ context.Context, _ int64) (*Account, error) { + return r.account, nil +} + +func (r *agentIdentityCredentialsRepo) UpdateCredentials(_ context.Context, _ int64, credentials map[string]any) error { + r.mu.Lock() + defer r.mu.Unlock() + r.credentials = credentials + return nil +} + +func mustAgentIdentityJSON(t *testing.T, value any) []byte { + t.Helper() + encoded, err := json.Marshal(value) + require.NoError(t, err) + return encoded +} diff --git a/backend/internal/service/openai_codex_models_service.go b/backend/internal/service/openai_codex_models_service.go index a7331f64c9..1d9356441c 100644 --- a/backend/internal/service/openai_codex_models_service.go +++ b/backend/internal/service/openai_codex_models_service.go @@ -241,7 +241,7 @@ func (s *OpenAIGatewayService) FetchCodexModelsManifest(ctx context.Context, acc switch { case credAccount.IsOpenAIOAuth(): authToken = strings.TrimSpace(credAccount.GetOpenAIAccessToken()) - if authToken == "" { + if authToken == "" && !credAccount.IsOpenAIAgentIdentity() { return nil, infraerrors.New(http.StatusBadGateway, "OPENAI_CODEX_MODELS_TOKEN_MISSING", "account has no Codex backend access token") } case credAccount.IsOpenAIApiKey(): @@ -277,16 +277,25 @@ func (s *OpenAIGatewayService) FetchCodexModelsManifest(ctx context.Context, acc } headers := make(http.Header) - headers.Set("Authorization", "Bearer "+authToken) + if useAPIKeyUpstream { + headers.Set("Authorization", "Bearer "+authToken) + credAccount.ApplyHeaderOverrides(headers) + } else { + authHeaders, authErr := s.buildOpenAIAuthenticationHeaders(ctx, credAccount, authToken) + if authErr != nil { + return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_CODEX_MODELS_AUTH_FAILED", "build Codex models authentication: %v", authErr) + } + for key, values := range authHeaders { + for _, value := range values { + headers.Add(key, value) + } + } + setOpenAIChatGPTAccountHeaders(headers, credAccount) + } headers.Set("Accept", "application/json") headers.Set("Originator", "codex_cli_rs") headers.Set("Version", clientVersion) headers.Set("User-Agent", codexCLIUserAgent) - if useAPIKeyUpstream { - credAccount.ApplyHeaderOverrides(headers) - } else { - setOpenAIChatGPTAccountHeaders(headers, credAccount) - } proxyURL := "" if account.ProxyID != nil && account.Proxy != nil { diff --git a/backend/internal/service/openai_codex_models_service_test.go b/backend/internal/service/openai_codex_models_service_test.go index 2c87861f60..3f4ec96a2f 100644 --- a/backend/internal/service/openai_codex_models_service_test.go +++ b/backend/internal/service/openai_codex_models_service_test.go @@ -199,6 +199,49 @@ func TestFetchCodexModelsManifestPassthrough(t *testing.T) { } } +func TestFetchCodexModelsManifestAgentIdentityUsesAssertionWithoutOAuthToken(t *testing.T) { + key, privateKey := newTestAgentIdentityKey(t) + account := &Account{ + ID: 3, + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": key.runtimeID, + "agent_private_key": privateKey, + "task_id": key.taskID, + "chatgpt_account_id": "acc-agent", + }, + } + + var gotAuth, gotAccountID string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotAuth = r.Header.Get("Authorization") + gotAccountID = r.Header.Get("chatgpt-account-id") + _, _ = w.Write([]byte(`{"models":[]}`)) + })) + defer server.Close() + + original := chatgptCodexModelsURL + chatgptCodexModelsURL = server.URL + defer func() { chatgptCodexModelsURL = original }() + + s := &OpenAIGatewayService{} + manifest, err := s.FetchCodexModelsManifest(context.Background(), account, "0.137.0", "") + if err != nil { + t.Fatalf("FetchCodexModelsManifest returned error: %v", err) + } + if string(manifest.Body) != `{"models":[]}` { + t.Fatalf("unexpected manifest body: %q", manifest.Body) + } + if !strings.HasPrefix(gotAuth, "AgentAssertion ") { + t.Fatalf("authorization scheme: got %q", strings.SplitN(gotAuth, " ", 2)[0]) + } + if gotAccountID != "acc-agent" { + t.Fatalf("chatgpt-account-id header: got %q", gotAccountID) + } +} + func TestFetchCodexModelsManifestDefaultClientVersion(t *testing.T) { var gotClientVersion string server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/backend/internal/service/openai_codex_transform.go b/backend/internal/service/openai_codex_transform.go index 3bde4abcfb..6535454403 100644 --- a/backend/internal/service/openai_codex_transform.go +++ b/backend/internal/service/openai_codex_transform.go @@ -83,6 +83,8 @@ type codexOAuthTransformOptions struct { PreserveToolCallIDs bool } +const codexImageGenerationFunctionToolName = "image_gen.imagegen" + const ( codexImageGenerationBridgeMarker = "" codexImageGenerationBridgeText = codexImageGenerationBridgeMarker + "\nWhen the user asks for raster image generation or editing, use the OpenAI Responses native `image_generation` tool attached to this request. The local Codex client may not expose an `image_gen` namespace, but that does not mean image generation is unavailable. Do not ask the user to switch to CLI fallback solely because `image_gen` is absent.\n" @@ -312,13 +314,30 @@ func normalizeCodexToolChoice(reqBody map[string]any) bool { } return modified } - if codexToolsContainType(reqBody["tools"], choiceType) { + if codexToolsContainType(reqBody["tools"], choiceType) || codexInputAdditionalToolsContainType(reqBody["input"], choiceType) { return modified } reqBody["tool_choice"] = "auto" return true } +func codexInputAdditionalToolsContainType(rawInput any, toolType string) bool { + input, ok := rawInput.([]any) + if !ok || strings.TrimSpace(toolType) == "" { + return false + } + for _, rawItem := range input { + item, ok := rawItem.(map[string]any) + if !ok || strings.TrimSpace(firstNonEmptyString(item["type"])) != "additional_tools" { + continue + } + if codexToolsContainType(item["tools"], toolType) { + return true + } + } + return false +} + func codexToolsContainType(rawTools any, toolType string) bool { tools, ok := rawTools.([]any) if !ok || strings.TrimSpace(toolType) == "" { @@ -599,6 +618,11 @@ func hasOpenAIImageGenerationTool(reqBody map[string]any) bool { return inputContainsImageGenerationTool(reqBody["input"]) } +func hasCodexImageGenerationFunctionTool(reqBody map[string]any) bool { + return len(reqBody) > 0 && + codexToolsContainFunctionName(reqBody["tools"], codexImageGenerationFunctionToolName) +} + func toolsContainImageGeneration(rawTools any) bool { if rawTools == nil { return false @@ -838,6 +862,9 @@ func ensureOpenAIResponsesImageGenerationTool(reqBody map[string]any) bool { if isCodexSparkModel(firstNonEmptyString(reqBody["model"])) { return false } + if hasCodexImageGenerationFunctionTool(reqBody) { + return false + } if hasOpenAIImageGenerationTool(reqBody) { return false } @@ -863,7 +890,7 @@ func ensureOpenAIResponsesImageGenerationTool(reqBody map[string]any) bool { } func ensureOpenAIResponsesImageGenerationToolChoiceAuto(reqBody map[string]any) bool { - if len(reqBody) == 0 || !hasOpenAIImageGenerationTool(reqBody) { + if len(reqBody) == 0 || hasCodexImageGenerationFunctionTool(reqBody) || !hasOpenAIImageGenerationTool(reqBody) { return false } if isCodexSparkModel(firstNonEmptyString(reqBody["model"])) { @@ -877,7 +904,7 @@ func ensureOpenAIResponsesImageGenerationToolChoiceAuto(reqBody map[string]any) } func applyCodexImageGenerationBridgeInstructions(reqBody map[string]any) bool { - if len(reqBody) == 0 || !hasOpenAIImageGenerationTool(reqBody) { + if len(reqBody) == 0 || hasCodexImageGenerationFunctionTool(reqBody) || !hasOpenAIImageGenerationTool(reqBody) { return false } if isCodexSparkModel(firstNonEmptyString(reqBody["model"])) { diff --git a/backend/internal/service/openai_codex_transform_test.go b/backend/internal/service/openai_codex_transform_test.go index 456740136b..40d0fd4b41 100644 --- a/backend/internal/service/openai_codex_transform_test.go +++ b/backend/internal/service/openai_codex_transform_test.go @@ -676,6 +676,86 @@ func TestEnsureOpenAIResponsesImageGenerationTool_PreservesImageGenNamespace(t * } } +func TestCodexImageGenerationBridge_PreservesClientImageFunctionTools(t *testing.T) { + tests := []struct { + name string + reqBody map[string]any + wantClient bool + }{ + { + name: "flat image_gen function", + reqBody: map[string]any{ + "model": "gpt-5.5", + "input": "draw a cat", + "tools": []any{ + map[string]any{"type": "function", "name": "image_gen.imagegen"}, + }, + }, + wantClient: true, + }, + { + name: "nested image_gen function", + reqBody: map[string]any{ + "model": "gpt-5.5", + "input": "draw a cat", + "tools": []any{ + map[string]any{ + "type": "function", + "function": map[string]any{ + "name": "image_gen.imagegen", + }, + }, + }, + }, + wantClient: true, + }, + { + name: "similar function name still receives hosted bridge", + reqBody: map[string]any{ + "model": "gpt-5.5", + "input": "draw a cat", + "tools": []any{ + map[string]any{"type": "function", "name": "image_gen.imagegenerator"}, + }, + }, + wantClient: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.reqBody["instructions"] = "existing instructions" + require.Equal(t, tt.wantClient, hasCodexImageGenerationFunctionTool(tt.reqBody)) + + toolModified := ensureOpenAIResponsesImageGenerationTool(tt.reqBody) + choiceModified := ensureOpenAIResponsesImageGenerationToolChoiceAuto(tt.reqBody) + instructionsModified := applyCodexImageGenerationBridgeInstructions(tt.reqBody) + + require.Equal(t, !tt.wantClient, toolModified) + require.Equal(t, !tt.wantClient, choiceModified) + require.Equal(t, !tt.wantClient, instructionsModified) + + hasHostedTool := false + tools, _ := tt.reqBody["tools"].([]any) + for _, rawTool := range tools { + tool, ok := rawTool.(map[string]any) + if ok && firstNonEmptyString(tool["type"]) == "image_generation" { + hasHostedTool = true + } + } + require.Equal(t, !tt.wantClient, hasHostedTool) + + if tt.wantClient { + require.NotContains(t, tt.reqBody, "tool_choice") + require.Equal(t, "existing instructions", tt.reqBody["instructions"]) + } else { + require.Equal(t, "auto", tt.reqBody["tool_choice"]) + require.Contains(t, tt.reqBody["instructions"], codexImageGenerationBridgeMarker) + } + }) + } +} + func TestApplyCodexImageGenerationBridgeInstructions_AppendsBridgeOnce(t *testing.T) { reqBody := map[string]any{ "model": "gpt-5.4", diff --git a/backend/internal/service/openai_content_session_seed.go b/backend/internal/service/openai_content_session_seed.go index fce85f11bd..5f8f1872e8 100644 --- a/backend/internal/service/openai_content_session_seed.go +++ b/backend/internal/service/openai_content_session_seed.go @@ -1,6 +1,7 @@ package service import ( + "bytes" "encoding/json" "strings" @@ -25,31 +26,96 @@ func deriveOpenAIContentSessionSeed(body []byte) string { return "" } + const ( + modelField = iota + toolsField + functionsField + instructionsField + messagesField + inputField + contentSessionSeedFieldCount + allContentSessionSeedFields = 1< len(root) { + return false + } + // Result.ForEach can continue after the root '}' on malformed input. + // The separator range excludes braces inside the preceding parsed value. + if bytes.IndexByte(root[nextKeyOffset:key.Index], '}') >= 0 { + return false + } + nextKeyOffset = value.Index + len(value.Raw) + + field := -1 + switch key.Str { + case "model": + field = modelField + case "tools": + field = toolsField + case "functions": + field = functionsField + case "instructions": + field = instructionsField + case "messages": + field = messagesField + case "input": + field = inputField + } + if field < 0 { + return true + } + mask := uint8(1 << field) + if seen&mask == 0 { + fields[field] = value + seen |= mask + } + return seen != allContentSessionSeedFields + }) + var b strings.Builder - if model := gjson.GetBytes(body, "model").String(); model != "" { + if model := fields[modelField].String(); model != "" { _, _ = b.WriteString("model=") _, _ = b.WriteString(model) } - if tools := gjson.GetBytes(body, "tools"); tools.Exists() && tools.IsArray() && tools.Raw != "[]" { + if tools := fields[toolsField]; tools.Exists() && tools.IsArray() && tools.Raw != "[]" { _, _ = b.WriteString("|tools=") _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(tools.Raw))) } - if funcs := gjson.GetBytes(body, "functions"); funcs.Exists() && funcs.IsArray() && funcs.Raw != "[]" { + if funcs := fields[functionsField]; funcs.Exists() && funcs.IsArray() && funcs.Raw != "[]" { _, _ = b.WriteString("|functions=") _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(funcs.Raw))) } - if instr := gjson.GetBytes(body, "instructions").String(); instr != "" { + if instr := fields[instructionsField].String(); instr != "" { _, _ = b.WriteString("|instructions=") _, _ = b.WriteString(instr) } firstUserCaptured := false - msgs := gjson.GetBytes(body, "messages") + msgs := fields[messagesField] if msgs.Exists() && msgs.IsArray() { msgs.ForEach(func(_, msg gjson.Result) bool { role := msg.Get("role").String() @@ -70,7 +136,7 @@ func deriveOpenAIContentSessionSeed(body []byte) string { } return true }) - } else if inp := gjson.GetBytes(body, "input"); inp.Exists() { + } else if inp := fields[inputField]; inp.Exists() { if inp.Type == gjson.String { _, _ = b.WriteString("|input=") _, _ = b.WriteString(inp.String()) diff --git a/backend/internal/service/openai_content_session_seed_benchmark_test.go b/backend/internal/service/openai_content_session_seed_benchmark_test.go new file mode 100644 index 0000000000..eda9deaa82 --- /dev/null +++ b/backend/internal/service/openai_content_session_seed_benchmark_test.go @@ -0,0 +1,29 @@ +package service + +import ( + "strings" + "testing" +) + +var benchmarkOpenAIContentSessionSeed string + +func BenchmarkDeriveOpenAIContentSessionSeedLargeBody(b *testing.B) { + largeHistory := strings.Repeat("payload", 1<<17) + tests := []struct { + name string + body []byte + }{ + {name: "ChatCompletions", body: []byte(`{"model":"gpt-5.4","tools":[{"type":"function","function":{"name":"lookup"}}],"messages":[{"role":"system","content":"Be concise."},{"role":"user","content":"Hello"},{"role":"assistant","content":"` + largeHistory + `"},{"role":"user","content":"Follow-up"}]}`)}, + {name: "Responses", body: []byte(`{"model":"gpt-5.4","instructions":"Be concise.","tools":[{"type":"function","name":"lookup"}],"input":[{"role":"system","content":"System prompt"},{"role":"user","content":"Hello"},{"role":"assistant","content":"` + largeHistory + `"}]}`)}, + } + + for _, test := range tests { + b.Run(test.name, func(b *testing.B) { + b.ReportAllocs() + b.SetBytes(int64(len(test.body))) + for range b.N { + benchmarkOpenAIContentSessionSeed = deriveOpenAIContentSessionSeed(test.body) + } + }) + } +} diff --git a/backend/internal/service/openai_content_session_seed_test.go b/backend/internal/service/openai_content_session_seed_test.go index 6dadc5cf53..0c6c63335c 100644 --- a/backend/internal/service/openai_content_session_seed_test.go +++ b/backend/internal/service/openai_content_session_seed_test.go @@ -1,9 +1,12 @@ package service import ( + "encoding/json" + "strings" "testing" "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" ) func TestDeriveOpenAIContentSessionSeed_EmptyInputs(t *testing.T) { @@ -197,6 +200,184 @@ func TestDeriveOpenAIContentSessionSeed_JSONCanonicalisation(t *testing.T) { require.Equal(t, s1, s2, "different formatting of identical JSON should produce the same seed") } +func TestDeriveOpenAIContentSessionSeed_SingleScanMatchesLegacyBytes(t *testing.T) { + largeValue := strings.Repeat("payload", 1<<17) + tests := []struct { + name string + body []byte + }{ + { + name: "large chat completions", + body: []byte(`{"metadata":"` + largeValue + `","model":"gpt-5.4","tools":[{"type":"function","function":{"name":"lookup"}}],"functions":[{"name":"legacy_lookup"}],"messages":[{"role":"system","content":"System prompt"},{"role":"developer","content":[{"type":"text","text":"Developer prompt"}]},{"role":"user","content":"Hello"}]}`), + }, + { + name: "large responses", + body: []byte(`{"metadata":"` + largeValue + `","model":"gpt-5.4","instructions":"Be concise.","tools":[{"type":"function","name":"lookup"}],"input":[{"role":"system","content":"System prompt"},{"role":"user","content":[{"type":"input_text","text":"Hello"}]}]}`), + }, + { + name: "fields in reverse order", + body: []byte(`{"input":"fallback input","messages":[{"role":"user","content":"chat wins"}],"instructions":"Be concise.","functions":[{"name":"lookup"}],"tools":[{"type":"function","name":"lookup"}],"model":"gpt-5.4"}`), + }, + { + name: "missing and wrong type fields", + body: []byte(`{"tools":[],"functions":null,"instructions":0,"messages":{},"input":[{"type":"input_text","text":"fallback"}]}`), + }, + { + name: "duplicate fields keep first value", + body: []byte(`{"model":"first","model":"second","tools":[{"name":"first"}],"tools":[{"name":"second"}],"functions":[],"functions":[{"name":"second"}],"instructions":"first","instructions":"second","messages":null,"messages":[{"role":"user","content":"second"}],"input":"first input","input":"second input"}`), + }, + { + name: "escaped field names", + body: []byte(`{"mo\u0064el":"gpt-5.4","mess\u0061ges":[{"role":"user","content":"Hello"}]}`), + }, + { + name: "trailing object fields are outside the root", + body: []byte(`{"foo":1}{"model":"trailing","input":"trailing input"}`), + }, + { + name: "trailing quoted fields are outside the root", + body: []byte(`{"model":"root"}"input":"trailing input"`), + }, + { + name: "leading garbage before the root", + body: []byte(`garbage{"model":"gpt-5.4","input":"Hello"}`), + }, + { + name: "escaped braces remain inside string values", + body: []byte(`{"metadata":"escaped } and [ and \" quote","model":"root","input":"Hello"}{"model":"trailing"}`), + }, + { + name: "nested braces do not end the root", + body: []byte(`{"metadata":{"nested":"} ]"},"model":"root","input":"Hello"}{"model":"trailing"}`), + }, + { + name: "root array does not expose nested or trailing object fields", + body: []byte(`[{"model":"nested"}]{"model":"trailing","input":"trailing input"}`), + }, + { + name: "trailing messages do not override root input", + body: []byte(`{"input":"root input"}{"messages":[{"role":"user","content":"trailing"}]}`), + }, + { + name: "truncated string containing a closing brace", + body: []byte(`{"model":"root","metadata":"still } inside`), + }, + { + name: "lenient truncated body", + body: []byte(`{"model":"gpt-5.4","messages":[{"role":"user","content":"Hello"}]`), + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + require.Equal(t, legacyDeriveOpenAIContentSessionSeed(test.body), deriveOpenAIContentSessionSeed(test.body)) + }) + } +} + +func TestDeriveOpenAIContentSessionSeed_AllTruncationOffsetsMatchLegacyBytes(t *testing.T) { + bodies := []string{ + `{"model":"gpt-5.4","tools":[{"type":"function","function":{"name":"lookup"}}],"functions":[{"name":"legacy"}],"instructions":"escaped \" } text","messages":[{"role":"system","content":"System"},{"role":"user","content":[{"type":"text","text":"Hello"}]}],"input":"fallback"}`, + `{"model":"gpt-5.4","instructions":"Be concise.","tools":[{"type":"function","name":"lookup"}],"input":[{"role":"system","content":"System"},{"role":"user","content":[{"type":"input_text","text":"Hello"}]}]}`, + } + for bodyIndex, body := range bodies { + for end := 1; end < len(body); end++ { + truncated := []byte(body[:end]) + require.Equalf(t, legacyDeriveOpenAIContentSessionSeed(truncated), deriveOpenAIContentSessionSeed(truncated), "body %d truncated at byte %d", bodyIndex, end) + } + } +} + +func legacyDeriveOpenAIContentSessionSeed(body []byte) string { + if len(body) == 0 { + return "" + } + + var b strings.Builder + + if model := gjson.GetBytes(body, "model").String(); model != "" { + _, _ = b.WriteString("model=") + _, _ = b.WriteString(model) + } + + if tools := gjson.GetBytes(body, "tools"); tools.Exists() && tools.IsArray() && tools.Raw != "[]" { + _, _ = b.WriteString("|tools=") + _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(tools.Raw))) + } + + if funcs := gjson.GetBytes(body, "functions"); funcs.Exists() && funcs.IsArray() && funcs.Raw != "[]" { + _, _ = b.WriteString("|functions=") + _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(funcs.Raw))) + } + + if instr := gjson.GetBytes(body, "instructions").String(); instr != "" { + _, _ = b.WriteString("|instructions=") + _, _ = b.WriteString(instr) + } + + firstUserCaptured := false + + msgs := gjson.GetBytes(body, "messages") + if msgs.Exists() && msgs.IsArray() { + msgs.ForEach(func(_, msg gjson.Result) bool { + role := msg.Get("role").String() + switch role { + case "system", "developer": + _, _ = b.WriteString("|system=") + if c := msg.Get("content"); c.Exists() { + _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(c.Raw))) + } + case "user": + if !firstUserCaptured { + _, _ = b.WriteString("|first_user=") + if c := msg.Get("content"); c.Exists() { + _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(c.Raw))) + } + firstUserCaptured = true + } + } + return true + }) + } else if inp := gjson.GetBytes(body, "input"); inp.Exists() { + if inp.Type == gjson.String { + _, _ = b.WriteString("|input=") + _, _ = b.WriteString(inp.String()) + } else if inp.IsArray() { + inp.ForEach(func(_, item gjson.Result) bool { + role := item.Get("role").String() + switch role { + case "system", "developer": + _, _ = b.WriteString("|system=") + if c := item.Get("content"); c.Exists() { + _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(c.Raw))) + } + case "user": + if !firstUserCaptured { + _, _ = b.WriteString("|first_user=") + if c := item.Get("content"); c.Exists() { + _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(c.Raw))) + } + firstUserCaptured = true + } + } + if !firstUserCaptured && item.Get("type").String() == "input_text" { + _, _ = b.WriteString("|first_user=") + if text := item.Get("text").String(); text != "" { + _, _ = b.WriteString(text) + } + firstUserCaptured = true + } + return true + }) + } + } + + if b.Len() == 0 { + return "" + } + return contentSessionSeedPrefix + b.String() +} + func TestDeriveOpenAIContentSessionSeed_ResponsesAPI_InputTextTypedItem(t *testing.T) { body := []byte(`{ "model": "gpt-5.4", diff --git a/backend/internal/service/openai_first_output_timeout.go b/backend/internal/service/openai_first_output_timeout.go new file mode 100644 index 0000000000..fbd985d067 --- /dev/null +++ b/backend/internal/service/openai_first_output_timeout.go @@ -0,0 +1,335 @@ +package service + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "io" + "net/http" + "os" + "runtime" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" + "github.com/gin-gonic/gin" +) + +const ( + openAIFirstOutputStageMemoryLimit = 64 * 1024 + openAIFirstOutputStageMaxBytes = 8 * 1024 * 1024 + openAIFirstOutputScannerFramingAllowance = 64 + openAIFirstOutputGuardQueueSize = 1 + openAIDefaultStreamQueueSize = 16 +) + +var ( + errOpenAIFirstOutputStageLimit = errors.New("openai first-output staging limit exceeded") + errOpenAIFirstOutputScannerLimit = errors.New("openai pre-output scanner token limit exceeded") +) + +type openAIFirstOutputStage struct { + limit int64 + size int64 + memory bytes.Buffer + tempFile *os.File + tempPath string + createTemp func() (*os.File, error) + removeFile func(string) error + memoryOnly bool + cleanupErr error + closed bool +} + +func newOpenAIFirstOutputStage(limit int64) *openAIFirstOutputStage { + if limit < 1 { + limit = 1 + } + return &openAIFirstOutputStage{ + limit: limit, + createTemp: func() (*os.File, error) { return os.CreateTemp("", "sub2api-openai-first-output-*") }, + removeFile: os.Remove, + memoryOnly: runtime.GOOS == "windows", + } +} + +func newDefaultOpenAIFirstOutputStage() *openAIFirstOutputStage { + return newOpenAIFirstOutputStage(openAIFirstOutputStageMaxBytes) +} + +func openAIFirstOutputEventQueueSize(guardFirstOutput bool) int { + if guardFirstOutput { + return openAIFirstOutputGuardQueueSize + } + return openAIDefaultStreamQueueSize +} + +func openAIFirstOutputDynamicScanLines(guardActive *atomic.Bool) bufio.SplitFunc { + return func(data []byte, atEOF bool) (advance int, token []byte, err error) { + advance, token, err = bufio.ScanLines(data, atEOF) + if err != nil || guardActive == nil || !guardActive.Load() { + return advance, token, err + } + limit := openAIFirstOutputStageMaxBytes + openAIFirstOutputScannerFramingAllowance + if token != nil { + if len(token) > limit { + return 0, nil, errOpenAIFirstOutputScannerLimit + } + return advance, token, nil + } + // At the limit with no delimiter, another byte would necessarily exceed + // the guarded token budget. Fail before Scanner grows toward MaxLineSize. + if len(data) >= limit { + return 0, nil, errOpenAIFirstOutputScannerLimit + } + return advance, token, nil + } +} + +func (s *openAIFirstOutputStage) Buffered() int64 { + if s == nil { + return 0 + } + return s.size +} + +func (s *openAIFirstOutputStage) WriteString(value string) (int, error) { + if err := s.prepareWrite(len(value)); err != nil { + return 0, err + } + var n int + var err error + if s.tempFile == nil { + n, err = s.memory.WriteString(value) + } else { + n, err = io.WriteString(s.tempFile, value) + } + s.size += int64(n) + if err != nil { + return n, fmt.Errorf("write first-output stage: %w", err) + } + return n, nil +} + +func (s *openAIFirstOutputStage) Write(p []byte) (int, error) { + if err := s.prepareWrite(len(p)); err != nil { + return 0, err + } + var n int + var err error + if s.tempFile == nil { + n, err = s.memory.Write(p) + } else { + n, err = s.tempFile.Write(p) + } + s.size += int64(n) + if err != nil { + return n, fmt.Errorf("write first-output stage: %w", err) + } + return n, nil +} + +func (s *openAIFirstOutputStage) prepareWrite(incoming int) error { + if s == nil || s.closed { + return os.ErrClosed + } + if int64(incoming) > s.limit-s.size { + return fmt.Errorf("%w: buffered=%d incoming=%d limit=%d", errOpenAIFirstOutputStageLimit, s.size, incoming, s.limit) + } + if s.tempFile != nil || s.memoryOnly || s.size+int64(incoming) <= openAIFirstOutputStageMemoryLimit { + return nil + } + file, err := s.createTemp() + if err != nil { + return fmt.Errorf("create first-output spool: %w", err) + } + path := file.Name() + // Unlink before writing any request data. Unix keeps the file descriptor + // readable, while crashes and SIGKILL cannot leave a named plaintext spool. + if unlinkErr := s.removeFile(path); unlinkErr != nil { + closeErr := file.Close() + removeErr := s.removeFile(path) + if errors.Is(removeErr, os.ErrNotExist) { + removeErr = nil + } + s.memoryOnly = true + if removeErr != nil && !errors.Is(removeErr, os.ErrNotExist) { + s.tempPath = path + } + s.cleanupErr = errors.Join( + s.cleanupErr, + fmt.Errorf("unlink first-output spool before use: %w", unlinkErr), + closeErr, + removeErr, + ) + return nil + } + if _, err := file.Write(s.memory.Bytes()); err != nil { + _ = file.Close() + return fmt.Errorf("initialize first-output spool: %w", err) + } + s.tempFile = file + s.tempPath = path + s.memory.Reset() + return nil +} + +func (s *openAIFirstOutputStage) CommitTo(dst io.Writer) error { + if s == nil || s.closed { + return os.ErrClosed + } + if s.tempFile == nil { + if _, err := io.Copy(dst, bytes.NewReader(s.memory.Bytes())); err != nil { + return err + } + } else { + if _, err := s.tempFile.Seek(0, io.SeekStart); err != nil { + return fmt.Errorf("seek first-output spool: %w", err) + } + if _, err := io.CopyN(dst, s.tempFile, s.size); err != nil { + return err + } + } + if err := s.Close(); err != nil { + // Delivery succeeded. Preserve cleanup failures for the handler's deferred + // cleanup/logging pass instead of turning committed bytes into a stream error. + s.cleanupErr = errors.Join(s.cleanupErr, err) + } + return nil +} + +func (s *openAIFirstOutputStage) Close() error { + if s == nil { + return nil + } + if s.closed && s.tempFile == nil && s.tempPath == "" && s.cleanupErr == nil { + return nil + } + s.closed = true + s.size = 0 + s.memory.Reset() + closeErr := s.cleanupErr + s.cleanupErr = nil + if s.tempFile != nil { + closeErr = errors.Join(closeErr, s.tempFile.Close()) + s.tempFile = nil + } + if s.tempPath != "" { + removeErr := s.removeFile(s.tempPath) + if removeErr == nil || errors.Is(removeErr, os.ErrNotExist) { + s.tempPath = "" + } else { + closeErr = errors.Join(closeErr, removeErr) + } + } + return closeErr +} + +func (s *OpenAIGatewayService) openAIFirstOutputTimeout(reasoningEffort string) time.Duration { + if s == nil || s.cfg == nil || s.cfg.Gateway.OpenAIFirstOutputTimeoutSeconds <= 0 { + return 0 + } + seconds := s.cfg.Gateway.OpenAIFirstOutputTimeoutSeconds + switch strings.ToLower(strings.TrimSpace(reasoningEffort)) { + case "high", "xhigh", "max": + if override := s.cfg.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds; override > 0 { + seconds = override + } + } + return time.Duration(seconds) * time.Second +} + +func (s *OpenAIGatewayService) newOpenAIFirstOutputTimeoutError( + ctx context.Context, + c *gin.Context, + account *Account, + startTime time.Time, + originalModel string, + reasoningEffort string, + timeout time.Duration, + phase string, + responseHeaders http.Header, +) *UpstreamFailoverError { + elapsed := time.Since(startTime) + logger.LegacyPrintf( + "service.openai_gateway", + "OpenAI first output timeout: account=%d model=%s effort=%s phase=%s elapsed=%s limit=%s", + account.ID, originalModel, reasoningEffort, phase, elapsed, timeout, + ) + requestID := strings.TrimSpace(responseHeaders.Get("x-request-id")) + appendOpsUpstreamError(c, OpsUpstreamErrorEvent{ + Platform: account.Platform, AccountID: account.ID, AccountName: account.Name, + UpstreamStatusCode: http.StatusGatewayTimeout, UpstreamRequestID: requestID, + Kind: "first_output_timeout", Message: "OpenAI upstream produced no semantic output before the deadline", + Detail: fmt.Sprintf("phase=%s elapsed_ms=%d timeout_ms=%d", phase, elapsed.Milliseconds(), timeout.Milliseconds()), + }) + if s.rateLimitService != nil { + s.rateLimitService.HandleStreamTimeout(ctx, account, originalModel) + } + return &UpstreamFailoverError{ + StatusCode: http.StatusGatewayTimeout, + ResponseBody: []byte(`{"error":{"type":"first_output_timeout","message":"Upstream produced no output before the deadline"}}`), + ResponseHeaders: responseHeaders.Clone(), SafeToFailoverAfterWrite: true, + } +} + +type openAIFirstOutputHeaderGuard struct { + cancel context.CancelFunc + release context.CancelFunc + timer *time.Timer + fired chan struct{} + once sync.Once +} + +func newOpenAIFirstOutputHeaderGuard( + ctx context.Context, + release context.CancelFunc, + deadline time.Time, +) (context.Context, *openAIFirstOutputHeaderGuard) { + guardedCtx, cancel := context.WithCancel(ctx) + guard := &openAIFirstOutputHeaderGuard{cancel: cancel, release: release, fired: make(chan struct{})} + remaining := time.Until(deadline) + if remaining <= 0 { + remaining = time.Nanosecond + } + guard.timer = time.AfterFunc(remaining, func() { + close(guard.fired) + cancel() + }) + return guardedCtx, guard +} + +func (g *openAIFirstOutputHeaderGuard) stopHeaderWait() bool { + if g.timer.Stop() { + return false + } + <-g.fired + return true +} + +func (g *openAIFirstOutputHeaderGuard) close() { + g.once.Do(func() { + g.timer.Stop() + g.cancel() + g.release() + }) +} + +type openAIRequestContextReadCloser struct { + io.ReadCloser + cleanup func() + once sync.Once + err error +} + +func (r *openAIRequestContextReadCloser) Close() error { + r.once.Do(func() { + r.cleanup() + r.err = r.ReadCloser.Close() + }) + return r.err +} diff --git a/backend/internal/service/openai_first_output_timeout_test.go b/backend/internal/service/openai_first_output_timeout_test.go new file mode 100644 index 0000000000..1cb7640a8d --- /dev/null +++ b/backend/internal/service/openai_first_output_timeout_test.go @@ -0,0 +1,640 @@ +package service + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "os" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type blockingOpenAIResponseHeaderUpstream struct { + canceled chan struct{} + once sync.Once +} + +type firstOutputCloseTrackingBody struct { + io.ReadCloser + closed chan struct{} + once sync.Once +} + +func (b *firstOutputCloseTrackingBody) Close() error { + b.once.Do(func() { close(b.closed) }) + return b.ReadCloser.Close() +} + +func (u *blockingOpenAIResponseHeaderUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) { + select { + case <-req.Context().Done(): + u.once.Do(func() { close(u.canceled) }) + return nil, req.Context().Err() + case <-time.After(1500 * time.Millisecond): + return nil, errors.New("test upstream was not canceled before response headers") + } +} + +func (u *blockingOpenAIResponseHeaderUpstream) DoWithTLS(req *http.Request, _ string, _ int64, _ int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return u.Do(req, "", 0, 0) +} + +func TestOpenAIForwardFirstOutputTimeoutIncludesResponseHeaderWait(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &blockingOpenAIResponseHeaderUpstream{canceled: make(chan struct{})} + svc := &OpenAIGatewayService{ + cfg: &config.Config{Gateway: config.GatewayConfig{ + OpenAIFirstOutputTimeoutSeconds: 1, + MaxLineSize: defaultMaxLineSize, + }}, + httpUpstream: upstream, + } + body := []byte(`{"model":"gpt-5.5","stream":true,"reasoning":{"effort":"low"},"input":"hello"}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + account := &Account{ + ID: 1, Name: "oauth-test", Platform: PlatformOpenAI, Type: AccountTypeOAuth, + Status: StatusActive, Schedulable: true, Concurrency: 1, + Credentials: map[string]any{"access_token": "test-token", "chatgpt_account_id": "test-account"}, + } + + started := time.Now() + _, err := svc.Forward(context.Background(), c, account, body) + + require.Error(t, err) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, http.StatusGatewayTimeout, failoverErr.StatusCode) + require.Contains(t, string(failoverErr.ResponseBody), "first_output_timeout") + require.True(t, failoverErr.SafeToFailoverAfterWrite) + require.Less(t, time.Since(started), 1300*time.Millisecond) + require.Empty(t, rec.Body.String()) + select { + case <-upstream.canceled: + default: + t.Fatal("response-header timeout did not cancel the upstream request context") + } +} + +func TestOpenAINativeFirstOutputTimeoutDisabledPreservesSynchronousStream(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{ + OpenAIFirstOutputTimeoutSeconds: 0, + MaxLineSize: defaultMaxLineSize, + }}} + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(strings.Join([]string{ + `data: {"type":"response.created","response":{"id":"resp_disabled"}}`, + "", + `data: {"type":"response.completed","response":{"id":"resp_disabled","usage":{"input_tokens":1,"output_tokens":1}}}`, + "", + }, "\n")))} + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + + result, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + + require.NoError(t, err) + require.NotNil(t, result) + require.Contains(t, rec.Body.String(), "response.completed") +} + +func TestOpenAINativeFirstOutputTimeoutIgnoresPreambleAndCleansReader(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{ + OpenAIFirstOutputTimeoutSeconds: 1, + MaxLineSize: defaultMaxLineSize, + }}} + pr, pw := io.Pipe() + writerDone := make(chan struct{}) + go func() { + defer close(writerDone) + defer func() { _ = pw.Close() }() + _, _ = pw.Write([]byte("data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_slow\"}}\n\n")) + _, _ = pw.Write([]byte("data: {\"type\":\"response.in_progress\",\"response\":{\"id\":\"resp_slow\"}}\n\n")) + time.Sleep(200 * time.Millisecond) + }() + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + body := &firstOutputCloseTrackingBody{ReadCloser: pr, closed: make(chan struct{})} + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: body} + + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, time.Now().Add(-2*time.Second), "model", "model") + + require.Error(t, err) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, http.StatusGatewayTimeout, failoverErr.StatusCode) + require.Contains(t, string(failoverErr.ResponseBody), "first_output_timeout") + require.True(t, failoverErr.SafeToFailoverAfterWrite) + require.Empty(t, rec.Body.String()) + select { + case <-body.closed: + default: + t.Fatal("first-output timeout did not close the upstream response body") + } + select { + case <-writerDone: + case <-time.After(time.Second): + t.Fatal("stream reader/writer goroutine did not exit after first-output timeout") + } +} + +func TestOpenAIFirstOutputTimeoutForReasoningEffort(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{ + OpenAIFirstOutputTimeoutSeconds: 120, + OpenAIHighEffortFirstOutputTimeoutSeconds: 300, + }}} + + require.Equal(t, 120*time.Second, svc.openAIFirstOutputTimeout("low")) + require.Equal(t, 300*time.Second, svc.openAIFirstOutputTimeout("high")) + require.Equal(t, 300*time.Second, svc.openAIFirstOutputTimeout("xhigh")) + require.Equal(t, 300*time.Second, svc.openAIFirstOutputTimeout("max")) +} + +func TestOpenAIFirstOutputStageDefaultLimitIsIndependentFromScannerLimit(t *testing.T) { + stage := newDefaultOpenAIFirstOutputStage() + defer func() { require.NoError(t, stage.Close()) }() + + require.EqualValues(t, 8*1024*1024, stage.limit) + require.Greater(t, stage.limit, int64(68106)) + require.Less(t, stage.limit, int64(defaultMaxLineSize)) +} + +func TestOpenAIFirstOutputEventQueueSizeBackpressuresGuardedStreams(t *testing.T) { + require.Equal(t, 1, openAIFirstOutputEventQueueSize(true)) + require.Equal(t, 16, openAIFirstOutputEventQueueSize(false)) +} + +func TestOpenAIFirstOutputDynamicScannerLimitsOnlyWhileGuardIsActive(t *testing.T) { + var guardActive atomic.Bool + guardActive.Store(true) + split := openAIFirstOutputDynamicScanLines(&guardActive) + guardLimit := openAIFirstOutputStageMaxBytes + openAIFirstOutputScannerFramingAllowance + undelimited := bytes.Repeat([]byte("x"), guardLimit) + + _, _, err := split(undelimited, false) + require.ErrorIs(t, err, errOpenAIFirstOutputScannerLimit) + + guardActive.Store(false) + advance, token, err := split(undelimited, false) + require.NoError(t, err) + require.Zero(t, advance) + require.Nil(t, token) +} + +func TestOpenAIFirstOutputStageOverflowIsAtomicAndCleanupRemovesSpool(t *testing.T) { + stage := newOpenAIFirstOutputStage(70 * 1024) + payload := bytes.Repeat([]byte("x"), 68*1024) + n, err := stage.Write(payload) + require.NoError(t, err) + require.Equal(t, len(payload), n) + if runtime.GOOS == "windows" { + require.Nil(t, stage.tempFile) + require.Empty(t, stage.tempPath) + } else { + require.NotNil(t, stage.tempFile) + require.NotEmpty(t, stage.tempPath) + _, err = os.Stat(stage.tempPath) + require.ErrorIs(t, err, os.ErrNotExist) + stat, statErr := stage.tempFile.Stat() + require.NoError(t, statErr) + require.Equal(t, os.FileMode(0o600), stat.Mode().Perm()) + } + + n, err = stage.Write(bytes.Repeat([]byte("y"), 3*1024)) + require.Zero(t, n) + require.ErrorIs(t, err, errOpenAIFirstOutputStageLimit) + require.EqualValues(t, len(payload), stage.Buffered()) + path := stage.tempPath + require.NoError(t, stage.Close()) + require.True(t, stage.closed) + require.Nil(t, stage.tempFile) + require.Empty(t, stage.tempPath) + if path != "" { + _, err = os.Stat(path) + require.ErrorIs(t, err, os.ErrNotExist) + } +} + +func TestOpenAIFirstOutputStageCommitCopiesSpoolAndRemovesTemp(t *testing.T) { + stage := newOpenAIFirstOutputStage(80 * 1024) + payload := bytes.Repeat([]byte("z"), 68*1024) + _, err := stage.Write(payload) + require.NoError(t, err) + path := stage.tempPath + if runtime.GOOS == "windows" { + require.Empty(t, path) + require.Nil(t, stage.tempFile) + } else { + require.NotEmpty(t, path) + require.NotNil(t, stage.tempFile) + _, statErr := os.Stat(path) + require.ErrorIs(t, statErr, os.ErrNotExist) + } + + var downstream bytes.Buffer + require.NoError(t, stage.CommitTo(&downstream)) + require.Equal(t, payload, downstream.Bytes()) + require.Zero(t, stage.Buffered()) + if path != "" { + _, err = os.Stat(path) + require.ErrorIs(t, err, os.ErrNotExist) + } + require.NoError(t, stage.Close()) +} + +func TestOpenAIFirstOutputStageUnlinkFailurePermanentlyFallsBackToMemoryAndRetriesCleanup(t *testing.T) { + stage := newDefaultOpenAIFirstOutputStage() + stage.memoryOnly = false + t.Cleanup(func() { + stage.removeFile = os.Remove + _ = stage.Close() + }) + createCalls := 0 + stage.createTemp = func() (*os.File, error) { + createCalls++ + return os.CreateTemp("", "sub2api-openai-first-output-fallback-*") + } + removeCalls := 0 + stage.removeFile = func(path string) error { + removeCalls++ + if removeCalls <= 2 { + return errors.New("forced remove failure") + } + return os.Remove(path) + } + + payload := bytes.Repeat([]byte("m"), 68*1024) + _, err := stage.Write(payload) + require.NoError(t, err) + require.True(t, stage.memoryOnly) + require.Nil(t, stage.tempFile) + require.NotEmpty(t, stage.tempPath) + require.Equal(t, 1, createCalls) + stat, statErr := os.Stat(stage.tempPath) + require.NoError(t, statErr) + require.Zero(t, stat.Size(), "failed-unlink fallback must never write plaintext to the named file") + + _, err = stage.WriteString("more") + require.NoError(t, err) + require.Equal(t, 1, createCalls, "memory-only fallback must not retry CreateTemp") + path := stage.tempPath + cleanupErr := stage.Close() + require.ErrorContains(t, cleanupErr, "forced remove failure") + require.Empty(t, stage.tempPath) + _, err = os.Stat(path) + require.ErrorIs(t, err, os.ErrNotExist) + require.NoError(t, stage.Close()) +} + +func TestOpenAINativeFirstOutputTimeoutDisarmsAfterSemanticOutput(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{ + OpenAIFirstOutputTimeoutSeconds: 1, + MaxLineSize: defaultMaxLineSize, + }} + svc := &OpenAIGatewayService{cfg: cfg, responseHeaderFilter: compileResponseHeaderFilter(cfg)} + pr, pw := io.Pipe() + go func() { + defer func() { _ = pw.Close() }() + _, _ = pw.Write([]byte("data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_ok\"}}\n\n")) + _, _ = pw.Write([]byte("data: {\"type\":\"response.output_text.delta\",\"delta\":\"hello\"}\n\n")) + time.Sleep(1100 * time.Millisecond) + _, _ = pw.Write([]byte("data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_ok\",\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n")) + }() + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{ + "X-Request-Id": []string{"request-winning"}, + "X-Ratelimit-Remaining-Requests": []string{"42"}, + }, Body: pr} + + result, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, result.firstTokenMs) + require.Contains(t, rec.Body.String(), "response.output_text.delta") + require.Contains(t, rec.Body.String(), "response.completed") + require.Equal(t, "request-winning", rec.Result().Header.Get("X-Request-Id")) + require.Equal(t, "42", rec.Result().Header.Get("X-Ratelimit-Remaining-Requests")) +} + +func TestOpenAINativeFirstOutputTimeoutWaitsForCompleteSemanticEvent(t *testing.T) { + const lineSize = 68106 + prefix := `data: {"type":"response.output_text.delta","delta":"` + suffix := `"}` + line := prefix + strings.Repeat("x", lineSize-len(prefix)-len(suffix)) + suffix + require.Len(t, line, lineSize) + assertOpenAINativeLargeOpenEventTimesOutWithoutLeak(t, line) +} + +func TestOpenAINativeFirstOutputTimeoutDoesNotLeakLargePreambleEvent(t *testing.T) { + const lineSize = 68106 + prefix := `data: {"type":"response.created","response":{"id":"resp_partial","padding":"` + suffix := `"}}` + line := prefix + strings.Repeat("x", lineSize-len(prefix)-len(suffix)) + suffix + require.Len(t, line, lineSize) + assertOpenAINativeLargeOpenEventTimesOutWithoutLeak(t, line) +} + +func assertOpenAINativeLargeOpenEventTimesOutWithoutLeak(t *testing.T, line string) { + t.Helper() + cfg := &config.Config{Gateway: config.GatewayConfig{ + OpenAIFirstOutputTimeoutSeconds: 1, + StreamKeepaliveInterval: 1, + MaxLineSize: defaultMaxLineSize, + }} + svc := &OpenAIGatewayService{cfg: cfg, responseHeaderFilter: compileResponseHeaderFilter(cfg)} + pr, pw := io.Pipe() + body := &firstOutputCloseTrackingBody{ReadCloser: pr, closed: make(chan struct{})} + writerDone := make(chan struct{}) + go func() { + defer close(writerDone) + defer func() { _ = pw.Close() }() + _, _ = pw.Write([]byte(line + "\n")) + select { + case <-body.closed: + case <-time.After(2 * time.Second): + } + }() + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{ + "X-Request-Id": []string{"request-partial"}, + "X-Ratelimit-Remaining-Requests": []string{"1"}, + }, Body: body} + + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, http.StatusGatewayTimeout, failoverErr.StatusCode) + require.Contains(t, string(failoverErr.ResponseBody), "first_output_timeout") + require.True(t, failoverErr.SafeToFailoverAfterWrite) + require.NotContains(t, rec.Body.String(), "data:", "attempt JSON must remain private before the SSE boundary") + require.NotContains(t, rec.Body.String(), `"type"`, "attempt JSON must remain private before the SSE boundary") + for _, outputLine := range strings.Split(strings.TrimSpace(rec.Body.String()), "\n") { + if outputLine != "" { + require.True(t, strings.HasPrefix(outputLine, ":"), "only keepalive comments may precede failover: %q", outputLine) + } + } + require.Empty(t, rec.Header().Values("X-Request-Id")) + require.Empty(t, rec.Header().Values("X-Ratelimit-Remaining-Requests")) + select { + case <-writerDone: + case <-time.After(time.Second): + t.Fatal("partial-event writer did not exit after timeout closed the body") + } +} + +func TestOpenAINativeFirstOutputEOFDispatchesTerminalEventWithoutBlankLine(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{ + OpenAIFirstOutputTimeoutSeconds: 1, + MaxLineSize: defaultMaxLineSize, + }} + svc := &OpenAIGatewayService{cfg: cfg, responseHeaderFilter: compileResponseHeaderFilter(cfg)} + payload := `data: {"type":"response.completed","response":{"id":"resp_eof","usage":{"input_tokens":3,"output_tokens":2}}}` + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{ + "X-Request-Id": []string{"request-eof"}, + "X-Ratelimit-Remaining-Requests": []string{"17"}, + }, + Body: io.NopCloser(strings.NewReader(payload)), + } + + result, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, result.firstTokenMs) + require.Equal(t, "resp_eof", result.responseID) + require.Equal(t, 3, result.usage.InputTokens) + require.Equal(t, 2, result.usage.OutputTokens) + require.Contains(t, rec.Body.String(), `"type":"response.completed"`) + require.Contains(t, rec.Body.String(), `"id":"resp_eof"`) + require.True(t, strings.HasSuffix(rec.Body.String(), "\n")) + require.False(t, strings.HasSuffix(rec.Body.String(), "\n\n"), "EOF dispatch must not synthesize a blank line") + require.Equal(t, "request-eof", rec.Result().Header.Get("X-Request-Id")) + require.Equal(t, "17", rec.Result().Header.Get("X-Ratelimit-Remaining-Requests")) +} + +func TestOpenAINativeFirstOutputStageOverflowFailsOverWithoutAttemptBytes(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{ + OpenAIFirstOutputTimeoutSeconds: 30, + MaxLineSize: 2 * 1024 * 1024, + }} + svc := &OpenAIGatewayService{cfg: cfg, responseHeaderFilter: compileResponseHeaderFilter(cfg)} + const lineSize = 1024*1024 - 256 + prefix := `data: {"type":"response.output_text.delta","delta":"` + suffix := `"}` + line := prefix + strings.Repeat("x", lineSize-len(prefix)-len(suffix)) + suffix + body := strings.Repeat(line+"\n", 9) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{ + "X-Request-Id": []string{"request-overflow"}, + "X-Ratelimit-Remaining-Requests": []string{"1"}, + }, + Body: io.NopCloser(strings.NewReader(body)), + } + + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, http.StatusBadGateway, failoverErr.StatusCode) + require.True(t, failoverErr.SafeToFailoverAfterWrite) + require.Contains(t, string(failoverErr.ResponseBody), "staging limit exceeded") + require.Empty(t, rec.Body.String()) + require.Empty(t, rec.Header().Values("X-Request-Id")) + require.Empty(t, rec.Header().Values("X-Ratelimit-Remaining-Requests")) +} + +func TestOpenAINativeFirstOutputScannerRejectsOversizedLineWithoutLeak(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{ + OpenAIFirstOutputTimeoutSeconds: 30, + MaxLineSize: defaultMaxLineSize, + }} + svc := &OpenAIGatewayService{cfg: cfg, responseHeaderFilter: compileResponseHeaderFilter(cfg)} + oversizedLine := "data: " + strings.Repeat("x", openAIFirstOutputStageMaxBytes+openAIFirstOutputScannerFramingAllowance+1024) + body := "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_private\"}}\n\n" + oversizedLine + "\n" + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{ + "X-Request-Id": []string{"request-too-large"}, + "X-Ratelimit-Remaining-Requests": []string{"1"}, + }, + Body: io.NopCloser(strings.NewReader(body)), + } + + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, http.StatusBadGateway, failoverErr.StatusCode) + require.True(t, failoverErr.SafeToFailoverAfterWrite) + require.Contains(t, string(failoverErr.ResponseBody), "line exceeds guarded first-output limit") + require.Empty(t, rec.Body.String()) + require.Empty(t, rec.Header().Values("X-Request-Id")) + require.Empty(t, rec.Header().Values("X-Ratelimit-Remaining-Requests")) +} + +func TestOpenAINativeFirstOutputScannerAllowsLargeEventAfterSemanticBoundary(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{ + OpenAIFirstOutputTimeoutSeconds: 30, + MaxLineSize: defaultMaxLineSize, + }} + svc := &OpenAIGatewayService{cfg: cfg, responseHeaderFilter: compileResponseHeaderFilter(cfg)} + largeDelta := strings.Repeat("i", openAIFirstOutputStageMaxBytes+openAIFirstOutputScannerFramingAllowance+1024) + body := strings.Join([]string{ + `data: {"type":"response.output_text.delta","delta":"ready"}`, + "", + `data: {"type":"response.output_text.delta","delta":"` + largeDelta + `"}`, + "", + `data: {"type":"response.completed","response":{"id":"resp_large_image","usage":{"input_tokens":4,"output_tokens":3}}}`, + "", + }, "\n") + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"X-Request-Id": []string{"request-large-image"}}, + Body: io.NopCloser(strings.NewReader(body)), + } + + result, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, result.firstTokenMs) + require.Equal(t, "resp_large_image", result.responseID) + require.Equal(t, 4, result.usage.InputTokens) + require.Equal(t, 3, result.usage.OutputTokens) + require.Contains(t, rec.Body.String(), `"delta":"ready"`) + require.Contains(t, rec.Body.String(), `"id":"resp_large_image"`) + require.Contains(t, rec.Body.String(), strings.Repeat("i", 1024)) + require.Equal(t, "request-large-image", rec.Result().Header.Get("X-Request-Id")) +} + +func TestOpenAINativeFirstOutputTimeoutDisabledPreservesKeepaliveFlush(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{ + StreamKeepaliveInterval: 1, + MaxLineSize: defaultMaxLineSize, + }}} + pr, pw := io.Pipe() + go func() { + defer func() { _ = pw.Close() }() + _, _ = pw.Write([]byte("data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_stalled\"}}\n\n")) + _, _ = pw.Write([]byte("data: {\"type\":\"response.in_progress\",\"response\":{\"id\":\"resp_stalled\"}}\n\n")) + time.Sleep(1100 * time.Millisecond) + }() + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: pr} + + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + + require.Error(t, err) + require.Contains(t, rec.Body.String(), ":\n\n") + require.Contains(t, rec.Body.String(), "response.created") + require.Contains(t, rec.Body.String(), "response.in_progress") +} + +func TestOpenAINativeFirstOutputFailoverKeepsAttemptHeadersPrivateAfterKeepaliveCommit(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{ + OpenAIFirstOutputTimeoutSeconds: 2, + StreamKeepaliveInterval: 1, + MaxLineSize: defaultMaxLineSize, + }} + svc := &OpenAIGatewayService{ + cfg: cfg, + responseHeaderFilter: compileResponseHeaderFilter(cfg), + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + firstBody, firstWriter := io.Pipe() + trackedFirstBody := &firstOutputCloseTrackingBody{ReadCloser: firstBody, closed: make(chan struct{})} + firstWriterDone := make(chan struct{}) + go func() { + defer close(firstWriterDone) + defer func() { _ = firstWriter.Close() }() + _, _ = firstWriter.Write([]byte("data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_first\"}}\n\n")) + select { + case <-trackedFirstBody.closed: + case <-time.After(4 * time.Second): + } + }() + firstResp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{ + "Content-Type": []string{"text/event-stream"}, + "X-Request-Id": []string{"request-first"}, + "X-Ratelimit-Remaining-Requests": []string{"1"}, + }, + Body: trackedFirstBody, + } + + _, firstErr := svc.handleStreamingResponse(c.Request.Context(), firstResp, c, &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, firstErr, &failoverErr) + require.Contains(t, rec.Body.String(), ":\n\n", "first attempt should have committed only a stable keepalive") + require.NotContains(t, rec.Body.String(), "resp_first") + + secondResp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{ + "Content-Type": []string{"text/event-stream"}, + "X-Request-Id": []string{"request-second"}, + "X-Ratelimit-Remaining-Requests": []string{"99"}, + }, + Body: io.NopCloser(strings.NewReader(strings.Join([]string{ + `data: {"type":"response.output_text.delta","delta":"hello"}`, + "", + `data: {"type":"response.completed","response":{"id":"resp_second","usage":{"input_tokens":1,"output_tokens":1}}}`, + "", + }, "\n"))), + } + result, secondErr := svc.handleStreamingResponse(c.Request.Context(), secondResp, c, &Account{ID: 2, Platform: PlatformOpenAI}, time.Now(), "model", "model") + + require.NoError(t, secondErr) + require.NotNil(t, result) + require.Contains(t, rec.Body.String(), "resp_second") + wireHeaders := rec.Result().Header + require.Empty(t, wireHeaders.Values("X-Request-Id")) + require.Empty(t, wireHeaders.Values("X-Ratelimit-Remaining-Requests")) + require.Empty(t, rec.Header().Values("X-Request-Id")) + require.Empty(t, rec.Header().Values("X-Ratelimit-Remaining-Requests")) + select { + case <-firstWriterDone: + case <-time.After(time.Second): + t.Fatal("first account writer did not exit after timeout") + } +} diff --git a/backend/internal/service/openai_gateway_cc_pipeline.go b/backend/internal/service/openai_gateway_cc_pipeline.go index 690b9991bb..2391e25ba5 100644 --- a/backend/internal/service/openai_gateway_cc_pipeline.go +++ b/backend/internal/service/openai_gateway_cc_pipeline.go @@ -118,6 +118,7 @@ func (s *OpenAIGatewayService) failoverOpenAIUpstreamHTTPError( return &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: respBody, + ResponseHeaders: resp.Header.Clone(), RetryableOnSameAccount: account.IsPoolMode() && (account.IsPoolModeRetryableStatus(resp.StatusCode) || isOpenAITransientProcessingError(resp.StatusCode, upstreamMsg, respBody)), } } @@ -197,7 +198,9 @@ func (s *OpenAIGatewayService) sendCCUpstreamRequest( // 账号级请求头覆写(仅 openai api_key 账号启用时生效) account.ApplyHeaderOverrides(upstreamReq.Header) if account.Platform == PlatformGrok { - applyGrokCLIHeaders(upstreamReq.Header) + if account.IsGrokOAuth() { + applyGrokCLIHeaders(upstreamReq.Header) + } applyGrokCacheHeaders(upstreamReq.Header, grokCacheIdentity) } diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index 533b562dc9..fe24b3db36 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -277,6 +277,13 @@ func (s *OpenAIGatewayService) ForwardAsChatCompletions( // 8. Handle error response with failover if resp.StatusCode >= 400 { respBody, upstreamMsg := s.readOpenAIUpstreamError(resp) + if !agentIdentityTaskRecoveryWasTried(ctx) && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, respBody) { + expectedTaskID := account.GetCredential("task_id") + if err := s.recoverAgentIdentityTask(ctx, account, expectedTaskID); err != nil { + return nil, fmt.Errorf("agent identity task recovery failed: %w", err) + } + return s.ForwardAsChatCompletions(markAgentIdentityTaskRecoveryTried(ctx), c, account, body, promptCacheKey, defaultMappedModel) + } if account.Type == AccountTypeAPIKey && openai_compat.ResolveResponsesSupport(account.Extra) == openai_compat.ResponsesSupportUnknown && !isResponsesEndpointSupportedByStatus(resp.StatusCode) { diff --git a/backend/internal/service/openai_gateway_chat_completions_raw.go b/backend/internal/service/openai_gateway_chat_completions_raw.go index 7693986b0d..800d53be32 100644 --- a/backend/internal/service/openai_gateway_chat_completions_raw.go +++ b/backend/internal/service/openai_gateway_chat_completions_raw.go @@ -9,7 +9,6 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" - "github.com/Wei-Shaw/sub2api/internal/pkg/xai" "github.com/Wei-Shaw/sub2api/internal/util/responseheaders" "github.com/gin-gonic/gin" "github.com/tidwall/gjson" @@ -109,7 +108,7 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions( // Grok Composer does not accept image_url parts directly, but Grok Build // can describe the images first. Bridge only this exact failure mode. - token, tokenKind, err := s.GetAccessToken(ctx, account) + token, tokenKind, err := s.getRequestCredential(ctx, c, account) if err != nil { return nil, err } @@ -162,7 +161,7 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions( } SetActualOpenAIUpstreamEndpoint(c, grokChatRawEndpoint) customUA := account.GetOpenAIUserAgent() - if customUA == "" && account.Platform == PlatformGrok { + if customUA == "" && account.IsGrokOAuth() { customUA = "sub2api-grok/1.0" } resp, err := s.sendCCUpstreamRequest(ctx, c, account, targetURL, upstreamBody, clientStream, token, customUA, grokCacheIdentity) @@ -189,6 +188,7 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions( return nil, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: respBody, + ResponseHeaders: resp.Header.Clone(), RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode), } } @@ -201,7 +201,7 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions( } if account.Platform == PlatformGrok { - s.updateGrokUsageSnapshot(ctx, account, xai.ParseQuotaHeaders(resp.Header, resp.StatusCode)) + s.updateGrokUsageFromResponse(ctx, account, resp.Header, resp.StatusCode) } // 8. Forward response @@ -221,7 +221,7 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions( func (s *OpenAIGatewayService) rawChatCompletionsURL(account *Account) (string, error) { if account.Platform == PlatformGrok { - targetURL, err := xai.BuildChatCompletionsURL(account.GetGrokBaseURL()) + targetURL, err := buildGrokChatCompletionsURL(account, s.cfg) if err != nil { return "", fmt.Errorf("invalid grok base_url: %w", err) } diff --git a/backend/internal/service/openai_gateway_count_tokens.go b/backend/internal/service/openai_gateway_count_tokens.go index 7518a6073a..46b5a3843a 100644 --- a/backend/internal/service/openai_gateway_count_tokens.go +++ b/backend/internal/service/openai_gateway_count_tokens.go @@ -215,7 +215,15 @@ func (s *OpenAIGatewayService) buildInputTokensUpstreamRequest( return nil, err } req = req.WithContext(WithHTTPUpstreamProfile(req.Context(), HTTPUpstreamProfileOpenAI)) - req.Header.Set("authorization", "Bearer "+token) + authHeaders, err := s.buildOpenAIAuthenticationHeaders(ctx, account, token) + if err != nil { + return nil, err + } + for key, values := range authHeaders { + for _, value := range values { + req.Header.Add(key, value) + } + } req.Header.Set("content-type", "application/json") req.Header.Set("accept", "application/json") diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 6c7d45946a..5259aa843c 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -20,6 +20,8 @@ import ( // Forward forwards request to OpenAI API func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, account *Account, body []byte) (*OpenAIForwardResult, error) { startTime := time.Now() + // 固定渠道映射后的请求级 canonical body;账号 normalize/strip 不得改写跨 failover hint。 + canonicalImageIntentBody := body restrictionResult := s.detectCodexClientRestriction(c, account, body) apiKeyID := getAPIKeyIDFromContext(c) @@ -42,6 +44,19 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if normalized { body = normalizedBody } + if account.IsOpenAIOAuth() && isOpenAIResponsesLiteHeader(c.GetHeader(responsesLiteHeader)) { + liteBody, changed, liteErr := normalizeOpenAIResponsesLiteToolsPayload(body) + if liteErr != nil { + setOpsUpstreamError(c, http.StatusBadRequest, liteErr.Error(), "") + c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{ + "type": "invalid_request_error", "message": liteErr.Error(), "param": "tools", + }}) + return nil, liteErr + } + if changed { + body = liteBody + } + } wsDecision := s.getOpenAIWSProtocolResolver().Resolve(account) // 仅允许 WS 入站请求走 WS 上游,避免出现 HTTP -> WS 协议混用。 wsDecision = resolveOpenAIWSDecisionByClientTransport(wsDecision, GetOpenAIClientTransport(c)) @@ -107,6 +122,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco return nil, errors.New("openai ws v1 is temporarily unsupported; use ws v2") } if passthroughEnabled { + attemptImageIntentInvalidated := false if isCodexCLI && codexImageGenerationExplicitToolPolicy == codexImageGenerationExplicitToolPolicyStrip { strippedBody, changed, stripErr := stripOpenAIImageGenerationToolsFromRawPayload(body) if stripErr != nil { @@ -115,6 +131,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if changed { body = strippedBody originalBody = strippedBody + attemptImageIntentInvalidated = true logger.LegacyPrintf("service.openai_gateway", "[OpenAI] Stripped /responses image_generation tool for Codex client by account policy") } } @@ -123,7 +140,18 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco reasoningEffort := extractOpenAIReasoningEffortFromBody(body, mappedModel) // 国产模型默认 effort 补充:也要用 mappedModel 判定是否是 passback-required 上游。 reasoningEffort = ApplyThinkingEnabledFallback(reasoningEffort, body, mappedModel) - return s.forwardOpenAIPassthrough(ctx, c, account, originalBody, reqModel, reasoningEffort, reqStream, startTime) + return s.forwardOpenAIPassthrough( + ctx, + c, + account, + originalBody, + canonicalImageIntentBody, + reqModel, + attemptImageIntentInvalidated, + reasoningEffort, + reqStream, + startTime, + ) } bodyModified := false @@ -188,6 +216,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco codexImageGenerationExplicitToolPolicy != codexImageGenerationExplicitToolPolicyStrip && s.isCodexImageGenerationBridgeEnabled(ctx, account, apiKey) var imageIntent bool + canonicalImageIntent := resolveOpenAIImageIntentHint(c, reqModel, canonicalImageIntentBody, IsImageGenerationIntent) if isCodexCLI && codexImageGenerationExplicitToolPolicy == codexImageGenerationExplicitToolPolicyStrip { decoded, decodeErr := ensureReqBody() if decodeErr != nil { @@ -199,7 +228,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } imageIntent = IsImageGenerationIntentMap(openAIResponsesEndpoint, reqModel, decoded) } else { - imageIntent = IsImageGenerationIntent(openAIResponsesEndpoint, reqModel, body) + imageIntent = canonicalImageIntent } if imageIntent && !imageGenerationAllowed { MarkOpsClientBusinessLimited(c, OpsClientBusinessLimitedReasonLocalFeatureGate) @@ -499,6 +528,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco var wsResult *OpenAIForwardResult var wsErr error wsLastFailureReason := "" + agentTaskRecoveryTried := false wsPrevResponseRecoveryTried := false wsInvalidEncryptedContentRecoveryTried := false recoverPrevResponseNotFound := func(attempt int) bool { @@ -583,6 +613,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco startTime, attempt, wsLastFailureReason, + &agentTaskRecoveryTried, ) if wsErr == nil { break @@ -590,6 +621,10 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if c != nil && c.Writer != nil && c.Writer.Written() { break } + var taskRecoveredErr *agentIdentityTaskRecoveredError + if errors.As(wsErr, &taskRecoveredErr) { + continue + } reason, retryable := classifyOpenAIWSReconnectReason(wsErr) if reason != "" { @@ -695,13 +730,37 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco return nil, wsErr } + reasoningEffort := extractOpenAIReasoningEffortFromBody(body, upstreamModel, billingModel, originalModel) + // 国产模型默认 effort 补充:此处 reqModel 已被 mapping 重写为 billingModel。 + reasoningEffort = ApplyThinkingEnabledFallback(reasoningEffort, body, reqModel) + reasoningEffortValue := "" + if reasoningEffort != nil { + reasoningEffortValue = *reasoningEffort + } + firstOutputTimeout := time.Duration(0) + if reqStream && account.Platform == PlatformOpenAI { + firstOutputTimeout = s.openAIFirstOutputTimeout(reasoningEffortValue) + } + httpInvalidEncryptedContentRetryTried := false + agentTaskRecoveryTried := false for { // Build upstream request upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) + var headerGuard *openAIFirstOutputHeaderGuard + if firstOutputTimeout > 0 { + upstreamCtx, headerGuard = newOpenAIFirstOutputHeaderGuard( + upstreamCtx, releaseUpstreamCtx, startTime.Add(firstOutputTimeout), + ) + } upstreamReq, err := s.buildUpstreamRequest(upstreamCtx, c, account, body, token, reqStream, promptCacheKey, isCodexCLI) - releaseUpstreamCtx() + if headerGuard == nil { + releaseUpstreamCtx() + } if err != nil { + if headerGuard != nil { + headerGuard.close() + } return nil, err } @@ -715,12 +774,31 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco upstreamStart := time.Now() resp, err := s.httpUpstream.Do(upstreamReq, proxyURL, account.ID, account.Concurrency) SetOpsLatencyMs(c, OpsUpstreamLatencyMsKey, time.Since(upstreamStart).Milliseconds()) + if headerGuard != nil && headerGuard.stopHeaderWait() { + if resp != nil && resp.Body != nil { + _ = resp.Body.Close() + } + headerGuard.close() + return nil, s.newOpenAIFirstOutputTimeoutError( + ctx, c, account, startTime, originalModel, reasoningEffortValue, + firstOutputTimeout, "response_headers", nil, + ) + } if err != nil { + if resp != nil && resp.Body != nil { + _ = resp.Body.Close() + } + if headerGuard != nil { + headerGuard.close() + } // Transport-level failure (proxy/DNS/TCP/TLS — no HTTP response). Convert to // a failover so the handler switches to a healthy account, and temporarily // unschedule the account on durable faults (e.g. rejected proxy credentials). return nil, s.handleOpenAIUpstreamTransportError(ctx, c, account, err, false) } + if headerGuard != nil { + resp.Body = &openAIRequestContextReadCloser{ReadCloser: resp.Body, cleanup: headerGuard.close} + } // Handle error response if resp.StatusCode >= 400 { @@ -731,6 +809,16 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody)) upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg) upstreamCode := extractUpstreamErrorCode(respBody) + if !agentTaskRecoveryTried && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, respBody) { + agentTaskRecoveryTried = true + expectedTaskID := account.GetCredential("task_id") + if err := s.recoverAgentIdentityTask(ctx, account, expectedTaskID); err != nil { + return nil, fmt.Errorf("agent identity task recovery failed: %w", err) + } + continue + } + respBody = s.redactAgentIdentitySensitiveBody(ctx, account, respBody) + resp.Body = io.NopCloser(bytes.NewReader(respBody)) if !httpInvalidEncryptedContentRetryTried && resp.StatusCode == http.StatusBadRequest && upstreamCode == "invalid_encrypted_content" { decoded, decodeErr := ensureReqBody() if decodeErr != nil { @@ -778,10 +866,6 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } defer func() { _ = resp.Body.Close() }() - reasoningEffort := extractOpenAIReasoningEffortFromBody(body, upstreamModel, billingModel, originalModel) - // 国产模型默认 effort 补充:此处 reqModel 已被 mapping 重写为 billingModel(见 - // line 2510-2515 的 GetMappedModel + reqModel 赋值),可直接作为 mappedModel。 - reasoningEffort = ApplyThinkingEnabledFallback(reasoningEffort, body, reqModel) serviceTier := extractOpenAIServiceTierFromBody(body) // 上游接受后只保留计费需要的标量,避免响应处理期间继续保活完整 input/tools map。 reqBody = nil @@ -793,7 +877,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco imageCount := 0 var imageOutputSizes []string if reqStream { - streamResult, err := s.handleStreamingResponse(ctx, resp, c, account, startTime, originalModel, upstreamModel) + streamResult, err := s.handleStreamingResponseWithReasoning(ctx, resp, c, account, startTime, originalModel, upstreamModel, reasoningEffortValue) if err != nil { return nil, err } @@ -881,8 +965,17 @@ func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin. } req = req.WithContext(WithHTTPUpstreamProfile(req.Context(), HTTPUpstreamProfileOpenAI)) - // Set authentication header - req.Header.Set("authorization", "Bearer "+token) + // Build authentication for this request. Agent Identity signs a fresh + // assertion here; OAuth/PAT/API-key keep their existing Bearer behavior. + authHeaders, err := s.buildOpenAIAuthenticationHeaders(ctx, account, token) + if err != nil { + return nil, fmt.Errorf("build openai authentication headers: %w", err) + } + for key, values := range authHeaders { + for _, value := range values { + req.Header.Add(key, value) + } + } // Set headers specific to OAuth accounts (ChatGPT internal API) if account.Type == AccountTypeOAuth { diff --git a/backend/internal/service/openai_gateway_grok.go b/backend/internal/service/openai_gateway_grok.go index 8bd1d456dc..93c0f8cb0f 100644 --- a/backend/internal/service/openai_gateway_grok.go +++ b/backend/internal/service/openai_gateway_grok.go @@ -11,6 +11,7 @@ import ( "strings" "time" + "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" "github.com/Wei-Shaw/sub2api/internal/pkg/xai" "github.com/gin-gonic/gin" @@ -25,6 +26,10 @@ const ( grokCLIVersion = "0.2.93" grokDefaultResponsesModel = "grok-4.5" grokRateLimitFallbackCooldown = 2 * time.Minute + grokRateLimitRepeatCooldown = 10 * time.Minute + grokRateLimitSustainedCooldown = 30 * time.Minute + grokRateLimitMaxAdaptiveCooldown = time.Hour + grokRateLimitBackoffQuietPeriod = time.Hour ) func (s *OpenAIGatewayService) forwardGrokResponses( @@ -44,6 +49,9 @@ func (s *OpenAIGatewayService) forwardGrokResponses( if strings.TrimSpace(upstreamModel) == "" { upstreamModel = grokDefaultResponsesModel } + if isGrokImageGenerationModel(upstreamModel) { + return nil, fmt.Errorf("model %s is an image model and is not available on the Responses endpoint; use /v1/images/generations instead", upstreamModel) + } cacheIdentity := resolveGrokCacheIdentity(c, body, "", upstreamModel) patchedBody, err := patchGrokResponsesBody(body, upstreamModel) if err != nil { @@ -54,14 +62,14 @@ func (s *OpenAIGatewayService) forwardGrokResponses( return nil, fmt.Errorf("apply grok prompt cache identity: %w", err) } - token, _, err := s.GetAccessToken(ctx, account) + token, _, err := s.getRequestCredential(ctx, c, account) if err != nil { return nil, err } upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) defer releaseUpstreamCtx() - upstreamReq, err := buildGrokResponsesRequest(upstreamCtx, c, account, patchedBody, token, cacheIdentity) + upstreamReq, err := buildGrokResponsesRequest(upstreamCtx, c, account, patchedBody, token, cacheIdentity, s.cfg) if err != nil { return nil, err } @@ -100,13 +108,14 @@ func (s *OpenAIGatewayService) forwardGrokResponses( return nil, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: respBody, + ResponseHeaders: resp.Header.Clone(), RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode), } } return s.handleErrorResponse(ctx, resp, c, account, patchedBody, upstreamModel) } - s.updateGrokUsageSnapshot(ctx, account, xai.ParseQuotaHeaders(resp.Header, resp.StatusCode)) + s.updateGrokUsageFromResponse(ctx, account, resp.Header, resp.StatusCode) var usage *OpenAIUsage var firstTokenMs *int @@ -573,7 +582,7 @@ func (s *OpenAIGatewayService) describeGrokComposerImage( upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) // Image-description probes are auxiliary requests, not conversation turns. // Do not bind them to the caller's Grok prompt-cache identity. - upstreamReq, err := buildGrokResponsesRequest(upstreamCtx, c, account, body, token, "") + upstreamReq, err := buildGrokResponsesRequest(upstreamCtx, c, account, body, token, "", s.cfg) releaseUpstreamCtx() if err != nil { return "", OpenAIUsage{}, fmt.Errorf("build grok composer image bridge request: %w", err) @@ -610,13 +619,14 @@ func (s *OpenAIGatewayService) describeGrokComposerImage( return "", OpenAIUsage{}, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: respBody, + ResponseHeaders: resp.Header.Clone(), RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode), } } return "", OpenAIUsage{}, fmt.Errorf("grok composer image bridge upstream error: %s", upstreamMsg) } - s.updateGrokUsageSnapshot(ctx, account, xai.ParseQuotaHeaders(resp.Header, resp.StatusCode)) + s.updateGrokUsageFromResponse(ctx, account, resp.Header, resp.StatusCode) respBody, err := ReadUpstreamResponseBody(resp.Body, s.cfg, c, nil) if err != nil { return "", OpenAIUsage{}, fmt.Errorf("read grok composer image bridge response: %w", err) @@ -738,8 +748,8 @@ func addOpenAIUsage(dst *OpenAIUsage, usage OpenAIUsage) { dst.ImageOutputTokens += usage.ImageOutputTokens } -func buildGrokResponsesRequest(ctx context.Context, c *gin.Context, account *Account, body []byte, token, cacheIdentity string) (*http.Request, error) { - targetURL, err := xai.BuildResponsesURL(account.GetGrokBaseURL()) +func buildGrokResponsesRequest(ctx context.Context, c *gin.Context, account *Account, body []byte, token, cacheIdentity string, cfg *config.Config) (*http.Request, error) { + targetURL, err := buildGrokResponsesURL(account, cfg) if err != nil { return nil, err } @@ -750,7 +760,9 @@ func buildGrokResponsesRequest(ctx context.Context, c *gin.Context, account *Acc req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json, text/event-stream") - applyGrokCLIHeaders(req.Header) + if account.IsGrokOAuth() { + applyGrokCLIHeaders(req.Header) + } applyGrokCacheHeaders(req.Header, cacheIdentity) if c != nil { if v := c.GetHeader("OpenAI-Beta"); strings.TrimSpace(v) != "" { @@ -776,11 +788,12 @@ func (s *OpenAIGatewayService) updateGrokUsageSnapshot(ctx context.Context, acco } accountID := account.ID now := time.Now() - resetAt, hasActiveLimit := grokRateLimitResetAt(snapshot, now) + resetAt, hasActiveLimit := grokRateLimitResetAtForAccount(account, snapshot, now) if hasActiveLimit { normalizeGrokExhaustedWindowResets(snapshot, resetAt, now) } - critical := snapshot.StatusCode == http.StatusTooManyRequests || hasActiveLimit + recovery := isSuccessfulGrokRateLimitRecovery(account, snapshot) + critical := snapshot.StatusCode == http.StatusTooManyRequests || hasActiveLimit || recovery if s.codexSnapshotThrottle != nil { allowed := s.codexSnapshotThrottle.Allow(accountID, now) if !critical && !allowed { @@ -806,6 +819,23 @@ func (s *OpenAIGatewayService) updateGrokUsageSnapshot(ctx context.Context, acco // on the passive snapshot scheduler check. if hasActiveLimit { s.rateLimitGrok(stateCtx, account, resetAt) + } else if recovery { + clearGrokRateLimitAfterRecovery(stateCtx, s.accountRepo, account) + } +} + +func (s *OpenAIGatewayService) updateGrokUsageFromResponse(ctx context.Context, account *Account, headers http.Header, statusCode int) { + snapshot := parseGrokQuotaSnapshot(headers, statusCode, time.Now()) + if snapshot != nil { + s.updateGrokUsageSnapshot(ctx, account, snapshot) + return + } + // Successful responses are recovery evidence even when the upstream omits + // optional quota headers. Do not replace an informative stored snapshot with + // an empty one; only clear the exact observed cooldown generation. + recoverySnapshot := &xai.QuotaSnapshot{StatusCode: statusCode} + if isSuccessfulGrokRateLimitRecovery(account, recoverySnapshot) { + clearGrokRateLimitAfterRecovery(ctx, s.accountRepo, account) } } @@ -896,6 +926,37 @@ func grokRateLimitResetAt(snapshot *xai.QuotaSnapshot, now time.Time) (time.Time return time.Time{}, false } +func grokRateLimitResetAtForAccount(account *Account, snapshot *xai.QuotaSnapshot, now time.Time) (time.Time, bool) { + resetAt, limited := grokRateLimitResetAt(snapshot, now) + if !limited || !isGrokOAuthAccount(account) || snapshot == nil || snapshot.StatusCode != http.StatusTooManyRequests { + return resetAt, limited + } + if account.RateLimitedAt == nil || account.RateLimitResetAt == nil { + return resetAt, true + } + previousResetAt := *account.RateLimitResetAt + if previousResetAt.After(now) || now.Sub(previousResetAt) > grokRateLimitBackoffQuietPeriod { + return resetAt, true + } + previousCooldown := previousResetAt.Sub(*account.RateLimitedAt) + if previousCooldown <= 0 { + return resetAt, true + } + + adaptiveCooldown := grokRateLimitRepeatCooldown + switch { + case previousCooldown >= grokRateLimitSustainedCooldown: + adaptiveCooldown = grokRateLimitMaxAdaptiveCooldown + case previousCooldown >= grokRateLimitRepeatCooldown: + adaptiveCooldown = grokRateLimitSustainedCooldown + } + adaptiveResetAt := now.Add(adaptiveCooldown) + if adaptiveResetAt.After(resetAt) { + resetAt = adaptiveResetAt + } + return resetAt, true +} + func normalizeGrokRateLimitResetAt(account *Account, resetAt, now time.Time) time.Time { if !resetAt.After(now) { resetAt = now.Add(grokRateLimitFallbackCooldown) @@ -910,6 +971,33 @@ type grokRateLimitExtendingRepository interface { SetRateLimitedIfLater(ctx context.Context, id int64, resetAt time.Time) error } +type grokRateLimitRecoveryRepository interface { + ClearRateLimitIfObserved(ctx context.Context, id int64, observedLimitedAt, observedResetAt time.Time) (bool, error) +} + +func isSuccessfulGrokRateLimitRecovery(account *Account, snapshot *xai.QuotaSnapshot) bool { + return isGrokOAuthAccount(account) && + account.RateLimitedAt != nil && + account.RateLimitResetAt != nil && + snapshot != nil && + snapshot.StatusCode >= http.StatusOK && + snapshot.StatusCode < http.StatusMultipleChoices +} + +func clearGrokRateLimitAfterRecovery(ctx context.Context, repo AccountRepository, account *Account) { + if repo == nil || account == nil || account.RateLimitedAt == nil || account.RateLimitResetAt == nil || ctx.Err() != nil { + return + } + recoveryRepo, ok := repo.(grokRateLimitRecoveryRepository) + if !ok { + return + } + _, err := recoveryRepo.ClearRateLimitIfObserved(ctx, account.ID, *account.RateLimitedAt, *account.RateLimitResetAt) + if err != nil { + slog.Warn("grok_rate_limit_recovery_clear_failed", "account_id", account.ID, "error", err) + } +} + func persistGrokRateLimit(ctx context.Context, repo AccountRepository, account *Account, resetAt time.Time) { if repo == nil || account == nil || account.ID <= 0 { return diff --git a/backend/internal/service/openai_gateway_grok_cache.go b/backend/internal/service/openai_gateway_grok_cache.go index 1d689bce8a..dac9e975e1 100644 --- a/backend/internal/service/openai_gateway_grok_cache.go +++ b/backend/internal/service/openai_gateway_grok_cache.go @@ -1,6 +1,7 @@ package service import ( + "encoding/json" "fmt" "net/http" "strings" @@ -14,6 +15,7 @@ const ( grokConversationIDHeader = "X-Grok-Conv-Id" grokFreeCacheNativeToolsJSON = `[{"type":"web_search"},{"type":"x_search"}]` grokFreeCacheDisabledToolChoice = "none" + grokFreeRolling24hTokenLimit = int64(2_000_000) ) // resolveGrokCacheIdentity derives one stable, tenant-isolated routing identity @@ -100,8 +102,8 @@ func isGrokRequestContext(c *gin.Context) bool { // Free OAuth requests without native search tools are routed by xAI to the // non-cacheable build-free model. For otherwise tool-free requests, add the // native tools with tool_choice=none: this selects the cache-capable tier -// without allowing an actual search. Any explicit client tools or tool_choice -// disable this augmentation so client function-calling semantics stay intact. +// without allowing an actual search. Explicit client tools are handled by the +// narrower Messages-only mixed-tools policy below. func applyGrokResponsesCacheIdentity(body, intentSourceBody []byte, identity string, injectFreeTierTools bool) ([]byte, error) { identity = strings.TrimSpace(identity) if identity == "" { @@ -130,6 +132,169 @@ func applyGrokResponsesCacheIdentity(body, intentSourceBody []byte, identity str return sjson.SetBytes(out, "tool_choice", grokFreeCacheDisabledToolChoice) } +// applyGrokFreeMessagesFunctionToolCacheRoute enables xAI's cache-capable +// mixed-tools route only for the Anthropic Messages bridge and only when the +// selected account is known to be Free. Native tools become eligible under +// auto selection, so callers must not apply this policy to paid accounts or +// other ingress protocols implicitly. +func applyGrokFreeMessagesFunctionToolCacheRoute(body, intentSourceBody []byte, account *Account, cacheIdentity string) ([]byte, error) { + if strings.TrimSpace(cacheIdentity) == "" || !isKnownGrokFreeAccount(account) { + return body, nil + } + intentTools := gjson.GetBytes(intentSourceBody, "tools") + intentToolChoice := gjson.GetBytes(intentSourceBody, "tool_choice") + if !isGrokFreeCacheFunctionToolIntent(intentTools, intentToolChoice) { + return body, nil + } + return appendMissingGrokFreeCacheNativeTools(body) +} + +func isKnownGrokFreeAccount(account *Account) bool { + if account == nil || !account.IsGrokOAuth() { + return false + } + freeSignal := false + paidSignal := false + inferredFreeSignal := false + if billing, err := grokBillingSnapshotFromExtra(account.Extra); err == nil && billing != nil { + if tier := strings.TrimSpace(billing.Plan); tier != "" { + if isGrokFreeSubscriptionTier(tier) { + freeSignal = true + } else if !isGrokUnknownSubscriptionTier(tier) { + paidSignal = true + } + } + if billing.UsagePercent != nil || billing.UsedPercent != nil || + (billing.MonthlyLimitCents != nil && *billing.MonthlyLimitCents > 0) { + paidSignal = true + } + // xAI deliberately reports an empty plan for Free accounts; only paid + // subscriptions receive a SuperGrok plan/monthly limit. A successful + // monthly billing observation with no paid signal is therefore positive + // Free evidence, not an unknown tier. Keep partial probes fail-closed. + if strings.TrimSpace(billing.MonthlyUpdatedAt) != "" || + (billing.StatusCode >= http.StatusOK && billing.StatusCode < http.StatusMultipleChoices && + !billing.Partial && len(billing.FailedWindows) == 0) { + inferredFreeSignal = true + } + } + if snapshot, err := grokQuotaSnapshotFromExtra(account.Extra); err == nil && snapshot != nil { + if tier := strings.TrimSpace(snapshot.SubscriptionTier); tier != "" { + if isGrokFreeSubscriptionTier(tier) { + freeSignal = true + } else if !isGrokUnknownSubscriptionTier(tier) { + paidSignal = true + } + } + if snapshot.Tokens != nil && snapshot.Tokens.Limit != nil && + *snapshot.Tokens.Limit == grokFreeRolling24hTokenLimit { + inferredFreeSignal = true + } + } + if tier := strings.TrimSpace(account.GetCredential("subscription_tier")); tier != "" { + if isGrokFreeSubscriptionTier(tier) { + freeSignal = true + } else if !isGrokUnknownSubscriptionTier(tier) { + paidSignal = true + } + } + // Explicit paid evidence always wins over an inferred Free signal. This + // protects upgraded/stale accounts whose previous quota snapshot still + // carries the historical 2M Free token limit. + return !paidSignal && (freeSignal || inferredFreeSignal) +} + +func isGrokFreeSubscriptionTier(tier string) bool { + switch strings.ToLower(strings.TrimSpace(tier)) { + case "free", "grok-free", "grok_free", "free-tier", "free_tier", "basic", "grok-basic", "grok_basic": + return true + default: + return false + } +} + +func isGrokUnknownSubscriptionTier(tier string) bool { + switch strings.ToLower(strings.TrimSpace(tier)) { + case "", "unknown", "n/a", "none": + return true + default: + return false + } +} + +func isGrokFreeCacheFunctionToolIntent(tools, toolChoice gjson.Result) bool { + if !tools.IsArray() { + return false + } + items := tools.Array() + if len(items) == 0 { + return false + } + for _, tool := range items { + if !tool.IsObject() || strings.TrimSpace(tool.Get("type").String()) != "function" { + return false + } + // Responses function declarations keep name at the top level. Reject + // Chat Completions' nested function shape and incomplete declarations. + if strings.TrimSpace(tool.Get("name").String()) == "" || tool.Get("function").Exists() { + return false + } + } + if !toolChoice.Exists() { + return true + } + return toolChoice.Type == gjson.String && strings.TrimSpace(toolChoice.String()) == "auto" +} + +func appendMissingGrokFreeCacheNativeTools(body []byte) ([]byte, error) { + tools := gjson.GetBytes(body, "tools") + if !tools.Exists() || !tools.IsArray() { + return body, nil + } + + items := tools.Array() + if len(items) == 0 { + return body, nil + } + merged := make([]json.RawMessage, 0, len(items)+2) + present := make(map[string]bool, 2) + hasFunction := false + for _, tool := range items { + toolType := strings.TrimSpace(tool.Get("type").String()) + switch toolType { + case "function": + if !tool.IsObject() || strings.TrimSpace(tool.Get("name").String()) == "" || tool.Get("function").Exists() { + return body, nil + } + hasFunction = true + case "web_search", "x_search": + // Native tools may already be present when this helper is retried. + default: + return body, nil + } + merged = append(merged, json.RawMessage(tool.Raw)) + present[toolType] = true + } + if !hasFunction { + return body, nil + } + for _, toolType := range []string{"web_search", "x_search"} { + if present[toolType] { + continue + } + raw, err := json.Marshal(map[string]string{"type": toolType}) + if err != nil { + return nil, err + } + merged = append(merged, raw) + } + encoded, err := json.Marshal(merged) + if err != nil { + return nil, err + } + return sjson.SetRawBytes(body, "tools", encoded) +} + // applyGrokCacheHeaders applies the documented Chat Completions conversation // routing header. The request is built from a fresh header map, so client // supplied x-grok headers cannot override this server-derived value. diff --git a/backend/internal/service/openai_gateway_grok_cache_test.go b/backend/internal/service/openai_gateway_grok_cache_test.go index 42abfc5800..c31ee7bc37 100644 --- a/backend/internal/service/openai_gateway_grok_cache_test.go +++ b/backend/internal/service/openai_gateway_grok_cache_test.go @@ -197,15 +197,213 @@ func TestApplyGrokCacheIdentityWritesResponsesBodyAndHeader(t *testing.T) { require.False(t, gjson.GetBytes(unscopedBody, "tool_choice").Exists()) } -func TestApplyGrokCacheIdentityPreservesExplicitClientToolFields(t *testing.T) { +func TestApplyGrokCacheIdentityAppendsNativeToolsToResponseFunctions(t *testing.T) { + account := healthyGrokOAuthGatewayTestAccount(901, "access-token") + account.Credentials["subscription_tier"] = " FREE " + tests := []struct { + name string + toolChoiceJSON string + wantChoice bool + }{ + {name: "missing tool choice"}, + {name: "automatic tool choice", toolChoiceJSON: `,"tool_choice":"auto"`, wantChoice: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + intentBody := []byte(`{"model":"grok","tools":[{"type":"function","name":"lookup","description":"look up a value","parameters":{"type":"object"}},{"type":"function","name":"save","parameters":{"type":"object"}}]` + tt.toolChoiceJSON + `}`) + body, err := applyGrokResponsesCacheIdentity(intentBody, intentBody, "isolated-id", true) + require.NoError(t, err) + body, err = applyGrokFreeMessagesFunctionToolCacheRoute(body, intentBody, account, "isolated-id") + + require.NoError(t, err) + require.Equal(t, "isolated-id", gjson.GetBytes(body, "prompt_cache_key").String()) + tools := gjson.GetBytes(body, "tools").Array() + require.Len(t, tools, 4) + require.Equal(t, "function", tools[0].Get("type").String()) + require.Equal(t, "lookup", tools[0].Get("name").String()) + require.Equal(t, "function", tools[1].Get("type").String()) + require.Equal(t, "save", tools[1].Get("name").String()) + require.Equal(t, "web_search", tools[2].Get("type").String()) + require.Equal(t, "x_search", tools[3].Get("type").String()) + require.Equal(t, tt.wantChoice, gjson.GetBytes(body, "tool_choice").Exists()) + if tt.wantChoice { + require.Equal(t, "auto", gjson.GetBytes(body, "tool_choice").String()) + } + + second, err := applyGrokResponsesCacheIdentity(body, intentBody, "isolated-id", true) + require.NoError(t, err) + second, err = applyGrokFreeMessagesFunctionToolCacheRoute(second, intentBody, account, "isolated-id") + require.NoError(t, err) + require.JSONEq(t, string(body), string(second), "native tools must not be duplicated") + require.Len(t, gjson.GetBytes(second, "tools").Array(), 4) + }) + } +} + +func TestApplyGrokCacheIdentityRequiresPatchedFunctionTools(t *testing.T) { + account := healthyGrokOAuthGatewayTestAccount(902, "access-token") + account.Credentials["subscription_tier"] = "free" + intentBody := []byte(`{"model":"grok","tools":[{"type":"function","name":"lookup"}],"tool_choice":"auto"}`) + tests := []struct { + name string + patchedBody string + }{ + {name: "missing tools", patchedBody: `{"model":"grok-4.5"}`}, + {name: "empty tools", patchedBody: `{"model":"grok-4.5","tools":[]}`}, + {name: "native tools only", patchedBody: `{"model":"grok-4.5","tools":[{"type":"web_search"}]}`}, + {name: "unexpected patched tool", patchedBody: `{"model":"grok-4.5","tools":[{"type":"function","name":"lookup"},{"type":"mcp","name":"server"}]}`}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + beforeTools := gjson.Get(tt.patchedBody, "tools") + body, err := applyGrokResponsesCacheIdentity([]byte(tt.patchedBody), intentBody, "isolated-id", true) + require.NoError(t, err) + body, err = applyGrokFreeMessagesFunctionToolCacheRoute(body, intentBody, account, "isolated-id") + + require.NoError(t, err) + require.Equal(t, "isolated-id", gjson.GetBytes(body, "prompt_cache_key").String()) + afterTools := gjson.GetBytes(body, "tools") + require.Equal(t, beforeTools.Exists(), afterTools.Exists()) + require.Equal(t, beforeTools.Raw, afterTools.Raw) + }) + } +} + +func TestGrokFreeMessagesFunctionToolCacheRouteRequiresKnownFreeTier(t *testing.T) { + intentBody := []byte(`{"model":"grok","tools":[{"type":"function","name":"lookup"}],"tool_choice":"auto"}`) + tests := []struct { + name string + account *Account + wantMix bool + }{ + { + name: "free credential tier", + account: func() *Account { + a := healthyGrokOAuthGatewayTestAccount(910, "access-token") + a.Credentials["subscription_tier"] = "free" + return a + }(), + wantMix: true, + }, + { + name: "free billing tier", + account: func() *Account { + a := healthyGrokOAuthGatewayTestAccount(911, "access-token") + a.Extra = map[string]any{grokBillingExtraKey: map[string]any{"plan": "FREE"}} + return a + }(), + wantMix: true, + }, + { + name: "free successful billing has blank plan", + account: func() *Account { + a := healthyGrokOAuthGatewayTestAccount(9111, "access-token") + a.Extra = map[string]any{grokBillingExtraKey: map[string]any{ + "status_code": http.StatusOK, + "source": "billing_probe", + "monthly_updated_at": "2026-07-15T05:00:00Z", + }} + return a + }(), + wantMix: true, + }, + { + name: "free rolling token quota", + account: func() *Account { + a := healthyGrokOAuthGatewayTestAccount(9112, "access-token") + a.Extra = map[string]any{grokQuotaSnapshotExtraKey: map[string]any{ + "headers_observed": true, + "tokens": map[string]any{"limit": grokFreeRolling24hTokenLimit}, + }} + return a + }(), + wantMix: true, + }, + { + name: "supergrok remains unchanged", + account: func() *Account { + a := healthyGrokOAuthGatewayTestAccount(912, "access-token") + a.Credentials["subscription_tier"] = "supergrok" + return a + }(), + }, + { + name: "paid billing overrides stale free quota", + account: func() *Account { + a := healthyGrokOAuthGatewayTestAccount(9121, "access-token") + a.Extra = map[string]any{ + grokBillingExtraKey: map[string]any{"plan": "SuperGrok", "status_code": http.StatusOK}, + grokQuotaSnapshotExtraKey: map[string]any{ + "headers_observed": true, + "tokens": map[string]any{"limit": grokFreeRolling24hTokenLimit}, + }, + } + return a + }(), + }, + { + name: "partial billing without monthly evidence remains unknown", + account: func() *Account { + a := healthyGrokOAuthGatewayTestAccount(9122, "access-token") + a.Extra = map[string]any{grokBillingExtraKey: map[string]any{ + "status_code": http.StatusOK, + "source": "billing_probe", + "partial": true, + "failed_windows": []string{"monthly"}, + }} + return a + }(), + }, + { + name: "unknown tier remains unchanged", + account: healthyGrokOAuthGatewayTestAccount(913, "access-token"), + }, + { + name: "api key remains unchanged", + account: &Account{ + ID: 914, + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + body, err := applyGrokFreeMessagesFunctionToolCacheRoute(intentBody, intentBody, tt.account, "isolated-id") + + require.NoError(t, err) + tools := gjson.GetBytes(body, "tools").Array() + if tt.wantMix { + require.Len(t, tools, 3) + require.Equal(t, "web_search", tools[1].Get("type").String()) + require.Equal(t, "x_search", tools[2].Get("type").String()) + return + } + require.Len(t, tools, 1) + }) + } +} + +func TestGrokFreeMessagesFunctionToolCacheRouteRequiresIdentity(t *testing.T) { + account := healthyGrokOAuthGatewayTestAccount(915, "access-token") + account.Credentials["subscription_tier"] = "free" + body := []byte(`{"model":"grok","tools":[{"type":"function","name":"lookup"}],"tool_choice":"auto"}`) + + patched, err := applyGrokFreeMessagesFunctionToolCacheRoute(body, body, account, "") + + require.NoError(t, err) + require.JSONEq(t, string(body), string(patched)) + require.Len(t, gjson.GetBytes(patched, "tools").Array(), 1) +} + +func TestApplyGrokCacheIdentityPreservesIneligibleClientToolFields(t *testing.T) { tests := []struct { name string body string }{ - { - name: "tools only", - body: `{"model":"grok","tools":[{"type":"function","name":"lookup","parameters":{"type":"object"}}]}`, - }, { name: "empty tools array", body: `{"model":"grok","tools":[]}`, @@ -223,13 +421,41 @@ func TestApplyGrokCacheIdentityPreservesExplicitClientToolFields(t *testing.T) { body: `{"model":"grok","tool_choice":null}`, }, { - name: "both fields", + name: "native tool with auto choice", body: `{"model":"grok","tools":[{"type":"web_search"}],"tool_choice":"auto"}`, }, { - name: "unsupported tool", + name: "function with required choice", + body: `{"model":"grok","tools":[{"type":"function","name":"lookup"}],"tool_choice":"required"}`, + }, + { + name: "function with none choice", + body: `{"model":"grok","tools":[{"type":"function","name":"lookup"}],"tool_choice":"none"}`, + }, + { + name: "function with specific choice", + body: `{"model":"grok","tools":[{"type":"function","name":"lookup"}],"tool_choice":{"type":"function","name":"lookup"}}`, + }, + { + name: "function with object auto choice", + body: `{"model":"grok","tools":[{"type":"function","name":"lookup"}],"tool_choice":{"type":"auto"}}`, + }, + { + name: "function mixed with unsupported tool", + body: `{"model":"grok","tools":[{"type":"function","name":"lookup"},{"type":"namespace","name":"client_tools"}],"tool_choice":"auto"}`, + }, + { + name: "unsupported tool only", body: `{"model":"grok","tools":[{"type":"namespace","name":"client_tools"}]}`, }, + { + name: "chat completions function shape", + body: `{"model":"grok","tools":[{"type":"function","function":{"name":"lookup","parameters":{"type":"object"}}}],"tool_choice":"auto"}`, + }, + { + name: "incomplete responses function", + body: `{"model":"grok","tools":[{"type":"function","parameters":{"type":"object"}}]}`, + }, } for _, tt := range tests { diff --git a/backend/internal/service/openai_gateway_grok_chat_bridge.go b/backend/internal/service/openai_gateway_grok_chat_bridge.go index fd6b426536..0b8f0e2d83 100644 --- a/backend/internal/service/openai_gateway_grok_chat_bridge.go +++ b/backend/internal/service/openai_gateway_grok_chat_bridge.go @@ -10,8 +10,8 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" - "github.com/Wei-Shaw/sub2api/internal/pkg/xai" "github.com/gin-gonic/gin" + "github.com/tidwall/gjson" ) const ( @@ -142,20 +142,63 @@ func grokChatResponsesBridgeEligibility(body []byte) (bool, string) { default: return false, "unsupported_message_role_" + role } - var content string - if raw, exists := message["content"]; !exists || json.Unmarshal(raw, &content) != nil { - // Structured content includes image_url and other parts whose exact - // behavior is not guaranteed by this bridge. + raw, exists := message["content"] + if !exists { return false, "non_text_message_content" } - if strings.TrimSpace(content) == "" { - return false, "empty_message_content" + var content string + if json.Unmarshal(raw, &content) == nil { + if strings.TrimSpace(content) == "" { + return false, "empty_message_content" + } + continue + } + // Structured content: only allow arrays whose parts are text or + // image_url. These are losslessly convertible to Responses input_text/ + // input_image parts, so the bridge preserves Chat Completions semantics. + if ok, reason := grokChatStructuredContentBridgeable(raw); !ok { + return false, reason } } return true, "" } +func grokChatStructuredContentBridgeable(raw json.RawMessage) (bool, string) { + var parts []map[string]json.RawMessage + if err := json.Unmarshal(raw, &parts); err != nil { + return false, "non_text_message_content" + } + if len(parts) == 0 { + return false, "empty_message_content" + } + hasContent := false + for _, part := range parts { + var partType string + rawType, ok := part["type"] + if !ok || json.Unmarshal(rawType, &partType) != nil { + return false, "non_text_message_content" + } + switch strings.TrimSpace(partType) { + case "text": + var text string + if raw, ok := part["text"]; ok && json.Unmarshal(raw, &text) == nil { + if strings.TrimSpace(text) != "" { + hasContent = true + } + } + case "image_url", "input_image": + hasContent = true + default: + return false, "unsupported_content_part_" + strings.TrimSpace(partType) + } + } + if !hasContent { + return false, "empty_message_content" + } + return true, "" +} + func grokChatNullOrEmptyArray(raw json.RawMessage) bool { if strings.TrimSpace(string(raw)) == "null" { return true @@ -210,7 +253,12 @@ func (s *OpenAIGatewayService) forwardGrokChatCompletionsViaResponses( billingModel := resolveOpenAIForwardModel(account, originalModel, defaultMappedModel) upstreamModel := normalizeOpenAIModelForUpstream(account, billingModel) cacheIdentity := resolveGrokCacheIdentity(c, body, promptCacheKey, upstreamModel) - if !grokChatResponsesRuntimeEligible(upstreamModel, cacheIdentity) { + // Image inputs must go through the Responses bridge: the raw Chat + // Completions path cannot forward image_url parts to Grok's native vision + // for non-composer models, so they would be silently dropped. Route them to + // Responses even when no prompt-cache identity is available. + hasImageInput := openAIJSONValueMayContainImageInput(gjson.GetBytes(body, "messages")) + if !grokChatResponsesRuntimeEligible(upstreamModel, cacheIdentity) && (!hasImageInput || strings.TrimSpace(upstreamModel) != "grok-4.5") { return s.forwardAsRawChatCompletions(ctx, c, account, body, defaultMappedModel) } @@ -253,12 +301,12 @@ func (s *OpenAIGatewayService) forwardGrokChatCompletionsViaResponses( } responsesBody = updatedBody - token, _, err := s.GetAccessToken(ctx, account) + token, _, err := s.getRequestCredential(ctx, c, account) if err != nil { return nil, fmt.Errorf("get grok access token: %w", err) } upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) - upstreamReq, err := buildGrokResponsesRequest(upstreamCtx, c, account, responsesBody, token, cacheIdentity) + upstreamReq, err := buildGrokResponsesRequest(upstreamCtx, c, account, responsesBody, token, cacheIdentity, s.cfg) releaseUpstreamCtx() if err != nil { return nil, fmt.Errorf("build grok responses bridge request: %w", err) @@ -294,13 +342,14 @@ func (s *OpenAIGatewayService) forwardGrokChatCompletionsViaResponses( return nil, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: respBody, + ResponseHeaders: resp.Header.Clone(), RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode), } } return s.handleChatCompletionsErrorResponse(resp, c, account, billingModel) } - s.updateGrokUsageSnapshot(ctx, account, xai.ParseQuotaHeaders(resp.Header, resp.StatusCode)) + s.updateGrokUsageFromResponse(ctx, account, resp.Header, resp.StatusCode) var result *OpenAIForwardResult if clientStream { diff --git a/backend/internal/service/openai_gateway_grok_chat_bridge_test.go b/backend/internal/service/openai_gateway_grok_chat_bridge_test.go index 0843f1ea42..86fc45e952 100644 --- a/backend/internal/service/openai_gateway_grok_chat_bridge_test.go +++ b/backend/internal/service/openai_gateway_grok_chat_bridge_test.go @@ -50,9 +50,29 @@ func TestGrokChatResponsesBridgeEligibility(t *testing.T) { reason: "unsupported_message_role_developer", }, { - name: "image content falls back", - body: `{"model":"grok","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,QQ=="}}]}]}`, - reason: "non_text_message_content", + name: "image content is bridgeable", + body: `{"model":"grok","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,QQ=="}}]}]}`, + want: true, + }, + { + name: "text and image parts are bridgeable", + body: `{"model":"grok","messages":[{"role":"user","content":[{"type":"text","text":"what is this"},{"type":"image_url","image_url":{"url":"data:image/png;base64,QQ=="}}]}]}`, + want: true, + }, + { + name: "text only parts are bridgeable", + body: `{"model":"grok","messages":[{"role":"user","content":[{"type":"text","text":"hello"}]}]}`, + want: true, + }, + { + name: "unknown content part falls back", + body: `{"model":"grok","messages":[{"role":"user","content":[{"type":"input_audio","input_audio":{"data":"AA=="}}]}]}`, + reason: "unsupported_content_part_input_audio", + }, + { + name: "empty content array falls back", + body: `{"model":"grok","messages":[{"role":"user","content":[]}]}`, + reason: "empty_message_content", }, { name: "function tools fall back", @@ -284,6 +304,7 @@ func TestForwardGrokChatViaResponses429UsesGrokRateLimitPolicy(t *testing.T) { var failoverErr *UpstreamFailoverError require.True(t, errors.As(err, &failoverErr)) require.Equal(t, http.StatusTooManyRequests, failoverErr.StatusCode) + require.Equal(t, "45", failoverErr.ResponseHeaders.Get("Retry-After")) require.Equal(t, xai.DefaultCLIBaseURL+"/responses", upstream.lastReq.URL.String()) require.Equal(t, grokChatResponsesEndpoint, GetActualOpenAIUpstreamEndpoint(c)) require.Equal(t, 1, repo.rateLimitedCalls) @@ -292,6 +313,45 @@ func TestForwardGrokChatViaResponses429UsesGrokRateLimitPolicy(t *testing.T) { require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) } +func TestForwardGrokRawChat429PreservesRetryAfter(t *testing.T) { + gin.SetMode(gin.TestMode) + + body := []byte(`{"model":"grok","messages":[{"role":"user","content":"hi"}],"stream":false,"stop":"done"}`) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, grokChatRawEndpoint, bytes.NewReader(body)) + c.Set("api_key", &APIKey{ID: 7551}) + + account := grokChatBridgeTestAccount(755) + account.Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ + accountsByID: map[int64]*Account{account.ID: account}, + }} + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusTooManyRequests, + Header: http.Header{ + "Content-Type": []string{"application/json"}, + "Retry-After": []string{"45"}, + }, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"rate limited"}}`)), + }} + svc := &OpenAIGatewayService{ + httpUpstream: upstream, + grokTokenProvider: NewGrokTokenProvider(repo, nil), + accountRepo: repo, + } + + result, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + + require.Error(t, err) + require.Nil(t, result) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, http.StatusTooManyRequests, failoverErr.StatusCode) + require.Equal(t, "45", failoverErr.ResponseHeaders.Get("Retry-After")) + require.Equal(t, xai.DefaultCLIBaseURL+"/chat/completions", upstream.lastReq.URL.String()) +} + func TestForwardGrokRawChatErrorRecordsActualEndpoint(t *testing.T) { gin.SetMode(gin.TestMode) @@ -329,11 +389,14 @@ func grokChatBridgeTestAccount(id int64) *Account { Name: "grok-cache-bridge", Platform: PlatformGrok, Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, Concurrency: 1, Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, + "access_token": "access-token", + "refresh_token": "refresh-token", + "expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339), + "base_url": xai.DefaultCLIBaseURL, }, } } diff --git a/backend/internal/service/openai_gateway_grok_test.go b/backend/internal/service/openai_gateway_grok_test.go index 3b64cbc16b..6b5367c0f0 100644 --- a/backend/internal/service/openai_gateway_grok_test.go +++ b/backend/internal/service/openai_gateway_grok_test.go @@ -256,10 +256,10 @@ func TestBuildGrokResponsesRequestUsesAccountBaseURLAndBearerToken(t *testing.T) }, } - req, err := buildGrokResponsesRequest(context.Background(), nil, account, []byte(`{"model":"grok-4.3"}`), "access-token", "isolated-cache-id") + req, err := buildGrokResponsesRequest(context.Background(), nil, account, []byte(`{"model":"grok-4.3"}`), "access-token", "isolated-cache-id", nil) require.NoError(t, err) require.Equal(t, http.MethodPost, req.Method) - require.Equal(t, "https://xai.test/v1/responses", req.URL.String()) + require.Equal(t, xai.DefaultCLIBaseURL+"/responses", req.URL.String()) require.Equal(t, "Bearer access-token", req.Header.Get("Authorization")) require.Equal(t, "application/json", req.Header.Get("Content-Type")) require.Contains(t, req.Header.Get("Accept"), "text/event-stream") @@ -280,10 +280,12 @@ func TestBuildGrokResponsesRequestAllowsPublicAPIKeyBaseURLByDefault(t *testing. }, } - req, err := buildGrokResponsesRequest(context.Background(), nil, account, []byte(`{"model":"grok-4.3"}`), "api-key", "") + req, err := buildGrokResponsesRequest(context.Background(), nil, account, []byte(`{"model":"grok-4.3"}`), "api-key", "", nil) require.NoError(t, err) require.Equal(t, "https://grok.example.test/v1/responses", req.URL.String()) require.Equal(t, "Bearer api-key", req.Header.Get("Authorization")) + require.Empty(t, req.Header.Get("X-Grok-Client-Version")) + require.NotEqual(t, grokUpstreamUserAgent, req.Header.Get("User-Agent")) } func TestBuildGrokResponsesRequestPinsOAuthCustomBaseURLByDefault(t *testing.T) { @@ -297,7 +299,7 @@ func TestBuildGrokResponsesRequestPinsOAuthCustomBaseURLByDefault(t *testing.T) }, } - req, err := buildGrokResponsesRequest(context.Background(), nil, account, []byte(`{"model":"grok-4.3"}`), "access-token", "") + req, err := buildGrokResponsesRequest(context.Background(), nil, account, []byte(`{"model":"grok-4.3"}`), "access-token", "", nil) require.NoError(t, err) require.Equal(t, xai.DefaultCLIBaseURL+"/responses", req.URL.String()) } @@ -425,7 +427,8 @@ func TestForwardGrokMediaImagesGenerationNormalizesImagineAlias(t *testing.T) { require.Equal(t, http.MethodPost, upstream.lastReq.Method) require.Equal(t, "Bearer api-key", upstream.lastReq.Header.Get("Authorization")) require.Equal(t, "application/json", upstream.lastReq.Header.Get("Content-Type")) - require.Equal(t, grokCLIVersion, upstream.lastReq.Header.Get("X-Grok-Client-Version")) + require.Empty(t, upstream.lastReq.Header.Get("X-Grok-Client-Version")) + require.NotEqual(t, grokUpstreamUserAgent, upstream.lastReq.Header.Get("User-Agent")) require.JSONEq(t, `{"model":"grok-imagine-image-quality","prompt":"draw a cat"}`, string(upstream.lastBody)) require.Equal(t, http.StatusOK, recorder.Code) require.JSONEq(t, `{"data":[]}`, recorder.Body.String()) @@ -611,7 +614,7 @@ func TestForwardGrokMediaVideoGenerationPreservesImageToVideoModel(t *testing.T) require.Equal(t, VideoBillingDefaultDurationSeconds, result.VideoDurationSeconds) } -func TestForwardGrokMediaOAuthImageToVideoUsesOfficialAPIForLargeBody(t *testing.T) { +func TestForwardGrokMediaOAuthImageToVideoKeepsCLIGatewayForLargeBody(t *testing.T) { gin.SetMode(gin.TestMode) recorder := httptest.NewRecorder() @@ -626,10 +629,14 @@ func TestForwardGrokMediaOAuthImageToVideoUsesOfficialAPIForLargeBody(t *testing Name: "grok-oauth", Platform: PlatformGrok, Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, Concurrency: 1, Credentials: map[string]any{ - "access_token": "oauth-access-token", - "base_url": xai.DefaultCLIBaseURL, + "access_token": "oauth-access-token", + "refresh_token": "oauth-refresh-token", + "expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339), + "base_url": xai.DefaultCLIBaseURL, }, } upstream := &httpUpstreamRecorder{resp: &http.Response{ @@ -639,11 +646,11 @@ func TestForwardGrokMediaOAuthImageToVideoUsesOfficialAPIForLargeBody(t *testing }, Body: io.NopCloser(strings.NewReader(`{"request_id":"video-request-oauth"}`)), }} - svc := &OpenAIGatewayService{httpUpstream: upstream} + svc := &OpenAIGatewayService{httpUpstream: upstream, grokTokenProvider: NewGrokTokenProvider(nil, nil)} _, err := svc.ForwardGrokMedia(context.Background(), c, account, GrokMediaEndpointVideosGenerations, "", body, "application/json") require.NoError(t, err) - require.Equal(t, xai.DefaultBaseURL+"/videos/generations", upstream.lastReq.URL.String()) + require.Equal(t, xai.DefaultCLIBaseURL+"/videos/generations", upstream.lastReq.URL.String()) require.Equal(t, "data:image/png;base64,"+imageData, gjson.GetBytes(upstream.lastBody, "image.image_url").String()) } @@ -681,6 +688,8 @@ func TestForwardGrokMediaVideoStatusUsesGETWithoutBody(t *testing.T) { require.Equal(t, "https://xai.test/v1/videos/request-123", upstream.lastReq.URL.String()) require.Equal(t, http.MethodGet, upstream.lastReq.Method) require.Equal(t, "Bearer api-key", upstream.lastReq.Header.Get("Authorization")) + require.Empty(t, upstream.lastReq.Header.Get("X-Grok-Client-Version")) + require.NotEqual(t, grokUpstreamUserAgent, upstream.lastReq.Header.Get("User-Agent")) require.Empty(t, upstream.lastReq.Header.Get("Content-Type")) require.Empty(t, upstream.lastBody) require.Equal(t, http.StatusOK, recorder.Code) @@ -792,6 +801,54 @@ func TestForwardGrokMedia429ReconcilesRateLimitBeforeCustomErrorBypass(t *testin require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) } +func TestGrokMedia429FailoverPreservesRetryAfter(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", nil) + account := &Account{ + ID: 641, Name: "grok-oauth", Platform: PlatformGrok, Type: AccountTypeOAuth, + Status: StatusActive, Schedulable: true, + Credentials: map[string]any{ + "custom_error_codes_enabled": true, + "custom_error_codes": []any{float64(http.StatusTooManyRequests)}, + }, + } + repo := &grokQuotaAccountRepo{} + svc := &OpenAIGatewayService{accountRepo: repo} + resp := &http.Response{ + StatusCode: http.StatusTooManyRequests, + Header: http.Header{"Retry-After": []string{"45"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"rate limited"}}`)), + } + + result, err := svc.handleGrokMediaErrorResponse(context.Background(), resp, c, account, "request-id", "grok-imagine") + + require.Nil(t, result) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, http.StatusTooManyRequests, failoverErr.StatusCode) + require.Equal(t, "45", failoverErr.ResponseHeaders.Get("Retry-After")) +} + +func healthyGrokOAuthGatewayTestAccount(id int64, token string) *Account { + return &Account{ + ID: id, + Name: "grok", + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{ + "access_token": token, + "refresh_token": "refresh-token", + "expires_at": time.Now().Add(2 * grokTokenRefreshSkew).UTC().Format(time.RFC3339), + "base_url": xai.DefaultCLIBaseURL, + }, + } +} + func TestForwardAsChatCompletionsForGrokStopFallsBackToXAIChatCompletions(t *testing.T) { gin.SetMode(gin.TestMode) @@ -801,18 +858,7 @@ func TestForwardAsChatCompletionsForGrokStopFallsBackToXAIChatCompletions(t *tes c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) c.Set("api_key", &APIKey{ID: 5101}) - account := &Account{ - ID: 51, - Name: "grok", - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, - }, - } + account := healthyGrokOAuthGatewayTestAccount(51, "access-token") repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{51: account}, @@ -864,18 +910,7 @@ func TestForwardGrokResponsesStreamingDefaultsEmptyModelTo45AndSnapshots(t *test c.Request.Header.Set("OpenAI-Beta", "responses=experimental") c.Set("api_key", &APIKey{ID: 5201}) - account := &Account{ - ID: 52, - Name: "grok", - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, - }, - } + account := healthyGrokOAuthGatewayTestAccount(52, "access-token") repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{52: account}, @@ -968,12 +1003,46 @@ func TestForwardGrokResponsesAPIKeyUsesXAIResponses(t *testing.T) { require.NoError(t, err) require.Equal(t, "https://api.x.ai/v1/responses", upstream.lastReq.URL.String()) require.Equal(t, "Bearer xai-test-key", upstream.lastReq.Header.Get("Authorization")) + require.Empty(t, upstream.lastReq.Header.Get("X-Grok-Client-Version")) + require.NotEqual(t, grokUpstreamUserAgent, upstream.lastReq.Header.Get("User-Agent")) require.Equal(t, "grok-4.5", gjson.GetBytes(upstream.lastBody, "model").String()) require.Equal(t, "resp_grok_api_key", result.ResponseID) require.Equal(t, 2, result.Usage.InputTokens) require.Equal(t, 1, result.Usage.OutputTokens) } +func TestForwardAsChatCompletionsForGrokAPIKeyUsesConfiguredRawEndpointWithoutOAuthIdentity(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + body := []byte(`{"model":"grok","messages":[{"role":"user","content":"hi"}],"stream":false}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + account := &Account{ + ID: 706, + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{ + "api_key": "third-party-key", + "base_url": "https://grok.example.test/v1", + }, + } + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"id":"chatcmpl","object":"chat.completion","model":"grok-4.5","choices":[],"usage":{"prompt_tokens":1,"completion_tokens":1}}`)), + }} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + require.NoError(t, err) + require.Equal(t, "https://grok.example.test/v1/chat/completions", upstream.lastReq.URL.String()) + require.Equal(t, "Bearer third-party-key", upstream.lastReq.Header.Get("Authorization")) + require.Empty(t, upstream.lastReq.Header.Get("X-Grok-Client-Version")) + require.NotEqual(t, grokUpstreamUserAgent, upstream.lastReq.Header.Get("User-Agent")) +} + func TestAccountTestServiceGrokAPIKeyUsesXAIResponses(t *testing.T) { gin.SetMode(gin.TestMode) @@ -1008,6 +1077,41 @@ func TestAccountTestServiceGrokAPIKeyUsesXAIResponses(t *testing.T) { require.Contains(t, recorder.Body.String(), `"type":"test_complete"`) } +func TestAccountTestServiceGrokAPIKeyAllowsConfiguredHTTPWhenGlobalPolicyDoes(t *testing.T) { + gin.SetMode(gin.TestMode) + + account := &Account{ + ID: 55, + Name: "grok-api-key-http", + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{ + "api_key": "third-party-key", + "base_url": "http://grok.example.test/v1", + }, + } + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader( + "data: {\"type\":\"response.output_text.delta\",\"delta\":\"ok\"}\n\n" + + "data: {\"type\":\"response.completed\"}\n\n", + )), + }} + svc := &AccountTestService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/55/test", nil) + + err := svc.testGrokAccountConnection(c, account, "grok") + require.NoError(t, err) + require.Equal(t, "http://grok.example.test/v1/responses", upstream.lastReq.URL.String()) + require.Equal(t, "Bearer third-party-key", upstream.lastReq.Header.Get("Authorization")) + require.Empty(t, upstream.lastReq.Header.Get("X-Grok-Client-Version")) + require.Contains(t, recorder.Body.String(), `"type":"test_complete"`) +} + func TestForwardAsChatCompletionsForGrokStreamingUsesRawXAIChatCompletions(t *testing.T) { gin.SetMode(gin.TestMode) @@ -1017,18 +1121,7 @@ func TestForwardAsChatCompletionsForGrokStreamingUsesRawXAIChatCompletions(t *te c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) c.Request.Header.Set("Content-Type", "application/json") - account := &Account{ - ID: 53, - Name: "grok", - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, - }, - } + account := healthyGrokOAuthGatewayTestAccount(53, "access-token") repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{53: account}, @@ -1085,22 +1178,16 @@ func TestForwardGrokResponsesNonStreamingUsesCacheIdentityAndCachedUsage(t *test c.Request.Header.Set("Content-Type", "application/json") c.Set("api_key", &APIKey{ID: 5202}) - account := &Account{ - ID: 56, - Name: "grok", - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, - }, - } + account := healthyGrokOAuthGatewayTestAccount(56, "access-token") + observedResetAt := time.Now().Add(-time.Second).UTC().Truncate(time.Second) + observedLimitedAt := observedResetAt.Add(-grokRateLimitRepeatCooldown) + account.RateLimitedAt = &observedLimitedAt + account.RateLimitResetAt = &observedResetAt repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{56: account}, }, + recoveryClearResult: true, } upstream := &httpUpstreamRecorder{resp: &http.Response{ StatusCode: http.StatusOK, @@ -1133,6 +1220,9 @@ func TestForwardGrokResponsesNonStreamingUsesCacheIdentityAndCachedUsage(t *test require.False(t, gjson.GetBytes(upstream.lastBody, "tools").Exists()) require.False(t, gjson.GetBytes(upstream.lastBody, "tool_choice").Exists()) require.Equal(t, "resp_grok_non_stream", gjson.Get(recorder.Body.String(), "id").String()) + require.Equal(t, 1, repo.recoveryClearCalls) + require.Equal(t, observedLimitedAt, repo.recoveryObservedAt) + require.Equal(t, observedResetAt, repo.recoveryObservedReset) } func TestForwardGrokResponsesFailoverKeepsCacheIdentityAcrossAccounts(t *testing.T) { @@ -1145,18 +1235,9 @@ func TestForwardGrokResponsesFailoverKeepsCacheIdentityAcrossAccounts(t *testing c.Set("api_key", &APIKey{ID: 5203}) newAccount := func(id int64, token string) *Account { - return &Account{ - ID: id, - Name: fmt.Sprintf("grok-%d", id), - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": token, - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, - }, - } + account := healthyGrokOAuthGatewayTestAccount(id, token) + account.Name = fmt.Sprintf("grok-%d", id) + return account } firstAccount := newAccount(58, "access-token-a") secondAccount := newAccount(59, "access-token-b") @@ -1213,18 +1294,7 @@ func TestForwardAsChatCompletionsForGrokStreamingStopFallsBackToRawXAIChatComple c.Request.Header.Set(grokConversationIDHeader, "native-client-conversation") c.Set("api_key", &APIKey{ID: 5301}) - account := &Account{ - ID: 53, - Name: "grok", - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, - }, - } + account := healthyGrokOAuthGatewayTestAccount(53, "access-token") repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{53: account}, @@ -1284,18 +1354,7 @@ func TestForwardAsChatCompletionsForGrokComposerBridgesImageInput(t *testing.T) c.Request.Header.Set("Content-Type", "application/json") c.Set("api_key", &APIKey{ID: 5501}) - account := &Account{ - ID: 55, - Name: "grok", - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, - }, - } + account := healthyGrokOAuthGatewayTestAccount(55, "access-token") repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{55: account}, @@ -1358,18 +1417,7 @@ func TestForwardAsAnthropicForGrokUsesXAIResponses(t *testing.T) { c.Request.Header.Set("OpenAI-Beta", "grok-experimental") c.Request.Header.Set("originator", "opencode") - account := &Account{ - ID: 54, - Name: "grok", - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, - }, - } + account := healthyGrokOAuthGatewayTestAccount(54, "access-token") repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{54: account}, @@ -1410,6 +1458,77 @@ func TestForwardAsAnthropicForGrokUsesXAIResponses(t *testing.T) { require.Contains(t, recorder.Body.String(), "ok") } +func TestForwardAsAnthropicForGrokFunctionToolUsesCacheCapableMixedRoute(t *testing.T) { + gin.SetMode(gin.TestMode) + + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + body := []byte(`{ + "model":"grok","max_tokens":32,"stream":false, + "messages":[{"role":"user","content":"look up alpha"}], + "tools":[{"name":"lookup","description":"look up a key","input_schema":{"type":"object","properties":{"key":{"type":"string"}},"required":["key"]}}], + "tool_choice":{"type":"auto"} + }`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + c.Set("api_key", &APIKey{ID: 5403}) + + account := healthyGrokOAuthGatewayTestAccount(58, "access-token") + account.Extra = map[string]any{grokBillingExtraKey: map[string]any{ + "status_code": http.StatusOK, + "source": "billing_probe", + "monthly_updated_at": "2026-07-15T05:00:00Z", + }} + repo := &grokQuotaAccountRepo{ + mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ + accountsByID: map[int64]*Account{58: account}, + }, + } + responseBody := strings.Join([]string{ + `data: {"type":"response.completed","response":{"id":"resp_grok_function","object":"response","model":"grok-4.5","status":"completed","output":[{"type":"function_call","id":"fc_lookup","call_id":"call_lookup","name":"lookup","arguments":"{\"key\":\"alpha\"}","status":"completed"}],"usage":{"input_tokens":7000,"output_tokens":2,"total_tokens":7002,"input_tokens_details":{"cached_tokens":6144}}}}`, + "", + "data: [DONE]", + "", + }, "\n") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(responseBody)), + }} + svc := &OpenAIGatewayService{ + httpUpstream: upstream, + grokTokenProvider: NewGrokTokenProvider(repo, nil), + accountRepo: repo, + } + + result, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, xai.DefaultCLIBaseURL+"/responses", upstream.lastReq.URL.String()) + identity := gjson.GetBytes(upstream.lastBody, "prompt_cache_key").String() + require.NotEmpty(t, identity) + require.Equal(t, identity, upstream.lastReq.Header.Get(grokConversationIDHeader)) + tools := gjson.GetBytes(upstream.lastBody, "tools").Array() + require.Len(t, tools, 3) + require.Equal(t, "function", tools[0].Get("type").String()) + require.Equal(t, "lookup", tools[0].Get("name").String()) + require.Equal(t, "object", tools[0].Get("parameters.type").String()) + require.Equal(t, "web_search", tools[1].Get("type").String()) + require.Equal(t, "x_search", tools[2].Get("type").String()) + require.Equal(t, "auto", gjson.GetBytes(upstream.lastBody, "tool_choice").String()) + + require.Equal(t, 7000, result.Usage.InputTokens) + require.Equal(t, 6144, result.Usage.CacheReadInputTokens) + clientBody := recorder.Body.String() + require.Equal(t, "tool_use", gjson.Get(clientBody, "content.0.type").String()) + require.Equal(t, "call_lookup", gjson.Get(clientBody, "content.0.id").String()) + require.Equal(t, "lookup", gjson.Get(clientBody, "content.0.name").String()) + require.Equal(t, "alpha", gjson.Get(clientBody, "content.0.input.key").String()) + require.Equal(t, "tool_use", gjson.Get(clientBody, "stop_reason").String()) + require.Equal(t, int64(856), gjson.Get(clientBody, "usage.input_tokens").Int()) + require.Equal(t, int64(6144), gjson.Get(clientBody, "usage.cache_read_input_tokens").Int()) +} + func TestForwardAsAnthropicForGrokStreamingPreservesCacheUsage(t *testing.T) { gin.SetMode(gin.TestMode) @@ -1419,18 +1538,7 @@ func TestForwardAsAnthropicForGrokStreamingPreservesCacheUsage(t *testing.T) { c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) c.Set("api_key", &APIKey{ID: 5402}) - account := &Account{ - ID: 57, - Name: "grok", - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, - }, - } + account := healthyGrokOAuthGatewayTestAccount(57, "access-token") repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{57: account}, @@ -1571,6 +1679,102 @@ func TestHandleGrokAccountUpstreamError429UsesFallbackReset(t *testing.T) { require.Zero(t, repo.tempUnschedCalls) } +func TestGrokRateLimitResetAtForAccountEscalatesRepeated429s(t *testing.T) { + now := time.Now().UTC().Truncate(time.Second) + retryAfter := 45 + snapshot := &xai.QuotaSnapshot{ + StatusCode: http.StatusTooManyRequests, + RetryAfterSeconds: &retryAfter, + UpdatedAt: now.Format(time.RFC3339), + } + tests := []struct { + name string + previousCooldown time.Duration + wantCooldown time.Duration + }{ + {name: "repeat after short boundary", previousCooldown: 45 * time.Second, wantCooldown: grokRateLimitRepeatCooldown}, + {name: "sustained repeat", previousCooldown: grokRateLimitRepeatCooldown, wantCooldown: grokRateLimitSustainedCooldown}, + {name: "capped repeat", previousCooldown: grokRateLimitSustainedCooldown, wantCooldown: grokRateLimitMaxAdaptiveCooldown}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + previousReset := now.Add(-time.Second) + previousLimited := previousReset.Add(-tt.previousCooldown) + account := &Account{ + ID: 630, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + RateLimitedAt: &previousLimited, + RateLimitResetAt: &previousReset, + } + + resetAt, limited := grokRateLimitResetAtForAccount(account, snapshot, now) + + require.True(t, limited) + require.WithinDuration(t, now.Add(tt.wantCooldown), resetAt, time.Second) + }) + } +} + +func TestGrokRateLimitResetAtForAccountPreservesAuthoritativeAndQuietRecovery(t *testing.T) { + now := time.Now().UTC().Truncate(time.Second) + retryAfter := 45 + previousReset := now.Add(-grokRateLimitBackoffQuietPeriod - time.Second) + previousLimited := previousReset.Add(-grokRateLimitSustainedCooldown) + account := &Account{ + ID: 631, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + RateLimitedAt: &previousLimited, + RateLimitResetAt: &previousReset, + } + snapshot := &xai.QuotaSnapshot{ + StatusCode: http.StatusTooManyRequests, + RetryAfterSeconds: &retryAfter, + UpdatedAt: now.Format(time.RFC3339), + } + + resetAt, limited := grokRateLimitResetAtForAccount(account, snapshot, now) + require.True(t, limited) + require.WithinDuration(t, now.Add(45*time.Second), resetAt, time.Second) + + authoritativeReset := now.Add(2 * time.Hour) + remaining := int64(0) + snapshot.Requests = &xai.QuotaWindow{Remaining: &remaining, ResetUnix: grokInt64PtrForTest(authoritativeReset.Unix())} + recentReset := now.Add(-time.Second) + recentLimited := recentReset.Add(-grokRateLimitSustainedCooldown) + account.RateLimitResetAt = &recentReset + account.RateLimitedAt = &recentLimited + + resetAt, limited = grokRateLimitResetAtForAccount(account, snapshot, now) + require.True(t, limited) + require.WithinDuration(t, authoritativeReset, resetAt, time.Second) +} + +func TestGrokRateLimitResetAtForAccountLeavesAPIKey429PolicyUnchanged(t *testing.T) { + now := time.Now().UTC().Truncate(time.Second) + retryAfter := 45 + previousReset := now.Add(-time.Second) + previousLimited := previousReset.Add(-grokRateLimitSustainedCooldown) + account := &Account{ + ID: 632, + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + RateLimitedAt: &previousLimited, + RateLimitResetAt: &previousReset, + } + snapshot := &xai.QuotaSnapshot{ + StatusCode: http.StatusTooManyRequests, + RetryAfterSeconds: &retryAfter, + UpdatedAt: now.Format(time.RFC3339), + } + + resetAt, limited := grokRateLimitResetAtForAccount(account, snapshot, now) + require.True(t, limited) + require.WithinDuration(t, now.Add(45*time.Second), resetAt, time.Second) +} + func TestGrokRateLimitResetAtUsesFutureWindowAfterRetryAfterExpires(t *testing.T) { now := time.Now().UTC().Truncate(time.Second) observedAt := now.Add(-2 * time.Minute) @@ -1672,6 +1876,72 @@ func TestUpdateGrokUsageSnapshotAvailableSuccessDoesNotSetRateLimited(t *testing require.Zero(t, repo.rateLimitedCalls) } +func TestUpdateGrokUsageFromResponseHeaderlessSuccessClearsObservedCooldown(t *testing.T) { + now := time.Now().UTC().Truncate(time.Second) + limitedAt := now.Add(-grokRateLimitRepeatCooldown) + observedResetAt := now.Add(-time.Second) + account := &Account{ + ID: 660, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + RateLimitedAt: &limitedAt, + RateLimitResetAt: &observedResetAt, + } + repo := &grokQuotaAccountRepo{recoveryClearResult: true} + svc := &OpenAIGatewayService{ + accountRepo: repo, + codexSnapshotThrottle: newAccountWriteThrottle(time.Hour), + } + + svc.updateGrokUsageFromResponse(context.Background(), account, nil, http.StatusOK) + + require.Zero(t, repo.updateCalls, "headerless success must not overwrite an informative quota snapshot") + require.Equal(t, 1, repo.recoveryClearCalls) + require.Equal(t, limitedAt, repo.recoveryObservedAt) + require.Equal(t, observedResetAt, repo.recoveryObservedReset) + require.Same(t, &observedResetAt, account.RateLimitResetAt, "shared account snapshots must not be mutated in place") +} + +func TestUpdateGrokUsageFromResponseRecoveryRespectsCancellationAndAPIKeyBoundary(t *testing.T) { + now := time.Now().UTC().Truncate(time.Second) + observedResetAt := now.Add(-time.Second) + observedLimitedAt := observedResetAt.Add(-grokRateLimitRepeatCooldown) + + t.Run("parent cancellation does not mutate account state", func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + account := &Account{ + ID: 661, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + RateLimitedAt: &observedLimitedAt, + RateLimitResetAt: &observedResetAt, + } + repo := &grokQuotaAccountRepo{recoveryClearResult: true} + svc := &OpenAIGatewayService{accountRepo: repo} + + svc.updateGrokUsageFromResponse(ctx, account, nil, http.StatusOK) + + require.Zero(t, repo.recoveryClearCalls) + }) + + t.Run("API key success does not alter OAuth cooldown state", func(t *testing.T) { + account := &Account{ + ID: 662, + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + RateLimitedAt: &observedLimitedAt, + RateLimitResetAt: &observedResetAt, + } + repo := &grokQuotaAccountRepo{recoveryClearResult: true} + svc := &OpenAIGatewayService{accountRepo: repo} + + svc.updateGrokUsageFromResponse(context.Background(), account, nil, http.StatusOK) + + require.Zero(t, repo.recoveryClearCalls) + }) +} + func TestUpdateGrokUsageSnapshotExhaustedSuccessWithoutResetUsesFallback(t *testing.T) { repo := &grokQuotaAccountRepo{} svc := &OpenAIGatewayService{accountRepo: repo} @@ -1838,3 +2108,25 @@ func TestPatchGrokResponsesBody_MultipleReasoningContentNull(t *testing.T) { require.False(t, items[0].Get("content").Exists()) require.False(t, items[2].Get("content").Exists()) } + +func TestIsGrokImageGenerationModel(t *testing.T) { + t.Parallel() + + tests := []struct { + model string + want bool + }{ + {"grok-imagine", true}, + {"grok-imagine-image-quality", true}, + {"grok-imagine-edit", true}, + {"grok-imagine-image-hd", true}, + {"grok-4.5", false}, + {"grok-composer", false}, + } + for _, tt := range tests { + t.Run(tt.model, func(t *testing.T) { + require.Equal(t, tt.want, isGrokImageGenerationModel(tt.model)) + }) + } +} + diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 8cf62bdc65..f37f2997cd 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -14,7 +14,6 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/claude" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/Wei-Shaw/sub2api/internal/pkg/openai_compat" - "github.com/Wei-Shaw/sub2api/internal/pkg/xai" "github.com/Wei-Shaw/sub2api/internal/util/responseheaders" "github.com/gin-gonic/gin" "go.uber.org/zap" @@ -246,19 +245,24 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( responsesBody = updatedBody grokCacheIdentity := "" if account.Platform == PlatformGrok { - grokCacheIdentity = resolveGrokCacheIdentity(c, responsesBody, promptCacheKey, upstreamModel) - patchedBody, patchErr := patchGrokResponsesBody(responsesBody, upstreamModel) + grokIntentBody := responsesBody + grokCacheIdentity = resolveGrokCacheIdentity(c, grokIntentBody, promptCacheKey, upstreamModel) + patchedBody, patchErr := patchGrokResponsesBody(grokIntentBody, upstreamModel) if patchErr != nil { return nil, patchErr } - responsesBody, patchErr = applyGrokResponsesCacheIdentity(patchedBody, responsesBody, grokCacheIdentity, account.IsGrokOAuth()) + responsesBody, patchErr = applyGrokResponsesCacheIdentity(patchedBody, grokIntentBody, grokCacheIdentity, account.IsGrokOAuth()) if patchErr != nil { return nil, fmt.Errorf("apply grok prompt cache identity: %w", patchErr) } + responsesBody, patchErr = applyGrokFreeMessagesFunctionToolCacheRoute(responsesBody, grokIntentBody, account, grokCacheIdentity) + if patchErr != nil { + return nil, fmt.Errorf("apply grok Free function-tool cache route: %w", patchErr) + } } // 5. Get access token - token, _, err := s.GetAccessToken(ctx, account) + token, _, err := s.getRequestCredential(ctx, c, account) if err != nil { return nil, fmt.Errorf("get access token: %w", err) } @@ -273,7 +277,7 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) var upstreamReq *http.Request if account.Platform == PlatformGrok { - upstreamReq, err = buildGrokResponsesRequest(upstreamCtx, c, account, responsesBody, token, grokCacheIdentity) + upstreamReq, err = buildGrokResponsesRequest(upstreamCtx, c, account, responsesBody, token, grokCacheIdentity, s.cfg) } else { upstreamReq, err = s.buildUpstreamRequest(upstreamCtx, c, account, responsesBody, token, isStream, promptCacheKey, false) } @@ -324,6 +328,13 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( // 8. Handle error response with failover if resp.StatusCode >= 400 { respBody, upstreamMsg := s.readOpenAIUpstreamError(resp) + if !agentIdentityTaskRecoveryWasTried(ctx) && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, respBody) { + expectedTaskID := account.GetCredential("task_id") + if err := s.recoverAgentIdentityTask(ctx, account, expectedTaskID); err != nil { + return nil, fmt.Errorf("agent identity task recovery failed: %w", err) + } + return s.ForwardAsAnthropic(markAgentIdentityTaskRecoveryTried(ctx), c, account, body, promptCacheKey, defaultMappedModel) + } if previousResponseID != "" && (isOpenAICompatPreviousResponseNotFound(resp.StatusCode, upstreamMsg, respBody) || isOpenAICompatPreviousResponseUnsupported(resp.StatusCode, upstreamMsg, respBody)) { if isOpenAICompatPreviousResponseUnsupported(resp.StatusCode, upstreamMsg, respBody) { s.disableOpenAICompatSessionContinuation(ctx, c, account, promptCacheKey) @@ -344,7 +355,7 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( return s.handleAnthropicErrorResponse(resp, c, account, billingModel) } if account.Platform == PlatformGrok && account.Type == AccountTypeOAuth && !account.IsShadow() { - s.updateGrokUsageSnapshot(ctx, account, xai.ParseQuotaHeaders(resp.Header, resp.StatusCode)) + s.updateGrokUsageFromResponse(ctx, account, resp.Header, resp.StatusCode) } if account.Type == AccountTypeOAuth && promptCacheKey != "" { @@ -782,7 +793,9 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( return false } - isTerminalEvent := isOpenAICompatResponsesTerminalEvent(event.Type) + eventType := strings.TrimSpace(event.Type) + isBareErrorEvent := eventType == "error" + isTerminalEvent := isOpenAICompatResponsesTerminalEvent(eventType) || isBareErrorEvent if isTerminalEvent { if event.Response != nil { if id := strings.TrimSpace(event.Response.ID); id != "" { @@ -797,7 +810,7 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( } // cyber_policy 致命不可重试:标记供 handler 事后记录;以 Anthropic SSE error 事件 // 回写让客户端感知并停止重试(F4),丢弃后续转换输出。 - if strings.TrimSpace(event.Type) == "response.failed" { + if eventType == "response.failed" || isBareErrorEvent { payloadBytes := []byte(payload) if hit, code, msg := detectOpenAICyberPolicy(payloadBytes); hit { MarkOpsCyberPolicy(c, CyberPolicyMark{ @@ -822,7 +835,10 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( return true } message := extractOpenAISSEErrorMessage(payloadBytes) - if openAIStreamFailedEventShouldFailover(payloadBytes, message) { + // Once Anthropic output has started, switching accounts would splice + // two model streams together. Surface a proper Anthropic error event + // instead of returning a failover error that the handler cannot retry. + if !clientOutputStarted && openAIStreamFailedEventShouldFailover(payloadBytes, message) { streamFailoverErr = s.newOpenAIStreamFailoverError(c, account, false, requestID, payloadBytes, message) return true } diff --git a/backend/internal/service/openai_gateway_messages_chat_fallback.go b/backend/internal/service/openai_gateway_messages_chat_fallback.go index a1a7023be4..82eee0e853 100644 --- a/backend/internal/service/openai_gateway_messages_chat_fallback.go +++ b/backend/internal/service/openai_gateway_messages_chat_fallback.go @@ -18,16 +18,15 @@ import ( // forwardAnthropicViaRawChatCompletions serves /v1/messages clients through // an OpenAI-compatible upstream that only supports /v1/chat/completions. // -// Conversion chain: +// Conversion chain (direct, no Responses intermediary): // -// Request: Anthropic Messages → Responses (AnthropicToResponses) -// → Chat Completions (ResponsesToChatCompletionsRequest) -// Response: CC chunk → Responses events (ChatCompletionsChunkToResponsesEvents) -// → Anthropic events (ResponsesEventToAnthropicEvents) +// Request: Anthropic Messages → Chat Completions (AnthropicToChatCompletionsRequest) +// Response: CC chunk/response → Anthropic events/response (direct bridge) // // This is the /v1/messages counterpart of forwardResponsesViaRawChatCompletions -// (which serves /v1/responses clients). The same conversion bridges are reused; -// only the inbound/outbound framing differs. +// (which serves /v1/responses clients). Unlike the Responses path, the direct +// bridge skips the Responses API intermediate representation entirely — every +// streaming token runs through a single state machine instead of two. func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions( ctx context.Context, c *gin.Context, @@ -51,22 +50,16 @@ func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions( applyOpenAICompatModelNormalization(&anthropicReq) clientStream := anthropicReq.Stream - // 2. Anthropic → Responses → Chat Completions - responsesReq, err := apicompat.AnthropicToResponses(&anthropicReq) + // 2. Anthropic → Chat Completions (direct, no Responses intermediary) + chatReq, err := apicompat.AnthropicToChatCompletionsRequest(&anthropicReq) if err != nil { writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) - return nil, fmt.Errorf("convert anthropic to responses: %w", err) + return nil, fmt.Errorf("convert anthropic to chat completions: %w", err) } billingModel := resolveOpenAIForwardModel(account, anthropicReq.Model, defaultMappedModel) upstreamModel := normalizeOpenAIModelForUpstream(account, billingModel) - responsesReq.Model = upstreamModel - - chatReq, err := apicompat.ResponsesToChatCompletionsRequest(responsesReq) - if err != nil { - writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) - return nil, fmt.Errorf("convert responses to chat completions: %w", err) - } + chatReq.Model = upstreamModel chatReq.Stream = clientStream if clientStream { chatReq.StreamOptions = &apicompat.ChatStreamOptions{IncludeUsage: true} @@ -140,9 +133,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsAnthropic( if err != nil { return nil, err } - responsesResp := apicompat.ChatCompletionsResponseToResponses(ccResp, originalModel, nil, false, nil) - - anthropicResp := apicompat.ResponsesToAnthropic(responsesResp, originalModel) + anthropicResp := apicompat.ChatCompletionsResponseToAnthropic(ccResp, originalModel) if s.responseHeaderFilter != nil { responseheaders.WriteFilteredHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter) @@ -175,34 +166,29 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic( requestID := resp.Header.Get("x-request-id") writeStreamHeaders := s.newStreamHeaderWriter(c, resp.Header) - ccState := apicompat.NewChatCompletionsToResponsesStreamState(originalModel) - anthropicState := apicompat.NewResponsesEventToAnthropicState() - anthropicState.Model = originalModel + anthropicState := apicompat.NewChatCompletionsToAnthropicStreamState(originalModel) clientDisconnected := false // 与 responses 兄弟不同:客户端断开后仍继续做事件转换(喂 anthropicState), // 仅跳过写出,保证 finalize 阶段的 usage 汇总不受断开影响。 emitChunk := func(chunk *apicompat.ChatCompletionsChunk) { - // CC chunk → Responses events → Anthropic events - responsesEvents := apicompat.ChatCompletionsChunkToResponsesEvents(chunk, ccState) - for _, rEvent := range responsesEvents { - anthropicEvents := apicompat.ResponsesEventToAnthropicEvents(&rEvent, anthropicState) - if clientDisconnected { + // CC chunk → Anthropic events (direct, single state machine) + anthropicEvents := apicompat.ChatCompletionsChunkToAnthropicEvents(chunk, anthropicState) + if clientDisconnected { + return + } + for _, aEvt := range anthropicEvents { + sse, err := apicompat.ResponsesAnthropicEventToSSE(aEvt) + if err != nil { continue } - for _, aEvt := range anthropicEvents { - sse, err := apicompat.ResponsesAnthropicEventToSSE(aEvt) - if err != nil { - continue - } - writeStreamHeaders() - if _, err := fmt.Fprint(c.Writer, sse); err != nil { - clientDisconnected = true - break - } + writeStreamHeaders() + if _, err := fmt.Fprint(c.Writer, sse); err != nil { + clientDisconnected = true + break } } - if !clientDisconnected && len(responsesEvents) > 0 { + if !clientDisconnected && len(anthropicEvents) > 0 { c.Writer.Flush() } } @@ -229,17 +215,10 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic( }, fmt.Errorf("stream usage incomplete: %w", scan.Err) } - // Finalize CC→Responses stream (emit response.completed) - finalEvents := apicompat.FinalizeChatCompletionsResponsesStream(ccState) - for _, rEvent := range finalEvents { - if rEvent.Response != nil && rEvent.Response.Usage != nil { - usage = copyOpenAIUsageFromResponsesUsage(rEvent.Response.Usage) - } - if clientDisconnected { - continue - } - anthropicEvents := apicompat.ResponsesEventToAnthropicEvents(&rEvent, anthropicState) - for _, aEvt := range anthropicEvents { + // Finalize: close open blocks + emit message_delta/message_stop. + finalEvents := apicompat.FinalizeChatCompletionsAnthropicStream(anthropicState) + if !clientDisconnected { + for _, aEvt := range finalEvents { sse, err := apicompat.ResponsesAnthropicEventToSSE(aEvt) if err != nil { continue @@ -250,8 +229,6 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic( break } } - } - if !clientDisconnected { c.Writer.Flush() } if !scan.SawDone { diff --git a/backend/internal/service/openai_gateway_messages_failed_response_test.go b/backend/internal/service/openai_gateway_messages_failed_response_test.go index a03efca42d..51d5fcb7c9 100644 --- a/backend/internal/service/openai_gateway_messages_failed_response_test.go +++ b/backend/internal/service/openai_gateway_messages_failed_response_test.go @@ -77,6 +77,84 @@ func TestForwardAsAnthropic_StreamingResponseFailed_ReturnsError(t *testing.T) { require.Contains(t, err.Error(), "upstream response failed") } +func TestForwardAsAnthropic_StreamingBareErrorAfterOutputIsVisible(t *testing.T) { + gin.SetMode(gin.TestMode) + + body := []byte(`{"model":"gpt-5.4","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":true}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + ssePayload := strings.Join([]string{ + `data: {"type":"response.created","response":{"id":"resp_bare_error","object":"response","model":"gpt-5.4","status":"in_progress","output":[]}}`, + "", + `data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"partial"}`, + "", + `event: error`, + `data: {"type":"error","error":{"type":"server_error","code":"upstream_error","message":"mixed tools failed"}}`, + "", + `data: [DONE]`, + "", + }, "\n") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(ssePayload)), + }} + svc := &OpenAIGatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: upstream, + } + + account := rawChatCompletionsTestAccount() + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + + require.Error(t, err) + require.Contains(t, err.Error(), "upstream response failed: mixed tools failed") + clientStream := rec.Body.String() + require.Contains(t, clientStream, `"text":"partial"`) + require.Contains(t, clientStream, "event: error") + require.Contains(t, clientStream, "mixed tools failed") + require.NotContains(t, clientStream, "event: message_stop") + require.NotContains(t, err.Error(), "missing terminal event") +} + +func TestForwardAsAnthropic_StreamingBareErrorBeforeOutputFailsOver(t *testing.T) { + gin.SetMode(gin.TestMode) + + body := []byte(`{"model":"gpt-5.4","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":true}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + ssePayload := strings.Join([]string{ + `event: error`, + `data: {"type":"error","error":{"type":"server_error","code":"upstream_error","message":"temporary upstream failure"}}`, + "", + `data: [DONE]`, + "", + }, "\n") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(ssePayload)), + }} + svc := &OpenAIGatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: upstream, + } + + account := rawChatCompletionsTestAccount() + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + + require.Error(t, err) + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "pre-output retryable error must remain failover-safe: %T: %v", err, err) + require.Empty(t, rec.Body.String(), "failover path must not commit downstream output") +} + func TestForwardAsAnthropic_BufferedResponseFailed_Failover(t *testing.T) { gin.SetMode(gin.TestMode) diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index 0a19a9d283..bbf80c97c9 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -1,8 +1,6 @@ package service -// 本文件由 openai_gateway_service.go 纯移动拆分而来:/v1/responses 直通 -// (passthrough)转发路径及其流式/非流式响应处理与错误处理。仅做代码搬迁, -// 无任何行为变更。 +// 本文件承载 /v1/responses 透传转发及其流式、非流式响应与错误处理。 import ( "bufio" @@ -11,8 +9,10 @@ import ( "encoding/json" "errors" "fmt" + "io" "net/http" "sort" + "strconv" "strings" "time" @@ -29,7 +29,9 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( c *gin.Context, account *Account, body []byte, + canonicalImageIntentBody []byte, reqModel string, + attemptImageIntentInvalidated bool, reasoningEffort *string, reqStream bool, startTime time.Time, @@ -44,6 +46,7 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( } body = nextBody upstreamPassthroughModel = compactMappedModel + attemptImageIntentInvalidated = true } } @@ -100,7 +103,17 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( body = updatedBody apiKey := getAPIKeyFromContext(c) - if IsImageGenerationIntent(openAIResponsesEndpoint, reqModel, body) && !GroupAllowsImageGeneration(apiKeyGroup(apiKey)) { + // 同一 attempt 的最终 model/body 只判定一次,权限检查与后续图片状态设置共用该结果。 + imageIntent := resolveOpenAIPassthroughImageIntent( + c, + reqModel, + canonicalImageIntentBody, + policyModel, + body, + attemptImageIntentInvalidated, + IsImageGenerationIntent, + ) + if imageIntent && !GroupAllowsImageGeneration(apiKeyGroup(apiKey)) { MarkOpsClientBusinessLimited(c, OpsClientBusinessLimitedReasonLocalFeatureGate) c.JSON(http.StatusForbidden, gin.H{ "error": gin.H{ @@ -113,7 +126,7 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( imageBillingModel := "" imageSizeTier := "" imageInputSize := "" - if IsImageGenerationIntent(openAIResponsesEndpoint, reqModel, body) { + if imageIntent { var imageCfgErr error imageCfg, imageCfgErr := resolveOpenAIResponsesImageBillingConfigDetailedFromBody(body, reqModel) if imageCfgErr != nil { @@ -161,13 +174,6 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( return nil, err } - upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) - upstreamReq, err := s.buildUpstreamRequestOpenAIPassthrough(upstreamCtx, c, account, body, token) - releaseUpstreamCtx() - if err != nil { - return nil, err - } - proxyURL := "" if account.ProxyID != nil && account.Proxy != nil { proxyURL = account.Proxy.URL() @@ -177,26 +183,52 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( c.Set("openai_passthrough", true) } - upstreamStart := time.Now() - resp, err := s.httpUpstream.Do(upstreamReq, proxyURL, account.ID, account.Concurrency) - SetOpsLatencyMs(c, OpsUpstreamLatencyMsKey, time.Since(upstreamStart).Milliseconds()) - if err != nil { - // Transport-level failure (proxy/DNS/TCP/TLS — no HTTP response). Convert to - // a failover so the handler switches to a healthy account, and temporarily - // unschedule the account on durable faults (e.g. rejected proxy credentials). - return nil, s.handleOpenAIUpstreamTransportError(ctx, c, account, err, true) + agentTaskRecoveryTried := false + var resp *http.Response + for { + upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) + upstreamReq, buildErr := s.buildUpstreamRequestOpenAIPassthrough(upstreamCtx, c, account, body, token) + releaseUpstreamCtx() + if buildErr != nil { + return nil, buildErr + } + + upstreamStart := time.Now() + resp, err = s.httpUpstream.Do(upstreamReq, proxyURL, account.ID, account.Concurrency) + SetOpsLatencyMs(c, OpsUpstreamLatencyMsKey, time.Since(upstreamStart).Milliseconds()) + if err != nil { + // Transport-level failure (proxy/DNS/TCP/TLS — no HTTP response). Convert to + // a failover so the handler switches to a healthy account. + return nil, s.handleOpenAIUpstreamTransportError(ctx, c, account, err, true) + } + if resp.StatusCode < 400 { + break + } + + // Peek only to identify an invalid task. Restore the body so the existing + // passthrough error handling sees the same response after recovery fails. + probeBody := s.readUpstreamErrorBody(resp) + _ = resp.Body.Close() + resp.Body = io.NopCloser(bytes.NewReader(probeBody)) + if !agentTaskRecoveryTried && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, probeBody) { + agentTaskRecoveryTried = true + expectedTaskID := account.GetCredential("task_id") + if recoveryErr := s.recoverAgentIdentityTask(ctx, account, expectedTaskID); recoveryErr != nil { + return nil, fmt.Errorf("agent identity task recovery failed: %w", recoveryErr) + } + continue + } + + // 透传模式默认保持原样代理;容量错误以及 API-key 上游的瞬时 + // 5xx 应先触发多账号 failover,且此时尚未写入下游响应。 + // probeBody 已在上方任务探测时读取过一次,直接复用避免重复读取。 + if shouldFailoverOpenAIPassthroughResponse(account, resp.StatusCode, probeBody) { + return nil, s.handleFailoverErrorResponsePassthrough(ctx, resp, c, account, body, probeBody) + } + return nil, s.handleErrorResponsePassthrough(ctx, resp, c, account, body, probeBody) } defer func() { _ = resp.Body.Close() }() - if resp.StatusCode >= 400 { - // 透传模式默认保持原样代理;但 429/529 属于网关必须兜底的 - // 上游容量类错误,应先触发多账号 failover 以维持基础 SLA。 - if shouldFailoverOpenAIPassthroughResponse(resp.StatusCode) { - return nil, s.handleFailoverErrorResponsePassthrough(ctx, resp, c, account, body) - } - return nil, s.handleErrorResponsePassthrough(ctx, resp, c, account, body) - } - serviceTier := extractOpenAIServiceTierFromBody(body) var usage *OpenAIUsage @@ -338,7 +370,15 @@ func (s *OpenAIGatewayService) buildUpstreamRequestOpenAIPassthrough( req.Header.Del("authorization") req.Header.Del("x-api-key") req.Header.Del("x-goog-api-key") - req.Header.Set("authorization", "Bearer "+token) + authHeaders, err := s.buildOpenAIAuthenticationHeaders(ctx, account, token) + if err != nil { + return nil, fmt.Errorf("build openai authentication headers: %w", err) + } + for key, values := range authHeaders { + for _, value := range values { + req.Header.Add(key, value) + } + } // OAuth 透传到 ChatGPT internal API 时补齐必要头。 if account.Type == AccountTypeOAuth { @@ -417,23 +457,111 @@ func (s *OpenAIGatewayService) buildUpstreamRequestOpenAIPassthrough( return req, nil } -func shouldFailoverOpenAIPassthroughResponse(statusCode int) bool { +func shouldFailoverOpenAIPassthroughResponse(account *Account, statusCode int, responseBody []byte) bool { + if isOpenAIContextWindowError("", responseBody) { + return false + } switch statusCode { case http.StatusTooManyRequests, 529: return true + } + if account == nil || account.Type != AccountTypeAPIKey { + return false + } + switch statusCode { + case http.StatusInternalServerError, + http.StatusBadGateway, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout, + 520, 521, 522, 523, 524: + return true default: return false } } +func writeOpenAIPassthroughErrorHeaders(dst, src http.Header) { + if dst == nil { + return + } + dst.Set("Content-Type", "application/json; charset=utf-8") + dst.Set("Cache-Control", "no-store") + dst.Del("Retry-After") + if src == nil { + return + } + rawRetryAfter := strings.TrimSpace(src.Get("Retry-After")) + if validOpenAIPassthroughRetryAfter(rawRetryAfter, time.Now()) { + dst.Set("Retry-After", rawRetryAfter) + } +} + +func validOpenAIPassthroughRetryAfter(raw string, now time.Time) bool { + raw = strings.TrimSpace(raw) + if raw == "" { + return false + } + delaySeconds := true + for i := 0; i < len(raw); i++ { + if raw[i] < '0' || raw[i] > '9' { + delaySeconds = false + break + } + } + if delaySeconds { + seconds, err := strconv.ParseUint(raw, 10, 64) + return err == nil && seconds > 0 + } + parsed, err := http.ParseTime(raw) + return err == nil && parsed.After(now) +} + +func writeSanitizedOpenAIPassthroughError(c *gin.Context, upstreamStatus int, upstreamHeaders http.Header) { + downstreamStatus := upstreamStatus + message := "Upstream request failed" + switch upstreamStatus { + case http.StatusUnauthorized: + downstreamStatus = http.StatusBadGateway + message = "Upstream authentication failed" + case http.StatusForbidden: + downstreamStatus = http.StatusBadGateway + message = "Upstream access denied" + default: + if upstreamStatus >= http.StatusInternalServerError { + message = "Upstream service temporarily unavailable" + } + } + writeOpenAIPassthroughErrorEnvelope(c, downstreamStatus, upstreamHeaders, message) +} + +// writeOpenAIPassthroughErrorEnvelope 以本地 JSON 信封 + 净化后的头策略写出 +// 错误响应;message 由调用方决定(净化通用文案或脱敏后的上游消息)。 +func writeOpenAIPassthroughErrorEnvelope(c *gin.Context, downstreamStatus int, upstreamHeaders http.Header, message string) { + if c == nil { + return + } + body, _ := json.Marshal(gin.H{ + "error": gin.H{ + "type": "upstream_error", + "message": message, + }, + }) + if writeOpenAICompactSSEBridge(c, downstreamStatus, body) { + return + } + writeOpenAIPassthroughErrorHeaders(c.Writer.Header(), upstreamHeaders) + c.Data(downstreamStatus, "application/json; charset=utf-8", body) +} + func (s *OpenAIGatewayService) handleFailoverErrorResponsePassthrough( ctx context.Context, resp *http.Response, c *gin.Context, account *Account, requestBody []byte, + responseBody []byte, ) error { - body := s.readUpstreamErrorBody(resp) + body := s.redactAgentIdentitySensitiveBody(ctx, account, responseBody) upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(body)) upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg) @@ -462,9 +590,10 @@ func (s *OpenAIGatewayService) handleFailoverErrorResponsePassthrough( UpstreamResponseBody: upstreamDetail, }) return &UpstreamFailoverError{ - StatusCode: resp.StatusCode, - ResponseBody: body, - ResponseHeaders: resp.Header.Clone(), + StatusCode: resp.StatusCode, + ResponseBody: body, + ResponseHeaders: resp.Header.Clone(), + RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode), } } @@ -474,12 +603,13 @@ func (s *OpenAIGatewayService) handleErrorResponsePassthrough( c *gin.Context, account *Account, requestBody []byte, + responseBody []byte, ) error { MarkResponseCommitted(c) - body := s.readUpstreamErrorBody(resp) + body := s.redactAgentIdentitySensitiveBody(ctx, account, responseBody) - // cyber_policy:透传账号本就把原始 body 回给客户端(下方 c.Data),此处仅打标记, - // 供 handler 事后写风控/邮件。cyber 是上游网络安全策略拦截,不冷却账号, + // cyber_policy 仍按原始 body 打内部标记,供 handler 事后写风控/邮件;面向客户端的 + // 错误体在下方统一重建。cyber 是上游网络安全策略拦截,不冷却账号, // 故下方跳过 handleOpenAIAccountUpstreamError(避免自定义 temp-unschedulable 规则误冷却)。 cyberHit, cyberCode, cyberMsg := detectOpenAICyberPolicy(body) if cyberHit { @@ -503,8 +633,8 @@ func (s *OpenAIGatewayService) handleErrorResponsePassthrough( } setOpsUpstreamError(c, resp.StatusCode, upstreamMsg, upstreamDetail) logOpenAIInstructionsRequiredDebug(ctx, c, account, resp.StatusCode, upstreamMsg, requestBody, body) - // 透传模式保留原始上游错误响应,但运行态账号状态仍需更新, - // 避免粘性路由继续复用刚被限流的账号。cyber 例外:不冷却账号。 + // 错误体虽不会原样透传,运行态账号状态仍需更新,避免粘性路由继续复用 + // 刚被限流的账号。cyber 例外:不冷却账号。 if !cyberHit { reqModel, _, _ := extractOpenAIRequestMetaFromBody(requestBody) _ = s.handleOpenAIAccountUpstreamError(ctx, account, resp.StatusCode, resp.Header, body, reqModel) @@ -521,18 +651,16 @@ func (s *OpenAIGatewayService) handleErrorResponsePassthrough( Detail: upstreamDetail, UpstreamResponseBody: upstreamDetail, }) - - writeOpenAIPassthroughResponseHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter) - contentType := resp.Header.Get("Content-Type") - if contentType == "" { - contentType = "application/json" + // context-window 超限是确定性请求失败(shouldFailoverOpenAIPassthroughResponse + // 已保证不切号),其文案对客户端可操作(如触发自动压缩);在净化信封内保留 + // 脱敏后的上游消息,而不是抹成通用文案。 + if isOpenAIContextWindowError(upstreamMsg, body) && upstreamMsg != "" { + writeOpenAIPassthroughErrorEnvelope(c, resp.StatusCode, resp.Header, upstreamMsg) + } else { + writeSanitizedOpenAIPassthroughError(c, resp.StatusCode, resp.Header) } - c.Data(resp.StatusCode, contentType, body) - if upstreamMsg == "" { - return fmt.Errorf("upstream error: %d", resp.StatusCode) - } - return fmt.Errorf("upstream error: %d message=%s", resp.StatusCode, upstreamMsg) + return fmt.Errorf("upstream error: %d (client response sanitized)", resp.StatusCode) } func isOpenAIPassthroughAllowedRequestHeader(lowerKey string, allowTimeoutHeaders bool) bool { @@ -862,7 +990,18 @@ func (s *OpenAIGatewayService) handleStreamingResponsePassthrough( failedMessage := "" clientOutputStarted := false upstreamRequestID := strings.TrimSpace(resp.Header.Get("x-request-id")) + // pendingLines 在首个可见输出前保留前导事件,确保无输出失败仍可安全 failover。 pendingLines := make([]string, 0, 8) + // flushPending 表示已写入但未到 SSE 空行边界的脏状态;defer 兜底函数退出前的残留,断连后不再 Flush。 + flushPending := false + flushPendingOutput := func() { + if clientDisconnected || !flushPending { + return + } + flusher.Flush() + flushPending = false + } + defer flushPendingOutput() writePendingLines := func() bool { for _, pending := range pendingLines { if _, err := fmt.Fprintln(w, pending); err != nil { @@ -883,6 +1022,7 @@ func (s *OpenAIGatewayService) handleStreamingResponsePassthrough( scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) defer putSSEScannerBuf64K(scanBuf) + documentScanner := newOpenAISSEJSONDocumentScanner(scanner) needModelReplace := strings.TrimSpace(originalModel) != "" && strings.TrimSpace(mappedModel) != "" && strings.TrimSpace(originalModel) != strings.TrimSpace(mappedModel) resultWithUsage := func() *openaiStreamingResultPassthrough { @@ -895,8 +1035,8 @@ func (s *OpenAIGatewayService) handleStreamingResponsePassthrough( } } - for scanner.Scan() { - line := scanner.Text() + for documentScanner.Scan() { + line := documentScanner.Text() lineStartsClientOutput := false forceFlushFailedEvent := false if data, ok := extractOpenAISSEDataLine(line); ok { @@ -1012,11 +1152,14 @@ func (s *OpenAIGatewayService) handleStreamingResponsePassthrough( logger.LegacyPrintf("service.openai_gateway", "[OpenAI passthrough] Client disconnected during streaming, continue draining upstream for usage: account=%d", account.ID) } else { clientOutputStarted = true - flusher.Flush() + flushPending = true + if line == "" { + flushPendingOutput() + } } } } - if err := scanner.Err(); err != nil { + if err := documentScanner.Err(); err != nil { if sawTerminalEvent && !sawFailedEvent { return resultWithUsage(), nil } diff --git a/backend/internal/service/openai_gateway_passthrough_flush_test.go b/backend/internal/service/openai_gateway_passthrough_flush_test.go new file mode 100644 index 0000000000..b36a037806 --- /dev/null +++ b/backend/internal/service/openai_gateway_passthrough_flush_test.go @@ -0,0 +1,284 @@ +package service + +import ( + "context" + "errors" + "io" + "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/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type passthroughFlushTestWriter struct { + gin.ResponseWriter + recorder *httptest.ResponseRecorder + failAfterWrites int + successfulWrites int + failedWrites int + flushBodyLengths []int +} + +func (w *passthroughFlushTestWriter) Write(data []byte) (int, error) { + if w.failAfterWrites >= 0 && w.successfulWrites >= w.failAfterWrites { + w.failedWrites++ + return 0, errors.New("client disconnected") + } + n, err := w.ResponseWriter.Write(data) + if err == nil { + w.successfulWrites++ + } + return n, err +} + +func (w *passthroughFlushTestWriter) WriteString(data string) (int, error) { + return w.Write([]byte(data)) +} + +func (w *passthroughFlushTestWriter) Flush() { + w.ResponseWriter.Flush() + w.flushBodyLengths = append(w.flushBodyLengths, w.recorder.Body.Len()) +} + +type passthroughFlushTestErrorBody struct { + payload []byte + err error + sent bool +} + +func (r *passthroughFlushTestErrorBody) Read(p []byte) (int, error) { + if !r.sent { + r.sent = true + return copy(p, r.payload), nil + } + return 0, r.err +} + +func (r *passthroughFlushTestErrorBody) Close() error { return nil } + +func runPassthroughFlushTest( + t *testing.T, + body io.ReadCloser, + failAfterWrites int, + setups ...func(*gin.Context), +) (*openaiStreamingResultPassthrough, *httptest.ResponseRecorder, *passthroughFlushTestWriter, error) { + t.Helper() + gin.SetMode(gin.TestMode) + + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + writer := &passthroughFlushTestWriter{ + ResponseWriter: c.Writer, + recorder: recorder, + failAfterWrites: failAfterWrites, + } + c.Writer = writer + for _, setup := range setups { + setup(c) + } + + svc := &OpenAIGatewayService{cfg: &config.Config{ + Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, + }} + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: body, + } + result, err := svc.handleStreamingResponsePassthrough( + context.Background(), + resp, + c, + &Account{ID: 1, Platform: PlatformOpenAI, Name: "flush-test"}, + time.Now(), + "", + "", + ) + return result, recorder, writer, err +} + +func TestOpenAIStreamingPassthroughFlushesAtCompleteEventBoundaries(t *testing.T) { + firstEvent := "event: response.output_text.delta\n" + + "id: event-1\n" + + `data: {"type":"response.output_text.delta","delta":"hello"}` + "\n\n" + heartbeat := ": keepalive\n\n" + terminalEvent := "event: response.completed\n" + + `data: {"type":"response.completed","response":{"id":"resp_flush","usage":{"input_tokens":3,"output_tokens":2,"total_tokens":5}}}` + "\n\n" + upstream := firstEvent + heartbeat + terminalEvent + + result, recorder, writer, err := runPassthroughFlushTest(t, io.NopCloser(strings.NewReader(upstream)), -1) + + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, upstream, recorder.Body.String()) + require.Equal(t, []int{ + len(firstEvent), + len(firstEvent) + len(heartbeat), + len(upstream), + }, writer.flushBodyLengths) + require.Equal(t, 3, result.usage.InputTokens) + require.Equal(t, 2, result.usage.OutputTokens) +} + +func TestOpenAIStreamingPassthroughKeepsPreamblePendingUntilFirstOutputBoundary(t *testing.T) { + preamble := "event: response.created\n" + + `data: {"type":"response.created","response":{"id":"resp_pending"}}` + "\n\n" + + ": waiting\n\n" + firstOutput := `data: {"type":"response.output_text.delta","delta":"ready"}` + "\n\n" + terminalEvent := `data: {"type":"response.completed","response":{"id":"resp_pending","usage":{"input_tokens":4,"output_tokens":1,"total_tokens":5}}}` + "\n\n" + upstream := preamble + firstOutput + terminalEvent + + _, recorder, writer, err := runPassthroughFlushTest(t, io.NopCloser(strings.NewReader(upstream)), -1) + + require.NoError(t, err) + require.Equal(t, upstream, recorder.Body.String()) + require.Equal(t, []int{ + len(preamble) + len(firstOutput), + len(upstream), + }, writer.flushBodyLengths) +} + +func TestOpenAIStreamingPassthroughFlushesTerminalEventAtEOFWithoutBlankLine(t *testing.T) { + upstream := "event: response.completed\n" + + `data: {"type":"response.completed","response":{"id":"resp_eof","usage":{"input_tokens":5,"output_tokens":2,"total_tokens":7}}}` + wantBody := upstream + "\n" + + result, recorder, writer, err := runPassthroughFlushTest(t, io.NopCloser(strings.NewReader(upstream)), -1) + + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, wantBody, recorder.Body.String()) + require.Equal(t, []int{len(wantBody)}, writer.flushBodyLengths) + require.Equal(t, 5, result.usage.InputTokens) + require.Equal(t, 2, result.usage.OutputTokens) +} + +func TestOpenAIStreamingPassthroughFailedBeforeOutputCanStillFailOverWithoutFlush(t *testing.T) { + upstream := "event: response.created\n" + + `data: {"type":"response.created","response":{"id":"resp_failover"}}` + "\n\n" + + "event: response.failed\n" + + `data: {"type":"response.failed","error":{"code":"server_error","message":"upstream processing failed"}}` + "\n\n" + + _, recorder, writer, err := runPassthroughFlushTest(t, io.NopCloser(strings.NewReader(upstream)), -1) + + require.Error(t, err) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Empty(t, recorder.Body.String()) + require.Empty(t, writer.flushBodyLengths) +} + +func TestOpenAIStreamingPassthroughNonRetryableFailedBeforeOutputFlushesAtBoundary(t *testing.T) { + upstream := "event: response.failed\n" + + `data: {"type":"response.failed","error":{"code":"content_policy","message":"request blocked by policy"},"usage":{"input_tokens":6,"output_tokens":0,"total_tokens":6}}` + "\n\n" + + result, recorder, writer, err := runPassthroughFlushTest(t, io.NopCloser(strings.NewReader(upstream)), -1) + + require.Error(t, err) + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr)) + require.NotNil(t, result) + require.Equal(t, upstream, recorder.Body.String()) + require.Equal(t, []int{len(upstream)}, writer.flushBodyLengths) + require.Equal(t, 6, result.usage.InputTokens) + require.Zero(t, result.usage.OutputTokens) +} + +func TestOpenAIStreamingPassthroughFailedAfterOutputFlushesAtBoundaryAndKeepsUsage(t *testing.T) { + firstOutput := `data: {"type":"response.output_text.delta","delta":"partial"}` + "\n\n" + failedEvent := "event: response.failed\n" + + `data: {"type":"response.failed","error":{"code":"server_error","message":"upstream processing failed"},"usage":{"input_tokens":7,"output_tokens":2,"total_tokens":9}}` + "\n\n" + upstream := firstOutput + failedEvent + + result, recorder, writer, err := runPassthroughFlushTest(t, io.NopCloser(strings.NewReader(upstream)), -1) + + require.Error(t, err) + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr)) + require.NotNil(t, result) + require.Equal(t, upstream, recorder.Body.String()) + require.Equal(t, []int{len(firstOutput), len(upstream)}, writer.flushBodyLengths) + require.Equal(t, 7, result.usage.InputTokens) + require.Equal(t, 2, result.usage.OutputTokens) +} + +func TestOpenAIStreamingPassthroughClientDisconnectStillDrainsTerminalUsage(t *testing.T) { + firstOutput := `data: {"type":"response.output_text.delta","delta":"partial"}` + "\n\n" + terminalEvent := `data: {"type":"response.completed","response":{"id":"resp_drain","usage":{"input_tokens":11,"output_tokens":4,"total_tokens":15}}}` + "\n\n" + + result, recorder, writer, err := runPassthroughFlushTest( + t, + io.NopCloser(strings.NewReader(firstOutput+terminalEvent)), + 2, + ) + + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, firstOutput, recorder.Body.String()) + require.Equal(t, []int{len(firstOutput)}, writer.flushBodyLengths) + require.Equal(t, 1, writer.failedWrites) + require.Equal(t, 11, result.usage.InputTokens) + require.Equal(t, 4, result.usage.OutputTokens) +} + +func TestOpenAIStreamingPassthroughScannerErrorFlushesWrittenResidual(t *testing.T) { + upstream := []byte(`data: {"type":"response.output_text.delta","delta":"partial"}`) + readErr := errors.New("upstream read failed") + + _, recorder, writer, err := runPassthroughFlushTest(t, &passthroughFlushTestErrorBody{ + payload: upstream, + err: readErr, + }, -1) + + require.ErrorIs(t, err, readErr) + wantBody := string(upstream) + "\n" + require.Equal(t, wantBody, recorder.Body.String()) + require.Equal(t, []int{len(wantBody)}, writer.flushBodyLengths) +} + +func TestOpenAIStreamingPassthroughNamespaceRestoreErrorFlushesWrittenResidualOnce(t *testing.T) { + writtenPrefix := `data: {"type":"response.output_text.delta","delta":"prefix"}` + "\n" + overflowData := `data: {"type":"response.output_text.delta","delta":"not-written","overflow":1e1000}` + + _, recorder, writer, err := runPassthroughFlushTest( + t, + io.NopCloser(strings.NewReader(writtenPrefix+overflowData)), + -1, + func(c *gin.Context) { + setOpenAIResponsesNamespaceNames(c, map[string]apicompat.ResponsesNamespaceName{ + "collaboration__spawn_agent": {Namespace: "collaboration", Name: "spawn_agent"}, + }) + }, + ) + + require.ErrorContains(t, err, "restore OpenAI passthrough namespace response") + require.Equal(t, writtenPrefix, recorder.Body.String()) + require.Equal(t, []int{len(writtenPrefix)}, writer.flushBodyLengths) +} + +func TestOpenAIStreamingPassthroughBlankWriteFailureDoesNotFlushAndStillDrainsUsage(t *testing.T) { + writtenDataLine := `data: {"type":"response.output_text.delta","delta":"partial"}` + "\n" + terminalEvent := `data: {"type":"response.completed","response":{"id":"resp_blank_failure","usage":{"input_tokens":13,"output_tokens":5,"total_tokens":18}}}` + "\n\n" + + result, recorder, writer, err := runPassthroughFlushTest( + t, + io.NopCloser(strings.NewReader(writtenDataLine+"\n"+terminalEvent)), + 1, + ) + + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, writtenDataLine, recorder.Body.String()) + require.Empty(t, writer.flushBodyLengths) + require.Equal(t, 1, writer.successfulWrites) + require.Equal(t, 1, writer.failedWrites) + require.Equal(t, 13, result.usage.InputTokens) + require.Equal(t, 5, result.usage.OutputTokens) +} diff --git a/backend/internal/service/openai_gateway_passthrough_image_intent_benchmark_test.go b/backend/internal/service/openai_gateway_passthrough_image_intent_benchmark_test.go new file mode 100644 index 0000000000..9335a4e435 --- /dev/null +++ b/backend/internal/service/openai_gateway_passthrough_image_intent_benchmark_test.go @@ -0,0 +1,27 @@ +package service + +import "testing" + +var passthroughImageIntentBenchmarkSink bool + +func BenchmarkOpenAIPassthroughImageIntentReuse_LargeBody(b *testing.B) { + body := buildLargeOpenAIResponsesImageToolBody(32 << 20) + + b.Run("Once", func(b *testing.B) { + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for i := 0; i < b.N; i++ { + passthroughImageIntentBenchmarkSink = IsImageGenerationIntent(openAIResponsesEndpoint, "gpt-5.4", body) + } + }) + + b.Run("Twice", func(b *testing.B) { + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for i := 0; i < b.N; i++ { + permissionIntent := IsImageGenerationIntent(openAIResponsesEndpoint, "gpt-5.4", body) + billingIntent := IsImageGenerationIntent(openAIResponsesEndpoint, "gpt-5.4", body) + passthroughImageIntentBenchmarkSink = permissionIntent && billingIntent + } + }) +} diff --git a/backend/internal/service/openai_gateway_passthrough_image_intent_test.go b/backend/internal/service/openai_gateway_passthrough_image_intent_test.go new file mode 100644 index 0000000000..1720ef6e13 --- /dev/null +++ b/backend/internal/service/openai_gateway_passthrough_image_intent_test.go @@ -0,0 +1,59 @@ +package service + +import ( + "context" + "io" + "net/http" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestOpenAIGatewayService_APIKeyPassthrough_ImageIntentPreservesGateAndBilling(t *testing.T) { + gin.SetMode(gin.TestMode) + body := []byte(`{"model":"gpt-5.4","stream":false,"tools":[{"type":"image_generation","model":"gpt-image-2","size":"2048x1152"}],"input":"draw"}`) + + t.Run("disabled group rejects before upstream", func(t *testing.T) { + upstream := &httpUpstreamRecorder{} + svc := newOpenAIImageGenerationControlTestService(upstream) + c, recorder := newOpenAIImageGenerationControlTestContext(false, "curl/8.0") + account := newOpenAIImageGenerationControlTestAccount() + account.Extra = map[string]any{"openai_passthrough": true} + + result, err := svc.Forward(context.Background(), c, account, body) + + require.Error(t, err) + require.Nil(t, result) + require.Equal(t, http.StatusForbidden, recorder.Code) + require.Equal(t, "permission_error", gjson.GetBytes(recorder.Body.Bytes(), "error.type").String()) + require.Nil(t, upstream.lastReq) + }) + + t.Run("allowed group keeps image billing", func(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader( + `{"output":[{"id":"ig_1","type":"image_generation_call","result":"final-image","size":"2048x1152"}],"usage":{"input_tokens":1,"output_tokens":2}}`, + )), + }} + svc := newOpenAIImageGenerationControlTestService(upstream) + c, _ := newOpenAIImageGenerationControlTestContext(true, "curl/8.0") + account := newOpenAIImageGenerationControlTestAccount() + account.Extra = map[string]any{"openai_passthrough": true} + + result, err := svc.Forward(context.Background(), c, account, body) + + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, upstream.lastReq) + require.Equal(t, body, upstream.lastBody) + require.Equal(t, 1, result.ImageCount) + require.Equal(t, "gpt-image-2", result.BillingModel) + require.Equal(t, "2K", result.ImageSize) + require.Equal(t, "2048x1152", result.ImageInputSize) + }) +} diff --git a/backend/internal/service/openai_gateway_response_flush_test.go b/backend/internal/service/openai_gateway_response_flush_test.go new file mode 100644 index 0000000000..3494824d6c --- /dev/null +++ b/backend/internal/service/openai_gateway_response_flush_test.go @@ -0,0 +1,473 @@ +package service + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type openAIResponseFlushRecorder struct { + header http.Header + mu sync.Mutex + body bytes.Buffer + status int + writes int + failAfterWrites int + flushSnapshots []string + flushEvents chan int + blockFlush int + flushBlocked chan struct{} + releaseFlush <-chan struct{} +} + +func newOpenAIResponseFlushRecorder() *openAIResponseFlushRecorder { + return &openAIResponseFlushRecorder{ + header: make(http.Header), + failAfterWrites: -1, + flushEvents: make(chan int, 16), + } +} + +func (w *openAIResponseFlushRecorder) Header() http.Header { + return w.header +} + +func (w *openAIResponseFlushRecorder) WriteHeader(statusCode int) { + w.mu.Lock() + defer w.mu.Unlock() + if w.status == 0 { + w.status = statusCode + } +} + +func (w *openAIResponseFlushRecorder) Write(data []byte) (int, error) { + w.mu.Lock() + defer w.mu.Unlock() + if w.failAfterWrites >= 0 && w.writes >= w.failAfterWrites { + return 0, errors.New("client disconnected") + } + w.writes++ + if w.status == 0 { + w.status = http.StatusOK + } + return w.body.Write(data) +} + +func (w *openAIResponseFlushRecorder) Flush() { + w.mu.Lock() + w.flushSnapshots = append(w.flushSnapshots, w.body.String()) + count := len(w.flushSnapshots) + w.mu.Unlock() + w.flushEvents <- count + if count == w.blockFlush { + close(w.flushBlocked) + <-w.releaseFlush + } +} + +func (w *openAIResponseFlushRecorder) snapshot() (string, []string) { + w.mu.Lock() + defer w.mu.Unlock() + return w.body.String(), append([]string(nil), w.flushSnapshots...) +} + +type stagedOpenAISSEReadCloser struct { + segments [][]byte + gates []<-chan struct{} + waiting []chan struct{} + eofReached chan struct{} + current []byte + index int +} + +func (r *stagedOpenAISSEReadCloser) Read(data []byte) (int, error) { + if len(r.current) == 0 { + if r.index >= len(r.segments) { + if r.eofReached != nil { + close(r.eofReached) + r.eofReached = nil + } + return 0, io.EOF + } + index := r.index + r.index++ + if index < len(r.waiting) && r.waiting[index] != nil { + close(r.waiting[index]) + } + if index < len(r.gates) && r.gates[index] != nil { + <-r.gates[index] + } + r.current = r.segments[index] + } + n := copy(data, r.current) + r.current = r.current[n:] + return n, nil +} + +func (r *stagedOpenAISSEReadCloser) Close() error { return nil } + +type openAIResponseFlushReadError struct { + payload []byte + err error + sent bool +} + +func (r *openAIResponseFlushReadError) Read(data []byte) (int, error) { + if !r.sent { + r.sent = true + return copy(data, r.payload), nil + } + if r.err != nil { + return 0, r.err + } + return 0, io.ErrUnexpectedEOF +} + +func (r *openAIResponseFlushReadError) Close() error { return nil } + +func TestOpenAIResponseFlush_SlowEventsFlushOnceAtBoundaries(t *testing.T) { + events := []string{ + `data: {"type":"response.output_text.delta","delta":"a"}`, + `data: {"type":"response.output_text.delta","delta":"b"}`, + `data: {"type":"response.output_text.delta","delta":"c"}`, + `data: [DONE]`, + } + body := strings.Join(events, "\n\n") + "\n\n" + recorder := newOpenAIResponseFlushRecorder() + + result, err := runOpenAIResponseFlushTest(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}) + + require.NoError(t, err) + require.NotNil(t, result) + gotBody, flushes := recorder.snapshot() + require.Equal(t, body, gotBody) + require.Len(t, flushes, len(events)) + for _, flushed := range flushes { + require.True(t, strings.HasSuffix(flushed, "\n\n"), "flush must occur after a complete SSE event") + } +} + +func TestOpenAIResponseFlush_DataQueuedButBlankDrainsFlushesOnce(t *testing.T) { + first := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"first\"}\n\n" + second := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"second\"}\n\n" + terminal := "data: [DONE]\n\n" + allowSecond := make(chan struct{}) + allowTerminal := make(chan struct{}) + terminalWaiting := make(chan struct{}) + reader := &stagedOpenAISSEReadCloser{ + segments: [][]byte{[]byte(first), []byte(second), []byte(terminal)}, + gates: []<-chan struct{}{nil, allowSecond, allowTerminal}, + waiting: []chan struct{}{nil, nil, terminalWaiting}, + } + releaseFirstFlush := make(chan struct{}) + recorder := newOpenAIResponseFlushRecorder() + recorder.blockFlush = 1 + recorder.flushBlocked = make(chan struct{}) + recorder.releaseFlush = releaseFirstFlush + resultCh, errCh := runOpenAIResponseFlushTestAsync(recorder, reader, config.GatewayConfig{StreamDataIntervalTimeout: 30}) + + waitOpenAIResponseFlushSignal(t, recorder.flushBlocked) + close(allowSecond) + waitOpenAIResponseFlushSignal(t, terminalWaiting) + close(releaseFirstFlush) + waitOpenAIResponseFlushCount(t, recorder, 2) + close(allowTerminal) + + require.NoError(t, <-errCh) + require.NotNil(t, <-resultCh) + gotBody, flushes := recorder.snapshot() + require.Equal(t, first+second+terminal, gotBody) + require.Len(t, flushes, 3) + require.Equal(t, first, flushes[0]) + require.Equal(t, first+second, flushes[1], "blank line that drains the queue must flush the complete event exactly once") +} + +func TestOpenAIResponseFlush_BurstDoesNotIncreaseFlushes(t *testing.T) { + first := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"first\"}\n\n" + burst := strings.Join([]string{ + `data: {"type":"response.output_text.delta","delta":"second"}`, + `data: {"type":"response.output_text.delta","delta":"third"}`, + `data: [DONE]`, + }, "\n\n") + "\n\n" + allowBurst := make(chan struct{}) + eofReached := make(chan struct{}) + reader := &stagedOpenAISSEReadCloser{ + segments: [][]byte{[]byte(first), []byte(burst)}, + gates: []<-chan struct{}{nil, allowBurst}, + eofReached: eofReached, + } + releaseFirstFlush := make(chan struct{}) + recorder := newOpenAIResponseFlushRecorder() + recorder.blockFlush = 1 + recorder.flushBlocked = make(chan struct{}) + recorder.releaseFlush = releaseFirstFlush + resultCh, errCh := runOpenAIResponseFlushTestAsync(recorder, reader, config.GatewayConfig{StreamDataIntervalTimeout: 30}) + + waitOpenAIResponseFlushSignal(t, recorder.flushBlocked) + close(allowBurst) + waitOpenAIResponseFlushSignal(t, eofReached) + close(releaseFirstFlush) + + require.NoError(t, <-errCh) + require.NotNil(t, <-resultCh) + gotBody, flushes := recorder.snapshot() + require.Equal(t, first+burst, gotBody) + require.Len(t, flushes, 2, "queued burst must remain batched until its drained event boundary") + require.Equal(t, first, flushes[0]) + require.Equal(t, first+burst, flushes[1]) +} + +func TestOpenAIResponseFlush_CommentAndEOFOnlyFlushCompleteResidual(t *testing.T) { + body := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"a\"}\n\n" + + ": upstream-comment\n\n" + + "data: [DONE]\n" + recorder := newOpenAIResponseFlushRecorder() + + result, err := runOpenAIResponseFlushTest(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}) + + require.NoError(t, err) + require.NotNil(t, result) + gotBody, flushes := recorder.snapshot() + require.Equal(t, body, gotBody) + require.Len(t, flushes, 3) + require.True(t, strings.HasSuffix(flushes[0], "\n\n")) + require.True(t, strings.HasSuffix(flushes[1], "\n\n")) + require.True(t, strings.HasSuffix(flushes[2], "data: [DONE]\n"), "EOF must flush only the remaining bytes") +} + +func TestOpenAIResponseFlush_TerminalReadErrorFlushesResidual(t *testing.T) { + body := "data: [DONE]\n" + recorder := newOpenAIResponseFlushRecorder() + + result, err := runOpenAIResponseFlushTest(recorder, &openAIResponseFlushReadError{payload: []byte(body)}, config.GatewayConfig{}) + + require.NoError(t, err) + require.NotNil(t, result) + gotBody, flushes := recorder.snapshot() + require.Equal(t, body, gotBody) + require.Equal(t, []string{body}, flushes) +} + +func TestOpenAIResponseFlush_OutputWithoutTerminalFlushesResidualWithoutFailover(t *testing.T) { + body := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"partial\"}\n" + recorder := newOpenAIResponseFlushRecorder() + + result, err := runOpenAIResponseFlushTest(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}) + + require.ErrorContains(t, err, "missing terminal event") + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr)) + require.NotNil(t, result) + gotBody, flushes := recorder.snapshot() + require.Equal(t, body, gotBody) + require.Equal(t, []string{body}, flushes) +} + +func TestOpenAIResponseFlush_PreambleWithoutTerminalRemainsBufferedForFailover(t *testing.T) { + body := "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_1\"}}\n" + recorder := newOpenAIResponseFlushRecorder() + + result, err := runOpenAIResponseFlushTest(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.NotNil(t, result) + gotBody, flushes := recorder.snapshot() + require.Empty(t, gotBody) + require.Empty(t, flushes) +} + +func TestOpenAIResponseFlush_CanceledAfterOutputFlushesResidualWithoutErrorEvent(t *testing.T) { + body := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"partial\"}\n" + recorder := newOpenAIResponseFlushRecorder() + + result, err := runOpenAIResponseFlushTest(recorder, &openAIResponseFlushReadError{payload: []byte(body), err: context.Canceled}, config.GatewayConfig{}) + + require.ErrorIs(t, err, context.Canceled) + require.NotNil(t, result) + gotBody, flushes := recorder.snapshot() + require.Equal(t, body, gotBody) + require.Equal(t, []string{body}, flushes) + require.NotContains(t, gotBody, "stream_read_error") +} + +func TestOpenAIResponseFlush_KeepaliveFlushesImmediately(t *testing.T) { + recorder := newOpenAIResponseFlushRecorder() + reader, writer := io.Pipe() + resultCh, errCh := runOpenAIResponseFlushTestAsync(recorder, reader, config.GatewayConfig{StreamKeepaliveInterval: 1}) + + waitOpenAIResponseFlushCount(t, recorder, 1) + _, flushes := recorder.snapshot() + require.Equal(t, ":\n\n", flushes[0]) + _, err := writer.Write([]byte("data: [DONE]\n\n")) + require.NoError(t, err) + require.NoError(t, writer.Close()) + + require.NoError(t, <-errCh) + require.NotNil(t, <-resultCh) + gotBody, flushes := recorder.snapshot() + require.Equal(t, ":\n\ndata: [DONE]\n\n", gotBody) + require.Len(t, flushes, 2) +} + +func TestOpenAIResponseFlush_KeepaliveDoesNotSplitOpenEvent(t *testing.T) { + const dataLine = `data: {"type":"response.output_text.delta","delta":"a"}` + // Filling the 16-slot scan queue proves the main loop processed data before the reader reaches the gated blank. + dataLines := make([]string, 17) + for i := range dataLines { + dataLines[i] = dataLine + } + partialEvent := strings.Join(dataLines, "\n") + "\n" + completeEvent := partialEvent + "\n" + terminal := "data: [DONE]\n\n" + allowBlank := make(chan struct{}) + allowTerminal := make(chan struct{}) + blankWaiting := make(chan struct{}) + terminalWaiting := make(chan struct{}) + reader := &stagedOpenAISSEReadCloser{ + segments: [][]byte{[]byte(partialEvent), []byte("\n"), []byte(terminal)}, + gates: []<-chan struct{}{nil, allowBlank, allowTerminal}, + waiting: []chan struct{}{nil, blankWaiting, terminalWaiting}, + } + recorder := newOpenAIResponseFlushRecorder() + resultCh, errCh := runOpenAIResponseFlushTestAsync(recorder, reader, config.GatewayConfig{StreamKeepaliveInterval: 1}) + + waitOpenAIResponseFlushSignal(t, blankWaiting) + timer := time.NewTimer(1250 * time.Millisecond) + select { + case count := <-recorder.flushEvents: + timer.Stop() + t.Fatalf("keepalive flushed open event before its blank boundary: flush %d", count) + case <-timer.C: + } + + close(allowBlank) + waitOpenAIResponseFlushSignal(t, terminalWaiting) + waitOpenAIResponseFlushCount(t, recorder, 1) + gotBody, flushes := recorder.snapshot() + require.Equal(t, completeEvent, gotBody) + require.Equal(t, []string{completeEvent}, flushes) + + close(allowTerminal) + require.NoError(t, <-errCh) + require.NotNil(t, <-resultCh) + gotBody, flushes = recorder.snapshot() + require.Equal(t, completeEvent+terminal, gotBody) + require.Len(t, flushes, 2) + require.Equal(t, completeEvent+terminal, flushes[1]) +} + +func TestOpenAIResponseFlush_FailedAndErrorEventsFlushAtBoundaries(t *testing.T) { + t.Run("failed at EOF", func(t *testing.T) { + body := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"a\"}\n\n" + + "data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"code\":\"safety_error\",\"message\":\"blocked\"},\"usage\":{\"input_tokens\":3,\"output_tokens\":1}}}\n" + recorder := newOpenAIResponseFlushRecorder() + + result, err := runOpenAIResponseFlushTest(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}) + + require.Error(t, err) + require.NotNil(t, result) + require.Equal(t, 3, result.usage.InputTokens) + gotBody, flushes := recorder.snapshot() + expectedBody := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"a\"}\n\n" + + "data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"code\":\"safety_error\",\"message\":\"blocked\"}}}\n" + require.Equal(t, expectedBody, gotBody) + require.Len(t, flushes, 2) + require.Contains(t, flushes[1], "response.failed") + }) + + t.Run("error event", func(t *testing.T) { + body := "data: {\"type\":\"error\",\"error\":{\"message\":\"failed\"}}\n\n" + + "data: [DONE]\n\n" + recorder := newOpenAIResponseFlushRecorder() + + result, err := runOpenAIResponseFlushTest(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}) + + require.NoError(t, err) + require.NotNil(t, result) + gotBody, flushes := recorder.snapshot() + require.Equal(t, body, gotBody) + require.Len(t, flushes, 2) + }) +} + +func TestOpenAIResponseFlush_ClientDisconnectStillDrainsUsage(t *testing.T) { + first := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"a\"}\n\n" + terminal := "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":7,\"output_tokens\":5,\"input_tokens_details\":{\"cached_tokens\":2}}}}\n\n" + recorder := newOpenAIResponseFlushRecorder() + recorder.failAfterWrites = 1 + + result, err := runOpenAIResponseFlushTest(recorder, io.NopCloser(strings.NewReader(first+terminal)), config.GatewayConfig{}) + + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, 7, result.usage.InputTokens) + require.Equal(t, 5, result.usage.OutputTokens) + require.Equal(t, 2, result.usage.CacheReadInputTokens) + gotBody, flushes := recorder.snapshot() + require.Equal(t, first, gotBody) + require.Len(t, flushes, 1) +} + +func runOpenAIResponseFlushTest(recorder *openAIResponseFlushRecorder, body io.ReadCloser, gatewayCfg config.GatewayConfig) (*openaiStreamingResult, error) { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + svc := &OpenAIGatewayService{ + cfg: &config.Config{Gateway: gatewayCfg}, + toolCorrector: NewCodexToolCorrector(), + } + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: body, + } + return svc.handleStreamingResponse(context.Background(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "gpt-5", "gpt-5") +} + +func runOpenAIResponseFlushTestAsync(recorder *openAIResponseFlushRecorder, body io.ReadCloser, gatewayCfg config.GatewayConfig) (<-chan *openaiStreamingResult, <-chan error) { + resultCh := make(chan *openaiStreamingResult, 1) + errCh := make(chan error, 1) + go func() { + result, err := runOpenAIResponseFlushTest(recorder, body, gatewayCfg) + resultCh <- result + errCh <- err + }() + return resultCh, errCh +} + +func waitOpenAIResponseFlushCount(t *testing.T, recorder *openAIResponseFlushRecorder, want int) { + t.Helper() + timer := time.NewTimer(3 * time.Second) + defer timer.Stop() + for { + select { + case count := <-recorder.flushEvents: + if count >= want { + return + } + case <-timer.C: + t.Fatalf("timed out waiting for flush %d", want) + } + } +} + +func waitOpenAIResponseFlushSignal(t *testing.T, signal <-chan struct{}) { + t.Helper() + select { + case <-signal: + case <-time.After(3 * time.Second): + t.Fatal("timed out waiting for stream signal") + } +} diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index 1d70245eb0..436e431163 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -39,7 +39,23 @@ type openaiNonStreamingResult struct { } func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp *http.Response, c *gin.Context, account *Account, startTime time.Time, originalModel, mappedModel string) (*openaiStreamingResult, error) { - if s.responseHeaderFilter != nil { + return s.handleStreamingResponseWithReasoning(ctx, resp, c, account, startTime, originalModel, mappedModel, "") +} + +func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context.Context, resp *http.Response, c *gin.Context, account *Account, startTime time.Time, originalModel, mappedModel, reasoningEffort string) (*openaiStreamingResult, error) { + firstOutputTimeout := time.Duration(0) + if account != nil && account.Platform == PlatformOpenAI { + firstOutputTimeout = s.openAIFirstOutputTimeout(reasoningEffort) + } + guardFirstOutput := firstOutputTimeout > 0 + var attemptResponseHeaders http.Header + if guardFirstOutput { + if s.responseHeaderFilter != nil { + attemptResponseHeaders = responseheaders.FilterHeaders(resp.Header, s.responseHeaderFilter) + } else if requestID := strings.TrimSpace(resp.Header.Get("x-request-id")); requestID != "" { + attemptResponseHeaders = http.Header{"X-Request-Id": []string{requestID}} + } + } else if s.responseHeaderFilter != nil { responseheaders.WriteFilteredHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter) } @@ -50,19 +66,68 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp c.Header("X-Accel-Buffering", "no") // Pass through other headers - if v := resp.Header.Get("x-request-id"); v != "" { + if !guardFirstOutput && resp.Header.Get("x-request-id") != "" { + v := resp.Header.Get("x-request-id") c.Header("x-request-id", v) } + applyAttemptResponseHeaders := func() { + if !guardFirstOutput || len(attemptResponseHeaders) == 0 || c.Writer.Written() { + return + } + for key, values := range attemptResponseHeaders { + for _, value := range values { + c.Writer.Header().Add(key, value) + } + } + // These headers describe this gateway's SSE stream and are stable across + // account attempts. Keep them authoritative over upstream values. + c.Header("Content-Type", "text/event-stream") + c.Header("Cache-Control", "no-cache") + c.Header("Connection", "keep-alive") + c.Header("X-Accel-Buffering", "no") + } w := c.Writer flusher, ok := w.(http.Flusher) if !ok { return nil, errors.New("streaming not supported") } + maxLineSize := defaultMaxLineSize + if s.cfg != nil && s.cfg.Gateway.MaxLineSize > 0 { + maxLineSize = s.cfg.Gateway.MaxLineSize + } + var firstTokenMs *int bufferedWriter := bufio.NewWriterSize(w, 4*1024) + var firstOutputStage *openAIFirstOutputStage + if guardFirstOutput { + firstOutputStage = newDefaultOpenAIFirstOutputStage() + defer func() { + if err := firstOutputStage.Close(); err != nil { + logger.LegacyPrintf("service.openai_gateway", "OpenAI first-output staging cleanup failed: account=%d model=%s error=%v", account.ID, originalModel, err) + } + }() + } + writePendingString := func(value string) (int, error) { + if firstOutputStage != nil && firstTokenMs == nil && !firstOutputStage.closed { + return firstOutputStage.WriteString(value) + } + return bufferedWriter.WriteString(value) + } + pendingBytes := func() int64 { + if firstOutputStage != nil && firstTokenMs == nil && !firstOutputStage.closed { + return firstOutputStage.Buffered() + } + return int64(bufferedWriter.Buffered()) + } flushBuffered := func() error { - if err := bufferedWriter.Flush(); err != nil { - return err + if firstOutputStage != nil && firstTokenMs == nil && !firstOutputStage.closed { + if err := firstOutputStage.CommitTo(w); err != nil { + return err + } + } else { + if err := bufferedWriter.Flush(); err != nil { + return err + } } flusher.Flush() return nil @@ -70,15 +135,16 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp usage := &OpenAIUsage{} imageCounter := newOpenAIImageOutputCounter() - var firstTokenMs *int responseID := "" + var firstOutputScanGuard atomic.Bool + firstOutputScanGuard.Store(guardFirstOutput) scanner := bufio.NewScanner(resp.Body) - maxLineSize := defaultMaxLineSize - if s.cfg != nil && s.cfg.Gateway.MaxLineSize > 0 { - maxLineSize = s.cfg.Gateway.MaxLineSize - } scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + if guardFirstOutput { + scanner.Split(openAIFirstOutputDynamicScanLines(&firstOutputScanGuard)) + } + documentScanner := newOpenAISSEJSONDocumentScanner(scanner) streamInterval := time.Duration(0) if s.cfg != nil && s.cfg.Gateway.StreamDataIntervalTimeout > 0 { @@ -109,6 +175,31 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp if keepaliveTicker != nil { keepaliveCh = keepaliveTicker.C } + + var firstOutputTimer *time.Timer + var firstOutputCh <-chan time.Time + if firstOutputTimeout > 0 { + remaining := time.Until(startTime.Add(firstOutputTimeout)) + if remaining <= 0 { + remaining = time.Nanosecond + } + firstOutputTimer = time.NewTimer(remaining) + firstOutputCh = firstOutputTimer.C + defer firstOutputTimer.Stop() + } + stopFirstOutputTimer := func() { + if firstOutputTimer == nil { + return + } + if !firstOutputTimer.Stop() { + select { + case <-firstOutputTimer.C: + default: + } + } + firstOutputTimer = nil + firstOutputCh = nil + } // Track downstream writes separately from upstream reads: pre-output failover // can buffer response.created / response.in_progress, so keepalive must be // based on downstream idle time. @@ -125,6 +216,52 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp clientOutputStarted := false upstreamRequestID := strings.TrimSpace(resp.Header.Get("x-request-id")) var streamEarlyErr error + eventInProgress := false + eventStartsClientOutput := false + eventShouldFlush := false + handlePendingWriteError := func(err error) { + if firstOutputStage != nil && firstTokenMs == nil && !firstOutputStage.closed { + message := "OpenAI first-output staging failed" + if errors.Is(err, errOpenAIFirstOutputStageLimit) { + message = "OpenAI first-output staging limit exceeded" + } + logger.LegacyPrintf("service.openai_gateway", "%s: account=%d model=%s error=%v", message, account.ID, originalModel, err) + failoverErr := s.newOpenAIStreamFailoverError(c, account, false, upstreamRequestID, nil, message) + failoverErr.SafeToFailoverAfterWrite = true + streamEarlyErr = failoverErr + _ = resp.Body.Close() + return + } + clientDisconnected = true + logger.LegacyPrintf("service.openai_gateway", "Client disconnected during streaming, continuing to drain upstream for billing") + } + completeGuardedEvent := func(queueDrained bool) { + completedSemanticEvent := eventStartsClientOutput + shouldFlush := eventShouldFlush || (queueDrained && clientOutputStarted) + eventInProgress = false + if !clientDisconnected { + if completedSemanticEvent { + applyAttemptResponseHeaders() + } + if shouldFlush { + if err := flushBuffered(); err != nil { + clientDisconnected = true + logger.LegacyPrintf("service.openai_gateway", "Client disconnected during streaming flush, continuing to drain upstream for billing") + } else { + clientOutputStarted = true + lastDownstreamWriteAt = time.Now() + } + } + } + if completedSemanticEvent && firstTokenMs == nil { + firstOutputScanGuard.Store(false) + ms := int(time.Since(startTime).Milliseconds()) + firstTokenMs = &ms + stopFirstOutputTimer() + } + eventStartsClientOutput = false + eventShouldFlush = false + } sendErrorEvent := func(reason string) { if errorEventSent || clientDisconnected { return @@ -135,7 +272,7 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp clientDisconnected = true return } - if _, err := bufferedWriter.WriteString("data: " + payload + "\n\n"); err != nil { + if _, err := writePendingString("data: " + payload + "\n\n"); err != nil { clientDisconnected = true return } @@ -160,49 +297,77 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp imageOutputSizes: imageCounter.Sizes(), } } + flushPending := func(disconnectMessage string) { + if clientDisconnected || pendingBytes() == 0 { + return + } + if err := flushBuffered(); err != nil { + clientDisconnected = true + logger.LegacyPrintf("service.openai_gateway", "%s", disconnectMessage) + return + } + clientOutputStarted = true + lastDownstreamWriteAt = time.Now() + } finalizeStream := func() (*openaiStreamingResult, error) { + if guardFirstOutput && eventInProgress { + // EOF dispatches the final SSE event even without a trailing blank line. + completeGuardedEvent(true) + } + if !sawTerminalEvent && !openAIStreamClientOutputStarted(c, clientOutputStarted) && !eventShouldFlush { + return resultWithUsage(), s.newOpenAIStreamFailoverError( + c, + account, + false, + upstreamRequestID, + nil, + "OpenAI stream ended before a terminal event", + ) + } + flushPending("Client disconnected during final flush, returning collected usage") if !sawTerminalEvent { - if !openAIStreamClientOutputStarted(c, clientOutputStarted) { - return resultWithUsage(), s.newOpenAIStreamFailoverError( - c, - account, - false, - upstreamRequestID, - nil, - "OpenAI stream ended before a terminal event", - ) - } return resultWithUsage(), fmt.Errorf("stream usage incomplete: missing terminal event") } if sawFailedEvent { return resultWithUsage(), fmt.Errorf("upstream response failed: %s", failedMessage) } - if !clientDisconnected { - hadBufferedData := bufferedWriter.Buffered() > 0 - if err := flushBuffered(); err != nil { - clientDisconnected = true - logger.LegacyPrintf("service.openai_gateway", "Client disconnected during final flush, returning collected usage") - } else if hadBufferedData { - clientOutputStarted = true - lastDownstreamWriteAt = time.Now() - } - } return resultWithUsage(), nil } handleScanErr := func(scanErr error) (*openaiStreamingResult, error, bool) { if scanErr == nil { return nil, nil, false } - if sawTerminalEvent && !sawFailedEvent { - logger.LegacyPrintf("service.openai_gateway", "Upstream scan ended after terminal event: %v", scanErr) - return resultWithUsage(), nil, true + if errors.Is(scanErr, errOpenAIFirstOutputScannerLimit) && firstTokenMs == nil { + logger.LegacyPrintf("service.openai_gateway", "SSE token exceeded guarded first-output limit: account=%d limit=%d error=%v", account.ID, openAIFirstOutputStageMaxBytes+openAIFirstOutputScannerFramingAllowance, scanErr) + failoverErr := s.newOpenAIStreamFailoverError( + c, account, false, upstreamRequestID, nil, + "OpenAI SSE line exceeds guarded first-output limit", + ) + failoverErr.SafeToFailoverAfterWrite = true + return resultWithUsage(), failoverErr, true } - if sawFailedEvent { - return resultWithUsage(), fmt.Errorf("upstream response failed: %s", failedMessage), true + if errors.Is(scanErr, bufio.ErrTooLong) && guardFirstOutput && firstTokenMs == nil { + logger.LegacyPrintf("service.openai_gateway", "SSE line too long before first output: account=%d max_size=%d error=%v", account.ID, maxLineSize, scanErr) + failoverErr := s.newOpenAIStreamFailoverError( + c, account, false, upstreamRequestID, nil, + "OpenAI SSE line exceeds guarded first-output limit", + ) + failoverErr.SafeToFailoverAfterWrite = true + return resultWithUsage(), failoverErr, true + } + if sawTerminalEvent { + if !sawFailedEvent { + logger.LegacyPrintf("service.openai_gateway", "Upstream scan ended after terminal event: %v", scanErr) + } + result, err := finalizeStream() + return result, err, true } // 客户端断开/取消请求时,上游读取往往会返回 context canceled。 // /v1/responses 的 SSE 事件必须符合 OpenAI 协议;这里不注入自定义 error event,避免下游 SDK 解析失败。 if errors.Is(scanErr, context.Canceled) || errors.Is(scanErr, context.DeadlineExceeded) { + if eventShouldFlush { + flushPending("Client disconnected during canceled stream flush, returning collected usage") + } return resultWithUsage(), fmt.Errorf("stream usage incomplete: %w", scanErr), true } if errors.Is(scanErr, bufio.ErrTooLong) { @@ -210,7 +375,7 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp sendErrorEvent("response_too_large") return resultWithUsage(), scanErr, true } - if !openAIStreamClientOutputStarted(c, clientOutputStarted) { + if !openAIStreamClientOutputStarted(c, clientOutputStarted) && !eventShouldFlush { msg := "OpenAI stream disconnected before completion" if errText := strings.TrimSpace(scanErr.Error()); errText != "" { msg += ": " + errText @@ -336,6 +501,9 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp line = s.replaceModelInSSELine(line, mappedModel, originalModel) } startsClientOutput := forceFlushFailedEvent || openAIStreamDataStartsClientOutput(data, eventType) + if guardFirstOutput { + eventStartsClientOutput = eventStartsClientOutput || startsClientOutput + } // 写入客户端(客户端断开后继续 drain 上游) if !clientDisconnected { @@ -344,13 +512,53 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp // 保证首个 token 事件尽快出站,避免影响 TTFT。 shouldFlush = true } - if _, err := bufferedWriter.WriteString(line); err != nil { - clientDisconnected = true - logger.LegacyPrintf("service.openai_gateway", "Client disconnected during streaming, continuing to drain upstream for billing") - } else if _, err := bufferedWriter.WriteString("\n"); err != nil { - clientDisconnected = true - logger.LegacyPrintf("service.openai_gateway", "Client disconnected during streaming, continuing to drain upstream for billing") - } else if shouldFlush { + eventShouldFlush = eventShouldFlush || shouldFlush + if _, err := writePendingString(line); err != nil { + handlePendingWriteError(err) + } else if _, err := writePendingString("\n"); err != nil { + handlePendingWriteError(err) + } else { + eventInProgress = true + } + } + + // Record first token time + if !guardFirstOutput && firstTokenMs == nil && startsClientOutput { + ms := int(time.Since(startTime).Milliseconds()) + firstTokenMs = &ms + stopFirstOutputTimer() + } + s.parseSSEUsageBytes(dataBytes, usage) + return + } + + // A blank line dispatches a guarded event from the attempt-local stage. + if guardFirstOutput && line == "" { + if !clientDisconnected { + if _, err := writePendingString("\n"); err != nil { + handlePendingWriteError(err) + } + } + if streamEarlyErr == nil { + completeGuardedEvent(queueDrained) + } + return + } + // Non-guarded streams retain upstream's event-boundary flushing: a keepalive + // or queue-drain flush must never split an open SSE event. + shouldFlush := false + if line == "" { + shouldFlush = eventShouldFlush || (queueDrained && clientOutputStarted) + eventShouldFlush = false + } + if !clientDisconnected { + if _, err := writePendingString(line); err != nil { + handlePendingWriteError(err) + } else if _, err := writePendingString("\n"); err != nil { + handlePendingWriteError(err) + } else { + eventInProgress = line != "" + if shouldFlush { if err := flushBuffered(); err != nil { clientDisconnected = true logger.LegacyPrintf("service.openai_gateway", "Client disconnected during streaming flush, continuing to drain upstream for billing") @@ -360,78 +568,71 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp } } } - - // Record first token time - if firstTokenMs == nil && startsClientOutput { - ms := int(time.Since(startTime).Milliseconds()) - firstTokenMs = &ms - } - s.parseSSEUsageBytes(dataBytes, usage) - return - } - - // Forward non-data lines as-is - if !clientDisconnected { - if _, err := bufferedWriter.WriteString(line); err != nil { - clientDisconnected = true - logger.LegacyPrintf("service.openai_gateway", "Client disconnected during streaming, continuing to drain upstream for billing") - } else if _, err := bufferedWriter.WriteString("\n"); err != nil { - clientDisconnected = true - logger.LegacyPrintf("service.openai_gateway", "Client disconnected during streaming, continuing to drain upstream for billing") - } else if queueDrained && clientOutputStarted { - if err := flushBuffered(); err != nil { - clientDisconnected = true - logger.LegacyPrintf("service.openai_gateway", "Client disconnected during streaming flush, continuing to drain upstream for billing") - } else { - clientOutputStarted = true - lastDownstreamWriteAt = time.Now() - } - } } } // 无超时/无 keepalive 的常见路径走同步扫描,减少 goroutine 与 channel 开销。 - if streamInterval <= 0 && keepaliveInterval <= 0 { + if streamInterval <= 0 && keepaliveInterval <= 0 && firstOutputTimeout <= 0 { defer putSSEScannerBuf64K(scanBuf) - for scanner.Scan() { - processSSELine(scanner.Text(), true) + for documentScanner.Scan() { + processSSELine(documentScanner.Text(), true) if streamEarlyErr != nil { return resultWithUsage(), streamEarlyErr } } - if result, err, done := handleScanErr(scanner.Err()); done { + if result, err, done := handleScanErr(documentScanner.Err()); done { return result, err } return finalizeStream() } type scanEvent struct { - line string - err error + line string + err error + processed chan struct{} } // 独立 goroutine 读取上游,避免读取阻塞影响 keepalive/超时处理 - events := make(chan scanEvent, 16) + // Guard mode permits one queued token plus the token being processed. With + // the guarded scanner cap this bounds scanner/channel retention near 16 MiB; + // the timeout-disabled path preserves the legacy depth of 16. + events := make(chan scanEvent, openAIFirstOutputEventQueueSize(guardFirstOutput)) done := make(chan struct{}) sendEvent := func(ev scanEvent) bool { + if guardFirstOutput { + ev.processed = make(chan struct{}) + } select { case events <- ev: + case <-done: + return false + } + if ev.processed == nil { + return true + } + select { + case <-ev.processed: return true case <-done: return false } } + markEventProcessed := func(ev scanEvent) { + if ev.processed != nil { + close(ev.processed) + } + } var lastReadAt int64 atomic.StoreInt64(&lastReadAt, time.Now().UnixNano()) go func(scanBuf *sseScannerBuf64K) { defer putSSEScannerBuf64K(scanBuf) defer close(events) - for scanner.Scan() { + for documentScanner.Scan() { atomic.StoreInt64(&lastReadAt, time.Now().UnixNano()) - if !sendEvent(scanEvent{line: scanner.Text()}) { + if !sendEvent(scanEvent{line: documentScanner.Text()}) { return } } - if err := scanner.Err(); err != nil { + if err := documentScanner.Err(); err != nil { _ = sendEvent(scanEvent{err: err}) } }(scanBuf) @@ -441,12 +642,19 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp select { case ev, ok := <-events: if !ok { + if guardFirstOutput && eventInProgress { + // EOF dispatches the final SSE event even without a trailing blank + // line. Do not synthesize extra bytes on the downstream wire. + completeGuardedEvent(true) + } return finalizeStream() } if result, err, done := handleScanErr(ev.err); done { + markEventProcessed(ev) return result, err } processSSELine(ev.line, len(events) == 0) + markEventProcessed(ev) if streamEarlyErr != nil { return resultWithUsage(), streamEarlyErr } @@ -467,14 +675,43 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp sendErrorEvent("stream_timeout") return resultWithUsage(), fmt.Errorf("stream data interval timeout") + case <-firstOutputCh: + if firstTokenMs != nil { + stopFirstOutputTimer() + continue + } + _ = resp.Body.Close() + for ev := range events { + markEventProcessed(ev) + } + return resultWithUsage(), s.newOpenAIFirstOutputTimeoutError( + ctx, c, account, startTime, originalModel, reasoningEffort, + firstOutputTimeout, "semantic_output", resp.Header, + ) + case <-keepaliveCh: if clientDisconnected { continue } + if eventInProgress { + continue + } if time.Since(lastDownstreamWriteAt) < keepaliveInterval { continue } - if _, err := bufferedWriter.WriteString(":\n\n"); err != nil { + if guardFirstOutput { + // Bypass attempt-local buffered frames. The stable SSE headers may be + // committed here, but account headers remain private until semantic output. + if _, err := w.Write([]byte(":\n\n")); err != nil { + clientDisconnected = true + logger.LegacyPrintf("service.openai_gateway", "Client disconnected during streaming, continuing to drain upstream for billing") + continue + } + flusher.Flush() + lastDownstreamWriteAt = time.Now() + continue + } + if _, err := writePendingString(":\n\n"); err != nil { clientDisconnected = true logger.LegacyPrintf("service.openai_gateway", "Client disconnected during streaming, continuing to drain upstream for billing") continue diff --git a/backend/internal/service/openai_gateway_service.go b/backend/internal/service/openai_gateway_service.go index 11a8255bfa..956f167d1b 100644 --- a/backend/internal/service/openai_gateway_service.go +++ b/backend/internal/service/openai_gateway_service.go @@ -393,6 +393,7 @@ type OpenAIGatewayService struct { openaiWSStateStoreOnce sync.Once openaiSchedulerOnce sync.Once openaiWSPassthroughDialerOnce sync.Once + agentIdentityTaskMu sync.Mutex openaiWSPool *openAIWSConnPool openaiWSStateStore OpenAIWSStateStore openaiScheduler OpenAIAccountScheduler @@ -401,6 +402,10 @@ type OpenAIGatewayService struct { openaiWSFallbackUntil sync.Map // key: int64(accountID), value: time.Time openaiAccountRuntimeBlockUntil sync.Map // key: int64(accountID), value: time.Time + openaiAccountRuntimeBlockLocks sync.Map // key: int64(accountID), value: *sync.Mutex + openaiAccountRuntimeBlockGeneration sync.Map // key: int64(accountID), value: uint64 + openaiAccountRuntimeBlockSequence atomic.Uint64 + grokCredentialMutationLocks sync.Map // key: int64(accountID), value: *sync.Mutex openaiOAuth429WindowStartUnixNano atomic.Int64 openaiOAuth429WindowCount atomic.Int64 openaiWSRetryMetrics openAIWSRetryMetrics @@ -591,6 +596,12 @@ func (s *OpenAIGatewayService) CloseOpenAIWSPool() { } } +func (s *OpenAIGatewayService) InvalidateAgentIdentityWSConnections(accountID int64) { + if pool := s.getOpenAIWSConnPool(); pool != nil { + pool.ClearAccount(accountID) + } +} + func (s *OpenAIGatewayService) logOpenAIWSModeBootstrap() { if s == nil || s.cfg == nil { return @@ -1090,6 +1101,9 @@ func (s *OpenAIGatewayService) GetAccessToken(ctx context.Context, account *Acco } switch account.Type { case AccountTypeOAuth: + if account.IsOpenAIAgentIdentity() { + return "", OpenAIAuthModeAgentIdentity, nil + } if account.Platform == PlatformGrok { if s.grokTokenProvider != nil { accessToken, err := s.grokTokenProvider.GetAccessToken(ctx, account) diff --git a/backend/internal/service/openai_gateway_service_hotpath_test.go b/backend/internal/service/openai_gateway_service_hotpath_test.go index 326fde534d..f12f47796e 100644 --- a/backend/internal/service/openai_gateway_service_hotpath_test.go +++ b/backend/internal/service/openai_gateway_service_hotpath_test.go @@ -221,6 +221,24 @@ func TestOpenAIGatewayService_Forward_MappedImageModelUsesImageGate(t *testing.T require.Nil(t, result) require.Nil(t, upstream.lastReq) require.Equal(t, http.StatusForbidden, rec.Code) + cached, known := getOpenAIImageIntentHint(c) + require.True(t, known) + require.False(t, cached) + + textAccount := *account + textAccount.ID = 4 + textAccount.Credentials = map[string]any{ + "api_key": "sk-test", + "base_url": "https://example.com", + } + result, err = svc.Forward(context.Background(), c, &textAccount, body) + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, upstream.lastReq) + require.Len(t, upstream.bodies, 1) + cached, known = getOpenAIImageIntentHint(c) + require.True(t, known) + require.False(t, cached) } func TestOpenAIGatewayService_Forward_TextResponsesSetsBillingModelToMappedModel(t *testing.T) { diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go index 2e661e7417..d8823fe4ed 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -279,6 +279,7 @@ func (s *OpenAIGatewayService) handleErrorResponse( requestedModel ...string, ) (*OpenAIForwardResult, error) { body := s.readUpstreamErrorBody(resp) + body = s.redactAgentIdentitySensitiveBody(ctx, account, body) // cyber_policy 硬阻断:透传上游原始错误体给客户端(不重包成通用 502),不冷却账号。 // 当前请求恒透传(需求1);标记供 handler 事后写风控/邮件。400 cyber 不可 failover @@ -470,6 +471,7 @@ func (s *OpenAIGatewayService) handleCompatErrorResponse( requestedModel ...string, ) (*OpenAIForwardResult, error) { body := s.readUpstreamErrorBody(resp) + body = s.redactAgentIdentitySensitiveBody(context.Background(), account, body) // cyber_policy:兼容路径(Chat Completions / Anthropic)以各自格式回写错误, // 不原样透传 responses 格式的 cyber body(否则对下游格式不合法)。cyber 是上游网络 diff --git a/backend/internal/service/openai_image_dimensions.go b/backend/internal/service/openai_image_dimensions.go new file mode 100644 index 0000000000..b297aeaf67 --- /dev/null +++ b/backend/internal/service/openai_image_dimensions.go @@ -0,0 +1,92 @@ +package service + +import ( + "bufio" + "encoding/base64" + "encoding/binary" + "fmt" + "image" + _ "image/jpeg" + _ "image/png" + "io" + "strings" +) + +const maxOpenAIImageDimensionProbeBytes int64 = 1 << 20 + +func detectOpenAIImageResultSize(encoded string) string { + payload := strings.TrimSpace(encoded) + if strings.HasPrefix(strings.ToLower(payload), "data:") { + comma := strings.IndexByte(payload, ',') + if comma < 0 || comma+1 >= len(payload) { + return "" + } + payload = strings.TrimSpace(payload[comma+1:]) + } + if payload == "" { + return "" + } + + for _, encoding := range []*base64.Encoding{base64.StdEncoding, base64.RawStdEncoding} { + decoded := base64.NewDecoder(encoding, strings.NewReader(payload)) + buffered := bufio.NewReader(io.LimitReader(decoded, maxOpenAIImageDimensionProbeBytes)) + prefix, _ := buffered.Peek(30) + if width, height, ok := detectOpenAIWebPDimensions(prefix); ok { + return fmt.Sprintf("%dx%d", width, height) + } + cfg, _, err := image.DecodeConfig(buffered) + if err != nil || cfg.Width <= 0 || cfg.Height <= 0 { + continue + } + return fmt.Sprintf("%dx%d", cfg.Width, cfg.Height) + } + return "" +} + +func detectOpenAIWebPDimensions(header []byte) (int, int, bool) { + if len(header) < 16 || string(header[:4]) != "RIFF" || string(header[8:12]) != "WEBP" { + return 0, 0, false + } + + switch string(header[12:16]) { + case "VP8X": + if len(header) < 30 { + return 0, 0, false + } + width := 1 + int(header[24]) + int(header[25])<<8 + int(header[26])<<16 + height := 1 + int(header[27]) + int(header[28])<<8 + int(header[29])<<16 + return width, height, width > 0 && height > 0 + case "VP8 ": + if len(header) < 30 || string(header[23:26]) != "\x9d\x01\x2a" { + return 0, 0, false + } + width := int(binary.LittleEndian.Uint16(header[26:28]) & 0x3fff) + height := int(binary.LittleEndian.Uint16(header[28:30]) & 0x3fff) + return width, height, width > 0 && height > 0 + case "VP8L": + if len(header) < 25 || header[20] != 0x2f { + return 0, 0, false + } + width := 1 + int(header[21]) + int(header[22]&0x3f)<<8 + height := 1 + int(header[22]>>6) + int(header[23])<<2 + int(header[24]&0x0f)<<10 + return width, height, width > 0 && height > 0 + default: + return 0, 0, false + } +} + +func reconcileOpenAIResponsesImageResultSizes(results []openAIResponsesImageResult, firstMeta *openAIResponsesImageResult) { + for i := range results { + // ChatGPT OAuth can normalize requested controls to "auto". The final + // image bytes are authoritative for response metadata and tier billing. + if actualSize := detectOpenAIImageResultSize(results[i].Result); actualSize != "" { + results[i].Size = actualSize + } + } + if firstMeta == nil || len(results) == 0 { + return + } + if size := strings.TrimSpace(results[0].Size); size != "" { + firstMeta.Size = size + } +} diff --git a/backend/internal/service/openai_image_generation_controls_test.go b/backend/internal/service/openai_image_generation_controls_test.go index 090948afd4..de2446eb7f 100644 --- a/backend/internal/service/openai_image_generation_controls_test.go +++ b/backend/internal/service/openai_image_generation_controls_test.go @@ -242,6 +242,7 @@ func TestOpenAIGatewayServiceForward_AccountPolicyStripsImageNamespaceTools(t *t } svc := newOpenAIImageGenerationControlTestService(upstream) c, _ := newOpenAIImageGenerationControlTestContext(false, "codex_cli_rs/0.144.1") + SetOpenAIClientTransport(c, OpenAIClientTransportHTTP) account := newOpenAIImageGenerationControlTestAccount() account.Extra = map[string]any{ featureKeyCodexImageGenerationExplicitToolPolicy: codexImageGenerationExplicitToolPolicyStrip, @@ -274,6 +275,9 @@ func TestOpenAIGatewayServiceForward_AccountPolicyStripsImageNamespaceTools(t *t require.True(t, gjson.GetBytes(upstream.lastBody, `tools.#(name=="shell")`).Exists()) require.True(t, gjson.GetBytes(upstream.lastBody, `tools.#(name=="code_tools")`).Exists()) require.Equal(t, "write code", gjson.GetBytes(upstream.lastBody, "input.0.content.0.text").String()) + cached, known := getOpenAIImageIntentHint(c) + require.True(t, known) + require.True(t, cached) }) } } @@ -349,6 +353,54 @@ func TestOpenAIGatewayServiceForward_CodexBridgeDoesNotInjectHostedToolAlongside require.Equal(t, "namespace", gjson.GetBytes(upstream.lastBody, `input.#(type=="additional_tools").tools.#(name=="image_gen").type`).String()) } +func TestOpenAIGatewayServiceForward_CodexBridgePreservesImageGenFunction(t *testing.T) { + gin.SetMode(gin.TestMode) + + tests := []struct { + name string + tool string + }{ + { + name: "flat function", + tool: `{"type":"function","name":"image_gen.imagegen","parameters":{"type":"object"}}`, + }, + { + name: "nested function", + tool: `{"type":"function","function":{"name":"image_gen.imagegen","parameters":{"type":"object"}}}`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + upstream := &httpUpstreamRecorder{ + resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"id":"resp_function_image","model":"gpt-5.5","usage":{"input_tokens":1,"output_tokens":1}}`)), + }, + } + svc := newOpenAIImageGenerationControlTestService(upstream) + svc.cfg.Gateway.CodexImageGenerationBridgeEnabled = true + c, _ := newOpenAIImageGenerationControlTestContext(true, "codex_cli_rs/0.144.1") + account := newOpenAIImageGenerationControlTestAccount() + body := []byte(`{"model":"gpt-5.5","input":"draw a cat","stream":false,"tools":[` + tt.tool + `]}`) + + result, err := svc.Forward(context.Background(), c, account, body) + + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, upstream.lastReq) + + var forwarded map[string]any + require.NoError(t, json.Unmarshal(upstream.lastBody, &forwarded)) + require.True(t, hasCodexImageGenerationFunctionTool(forwarded)) + require.False(t, gjson.GetBytes(upstream.lastBody, `tools.#(type=="image_generation")`).Exists()) + require.False(t, gjson.GetBytes(upstream.lastBody, "tool_choice").Exists()) + require.NotContains(t, gjson.GetBytes(upstream.lastBody, "instructions").String(), codexImageGenerationBridgeMarker) + }) + } +} + func TestOpenAIGatewayServiceForward_CodexBridgePreservesExistingToolChoice(t *testing.T) { gin.SetMode(gin.TestMode) diff --git a/backend/internal/service/openai_image_intent_hint.go b/backend/internal/service/openai_image_intent_hint.go new file mode 100644 index 0000000000..f8f966e5fc --- /dev/null +++ b/backend/internal/service/openai_image_intent_hint.go @@ -0,0 +1,59 @@ +package service + +import "github.com/gin-gonic/gin" + +// 请求级 hint 仅限 HTTP:缺失表示 unknown,false/true 都表示已完成 canonical 判定。 +const openAIImageIntentHintContextKey = "openai_image_intent_hint" + +type openAIImageIntentClassifier func(endpoint string, requestedModel string, body []byte) bool + +// SetOpenAIImageIntentHint 只写入请求级 canonical 判定,不记录 attempt-local 结果。 +func SetOpenAIImageIntentHint(c *gin.Context, imageIntent bool) { + if c == nil || GetOpenAIClientTransport(c) != OpenAIClientTransportHTTP { + return + } + c.Set(openAIImageIntentHintContextKey, imageIntent) +} + +func getOpenAIImageIntentHint(c *gin.Context) (imageIntent bool, known bool) { + if c == nil || GetOpenAIClientTransport(c) != OpenAIClientTransportHTTP { + return false, false + } + value, ok := c.Get(openAIImageIntentHintContextKey) + if !ok { + return false, false + } + imageIntent, ok = value.(bool) + return imageIntent, ok +} + +func resolveOpenAIImageIntentHint( + c *gin.Context, + requestedModel string, + canonicalBody []byte, + classify openAIImageIntentClassifier, +) bool { + if imageIntent, known := getOpenAIImageIntentHint(c); known { + return imageIntent + } + imageIntent := classify(openAIResponsesEndpoint, requestedModel, canonicalBody) + SetOpenAIImageIntentHint(c, imageIntent) + return imageIntent +} + +func resolveOpenAIPassthroughImageIntent( + c *gin.Context, + canonicalRequestedModel string, + canonicalBody []byte, + attemptRequestedModel string, + attemptBody []byte, + attemptInvalidated bool, + classify openAIImageIntentClassifier, +) bool { + imageIntent := resolveOpenAIImageIntentHint(c, canonicalRequestedModel, canonicalBody, classify) + if attemptInvalidated { + // strip/compact 改写只重算当前 attempt,不得把变换后的结果写回请求级 canonical hint。 + imageIntent = classify(openAIResponsesEndpoint, attemptRequestedModel, attemptBody) + } + return imageIntent +} diff --git a/backend/internal/service/openai_image_intent_hint_test.go b/backend/internal/service/openai_image_intent_hint_test.go new file mode 100644 index 0000000000..be5c61d091 --- /dev/null +++ b/backend/internal/service/openai_image_intent_hint_test.go @@ -0,0 +1,338 @@ +package service + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func newOpenAIImageIntentHintTestContext(transport OpenAIClientTransport) *gin.Context { + c := &gin.Context{} + SetOpenAIClientTransport(c, transport) + return c +} + +func countingOpenAIImageIntentClassifier(calls *atomic.Int64) openAIImageIntentClassifier { + return func(endpoint string, requestedModel string, body []byte) bool { + calls.Add(1) + return IsImageGenerationIntent(endpoint, requestedModel, body) + } +} + +func TestResolveOpenAIImageIntentHintCachesTrueAndFalse(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + body []byte + want bool + }{ + {name: "true", body: []byte(`{"model":"gpt-5.4","tools":[{"type":"image_generation"}]}`), want: true}, + {name: "false is known", body: []byte(`{"model":"gpt-5.4","input":"write code"}`), want: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := newOpenAIImageIntentHintTestContext(OpenAIClientTransportHTTP) + var calls atomic.Int64 + classify := countingOpenAIImageIntentClassifier(&calls) + + require.Equal(t, tt.want, resolveOpenAIImageIntentHint(c, "gpt-5.4", tt.body, classify)) + require.Equal(t, tt.want, resolveOpenAIImageIntentHint(c, "gpt-5.4", tt.body, classify)) + require.Equal(t, int64(1), calls.Load()) + cached, known := getOpenAIImageIntentHint(c) + require.True(t, known) + require.Equal(t, tt.want, cached) + }) + } +} + +func TestResolveOpenAIImageIntentHintUsesHandlerSeed(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, seeded := range []bool{false, true} { + c := newOpenAIImageIntentHintTestContext(OpenAIClientTransportHTTP) + SetOpenAIImageIntentHint(c, seeded) + var calls atomic.Int64 + + got := resolveOpenAIImageIntentHint(c, "gpt-5.4", []byte(`{"model":"gpt-5.4"}`), countingOpenAIImageIntentClassifier(&calls)) + + require.Equal(t, seeded, got) + require.Zero(t, calls.Load()) + } +} + +func TestResolveOpenAIPassthroughImageIntentReusesCanonicalAcrossFailover(t *testing.T) { + gin.SetMode(gin.TestMode) + c := newOpenAIImageIntentHintTestContext(OpenAIClientTransportHTTP) + body := []byte(`{"model":"gpt-5.4","input":"write code"}`) + var calls atomic.Int64 + classify := countingOpenAIImageIntentClassifier(&calls) + + for range 3 { + require.False(t, resolveOpenAIPassthroughImageIntent(c, "gpt-5.4", body, "gpt-5.4", body, false, classify)) + } + require.Equal(t, int64(1), calls.Load()) +} + +func TestResolveOpenAIPassthroughImageIntentKeepsCompactMappingAttemptLocal(t *testing.T) { + gin.SetMode(gin.TestMode) + t.Run("text to image", func(t *testing.T) { + c := newOpenAIImageIntentHintTestContext(OpenAIClientTransportHTTP) + body := []byte(`{"model":"draw-alias","input":"draw"}`) + compactBody := []byte(`{"model":"gpt-image-2","input":"draw"}`) + var calls atomic.Int64 + classify := countingOpenAIImageIntentClassifier(&calls) + + require.True(t, resolveOpenAIPassthroughImageIntent(c, "draw-alias", body, "gpt-image-2", compactBody, true, classify)) + cached, known := getOpenAIImageIntentHint(c) + require.True(t, known) + require.False(t, cached) + + require.False(t, resolveOpenAIPassthroughImageIntent(c, "draw-alias", body, "draw-alias", body, false, classify)) + require.Equal(t, int64(2), calls.Load()) + cached, known = getOpenAIImageIntentHint(c) + require.True(t, known) + require.False(t, cached) + }) + + t.Run("image to text", func(t *testing.T) { + c := newOpenAIImageIntentHintTestContext(OpenAIClientTransportHTTP) + body := []byte(`{"model":"gpt-image-2","input":"draw"}`) + compactBody := []byte(`{"model":"gpt-5.4","input":"draw"}`) + var calls atomic.Int64 + classify := countingOpenAIImageIntentClassifier(&calls) + + require.False(t, resolveOpenAIPassthroughImageIntent(c, "gpt-image-2", body, "gpt-5.4", compactBody, true, classify)) + cached, known := getOpenAIImageIntentHint(c) + require.True(t, known) + require.True(t, cached) + + require.True(t, resolveOpenAIPassthroughImageIntent(c, "gpt-image-2", body, "gpt-image-2", body, false, classify)) + require.Equal(t, int64(2), calls.Load()) + }) +} + +func TestResolveOpenAIPassthroughImageIntentInvalidationDoesNotPolluteCanonical(t *testing.T) { + gin.SetMode(gin.TestMode) + c := newOpenAIImageIntentHintTestContext(OpenAIClientTransportHTTP) + canonicalBody := []byte(`{"model":"gpt-5.4","tools":[{"type":"image_generation"}]}`) + strippedBody := []byte(`{"model":"gpt-5.4","tools":[]}`) + var calls atomic.Int64 + classify := countingOpenAIImageIntentClassifier(&calls) + + require.False(t, resolveOpenAIPassthroughImageIntent(c, "gpt-5.4", canonicalBody, "gpt-5.4", strippedBody, true, classify)) + require.Equal(t, int64(2), calls.Load(), "unknown canonical and invalidated attempt are classified independently") + cached, known := getOpenAIImageIntentHint(c) + require.True(t, known) + require.True(t, cached) + + require.True(t, resolveOpenAIPassthroughImageIntent(c, "gpt-5.4", canonicalBody, "gpt-5.4", canonicalBody, false, classify)) + require.Equal(t, int64(2), calls.Load()) +} + +func TestResolveOpenAIPassthroughImageIntentMappedBodyStartsUnknownThenSeedsCanonical(t *testing.T) { + gin.SetMode(gin.TestMode) + c := newOpenAIImageIntentHintTestContext(OpenAIClientTransportHTTP) + canonicalBody := []byte(`{"model":"gpt-image-2","input":"draw"}`) + strippedAttemptBody := []byte(`{"model":"gpt-5.4","input":"draw"}`) + _, known := getOpenAIImageIntentHint(c) + require.False(t, known) + var calls atomic.Int64 + classify := countingOpenAIImageIntentClassifier(&calls) + + require.False(t, resolveOpenAIPassthroughImageIntent(c, "gpt-image-2", canonicalBody, "gpt-5.4", strippedAttemptBody, true, classify)) + require.Equal(t, int64(2), calls.Load()) + cached, known := getOpenAIImageIntentHint(c) + require.True(t, known) + require.True(t, cached) +} + +func TestResolveOpenAIPassthroughImageIntentReusesAcrossInvariantMutations(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + canonicalBody []byte + attemptBody []byte + want bool + }{ + { + name: "oauth sanitize fast policy and reasoning", + canonicalBody: []byte(`{"model":"gpt-5.4","input":[{"type":"input_image","image_url":"data:image/png;base64,"}],"service_tier":"fast","reasoning":{"effort":"minimal"}}`), + attemptBody: []byte(`{"model":"gpt-5.4","input":[],"service_tier":"priority","reasoning":{"effort":"none"},"store":false,"stream":true}`), + want: false, + }, + { + name: "namespace flatten", + canonicalBody: []byte(`{"model":"gpt-5.4","tools":[{"type":"namespace","name":"code_tools"}]}`), + attemptBody: []byte(`{"model":"gpt-5.4","tools":[{"type":"function","name":"code_tools.run"}]}`), + want: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := newOpenAIImageIntentHintTestContext(OpenAIClientTransportHTTP) + var calls atomic.Int64 + classify := countingOpenAIImageIntentClassifier(&calls) + + require.Equal(t, tt.want, resolveOpenAIPassthroughImageIntent(c, "gpt-5.4", tt.canonicalBody, "gpt-5.4", tt.attemptBody, false, classify)) + require.Equal(t, tt.want, resolveOpenAIPassthroughImageIntent(c, "gpt-5.4", tt.canonicalBody, "gpt-5.4", tt.attemptBody, false, classify)) + require.Equal(t, int64(1), calls.Load()) + }) + } +} + +func TestOpenAIGatewayServicePassthroughCompactImageIntentIsAttemptLocal(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + canonicalModel string + compactModel string + wantRejected bool + wantCanonical bool + }{ + { + name: "text to image rejects", + canonicalModel: "gpt-5.4", + compactModel: "gpt-image-2", + wantRejected: true, + }, + { + name: "image to text reaches upstream", + canonicalModel: "gpt-image-2", + compactModel: "gpt-5.4", + wantCanonical: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"id":"resp_compact","model":"` + tt.compactModel + `","usage":{"input_tokens":1,"output_tokens":1}}`)), + }} + svc := newOpenAIImageGenerationControlTestService(upstream) + c, recorder := newOpenAIImageGenerationControlTestContext(false, "unit-test-agent/1.0") + c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/responses/compact", nil) + SetOpenAIClientTransport(c, OpenAIClientTransportHTTP) + account := newOpenAIImageGenerationControlTestAccount() + account.Extra = map[string]any{"openai_passthrough": true} + account.Credentials = map[string]any{ + "api_key": "sk-test", + "compact_model_mapping": map[string]any{ + tt.canonicalModel: tt.compactModel, + }, + } + body := []byte(`{"model":"` + tt.canonicalModel + `","stream":false,"input":"draw"}`) + + result, err := svc.Forward(context.Background(), c, account, body) + + cached, known := getOpenAIImageIntentHint(c) + require.True(t, known) + require.Equal(t, tt.wantCanonical, cached) + if tt.wantRejected { + require.Error(t, err) + require.Nil(t, result) + require.Equal(t, http.StatusForbidden, recorder.Code) + require.Nil(t, upstream.lastReq) + return + } + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, upstream.lastReq) + require.Equal(t, tt.compactModel, gjson.GetBytes(upstream.lastBody, "model").String()) + }) + } +} + +func TestResolveOpenAIImageIntentHintExcludesWebSocketAndUnknownTransport(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, transport := range []OpenAIClientTransport{OpenAIClientTransportWS, OpenAIClientTransportUnknown} { + c := newOpenAIImageIntentHintTestContext(transport) + var calls atomic.Int64 + classify := countingOpenAIImageIntentClassifier(&calls) + body := []byte(`{"model":"gpt-5.4","input":"write code"}`) + + require.False(t, resolveOpenAIImageIntentHint(c, "gpt-5.4", body, classify)) + require.False(t, resolveOpenAIImageIntentHint(c, "gpt-5.4", body, classify)) + require.Equal(t, int64(2), calls.Load()) + _, known := getOpenAIImageIntentHint(c) + require.False(t, known) + } +} + +func TestResolveOpenAIImageIntentHintConcurrentRequestsAreIsolated(t *testing.T) { + gin.SetMode(gin.TestMode) + const requests = 32 + var calls atomic.Int64 + classify := countingOpenAIImageIntentClassifier(&calls) + var wg sync.WaitGroup + results := make([][2]bool, requests) + + for i := range requests { + wg.Add(1) + go func(index int, image bool) { + defer wg.Done() + c := newOpenAIImageIntentHintTestContext(OpenAIClientTransportHTTP) + body := []byte(`{"model":"gpt-5.4","input":"write code"}`) + if image { + body = []byte(`{"model":"gpt-5.4","tools":[{"type":"image_generation"}]}`) + } + results[index][0] = resolveOpenAIImageIntentHint(c, "gpt-5.4", body, classify) + results[index][1] = resolveOpenAIImageIntentHint(c, "gpt-5.4", body, classify) + }(i, i%2 == 0) + } + wg.Wait() + for i, result := range results { + require.Equal(t, i%2 == 0, result[0]) + require.Equal(t, result[0], result[1]) + } + require.Equal(t, int64(requests), calls.Load()) +} + +var openAIImageIntentHintBenchmarkSink bool + +func BenchmarkOpenAIPassthroughImageIntentHintLargeBody(b *testing.B) { + body := []byte(`{"model":"gpt-5.4","input":"` + strings.Repeat("x", 4<<20) + `"}`) + const attempts = 4 + + b.Run("scan_each_attempt", func(b *testing.B) { + c := newOpenAIImageIntentHintTestContext(OpenAIClientTransportHTTP) + b.ReportAllocs() + calls := 0 + for range b.N { + c.Set(openAIImageIntentHintContextKey, struct{}{}) + for range attempts { + calls++ + openAIImageIntentHintBenchmarkSink = IsImageGenerationIntent(openAIResponsesEndpoint, "gpt-5.4", body) + } + } + b.ReportMetric(float64(calls)/float64(b.N), "classifier_calls/op") + }) + + b.Run("request_scoped_hint", func(b *testing.B) { + c := newOpenAIImageIntentHintTestContext(OpenAIClientTransportHTTP) + b.ReportAllocs() + calls := 0 + classify := func(endpoint string, requestedModel string, candidate []byte) bool { + calls++ + return IsImageGenerationIntent(endpoint, requestedModel, candidate) + } + for range b.N { + c.Set(openAIImageIntentHintContextKey, struct{}{}) + for range attempts { + openAIImageIntentHintBenchmarkSink = resolveOpenAIPassthroughImageIntent(c, "gpt-5.4", body, "gpt-5.4", body, false, classify) + } + } + b.ReportMetric(float64(calls)/float64(b.N), "classifier_calls/op") + }) +} diff --git a/backend/internal/service/openai_images.go b/backend/internal/service/openai_images.go index fc7d37a173..081b5e741b 100644 --- a/backend/internal/service/openai_images.go +++ b/backend/internal/service/openai_images.go @@ -632,6 +632,7 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesAPIKey( if resp.StatusCode >= 400 { respBody := s.readUpstreamErrorBody(resp) _ = resp.Body.Close() + respBody = s.redactAgentIdentitySensitiveBody(upstreamCtx, account, respBody) resp.Body = io.NopCloser(bytes.NewReader(respBody)) upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody)) upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg) @@ -752,7 +753,15 @@ func (s *OpenAIGatewayService) buildOpenAIImagesRequest( return nil, err } req = req.WithContext(WithHTTPUpstreamProfile(req.Context(), HTTPUpstreamProfileOpenAI)) - req.Header.Set("Authorization", "Bearer "+token) + authHeaders, err := s.buildOpenAIAuthenticationHeaders(ctx, account, token) + if err != nil { + return nil, fmt.Errorf("build openai authentication headers: %w", err) + } + for key, values := range authHeaders { + for _, value := range values { + req.Header.Add(key, value) + } + } for key, values := range c.Request.Header { if !openaiPassthroughAllowedHeaders[strings.ToLower(key)] { continue diff --git a/backend/internal/service/openai_images_actual_size_test.go b/backend/internal/service/openai_images_actual_size_test.go new file mode 100644 index 0000000000..4455e415a0 --- /dev/null +++ b/backend/internal/service/openai_images_actual_size_test.go @@ -0,0 +1,174 @@ +package service + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/binary" + "fmt" + "image" + "image/color" + "image/jpeg" + "image/png" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestDetectOpenAIImageResultSize(t *testing.T) { + pngEncoded := encodeOpenAIImageTestPNG(t, 1672, 941) + jpegEncoded := encodeOpenAIImageTestJPEG(t, 640, 360) + webpVP8XEncoded := encodeOpenAIImageTestWebPVP8X(1920, 1080) + webpVP8Encoded := encodeOpenAIImageTestWebPVP8(1280, 720) + webpVP8LEncoded := encodeOpenAIImageTestWebPVP8L(640, 480) + + require.Equal(t, "1672x941", detectOpenAIImageResultSize(pngEncoded)) + require.Equal(t, "1672x941", detectOpenAIImageResultSize(strings.TrimRight(pngEncoded, "="))) + require.Equal(t, "1672x941", detectOpenAIImageResultSize("data:image/png;base64,"+pngEncoded)) + require.Equal(t, "640x360", detectOpenAIImageResultSize(jpegEncoded)) + require.Equal(t, "1920x1080", detectOpenAIImageResultSize(webpVP8XEncoded)) + require.Equal(t, "1280x720", detectOpenAIImageResultSize(webpVP8Encoded)) + require.Equal(t, "640x480", detectOpenAIImageResultSize(webpVP8LEncoded)) + require.Empty(t, detectOpenAIImageResultSize("data:image/png;base64")) + require.Empty(t, detectOpenAIImageResultSize("not-image-data")) +} + +func TestOpenAIGatewayServiceForwardImages_OAuthUsesDecodedOutputDimensions(t *testing.T) { + run := runOpenAIOAuthImageActualSizeTest(t, false) + + require.Equal(t, "3840x2160", gjson.GetBytes(run.upstream.lastBody, "tools.0.size").String()) + require.Equal(t, "low", gjson.GetBytes(run.upstream.lastBody, "tools.0.quality").String()) + require.Equal(t, "1672x941", gjson.Get(run.recorder.Body.String(), "size").String()) + require.Equal(t, "auto", gjson.Get(run.recorder.Body.String(), "quality").String()) + require.Equal(t, []string{"1672x941"}, run.result.ImageOutputSizes) + + ApplyOpenAIImageBillingResolution(run.result) + require.Equal(t, ImageBillingSize2K, run.result.ImageSize) + require.Equal(t, "1672x941", run.result.ImageOutputSize) + require.Equal(t, ImageSizeSourceOutput, run.result.ImageSizeSource) +} + +func TestOpenAIGatewayServiceForwardImages_OAuthStreamingUsesDecodedOutputDimensions(t *testing.T) { + run := runOpenAIOAuthImageActualSizeTest(t, true) + + events := parseOpenAIImageTestSSEEvents(run.recorder.Body.String()) + completed, ok := findOpenAIImageTestSSEEvent(events, "image_generation.completed") + require.True(t, ok) + require.Equal(t, "1672x941", gjson.Get(completed.Data, "size").String()) + require.Equal(t, "auto", gjson.Get(completed.Data, "quality").String()) + require.Equal(t, []string{"1672x941"}, run.result.ImageOutputSizes) +} + +type openAIOAuthImageActualSizeTestRun struct { + result *OpenAIForwardResult + recorder *httptest.ResponseRecorder + upstream *httpUpstreamRecorder +} + +func runOpenAIOAuthImageActualSizeTest(t *testing.T, stream bool) openAIOAuthImageActualSizeTestRun { + t.Helper() + gin.SetMode(gin.TestMode) + body := []byte(fmt.Sprintf(`{"model":"gpt-image-2","prompt":"draw a test chart","size":"3840x2160","quality":"low","output_format":"png","stream":%t}`, stream)) + req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = req + c.Set("api_key", &APIKey{ID: 42}) + + encoded := encodeOpenAIImageTestPNG(t, 1672, 941) + upstreamBody := fmt.Sprintf( + "data: {\"type\":\"response.created\",\"response\":{\"created_at\":1710000000,\"tools\":[{\"type\":\"image_generation\",\"model\":\"gpt-image-2\",\"size\":\"auto\",\"quality\":\"auto\",\"output_format\":\"png\"}]}}\n\n"+ + "data: {\"type\":\"response.completed\",\"response\":{\"created_at\":1710000000,\"tools\":[{\"type\":\"image_generation\",\"model\":\"gpt-image-2\",\"size\":\"auto\",\"quality\":\"auto\",\"output_format\":\"png\"}],\"output\":[{\"id\":\"ig_actual_size\",\"type\":\"image_generation_call\",\"result\":%q}]}}\n\n"+ + "data: [DONE]\n\n", + encoded, + ) + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{ + "Content-Type": []string{"text/event-stream"}, + "X-Request-Id": []string{"req_img_actual_size"}, + }, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + }} + svc := &OpenAIGatewayService{httpUpstream: upstream} + parsed, err := svc.ParseOpenAIImagesRequest(c, body) + require.NoError(t, err) + + account := &Account{ + ID: 1, + Name: "openai-oauth", + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "access_token": "token-123", + "chatgpt_account_id": "acct-123", + }, + } + result, err := svc.ForwardImages(context.Background(), c, account, body, parsed, "") + require.NoError(t, err) + require.NotNil(t, result) + return openAIOAuthImageActualSizeTestRun{result: result, recorder: rec, upstream: upstream} +} + +func encodeOpenAIImageTestPNG(t *testing.T, width, height int) string { + t.Helper() + img := image.NewNRGBA(image.Rect(0, 0, width, height)) + img.SetNRGBA(0, 0, color.NRGBA{R: 0xff, A: 0xff}) + var buf bytes.Buffer + require.NoError(t, png.Encode(&buf, img)) + return base64.StdEncoding.EncodeToString(buf.Bytes()) +} + +func encodeOpenAIImageTestJPEG(t *testing.T, width, height int) string { + t.Helper() + img := image.NewNRGBA(image.Rect(0, 0, width, height)) + img.SetNRGBA(0, 0, color.NRGBA{G: 0xff, A: 0xff}) + var buf bytes.Buffer + require.NoError(t, jpeg.Encode(&buf, img, nil)) + return base64.StdEncoding.EncodeToString(buf.Bytes()) +} + +func encodeOpenAIImageTestWebPVP8X(width, height int) string { + header := make([]byte, 30) + copy(header[0:4], "RIFF") + copy(header[8:12], "WEBP") + copy(header[12:16], "VP8X") + width-- + height-- + header[24], header[25], header[26] = byte(width), byte(width>>8), byte(width>>16) + header[27], header[28], header[29] = byte(height), byte(height>>8), byte(height>>16) + return base64.StdEncoding.EncodeToString(header) +} + +func encodeOpenAIImageTestWebPVP8(width, height int) string { + header := make([]byte, 30) + copy(header[0:4], "RIFF") + copy(header[8:12], "WEBP") + copy(header[12:16], "VP8 ") + copy(header[23:26], "\x9d\x01\x2a") + binary.LittleEndian.PutUint16(header[26:28], uint16(width)) + binary.LittleEndian.PutUint16(header[28:30], uint16(height)) + return base64.StdEncoding.EncodeToString(header) +} + +func encodeOpenAIImageTestWebPVP8L(width, height int) string { + header := make([]byte, 25) + copy(header[0:4], "RIFF") + copy(header[8:12], "WEBP") + copy(header[12:16], "VP8L") + header[20] = 0x2f + width-- + height-- + header[21] = byte(width) + header[22] = byte(width>>8)&0x3f | byte(height&0x03)<<6 + header[23] = byte(height >> 2) + header[24] = byte(height>>10) & 0x0f + return base64.StdEncoding.EncodeToString(header) +} diff --git a/backend/internal/service/openai_images_json_keepalive.go b/backend/internal/service/openai_images_json_keepalive.go index 0d8b24fb0a..6ad79b1ae5 100644 --- a/backend/internal/service/openai_images_json_keepalive.go +++ b/backend/internal/service/openai_images_json_keepalive.go @@ -127,6 +127,12 @@ func StopOpenAIImagesJSONKeepaliveCommitted(c *gin.Context) bool { return committed } +// OpenAIImagesJSONKeepalivePresent reports whether the response writer belongs +// to an Images JSON request, including fast responses before the first beat. +func OpenAIImagesJSONKeepalivePresent(c *gin.Context) bool { + return openAIImagesJSONKeepaliveFromContext(c) != nil +} + // OpenAIImagesJSONKeepaliveAdjustedWrittenSize excludes heartbeat whitespace // from response-size checks so account retry and failover remain available. func OpenAIImagesJSONKeepaliveAdjustedWrittenSize(c *gin.Context) int { diff --git a/backend/internal/service/openai_images_responses.go b/backend/internal/service/openai_images_responses.go index 363ba9f591..151de2c4b1 100644 --- a/backend/internal/service/openai_images_responses.go +++ b/backend/internal/service/openai_images_responses.go @@ -565,12 +565,14 @@ func collectOpenAIImagesFromResponsesBody(body []byte) ([]openAIResponsesImageRe return nil, 0, nil, openAIResponsesImageResult{}, false, collectErr } if len(finalResults) > 0 { + reconcileOpenAIResponsesImageResultSizes(finalResults, &finalMeta) return finalResults, createdAt, usageRaw, finalMeta, true, nil } if len(fallbackResults) > 0 { firstMeta := fallbackResults[0] mergeOpenAIResponsesImageMeta(&firstMeta, responseMeta) + reconcileOpenAIResponsesImageResultSizes(fallbackResults, &firstMeta) return fallbackResults, createdAt, usageRaw, firstMeta, foundFinal, nil } return nil, createdAt, usageRaw, openAIResponsesImageResult{}, foundFinal, nil @@ -1262,6 +1264,7 @@ func (s *OpenAIGatewayService) handleOpenAIImagesOAuthStreamingResponse( mergeOpenAIResponsesImageMeta(&img, streamMeta) appendOpenAIResponsesImageResultDedup(&finalResults, finalSeen, "", img) } + reconcileOpenAIResponsesImageResultSizes(finalResults, nil) if len(finalResults) == 0 { outputErr := fmt.Errorf("upstream did not return image output") // 软失败:response.completed 事件里没有图片。记录上游诊断摘要到 ops, @@ -1324,8 +1327,12 @@ func (s *OpenAIGatewayService) handleOpenAIImagesOAuthStreamingResponse( } if len(pendingResults) > 0 { eventName := streamPrefix + ".completed" - for _, img := range pendingResults { - mergeOpenAIResponsesImageMeta(&img, streamMeta) + finalResults := append([]openAIResponsesImageResult(nil), pendingResults...) + for i := range finalResults { + mergeOpenAIResponsesImageMeta(&finalResults[i], streamMeta) + } + reconcileOpenAIResponsesImageResultSizes(finalResults, nil) + for _, img := range finalResults { key := openAIResponsesImageResultKey("", img) if _, exists := emitted[key]; exists { continue @@ -1335,7 +1342,7 @@ func (s *OpenAIGatewayService) handleOpenAIImagesOAuthStreamingResponse( s.tryWriteOpenAIImagesStreamEvent(c, flusher, &clientDisconnected, &lastDownstreamWriteAt, eventName, payload) } imageCount = len(emitted) - imageOutputSizes = openAIResponsesImageResultSizes(pendingResults) + imageOutputSizes = openAIResponsesImageResultSizes(finalResults) return nil } @@ -1564,6 +1571,14 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesOAuth( if resp.StatusCode >= 400 { respBody := s.readUpstreamErrorBody(resp) _ = resp.Body.Close() + respBody = s.redactAgentIdentitySensitiveBody(upstreamCtx, account, respBody) + if !agentIdentityTaskRecoveryWasTried(ctx) && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, respBody) { + expectedTaskID := account.GetCredential("task_id") + if err := s.recoverAgentIdentityTask(ctx, account, expectedTaskID); err != nil { + return nil, fmt.Errorf("agent identity task recovery failed: %w", err) + } + return s.forwardOpenAIImagesOAuth(markAgentIdentityTaskRecoveryTried(ctx), c, account, parsed, channelMappedModel) + } resp.Body = io.NopCloser(bytes.NewReader(respBody)) upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody)) upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg) diff --git a/backend/internal/service/openai_oauth_passthrough_test.go b/backend/internal/service/openai_oauth_passthrough_test.go index 0aa536f94f..5fc5d2996a 100644 --- a/backend/internal/service/openai_oauth_passthrough_test.go +++ b/backend/internal/service/openai_oauth_passthrough_test.go @@ -41,6 +41,16 @@ type passthroughErrReadCloser struct { err error } +type passthroughCloseTrackingReadCloser struct { + io.Reader + closed bool +} + +func (r *passthroughCloseTrackingReadCloser) Close() error { + r.closed = true + return nil +} + func (r passthroughErrReadCloser) Read(_ []byte) (int, error) { if r.err != nil { return 0, r.err @@ -995,7 +1005,7 @@ func TestOpenAIGatewayService_OAuthPassthrough_UpstreamErrorIncludesPassthroughF _, err := svc.Forward(context.Background(), c, account, originalBody) require.Error(t, err) - require.True(t, c.Writer.Written(), "非 429/529 的 passthrough 错误应继续原样写回客户端") + require.True(t, c.Writer.Written(), "非 429/529 的 passthrough 错误应直接写回客户端") require.Equal(t, http.StatusBadRequest, rec.Code) // should append an upstream error event with passthrough=true @@ -1008,6 +1018,255 @@ func TestOpenAIGatewayService_OAuthPassthrough_UpstreamErrorIncludesPassthroughF require.Equal(t, "http_error", arr[len(arr)-1].Kind) } +func TestOpenAIGatewayService_APIKeyPassthrough_RebuildsUpstreamErrors(t *testing.T) { + gin.SetMode(gin.TestMode) + + tests := []struct { + name string + statusCode int + contentType string + responseBody string + retryAfter string + wantStatus int + wantMessage string + wantRetryAfter string + }{ + { + name: "upstream forbidden is reported as gateway failure", + statusCode: http.StatusForbidden, + contentType: "text/html; charset=UTF-8", + responseBody: `secret-upstream.example denied the request`, + retryAfter: "17", + wantStatus: http.StatusBadGateway, + wantMessage: "Upstream access denied", + wantRetryAfter: "17", + }, + { + name: "upstream unauthorized is reported as gateway failure", + statusCode: http.StatusUnauthorized, + contentType: "application/json", + responseBody: `{"error":{"message":"invalid secret-upstream.example token","type":"authentication_error","code":"invalid_api_key","param":"api_key"},"rate_limit":{"remaining":0}}`, + wantStatus: http.StatusBadGateway, + wantMessage: "Upstream authentication failed", + }, + // 瞬时 5xx(500/502/503/504/520-524)对 API-key 账号已改走多账号 + // failover(见 APIKeyPassthrough_Transient5xxTriggersFailover),此处 + // 改用非瞬时 5xx 状态码,继续覆盖净化重建路径。 + { + name: "html 5xx", + statusCode: 530, + contentType: "text/html; charset=UTF-8", + responseBody: `secret-upstream.example | 530: Origin DNS error`, + wantStatus: 530, + wantMessage: "Upstream service temporarily unavailable", + }, + { + name: "structured 5xx", + statusCode: http.StatusNotImplemented, + contentType: "application/json", + responseBody: `{"error":{"message":"secret-upstream.example internal failure"}}`, + wantStatus: http.StatusNotImplemented, + wantMessage: "Upstream service temporarily unavailable", + }, + { + name: "unstructured 4xx", + statusCode: http.StatusBadRequest, + contentType: "text/plain", + responseBody: `proxy secret-upstream.example rejected the request`, + wantStatus: http.StatusBadRequest, + wantMessage: "Upstream request failed", + }, + { + name: "malicious valid json 4xx", + statusCode: http.StatusBadRequest, + contentType: "application/json", + responseBody: `{"error":{"message":"secret-upstream.example invalid parameter","type":"invalid_request_error","code":"upstream_secret_code","param":"private_field","internal_token":"sk-upstream-secret"},"rate_limit":{"remaining":0,"reset":"internal-window"},"debug":{"admin":"root"},"redirect":"https://secret-upstream.example/admin"}`, + retryAfter: "not-a-valid-delay", + wantStatus: http.StatusBadRequest, + wantMessage: "Upstream request failed", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil)) + c.Request.Header.Set("User-Agent", "codex_cli_rs/0.1.0") + + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: tt.statusCode, + Header: http.Header{ + "Content-Type": []string{tt.contentType}, + "Location": []string{"https://secret-upstream.example/admin"}, + "Retry-After": []string{tt.retryAfter}, + "Server": []string{"secret-upstream-proxy"}, + "Set-Cookie": []string{"admin_token=secret"}, + "WWW-Authenticate": []string{`Bearer realm="secret-upstream.example"`}, + "X-Admin-Debug": []string{"internal-route=secret-upstream.example"}, + "X-Codex-Primary-Used-Percent": []string{"99"}, + "x-request-id": []string{"rid-sensitive-upstream"}, + }, + Body: io.NopCloser(strings.NewReader(tt.responseBody)), + }} + svc := &OpenAIGatewayService{ + cfg: &config.Config{Gateway: config.GatewayConfig{ForceCodexCLI: false}}, + httpUpstream: upstream, + } + account := &Account{ + ID: 124, + Name: "sensitive-upstream", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{ + "api_key": "sk-test", + "base_url": "https://secret-upstream.example", + }, + Extra: map[string]any{"openai_passthrough": true}, + Status: StatusActive, + Schedulable: true, + } + requestBody := []byte(`{"model":"gpt-5.2","stream":false,"input":"hello"}`) + + _, err := svc.Forward(context.Background(), c, account, requestBody) + + require.Error(t, err) + require.Equal(t, tt.wantStatus, rec.Code) + opsValue, ok := c.Get(OpsUpstreamErrorsKey) + require.True(t, ok) + opsEvents, ok := opsValue.([]*OpsUpstreamErrorEvent) + require.True(t, ok) + require.NotEmpty(t, opsEvents) + require.Equal(t, tt.statusCode, opsEvents[len(opsEvents)-1].UpstreamStatusCode) + require.Contains(t, rec.Header().Get("Content-Type"), "application/json") + require.Equal(t, tt.wantRetryAfter, rec.Header().Get("Retry-After")) + for _, key := range []string{ + "Location", + "Server", + "Set-Cookie", + "WWW-Authenticate", + "X-Admin-Debug", + "X-Codex-Primary-Used-Percent", + "X-Request-Id", + } { + require.Empty(t, rec.Header().Values(key), "sensitive upstream header %s must be dropped", key) + } + require.Equal(t, "upstream_error", gjson.Get(rec.Body.String(), "error.type").String()) + require.Equal(t, tt.wantMessage, gjson.Get(rec.Body.String(), "error.message").String()) + require.False(t, gjson.Get(rec.Body.String(), "error.code").Exists()) + require.False(t, gjson.Get(rec.Body.String(), "error.param").Exists()) + require.False(t, gjson.Get(rec.Body.String(), "rate_limit").Exists()) + require.NotContains(t, rec.Body.String(), "secret-upstream.example") + require.NotContains(t, rec.Body.String(), "sk-upstream-secret") + require.NotContains(t, err.Error(), "secret-upstream.example") + }) + } +} + +func TestWriteOpenAIPassthroughErrorHeaders_StrictRetryAfter(t *testing.T) { + now := time.Now().UTC() + tests := []struct { + name string + raw string + want bool + }{ + {name: "positive delay seconds", raw: "17", want: true}, + {name: "fractional delay", raw: "1.5"}, + {name: "scientific notation", raw: "1e3"}, + {name: "explicit plus sign", raw: "+17"}, + {name: "zero", raw: "0"}, + {name: "negative delay", raw: "-1"}, + {name: "uint64 overflow", raw: "18446744073709551616"}, + {name: "future http date", raw: now.Add(time.Hour).Format(http.TimeFormat), want: true}, + {name: "past http date", raw: now.Add(-time.Hour).Format(http.TimeFormat)}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dst := http.Header{"Retry-After": []string{"stale"}} + writeOpenAIPassthroughErrorHeaders(dst, http.Header{"Retry-After": []string{tt.raw}}) + if tt.want { + require.Equal(t, tt.raw, dst.Get("Retry-After")) + } else { + require.Empty(t, dst.Get("Retry-After")) + } + }) + } +} + +func TestOpenAIGatewayService_APIKeyPassthrough_CompactErrorBeforeKeepaliveIsSingleJSON(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses/compact", bytes.NewReader(nil)) + MarkOpenAICompactClientStream(c) + stop := StartOpenAICompactSSEKeepalive(c, time.Hour) + defer stop() + + svc := &OpenAIGatewayService{ + cfg: &config.Config{Gateway: config.GatewayConfig{ForceCodexCLI: false}}, + httpUpstream: &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusBadRequest, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"secret-upstream.example invalid request"}}`)), + }}, + } + account := &Account{ + ID: 125, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test", "base_url": "https://secret-upstream.example"}, + Extra: map[string]any{"openai_passthrough": true}, Status: StatusActive, Schedulable: true, + } + + _, err := svc.Forward(context.Background(), c, account, []byte(`{"model":"gpt-5.2","input":"hello"}`)) + + require.Error(t, err) + require.Equal(t, http.StatusBadRequest, rec.Code) + require.True(t, gjson.Valid(rec.Body.String())) + require.Equal(t, "upstream_error", gjson.Get(rec.Body.String(), "error.type").String()) + require.NotContains(t, rec.Body.String(), "event:") + require.NotContains(t, rec.Body.String(), ": keepalive") + require.NotContains(t, rec.Body.String(), "secret-upstream.example") +} + +func TestOpenAIGatewayService_APIKeyPassthrough_CompactErrorAfterKeepaliveIsFailedSSE(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses/compact", bytes.NewReader(nil)) + MarkOpenAICompactClientStream(c) + stop := StartOpenAICompactSSEKeepalive(c, keepaliveTestInterval) + defer stop() + waitForKeepaliveBeats() + + svc := &OpenAIGatewayService{ + cfg: &config.Config{Gateway: config.GatewayConfig{ForceCodexCLI: false}}, + httpUpstream: &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusBadRequest, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"secret-upstream.example invalid request"}}`)), + }}, + } + account := &Account{ + ID: 126, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test", "base_url": "https://secret-upstream.example"}, + Extra: map[string]any{"openai_passthrough": true}, Status: StatusActive, Schedulable: true, + } + + _, err := svc.Forward(context.Background(), c, account, []byte(`{"model":"gpt-5.2","input":"hello"}`)) + + require.Error(t, err) + require.Equal(t, http.StatusOK, rec.Code) + require.Contains(t, rec.Result().Header.Get("Content-Type"), "text/event-stream") + events := parseCompactBridgeSSE(t, stripKeepaliveComments(rec.Body.String())) + require.Len(t, events, 1) + require.Equal(t, "response.failed", events[0][0]) + require.Equal(t, "failed", gjson.Get(events[0][1], "response.status").String()) + require.Equal(t, "upstream_error", gjson.Get(events[0][1], "response.error.code").String()) + require.Equal(t, "Upstream request failed", gjson.Get(events[0][1], "response.error.message").String()) + require.NotContains(t, rec.Body.String(), "secret-upstream.example") +} + func TestOpenAIGatewayService_OpenAIPassthrough_RetryableStatusesTriggerFailover(t *testing.T) { gin.SetMode(gin.TestMode) originalBody := []byte(`{"model":"gpt-5.2","stream":false,"instructions":"local-test-instructions","input":[{"type":"text","text":"hi"}]}`) @@ -1194,6 +1453,142 @@ func TestOpenAIGatewayService_OpenAIPassthrough_RetryableStatusesTriggerFailover } } +func TestOpenAIGatewayService_APIKeyPassthrough_Transient5xxTriggersFailover(t *testing.T) { + gin.SetMode(gin.TestMode) + requestBody := []byte(`{"model":"gpt-5.2","stream":false,"input":"hello"}`) + + for _, statusCode := range []int{ + http.StatusInternalServerError, + http.StatusBadGateway, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout, + 520, 521, 522, 523, 524, + } { + t.Run(fmt.Sprintf("status_%d", statusCode), func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil)) + c.Request.Header.Set("User-Agent", "codex_cli_rs/0.1.0") + + upstreamBody := fmt.Sprintf(`{"error":{"message":"temporary upstream failure","status":%d}}`, statusCode) + body := &passthroughCloseTrackingReadCloser{Reader: strings.NewReader(upstreamBody)} + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: statusCode, + Header: http.Header{ + "Content-Type": []string{"application/json"}, + "X-Request-Id": []string{"rid-api-key-5xx"}, + }, + Body: body, + }} + svc := &OpenAIGatewayService{ + cfg: &config.Config{Gateway: config.GatewayConfig{ForceCodexCLI: false}}, + httpUpstream: upstream, + } + account := &Account{ + ID: 124, + Name: "api-key-transient-5xx", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{ + "api_key": "sk-test", + "base_url": "https://api.example.test", + }, + Extra: map[string]any{"openai_passthrough": true}, + Status: StatusActive, + Schedulable: true, + } + + result, err := svc.Forward(context.Background(), c, account, requestBody) + + require.Nil(t, result, "failed attempts must not report usage or success metadata") + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, statusCode, failoverErr.StatusCode) + require.JSONEq(t, upstreamBody, string(failoverErr.ResponseBody)) + require.Equal(t, "rid-api-key-5xx", failoverErr.ResponseHeaders.Get("x-request-id")) + require.False(t, c.Writer.Written(), "failover must happen before downstream output is committed") + require.True(t, body.closed, "the failed upstream response body must be closed") + require.Equal(t, requestBody, upstream.lastBody, "the request body remains available for the outer account retry") + + value, ok := c.Get(OpsUpstreamErrorsKey) + require.True(t, ok) + events, ok := value.([]*OpsUpstreamErrorEvent) + require.True(t, ok) + require.NotEmpty(t, events) + require.Equal(t, "failover", events[len(events)-1].Kind) + require.Equal(t, account.ID, events[len(events)-1].AccountID) + }) + } +} + +func TestOpenAIGatewayService_APIKeyPassthrough_ContextWindow502DoesNotFailover(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil)) + + const upstreamBody = `{"error":{"message":"Your input exceeds the context window of this model. Please adjust your input and try again.","type":"upstream_error"}}` + body := &passthroughCloseTrackingReadCloser{Reader: strings.NewReader(upstreamBody)} + svc := &OpenAIGatewayService{ + cfg: &config.Config{Gateway: config.GatewayConfig{ForceCodexCLI: false}}, + httpUpstream: &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusBadGateway, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: body, + }}, + } + account := &Account{ + ID: 127, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test", "base_url": "https://api.example.test"}, + Extra: map[string]any{"openai_passthrough": true}, Status: StatusActive, Schedulable: true, + } + + result, err := svc.Forward(context.Background(), c, account, []byte(`{"model":"gpt-5.2","input":"hello"}`)) + + require.Nil(t, result) + require.Error(t, err) + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr), "context-window errors are deterministic request failures") + require.True(t, c.Writer.Written()) + require.Equal(t, http.StatusBadGateway, rec.Code) + require.Contains(t, rec.Body.String(), "exceeds the context window") + require.True(t, body.closed) +} + +func TestOpenAIGatewayService_APIKeyPassthrough_PoolModeConfigured5xxRetriesSameAccount(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil)) + + svc := &OpenAIGatewayService{ + cfg: &config.Config{Gateway: config.GatewayConfig{ForceCodexCLI: false}}, + httpUpstream: &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusBadGateway, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"temporary upstream failure"}}`)), + }}, + } + account := &Account{ + ID: 128, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Concurrency: 1, + Credentials: map[string]any{ + "api_key": "sk-test", + "base_url": "https://api.example.test", + "pool_mode": true, + "pool_mode_retry_status_codes": []any{float64(http.StatusBadGateway)}, + }, + Extra: map[string]any{"openai_passthrough": true}, Status: StatusActive, Schedulable: true, + } + + _, err := svc.Forward(context.Background(), c, account, []byte(`{"model":"gpt-5.2","input":"hello"}`)) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.True(t, failoverErr.RetryableOnSameAccount) + require.False(t, c.Writer.Written()) +} + func TestOpenAIGatewayService_OpenAIPassthrough_CompactNetworkErrorsTriggerFailover(t *testing.T) { gin.SetMode(gin.TestMode) diff --git a/backend/internal/service/openai_quota_reset_credits.go b/backend/internal/service/openai_quota_reset_credits.go index 75756976db..9ff7e70f16 100644 --- a/backend/internal/service/openai_quota_reset_credits.go +++ b/backend/internal/service/openai_quota_reset_credits.go @@ -59,7 +59,7 @@ func parseOpenAIRateLimitResetCreditDetails(body []byte) (openAIRateLimitResetCr payload.Data, ) if err != nil { - return openAIRateLimitResetCreditDetails{}, err + return openAIRateLimitResetCreditDetails{AvailableCount: availableCount}, err } } diff --git a/backend/internal/service/openai_quota_reset_credits_test.go b/backend/internal/service/openai_quota_reset_credits_test.go index 5d994602e1..34f87f9a2f 100644 --- a/backend/internal/service/openai_quota_reset_credits_test.go +++ b/backend/internal/service/openai_quota_reset_credits_test.go @@ -82,6 +82,19 @@ func TestQueryUsageResetCreditCountPrecedence(t *testing.T) { wantCount: 5, wantCredits: 1, }, + { + name: "valid detail count survives malformed authoritative list", + usageBody: `{"rate_limit_reset_credits":{"available_count":7,"credits":[{"expires_at":"usage-expiry"}]}}`, + detailBody: `{"available_count":2,"credits":"malformed"}`, + wantCount: 2, + wantCredits: 1, + }, + { + name: "valid detail count creates quota despite malformed authoritative list", + usageBody: `{}`, + detailBody: `{"available_count":2,"credits":"malformed"}`, + wantCount: 2, + }, { name: "negative detail count without list preserves usage", usageBody: `{"rate_limit_reset_credits":{"available_count":4}}`, diff --git a/backend/internal/service/openai_quota_service.go b/backend/internal/service/openai_quota_service.go index 91b511122e..a94d5fe3f8 100644 --- a/backend/internal/service/openai_quota_service.go +++ b/backend/internal/service/openai_quota_service.go @@ -8,6 +8,7 @@ import ( "log/slog" "net/http" "strings" + "sync" "time" infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" @@ -21,6 +22,8 @@ import ( // errors.Is still matches it by identity since ResetCredit returns this var. var ErrSparkShadowResetNotSupported = infraerrors.New(http.StatusConflict, "SPARK_SHADOW_RESET_NOT_SUPPORTED", "spark shadow account does not support credit reset; reset the parent account") +var ErrAgentIdentityResetNotSupported = infraerrors.New(http.StatusConflict, "AGENT_IDENTITY_RESET_NOT_SUPPORTED", "agent identity does not support rate-limit reset credit consumption") + // Endpoints used by the OpenAI/ChatGPT/Codex quota query and reset feature. const ( chatGPTUsageURL = "https://chatgpt.com/backend-api/wham/usage" @@ -116,6 +119,8 @@ type OpenAIQuotaService struct { proxyRepo ProxyRepository tokenProvider *OpenAITokenProvider privacyClientFactory PrivacyClientFactory + agentIdentityTaskMu sync.Mutex + agentIdentityWS agentIdentityWSConnectionInvalidator } // NewOpenAIQuotaService constructs a quota service. token provider is required — @@ -151,21 +156,36 @@ func (s *OpenAIQuotaService) QueryUsage(ctx context.Context, accountID int64) (* callCtx, cancel := context.WithTimeout(ctx, openaiQuotaUpstreamTimeout) defer cancel() + agentIdentity := s.isAgentIdentityAccount(ctx, accountID) var payload OpenAIQuotaUsage - resp, err := client.R(). - SetContext(callCtx). - SetHeaders(buildCodexCommonHeaders(accessToken, chatGPTAccountID, fedRAMP)). - SetSuccessResult(&payload). - Get(chatGPTUsageURL) - if err != nil { - return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_REQUEST_FAILED", "upstream request failed: %v", err) - } - if !resp.IsSuccessState() { - status := resp.StatusCode - body := truncate(resp.String(), 240) - slog.Warn("openai_quota_query_failed", "account_id", accountID, "status", status, "body", body) - return nil, infraerrors.Newf(mapUpstreamStatus(status), "OPENAI_QUOTA_UPSTREAM_ERROR", "upstream returned %d: %s", status, body) + for recovered := false; ; { + quotaHeaders, headerErr := s.buildCodexQuotaHeaders(callCtx, accountID, accessToken, chatGPTAccountID, fedRAMP) + if headerErr != nil { + return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_AUTH_FAILED", "failed to build upstream authentication: %v", headerErr) + } + resp, err := client.R(). + SetContext(callCtx). + SetHeaders(quotaHeaders). + SetSuccessResult(&payload). + Get(chatGPTUsageURL) + if err != nil { + return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_REQUEST_FAILED", "upstream request failed: %v", err) + } + if !resp.IsSuccessState() { + if agentIdentity && !recovered && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, []byte(resp.String())) { + recovered = true + if err := s.recoverAgentIdentityTask(ctx, accountID); err != nil { + return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_AUTH_FAILED", "agent identity task recovery failed: %v", err) + } + continue + } + status := resp.StatusCode + body := truncate(s.redactQuotaErrorBody(ctx, accountID, resp.String()), 240) + slog.Warn("openai_quota_query_failed", "account_id", accountID, "status", status, "body", body) + return nil, infraerrors.Newf(mapUpstreamStatus(status), "OPENAI_QUOTA_UPSTREAM_ERROR", "upstream returned %d: %s", status, body) + } + break } payload.FetchedAt = time.Now().Unix() @@ -189,9 +209,14 @@ func (s *OpenAIQuotaService) QueryUsage(ctx context.Context, accountID int64) (* } func (s *OpenAIQuotaService) queryResetCreditDetails(ctx context.Context, client *req.Client, accessToken, chatGPTAccountID string, fedRAMP bool, accountID int64) *openAIRateLimitResetCreditDetails { + quotaHeaders, headerErr := s.buildCodexQuotaHeaders(ctx, accountID, accessToken, chatGPTAccountID, fedRAMP) + if headerErr != nil { + slog.Warn("openai_quota_reset_credit_details_auth_failed", "account_id", accountID, "error", headerErr) + return nil + } resp, err := client.R(). SetContext(ctx). - SetHeaders(buildCodexCommonHeaders(accessToken, chatGPTAccountID, fedRAMP)). + SetHeaders(quotaHeaders). Get(chatGPTRateLimitCreditsURL) if err != nil { slog.Warn("openai_quota_reset_credit_details_failed", "account_id", accountID, "error", err) @@ -205,7 +230,9 @@ func (s *OpenAIQuotaService) queryResetCreditDetails(ctx context.Context, client details, err := parseOpenAIRateLimitResetCreditDetails(resp.Bytes()) if err != nil { slog.Warn("openai_quota_reset_credit_details_parse_failed", "account_id", accountID, "error", err) - return nil + if details.AvailableCount == nil { + return nil + } } if details.AvailableCount == nil && !details.CreditListPresent { return nil @@ -233,6 +260,9 @@ func (s *OpenAIQuotaService) ResetCredit(ctx context.Context, accountID int64) ( if acc.IsShadow() { return nil, ErrSparkShadowResetNotSupported } + if acc.IsOpenAIAgentIdentity() { + return nil, ErrAgentIdentityResetNotSupported + } } accessToken, chatGPTAccountID, proxyURL, fedRAMP, err := s.prepareUpstreamCall(ctx, accountID) @@ -252,11 +282,12 @@ func (s *OpenAIQuotaService) ResetCredit(ctx context.Context, accountID int64) ( callCtx, cancel := context.WithTimeout(ctx, openaiQuotaUpstreamTimeout) defer cancel() - - headers := buildCodexCommonHeaders(accessToken, chatGPTAccountID, fedRAMP) - headers["content-type"] = "application/json" - var payload OpenAIQuotaResetResult + headers, headerErr := s.buildCodexQuotaHeaders(callCtx, accountID, accessToken, chatGPTAccountID, fedRAMP) + if headerErr != nil { + return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_AUTH_FAILED", "failed to build upstream authentication: %v", headerErr) + } + headers["content-type"] = "application/json" resp, err := client.R(). SetContext(callCtx). SetHeaders(headers). @@ -268,7 +299,7 @@ func (s *OpenAIQuotaService) ResetCredit(ctx context.Context, accountID int64) ( } if !resp.IsSuccessState() { status := resp.StatusCode - body := truncate(resp.String(), 240) + body := truncate(s.redactQuotaErrorBody(callCtx, accountID, resp.String()), 240) slog.Warn("openai_quota_reset_failed", "account_id", accountID, "status", status, "body", body) return nil, infraerrors.Newf(mapUpstreamStatus(status), "OPENAI_QUOTA_RESET_UPSTREAM_ERROR", "upstream returned %d: %s", status, body) } @@ -285,7 +316,7 @@ func (s *OpenAIQuotaService) ResetCredit(ctx context.Context, accountID int64) ( // token via the shared TokenProvider, and resolves the chatgpt-account-id and // proxy URL. Centralized so QueryUsage / ResetCredit share validation. func (s *OpenAIQuotaService) prepareUpstreamCall(ctx context.Context, accountID int64) (accessToken, chatGPTAccountID, proxyURL string, fedRAMP bool, err error) { - if s == nil || s.accountRepo == nil || s.tokenProvider == nil || s.privacyClientFactory == nil { + if s == nil || s.accountRepo == nil || s.privacyClientFactory == nil { return "", "", "", false, infraerrors.New(http.StatusInternalServerError, "OPENAI_QUOTA_NOT_CONFIGURED", "openai quota service is not configured") } @@ -323,12 +354,17 @@ func (s *OpenAIQuotaService) prepareUpstreamCall(ctx context.Context, accountID return "", "", "", false, infraerrors.New(http.StatusBadRequest, "OPENAI_QUOTA_MISSING_ACCOUNT_ID", "chatgpt_account_id is missing; please re-authorize this account") } - accessToken, err = s.tokenProvider.GetAccessToken(ctx, account) - if err != nil { - return "", "", "", false, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_TOKEN_UNAVAILABLE", "failed to acquire access token: %v", err) - } - if strings.TrimSpace(accessToken) == "" { - return "", "", "", false, infraerrors.New(http.StatusBadGateway, "OPENAI_QUOTA_TOKEN_UNAVAILABLE", "access token is empty") + if !account.IsOpenAIAgentIdentity() { + if s.tokenProvider == nil { + return "", "", "", false, infraerrors.New(http.StatusInternalServerError, "OPENAI_QUOTA_NOT_CONFIGURED", "openai quota token provider is not configured") + } + accessToken, err = s.tokenProvider.GetAccessToken(ctx, account) + if err != nil { + return "", "", "", false, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_TOKEN_UNAVAILABLE", "failed to acquire access token: %v", err) + } + if strings.TrimSpace(accessToken) == "" { + return "", "", "", false, infraerrors.New(http.StatusBadGateway, "OPENAI_QUOTA_TOKEN_UNAVAILABLE", "access token is empty") + } } fedRAMP = account.IsChatGPTAccountFedRAMP() @@ -351,6 +387,91 @@ func (s *OpenAIQuotaService) prepareUpstreamCall(ctx context.Context, accountID return accessToken, chatGPTAccountID, proxyURL, fedRAMP, nil } +func (s *OpenAIQuotaService) recoverAgentIdentityTask(ctx context.Context, accountID int64) error { + if s == nil || s.accountRepo == nil { + return fmt.Errorf("account repository is unavailable") + } + account, err := s.accountRepo.GetByID(ctx, accountID) + if err != nil || account == nil { + return fmt.Errorf("account is unavailable") + } + if account.IsShadow() { + account, err = resolveCredentialAccount(ctx, s.accountRepo, account) + if err != nil || account == nil { + return fmt.Errorf("credential account is unavailable") + } + } + if !account.IsOpenAIAgentIdentity() { + return nil + } + return ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, account, account.GetCredential("task_id")) +} + +func (s *OpenAIQuotaService) isAgentIdentityAccount(ctx context.Context, accountID int64) bool { + if s == nil || s.accountRepo == nil { + return false + } + account, err := s.accountRepo.GetByID(ctx, accountID) + if err != nil || account == nil { + return false + } + if account.IsShadow() { + account, err = resolveCredentialAccount(ctx, s.accountRepo, account) + if err != nil || account == nil { + return false + } + } + return account.IsOpenAIAgentIdentity() +} + +func (s *OpenAIQuotaService) buildCodexQuotaHeaders(ctx context.Context, accountID int64, accessToken, chatGPTAccountID string, fedRAMP bool) (map[string]string, error) { + headers := buildCodexCommonHeaders(accessToken, chatGPTAccountID, fedRAMP) + if s == nil || s.accountRepo == nil { + return headers, nil + } + account, err := s.accountRepo.GetByID(ctx, accountID) + if err != nil || account == nil { + if strings.TrimSpace(accessToken) == "" { + return nil, fmt.Errorf("agent identity account credentials are unavailable") + } + return headers, nil + } + if account.IsShadow() { + if resolved, resolveErr := resolveCredentialAccount(ctx, s.accountRepo, account); resolveErr == nil && resolved != nil { + account = resolved + } else if strings.TrimSpace(accessToken) == "" { + return nil, fmt.Errorf("agent identity shadow credentials are unavailable") + } + } + if !account.IsOpenAIAgentIdentity() { + return headers, nil + } + if err := ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, account, ""); err != nil { + return nil, err + } + key, err := agentIdentityKeyFromAccount(account) + if err != nil { + return nil, err + } + assertion, err := buildAgentAssertion(key, time.Now()) + if err != nil { + return nil, err + } + headers["authorization"] = assertion + return headers, nil +} + +func (s *OpenAIQuotaService) redactQuotaErrorBody(ctx context.Context, accountID int64, body string) string { + if s == nil || s.accountRepo == nil { + return body + } + account, err := s.accountRepo.GetByID(ctx, accountID) + if err != nil || account == nil { + return body + } + return string(redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, account, []byte(body))) +} + // buildCodexCommonHeaders sets the request headers expected by the chatgpt.com // backend so calls succeed past Cloudflare/WASM checks. func buildCodexCommonHeaders(accessToken, chatGPTAccountID string, fedRAMP bool) map[string]string { diff --git a/backend/internal/service/openai_quota_spark_window_test.go b/backend/internal/service/openai_quota_spark_window_test.go index 213669f5e6..c521b149e9 100644 --- a/backend/internal/service/openai_quota_spark_window_test.go +++ b/backend/internal/service/openai_quota_spark_window_test.go @@ -2,6 +2,10 @@ package service import ( "context" + "crypto/ed25519" + "crypto/rand" + "crypto/x509" + "encoding/base64" "encoding/json" "errors" "fmt" @@ -34,6 +38,15 @@ func (r *stubQuotaAccountRepo) GetByID(_ context.Context, id int64) (*Account, e return acc, nil } +func (r *stubQuotaAccountRepo) UpdateCredentials(_ context.Context, id int64, credentials map[string]any) error { + acc, ok := r.accounts[id] + if !ok { + return fmt.Errorf("account %d not found", id) + } + acc.Credentials = credentials + return nil +} + // stubQuotaTokenCache 实现 OpenAITokenCache,返回预设静态 token。 type stubQuotaTokenCache struct { tokens map[string]string @@ -163,6 +176,23 @@ func TestResetCreditShadowRejected(t *testing.T) { "shadow ResetCredit 应映射为 409 Conflict 而非 500") } +func TestResetCreditAgentIdentityRejectedBeforeUpstream(t *testing.T) { + account := &Account{ + ID: 201, + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + }, + } + repo := &stubQuotaAccountRepo{accounts: map[int64]*Account{account.ID: account}} + svc := &OpenAIQuotaService{accountRepo: repo} + + _, err := svc.ResetCredit(context.Background(), account.ID) + require.ErrorIs(t, err, ErrAgentIdentityResetNotSupported) + require.Equal(t, http.StatusConflict, infraerrors.Code(err)) +} + // ── Part B: prepareUpstreamCall 影子 resolve ────────────────────────────── // TestPrepareUpstreamCallShadowResolve 验证影子账号(200)QueryUsage 时: @@ -214,6 +244,101 @@ func TestPrepareUpstreamCallShadowResolve(t *testing.T) { "prepareUpstreamCall should use parent's chatgpt_account_id after shadow resolve") } +func TestQueryUsageAgentIdentityUsesAssertionWithoutOAuthToken(t *testing.T) { + _, privateKey, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + der, err := x509.MarshalPKCS8PrivateKey(privateKey) + require.NoError(t, err) + account := &Account{ + ID: 300, + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": "runtime-quota", + "agent_private_key": base64.StdEncoding.EncodeToString(der), + "task_id": "task-quota", + "chatgpt_account_id": "account-quota", + "chatgpt_account_is_fedramp": true, + }, + } + repo := &stubQuotaAccountRepo{accounts: map[int64]*Account{account.ID: account}} + var authorization string + var accountHeader string + var fedrampHeader string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + authorization = r.Header.Get("authorization") + accountHeader = r.Header.Get("chatgpt-account-id") + fedrampHeader = r.Header.Get("x-openai-fedramp") + w.Header().Set("content-type", "application/json") + _, _ = w.Write([]byte(`{"plan_type":"pro","rate_limit":{"allowed":true}}`)) + })) + defer srv.Close() + svc := NewOpenAIQuotaService(repo, nil, nil, newQuotaRedirectingFactory(srv)) + usage, err := svc.QueryUsage(context.Background(), account.ID) + require.NoError(t, err) + require.NotNil(t, usage) + require.True(t, strings.HasPrefix(authorization, "AgentAssertion ")) + require.Equal(t, "account-quota", accountHeader) + require.Equal(t, "true", fedrampHeader) +} + +func TestQueryUsageAgentIdentityRecoversInvalidTaskOnce(t *testing.T) { + _, privateKey, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + der, err := x509.MarshalPKCS8PrivateKey(privateKey) + require.NoError(t, err) + account := &Account{ + ID: 301, + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": "runtime-quota-recovery", + "agent_private_key": base64.StdEncoding.EncodeToString(der), + "task_id": "task-quota-old", + "chatgpt_account_id": "account-quota-recovery", + }, + } + repo := &stubQuotaAccountRepo{accounts: map[int64]*Account{account.ID: account}} + usageCalls := 0 + registerCalls := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("content-type", "application/json") + if strings.Contains(r.URL.Path, "/task/register") { + registerCalls++ + _, _ = w.Write([]byte(`{"task_id":"task-quota-new"}`)) + return + } + if strings.Contains(r.URL.Path, "rate-limit-reset-credits") { + _, _ = w.Write([]byte(`{}`)) + return + } + usageCalls++ + if usageCalls == 1 { + w.WriteHeader(http.StatusUnauthorized) + _, _ = w.Write([]byte(`{"error":{"code":"invalid_task_id"}}`)) + return + } + _, _ = w.Write([]byte(`{"plan_type":"pro","rate_limit":{"allowed":true}}`)) + })) + defer srv.Close() + oldBase := openAIAgentIdentityAuthAPIBaseURL + openAIAgentIdentityAuthAPIBaseURL = srv.URL + t.Cleanup(func() { openAIAgentIdentityAuthAPIBaseURL = oldBase }) + + invalidator := &agentIdentityWSInvalidationRecorder{} + svc := NewOpenAIQuotaService(repo, nil, nil, newQuotaRedirectingFactory(srv)) + svc.agentIdentityWS = invalidator + usage, err := svc.QueryUsage(context.Background(), account.ID) + require.NoError(t, err) + require.NotNil(t, usage) + require.Equal(t, 2, usageCalls) + require.Equal(t, 1, registerCalls) + require.Equal(t, "task-quota-new", account.GetCredential("task_id")) + require.Equal(t, []int64{account.ID}, invalidator.accountIDs) +} + func TestParseOpenAIRateLimitResetCreditDetails_CompatibleContainers(t *testing.T) { tests := []struct { name string diff --git a/backend/internal/service/openai_responses_lite_tools.go b/backend/internal/service/openai_responses_lite_tools.go new file mode 100644 index 0000000000..a15bc498bc --- /dev/null +++ b/backend/internal/service/openai_responses_lite_tools.go @@ -0,0 +1,191 @@ +package service + +import ( + "encoding/json" + "fmt" + "reflect" + "strings" +) + +// normalizeOpenAIResponsesLiteTools converts private namespace declarations +// into the input.additional_tools carrier required by Responses Lite. Other +// top-level tools must belong to the small set accepted by the Lite endpoint; +// rejecting unsupported hosted tools is intentional because silently dropping +// them would change the client's requested behavior. +func normalizeOpenAIResponsesLiteTools(reqBody map[string]any) (bool, error) { + if reqBody == nil { + return false, nil + } + rawTools, exists := reqBody["tools"] + if !exists || rawTools == nil { + return false, nil + } + tools, ok := rawTools.([]any) + if !ok { + return false, fmt.Errorf("responses Lite requires tools to be an array") + } + + topLevelTools := make([]any, 0, len(tools)) + namespaceTools := make([]any, 0, len(tools)) + for index, rawTool := range tools { + if customTool, ok := rawTool.(string); ok { + if strings.TrimSpace(customTool) == "" { + return false, fmt.Errorf("responses Lite custom tool at index %d must not be empty", index) + } + topLevelTools = append(topLevelTools, rawTool) + continue + } + tool, ok := rawTool.(map[string]any) + if !ok { + return false, fmt.Errorf("responses Lite tool at index %d must be an object", index) + } + toolType := strings.TrimSpace(firstNonEmptyString(tool["type"])) + switch toolType { + case "function", "custom", "tool_search": + topLevelTools = append(topLevelTools, rawTool) + case "namespace": + namespaceTools = append(namespaceTools, rawTool) + case "": + return false, fmt.Errorf("responses Lite tool at index %d is missing type", index) + default: + return false, fmt.Errorf("responses Lite does not support top-level tool type %q at index %d", toolType, index) + } + } + if len(namespaceTools) == 0 { + return false, nil + } + + input, err := appendOpenAIResponsesLiteAdditionalTools(reqBody["input"], namespaceTools) + if err != nil { + return false, err + } + reqBody["input"] = input + if len(topLevelTools) == 0 { + delete(reqBody, "tools") + } else { + reqBody["tools"] = topLevelTools + } + return true, nil +} + +func appendOpenAIResponsesLiteAdditionalTools(input any, namespaceTools []any) ([]any, error) { + var items []any + switch typed := input.(type) { + case nil: + items = make([]any, 0, 1) + case string: + items = []any{map[string]any{ + "type": "message", + "role": "user", + "content": typed, + }} + case []any: + items = typed + default: + return nil, fmt.Errorf("responses Lite namespace tools require input to be a string or array") + } + + var target map[string]any + var targetTools []any + var allAdditionalTools []any + for _, rawItem := range items { + item, ok := rawItem.(map[string]any) + if !ok || strings.TrimSpace(firstNonEmptyString(item["type"])) != "additional_tools" { + continue + } + rawAdditionalTools, exists := item["tools"] + additionalTools := []any(nil) + toolsOK := true + if exists && rawAdditionalTools != nil { + additionalTools, toolsOK = rawAdditionalTools.([]any) + } + if !toolsOK { + return nil, fmt.Errorf("responses Lite input.additional_tools tools must be an array") + } + if target == nil { + target = item + targetTools = additionalTools + } + allAdditionalTools = append(allAdditionalTools, additionalTools...) + } + + merged, err := mergeOpenAIResponsesLiteAdditionalTools(allAdditionalTools, namespaceTools) + if err != nil { + return nil, err + } + newTools := merged[len(allAdditionalTools):] + if target != nil { + if len(newTools) > 0 { + target["tools"] = append(append([]any(nil), targetTools...), newTools...) + } + return items, nil + } + + items = append(items, map[string]any{ + "type": "additional_tools", + "role": "developer", + "tools": newTools, + }) + return items, nil +} + +func mergeOpenAIResponsesLiteAdditionalTools(existing []any, moved []any) ([]any, error) { + merged := append([]any(nil), existing...) + seen := make(map[string]any, len(existing)+len(moved)) + for _, rawTool := range existing { + if identity := openAIResponsesLiteToolIdentity(rawTool); identity != "" { + if previous, exists := seen[identity]; exists && !reflect.DeepEqual(previous, rawTool) { + return nil, fmt.Errorf("responses Lite additional_tools contains conflicting definitions for %s", openAIResponsesLiteToolIdentityForError(rawTool)) + } + seen[identity] = rawTool + } + } + for _, rawTool := range moved { + identity := openAIResponsesLiteToolIdentity(rawTool) + if identity != "" { + if previous, exists := seen[identity]; exists { + if reflect.DeepEqual(previous, rawTool) { + continue + } + return nil, fmt.Errorf("responses Lite additional_tools conflicts with migrated %s", openAIResponsesLiteToolIdentityForError(rawTool)) + } + seen[identity] = rawTool + } + merged = append(merged, rawTool) + } + return merged, nil +} + +func openAIResponsesLiteToolIdentity(rawTool any) string { + tool, ok := rawTool.(map[string]any) + if !ok { + return "" + } + toolType := strings.TrimSpace(firstNonEmptyString(tool["type"])) + name := strings.TrimSpace(firstNonEmptyString(tool["name"])) + if toolType == "" || name == "" { + return "" + } + return toolType + "\x00" + name +} + +func openAIResponsesLiteToolIdentityForError(rawTool any) string { + tool, _ := rawTool.(map[string]any) + return fmt.Sprintf("tool type %q name %q", strings.TrimSpace(firstNonEmptyString(tool["type"])), strings.TrimSpace(firstNonEmptyString(tool["name"]))) +} + +func normalizeOpenAIResponsesLiteToolsPayload(body []byte) ([]byte, bool, error) { + var requestBody map[string]any + if err := json.Unmarshal(body, &requestBody); err != nil { + return body, false, fmt.Errorf("decode responses Lite request body: %w", err) + } + changed, err := normalizeOpenAIResponsesLiteTools(requestBody) + if err != nil || !changed { + return body, false, err + } + rebuilt, err := marshalOpenAIUpstreamJSON(requestBody) + if err != nil { + return body, false, fmt.Errorf("encode responses Lite request body: %w", err) + } + return rebuilt, true, nil +} diff --git a/backend/internal/service/openai_responses_lite_tools_test.go b/backend/internal/service/openai_responses_lite_tools_test.go new file mode 100644 index 0000000000..aa03954463 --- /dev/null +++ b/backend/internal/service/openai_responses_lite_tools_test.go @@ -0,0 +1,267 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestNormalizeOpenAIResponsesLiteTools_MovesNamespacesAndKeepsSupportedTools(t *testing.T) { + reqBody := map[string]any{ + "model": "gpt-5.6-terra", + "tools": []any{ + map[string]any{"type": "function", "name": "shell"}, + map[string]any{"type": "custom", "name": "exec"}, + map[string]any{"type": "tool_search"}, + map[string]any{"type": "namespace", "name": "collaboration", "tools": []any{ + map[string]any{"type": "function", "name": "spawn_agent"}, + }}, + }, + "input": []any{ + map[string]any{"type": "message", "role": "user", "content": "hello"}, + map[string]any{"type": "additional_tools", "role": "developer", "tools": []any{ + map[string]any{"type": "namespace", "name": "image_gen"}, + map[string]any{"type": "namespace", "name": "collaboration", "tools": []any{ + map[string]any{"type": "function", "name": "spawn_agent"}, + }}, + }}, + }, + "tool_choice": map[string]any{"type": "namespace", "name": "collaboration"}, + } + + changed, err := normalizeOpenAIResponsesLiteTools(reqBody) + + require.NoError(t, err) + require.True(t, changed) + tools := reqBody["tools"].([]any) + require.Len(t, tools, 3) + require.Equal(t, "function", tools[0].(map[string]any)["type"]) + require.Equal(t, "custom", tools[1].(map[string]any)["type"]) + require.Equal(t, "tool_search", tools[2].(map[string]any)["type"]) + input := reqBody["input"].([]any) + require.Len(t, input, 2) + additional := input[1].(map[string]any)["tools"].([]any) + require.Len(t, additional, 2) + require.Equal(t, "image_gen", additional[0].(map[string]any)["name"]) + require.Equal(t, "collaboration", additional[1].(map[string]any)["name"], "existing namespace must not be duplicated") + require.Equal(t, map[string]any{"type": "namespace", "name": "collaboration"}, reqBody["tool_choice"]) +} + +func TestNormalizeOpenAIResponsesLiteTools_RejectsConflictingAdditionalTool(t *testing.T) { + reqBody := map[string]any{ + "tools": []any{map[string]any{ + "type": "namespace", + "name": "collaboration", + "tools": []any{map[string]any{"type": "function", "name": "spawn_agent"}}, + }}, + "input": []any{map[string]any{ + "type": "additional_tools", + "tools": []any{map[string]any{ + "type": "namespace", + "name": "collaboration", + "tools": []any{map[string]any{"type": "function", "name": "send_message"}}, + }}, + }}, + } + + changed, err := normalizeOpenAIResponsesLiteTools(reqBody) + + require.ErrorContains(t, err, `conflicts with migrated tool type "namespace" name "collaboration"`) + require.False(t, changed) + require.Len(t, reqBody["tools"], 1, "conflicts must not partially remove top-level tools") +} + +func TestNormalizeOpenAIResponsesLiteTools_DeduplicatesAcrossAdditionalToolItems(t *testing.T) { + namespace := map[string]any{ + "type": "namespace", + "name": "collaboration", + "tools": []any{map[string]any{"type": "function", "name": "spawn_agent"}}, + } + reqBody := map[string]any{ + "tools": []any{namespace}, + "input": []any{ + map[string]any{ + "type": "additional_tools", + "tools": []any{map[string]any{"type": "custom", "name": "exec"}}, + }, + map[string]any{ + "type": "additional_tools", + "tools": []any{namespace}, + }, + }, + } + + changed, err := normalizeOpenAIResponsesLiteTools(reqBody) + + require.NoError(t, err) + require.True(t, changed) + require.NotContains(t, reqBody, "tools") + input := reqBody["input"].([]any) + require.Len(t, input[0].(map[string]any)["tools"], 1) + require.Len(t, input[1].(map[string]any)["tools"], 1) +} + +func TestNormalizeOpenAIResponsesLiteTools_ConvertsStringInput(t *testing.T) { + reqBody := map[string]any{ + "input": "hello", + "tools": []any{map[string]any{ + "type": "namespace", + "name": "collaboration", + }}, + } + + changed, err := normalizeOpenAIResponsesLiteTools(reqBody) + + require.NoError(t, err) + require.True(t, changed) + require.NotContains(t, reqBody, "tools") + input := reqBody["input"].([]any) + require.Len(t, input, 2) + require.Equal(t, "message", input[0].(map[string]any)["type"]) + require.Equal(t, "hello", input[0].(map[string]any)["content"]) + require.Equal(t, "additional_tools", input[1].(map[string]any)["type"]) +} + +func TestNormalizeOpenAIResponsesLiteTools_KeepsSupportedTopLevelTools(t *testing.T) { + reqBody := map[string]any{ + "tools": []any{ + map[string]any{"type": "function", "name": "shell"}, + map[string]any{"type": "custom", "name": "exec"}, + map[string]any{"type": "tool_search"}, + "custom shorthand", + }, + } + + changed, err := normalizeOpenAIResponsesLiteTools(reqBody) + + require.NoError(t, err) + require.False(t, changed) + require.Len(t, reqBody["tools"], 4) +} + +func TestNormalizeOpenAIResponsesLiteTools_RejectsUnsupportedTools(t *testing.T) { + tests := []struct { + name string + tool map[string]any + want string + }{ + {name: "hosted web search", tool: map[string]any{"type": "web_search"}, want: `top-level tool type "web_search"`}, + {name: "hosted image generation", tool: map[string]any{"type": "image_generation"}, want: `top-level tool type "image_generation"`}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reqBody := map[string]any{"tools": []any{tt.tool}} + changed, err := normalizeOpenAIResponsesLiteTools(reqBody) + require.ErrorContains(t, err, tt.want) + require.False(t, changed) + require.Len(t, reqBody["tools"], 1, "validation errors must not partially mutate tools") + }) + } +} + +func TestNormalizeOpenAIResponsesLiteToolsPayload_PreservesResponseCreateShape(t *testing.T) { + body := []byte(`{ + "type":"response.create", + "model":"gpt-5.6-terra", + "client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":"true"}, + "input":[{"type":"message","role":"user","content":"hello"}], + "tools":[{"type":"namespace","name":"collaboration","tools":[{"type":"function","name":"spawn_agent"}]}], + "tool_choice":{"type":"namespace","name":"collaboration"} + }`) + + updated, changed, err := normalizeOpenAIResponsesLiteToolsPayload(body) + + require.NoError(t, err) + require.True(t, changed) + require.Equal(t, "response.create", gjson.GetBytes(updated, "type").String()) + require.False(t, gjson.GetBytes(updated, "tools").Exists()) + require.Equal(t, "collaboration", gjson.GetBytes(updated, `input.#(type=="additional_tools").tools.0.name`).String()) + require.Equal(t, "namespace", gjson.GetBytes(updated, "tool_choice.type").String()) +} + +func TestApplyCodexOAuthTransform_PreservesLiteNamespaceToolChoice(t *testing.T) { + reqBody := map[string]any{ + "model": "gpt-5.6-terra", + "input": []any{map[string]any{ + "type": "additional_tools", + "tools": []any{map[string]any{ + "type": "namespace", + "name": "collaboration", + }}, + }}, + "tool_choice": map[string]any{"type": "namespace", "name": "collaboration"}, + } + + applyCodexOAuthTransform(reqBody, true, false) + + require.Equal(t, map[string]any{"type": "namespace", "name": "collaboration"}, reqBody["tool_choice"]) +} + +func TestOpenAIGatewayServiceForward_NormalizesResponsesLiteToolsForOAuth(t *testing.T) { + gin.SetMode(gin.TestMode) + + for _, passthrough := range []bool{false, true} { + name := "managed" + if passthrough { + name = "passthrough" + } + t.Run(name, func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil)) + c.Request.Header.Set("User-Agent", "codex_cli_rs/0.144.1") + c.Request.Header.Set(responsesLiteHeader, "true") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader( + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_lite\",\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n" + + "data: [DONE]\n\n", + )), + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := &Account{ + ID: 501, Name: "responses-lite", Platform: PlatformOpenAI, Type: AccountTypeOAuth, + Concurrency: 1, Status: StatusActive, Schedulable: true, RateMultiplier: f64p(1), + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-account"}, + Extra: map[string]any{"openai_passthrough": passthrough}, + } + body := []byte(`{ + "model":"gpt-5.6-terra","stream":true,"instructions":"test", + "tools":[ + {"type":"function","name":"shell","parameters":{"type":"object"}}, + {"type":"custom","name":"exec"}, + {"type":"tool_search"}, + {"type":"namespace","name":"collaboration","tools":[{"type":"function","name":"spawn_agent","parameters":{"type":"object"}}]} + ], + "input":[{"type":"message","role":"user","content":"hello"}], + "tool_choice":{"type":"namespace","name":"collaboration"} + }`) + + result, err := svc.Forward(context.Background(), c, account, body) + + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, "true", upstream.lastReq.Header.Get(responsesLiteHeader)) + require.False(t, gjson.GetBytes(upstream.lastBody, `tools.#(type=="namespace")`).Exists()) + require.Equal(t, "shell", gjson.GetBytes(upstream.lastBody, `tools.#(type=="function").name`).String()) + require.Equal(t, "exec", gjson.GetBytes(upstream.lastBody, `tools.#(type=="custom").name`).String()) + require.True(t, gjson.GetBytes(upstream.lastBody, `tools.#(type=="tool_search")`).Exists()) + require.Equal(t, "collaboration", gjson.GetBytes(upstream.lastBody, `input.#(type=="additional_tools").tools.0.name`).String()) + require.Equal(t, "namespace", gjson.GetBytes(upstream.lastBody, "tool_choice.type").String()) + require.Equal(t, "collaboration", gjson.GetBytes(upstream.lastBody, "tool_choice.name").String()) + }) + } +} diff --git a/backend/internal/service/openai_sse_concatenated_json_test.go b/backend/internal/service/openai_sse_concatenated_json_test.go new file mode 100644 index 0000000000..9b06ef9a39 --- /dev/null +++ b/backend/internal/service/openai_sse_concatenated_json_test.go @@ -0,0 +1,271 @@ +package service + +import ( + "bufio" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestOpenAIStreamingRepairsConcatenatedJSONDocumentsInSingleDataLine(t *testing.T) { + testOpenAIStreamingRepairsConcatenatedJSONDocuments(t, false, 0) +} + +func TestOpenAIStreamingAsyncScannerRepairsConcatenatedJSONDocumentsInSingleDataLine(t *testing.T) { + testOpenAIStreamingRepairsConcatenatedJSONDocuments(t, false, 30) +} + +func TestOpenAIStreamingPassthroughRepairsConcatenatedJSONDocumentsInSingleDataLine(t *testing.T) { + testOpenAIStreamingRepairsConcatenatedJSONDocuments(t, true, 0) +} + +func TestOpenAIWSv2StreamingRepairsConcatenatedJSONDocumentsInSingleMessage(t *testing.T) { + gin.SetMode(gin.TestMode) + + largeInProgress, outputItemAdded, completed := openAIConcatenatedJSONTestEvents(t) + captureConn := &openAIWSCaptureConn{events: [][]byte{ + []byte(largeInProgress + outputItemAdded), + []byte(completed), + }} + + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = false + cfg.Gateway.OpenAIWS.Enabled = true + cfg.Gateway.OpenAIWS.APIKeyEnabled = true + cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true + cfg.Gateway.OpenAIWS.MaxConnsPerAccount = 1 + cfg.Gateway.OpenAIWS.MaxIdlePerAccount = 1 + cfg.Gateway.OpenAIWS.QueueLimitPerConn = 8 + cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3 + cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 5 + cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3 + + pool := newOpenAIWSConnPool(cfg) + pool.setClientDialerForTest(&openAIWSCaptureDialer{conn: captureConn}) + svc := &OpenAIGatewayService{ + cfg: cfg, + cache: &stubGatewayCache{}, + httpUpstream: &httpUpstreamRecorder{}, + openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), + openaiWSPool: pool, + toolCorrector: NewCodexToolCorrector(), + } + account := &Account{ + ID: 2, + Name: "ws-test", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{"responses_websockets_v2_enabled": true}, + } + + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + groupID := int64(1) + c.Set("api_key", &APIKey{GroupID: &groupID}) + + result, err := svc.Forward(context.Background(), c, account, []byte(`{"model":"gpt-5.6-sol","stream":true,"input":"hello"}`)) + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, 7, result.Usage.InputTokens) + require.Equal(t, 9, result.Usage.OutputTokens) + require.Nil(t, result.FirstTokenMs) + assertOpenAISSEFrames(t, recorder.Body.String(), []string{ + "response.in_progress", + "response.output_item.added", + "response.completed", + }) +} + +func TestSplitOpenAIConcatenatedJSONDocumentsRejectsPayloadOverRepairLimit(t *testing.T) { + first := `{"type":"response.in_progress","padding":"` + strings.Repeat("x", 16*1024*1024) + `"}` + second := `{"type":"response.completed"}` + payload := first + second + + documents, repaired := splitOpenAIConcatenatedJSONDocuments([]byte(payload)) + require.False(t, repaired) + require.Nil(t, documents) + + line := "data: " + payload + scanner := bufio.NewScanner(strings.NewReader(line)) + scanner.Buffer(make([]byte, 1024), len(line)+1) + documentScanner := newOpenAISSEJSONDocumentScanner(scanner) + require.True(t, documentScanner.Scan()) + require.Equal(t, line, documentScanner.Text()) + require.False(t, documentScanner.Scan()) + require.NoError(t, documentScanner.Err()) +} + +func TestOpenAIWSv2StreamingBreaksConnectionWhenTerminalHasTrailingDocument(t *testing.T) { + gin.SetMode(gin.TestMode) + completed := `{"type":"response.completed","response":{"id":"resp_terminal_tail","usage":{"input_tokens":2,"output_tokens":1}}}` + tail := `{"type":"error","error":{"type":"upstream_error","message":"tail"}}` + captureConn := &openAIWSCaptureConn{events: [][]byte{[]byte(completed + tail)}} + + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = false + cfg.Gateway.OpenAIWS.Enabled = true + cfg.Gateway.OpenAIWS.APIKeyEnabled = true + cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true + cfg.Gateway.OpenAIWS.MaxConnsPerAccount = 1 + cfg.Gateway.OpenAIWS.MaxIdlePerAccount = 1 + cfg.Gateway.OpenAIWS.QueueLimitPerConn = 8 + cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3 + cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 5 + cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3 + + pool := newOpenAIWSConnPool(cfg) + pool.setClientDialerForTest(&openAIWSCaptureDialer{conn: captureConn}) + svc := &OpenAIGatewayService{ + cfg: cfg, + cache: &stubGatewayCache{}, + httpUpstream: &httpUpstreamRecorder{}, + openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), + openaiWSPool: pool, + toolCorrector: NewCodexToolCorrector(), + } + account := &Account{ + ID: 3, + Name: "ws-terminal-tail", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{"responses_websockets_v2_enabled": true}, + } + + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + groupID := int64(1) + c.Set("api_key", &APIKey{GroupID: &groupID}) + + result, err := svc.Forward(context.Background(), c, account, []byte(`{"model":"gpt-5.6-sol","stream":true,"input":"hello"}`)) + require.NoError(t, err) + require.NotNil(t, result) + require.True(t, captureConn.closed, "a WS message with data after a terminal event must not return to the pool") + assertOpenAISSEFrames(t, recorder.Body.String(), []string{"response.completed"}) +} + +func testOpenAIStreamingRepairsConcatenatedJSONDocuments(t *testing.T, passthrough bool, streamDataIntervalTimeout int) { + t.Helper() + gin.SetMode(gin.TestMode) + + largeInProgress, outputItemAdded, completed := openAIConcatenatedJSONTestEvents(t) + + upstreamBody := strings.Join([]string{ + "event: response.in_progress", + "data: " + largeInProgress + outputItemAdded, + "", + "event: response.completed", + "data: " + completed, + "", + }, "\n") + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + } + + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + svc := &OpenAIGatewayService{ + cfg: &config.Config{Gateway: config.GatewayConfig{ + MaxLineSize: defaultMaxLineSize, + StreamDataIntervalTimeout: streamDataIntervalTimeout, + }}, + toolCorrector: NewCodexToolCorrector(), + } + account := &Account{ID: 1, Name: "test", Platform: PlatformOpenAI} + + var usage *OpenAIUsage + var err error + if passthrough { + result, forwardErr := svc.handleStreamingResponsePassthrough(c.Request.Context(), resp, c, account, time.Now(), "gpt-5.6-sol", "gpt-5.6-sol") + err = forwardErr + if result != nil { + usage = result.usage + } + } else { + result, forwardErr := svc.handleStreamingResponse(c.Request.Context(), resp, c, account, time.Now(), "gpt-5.6-sol", "gpt-5.6-sol") + err = forwardErr + if result != nil { + usage = result.usage + } + } + require.NoError(t, err) + require.NotNil(t, usage) + require.Equal(t, 7, usage.InputTokens) + require.Equal(t, 9, usage.OutputTokens) + + assertOpenAISSEFrames(t, recorder.Body.String(), []string{ + "response.in_progress", + "response.output_item.added", + "response.completed", + }) +} + +func assertOpenAISSEFrames(t *testing.T, body string, expectedTypes []string) { + t.Helper() + var parser openAICompatSSEFrameParser + var eventTypes []string + for _, line := range strings.Split(body, "\n") { + frame, ok := parser.AddLine(strings.TrimSuffix(line, "\r")) + if !ok { + continue + } + require.True(t, json.Valid([]byte(frame.Data)), "each downstream SSE frame must contain exactly one JSON document") + var event struct { + Type string `json:"type"` + } + require.NoError(t, json.Unmarshal([]byte(frame.Data), &event)) + if frame.EventType != "" { + require.Equal(t, event.Type, frame.EventType) + } + eventTypes = append(eventTypes, event.Type) + } + if frame, ok := parser.Finish(); ok { + require.True(t, json.Valid([]byte(frame.Data))) + var event struct { + Type string `json:"type"` + } + require.NoError(t, json.Unmarshal([]byte(frame.Data), &event)) + eventTypes = append(eventTypes, event.Type) + } + require.Equal(t, expectedTypes, eventTypes) +} + +func openAIConcatenatedJSONTestEvents(t *testing.T) (string, string, string) { + t.Helper() + const javascriptErrorPosition = 68106 + prefix := `{"type":"response.in_progress","response":{"id":"resp_large","status":"in_progress","instructions":"` + suffix := `"},"sequence_number":1}` + require.Less(t, len(prefix)+len(suffix), javascriptErrorPosition) + largeInProgress := prefix + strings.Repeat("x", javascriptErrorPosition-len(prefix)-len(suffix)) + suffix + outputItemAdded := `{"type":"response.output_item.added","output_index":0,"item":{"id":"msg_1","type":"message","role":"assistant","status":"in_progress","content":[]},"sequence_number":2}` + completed := `{"type":"response.completed","response":{"id":"resp_large","status":"completed","output":[],"usage":{"input_tokens":7,"output_tokens":9}},"sequence_number":3}` + require.Len(t, largeInProgress, javascriptErrorPosition) + require.True(t, json.Valid([]byte(largeInProgress))) + var decoded any + err := json.Unmarshal([]byte(largeInProgress+outputItemAdded), &decoded) + var syntaxErr *json.SyntaxError + require.ErrorAs(t, err, &syntaxErr) + require.Equal(t, int64(javascriptErrorPosition+1), syntaxErr.Offset) + return largeInProgress, outputItemAdded, completed +} diff --git a/backend/internal/service/openai_sse_json_documents.go b/backend/internal/service/openai_sse_json_documents.go new file mode 100644 index 0000000000..3f6fa28fa8 --- /dev/null +++ b/backend/internal/service/openai_sse_json_documents.go @@ -0,0 +1,115 @@ +package service + +import ( + "bufio" + "bytes" + "encoding/json" + "io" + "strings" +) + +const ( + maxOpenAIConcatenatedJSONDocuments = 16 + maxOpenAIConcatenatedJSONBytes = 16 * 1024 * 1024 +) + +// splitOpenAIConcatenatedJSONDocuments recognizes the narrow corruption shape +// produced when multiple complete Responses events arrive in one transport +// message. Other malformed payloads are left untouched for normal error paths. +func splitOpenAIConcatenatedJSONDocuments(payload []byte) ([][]byte, bool) { + payload = bytes.TrimSpace(payload) + if len(payload) == 0 || len(payload) > maxOpenAIConcatenatedJSONBytes || json.Valid(payload) { + return nil, false + } + + decoder := json.NewDecoder(bytes.NewReader(payload)) + documents := make([][]byte, 0, 2) + for { + var raw json.RawMessage + err := decoder.Decode(&raw) + if err != nil { + if err == io.EOF && len(documents) > 1 { + return documents, true + } + return nil, false + } + raw = bytes.TrimSpace(raw) + var envelope struct { + Type string `json:"type"` + } + if err := json.Unmarshal(raw, &envelope); err != nil { + return nil, false + } + eventType := strings.TrimSpace(envelope.Type) + if eventType == "" || strings.ContainsAny(eventType, "\r\n") { + return nil, false + } + if len(documents) == maxOpenAIConcatenatedJSONDocuments { + return nil, false + } + documents = append(documents, raw) + } +} + +type openAISSEJSONDocumentScanner struct { + scanner *bufio.Scanner + pending []string + current string +} + +func newOpenAISSEJSONDocumentScanner(scanner *bufio.Scanner) *openAISSEJSONDocumentScanner { + return &openAISSEJSONDocumentScanner{scanner: scanner} +} + +func (s *openAISSEJSONDocumentScanner) Scan() bool { + if len(s.pending) > 0 { + s.current = s.pending[0] + s.pending = s.pending[1:] + return true + } + if s.scanner == nil || !s.scanner.Scan() { + return false + } + + line := s.scanner.Text() + data, ok := extractOpenAISSEDataLine(line) + if !ok { + s.current = line + return true + } + if len(data) > maxOpenAIConcatenatedJSONBytes { + s.current = line + return true + } + documents, repaired := splitOpenAIConcatenatedJSONDocuments([]byte(data)) + if !repaired { + s.current = line + return true + } + + expanded := make([]string, 0, len(documents)*3) + for i, document := range documents { + if i > 0 { + var envelope struct { + Type string `json:"type"` + } + _ = json.Unmarshal(document, &envelope) + expanded = append(expanded, "event: "+strings.TrimSpace(envelope.Type)) + } + expanded = append(expanded, "data: "+string(document), "") + } + s.current = expanded[0] + s.pending = expanded[1:] + return true +} + +func (s *openAISSEJSONDocumentScanner) Text() string { + return s.current +} + +func (s *openAISSEJSONDocumentScanner) Err() error { + if s.scanner == nil { + return nil + } + return s.scanner.Err() +} diff --git a/backend/internal/service/openai_ws_client.go b/backend/internal/service/openai_ws_client.go index e336abcbd6..c9b92d22e8 100644 --- a/backend/internal/service/openai_ws_client.go +++ b/backend/internal/service/openai_ws_client.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "io" "net/http" "net/url" "strings" @@ -68,6 +69,28 @@ type coderOpenAIWSClientDialer struct { proxyMisses atomic.Int64 } +// openAIWSHandshakeError keeps a bounded, non-logged HTTP error body so the +// Agent Identity recovery path can distinguish an invalid task from other +// 401 handshake failures. +type openAIWSHandshakeError struct { + Body []byte + Err error +} + +func (e *openAIWSHandshakeError) Error() string { + if e == nil || e.Err == nil { + return "openai ws handshake failed" + } + return e.Err.Error() +} + +func (e *openAIWSHandshakeError) Unwrap() error { + if e == nil { + return nil + } + return e.Err +} + type openAIWSProxyClientEntry struct { client *http.Client lastUsedUnixNano int64 @@ -104,7 +127,12 @@ func (d *coderOpenAIWSClientDialer) Dial( status = resp.StatusCode respHeaders = cloneHeader(resp.Header) } - return nil, status, respHeaders, err + var body []byte + if resp != nil && resp.Body != nil { + body, _ = io.ReadAll(io.LimitReader(resp.Body, 8<<10)) + _ = resp.Body.Close() + } + return nil, status, respHeaders, &openAIWSHandshakeError{Body: body, Err: err} } // coder/websocket 默认单消息读取上限为 32KB,Codex WS 事件(如 rate_limits/大 delta) // 可能超过该阈值,需显式提高上限,避免本地 read_fail(message too big)。 diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index b632c451df..51aace6419 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -46,8 +46,8 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( if account == nil { return errors.New("account is nil") } - if strings.TrimSpace(token) == "" { - return errors.New("token is empty") + if err := validateOpenAIWSBearerToken(account, token); err != nil { + return err } // 预取一次 OpenAI Fast Policy settings,绑定到 ctx,让该 WS session @@ -232,6 +232,17 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } normalized = next } + if account.IsOpenAIOAuth() && isOpenAIResponsesLiteWebSocketPayload(normalized) { + litePayload, _, liteErr := normalizeOpenAIResponsesLiteToolsPayload(normalized) + if liteErr != nil { + return openAIWSClientPayload{}, NewOpenAIWSClientCloseError( + coderws.StatusPolicyViolation, + liteErr.Error(), + liteErr, + ) + } + normalized = litePayload + } apiKey := getAPIKeyFromContext(c) imageGenerationAllowed := GroupAllowsImageGeneration(apiKeyGroup(apiKey)) codexImageGenerationExplicitToolPolicy := codexImageGenerationExplicitToolPolicyAllow @@ -577,6 +588,9 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( Account: account, WSURL: wsURL, Headers: wsHeaders, + HeadersFactory: func(factoryCtx context.Context, headers http.Header) (http.Header, error) { + return s.refreshOpenAIAgentIdentityHeaders(factoryCtx, account, headers) + }, ProxyURL: func() string { if account.ProxyID != nil && account.Proxy != nil { return account.Proxy.URL() @@ -640,7 +654,9 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( acquireTimeout = 30 * time.Second } - acquireTurnLease := func(turn int, preferred string, forcePreferredConn bool) (*openAIWSConnLease, error) { + agentTaskRecoveryTried := false + var acquireTurnLease func(int, string, bool) (*openAIWSConnLease, error) + acquireTurnLease = func(turn int, preferred string, forcePreferredConn bool) (*openAIWSConnLease, error) { req := cloneOpenAIWSAcquireRequest(baseAcquireReq) req.PreferredConnID = strings.TrimSpace(preferred) req.ForcePreferredConn = forcePreferredConn @@ -649,6 +665,14 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( acquireCtx, acquireCancel := context.WithTimeout(ctx, acquireTimeout) lease, acquireErr := pool.Acquire(acquireCtx, req) acquireCancel() + var dialErr *openAIWSDialError + if acquireErr != nil && s.isAgentIdentityAccount(ctx, account) && errors.As(acquireErr, &dialErr) && isAgentIdentityTaskInvalidWSDialError(dialErr) && !agentTaskRecoveryTried { + agentTaskRecoveryTried = true + if recoveryErr := s.recoverAgentIdentityTask(ctx, account, account.GetCredential("task_id")); recoveryErr != nil { + return nil, fmt.Errorf("agent identity task recovery failed: %w", recoveryErr) + } + return acquireTurnLease(turn, preferred, forcePreferredConn) + } if acquireErr != nil { dialStatus, dialClass, dialCloseStatus, dialCloseReason, dialRespServer, dialRespVia, dialRespCFRay, dialRespReqID := summarizeOpenAIWSDialError(acquireErr) logOpenAIWSModeInfo( diff --git a/backend/internal/service/openai_ws_forwarder_ingress_session_test.go b/backend/internal/service/openai_ws_forwarder_ingress_session_test.go index 5ec4b5333b..3752c1bd0e 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress_session_test.go +++ b/backend/internal/service/openai_ws_forwarder_ingress_session_test.go @@ -425,6 +425,7 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_CodexImageBridge events: [][]byte{ []byte(`{"type":"response.completed","response":{"id":"resp_codex_image_bridge","model":"gpt-5.5","usage":{"input_tokens":1,"output_tokens":1}}}`), []byte(`{"type":"response.completed","response":{"id":"resp_codex_image_lite","model":"gpt-5.5","usage":{"input_tokens":1,"output_tokens":1}}}`), + []byte(`{"type":"response.completed","response":{"id":"resp_codex_image_function","model":"gpt-5.5","usage":{"input_tokens":1,"output_tokens":1}}}`), }, } captureDialer := &openAIWSCaptureDialer{conn: captureConn} @@ -531,10 +532,12 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_CodexImageBridge "stream":false, "previous_response_id":"resp_codex_image_bridge", "client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":"true"}, + "tools":[{"type":"namespace","name":"collaboration","tools":[{"type":"function","name":"spawn_agent"}]}], "input":[ {"type":"additional_tools","role":"developer","tools":[{"type":"custom","name":"exec","description":"Execute code-mode tools, including image_gen.imagegen."}]}, {"type":"message","role":"user","content":[{"type":"input_text","text":"draw a cat"}]} - ] + ], + "tool_choice":{"type":"namespace","name":"collaboration"} }`)) cancelWrite() require.NoError(t, err) @@ -546,6 +549,25 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_CodexImageBridge require.Equal(t, coderws.MessageText, msgType) require.Equal(t, "resp_codex_image_lite", gjson.GetBytes(message, "response.id").String()) + writeCtx, cancelWrite = context.WithTimeout(context.Background(), 3*time.Second) + err = clientConn.Write(writeCtx, coderws.MessageText, []byte(`{ + "type":"response.create", + "model":"gpt-5.5", + "stream":false, + "previous_response_id":"resp_codex_image_lite", + "input":"draw a cat", + "tools":[{"type":"function","name":"image_gen.imagegen","parameters":{"type":"object"}}] + }`)) + cancelWrite() + require.NoError(t, err) + + readCtx, cancelRead = context.WithTimeout(context.Background(), 3*time.Second) + msgType, message, err = clientConn.Read(readCtx) + cancelRead() + require.NoError(t, err) + require.Equal(t, coderws.MessageText, msgType) + require.Equal(t, "resp_codex_image_function", gjson.GetBytes(message, "response.id").String()) + _ = clientConn.Close(coderws.StatusNormalClosure, "done") select { @@ -555,7 +577,7 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_CodexImageBridge t.Fatal("等待 ingress websocket 结束超时") } - require.Len(t, captureConn.writes, 2) + require.Len(t, captureConn.writes, 3) nonLitePayload := requestToJSONString(captureConn.writes[0]) require.True(t, gjson.Get(nonLitePayload, `tools.#(type=="image_generation")`).Exists()) require.Equal(t, "png", gjson.Get(nonLitePayload, `tools.#(type=="image_generation").output_format`).String()) @@ -564,10 +586,19 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_CodexImageBridge litePayload := requestToJSONString(captureConn.writes[1]) require.False(t, gjson.Get(litePayload, `tools.#(type=="image_generation")`).Exists()) - require.False(t, gjson.Get(litePayload, "tool_choice").Exists()) require.NotContains(t, gjson.Get(litePayload, "instructions").String(), "image_generation") require.Equal(t, "exec", gjson.Get(litePayload, `input.#(type=="additional_tools").tools.0.name`).String()) require.Contains(t, gjson.Get(litePayload, `input.#(type=="additional_tools").tools.0.description`).String(), "image_gen.imagegen") + require.False(t, gjson.Get(litePayload, `tools.#(type=="namespace")`).Exists()) + require.Equal(t, "collaboration", gjson.Get(litePayload, `input.#(type=="additional_tools").tools.1.name`).String()) + require.Equal(t, "namespace", gjson.Get(litePayload, "tool_choice.type").String()) + require.Equal(t, "collaboration", gjson.Get(litePayload, "tool_choice.name").String()) + + functionPayload := requestToJSONString(captureConn.writes[2]) + require.True(t, gjson.Get(functionPayload, `tools.#(name=="image_gen.imagegen")`).Exists()) + require.False(t, gjson.Get(functionPayload, `tools.#(type=="image_generation")`).Exists()) + require.False(t, gjson.Get(functionPayload, "tool_choice").Exists()) + require.NotContains(t, gjson.Get(functionPayload, "instructions").String(), codexImageGenerationBridgeMarker) } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_DedicatedModeDoesNotReuseConnAcrossSessions(t *testing.T) { @@ -940,7 +971,16 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_PassthroughHeade }() writeCtx, cancelWrite := context.WithTimeout(context.Background(), 3*time.Second) - err = clientConn.Write(writeCtx, coderws.MessageText, []byte(`{"type":"response.create","model":"gpt-5.1","stream":false,"prompt_cache_key":"pcache_passthrough"}`)) + err = clientConn.Write(writeCtx, coderws.MessageText, []byte(`{ + "type":"response.create", + "model":"gpt-5.1", + "stream":false, + "prompt_cache_key":"pcache_passthrough", + "client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":"true"}, + "tools":[{"type":"namespace","name":"collaboration","tools":[{"type":"function","name":"spawn_agent"}]}], + "input":[{"type":"message","role":"user","content":"hello"}], + "tool_choice":{"type":"namespace","name":"collaboration"} + }`)) cancelWrite() require.NoError(t, err) @@ -963,6 +1003,12 @@ func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_PassthroughHeade require.Equal(t, isolateOpenAISessionID(0, "pcache_passthrough"), captureDialer.lastHeaders.Get("session_id")) require.Equal(t, "turn-state-1", captureDialer.lastHeaders.Get(openAIWSTurnStateHeader)) require.Equal(t, "turn-meta-1", captureDialer.lastHeaders.Get(openAIWSTurnMetadataHeader)) + require.Len(t, upstreamConn.writes, 1) + forwarded := requestToJSONString(upstreamConn.writes[0]) + require.False(t, gjson.Get(forwarded, `tools.#(type=="namespace")`).Exists()) + require.Equal(t, "collaboration", gjson.Get(forwarded, `input.#(type=="additional_tools").tools.0.name`).String()) + require.Equal(t, "namespace", gjson.Get(forwarded, "tool_choice.type").String()) + require.Equal(t, "collaboration", gjson.Get(forwarded, "tool_choice.name").String()) } func TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_HTTPBridgeModeRelaysHTTPStream(t *testing.T) { diff --git a/backend/internal/service/openai_ws_forwarder_payload.go b/backend/internal/service/openai_ws_forwarder_payload.go index 5830444815..511b28d0ba 100644 --- a/backend/internal/service/openai_ws_forwarder_payload.go +++ b/backend/internal/service/openai_ws_forwarder_payload.go @@ -15,6 +15,16 @@ import ( "github.com/tidwall/sjson" ) +func validateOpenAIWSBearerToken(account *Account, token string) error { + if account == nil { + return errors.New("account is nil") + } + if strings.TrimSpace(token) == "" && !account.IsOpenAIAgentIdentity() { + return errors.New("token is empty") + } + return nil +} + func (s *OpenAIGatewayService) buildOpenAIResponsesWSURL(account *Account) (string, error) { if account == nil { return "", errors.New("account is nil") @@ -67,7 +77,9 @@ func (s *OpenAIGatewayService) buildOpenAIWSHeaders( promptCacheKey string, ) (http.Header, openAIWSSessionHeaderResolution, error) { headers := make(http.Header) - headers.Set("authorization", "Bearer "+token) + if account == nil || !account.IsOpenAIAgentIdentity() { + headers.Set("authorization", "Bearer "+token) + } sessionResolution := resolveOpenAIWSSessionHeaders(c, promptCacheKey) if c != nil && c.Request != nil { diff --git a/backend/internal/service/openai_ws_forwarder_v2.go b/backend/internal/service/openai_ws_forwarder_v2.go index f0f71648dd..9054e60502 100644 --- a/backend/internal/service/openai_ws_forwarder_v2.go +++ b/backend/internal/service/openai_ws_forwarder_v2.go @@ -30,6 +30,7 @@ func (s *OpenAIGatewayService) forwardOpenAIWSV2( startTime time.Time, attempt int, lastFailureReason string, + agentTaskRecoveryTried *bool, ) (*OpenAIForwardResult, error) { if s == nil || account == nil { return nil, wrapOpenAIWSFallback("invalid_state", errors.New("service or account is nil")) @@ -174,9 +175,12 @@ func (s *OpenAIGatewayService) forwardOpenAIWSV2( defer acquireCancel() lease, err := s.getOpenAIWSConnPool().Acquire(acquireCtx, openAIWSAcquireRequest{ - Account: account, - WSURL: wsURL, - Headers: wsHeaders, + Account: account, + WSURL: wsURL, + Headers: wsHeaders, + HeadersFactory: func(factoryCtx context.Context, headers http.Header) (http.Header, error) { + return s.refreshOpenAIAgentIdentityHeaders(factoryCtx, account, headers) + }, PreferredConnID: preferredConnID, ForceNewConn: forceNewConn, ProxyURL: func() string { @@ -187,6 +191,14 @@ func (s *OpenAIGatewayService) forwardOpenAIWSV2( }(), }) if err != nil { + var agentDialErr *openAIWSDialError + if s.isAgentIdentityAccount(ctx, account) && errors.As(err, &agentDialErr) && isAgentIdentityTaskInvalidWSDialError(agentDialErr) && agentTaskRecoveryTried != nil && !*agentTaskRecoveryTried { + *agentTaskRecoveryTried = true + if recoveryErr := s.recoverAgentIdentityTask(ctx, account, account.GetCredential("task_id")); recoveryErr != nil { + return nil, fmt.Errorf("agent identity task recovery failed: %w", recoveryErr) + } + return nil, &agentIdentityTaskRecoveredError{} + } dialStatus, dialClass, dialCloseStatus, dialCloseReason, dialRespServer, dialRespVia, dialRespCFRay, dialRespReqID := summarizeOpenAIWSDialError(err) logOpenAIWSModeInfo( "acquire_fail account_id=%d account_type=%s transport=%s reason=%s dial_status=%d dial_class=%s dial_close_status=%s dial_close_reason=%s dial_resp_server=%s dial_resp_via=%s dial_resp_cf_ray=%s dial_resp_x_request_id=%s cause=%s preferred_conn_id=%s force_new_conn=%v ws_host=%s ws_path=%s proxy_enabled=%v", @@ -418,9 +430,30 @@ func (s *OpenAIGatewayService) forwardOpenAIWSV2( } readTimeout := s.openAIWSReadTimeout() + var pendingJSONDocuments [][]byte for { - message, readErr := lease.ReadMessageWithContextTimeout(ctx, readTimeout) + var message []byte + var readErr error + if len(pendingJSONDocuments) > 0 { + message = pendingJSONDocuments[0] + pendingJSONDocuments = pendingJSONDocuments[1:] + } else { + message, readErr = lease.ReadMessageWithContextTimeout(ctx, readTimeout) + if readErr == nil { + if documents, repaired := splitOpenAIConcatenatedJSONDocuments(message); repaired { + logOpenAIWSModeInfo( + "concatenated_json_repaired account_id=%d conn_id=%s documents=%d bytes=%d", + account.ID, + truncateOpenAIWSLogValue(connID, openAIWSIDValueMaxLen), + len(documents), + len(message), + ) + message = documents[0] + pendingJSONDocuments = append(pendingJSONDocuments, documents[1:]...) + } + } + } if readErr != nil { lease.MarkBroken() closeStatus, closeReason := summarizeOpenAIWSReadCloseError(readErr) @@ -617,7 +650,10 @@ func (s *OpenAIGatewayService) forwardOpenAIWSV2( } if isTerminalEvent { - cleanExit = true + // A terminal event must be the final JSON document in its WS message. + // Ignore any tail for the completed client turn, but never reuse the + // ambiguous upstream connection for another request. + cleanExit = len(pendingJSONDocuments) == 0 break } } diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index dbc24c850a..091b3592d1 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -12,7 +12,6 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/config" - "github.com/Wei-Shaw/sub2api/internal/pkg/xai" "github.com/gin-gonic/gin" "github.com/tidwall/gjson" ) @@ -23,6 +22,15 @@ const ( openAIWSHTTPBridgeErrorBodyLimitBytes = 64 * 1024 ) +// ResolveOpenAIWSClientFirstMessageTimeout returns the effective client ingress deadline. +func ResolveOpenAIWSClientFirstMessageTimeout(cfg *config.Config) time.Duration { + seconds := config.DefaultOpenAIWSClientFirstMessageTimeoutSeconds + if cfg != nil && cfg.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds > 0 { + seconds = cfg.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds + } + return time.Duration(seconds) * time.Second +} + func ResolveOpenAIWSClientReadLimitBytes(cfg *config.Config) int64 { if cfg == nil || cfg.Gateway.OpenAIWS.ClientReadLimitBytes <= 0 { return openAIWSClientReadLimitBytesDefault @@ -193,7 +201,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( releaseUpstreamCtx() return nil, fmt.Errorf("apply grok prompt cache identity: %w", err) } - upstreamReq, err = buildGrokResponsesRequest(upstreamCtx, c, account, body, token, grokCacheIdentity) + upstreamReq, err = buildGrokResponsesRequest(upstreamCtx, c, account, body, token, grokCacheIdentity, s.cfg) } else { upstreamReq, err = s.buildUpstreamRequestOpenAIPassthrough(upstreamCtx, c, account, body, token) } @@ -236,7 +244,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( return nil, fmt.Errorf("upstream http bridge error: status=%d message=%s", resp.StatusCode, upstreamMsg) } if account.Platform == PlatformGrok { - s.updateGrokUsageSnapshot(ctx, account, xai.ParseQuotaHeaders(resp.Header, resp.StatusCode)) + s.updateGrokUsageFromResponse(ctx, account, resp.Header, resp.StatusCode) } responseID := "" diff --git a/backend/internal/service/openai_ws_http_bridge_test.go b/backend/internal/service/openai_ws_http_bridge_test.go index b1bfb4d342..cbc11abcc2 100644 --- a/backend/internal/service/openai_ws_http_bridge_test.go +++ b/backend/internal/service/openai_ws_http_bridge_test.go @@ -19,6 +19,17 @@ import ( "github.com/tidwall/gjson" ) +func TestResolveOpenAIWSClientFirstMessageTimeout(t *testing.T) { + defaultTimeout := time.Duration(config.DefaultOpenAIWSClientFirstMessageTimeoutSeconds) * time.Second + require.Equal(t, defaultTimeout, ResolveOpenAIWSClientFirstMessageTimeout(nil)) + + cfg := &config.Config{} + require.Equal(t, defaultTimeout, ResolveOpenAIWSClientFirstMessageTimeout(cfg)) + + cfg.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds = 120 + require.Equal(t, 120*time.Second, ResolveOpenAIWSClientFirstMessageTimeout(cfg)) +} + func TestPrepareOpenAIWSHTTPBridgeBodyStripsWSFields(t *testing.T) { body, err := prepareOpenAIWSHTTPBridgeBody([]byte(`{"type":"response.create","generate":true,"model":"gpt-5","stream":false,"previous_response_id":"resp_prev","input":"hi"}`)) require.NoError(t, err) diff --git a/backend/internal/service/openai_ws_pool.go b/backend/internal/service/openai_ws_pool.go index 8affe2a930..8579cc58d6 100644 --- a/backend/internal/service/openai_ws_pool.go +++ b/backend/internal/service/openai_ws_pool.go @@ -39,6 +39,7 @@ var ( type openAIWSDialError struct { StatusCode int ResponseHeaders http.Header + ResponseBody []byte Err error } @@ -60,9 +61,13 @@ func (e *openAIWSDialError) Unwrap() error { } type openAIWSAcquireRequest struct { - Account *Account - WSURL string - Headers http.Header + Account *Account + WSURL string + Headers http.Header + // HeadersFactory is evaluated inside dialConn. It exists so credentials + // whose authorization is per-dial (Agent Identity) are never cached in + // lastAcquire or delayed prewarm state. + HeadersFactory func(context.Context, http.Header) (http.Header, error) ProxyURL string PreferredConnID string // ForceNewConn: 强制本次获取新连接(避免复用导致连接内续链状态互相污染)。 @@ -544,6 +549,7 @@ type openAIWSAccountPool struct { pinnedConns map[string]int changedCh chan struct{} creating int + generation uint64 lastCleanupAt time.Time lastAcquire *openAIWSAcquireRequest prewarmActive bool @@ -1391,6 +1397,7 @@ func (p *openAIWSConnPool) ensureTargetIdleAsync(accountID int64) { } var req openAIWSAcquireRequest + generation := uint64(0) need := 0 ap, ok := p.getAccountPool(accountID) if !ok || ap == nil { @@ -1425,6 +1432,7 @@ func (p *openAIWSConnPool) ensureTargetIdleAsync(accountID int64) { return } req = cloneOpenAIWSAcquireRequest(*ap.lastAcquire) + generation = ap.generation ap.prewarmActive = true if cooldown := p.prewarmCooldown(); cooldown > 0 { ap.prewarmUntil = now.Add(cooldown) @@ -1432,7 +1440,7 @@ func (p *openAIWSConnPool) ensureTargetIdleAsync(accountID int64) { ap.creating += need p.metrics.scaleUpTotal.Add(int64(need)) - go p.prewarmConns(accountID, req, need) + go p.prewarmConns(accountID, req, need, generation) } func (p *openAIWSConnPool) targetConnCountLocked(ap *openAIWSAccountPool, maxConns int) int { @@ -1475,7 +1483,11 @@ func (p *openAIWSConnPool) targetConnCountLocked(ap *openAIWSAccountPool, maxCon return target } -func (p *openAIWSConnPool) prewarmConns(accountID int64, req openAIWSAcquireRequest, total int) { +func (p *openAIWSConnPool) prewarmConns(accountID int64, req openAIWSAcquireRequest, total int, generations ...uint64) { + generation := uint64(0) + if len(generations) > 0 { + generation = generations[0] + } defer func() { if ap, ok := p.getAccountPool(accountID); ok && ap != nil { ap.mu.Lock() @@ -1507,6 +1519,11 @@ func (p *openAIWSConnPool) prewarmConns(accountID int64, req openAIWSAcquireRequ ap.mu.Unlock() continue } + if ap.generation != generation || ap.lastAcquire == nil { + ap.mu.Unlock() + conn.close() + continue + } if len(ap.conns) >= p.effectiveMaxConnsByAccount(req.Account) { ap.signalChangedLocked() ap.mu.Unlock() @@ -1521,6 +1538,35 @@ func (p *openAIWSConnPool) prewarmConns(accountID int64, req openAIWSAcquireRequ } } +// ClearAccount closes all pooled connections and discards delayed prewarm +// state for one account. The generation guard prevents an in-flight prewarm +// started before credential recovery from re-entering the pool afterwards. +func (p *openAIWSConnPool) ClearAccount(accountID int64) { + if p == nil || accountID <= 0 { + return + } + ap, ok := p.getAccountPool(accountID) + if !ok || ap == nil { + return + } + ap.mu.Lock() + ap.generation++ + conns := make([]*openAIWSConn, 0, len(ap.conns)) + for id, conn := range ap.conns { + delete(ap.conns, id) + delete(ap.pinnedConns, id) + if conn != nil { + conns = append(conns, conn) + } + } + ap.lastAcquire = nil + ap.prewarmUntil = time.Time{} + ap.prewarmFails = 0 + ap.prewarmFailAt = time.Time{} + ap.mu.Unlock() + closeOpenAIWSConns(conns) +} + func (p *openAIWSConnPool) evictConn(accountID int64, connID string) { if p == nil || accountID <= 0 || stringsTrim(connID) == "" { return @@ -1599,11 +1645,25 @@ func (p *openAIWSConnPool) dialConn(ctx context.Context, req openAIWSAcquireRequ if p == nil || p.clientDialer == nil { return nil, errors.New("openai ws client dialer is nil") } - conn, status, handshakeHeaders, err := p.clientDialer.Dial(ctx, req.WSURL, req.Headers, req.ProxyURL) + headers := cloneHeader(req.Headers) + var err error + if req.HeadersFactory != nil { + headers, err = req.HeadersFactory(ctx, headers) + if err != nil { + return nil, err + } + } + conn, status, handshakeHeaders, err := p.clientDialer.Dial(ctx, req.WSURL, headers, req.ProxyURL) if err != nil { + var handshakeErr *openAIWSHandshakeError + var responseBody []byte + if errors.As(err, &handshakeErr) && handshakeErr != nil { + responseBody = append([]byte(nil), handshakeErr.Body...) + } return nil, &openAIWSDialError{ StatusCode: status, ResponseHeaders: cloneHeader(handshakeHeaders), + ResponseBody: responseBody, Err: err, } } diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index d822d181cd..d2cf26a8ce 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -243,8 +243,15 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( if account == nil { return errors.New("account is nil") } - if strings.TrimSpace(token) == "" { - return errors.New("token is empty") + if err := validateOpenAIWSBearerToken(account, token); err != nil { + return err + } + if account.IsOpenAIOAuth() && isOpenAIResponsesLiteWebSocketPayload(firstClientMessage) { + liteFirstMessage, _, liteErr := normalizeOpenAIResponsesLiteToolsPayload(firstClientMessage) + if liteErr != nil { + return NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, liteErr.Error(), liteErr) + } + firstClientMessage = liteFirstMessage } requestModel := strings.TrimSpace(gjson.GetBytes(firstClientMessage, "model").String()) requestPreviousResponseID := strings.TrimSpace(gjson.GetBytes(firstClientMessage, "previous_response_id").String()) @@ -359,10 +366,34 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( return errors.New("openai ws passthrough dialer is nil") } - dialCtx, cancelDial := context.WithTimeout(ctx, s.openAIWSDialTimeout()) - defer cancelDial() - upstreamConn, statusCode, handshakeHeaders, err := dialer.Dial(dialCtx, wsURL, headers, proxyURL) - if err != nil { + agentTaskRecoveryTried := false + var upstreamConn openAIWSClientConn + statusCode := 0 + var handshakeHeaders http.Header + for { + headers, err = s.refreshOpenAIAgentIdentityHeaders(ctx, account, headers) + if err != nil { + return fmt.Errorf("refresh ws authentication headers: %w", err) + } + dialCtx, cancelDial := context.WithTimeout(ctx, s.openAIWSDialTimeout()) + upstreamConn, statusCode, handshakeHeaders, err = dialer.Dial(dialCtx, wsURL, headers, proxyURL) + cancelDial() + if err == nil { + break + } + var handshakeErr *openAIWSHandshakeError + responseBody := []byte(nil) + if errors.As(err, &handshakeErr) && handshakeErr != nil { + responseBody = handshakeErr.Body + } + dialErr := &openAIWSDialError{StatusCode: statusCode, ResponseBody: responseBody, Err: err} + if s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidWSDialError(dialErr) && !agentTaskRecoveryTried { + agentTaskRecoveryTried = true + if recoveryErr := s.recoverAgentIdentityTask(ctx, account, account.GetCredential("task_id")); recoveryErr != nil { + return fmt.Errorf("agent identity task recovery failed: %w", recoveryErr) + } + continue + } logOpenAIWSV2Passthrough( "relay_dial_failed account_id=%d status_code=%d err=%s", account.ID, @@ -404,6 +435,15 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( if msgType != coderws.MessageText { return payload, nil, nil } + if strings.TrimSpace(gjson.GetBytes(payload, "type").String()) == "response.create" { + if account.IsOpenAIOAuth() && isOpenAIResponsesLiteWebSocketPayload(payload) { + litePayload, _, liteErr := normalizeOpenAIResponsesLiteToolsPayload(payload) + if liteErr != nil { + return payload, nil, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, liteErr.Error(), liteErr) + } + payload = litePayload + } + } if strings.TrimSpace(gjson.GetBytes(payload, "type").String()) == "response.create" && hooks != nil && hooks.BeforeRequest != nil { turnNo := int(completedTurns.Load()) + 1 if turnNo < 2 { @@ -678,9 +718,15 @@ func (s *OpenAIGatewayService) mapOpenAIWSPassthroughDialError( wrappedErr := err var dialErr *openAIWSDialError if !errors.As(err, &dialErr) { + var handshakeErr *openAIWSHandshakeError + var responseBody []byte + if errors.As(err, &handshakeErr) && handshakeErr != nil { + responseBody = append([]byte(nil), handshakeErr.Body...) + } wrappedErr = &openAIWSDialError{ StatusCode: statusCode, ResponseHeaders: cloneHeader(handshakeHeaders), + ResponseBody: responseBody, Err: err, } } diff --git a/backend/internal/service/ops_metrics_collector.go b/backend/internal/service/ops_metrics_collector.go index b654190cfb..d4f5c32929 100644 --- a/backend/internal/service/ops_metrics_collector.go +++ b/backend/internal/service/ops_metrics_collector.go @@ -39,6 +39,10 @@ const ( var opsMetricsCollectorAdvisoryLockID = hashAdvisoryLockID(opsMetricsCollectorLeaderLockKey) +type opsSchedulableAccountLoadRepository interface { + ListSchedulableAccountLoads(ctx context.Context) ([]AccountWithConcurrency, error) +} + type OpsMetricsCollector struct { opsRepo OpsRepository settingRepo SettingRepository @@ -375,31 +379,16 @@ func (c *OpsMetricsCollector) collectConcurrencyQueueDepth(parentCtx context.Con ctx, cancel := context.WithTimeout(parentCtx, 2*time.Second) defer cancel() - accounts, err := c.accountRepo.ListSchedulable(ctx) + accountLoads, err := c.listSchedulableAccountLoads(ctx) if err != nil { return nil } - if len(accounts) == 0 { + if len(accountLoads) == 0 { zero := 0 return &zero } - batch := make([]AccountWithConcurrency, 0, len(accounts)) - for _, acc := range accounts { - if acc.ID <= 0 { - continue - } - batch = append(batch, AccountWithConcurrency{ - ID: acc.ID, - MaxConcurrency: acc.EffectiveLoadFactor(), - }) - } - if len(batch) == 0 { - zero := 0 - return &zero - } - - loadMap, err := c.concurrencyService.GetAccountsLoadBatch(ctx, batch) + loadMap, err := c.concurrencyService.GetAccountsLoadBatch(ctx, accountLoads) if err != nil { return nil } @@ -423,6 +412,28 @@ func (c *OpsMetricsCollector) collectConcurrencyQueueDepth(parentCtx context.Con return &v } +func (c *OpsMetricsCollector) listSchedulableAccountLoads(ctx context.Context) ([]AccountWithConcurrency, error) { + if repo, ok := c.accountRepo.(opsSchedulableAccountLoadRepository); ok { + return repo.ListSchedulableAccountLoads(ctx) + } + + accounts, err := c.accountRepo.ListSchedulable(ctx) + if err != nil { + return nil, err + } + loads := make([]AccountWithConcurrency, 0, len(accounts)) + for _, account := range accounts { + if account.ID <= 0 { + continue + } + loads = append(loads, AccountWithConcurrency{ + ID: account.ID, + MaxConcurrency: account.EffectiveLoadFactor(), + }) + } + return loads, nil +} + type opsCollectedPercentiles struct { p50 *int p90 *int diff --git a/backend/internal/service/ops_metrics_collector_projection_test.go b/backend/internal/service/ops_metrics_collector_projection_test.go new file mode 100644 index 0000000000..e0d1da774d --- /dev/null +++ b/backend/internal/service/ops_metrics_collector_projection_test.go @@ -0,0 +1,128 @@ +package service + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +type opsMetricsProjectionRepo struct { + AccountRepository + accounts []Account + accountLoads []AccountWithConcurrency + listCalls int + projectionCalls int +} + +func (r *opsMetricsProjectionRepo) ListSchedulable(context.Context) ([]Account, error) { + r.listCalls++ + return r.accounts, nil +} + +func (r *opsMetricsProjectionRepo) ListSchedulableAccountLoads(context.Context) ([]AccountWithConcurrency, error) { + r.projectionCalls++ + return r.accountLoads, nil +} + +type opsMetricsFallbackRepo struct { + AccountRepository + accounts []Account + listCalls int +} + +func (r *opsMetricsFallbackRepo) ListSchedulable(context.Context) ([]Account, error) { + r.listCalls++ + return r.accounts, nil +} + +type opsMetricsLoadCache struct { + ConcurrencyCache + loads map[int64]*AccountLoadInfo + got []AccountWithConcurrency +} + +func (c *opsMetricsLoadCache) GetAccountsLoadBatch(_ context.Context, accounts []AccountWithConcurrency) (map[int64]*AccountLoadInfo, error) { + c.got = accounts + return c.loads, nil +} + +func TestCollectConcurrencyQueueDepthUsesProjectionAndPreservesFallbackResult(t *testing.T) { + loadFactor := 7 + accounts := []Account{ + {ID: 11, Concurrency: 2, LoadFactor: &loadFactor}, + {ID: 12, Concurrency: 3}, + {ID: 13}, + } + accountLoads := []AccountWithConcurrency{ + {ID: 11, MaxConcurrency: 7}, + {ID: 12, MaxConcurrency: 3}, + {ID: 13, MaxConcurrency: 1}, + } + loads := map[int64]*AccountLoadInfo{ + 11: {AccountID: 11, WaitingCount: 2}, + 12: {AccountID: 12, WaitingCount: 3}, + 13: {AccountID: 13, WaitingCount: 0}, + } + + projectionRepo := &opsMetricsProjectionRepo{accounts: accounts, accountLoads: accountLoads} + projectionCache := &opsMetricsLoadCache{loads: loads} + projectionConcurrency := NewConcurrencyService(projectionCache) + projectionConcurrency.SetAccountLoadBatchCacheTTL(0) + projectionCollector := &OpsMetricsCollector{ + accountRepo: projectionRepo, + concurrencyService: projectionConcurrency, + } + + fallbackRepo := &opsMetricsFallbackRepo{accounts: accounts} + fallbackCache := &opsMetricsLoadCache{loads: loads} + fallbackConcurrency := NewConcurrencyService(fallbackCache) + fallbackConcurrency.SetAccountLoadBatchCacheTTL(0) + fallbackCollector := &OpsMetricsCollector{ + accountRepo: fallbackRepo, + concurrencyService: fallbackConcurrency, + } + + projectionDepth := projectionCollector.collectConcurrencyQueueDepth(context.Background()) + fallbackDepth := fallbackCollector.collectConcurrencyQueueDepth(context.Background()) + + require.NotNil(t, projectionDepth) + require.NotNil(t, fallbackDepth) + require.Equal(t, 5, *projectionDepth) + require.Equal(t, *fallbackDepth, *projectionDepth) + require.Equal(t, 1, projectionRepo.projectionCalls) + require.Zero(t, projectionRepo.listCalls) + require.Equal(t, 1, fallbackRepo.listCalls) + require.Equal(t, accountLoads, projectionCache.got) + require.Equal(t, fallbackCache.got, projectionCache.got) +} + +func BenchmarkOpsMetricsCollectorCollectConcurrencyQueueDepth(b *testing.B) { + const accountCount = 1000 + loadFactor := 8 + accounts := make([]Account, accountCount) + accountLoads := make([]AccountWithConcurrency, accountCount) + for i := range accountCount { + id := int64(i + 1) + accounts[i] = Account{ + ID: id, + Concurrency: 4, + LoadFactor: &loadFactor, + } + accountLoads[i] = AccountWithConcurrency{ID: id, MaxConcurrency: loadFactor} + } + + repo := &opsMetricsProjectionRepo{accounts: accounts, accountLoads: accountLoads} + cache := &opsMetricsLoadCache{loads: map[int64]*AccountLoadInfo{}} + concurrency := NewConcurrencyService(cache) + concurrency.SetAccountLoadBatchCacheTTL(0) + collector := &OpsMetricsCollector{accountRepo: repo, concurrencyService: concurrency} + + b.ReportAllocs() + b.ResetTimer() + for range b.N { + if depth := collector.collectConcurrencyQueueDepth(context.Background()); depth == nil || *depth != 0 { + b.Fatalf("unexpected queue depth: %v", depth) + } + } +} diff --git a/backend/internal/service/ops_models.go b/backend/internal/service/ops_models.go index d95bbadbb8..411ca7595b 100644 --- a/backend/internal/service/ops_models.go +++ b/backend/internal/service/ops_models.go @@ -27,7 +27,7 @@ type OpsErrorLog struct { CreatedAt time.Time `json:"created_at"` // Standardized classification - // - phase: request|auth|routing|upstream|network|internal + // - phase: request|auth|account_auth|routing|upstream|network|internal // - owner: client|provider|platform // - source: client_request|upstream_http|gateway Phase string `json:"phase"` @@ -121,7 +121,7 @@ type OpsErrorLogFilter struct { StatusCodes []int StatusCodesOther bool - Phase string // Special: Phase=="upstream" bypasses status>=400 clause; do not set together with ErrorPhasesAny. + Phase string // Recovered provider rows bypass status>=400 only with the explicit opt-in below. Owner string Source string Resolved *bool @@ -150,14 +150,15 @@ type OpsErrorLogFilter struct { // ExcludeCountTokens drops count_tokens probe errors (is_count_tokens=true). ExcludeCountTokens bool - // IncludeRecoveredUpstream 显式豁免 status>=400 守卫(仅在 Phase=="upstream" 时生效): - // ops 专用上游错误列表需要看到 status<400 的 recovered upstream 行。 - // 请求错误语义的端点不设此开关,phase=upstream 过滤照常生效且守卫保留。 + // IncludeRecoveredUpstream explicitly exempts provider-health phases + // (upstream and account_auth) from the status>=400 guard. Ops provider + // health lists need status<400 recovered rows; request-error endpoints do + // not set this flag and retain client-error semantics. IncludeRecoveredUpstream bool // ErrorPhasesAny / ErrorTypesAny add plain ANY() filters WITHOUT touching the - // special-cased single `Phase` field (only Phase=="upstream" with - // IncludeRecoveredUpstream bypasses the status>=400 clause). + // special-cased single `Phase` field. With IncludeRecoveredUpstream, an ANY + // list containing only upstream/account_auth also bypasses status>=400. // NOTE: these ANY filters do NOT bypass status>=400; records with error_phase='upstream' // but status_code<400 (recovered upstream errors) remain excluded. // Used to map user-facing coarse categories to backend conditions. diff --git a/backend/internal/service/ops_service.go b/backend/internal/service/ops_service.go index 61f85ef904..3b27252665 100644 --- a/backend/internal/service/ops_service.go +++ b/backend/internal/service/ops_service.go @@ -222,6 +222,33 @@ func (s *OpsService) prepareErrorLogInput(ctx context.Context, entry *OpsInsertE entry.ErrorType = "api_error" } + // Credential acquisition is a gateway/account-auth stage, not an inference + // HTTP attempt. Enforce that ownership at the persistence boundary so an + // earlier inference attempt cannot leak its status or text into top-level + // auth fields even if a caller supplied stale single-value context. + for i := len(entry.UpstreamErrors) - 1; i >= 0; i-- { + last := entry.UpstreamErrors[i] + if last == nil { + continue + } + if last.Stage == string(GatewayFailureStageAccountAuth) { + entry.ErrorPhase = string(GatewayFailureStageAccountAuth) + entry.ErrorOwner = "provider" + entry.ErrorSource = "gateway" + code := 0 + entry.UpstreamStatusCode = &code + entry.UpstreamErrorMessage = nil + if message := strings.TrimSpace(last.Message); message != "" { + entry.UpstreamErrorMessage = &message + } + entry.UpstreamErrorDetail = nil + if detail := strings.TrimSpace(last.Detail); detail != "" { + entry.UpstreamErrorDetail = &detail + } + } + break + } + // Sanitize + truncate error_body to avoid storing sensitive data. if strings.TrimSpace(entry.ErrorBody) != "" { sanitized, _ := sanitizeErrorBodyForStorage(entry.ErrorBody, opsMaxStoredErrorBodyBytes) @@ -229,7 +256,7 @@ func (s *OpsService) prepareErrorLogInput(ctx context.Context, entry *OpsInsertE } // Sanitize upstream error context if provided by gateway services. - if entry.UpstreamStatusCode != nil && *entry.UpstreamStatusCode <= 0 { + if entry.UpstreamStatusCode != nil && *entry.UpstreamStatusCode <= 0 && entry.ErrorPhase != string(GatewayFailureStageAccountAuth) { entry.UpstreamStatusCode = nil } if entry.UpstreamErrorMessage != nil { diff --git a/backend/internal/service/ops_service_batch_test.go b/backend/internal/service/ops_service_batch_test.go index a9419ad7bf..a027f48737 100644 --- a/backend/internal/service/ops_service_batch_test.go +++ b/backend/internal/service/ops_service_batch_test.go @@ -97,6 +97,54 @@ func TestOpsServiceRecordErrorBatch_FallsBackToSingleInsert(t *testing.T) { require.Equal(t, 2, singleCalls) } +func TestOpsServiceRecordErrorPersistsExplicitAccountAuthStatusZero(t *testing.T) { + t.Parallel() + + var captured *OpsInsertErrorLogInput + repo := &opsRepoMock{ + InsertErrorLogFn: func(_ context.Context, input *OpsInsertErrorLogInput) (int64, error) { + captured = input + return 1, nil + }, + } + svc := NewOpsService(repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + staleStatus := 403 + staleMessage := "stale inference message" + staleDetail := "stale inference detail" + + err := svc.RecordError(context.Background(), &OpsInsertErrorLogInput{ + ErrorPhase: "upstream", + ErrorType: "upstream_error", + ErrorOwner: "provider", + ErrorSource: "upstream_http", + UpstreamStatusCode: &staleStatus, + UpstreamErrorMessage: &staleMessage, + UpstreamErrorDetail: &staleDetail, + UpstreamErrors: []*OpsUpstreamErrorEvent{ + {Stage: string(GatewayFailureStageInference), UpstreamStatusCode: 403, Message: staleMessage, Detail: staleDetail}, + { + Stage: string(GatewayFailureStageAccountAuth), Scope: string(GatewayFailureScopeAccount), + Reason: string(GrokCredentialReasonRevoked), Message: "Grok OAuth credentials require account action", + }, + }, + }) + + require.NoError(t, err) + require.NotNil(t, captured) + require.Equal(t, "account_auth", captured.ErrorPhase) + require.Equal(t, "provider", captured.ErrorOwner) + require.Equal(t, "gateway", captured.ErrorSource) + require.NotNil(t, captured.UpstreamStatusCode) + require.Zero(t, *captured.UpstreamStatusCode) + require.NotNil(t, captured.UpstreamErrorMessage) + require.Equal(t, "Grok OAuth credentials require account action", *captured.UpstreamErrorMessage) + require.Nil(t, captured.UpstreamErrorDetail) + require.Nil(t, captured.UpstreamErrors) + require.NotNil(t, captured.UpstreamErrorsJSON) + require.Contains(t, *captured.UpstreamErrorsJSON, `"upstream_status_code":403`) + require.Contains(t, *captured.UpstreamErrorsJSON, `"stage":"account_auth"`) +} + func strPtr(v string) *string { return &v } diff --git a/backend/internal/service/ops_upstream_context.go b/backend/internal/service/ops_upstream_context.go index 6389f1ecb5..2d28f1a168 100644 --- a/backend/internal/service/ops_upstream_context.go +++ b/backend/internal/service/ops_upstream_context.go @@ -188,6 +188,11 @@ type OpsUpstreamErrorEvent struct { // Kind: http_error | request_error | retry_exhausted | failover Kind string `json:"kind,omitempty"` + // Stage/Scope/Reason distinguish credential acquisition from inference + // without overloading upstream_status_code with a synthetic HTTP status. + Stage string `json:"stage,omitempty"` + Scope string `json:"scope,omitempty"` + Reason string `json:"reason,omitempty"` Message string `json:"message,omitempty"` Detail string `json:"detail,omitempty"` @@ -204,6 +209,9 @@ func appendOpsUpstreamError(c *gin.Context, ev OpsUpstreamErrorEvent) { ev.UpstreamRequestID = strings.TrimSpace(ev.UpstreamRequestID) ev.UpstreamResponseBody = strings.TrimSpace(ev.UpstreamResponseBody) ev.Kind = strings.TrimSpace(ev.Kind) + ev.Stage = strings.TrimSpace(ev.Stage) + ev.Scope = strings.TrimSpace(ev.Scope) + ev.Reason = strings.TrimSpace(ev.Reason) ev.UpstreamURL = strings.TrimSpace(ev.UpstreamURL) ev.Message = strings.TrimSpace(ev.Message) ev.Detail = strings.TrimSpace(ev.Detail) diff --git a/backend/internal/service/ops_user_error.go b/backend/internal/service/ops_user_error.go index e3055c2392..22d160bf34 100644 --- a/backend/internal/service/ops_user_error.go +++ b/backend/internal/service/ops_user_error.go @@ -44,7 +44,7 @@ func MapUserErrorCategory(phase, errType string) string { return "auth" case "routing": return "service_unavailable" - case "upstream", "network": + case "account_auth", "upstream", "network": return "upstream" case "internal": return "internal" @@ -73,7 +73,7 @@ func CategoryToFilter(category string) (phases []string, errorTypes []string) { case "service_unavailable": return []string{"routing"}, nil case "upstream": - return []string{"upstream", "network"}, nil + return []string{"account_auth", "upstream", "network"}, nil case "internal": return []string{"internal"}, nil case "rate_limit": diff --git a/backend/internal/service/ops_user_error_test.go b/backend/internal/service/ops_user_error_test.go index 9e0bc164b4..c72cf5dbfb 100644 --- a/backend/internal/service/ops_user_error_test.go +++ b/backend/internal/service/ops_user_error_test.go @@ -17,6 +17,7 @@ func TestMapUserErrorCategory(t *testing.T) { {"request", "subscription_error", "quota"}, {"request", "invalid_request_error", "invalid_request"}, {"routing", "api_error", "service_unavailable"}, + {"account_auth", "upstream_error", "upstream"}, {"upstream", "upstream_error", "upstream"}, {"network", "api_error", "upstream"}, {"internal", "api_error", "internal"}, @@ -43,7 +44,7 @@ func TestCategoryToFilter(t *testing.T) { t.Fatalf("service_unavailable => phases=%v types=%v", phases, types) } phases, types = CategoryToFilter("upstream") - if len(phases) != 2 || phases[0] != "upstream" || phases[1] != "network" || len(types) != 0 { + if len(phases) != 3 || phases[0] != "account_auth" || phases[1] != "upstream" || phases[2] != "network" || len(types) != 0 { t.Fatalf("upstream => phases=%v types=%v", phases, types) } phases, types = CategoryToFilter("internal") diff --git a/backend/internal/service/refresh_policy.go b/backend/internal/service/refresh_policy.go index 7f299be019..6b90077e3b 100644 --- a/backend/internal/service/refresh_policy.go +++ b/backend/internal/service/refresh_policy.go @@ -61,6 +61,14 @@ func AntigravityProviderRefreshPolicy() ProviderRefreshPolicy { } } +func GrokProviderRefreshPolicy() ProviderRefreshPolicy { + return ProviderRefreshPolicy{ + OnRefreshError: ProviderRefreshErrorReturn, + OnLockHeld: ProviderLockHeldWaitForCache, + FailureTTL: 0, + } +} + // BackgroundSkipAction 定义后台刷新服务在“未实际刷新”场景的计数方式。 type BackgroundSkipAction int diff --git a/backend/internal/service/scheduler_cache.go b/backend/internal/service/scheduler_cache.go index f9794c8214..d507d6ce2a 100644 --- a/backend/internal/service/scheduler_cache.go +++ b/backend/internal/service/scheduler_cache.go @@ -2,6 +2,7 @@ package service import ( "context" + "errors" "fmt" "strconv" "strings" @@ -14,6 +15,35 @@ const ( SchedulerModeForced = "forced" ) +var ( + ErrSchedulerBucketRetired = errors.New("scheduler bucket retired") + ErrSchedulerBucketWriteFenced = errors.New("scheduler bucket write fenced") + ErrSchedulerGroupLifecycleLeaseInvalid = errors.New("scheduler group lifecycle lease invalid") + ErrSchedulerGroupLifecycleLeaseLost = errors.New("scheduler group lifecycle lease lost") +) + +// SchedulerBucketWriteToken fences a snapshot writer to one bucket epoch. +// Tokens must be captured before any database load or queued rebuild work. +type SchedulerBucketWriteToken struct { + Bucket SchedulerBucket + Epoch int64 +} + +func (t SchedulerBucketWriteToken) ValidFor(bucket SchedulerBucket) bool { + return t.Epoch > 0 && t.Bucket == bucket +} + +// SchedulerGroupLifecycleLease identifies one owner of a group's short-lived +// retirement/reopen critical section. +type SchedulerGroupLifecycleLease struct { + GroupID int64 + OwnerToken string +} + +func (l SchedulerGroupLifecycleLease) ValidFor(groupID int64) bool { + return groupID > 0 && l.GroupID == groupID && l.OwnerToken != "" +} + type SchedulerBucket struct { GroupID int64 Platform string @@ -47,8 +77,29 @@ func ParseSchedulerBucket(raw string) (SchedulerBucket, bool) { type SchedulerCache interface { // GetSnapshot 读取快照并返回命中与否(ready + active + 数据完整)。 GetSnapshot(ctx context.Context, bucket SchedulerBucket) ([]*Account, bool, error) - // SetSnapshot 写入快照并切换激活版本。 - SetSnapshot(ctx context.Context, bucket SchedulerBucket, accounts []Account) error + // CaptureBucketWriteToken captures the current open epoch without changing + // retirement state. A tombstoned bucket returns ErrSchedulerBucketRetired. + CaptureBucketWriteToken(ctx context.Context, bucket SchedulerBucket) (SchedulerBucketWriteToken, error) + // SetSnapshot 写入快照并切换激活版本。token 必须在 DB load/任务排队前取得。 + SetSnapshot(ctx context.Context, bucket SchedulerBucket, token SchedulerBucketWriteToken, accounts []Account) error + // RetireBucket persistently tombstones a bucket and fences every older writer. + // Readers that captured the active version before retirement may finish; new + // readers observe ready/active as absent. + RetireBucket(ctx context.Context, bucket SchedulerBucket) error + // ReopenBucket is the only operation allowed to clear a tombstone. It returns + // the retirement generation established by RetireBucket; repeated calls for + // the same generation are idempotent. Callers must serialize a fresh authority + // check through ReopenBucket with RetireBucket under the same group lifecycle + // lease; ordinary rebuild paths never call ReopenBucket. + ReopenBucket(ctx context.Context, bucket SchedulerBucket) (SchedulerBucketWriteToken, error) + // TryAcquireGroupLifecycleLease serializes authoritative retirement/reopen + // decisions for one non-zero group across instances. + TryAcquireGroupLifecycleLease(ctx context.Context, groupID int64, ttl time.Duration) (SchedulerGroupLifecycleLease, bool, error) + // ReleaseGroupLifecycleLease releases the lease only if its owner token still + // matches, so an expired holder cannot delete a successor's lease. Missing, + // expired, mismatched, and already released leases return + // ErrSchedulerGroupLifecycleLeaseLost. + ReleaseGroupLifecycleLease(ctx context.Context, lease SchedulerGroupLifecycleLease) error // GetAccount 获取单账号快照。 GetAccount(ctx context.Context, accountID int64) (*Account, error) // SetAccount 写入单账号快照(包含不可调度状态)。 diff --git a/backend/internal/service/scheduler_snapshot_batch_query_test.go b/backend/internal/service/scheduler_snapshot_batch_query_test.go new file mode 100644 index 0000000000..a2e7ae8e85 --- /dev/null +++ b/backend/internal/service/scheduler_snapshot_batch_query_test.go @@ -0,0 +1,534 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +type batchAccountQueryKey struct { + groupID int64 + platform string + mixed bool +} + +type batchAccountQueryResult struct { + accounts []Account + err error +} + +type batchAccountQueryRepo struct { + AccountRepository + + mu sync.Mutex + calls map[batchAccountQueryKey]int + results map[batchAccountQueryKey][]batchAccountQueryResult + beforeRun func(batchAccountQueryKey) +} + +func newBatchAccountQueryRepo() *batchAccountQueryRepo { + return &batchAccountQueryRepo{ + calls: make(map[batchAccountQueryKey]int), + results: make(map[batchAccountQueryKey][]batchAccountQueryResult), + } +} + +func (r *batchAccountQueryRepo) ListSchedulableByGroupIDAndPlatform(_ context.Context, groupID int64, platform string) ([]Account, error) { + return r.run(batchAccountQueryKey{groupID: groupID, platform: platform}) +} + +func (r *batchAccountQueryRepo) ListSchedulableByGroupIDAndPlatforms(_ context.Context, groupID int64, platforms []string) ([]Account, error) { + return r.run(batchAccountQueryKey{groupID: groupID, platform: platforms[0], mixed: true}) +} + +func (r *batchAccountQueryRepo) ListSchedulableUngroupedByPlatform(_ context.Context, platform string) ([]Account, error) { + return r.run(batchAccountQueryKey{platform: platform}) +} + +func (r *batchAccountQueryRepo) ListSchedulableUngroupedByPlatforms(_ context.Context, platforms []string) ([]Account, error) { + return r.run(batchAccountQueryKey{platform: platforms[0], mixed: true}) +} + +func (r *batchAccountQueryRepo) ListSchedulableByPlatform(_ context.Context, platform string) ([]Account, error) { + return r.run(batchAccountQueryKey{platform: platform}) +} + +func (r *batchAccountQueryRepo) ListSchedulableByPlatforms(_ context.Context, platforms []string) ([]Account, error) { + return r.run(batchAccountQueryKey{platform: platforms[0], mixed: true}) +} + +func (r *batchAccountQueryRepo) run(key batchAccountQueryKey) ([]Account, error) { + r.mu.Lock() + r.calls[key]++ + call := r.calls[key] + results := r.results[key] + beforeRun := r.beforeRun + r.mu.Unlock() + + if beforeRun != nil { + beforeRun(key) + } + if call <= len(results) { + result := results[call-1] + return append([]Account(nil), result.accounts...), result.err + } + return []Account{{ + ID: int64(call), + Name: "source", + Platform: key.platform, + Status: StatusActive, + Schedulable: true, + }}, nil +} + +func (r *batchAccountQueryRepo) callCount(key batchAccountQueryKey) int { + r.mu.Lock() + defer r.mu.Unlock() + return r.calls[key] +} + +type batchSnapshotWrite struct { + token SchedulerBucketWriteToken + accounts []Account +} + +type batchSnapshotCache struct { + SchedulerCache + + mu sync.Mutex + nextEpoch int64 + captures []SchedulerBucket + captured map[SchedulerBucket]SchedulerBucketWriteToken + locks map[SchedulerBucket]int + lockBusy map[SchedulerBucket]bool + lockErrors map[SchedulerBucket]error + setErrors map[SchedulerBucket]error + setAttempts map[SchedulerBucket]int + writes map[SchedulerBucket][]batchSnapshotWrite + versions map[SchedulerBucket]int + beforeSet func() +} + +func newBatchSnapshotCache() *batchSnapshotCache { + return &batchSnapshotCache{ + captured: make(map[SchedulerBucket]SchedulerBucketWriteToken), + locks: make(map[SchedulerBucket]int), + lockBusy: make(map[SchedulerBucket]bool), + lockErrors: make(map[SchedulerBucket]error), + setErrors: make(map[SchedulerBucket]error), + setAttempts: make(map[SchedulerBucket]int), + writes: make(map[SchedulerBucket][]batchSnapshotWrite), + versions: make(map[SchedulerBucket]int), + } +} + +func (c *batchSnapshotCache) CaptureBucketWriteToken(_ context.Context, bucket SchedulerBucket) (SchedulerBucketWriteToken, error) { + c.mu.Lock() + defer c.mu.Unlock() + c.nextEpoch++ + token := SchedulerBucketWriteToken{Bucket: bucket, Epoch: c.nextEpoch} + c.captures = append(c.captures, bucket) + c.captured[bucket] = token + return token, nil +} + +func (c *batchSnapshotCache) TryLockBucket(_ context.Context, bucket SchedulerBucket, _ time.Duration) (bool, error) { + c.mu.Lock() + defer c.mu.Unlock() + c.locks[bucket]++ + if err := c.lockErrors[bucket]; err != nil { + return false, err + } + return !c.lockBusy[bucket], nil +} + +func (c *batchSnapshotCache) UnlockBucket(context.Context, SchedulerBucket) error { + return nil +} + +func (c *batchSnapshotCache) SetSnapshot(_ context.Context, bucket SchedulerBucket, token SchedulerBucketWriteToken, accounts []Account) error { + if c.beforeSet != nil { + c.beforeSet() + } + c.mu.Lock() + defer c.mu.Unlock() + c.setAttempts[bucket]++ + if token != c.captured[bucket] || !token.ValidFor(bucket) { + return ErrSchedulerBucketWriteFenced + } + if err := c.setErrors[bucket]; err != nil { + return err + } + c.versions[bucket]++ + c.writes[bucket] = append(c.writes[bucket], batchSnapshotWrite{ + token: token, + accounts: append([]Account(nil), accounts...), + }) + return nil +} + +func (c *batchSnapshotCache) captureCount() int { + c.mu.Lock() + defer c.mu.Unlock() + return len(c.captures) +} + +func (c *batchSnapshotCache) bucketState(bucket SchedulerBucket) (locks, attempts, version int, writes []batchSnapshotWrite) { + c.mu.Lock() + defer c.mu.Unlock() + return c.locks[bucket], c.setAttempts[bucket], c.versions[bucket], append([]batchSnapshotWrite(nil), c.writes[bucket]...) +} + +func newBatchQueryTestService(cache SchedulerCache, accounts AccountRepository, runMode string) *SchedulerSnapshotService { + return NewSchedulerSnapshotService(cache, nil, accounts, nil, &config.Config{RunMode: runMode}) +} + +func TestSchedulerRebuildBatchReusesSingleForcedQueryAndKeepsSnapshotsIndependent(t *testing.T) { + const groupID int64 = 201 + single := SchedulerBucket{GroupID: groupID, Platform: PlatformOpenAI, Mode: SchedulerModeSingle} + forced := SchedulerBucket{GroupID: groupID, Platform: PlatformOpenAI, Mode: SchedulerModeForced} + cache := newBatchSnapshotCache() + repo := newBatchAccountQueryRepo() + wantCaptures := 2 + repo.beforeRun = func(batchAccountQueryKey) { + require.Equal(t, wantCaptures, cache.captureCount(), "all tokens must be prepared before the first DB query") + wantCaptures += 2 + } + svc := newBatchQueryTestService(cache, repo, config.RunModeStandard) + + require.NoError(t, svc.rebuildBuckets(context.Background(), []SchedulerBucket{single, forced}, "first")) + queryKey := batchAccountQueryKey{groupID: groupID, platform: PlatformOpenAI} + require.Equal(t, 1, repo.callCount(queryKey)) + for _, bucket := range []SchedulerBucket{single, forced} { + locks, attempts, version, writes := cache.bucketState(bucket) + require.Equal(t, 1, locks, bucket.String()) + require.Equal(t, 1, attempts, bucket.String()) + require.Equal(t, 1, version, bucket.String()) + require.Len(t, writes, 1, bucket.String()) + require.Equal(t, "source", writes[0].accounts[0].Name, bucket.String()) + require.Equal(t, bucket, writes[0].token.Bucket) + } + _, _, _, singleWrites := cache.bucketState(single) + _, _, _, forcedWrites := cache.bucketState(forced) + require.NotEqual(t, singleWrites[0].token.Epoch, forcedWrites[0].token.Epoch) + + require.NoError(t, svc.rebuildBuckets(context.Background(), []SchedulerBucket{single, forced}, "second")) + require.Equal(t, 2, repo.callCount(queryKey), "successful results must not be cached across rebuild batches") + for _, bucket := range []SchedulerBucket{single, forced} { + locks, attempts, version, writes := cache.bucketState(bucket) + require.Equal(t, 2, locks, bucket.String()) + require.Equal(t, 2, attempts, bucket.String()) + require.Equal(t, 2, version, bucket.String()) + require.Len(t, writes, 2, bucket.String()) + require.Equal(t, "source", writes[1].accounts[0].Name, bucket.String()) + } +} + +func TestSchedulerRebuildBatchKeepsMixedAndDifferentKeysIndependent(t *testing.T) { + const groupID int64 = 202 + buckets := []SchedulerBucket{ + {GroupID: groupID, Platform: PlatformAnthropic, Mode: SchedulerModeSingle}, + {GroupID: groupID, Platform: PlatformAnthropic, Mode: SchedulerModeForced}, + {GroupID: groupID, Platform: PlatformAnthropic, Mode: SchedulerModeMixed}, + {GroupID: groupID + 1, Platform: PlatformAnthropic, Mode: SchedulerModeSingle}, + {GroupID: groupID, Platform: PlatformGemini, Mode: SchedulerModeForced}, + {GroupID: 0, Platform: PlatformOpenAI, Mode: SchedulerModeSingle}, + {GroupID: -1, Platform: PlatformOpenAI, Mode: SchedulerModeForced}, + } + cache := newBatchSnapshotCache() + repo := newBatchAccountQueryRepo() + svc := newBatchQueryTestService(cache, repo, config.RunModeStandard) + + require.NoError(t, svc.rebuildBuckets(context.Background(), buckets, "test")) + require.Equal(t, 1, repo.callCount(batchAccountQueryKey{groupID: groupID, platform: PlatformAnthropic})) + require.Equal(t, 1, repo.callCount(batchAccountQueryKey{groupID: groupID, platform: PlatformAnthropic, mixed: true})) + require.Equal(t, 1, repo.callCount(batchAccountQueryKey{groupID: groupID + 1, platform: PlatformAnthropic})) + require.Equal(t, 1, repo.callCount(batchAccountQueryKey{groupID: groupID, platform: PlatformGemini})) + require.Equal(t, 2, repo.callCount(batchAccountQueryKey{platform: PlatformOpenAI}), "group0 and a negative historical group must not share") + for _, bucket := range buckets { + locks, attempts, version, _ := cache.bucketState(bucket) + require.Equal(t, 1, locks, bucket.String()) + require.Equal(t, 1, attempts, bucket.String()) + require.Equal(t, 1, version, bucket.String()) + } +} + +func TestSchedulerRebuildBatchKeepsSimpleModeBucketGroupsIndependent(t *testing.T) { + single := SchedulerBucket{GroupID: 204, Platform: PlatformOpenAI, Mode: SchedulerModeSingle} + forced := SchedulerBucket{GroupID: 0, Platform: PlatformOpenAI, Mode: SchedulerModeForced} + cache := newBatchSnapshotCache() + repo := newBatchAccountQueryRepo() + svc := newBatchQueryTestService(cache, repo, config.RunModeSimple) + + require.NoError(t, svc.rebuildBuckets(context.Background(), []SchedulerBucket{single, forced}, "test")) + require.Equal(t, 2, repo.callCount(batchAccountQueryKey{platform: PlatformOpenAI})) +} + +func TestSchedulerRebuildBatchDoesNotCacheMixedOrHistoricalQueries(t *testing.T) { + for _, tc := range []struct { + name string + bucket SchedulerBucket + key batchAccountQueryKey + }{ + { + name: "mixed", + bucket: SchedulerBucket{GroupID: 204, Platform: PlatformAnthropic, Mode: SchedulerModeMixed}, + key: batchAccountQueryKey{groupID: 204, platform: PlatformAnthropic, mixed: true}, + }, + { + name: "historical", + bucket: SchedulerBucket{GroupID: 204, Platform: PlatformOpenAI, Mode: "unknown"}, + key: batchAccountQueryKey{groupID: 204, platform: PlatformOpenAI}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + cache := newBatchSnapshotCache() + token, err := cache.CaptureBucketWriteToken(context.Background(), tc.bucket) + require.NoError(t, err) + repo := newBatchAccountQueryRepo() + svc := newBatchQueryTestService(cache, repo, config.RunModeStandard) + tasks := []schedulerBucketWriteTask{ + {bucket: tc.bucket, token: token}, + {bucket: tc.bucket, token: token}, + } + queries := newSchedulerAccountQueryCache(tasks) + + require.NoError(t, svc.rebuildPreparedBucketTasks(context.Background(), tasks, "test", false, queries)) + require.Equal(t, 2, repo.callCount(tc.key)) + require.Empty(t, queries.accounts) + locks, attempts, version, _ := cache.bucketState(tc.bucket) + require.Equal(t, 2, locks) + require.Equal(t, 2, attempts) + require.Equal(t, 2, version) + }) + } +} + +func TestSchedulerRebuildBatchRetriesQueryFailureForFollowingBucket(t *testing.T) { + const groupID int64 = 205 + single := SchedulerBucket{GroupID: groupID, Platform: PlatformOpenAI, Mode: SchedulerModeSingle} + forced := SchedulerBucket{GroupID: groupID, Platform: PlatformOpenAI, Mode: SchedulerModeForced} + wantErr := errors.New("first query failed") + key := batchAccountQueryKey{groupID: groupID, platform: PlatformOpenAI} + repo := newBatchAccountQueryRepo() + repo.results[key] = []batchAccountQueryResult{ + {err: wantErr}, + {accounts: []Account{{ID: 2051, Name: "retry", Platform: PlatformOpenAI}}}, + } + cache := newBatchSnapshotCache() + svc := newBatchQueryTestService(cache, repo, config.RunModeStandard) + + err := svc.rebuildBuckets(context.Background(), []SchedulerBucket{single, forced}, "test") + require.ErrorIs(t, err, wantErr) + require.Equal(t, 2, repo.callCount(key), "failed queries must not enter the batch cache") + _, singleAttempts, singleVersion, _ := cache.bucketState(single) + _, forcedAttempts, forcedVersion, forcedWrites := cache.bucketState(forced) + require.Zero(t, singleAttempts) + require.Zero(t, singleVersion) + require.Equal(t, 1, forcedAttempts) + require.Equal(t, 1, forcedVersion) + require.Equal(t, "retry", forcedWrites[0].accounts[0].Name) +} + +func TestSchedulerFullRebuildSharesSuccessfulQueryAcrossStrictAndOrdinarySegments(t *testing.T) { + const groupID int64 = 206 + single := SchedulerBucket{GroupID: groupID, Platform: PlatformOpenAI, Mode: SchedulerModeSingle} + forced := SchedulerBucket{GroupID: groupID, Platform: PlatformOpenAI, Mode: SchedulerModeForced} + cache := newBatchSnapshotCache() + cache.setErrors[single] = ErrSchedulerBucketWriteFenced + singleToken, err := cache.CaptureBucketWriteToken(context.Background(), single) + require.NoError(t, err) + forcedToken, err := cache.CaptureBucketWriteToken(context.Background(), forced) + require.NoError(t, err) + repo := newBatchAccountQueryRepo() + svc := newBatchQueryTestService(cache, repo, config.RunModeStandard) + + err = svc.prepareAndRebuildFullSnapshot( + context.Background(), + []schedulerBucketWriteTask{{bucket: forced, token: forcedToken}}, + []schedulerBucketWriteTask{{bucket: single, token: singleToken}}, + nil, + "test", + ) + require.ErrorIs(t, err, ErrSchedulerBucketWriteFenced) + require.Equal(t, 1, repo.callCount(batchAccountQueryKey{groupID: groupID, platform: PlatformOpenAI}), "SetSnapshot failure must not discard a successful query") + _, singleAttempts, singleVersion, _ := cache.bucketState(single) + _, forcedAttempts, forcedVersion, _ := cache.bucketState(forced) + require.Equal(t, 1, singleAttempts) + require.Zero(t, singleVersion) + require.Equal(t, 1, forcedAttempts) + require.Equal(t, 1, forcedVersion) +} + +func TestSchedulerRebuildBatchPreservesLockBusyAndFencingPolicy(t *testing.T) { + const groupID int64 = 207 + single := SchedulerBucket{GroupID: groupID, Platform: PlatformOpenAI, Mode: SchedulerModeSingle} + forced := SchedulerBucket{GroupID: groupID, Platform: PlatformOpenAI, Mode: SchedulerModeForced} + + t.Run("ordinary lock busy skips only that bucket", func(t *testing.T) { + cache := newBatchSnapshotCache() + cache.lockBusy[single] = true + repo := newBatchAccountQueryRepo() + svc := newBatchQueryTestService(cache, repo, config.RunModeStandard) + + require.NoError(t, svc.rebuildBuckets(context.Background(), []SchedulerBucket{single, forced}, "test")) + require.Equal(t, 1, repo.callCount(batchAccountQueryKey{groupID: groupID, platform: PlatformOpenAI})) + _, singleAttempts, _, _ := cache.bucketState(single) + _, forcedAttempts, forcedVersion, _ := cache.bucketState(forced) + require.Zero(t, singleAttempts) + require.Equal(t, 1, forcedAttempts) + require.Equal(t, 1, forcedVersion) + }) + + t.Run("strict lock busy is returned while ordinary work continues", func(t *testing.T) { + cache := newBatchSnapshotCache() + cache.lockBusy[single] = true + singleToken, err := cache.CaptureBucketWriteToken(context.Background(), single) + require.NoError(t, err) + forcedToken, err := cache.CaptureBucketWriteToken(context.Background(), forced) + require.NoError(t, err) + repo := newBatchAccountQueryRepo() + svc := newBatchQueryTestService(cache, repo, config.RunModeStandard) + + err = svc.prepareAndRebuildFullSnapshot( + context.Background(), + []schedulerBucketWriteTask{{bucket: forced, token: forcedToken}}, + []schedulerBucketWriteTask{{bucket: single, token: singleToken}}, + nil, + "test", + ) + require.ErrorIs(t, err, ErrSchedulerBucketRebuildBusy) + require.Equal(t, 1, repo.callCount(batchAccountQueryKey{groupID: groupID, platform: PlatformOpenAI})) + _, forcedAttempts, forcedVersion, _ := cache.bucketState(forced) + require.Equal(t, 1, forcedAttempts) + require.Equal(t, 1, forcedVersion) + }) + + t.Run("ordinary fencing stays non-fatal", func(t *testing.T) { + cache := newBatchSnapshotCache() + cache.setErrors[single] = ErrSchedulerBucketWriteFenced + repo := newBatchAccountQueryRepo() + svc := newBatchQueryTestService(cache, repo, config.RunModeStandard) + + require.NoError(t, svc.rebuildBuckets(context.Background(), []SchedulerBucket{single, forced}, "test")) + require.Equal(t, 1, repo.callCount(batchAccountQueryKey{groupID: groupID, platform: PlatformOpenAI})) + _, singleAttempts, singleVersion, _ := cache.bucketState(single) + _, forcedAttempts, forcedVersion, _ := cache.bucketState(forced) + require.Equal(t, 1, singleAttempts) + require.Zero(t, singleVersion) + require.Equal(t, 1, forcedAttempts) + require.Equal(t, 1, forcedVersion) + }) +} + +func TestSchedulerRebuildBatchReleasesResultsAfterLastConsumer(t *testing.T) { + const groups = 128 + cache := newBatchSnapshotCache() + repo := newBatchAccountQueryRepo() + tasks := make([]schedulerBucketWriteTask, 0, groups*2) + wantLockErr := errors.New("lock failed") + for i := 1; i <= groups; i++ { + groupID := int64(300 + i) + single := SchedulerBucket{GroupID: groupID, Platform: PlatformOpenAI, Mode: SchedulerModeSingle} + forced := SchedulerBucket{GroupID: groupID, Platform: PlatformOpenAI, Mode: SchedulerModeForced} + if i == 1 { + cache.lockBusy[single] = true + } + if i == 2 { + cache.lockErrors[single] = wantLockErr + } + for _, bucket := range []SchedulerBucket{single, forced} { + token, err := cache.CaptureBucketWriteToken(context.Background(), bucket) + require.NoError(t, err) + tasks = append(tasks, schedulerBucketWriteTask{bucket: bucket, token: token}) + } + } + queries := newSchedulerAccountQueryCache(tasks) + maxResident := 0 + cache.beforeSet = func() { + if resident := len(queries.accounts); resident > maxResident { + maxResident = resident + } + } + svc := newBatchQueryTestService(cache, repo, config.RunModeStandard) + + err := svc.rebuildPreparedBucketTasks(context.Background(), tasks, "test", false, queries) + require.ErrorIs(t, err, wantLockErr) + require.LessOrEqual(t, maxResident, 1, "adjacent single/forced pairs must not accumulate full-batch results") + require.Empty(t, queries.accounts) + require.Empty(t, queries.remaining) + for i := 1; i <= groups; i++ { + key := batchAccountQueryKey{groupID: int64(300 + i), platform: PlatformOpenAI} + require.Equal(t, 1, repo.callCount(key), key) + } +} + +type batchQueryBenchmarkRepo struct { + AccountRepository + accounts []Account +} + +func (r *batchQueryBenchmarkRepo) ListSchedulableByGroupIDAndPlatform(context.Context, int64, string) ([]Account, error) { + return r.accounts, nil +} + +type batchQueryBenchmarkCache struct { + SchedulerCache +} + +func (c *batchQueryBenchmarkCache) CaptureBucketWriteToken(_ context.Context, bucket SchedulerBucket) (SchedulerBucketWriteToken, error) { + return SchedulerBucketWriteToken{Bucket: bucket, Epoch: 1}, nil +} + +func (c *batchQueryBenchmarkCache) TryLockBucket(context.Context, SchedulerBucket, time.Duration) (bool, error) { + return true, nil +} + +func (c *batchQueryBenchmarkCache) UnlockBucket(context.Context, SchedulerBucket) error { + return nil +} + +var batchQueryBenchmarkAccountCount int + +func (c *batchQueryBenchmarkCache) SetSnapshot(_ context.Context, _ SchedulerBucket, _ SchedulerBucketWriteToken, accounts []Account) error { + batchQueryBenchmarkAccountCount = len(accounts) + return nil +} + +func BenchmarkSchedulerRebuildBatchQueryReuse(b *testing.B) { + const groupID int64 = 208 + buckets := []SchedulerBucket{ + {GroupID: groupID, Platform: PlatformOpenAI, Mode: SchedulerModeSingle}, + {GroupID: groupID, Platform: PlatformOpenAI, Mode: SchedulerModeForced}, + } + for _, tc := range []struct { + name string + size int + }{ + {name: "1_account", size: 1}, + {name: "10000_accounts", size: 10_000}, + } { + b.Run(tc.name, func(b *testing.B) { + accounts := make([]Account, tc.size) + svc := newBatchQueryTestService( + &batchQueryBenchmarkCache{}, + &batchQueryBenchmarkRepo{accounts: accounts}, + config.RunModeStandard, + ) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + if err := svc.rebuildBuckets(context.Background(), buckets, "benchmark"); err != nil { + b.Fatal(err) + } + } + }) + } +} diff --git a/backend/internal/service/scheduler_snapshot_full_rebuild_lifecycle_test.go b/backend/internal/service/scheduler_snapshot_full_rebuild_lifecycle_test.go new file mode 100644 index 0000000000..35ce99a8d1 --- /dev/null +++ b/backend/internal/service/scheduler_snapshot_full_rebuild_lifecycle_test.go @@ -0,0 +1,666 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +type fullRebuildLifecycleCache struct { + *groupLifecycleTestCache + + mu sync.Mutex + captureAttempts []SchedulerBucket + captureErrors map[string]error + lockBusyOnce map[string]bool + watermark int64 + watermarkWrites []int64 +} + +func newFullRebuildLifecycleCache(buckets ...SchedulerBucket) *fullRebuildLifecycleCache { + return &fullRebuildLifecycleCache{ + groupLifecycleTestCache: newGroupLifecycleTestCache(buckets...), + captureErrors: make(map[string]error), + lockBusyOnce: make(map[string]bool), + } +} + +func (c *fullRebuildLifecycleCache) CaptureBucketWriteToken(ctx context.Context, bucket SchedulerBucket) (SchedulerBucketWriteToken, error) { + c.mu.Lock() + c.captureAttempts = append(c.captureAttempts, bucket) + err := c.captureErrors[bucket.String()] + c.mu.Unlock() + if err != nil { + return SchedulerBucketWriteToken{}, err + } + return c.retirementRaceCache.CaptureBucketWriteToken(ctx, bucket) +} + +func (c *fullRebuildLifecycleCache) ListBuckets(ctx context.Context) ([]SchedulerBucket, error) { + buckets, err := c.groupLifecycleTestCache.ListBuckets(ctx) + if err != nil { + return nil, err + } + c.retirementRaceCache.mu.Lock() + defer c.retirementRaceCache.mu.Unlock() + registered := make([]SchedulerBucket, 0, len(buckets)) + for _, bucket := range buckets { + if !c.retirementRaceCache.retired[bucket.String()] { + registered = append(registered, bucket) + } + } + return registered, nil +} + +func (c *fullRebuildLifecycleCache) TryLockBucket(ctx context.Context, bucket SchedulerBucket, ttl time.Duration) (bool, error) { + c.mu.Lock() + busy := c.lockBusyOnce[bucket.String()] + if busy { + delete(c.lockBusyOnce, bucket.String()) + } + c.mu.Unlock() + if busy { + return false, nil + } + return c.groupLifecycleTestCache.TryLockBucket(ctx, bucket, ttl) +} + +func (c *fullRebuildLifecycleCache) GetOutboxWatermark(context.Context) (int64, error) { + c.mu.Lock() + defer c.mu.Unlock() + return c.watermark, nil +} + +func (c *fullRebuildLifecycleCache) SetOutboxWatermark(_ context.Context, id int64) error { + c.mu.Lock() + defer c.mu.Unlock() + c.watermark = id + c.watermarkWrites = append(c.watermarkWrites, id) + return nil +} + +func (c *fullRebuildLifecycleCache) captureAttemptCount() int { + c.mu.Lock() + defer c.mu.Unlock() + return len(c.captureAttempts) +} + +func (c *fullRebuildLifecycleCache) currentWatermark() int64 { + c.mu.Lock() + defer c.mu.Unlock() + return c.watermark +} + +func (c *fullRebuildLifecycleCache) totalSetAttempts() int { + c.retirementRaceCache.mu.Lock() + defer c.retirementRaceCache.mu.Unlock() + var total int + for _, attempts := range c.retirementRaceCache.setAttempts { + total += attempts + } + return total +} + +type fullRebuildLifecycleGroupRepo struct { + GroupRepository + + mu sync.Mutex + activeIDs []int64 + activeIDsErr error + listActiveErr error + fresh map[int64]*Group + freshErr map[int64]error + activeIDCalls int + listActiveCalls int + freshCalls []int64 +} + +func (r *fullRebuildLifecycleGroupRepo) ListActiveIDs(context.Context) ([]int64, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.activeIDCalls++ + return append([]int64(nil), r.activeIDs...), r.activeIDsErr +} + +func (r *fullRebuildLifecycleGroupRepo) ListActive(context.Context) ([]Group, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.listActiveCalls++ + return nil, r.listActiveErr +} + +func (r *fullRebuildLifecycleGroupRepo) GetByIDLite(_ context.Context, id int64) (*Group, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.freshCalls = append(r.freshCalls, id) + if err := r.freshErr[id]; err != nil { + return nil, err + } + group := r.fresh[id] + if group == nil { + return nil, ErrGroupNotFound + } + copyGroup := *group + return ©Group, nil +} + +func (r *fullRebuildLifecycleGroupRepo) stats() (activeIDs, listActive int, fresh []int64) { + r.mu.Lock() + defer r.mu.Unlock() + return r.activeIDCalls, r.listActiveCalls, append([]int64(nil), r.freshCalls...) +} + +type fullRebuildFallbackGroupRepo struct { + GroupRepository + + mu sync.Mutex + groups []Group + err error + listCalls int +} + +func (r *fullRebuildFallbackGroupRepo) ListActive(context.Context) ([]Group, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.listCalls++ + return append([]Group(nil), r.groups...), r.err +} + +type fullRebuildAccountCall struct { + groupID int64 + platform string +} + +type fullRebuildAccountRepo struct { + AccountRepository + + mu sync.Mutex + calls []fullRebuildAccountCall + beforeFirst func() + once sync.Once +} + +func (r *fullRebuildAccountRepo) record(groupID int64, platform string) ([]Account, error) { + r.mu.Lock() + r.calls = append(r.calls, fullRebuildAccountCall{groupID: groupID, platform: platform}) + beforeFirst := r.beforeFirst + r.mu.Unlock() + if beforeFirst != nil { + r.once.Do(beforeFirst) + } + return []Account{{ID: 1, Platform: platform, Status: StatusActive, Schedulable: true}}, nil +} + +func (r *fullRebuildAccountRepo) ListSchedulableByGroupIDAndPlatform(_ context.Context, groupID int64, platform string) ([]Account, error) { + return r.record(groupID, platform) +} + +func (r *fullRebuildAccountRepo) ListSchedulableByGroupIDAndPlatforms(_ context.Context, groupID int64, platforms []string) ([]Account, error) { + return r.record(groupID, firstPlatform(platforms)) +} + +func (r *fullRebuildAccountRepo) ListSchedulableUngroupedByPlatform(_ context.Context, platform string) ([]Account, error) { + return r.record(0, platform) +} + +func (r *fullRebuildAccountRepo) ListSchedulableUngroupedByPlatforms(_ context.Context, platforms []string) ([]Account, error) { + return r.record(0, firstPlatform(platforms)) +} + +func (r *fullRebuildAccountRepo) ListSchedulableByPlatform(_ context.Context, platform string) ([]Account, error) { + return r.record(0, platform) +} + +func (r *fullRebuildAccountRepo) ListSchedulableByPlatforms(_ context.Context, platforms []string) ([]Account, error) { + return r.record(0, firstPlatform(platforms)) +} + +func (r *fullRebuildAccountRepo) callCount() int { + r.mu.Lock() + defer r.mu.Unlock() + return len(r.calls) +} + +func (r *fullRebuildAccountRepo) groupCallCount(groupID int64) int { + r.mu.Lock() + defer r.mu.Unlock() + var count int + for _, call := range r.calls { + if call.groupID == groupID { + count++ + } + } + return count +} + +func firstPlatform(platforms []string) string { + if len(platforms) == 0 { + return "" + } + return platforms[0] +} + +func newFullRebuildLifecycleService( + cache SchedulerCache, + outbox SchedulerOutboxRepository, + accounts AccountRepository, + groups GroupRepository, + runMode string, +) *SchedulerSnapshotService { + return NewSchedulerSnapshotService(cache, outbox, accounts, groups, &config.Config{RunMode: runMode}) +} + +func TestSchedulerFullRebuildActiveTombstoneDoesNotBlockFollowingGroupEvent(t *testing.T) { + const groupID int64 = 101 + canonical := schedulerBucketsForGroup(groupID) + cache := newFullRebuildLifecycleCache() + require.NoError(t, cache.retirementRaceCache.RetireBucket(context.Background(), canonical[0])) + groups := &fullRebuildLifecycleGroupRepo{ + activeIDs: []int64{groupID}, + fresh: map[int64]*Group{ + groupID: {ID: groupID, Status: StatusActive, Hydrated: true}, + }, + freshErr: make(map[int64]error), + } + accounts := &fullRebuildAccountRepo{} + outbox := &outboxCleanupRepo{events: []SchedulerOutboxEvent{ + {ID: 1, EventType: SchedulerOutboxEventFullRebuild}, + {ID: 2, EventType: SchedulerOutboxEventGroupChanged, GroupID: ptrInt64(groupID)}, + }} + svc := newFullRebuildLifecycleService(cache, outbox, accounts, groups, config.RunModeStandard) + + svc.pollOutbox() + + require.Equal(t, int64(2), cache.currentWatermark()) + cache.mu.Lock() + require.Equal(t, []int64{2}, cache.watermarkWrites) + cache.mu.Unlock() + activeCalls, fallbackCalls, freshCalls := groups.stats() + require.Equal(t, 1, activeCalls) + require.Zero(t, fallbackCalls) + require.Equal(t, []int64{groupID, groupID}, freshCalls) + require.Len(t, cache.tokens(), 24, "full rebuild and the following group event must each run fresh authority") + _, reopenHeld := cache.lifecycleMutationLeaseStates() + require.Len(t, reopenHeld, 24) + for _, held := range reopenHeld { + require.True(t, held) + } + require.Equal(t, 21, accounts.callCount()) +} + +func TestSchedulerFullRebuildGlobalReadErrorsFailBeforeMutationOrDB(t *testing.T) { + t.Run("list buckets", func(t *testing.T) { + cache := newFullRebuildLifecycleCache() + cache.listErr = errors.New("registry failed") + groups := &fullRebuildLifecycleGroupRepo{fresh: make(map[int64]*Group), freshErr: make(map[int64]error)} + accounts := &fullRebuildAccountRepo{} + svc := newFullRebuildLifecycleService(cache, nil, accounts, groups, config.RunModeStandard) + + err := svc.rebuildFullSnapshot(context.Background(), "test") + require.ErrorIs(t, err, cache.listErr) + activeCalls, fallbackCalls, freshCalls := groups.stats() + require.Zero(t, activeCalls) + require.Zero(t, fallbackCalls) + require.Empty(t, freshCalls) + requireFullRebuildNoMutationOrDB(t, cache, accounts) + }) + + t.Run("list active ids without fallback", func(t *testing.T) { + cache := newFullRebuildLifecycleCache() + groups := &fullRebuildLifecycleGroupRepo{ + activeIDsErr: errors.New("active ids failed"), + listActiveErr: errors.New("fallback must not run"), + fresh: make(map[int64]*Group), + freshErr: make(map[int64]error), + } + accounts := &fullRebuildAccountRepo{} + svc := newFullRebuildLifecycleService(cache, nil, accounts, groups, config.RunModeStandard) + + err := svc.rebuildFullSnapshot(context.Background(), "test") + require.ErrorIs(t, err, groups.activeIDsErr) + activeCalls, fallbackCalls, freshCalls := groups.stats() + require.Equal(t, 1, activeCalls) + require.Zero(t, fallbackCalls) + require.Empty(t, freshCalls) + requireFullRebuildNoMutationOrDB(t, cache, accounts) + }) + + t.Run("list active fallback", func(t *testing.T) { + cache := newFullRebuildLifecycleCache() + groups := &fullRebuildFallbackGroupRepo{err: errors.New("active groups failed")} + accounts := &fullRebuildAccountRepo{} + svc := newFullRebuildLifecycleService(cache, nil, accounts, groups, config.RunModeStandard) + + err := svc.rebuildFullSnapshot(context.Background(), "test") + require.ErrorIs(t, err, groups.err) + groups.mu.Lock() + require.Equal(t, 1, groups.listCalls) + groups.mu.Unlock() + requireFullRebuildNoMutationOrDB(t, cache, accounts) + }) +} + +func TestSchedulerFullRebuildFreshActivePreparesEveryTokenBeforeFirstDB(t *testing.T) { + const groupID int64 = 102 + historical := SchedulerBucket{GroupID: groupID, Platform: "legacy", Mode: "unknown"} + cache := newFullRebuildLifecycleCache(historical) + groups := &fullRebuildLifecycleGroupRepo{ + fresh: map[int64]*Group{ + groupID: {ID: groupID, Status: StatusActive, Hydrated: true}, + }, + freshErr: make(map[int64]error), + } + accounts := &fullRebuildAccountRepo{} + var capturesAtFirstDB int + accounts.beforeFirst = func() { + capturesAtFirstDB = cache.captureAttemptCount() + held, reopenCount := cache.leaseHeldAndTokenCount() + require.False(t, held) + require.Equal(t, 12, reopenCount) + require.Equal(t, 13, capturesAtFirstDB, "C(0) and the historical bucket must be captured before DB") + } + svc := newFullRebuildLifecycleService(cache, nil, accounts, groups, config.RunModeStandard) + + require.NoError(t, svc.rebuildFullSnapshot(context.Background(), "test")) + require.Equal(t, capturesAtFirstDB, cache.captureAttemptCount()) + require.Equal(t, 15, accounts.callCount()) + require.Equal(t, 8, accounts.groupCallCount(groupID)) + _, historicalPublished := cache.counts(historical) + require.Equal(t, 1, historicalPublished) + activeCalls, fallbackCalls, freshCalls := groups.stats() + require.Equal(t, 1, activeCalls) + require.Zero(t, fallbackCalls) + require.Equal(t, []int64{groupID}, freshCalls) + _, _, listCalls := cache.lifecycleCounts() + require.Equal(t, 1, listCalls, "known Rg must prevent a second registry read") +} + +func TestSchedulerFullRebuildOrdinaryCaptureErrorReturnsBeforeFirstDB(t *testing.T) { + first := SchedulerBucket{GroupID: 0, Platform: "legacy-a", Mode: "unknown"} + last := SchedulerBucket{GroupID: 0, Platform: "legacy-b", Mode: "unknown"} + cache := newFullRebuildLifecycleCache(first, last) + wantErr := errors.New("capture failed") + cache.captureErrors[last.String()] = wantErr + groups := &fullRebuildLifecycleGroupRepo{fresh: make(map[int64]*Group), freshErr: make(map[int64]error)} + accounts := &fullRebuildAccountRepo{} + svc := newFullRebuildLifecycleService(cache, nil, accounts, groups, config.RunModeStandard) + + err := svc.rebuildFullSnapshot(context.Background(), "test") + require.ErrorIs(t, err, wantErr) + require.Equal(t, 14, cache.captureAttemptCount(), "all canonical and ordinary captures must be attempted before returning") + require.Zero(t, accounts.callCount()) + require.Zero(t, cache.totalSetAttempts()) +} + +func TestSchedulerFullRebuildPreservesGroupZeroActiveHistoricalAndInvalidRegistryBuckets(t *testing.T) { + const groupID int64 = 103 + groupZeroHistorical := SchedulerBucket{GroupID: 0, Platform: "legacy-zero", Mode: "unknown"} + activeHistorical := SchedulerBucket{GroupID: groupID, Platform: "legacy-active", Mode: "unknown"} + activeForced := SchedulerBucket{GroupID: groupID, Platform: PlatformOpenAI, Mode: SchedulerModeForced} + activeMixed := SchedulerBucket{GroupID: groupID, Platform: PlatformAnthropic, Mode: SchedulerModeMixed} + invalidHistorical := SchedulerBucket{GroupID: -7, Platform: "legacy-invalid", Mode: "unknown"} + cache := newFullRebuildLifecycleCache(groupZeroHistorical, activeHistorical, activeForced, activeMixed, invalidHistorical) + groups := &fullRebuildFallbackGroupRepo{groups: []Group{{ID: groupID, Status: StatusActive}}} + accounts := &fullRebuildAccountRepo{} + svc := newFullRebuildLifecycleService(cache, nil, accounts, groups, config.RunModeStandard) + + require.NoError(t, svc.rebuildFullSnapshot(context.Background(), "test")) + require.Equal(t, 27, cache.captureAttemptCount()) + require.Equal(t, 17, accounts.callCount()) + groups.mu.Lock() + require.Equal(t, 1, groups.listCalls) + groups.mu.Unlock() + require.Empty(t, cache.retiredBuckets()) + require.Empty(t, cache.tokens()) + for _, bucket := range []SchedulerBucket{groupZeroHistorical, activeHistorical, activeForced, activeMixed, invalidHistorical} { + _, published := cache.counts(bucket) + require.Equal(t, 1, published, bucket.String()) + } +} + +func TestSchedulerFullRebuildActiveTombstoneFreshInactiveOrMissingFiltersAllGroupTasks(t *testing.T) { + for _, tc := range []struct { + name string + group *Group + }{ + {name: "inactive", group: &Group{ID: 104, Status: StatusDisabled, Hydrated: true}}, + {name: "missing"}, + } { + t.Run(tc.name, func(t *testing.T) { + const groupID int64 = 104 + canonical := schedulerBucketsForGroup(groupID) + historical := SchedulerBucket{GroupID: groupID, Platform: "legacy", Mode: "unknown"} + cache := newFullRebuildLifecycleCache(historical) + require.NoError(t, cache.retirementRaceCache.RetireBucket(context.Background(), canonical[5])) + groups := &fullRebuildLifecycleGroupRepo{ + activeIDs: []int64{groupID}, + fresh: make(map[int64]*Group), + freshErr: make(map[int64]error), + } + if tc.group != nil { + groups.fresh[groupID] = tc.group + } + accounts := &fullRebuildAccountRepo{} + svc := newFullRebuildLifecycleService(cache, nil, accounts, groups, config.RunModeStandard) + + require.NoError(t, svc.rebuildFullSnapshot(context.Background(), "test")) + require.Zero(t, accounts.groupCallCount(groupID)) + require.Equal(t, 7, accounts.groupCallCount(0)) + require.Empty(t, cache.tokens()) + require.Equal(t, bucketStrings(append(canonical, historical)), bucketStrings(cache.retiredBuckets())) + for _, bucket := range append(canonical, historical) { + attempts, published := cache.counts(bucket) + require.Zero(t, attempts, bucket.String()) + require.Zero(t, published, bucket.String()) + } + _, _, listCalls := cache.lifecycleCounts() + require.Equal(t, 1, listCalls) + }) + } +} + +func TestSchedulerFullRebuildStaleCandidatesAreSortedAndNeverReopenedAcrossRounds(t *testing.T) { + historical := []SchedulerBucket{ + {GroupID: 3, Platform: "legacy", Mode: "unknown"}, + {GroupID: 1, Platform: "legacy", Mode: "unknown"}, + {GroupID: 2, Platform: "legacy", Mode: "unknown"}, + } + cache := newFullRebuildLifecycleCache(historical...) + groups := &fullRebuildLifecycleGroupRepo{ + fresh: map[int64]*Group{ + 1: {ID: 1, Status: StatusDisabled, Hydrated: true}, + 3: {ID: 3, Status: StatusDisabled, Hydrated: true}, + }, + freshErr: make(map[int64]error), + } + accounts := &fullRebuildAccountRepo{} + svc := newFullRebuildLifecycleService(cache, nil, accounts, groups, config.RunModeStandard) + + require.NoError(t, svc.rebuildFullSnapshot(context.Background(), "first")) + retireCallsAfterFirst := len(cache.retiredBuckets()) + require.NoError(t, svc.rebuildFullSnapshot(context.Background(), "second")) + _, _, freshCalls := groups.stats() + require.Equal(t, []int64{1, 2, 3}, freshCalls) + require.Equal(t, retireCallsAfterFirst, len(cache.retiredBuckets())) + require.Empty(t, cache.tokens()) + require.Zero(t, accounts.groupCallCount(1)) + require.Zero(t, accounts.groupCallCount(2)) + require.Zero(t, accounts.groupCallCount(3)) + _, _, listCalls := cache.lifecycleCounts() + require.Equal(t, 2, listCalls, "each round must use only its one global registry snapshot") + for _, bucket := range historical { + require.Contains(t, bucketStrings(cache.retiredBuckets()), bucket.String()) + } +} + +func TestSchedulerFullRebuildPartialLifecycleFailureReturnsBeforeDBAndRetries(t *testing.T) { + historical := []SchedulerBucket{ + {GroupID: 1, Platform: "legacy", Mode: "unknown"}, + {GroupID: 2, Platform: "legacy", Mode: "unknown"}, + {GroupID: 3, Platform: "legacy", Mode: "unknown"}, + } + wantErr := errors.New("fresh group query failed") + cache := newFullRebuildLifecycleCache(historical...) + groups := &fullRebuildLifecycleGroupRepo{ + fresh: map[int64]*Group{ + 1: {ID: 1, Status: StatusDisabled, Hydrated: true}, + 3: {ID: 3, Status: StatusDisabled, Hydrated: true}, + }, + freshErr: map[int64]error{2: wantErr}, + } + accounts := &fullRebuildAccountRepo{} + svc := newFullRebuildLifecycleService(cache, nil, accounts, groups, config.RunModeStandard) + + err := svc.triggerFullRebuild("first") + require.ErrorIs(t, err, wantErr) + _, _, freshCalls := groups.stats() + require.Equal(t, []int64{1, 2}, freshCalls) + require.Zero(t, accounts.callCount()) + require.Zero(t, cache.totalSetAttempts()) + require.Equal(t, 13, len(cache.retiredBuckets())) + + groups.mu.Lock() + delete(groups.freshErr, 2) + groups.fresh[2] = &Group{ID: 2, Status: StatusDisabled, Hydrated: true} + groups.mu.Unlock() + require.NoError(t, svc.triggerFullRebuild("retry")) + _, _, freshCalls = groups.stats() + require.Equal(t, []int64{1, 2, 2, 3}, freshCalls) + require.Equal(t, 39, len(cache.retiredBuckets())) + require.Equal(t, 7, accounts.callCount()) + require.Empty(t, cache.tokens()) +} + +func TestSchedulerFullRebuildActiveTombstoneLazyRecoveryDiscardsPartialCaptureTasks(t *testing.T) { + const groupID int64 = 105 + canonical := schedulerBucketsForGroup(groupID) + historical := SchedulerBucket{GroupID: groupID, Platform: "legacy", Mode: "unknown"} + cache := newFullRebuildLifecycleCache(canonical[0], canonical[4], historical) + require.NoError(t, cache.retirementRaceCache.RetireBucket(context.Background(), canonical[5])) + groups := &fullRebuildLifecycleGroupRepo{ + activeIDs: []int64{groupID}, + fresh: map[int64]*Group{ + groupID: {ID: groupID, Status: StatusActive, Hydrated: true}, + }, + freshErr: make(map[int64]error), + } + accounts := &fullRebuildAccountRepo{} + var capturesAtFirstDB int + accounts.beforeFirst = func() { + capturesAtFirstDB = cache.captureAttemptCount() + held, reopenCount := cache.leaseHeldAndTokenCount() + require.False(t, held) + require.Equal(t, 12, reopenCount) + require.Equal(t, 19, capturesAtFirstDB) + } + svc := newFullRebuildLifecycleService(cache, nil, accounts, groups, config.RunModeStandard) + + require.NoError(t, svc.rebuildFullSnapshot(context.Background(), "test")) + require.Equal(t, capturesAtFirstDB, cache.captureAttemptCount()) + require.Equal(t, 15, accounts.callCount()) + for _, bucket := range canonical { + attempts, published := cache.counts(bucket) + require.Equal(t, 1, attempts, "discarded pre-recovery tokens must never publish: %s", bucket.String()) + require.Equal(t, 1, published, bucket.String()) + } + _, published := cache.counts(historical) + require.Equal(t, 1, published) + _, _, listCalls := cache.lifecycleCounts() + require.Equal(t, 1, listCalls) +} + +func TestSchedulerFullRebuildSimpleModePreservesRegistryWithoutLifecycleAuthority(t *testing.T) { + registered := []SchedulerBucket{ + {GroupID: 0, Platform: "legacy-zero", Mode: "unknown"}, + {GroupID: 106, Platform: "legacy-positive", Mode: "unknown"}, + {GroupID: -8, Platform: "legacy-negative", Mode: "unknown"}, + } + cache := newFullRebuildLifecycleCache(registered...) + groups := &fullRebuildLifecycleGroupRepo{ + activeIDsErr: errors.New("simple mode must not query groups"), + fresh: make(map[int64]*Group), + freshErr: make(map[int64]error), + } + accounts := &fullRebuildAccountRepo{} + svc := newFullRebuildLifecycleService(cache, nil, accounts, groups, config.RunModeSimple) + + require.NoError(t, svc.rebuildFullSnapshot(context.Background(), "test")) + activeCalls, fallbackCalls, freshCalls := groups.stats() + require.Zero(t, activeCalls) + require.Zero(t, fallbackCalls) + require.Empty(t, freshCalls) + require.Equal(t, 15, cache.captureAttemptCount()) + require.Equal(t, 10, accounts.callCount()) + require.Equal(t, 10, accounts.groupCallCount(0)) + require.Empty(t, cache.retiredBuckets()) + require.Empty(t, cache.tokens()) + for _, bucket := range registered { + _, published := cache.counts(bucket) + require.Equal(t, 1, published, bucket.String()) + } +} + +func TestSchedulerFullRebuildFreshReopenLockBusyRetriesWithoutBlockingOrdinaryTasks(t *testing.T) { + const groupID int64 = 107 + canonical := schedulerBucketsForGroup(groupID) + cache := newFullRebuildLifecycleCache() + require.NoError(t, cache.retirementRaceCache.RetireBucket(context.Background(), canonical[0])) + cache.lockBusyOnce[canonical[0].String()] = true + groups := &fullRebuildLifecycleGroupRepo{ + activeIDs: []int64{groupID}, + fresh: map[int64]*Group{ + groupID: {ID: groupID, Status: StatusActive, Hydrated: true}, + }, + freshErr: make(map[int64]error), + } + accounts := &fullRebuildAccountRepo{} + outbox := &outboxCleanupRepo{events: []SchedulerOutboxEvent{{ID: 1, EventType: SchedulerOutboxEventFullRebuild}}} + svc := newFullRebuildLifecycleService(cache, outbox, accounts, groups, config.RunModeStandard) + + svc.pollOutbox() + require.Zero(t, cache.currentWatermark()) + _, groupZeroPublished := cache.counts(schedulerCanonicalBuckets(0)[0]) + require.Equal(t, 1, groupZeroPublished, "ordinary tasks must still run when one strict Reopen task is busy") + require.Equal(t, 14, accounts.callCount()) + + svc.pollOutbox() + require.Equal(t, int64(1), cache.currentWatermark()) + require.Equal(t, 28, accounts.callCount()) + _, busyBucketPublished := cache.counts(canonical[0]) + require.Equal(t, 1, busyBucketPublished) + activeCalls, fallbackCalls, freshCalls := groups.stats() + require.Equal(t, 2, activeCalls) + require.Zero(t, fallbackCalls) + require.Equal(t, []int64{groupID}, freshCalls) +} + +func TestSchedulerFullRebuildOrdinaryLockBusyKeepsExistingSkipSemantics(t *testing.T) { + busyBucket := schedulerCanonicalBuckets(0)[0] + cache := newFullRebuildLifecycleCache() + cache.lockBusyOnce[busyBucket.String()] = true + groups := &fullRebuildLifecycleGroupRepo{fresh: make(map[int64]*Group), freshErr: make(map[int64]error)} + accounts := &fullRebuildAccountRepo{} + svc := newFullRebuildLifecycleService(cache, nil, accounts, groups, config.RunModeStandard) + + require.NoError(t, svc.rebuildFullSnapshot(context.Background(), "test")) + require.Equal(t, 7, accounts.callCount()) + attempts, published := cache.counts(busyBucket) + require.Zero(t, attempts) + require.Zero(t, published) +} + +func requireFullRebuildNoMutationOrDB(t *testing.T, cache *fullRebuildLifecycleCache, accounts *fullRebuildAccountRepo) { + t.Helper() + require.Zero(t, cache.captureAttemptCount()) + require.Empty(t, cache.retiredBuckets()) + require.Empty(t, cache.tokens()) + require.Zero(t, accounts.callCount()) + require.Zero(t, cache.totalSetAttempts()) +} diff --git a/backend/internal/service/scheduler_snapshot_full_rebuild_test.go b/backend/internal/service/scheduler_snapshot_full_rebuild_test.go index 09ec2790ce..02b7548348 100644 --- a/backend/internal/service/scheduler_snapshot_full_rebuild_test.go +++ b/backend/internal/service/scheduler_snapshot_full_rebuild_test.go @@ -17,6 +17,7 @@ type schedulerFullRebuildTestCache struct { mu sync.Mutex listErr error listCalls int + captures int lockCalls int } @@ -34,6 +35,17 @@ func (c *schedulerFullRebuildTestCache) TryLockBucket(context.Context, Scheduler return false, nil } +func (c *schedulerFullRebuildTestCache) CaptureBucketWriteToken(_ context.Context, bucket SchedulerBucket) (SchedulerBucketWriteToken, error) { + c.mu.Lock() + c.captures++ + c.mu.Unlock() + return SchedulerBucketWriteToken{Bucket: bucket, Epoch: 1}, nil +} + +func (c *schedulerFullRebuildTestCache) ReopenBucket(_ context.Context, bucket SchedulerBucket) (SchedulerBucketWriteToken, error) { + return SchedulerBucketWriteToken{Bucket: bucket, Epoch: 1}, nil +} + func TestSchedulerSnapshotServiceFullRebuildCoalescesConcurrentRequestsIntoTrailingRun(t *testing.T) { svc := &SchedulerSnapshotService{} wantTrailingErr := errors.New("trailing rebuild failed") @@ -121,7 +133,7 @@ func TestSchedulerSnapshotServiceFullRebuildRunsAgainForSequentialRequest(t *tes require.Equal(t, requested, completed) } -func TestSchedulerSnapshotServiceInitialFullRebuildFallsBackWhenListBucketsFails(t *testing.T) { +func TestSchedulerSnapshotServiceInitialFullRebuildFailsClosedWhenListBucketsFails(t *testing.T) { cache := &schedulerFullRebuildTestCache{listErr: errors.New("list buckets failed")} svc := NewSchedulerSnapshotService(cache, nil, nil, nil, nil) @@ -129,13 +141,18 @@ func TestSchedulerSnapshotServiceInitialFullRebuildFallsBackWhenListBucketsFails cache.mu.Lock() listCalls := cache.listCalls + captures := cache.captures lockCalls := cache.lockCalls cache.mu.Unlock() require.Equal(t, 1, listCalls) - require.Positive(t, lockCalls, "startup should rebuild default buckets after ListBuckets fails") + require.Zero(t, captures) + require.Zero(t, lockCalls) requested, completed := schedulerFullRebuildState(svc) require.EqualValues(t, 1, requested) require.Equal(t, requested, completed) + svc.fullRebuildStateMu.Lock() + require.ErrorIs(t, svc.fullRebuildLastErr, cache.listErr) + svc.fullRebuildStateMu.Unlock() } func schedulerFullRebuildState(svc *SchedulerSnapshotService) (requested uint64, completed uint64) { diff --git a/backend/internal/service/scheduler_snapshot_group_lifecycle_test.go b/backend/internal/service/scheduler_snapshot_group_lifecycle_test.go new file mode 100644 index 0000000000..ffc697eafc --- /dev/null +++ b/backend/internal/service/scheduler_snapshot_group_lifecycle_test.go @@ -0,0 +1,796 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +type groupLifecycleTestCache struct { + *retirementRaceCache + + stateMu sync.Mutex + + leaseHeld bool + lease SchedulerGroupLifecycleLease + leaseSequence int + leaseBusy bool + leaseAcquireErr error + leaseReleaseErr error + acquireCalls int + releaseCalls int + acquireTTL time.Duration + acquireDeadline bool + releaseDeadline bool + releaseCtxErr error + + listErr error + listCalls int + + retireCalls []SchedulerBucket + reopenTokens []SchedulerBucketWriteToken + retireHeld []bool + reopenHeld []bool + retireErr error + retireErrAt int + reopenErr error + reopenErrAt int + + bucketLockBusy bool + bucketLockErr error + bucketLockTTLs []time.Duration + unlockCalls int + setErr error +} + +func newGroupLifecycleTestCache(buckets ...SchedulerBucket) *groupLifecycleTestCache { + return &groupLifecycleTestCache{retirementRaceCache: newRetirementRaceCache(buckets...)} +} + +func (c *groupLifecycleTestCache) TryAcquireGroupLifecycleLease(ctx context.Context, groupID int64, ttl time.Duration) (SchedulerGroupLifecycleLease, bool, error) { + c.stateMu.Lock() + defer c.stateMu.Unlock() + c.acquireCalls++ + c.acquireTTL = ttl + _, c.acquireDeadline = ctx.Deadline() + if c.leaseAcquireErr != nil { + return SchedulerGroupLifecycleLease{}, false, c.leaseAcquireErr + } + if c.leaseBusy || c.leaseHeld { + return SchedulerGroupLifecycleLease{}, false, nil + } + c.leaseSequence++ + c.lease = SchedulerGroupLifecycleLease{GroupID: groupID, OwnerToken: fmt.Sprintf("owner-%d", c.leaseSequence)} + c.leaseHeld = true + return c.lease, true, nil +} + +func (c *groupLifecycleTestCache) ReleaseGroupLifecycleLease(ctx context.Context, lease SchedulerGroupLifecycleLease) error { + c.stateMu.Lock() + defer c.stateMu.Unlock() + c.releaseCalls++ + _, c.releaseDeadline = ctx.Deadline() + c.releaseCtxErr = ctx.Err() + if c.leaseReleaseErr != nil { + return c.leaseReleaseErr + } + if !c.leaseHeld || lease != c.lease { + return ErrSchedulerGroupLifecycleLeaseLost + } + c.leaseHeld = false + return nil +} + +func (c *groupLifecycleTestCache) RetireBucket(ctx context.Context, bucket SchedulerBucket) error { + c.stateMu.Lock() + c.retireCalls = append(c.retireCalls, bucket) + c.retireHeld = append(c.retireHeld, c.leaseHeld) + held := c.leaseHeld + call := len(c.retireCalls) + err := c.retireErr + errAt := c.retireErrAt + c.stateMu.Unlock() + if !held { + return errors.New("retire called outside group lifecycle lease") + } + if err != nil && (errAt <= 0 || call == errAt) { + return err + } + return c.retirementRaceCache.RetireBucket(ctx, bucket) +} + +func (c *groupLifecycleTestCache) ReopenBucket(ctx context.Context, bucket SchedulerBucket) (SchedulerBucketWriteToken, error) { + if err := ctx.Err(); err != nil { + return SchedulerBucketWriteToken{}, err + } + c.stateMu.Lock() + c.reopenHeld = append(c.reopenHeld, c.leaseHeld) + held := c.leaseHeld + call := len(c.reopenHeld) + reopenErr := c.reopenErr + reopenErrAt := c.reopenErrAt + c.stateMu.Unlock() + if !held { + return SchedulerBucketWriteToken{}, errors.New("reopen called outside group lifecycle lease") + } + if reopenErr != nil && (reopenErrAt <= 0 || call == reopenErrAt) { + return SchedulerBucketWriteToken{}, reopenErr + } + token, err := c.retirementRaceCache.ReopenBucket(ctx, bucket) + if err != nil { + return SchedulerBucketWriteToken{}, err + } + c.stateMu.Lock() + c.reopenTokens = append(c.reopenTokens, token) + c.stateMu.Unlock() + return token, nil +} + +func (c *groupLifecycleTestCache) ListBuckets(ctx context.Context) ([]SchedulerBucket, error) { + c.stateMu.Lock() + c.listCalls++ + err := c.listErr + c.stateMu.Unlock() + if err != nil { + return nil, err + } + return c.retirementRaceCache.ListBuckets(ctx) +} + +func (c *groupLifecycleTestCache) TryLockBucket(_ context.Context, _ SchedulerBucket, ttl time.Duration) (bool, error) { + c.stateMu.Lock() + defer c.stateMu.Unlock() + c.bucketLockTTLs = append(c.bucketLockTTLs, ttl) + if c.bucketLockErr != nil { + return false, c.bucketLockErr + } + return !c.bucketLockBusy, nil +} + +func (c *groupLifecycleTestCache) UnlockBucket(context.Context, SchedulerBucket) error { + c.stateMu.Lock() + c.unlockCalls++ + c.stateMu.Unlock() + return nil +} + +func (c *groupLifecycleTestCache) SetSnapshot(ctx context.Context, bucket SchedulerBucket, token SchedulerBucketWriteToken, accounts []Account) error { + c.stateMu.Lock() + err := c.setErr + c.stateMu.Unlock() + if err != nil { + return err + } + return c.retirementRaceCache.SetSnapshot(ctx, bucket, token, accounts) +} + +func (c *groupLifecycleTestCache) lifecycleCounts() (acquires, releases, listCalls int) { + c.stateMu.Lock() + defer c.stateMu.Unlock() + return c.acquireCalls, c.releaseCalls, c.listCalls +} + +func (c *groupLifecycleTestCache) retiredBuckets() []SchedulerBucket { + c.stateMu.Lock() + defer c.stateMu.Unlock() + return append([]SchedulerBucket(nil), c.retireCalls...) +} + +func (c *groupLifecycleTestCache) tokens() []SchedulerBucketWriteToken { + c.stateMu.Lock() + defer c.stateMu.Unlock() + return append([]SchedulerBucketWriteToken(nil), c.reopenTokens...) +} + +func (c *groupLifecycleTestCache) leaseHeldAndTokenCount() (bool, int) { + c.stateMu.Lock() + defer c.stateMu.Unlock() + return c.leaseHeld, len(c.reopenTokens) +} + +func (c *groupLifecycleTestCache) lockStats() ([]time.Duration, int) { + c.stateMu.Lock() + defer c.stateMu.Unlock() + return append([]time.Duration(nil), c.bucketLockTTLs...), c.unlockCalls +} + +func (c *groupLifecycleTestCache) lifecycleMutationLeaseStates() (retire, reopen []bool) { + c.stateMu.Lock() + defer c.stateMu.Unlock() + return append([]bool(nil), c.retireHeld...), append([]bool(nil), c.reopenHeld...) +} + +type groupLifecycleTestGroupRepo struct { + GroupRepository + + mu sync.Mutex + group *Group + err error + calls int + afterGet func() +} + +func (r *groupLifecycleTestGroupRepo) GetByIDLite(context.Context, int64) (*Group, error) { + r.mu.Lock() + r.calls++ + if r.err != nil { + err := r.err + r.mu.Unlock() + return nil, err + } + if r.group == nil { + r.mu.Unlock() + return nil, ErrGroupNotFound + } + copyGroup := *r.group + afterGet := r.afterGet + r.mu.Unlock() + if afterGet != nil { + afterGet() + } + return ©Group, nil +} + +func (r *groupLifecycleTestGroupRepo) set(group *Group, err error) { + r.mu.Lock() + defer r.mu.Unlock() + r.group = group + r.err = err +} + +func (r *groupLifecycleTestGroupRepo) callCount() int { + r.mu.Lock() + defer r.mu.Unlock() + return r.calls +} + +type groupLifecycleTestAccountRepo struct { + AccountRepository + + mu sync.Mutex + calls int + callsByPlatform map[string]int + err error + started chan struct{} + release chan struct{} + once sync.Once + beforeLoad func() + beforeLoadOnce sync.Once +} + +func (r *groupLifecycleTestAccountRepo) load(ctx context.Context, platform string) ([]Account, error) { + r.mu.Lock() + r.calls++ + if r.callsByPlatform == nil { + r.callsByPlatform = make(map[string]int) + } + r.callsByPlatform[platform]++ + err := r.err + started := r.started + release := r.release + r.mu.Unlock() + if started != nil { + r.once.Do(func() { close(started) }) + } + if r.beforeLoad != nil { + r.beforeLoadOnce.Do(r.beforeLoad) + } + if release != nil { + select { + case <-release: + case <-ctx.Done(): + return nil, ctx.Err() + } + } + if err != nil { + return nil, err + } + return []Account{{ID: 9001, Platform: platform, Status: StatusActive, Schedulable: true}}, nil +} + +func (r *groupLifecycleTestAccountRepo) ListSchedulableByGroupIDAndPlatform(ctx context.Context, _ int64, platform string) ([]Account, error) { + return r.load(ctx, platform) +} + +func (r *groupLifecycleTestAccountRepo) ListSchedulableByGroupIDAndPlatforms(ctx context.Context, _ int64, platforms []string) ([]Account, error) { + platform := "mixed" + if len(platforms) > 0 { + platform = platforms[0] + } + return r.load(ctx, platform) +} + +func (r *groupLifecycleTestAccountRepo) callCount() int { + r.mu.Lock() + defer r.mu.Unlock() + return r.calls +} + +func (r *groupLifecycleTestAccountRepo) platformCallCount(platform string) int { + r.mu.Lock() + defer r.mu.Unlock() + return r.callsByPlatform[platform] +} + +func newGroupLifecycleTestService(cache SchedulerCache, accounts AccountRepository, groups GroupRepository, runMode string) *SchedulerSnapshotService { + return NewSchedulerSnapshotService(cache, nil, accounts, groups, &config.Config{RunMode: runMode}) +} + +func expectedGroupLifecycleBuckets(groupID int64) []SchedulerBucket { + platforms := []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok} + buckets := make([]SchedulerBucket, 0, 12) + for _, platform := range platforms { + buckets = append(buckets, + SchedulerBucket{GroupID: groupID, Platform: platform, Mode: SchedulerModeSingle}, + SchedulerBucket{GroupID: groupID, Platform: platform, Mode: SchedulerModeForced}, + ) + if platform == PlatformAnthropic || platform == PlatformGemini { + buckets = append(buckets, SchedulerBucket{GroupID: groupID, Platform: platform, Mode: SchedulerModeMixed}) + } + } + return buckets +} + +func bucketStrings(buckets []SchedulerBucket) map[string]struct{} { + out := make(map[string]struct{}, len(buckets)) + for _, bucket := range buckets { + out[bucket.String()] = struct{}{} + } + return out +} + +func requireLifecycleSeen(t *testing.T, seen map[batchSeenKey]struct{}, groupID int64) { + t.Helper() + _, ok := seen[batchSeenKey{groupID: groupID, lifecycle: true}] + require.True(t, ok) + for _, platform := range schedulerSnapshotPlatforms() { + _, ok = seen[batchSeenKey{groupID: groupID, platform: platform}] + require.True(t, ok) + } +} + +func requireLifecycleNotSeen(t *testing.T, seen map[batchSeenKey]struct{}, groupID int64) { + t.Helper() + _, ok := seen[batchSeenKey{groupID: groupID, lifecycle: true}] + require.False(t, ok) + for _, platform := range schedulerSnapshotPlatforms() { + _, ok = seen[batchSeenKey{groupID: groupID, platform: platform}] + require.False(t, ok) + } +} + +func TestSchedulerGroupLifecycleInactiveAndMissingRetireAllHistoricalBucketsWithoutAccountReads(t *testing.T) { + for _, tc := range []struct { + name string + group *Group + err error + }{ + {name: "inactive", group: &Group{ID: 81, Status: StatusDisabled, Hydrated: true}}, + {name: "missing", err: ErrGroupNotFound}, + } { + t.Run(tc.name, func(t *testing.T) { + const groupID int64 = 81 + current := expectedGroupLifecycleBuckets(groupID) + historical := SchedulerBucket{GroupID: groupID, Platform: "legacy", Mode: "obsolete"} + other := SchedulerBucket{GroupID: groupID + 1, Platform: PlatformOpenAI, Mode: SchedulerModeForced} + groupZero := SchedulerBucket{GroupID: 0, Platform: PlatformOpenAI, Mode: SchedulerModeForced} + cache := newGroupLifecycleTestCache(current[0], historical, other, groupZero) + groups := &groupLifecycleTestGroupRepo{group: tc.group, err: tc.err} + accounts := &groupLifecycleTestAccountRepo{} + svc := newGroupLifecycleTestService(cache, accounts, groups, config.RunModeStandard) + seen := make(map[batchSeenKey]struct{}) + + require.NoError(t, svc.handleGroupEvent(context.Background(), ptrInt64(groupID), seen)) + + expected := bucketStrings(append(current, historical)) + got := bucketStrings(cache.retiredBuckets()) + require.Equal(t, expected, got) + retireHeld, _ := cache.lifecycleMutationLeaseStates() + require.Len(t, retireHeld, len(expected)) + for _, held := range retireHeld { + require.True(t, held) + } + require.NotContains(t, got, other.String()) + require.NotContains(t, got, groupZero.String()) + require.Zero(t, accounts.callCount()) + require.Equal(t, 1, groups.callCount()) + _, _, listCalls := cache.lifecycleCounts() + require.Equal(t, 1, listCalls) + requireLifecycleSeen(t, seen, groupID) + }) + } +} + +func TestSchedulerPrepareGroupLifecycleUsesKnownHistoricalBucketsWithoutListingRegistry(t *testing.T) { + const groupID int64 = 811 + historical := SchedulerBucket{GroupID: groupID, Platform: "legacy", Mode: "obsolete"} + cache := newGroupLifecycleTestCache() + cache.listErr = errors.New("registry must not be listed") + groups := &groupLifecycleTestGroupRepo{group: &Group{ID: groupID, Status: StatusDisabled, Hydrated: true}} + accounts := &groupLifecycleTestAccountRepo{} + svc := newGroupLifecycleTestService(cache, accounts, groups, config.RunModeStandard) + + plan, err := svc.prepareGroupLifecycle(context.Background(), groupID, []SchedulerBucket{historical}) + require.NoError(t, err) + require.False(t, plan.active) + require.Empty(t, plan.tasks) + _, _, listCalls := cache.lifecycleCounts() + require.Zero(t, listCalls) + require.Contains(t, bucketStrings(cache.retiredBuckets()), historical.String()) + require.Zero(t, accounts.callCount()) +} + +func TestSchedulerGroupLifecycleActiveReopensAndRebuildsAllCurrentBuckets(t *testing.T) { + const groupID int64 = 82 + current := expectedGroupLifecycleBuckets(groupID) + historical := SchedulerBucket{GroupID: groupID, Platform: "legacy", Mode: "obsolete"} + cache := newGroupLifecycleTestCache(historical) + for _, bucket := range current { + require.NoError(t, cache.retirementRaceCache.RetireBucket(context.Background(), bucket)) + } + groups := &groupLifecycleTestGroupRepo{group: &Group{ID: groupID, Platform: PlatformOpenAI, Status: StatusActive, Hydrated: true}} + accounts := &groupLifecycleTestAccountRepo{} + accounts.beforeLoad = func() { + held, tokenCount := cache.leaseHeldAndTokenCount() + require.False(t, held, "the group lifecycle lease must be released before the first account query") + require.Equal(t, 12, tokenCount, "all reopen tokens must be prepared before the first account query") + } + svc := newGroupLifecycleTestService(cache, accounts, groups, config.RunModeStandard) + seen := make(map[batchSeenKey]struct{}) + + require.NoError(t, svc.handleGroupEvent(context.Background(), ptrInt64(groupID), seen)) + + require.Equal(t, bucketStrings(current), bucketStrings(cache.reopens)) + require.Empty(t, cache.retiredBuckets()) + registered, err := cache.retirementRaceCache.ListBuckets(context.Background()) + require.NoError(t, err) + require.Contains(t, bucketStrings(registered), historical.String()) + require.Len(t, cache.tokens(), 12) + require.Equal(t, 7, accounts.callCount()) + require.Equal(t, 1, accounts.platformCallCount(PlatformOpenAI)) + for _, bucket := range current { + _, published := cache.counts(bucket) + require.Equal(t, 1, published, bucket.String()) + } + require.Contains(t, bucketStrings(current), SchedulerBucket{GroupID: groupID, Platform: PlatformAntigravity, Mode: SchedulerModeForced}.String()) + require.Contains(t, bucketStrings(current), SchedulerBucket{GroupID: groupID, Platform: PlatformAnthropic, Mode: SchedulerModeMixed}.String()) + require.Contains(t, bucketStrings(current), SchedulerBucket{GroupID: groupID, Platform: PlatformGemini, Mode: SchedulerModeMixed}.String()) + acquires, releases, listCalls := cache.lifecycleCounts() + require.Equal(t, 1, acquires) + require.Equal(t, 1, releases) + require.Zero(t, listCalls) + require.Equal(t, schedulerGroupLifecycleLeaseTTL, cache.acquireTTL) + require.True(t, cache.acquireDeadline) + require.True(t, cache.releaseDeadline) + require.NoError(t, cache.releaseCtxErr) + _, reopenHeld := cache.lifecycleMutationLeaseStates() + require.Len(t, reopenHeld, 12) + for _, held := range reopenHeld { + require.True(t, held) + } + lockTTLs, unlockCalls := cache.lockStats() + require.Len(t, lockTTLs, 12) + for _, ttl := range lockTTLs { + require.Equal(t, 30*time.Second, ttl) + } + require.Equal(t, 12, unlockCalls) + requireLifecycleSeen(t, seen, groupID) +} + +func TestSchedulerGroupLifecycleInactiveThenActiveAuthoritativelyReopens(t *testing.T) { + const groupID int64 = 83 + cache := newGroupLifecycleTestCache() + groups := &groupLifecycleTestGroupRepo{group: &Group{ID: groupID, Status: StatusDisabled, Hydrated: true}} + accounts := &groupLifecycleTestAccountRepo{} + svc := newGroupLifecycleTestService(cache, accounts, groups, config.RunModeStandard) + + require.NoError(t, svc.handleGroupEvent(context.Background(), ptrInt64(groupID), make(map[batchSeenKey]struct{}))) + require.Zero(t, accounts.callCount()) + groups.set(&Group{ID: groupID, Status: StatusActive, Hydrated: true}, nil) + require.NoError(t, svc.handleGroupEvent(context.Background(), ptrInt64(groupID), make(map[batchSeenKey]struct{}))) + + require.Len(t, cache.tokens(), 12) + require.Equal(t, 7, accounts.callCount()) + for _, bucket := range expectedGroupLifecycleBuckets(groupID) { + _, published := cache.counts(bucket) + require.Equal(t, 1, published, bucket.String()) + } +} + +func TestSchedulerGroupLifecycleLaterInactiveFencesLongActiveRebuild(t *testing.T) { + const groupID int64 = 84 + cache := newGroupLifecycleTestCache() + groups := &groupLifecycleTestGroupRepo{group: &Group{ID: groupID, Status: StatusActive, Hydrated: true}} + started := make(chan struct{}) + release := make(chan struct{}) + accounts := &groupLifecycleTestAccountRepo{started: started, release: release} + svc := newGroupLifecycleTestService(cache, accounts, groups, config.RunModeStandard) + activeSeen := make(map[batchSeenKey]struct{}) + inactiveSeen := make(map[batchSeenKey]struct{}) + activeResult := make(chan error, 1) + + go func() { + activeResult <- svc.handleGroupEvent(context.Background(), ptrInt64(groupID), activeSeen) + }() + select { + case <-started: + case <-time.After(time.Second): + t.Fatal("active rebuild did not reach the account load") + } + + groups.set(&Group{ID: groupID, Status: StatusDisabled, Hydrated: true}, nil) + require.NoError(t, svc.handleGroupEvent(context.Background(), ptrInt64(groupID), inactiveSeen)) + close(release) + err := <-activeResult + require.ErrorIs(t, err, ErrSchedulerBucketRetired) + requireLifecycleNotSeen(t, activeSeen, groupID) + requireLifecycleSeen(t, inactiveSeen, groupID) +} + +func TestSchedulerGroupLifecycleEpochPreventsABA(t *testing.T) { + const groupID int64 = 85 + cache := newGroupLifecycleTestCache() + groups := &groupLifecycleTestGroupRepo{group: &Group{ID: groupID, Status: StatusDisabled, Hydrated: true}} + accounts := &groupLifecycleTestAccountRepo{} + svc := newGroupLifecycleTestService(cache, accounts, groups, config.RunModeStandard) + + require.NoError(t, svc.handleGroupEvent(context.Background(), ptrInt64(groupID), make(map[batchSeenKey]struct{}))) + groups.set(&Group{ID: groupID, Status: StatusActive, Hydrated: true}, nil) + require.NoError(t, svc.handleGroupEvent(context.Background(), ptrInt64(groupID), make(map[batchSeenKey]struct{}))) + firstActiveTokens := cache.tokens() + require.Len(t, firstActiveTokens, 12) + + groups.set(&Group{ID: groupID, Status: StatusDisabled, Hydrated: true}, nil) + require.NoError(t, svc.handleGroupEvent(context.Background(), ptrInt64(groupID), make(map[batchSeenKey]struct{}))) + groups.set(&Group{ID: groupID, Status: StatusActive, Hydrated: true}, nil) + require.NoError(t, svc.handleGroupEvent(context.Background(), ptrInt64(groupID), make(map[batchSeenKey]struct{}))) + allTokens := cache.tokens() + require.Len(t, allTokens, 24) + require.Greater(t, allTokens[12].Epoch, firstActiveTokens[0].Epoch) + require.ErrorIs(t, cache.SetSnapshot(context.Background(), firstActiveTokens[0].Bucket, firstActiveTokens[0], nil), ErrSchedulerBucketWriteFenced) +} + +func TestSchedulerGroupLifecycleSeenIsIndependentAndDeduplicatesGroupEvents(t *testing.T) { + const groupID int64 = 86 + cache := newGroupLifecycleTestCache() + groups := &groupLifecycleTestGroupRepo{group: &Group{ID: groupID, Status: StatusActive, Hydrated: true}} + accounts := &groupLifecycleTestAccountRepo{} + svc := newGroupLifecycleTestService(cache, accounts, groups, config.RunModeStandard) + seen := make(map[batchSeenKey]struct{}) + for _, platform := range schedulerSnapshotPlatforms() { + seen[batchSeenKey{groupID: groupID, platform: platform}] = struct{}{} + } + + require.NoError(t, svc.handleGroupEvent(context.Background(), ptrInt64(groupID), seen)) + require.Equal(t, 1, groups.callCount()) + require.Equal(t, 7, accounts.callCount()) + requireLifecycleSeen(t, seen, groupID) + require.NoError(t, svc.handleGroupEvent(context.Background(), ptrInt64(groupID), seen)) + require.Equal(t, 1, groups.callCount()) + require.Equal(t, 7, accounts.callCount()) +} + +func TestSchedulerGroupLifecycleFailuresDoNotMarkSeen(t *testing.T) { + tests := []struct { + name string + prepare func(*groupLifecycleTestCache, *groupLifecycleTestGroupRepo, *groupLifecycleTestAccountRepo) + check func(*testing.T, error) + }{ + { + name: "lease busy", + prepare: func(cache *groupLifecycleTestCache, _ *groupLifecycleTestGroupRepo, _ *groupLifecycleTestAccountRepo) { + cache.leaseBusy = true + }, + check: func(t *testing.T, err error) { require.ErrorIs(t, err, ErrSchedulerGroupLifecycleLeaseBusy) }, + }, + { + name: "lease error", + prepare: func(cache *groupLifecycleTestCache, _ *groupLifecycleTestGroupRepo, _ *groupLifecycleTestAccountRepo) { + cache.leaseAcquireErr = errors.New("lease failed") + }, + check: func(t *testing.T, err error) { require.EqualError(t, err, "lease failed") }, + }, + { + name: "release lost", + prepare: func(cache *groupLifecycleTestCache, _ *groupLifecycleTestGroupRepo, _ *groupLifecycleTestAccountRepo) { + cache.leaseReleaseErr = ErrSchedulerGroupLifecycleLeaseLost + }, + check: func(t *testing.T, err error) { require.ErrorIs(t, err, ErrSchedulerGroupLifecycleLeaseLost) }, + }, + { + name: "release error", + prepare: func(cache *groupLifecycleTestCache, _ *groupLifecycleTestGroupRepo, _ *groupLifecycleTestAccountRepo) { + cache.leaseReleaseErr = errors.New("release failed") + }, + check: func(t *testing.T, err error) { require.EqualError(t, err, "release failed") }, + }, + { + name: "group query error", + prepare: func(_ *groupLifecycleTestCache, groups *groupLifecycleTestGroupRepo, _ *groupLifecycleTestAccountRepo) { + groups.err = errors.New("group query failed") + }, + check: func(t *testing.T, err error) { require.EqualError(t, err, "group query failed") }, + }, + { + name: "list buckets error", + prepare: func(cache *groupLifecycleTestCache, groups *groupLifecycleTestGroupRepo, _ *groupLifecycleTestAccountRepo) { + groups.group.Status = StatusDisabled + cache.listErr = errors.New("list buckets failed") + }, + check: func(t *testing.T, err error) { require.EqualError(t, err, "list buckets failed") }, + }, + { + name: "retire bucket error", + prepare: func(cache *groupLifecycleTestCache, groups *groupLifecycleTestGroupRepo, _ *groupLifecycleTestAccountRepo) { + groups.group.Status = StatusDisabled + cache.retireErr = errors.New("retire bucket failed") + cache.retireErrAt = 2 + }, + check: func(t *testing.T, err error) { require.EqualError(t, err, "retire bucket failed") }, + }, + { + name: "reopen bucket error", + prepare: func(cache *groupLifecycleTestCache, _ *groupLifecycleTestGroupRepo, _ *groupLifecycleTestAccountRepo) { + cache.reopenErr = errors.New("reopen bucket failed") + cache.reopenErrAt = 2 + }, + check: func(t *testing.T, err error) { require.EqualError(t, err, "reopen bucket failed") }, + }, + { + name: "account rebuild error", + prepare: func(_ *groupLifecycleTestCache, _ *groupLifecycleTestGroupRepo, accounts *groupLifecycleTestAccountRepo) { + accounts.err = errors.New("account load failed") + }, + check: func(t *testing.T, err error) { require.EqualError(t, err, "account load failed") }, + }, + { + name: "bucket lock busy", + prepare: func(cache *groupLifecycleTestCache, _ *groupLifecycleTestGroupRepo, _ *groupLifecycleTestAccountRepo) { + cache.bucketLockBusy = true + }, + check: func(t *testing.T, err error) { require.ErrorIs(t, err, ErrSchedulerBucketRebuildBusy) }, + }, + { + name: "bucket lock error", + prepare: func(cache *groupLifecycleTestCache, _ *groupLifecycleTestGroupRepo, _ *groupLifecycleTestAccountRepo) { + cache.bucketLockErr = errors.New("bucket lock failed") + }, + check: func(t *testing.T, err error) { require.EqualError(t, err, "bucket lock failed") }, + }, + { + name: "set snapshot error", + prepare: func(cache *groupLifecycleTestCache, _ *groupLifecycleTestGroupRepo, _ *groupLifecycleTestAccountRepo) { + cache.setErr = errors.New("set snapshot failed") + }, + check: func(t *testing.T, err error) { require.EqualError(t, err, "set snapshot failed") }, + }, + } + + for index, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + groupID := int64(870 + index) + cache := newGroupLifecycleTestCache() + groups := &groupLifecycleTestGroupRepo{group: &Group{ID: groupID, Status: StatusActive, Hydrated: true}} + accounts := &groupLifecycleTestAccountRepo{} + tc.prepare(cache, groups, accounts) + svc := newGroupLifecycleTestService(cache, accounts, groups, config.RunModeStandard) + seen := make(map[batchSeenKey]struct{}) + + err := svc.handleGroupEvent(context.Background(), ptrInt64(groupID), seen) + tc.check(t, err) + requireLifecycleNotSeen(t, seen, groupID) + if tc.name == "release lost" || tc.name == "release error" { + require.Zero(t, accounts.callCount()) + } + if tc.name == "retire bucket error" || tc.name == "reopen bucket error" { + _, releases, _ := cache.lifecycleCounts() + require.Equal(t, 1, releases) + require.Zero(t, accounts.callCount()) + } + if tc.name == "account rebuild error" || tc.name == "set snapshot error" { + lockTTLs, unlockCalls := cache.lockStats() + require.Len(t, lockTTLs, 1) + require.Equal(t, 1, unlockCalls) + require.Equal(t, 1, accounts.callCount()) + } + }) + } +} + +func TestSchedulerGroupLifecycleOperationAndReleaseErrorsPreserveBothCauses(t *testing.T) { + const groupID int64 = 880 + operationErr := errors.New("group query failed") + cache := newGroupLifecycleTestCache() + cache.leaseReleaseErr = ErrSchedulerGroupLifecycleLeaseLost + groups := &groupLifecycleTestGroupRepo{err: operationErr} + accounts := &groupLifecycleTestAccountRepo{} + svc := newGroupLifecycleTestService(cache, accounts, groups, config.RunModeStandard) + seen := make(map[batchSeenKey]struct{}) + + err := svc.handleGroupEvent(context.Background(), ptrInt64(groupID), seen) + require.ErrorIs(t, err, operationErr) + require.ErrorIs(t, err, ErrSchedulerGroupLifecycleLeaseLost) + requireLifecycleNotSeen(t, seen, groupID) + require.Zero(t, accounts.callCount()) +} + +func TestSchedulerGroupLifecycleUntrustedGroupStateFailsClosed(t *testing.T) { + for _, tc := range []struct { + name string + group *Group + }{ + {name: "not hydrated", group: &Group{ID: 88, Status: StatusActive}}, + {name: "mismatched id", group: &Group{ID: 89, Status: StatusActive, Hydrated: true}}, + } { + t.Run(tc.name, func(t *testing.T) { + const eventGroupID int64 = 88 + cache := newGroupLifecycleTestCache() + groups := &groupLifecycleTestGroupRepo{group: tc.group} + accounts := &groupLifecycleTestAccountRepo{} + svc := newGroupLifecycleTestService(cache, accounts, groups, config.RunModeStandard) + seen := make(map[batchSeenKey]struct{}) + + err := svc.handleGroupEvent(context.Background(), ptrInt64(eventGroupID), seen) + require.Error(t, err) + require.Empty(t, cache.retiredBuckets()) + require.Empty(t, cache.tokens()) + require.Zero(t, accounts.callCount()) + requireLifecycleNotSeen(t, seen, eventGroupID) + acquires, releases, listCalls := cache.lifecycleCounts() + require.Equal(t, 1, acquires) + require.Equal(t, 1, releases) + require.Zero(t, listCalls) + }) + } +} + +func TestSchedulerGroupLifecycleCanceledAfterFreshQueryUsesIndependentReleaseContext(t *testing.T) { + const groupID int64 = 89 + ctx, cancel := context.WithCancel(context.Background()) + cache := newGroupLifecycleTestCache() + groups := &groupLifecycleTestGroupRepo{ + group: &Group{ID: groupID, Status: StatusActive, Hydrated: true}, + afterGet: cancel, + } + accounts := &groupLifecycleTestAccountRepo{} + svc := newGroupLifecycleTestService(cache, accounts, groups, config.RunModeStandard) + seen := make(map[batchSeenKey]struct{}) + + err := svc.handleGroupEvent(ctx, ptrInt64(groupID), seen) + require.ErrorIs(t, err, context.Canceled) + requireLifecycleNotSeen(t, seen, groupID) + require.Empty(t, cache.tokens()) + require.Zero(t, accounts.callCount()) + acquires, releases, _ := cache.lifecycleCounts() + require.Equal(t, 1, acquires) + require.Equal(t, 1, releases) + require.True(t, cache.releaseDeadline) + require.NoError(t, cache.releaseCtxErr) +} + +func TestSchedulerGroupLifecycleGroupZeroAndSimpleModeAreNoOps(t *testing.T) { + cache := newGroupLifecycleTestCache() + groups := &groupLifecycleTestGroupRepo{group: &Group{ID: 88, Status: StatusActive, Hydrated: true}} + accounts := &groupLifecycleTestAccountRepo{} + standard := newGroupLifecycleTestService(cache, accounts, groups, config.RunModeStandard) + simple := newGroupLifecycleTestService(cache, accounts, groups, config.RunModeSimple) + + require.NoError(t, standard.handleGroupEvent(context.Background(), nil, make(map[batchSeenKey]struct{}))) + require.NoError(t, standard.handleGroupEvent(context.Background(), ptrInt64(0), make(map[batchSeenKey]struct{}))) + require.NoError(t, simple.handleGroupEvent(context.Background(), ptrInt64(88), make(map[batchSeenKey]struct{}))) + + acquires, releases, listCalls := cache.lifecycleCounts() + require.Zero(t, acquires) + require.Zero(t, releases) + require.Zero(t, listCalls) + require.Zero(t, groups.callCount()) + require.Zero(t, accounts.callCount()) +} diff --git a/backend/internal/service/scheduler_snapshot_hydration_test.go b/backend/internal/service/scheduler_snapshot_hydration_test.go index 0a1d0a0a52..e87aac180d 100644 --- a/backend/internal/service/scheduler_snapshot_hydration_test.go +++ b/backend/internal/service/scheduler_snapshot_hydration_test.go @@ -19,7 +19,27 @@ func (c *snapshotHydrationCache) GetSnapshot(ctx context.Context, bucket Schedul return c.snapshot, true, nil } -func (c *snapshotHydrationCache) SetSnapshot(ctx context.Context, bucket SchedulerBucket, accounts []Account) error { +func (c *snapshotHydrationCache) CaptureBucketWriteToken(ctx context.Context, bucket SchedulerBucket) (SchedulerBucketWriteToken, error) { + return SchedulerBucketWriteToken{Bucket: bucket, Epoch: 1}, nil +} + +func (c *snapshotHydrationCache) SetSnapshot(ctx context.Context, bucket SchedulerBucket, token SchedulerBucketWriteToken, accounts []Account) error { + return nil +} + +func (c *snapshotHydrationCache) RetireBucket(ctx context.Context, bucket SchedulerBucket) error { + return nil +} + +func (c *snapshotHydrationCache) ReopenBucket(ctx context.Context, bucket SchedulerBucket) (SchedulerBucketWriteToken, error) { + return SchedulerBucketWriteToken{Bucket: bucket, Epoch: 1}, nil +} + +func (c *snapshotHydrationCache) TryAcquireGroupLifecycleLease(context.Context, int64, time.Duration) (SchedulerGroupLifecycleLease, bool, error) { + return SchedulerGroupLifecycleLease{}, false, nil +} + +func (c *snapshotHydrationCache) ReleaseGroupLifecycleLease(context.Context, SchedulerGroupLifecycleLease) error { return nil } diff --git a/backend/internal/service/scheduler_snapshot_outbox_cleanup_test.go b/backend/internal/service/scheduler_snapshot_outbox_cleanup_test.go index 91e2d36f76..2a476ff077 100644 --- a/backend/internal/service/scheduler_snapshot_outbox_cleanup_test.go +++ b/backend/internal/service/scheduler_snapshot_outbox_cleanup_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "reflect" + "sync" "testing" "time" @@ -14,6 +15,8 @@ type outboxCleanupCache struct { watermark int64 setWatermarks []int64 updateErr error + listBucketErr error + listBuckets []SchedulerBucket listBucketCalls int } @@ -21,7 +24,27 @@ func (c *outboxCleanupCache) GetSnapshot(ctx context.Context, bucket SchedulerBu return nil, false, nil } -func (c *outboxCleanupCache) SetSnapshot(ctx context.Context, bucket SchedulerBucket, accounts []Account) error { +func (c *outboxCleanupCache) CaptureBucketWriteToken(ctx context.Context, bucket SchedulerBucket) (SchedulerBucketWriteToken, error) { + return SchedulerBucketWriteToken{Bucket: bucket, Epoch: 1}, nil +} + +func (c *outboxCleanupCache) SetSnapshot(ctx context.Context, bucket SchedulerBucket, token SchedulerBucketWriteToken, accounts []Account) error { + return nil +} + +func (c *outboxCleanupCache) RetireBucket(ctx context.Context, bucket SchedulerBucket) error { + return nil +} + +func (c *outboxCleanupCache) ReopenBucket(ctx context.Context, bucket SchedulerBucket) (SchedulerBucketWriteToken, error) { + return SchedulerBucketWriteToken{Bucket: bucket, Epoch: 1}, nil +} + +func (c *outboxCleanupCache) TryAcquireGroupLifecycleLease(context.Context, int64, time.Duration) (SchedulerGroupLifecycleLease, bool, error) { + return SchedulerGroupLifecycleLease{}, false, nil +} + +func (c *outboxCleanupCache) ReleaseGroupLifecycleLease(context.Context, SchedulerGroupLifecycleLease) error { return nil } @@ -51,7 +74,7 @@ func (c *outboxCleanupCache) UnlockBucket(ctx context.Context, bucket SchedulerB func (c *outboxCleanupCache) ListBuckets(ctx context.Context) ([]SchedulerBucket, error) { c.listBucketCalls++ - return nil, nil + return c.listBuckets, c.listBucketErr } func (c *outboxCleanupCache) GetOutboxWatermark(ctx context.Context) (int64, error) { @@ -72,6 +95,8 @@ type outboxCleanupDeleteCall struct { type outboxCleanupRepo struct { events []SchedulerOutboxEvent rows []int64 + maxIDCalls int + maxIDErr error lockAcquired bool lockAttempts int releaseCount int @@ -79,6 +104,40 @@ type outboxCleanupRepo struct { firstCreatedAfterID []int64 } +type outboxCleanupAccountRepo struct { + AccountRepository +} + +func (r *outboxCleanupAccountRepo) ListSchedulableUngroupedByPlatform(context.Context, string) ([]Account, error) { + return nil, nil +} + +type blockingOutboxCleanupCache struct { + *outboxCleanupCache + mu sync.Mutex + calls int + started chan struct{} + release chan struct{} +} + +func (c *blockingOutboxCleanupCache) ListBuckets(context.Context) ([]SchedulerBucket, error) { + c.mu.Lock() + c.calls++ + call := c.calls + c.mu.Unlock() + if call == 1 { + close(c.started) + <-c.release + } + return c.listBuckets, c.listBucketErr +} + +func (c *blockingOutboxCleanupCache) listCalls() int { + c.mu.Lock() + defer c.mu.Unlock() + return c.calls +} + func (r *outboxCleanupRepo) ListAfterAndReleaseDedup(ctx context.Context, afterID int64, limit int) ([]SchedulerOutboxEvent, error) { events := make([]SchedulerOutboxEvent, 0, len(r.events)) for _, event := range r.events { @@ -104,6 +163,10 @@ func (r *outboxCleanupRepo) FirstCreatedAtAfter(ctx context.Context, afterID int } func (r *outboxCleanupRepo) MaxID(ctx context.Context) (int64, error) { + r.maxIDCalls++ + if r.maxIDErr != nil { + return 0, r.maxIDErr + } var maxID int64 for _, id := range r.rows { if id > maxID { @@ -293,6 +356,515 @@ func TestSchedulerSnapshotServicePollOutboxDoesNotUseConsumedEventForLag(t *test } } +func TestSchedulerSnapshotServiceCheckOutboxLagLatchesPersistentDegradation(t *testing.T) { + tests := []struct { + name string + createdAt time.Time + rows []int64 + lagSeconds int + backlogThreshold int + }{ + { + name: "lag", + createdAt: time.Now().Add(-time.Hour), + rows: []int64{1}, + lagSeconds: 1, + }, + { + name: "backlog", + createdAt: time.Now(), + rows: []int64{100}, + backlogThreshold: 50, + }, + { + name: "lag_and_backlog", + createdAt: time.Now().Add(-time.Hour), + rows: []int64{100}, + lagSeconds: 1, + backlogThreshold: 50, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cache := &outboxCleanupCache{listBuckets: []SchedulerBucket{{Platform: PlatformOpenAI, Mode: SchedulerModeSingle}}} + repo := &outboxCleanupRepo{ + events: []SchedulerOutboxEvent{{ID: 1, CreatedAt: tt.createdAt}}, + rows: tt.rows, + } + cfg := &config.Config{ + Gateway: config.GatewayConfig{ + Scheduling: config.GatewaySchedulingConfig{ + OutboxLagRebuildSeconds: tt.lagSeconds, + OutboxLagRebuildFailures: 1, + OutboxBacklogRebuildRows: tt.backlogThreshold, + }, + }, + } + svc := NewSchedulerSnapshotService(cache, repo, &outboxCleanupAccountRepo{}, nil, cfg) + + for range 3 { + svc.checkOutboxLag(context.Background(), 0) + } + + if cache.listBucketCalls != 1 { + t.Fatalf("expected one rebuild attempt during a persistent degraded episode, got %d", cache.listBucketCalls) + } + }) + } +} + +func TestSchedulerSnapshotServiceCheckOutboxLagFailedRebuildRearmsAfterRecovery(t *testing.T) { + cache := &outboxCleanupCache{listBucketErr: errors.New("list buckets failed")} + repo := &outboxCleanupRepo{ + events: []SchedulerOutboxEvent{{ID: 1, CreatedAt: time.Now().Add(-time.Hour)}}, + rows: []int64{1}, + } + cfg := &config.Config{ + Gateway: config.GatewayConfig{ + Scheduling: config.GatewaySchedulingConfig{ + OutboxLagRebuildSeconds: 1, + OutboxLagRebuildFailures: 1, + }, + }, + } + svc := NewSchedulerSnapshotService(cache, repo, nil, nil, cfg) + + svc.checkOutboxLag(context.Background(), 0) + svc.checkOutboxLag(context.Background(), 0) + if cache.listBucketCalls != 1 { + t.Fatalf("expected a failed rebuild to stay bounded within the episode, got %d attempts", cache.listBucketCalls) + } + + svc.checkOutboxLag(context.Background(), 1) + repo.events = append(repo.events, SchedulerOutboxEvent{ID: 2, CreatedAt: time.Now().Add(-time.Hour)}) + repo.rows = []int64{2} + svc.checkOutboxLag(context.Background(), 1) + + if cache.listBucketCalls != 2 { + t.Fatalf("expected recovery to rearm a failed rebuild for the next episode, got %d attempts", cache.listBucketCalls) + } +} + +func TestSchedulerSnapshotServiceCheckOutboxLagFailedRebuildRetriesAfterCooldownWithoutRecovery(t *testing.T) { + cache := &outboxCleanupCache{ + listBucketErr: errors.New("list buckets failed"), + listBuckets: []SchedulerBucket{{Platform: PlatformOpenAI, Mode: SchedulerModeSingle}}, + } + repo := &outboxCleanupRepo{ + events: []SchedulerOutboxEvent{{ID: 1, CreatedAt: time.Now().Add(-time.Hour)}}, + rows: []int64{1}, + } + cfg := &config.Config{ + Gateway: config.GatewayConfig{ + Scheduling: config.GatewaySchedulingConfig{ + OutboxLagRebuildSeconds: 1, + OutboxLagRebuildFailures: 1, + FullRebuildIntervalSeconds: 0, + }, + }, + } + svc := NewSchedulerSnapshotService(cache, repo, &outboxCleanupAccountRepo{}, nil, cfg) + + svc.checkOutboxLag(context.Background(), 0) + for range 3 { + svc.checkOutboxLag(context.Background(), 0) + } + if cache.listBucketCalls != 1 { + t.Fatalf("expected failed rebuild polls to be rate limited, got %d attempts", cache.listBucketCalls) + } + + svc.lagMu.Lock() + if !svc.outboxRebuildRetryAt.After(time.Now()) { + t.Fatal("expected failed rebuild to schedule a future retry") + } + svc.outboxRebuildRetryAt = time.Now().Add(-time.Second) + svc.lagMu.Unlock() + svc.checkOutboxLag(context.Background(), 0) + if cache.listBucketCalls != 2 { + t.Fatalf("expected persistent degradation to retry after cooldown, got %d attempts", cache.listBucketCalls) + } + + for range 3 { + svc.checkOutboxLag(context.Background(), 0) + } + if cache.listBucketCalls != 2 { + t.Fatalf("expected repeated rebuild failures to stay rate limited, got %d attempts", cache.listBucketCalls) + } + + svc.lagMu.Lock() + svc.outboxRebuildRetryAt = time.Now().Add(-time.Second) + svc.lagMu.Unlock() + cache.listBucketErr = nil + svc.checkOutboxLag(context.Background(), 0) + if cache.listBucketCalls != 3 { + t.Fatalf("expected degraded episode to retry after cooldown, got %d attempts", cache.listBucketCalls) + } + + for range 3 { + svc.checkOutboxLag(context.Background(), 0) + } + if cache.listBucketCalls != 3 { + t.Fatalf("expected successful retry to latch the degraded episode, got %d attempts", cache.listBucketCalls) + } +} + +func TestSchedulerSnapshotServiceCheckOutboxLagBacklogRetryDoesNotBypassNewLagThreshold(t *testing.T) { + cache := &outboxCleanupCache{listBucketErr: errors.New("list buckets failed")} + repo := &outboxCleanupRepo{ + events: []SchedulerOutboxEvent{{ID: 1, CreatedAt: time.Now()}}, + rows: []int64{100}, + } + cfg := &config.Config{ + Gateway: config.GatewayConfig{ + Scheduling: config.GatewaySchedulingConfig{ + OutboxLagRebuildSeconds: 1, + OutboxLagRebuildFailures: 3, + OutboxBacklogRebuildRows: 50, + }, + }, + } + svc := NewSchedulerSnapshotService(cache, repo, nil, nil, cfg) + + // Start with backlog-only degradation and leave its failed rebuild retry due. + svc.checkOutboxLag(context.Background(), 0) + if cache.listBucketCalls != 1 { + t.Fatalf("expected the backlog degradation to attempt one rebuild, got %d", cache.listBucketCalls) + } + svc.lagMu.Lock() + svc.outboxRebuildRetryAt = time.Now().Add(-time.Second) + svc.lagMu.Unlock() + + // The backlog recovers while lag becomes newly degraded. The stale backlog + // retry must not make the first lag observation bypass its failure threshold. + repo.rows = []int64{1} + repo.events[0].CreatedAt = time.Now().Add(-time.Hour) + svc.checkOutboxLag(context.Background(), 0) + if cache.listBucketCalls != 1 { + t.Fatalf("expected the new lag episode to start at its own threshold, got %d rebuild attempts", cache.listBucketCalls) + } + + svc.checkOutboxLag(context.Background(), 0) + svc.checkOutboxLag(context.Background(), 0) + if cache.listBucketCalls != 2 { + t.Fatalf("expected lag rebuild only after three lag observations, got %d attempts", cache.listBucketCalls) + } +} + +func TestSchedulerSnapshotServiceCheckOutboxLagLagRetryDoesNotDelayOrEscalateNewBacklog(t *testing.T) { + cache := &outboxCleanupCache{listBucketErr: errors.New("list buckets failed")} + repo := &outboxCleanupRepo{ + events: []SchedulerOutboxEvent{{ID: 1, CreatedAt: time.Now().Add(-time.Hour)}}, + rows: []int64{1}, + } + cfg := &config.Config{ + Gateway: config.GatewayConfig{ + Scheduling: config.GatewaySchedulingConfig{ + OutboxLagRebuildSeconds: 1, + OutboxLagRebuildFailures: 1, + OutboxBacklogRebuildRows: 50, + }, + }, + } + svc := NewSchedulerSnapshotService(cache, repo, nil, nil, cfg) + + // Start with lag-only degradation and a failed rebuild in cooldown. + svc.checkOutboxLag(context.Background(), 0) + if cache.listBucketCalls != 1 { + t.Fatalf("expected the lag degradation to attempt one rebuild, got %d", cache.listBucketCalls) + } + + // Lag recovers while backlog becomes newly degraded. It must start immediately + // and its first failure must use the base retry generation, not lag's count. + repo.events[0].CreatedAt = time.Now() + repo.rows = []int64{100} + svc.checkOutboxLag(context.Background(), 0) + if cache.listBucketCalls != 2 { + t.Fatalf("expected the new backlog degradation not to inherit lag cooldown, got %d rebuild attempts", cache.listBucketCalls) + } + svc.lagMu.Lock() + failures := svc.outboxRebuildFailures + svc.lagMu.Unlock() + if failures != 1 { + t.Fatalf("expected backlog retry failures to restart at one, got %d", failures) + } +} + +func TestSchedulerSnapshotServiceCheckOutboxLagBacklogRetrySurvivesUnknownBacklog(t *testing.T) { + cache := &outboxCleanupCache{listBucketErr: errors.New("list buckets failed")} + repo := &outboxCleanupRepo{ + events: []SchedulerOutboxEvent{{ID: 1, CreatedAt: time.Now()}}, + rows: []int64{100}, + } + cfg := &config.Config{ + Gateway: config.GatewayConfig{ + Scheduling: config.GatewaySchedulingConfig{ + OutboxBacklogRebuildRows: 50, + }, + }, + } + svc := NewSchedulerSnapshotService(cache, repo, nil, nil, cfg) + + // A failed backlog rebuild starts a reason-scoped cooldown. + svc.checkOutboxLag(context.Background(), 0) + if cache.listBucketCalls != 1 { + t.Fatalf("expected one initial backlog rebuild, got %d", cache.listBucketCalls) + } + svc.lagMu.Lock() + retryAt := svc.outboxRebuildRetryAt + svc.lagMu.Unlock() + if !retryAt.After(time.Now()) { + t.Fatalf("expected a future backlog retry, got %s", retryAt) + } + + // A temporary MaxID failure makes backlog health unknown, not recovered. + repo.maxIDErr = errors.New("max id unavailable") + svc.checkOutboxLag(context.Background(), 0) + svc.lagMu.Lock() + retryReason := svc.outboxRebuildRetryReason + failures := svc.outboxRebuildFailures + retryAtAfterUnknown := svc.outboxRebuildRetryAt + svc.lagMu.Unlock() + if retryReason != "outbox_backlog" || failures != 1 || !retryAtAfterUnknown.Equal(retryAt) { + t.Fatalf("expected unknown backlog to preserve retry state, got reason=%q failures=%d retry_at=%s", retryReason, failures, retryAtAfterUnknown) + } + + // When MaxID recovers and backlog remains degraded, the original cooldown + // still applies; only an expired cooldown may trigger the retry. + repo.maxIDErr = nil + svc.checkOutboxLag(context.Background(), 0) + if cache.listBucketCalls != 1 { + t.Fatalf("expected backlog recovery before cooldown to stay rate limited, got %d attempts", cache.listBucketCalls) + } + svc.lagMu.Lock() + svc.outboxRebuildRetryAt = time.Now().Add(-time.Second) + svc.lagMu.Unlock() + svc.checkOutboxLag(context.Background(), 0) + if cache.listBucketCalls != 2 { + t.Fatalf("expected backlog retry after cooldown expiry, got %d attempts", cache.listBucketCalls) + } +} + +func TestSchedulerSnapshotServiceCheckOutboxLagPreemptsUnknownBacklogRetryAtThreshold(t *testing.T) { + cache := &outboxCleanupCache{listBucketErr: errors.New("list buckets failed")} + repo := &outboxCleanupRepo{ + events: []SchedulerOutboxEvent{{ID: 1, CreatedAt: time.Now()}}, + rows: []int64{100}, + } + cfg := &config.Config{ + Gateway: config.GatewayConfig{ + Scheduling: config.GatewaySchedulingConfig{ + OutboxLagRebuildSeconds: 1, + OutboxLagRebuildFailures: 3, + OutboxBacklogRebuildRows: 50, + }, + }, + } + svc := NewSchedulerSnapshotService(cache, repo, nil, nil, cfg) + + // Backlog starts the first failed rebuild generation and remains unknown. + svc.checkOutboxLag(context.Background(), 0) + if cache.listBucketCalls != 1 { + t.Fatalf("expected one initial backlog rebuild, got %d", cache.listBucketCalls) + } + repo.maxIDErr = errors.New("max id unavailable") + repo.events[0].CreatedAt = time.Now().Add(-time.Hour) + + // A known lag degradation must keep accumulating independently of the active + // backlog cooldown and preempt it only after reaching its own threshold. + for observation := 1; observation <= 2; observation++ { + svc.checkOutboxLag(context.Background(), 0) + if cache.listBucketCalls != 1 { + t.Fatalf("expected lag observation %d to stay below threshold, got %d rebuild attempts", observation, cache.listBucketCalls) + } + } + svc.checkOutboxLag(context.Background(), 0) + if cache.listBucketCalls != 2 { + t.Fatalf("expected lag to preempt backlog cooldown at its threshold, got %d attempts", cache.listBucketCalls) + } + + svc.lagMu.Lock() + retryReason := svc.outboxRebuildRetryReason + failures := svc.outboxRebuildFailures + retryAt := svc.outboxRebuildRetryAt + svc.lagMu.Unlock() + if retryReason != "outbox_lag" || failures != 1 || !retryAt.After(time.Now()) { + t.Fatalf("expected a fresh lag retry generation, got reason=%q failures=%d retry_at=%s", retryReason, failures, retryAt) + } +} + +func TestOutboxRebuildRetryDelayIsExponentiallyBounded(t *testing.T) { + previous := time.Duration(0) + for failures := 1; failures <= 20; failures++ { + delay := outboxRebuildRetryDelay(failures) + if delay < previous { + t.Fatalf("expected retry delay to be monotonic, failure %d produced %s after %s", failures, delay, previous) + } + if delay > outboxRebuildRetryMaxDelay { + t.Fatalf("expected retry delay to stay bounded, got %s", delay) + } + previous = delay + } + if previous != outboxRebuildRetryMaxDelay { + t.Fatalf("expected repeated failures to reach max delay %s, got %s", outboxRebuildRetryMaxDelay, previous) + } +} + +func TestSchedulerSnapshotServicePollOutboxEmptyBatchClearsDegradedEpisode(t *testing.T) { + cache := &outboxCleanupCache{listBuckets: []SchedulerBucket{{Platform: PlatformOpenAI, Mode: SchedulerModeSingle}}} + repo := &outboxCleanupRepo{ + events: []SchedulerOutboxEvent{{ID: 1, CreatedAt: time.Now().Add(-time.Hour)}}, + rows: []int64{1}, + } + cfg := &config.Config{ + Gateway: config.GatewayConfig{ + Scheduling: config.GatewaySchedulingConfig{ + OutboxLagRebuildSeconds: 1, + OutboxLagRebuildFailures: 1, + OutboxBacklogRebuildRows: 1, + }, + }, + } + svc := NewSchedulerSnapshotService(cache, repo, &outboxCleanupAccountRepo{}, nil, cfg) + + svc.checkOutboxLag(context.Background(), 0) + cache.watermark = 1 + svc.pollOutbox() + + if !reflect.DeepEqual(repo.firstCreatedAfterID, []int64{0}) { + t.Fatalf("expected empty poll to use the empty batch as recovery evidence, got watermarks %#v", repo.firstCreatedAfterID) + } + if repo.maxIDCalls != 1 { + t.Fatalf("expected empty poll to skip a redundant backlog query, got %d health checks", repo.maxIDCalls) + } + + repo.events = append(repo.events, SchedulerOutboxEvent{ID: 2, CreatedAt: time.Now().Add(-time.Hour)}) + repo.rows = []int64{2} + svc.checkOutboxLag(context.Background(), 1) + if cache.listBucketCalls != 2 { + t.Fatalf("expected empty-poll recovery to rearm the next degraded episode, got %d attempts", cache.listBucketCalls) + } +} + +func TestSchedulerSnapshotServiceOutboxLagWarningIsTransitionLimited(t *testing.T) { + svc := NewSchedulerSnapshotService(nil, nil, nil, nil, nil) + + if !svc.shouldLogOutboxLagWarning(true) { + t.Fatal("expected the initial degraded transition to log") + } + if svc.shouldLogOutboxLagWarning(true) { + t.Fatal("expected persistent degradation to suppress repeated warnings") + } + if svc.shouldLogOutboxLagWarning(true) { + t.Fatal("expected persistent degradation to suppress repeated warnings") + } + if svc.shouldLogOutboxLagWarning(false) { + t.Fatal("expected recovery not to emit a lag warning") + } + if !svc.shouldLogOutboxLagWarning(true) { + t.Fatal("expected renewed degradation to log after recovery") + } +} + +func TestSchedulerSnapshotServiceCheckOutboxLagSamplesMaxIDErrors(t *testing.T) { + svc := NewSchedulerSnapshotService(nil, nil, nil, nil, nil) + now := time.Now() + + if !svc.shouldLogOutboxMaxIDError(now) { + t.Fatal("expected the first MaxID error to log") + } + if svc.shouldLogOutboxMaxIDError(now.Add(outboxMaxIDErrorLogSampleInterval / 2)) { + t.Fatal("expected MaxID errors inside the sample interval to be suppressed") + } + if !svc.shouldLogOutboxMaxIDError(now.Add(outboxMaxIDErrorLogSampleInterval)) { + t.Fatal("expected MaxID error logging to rearm after the sample interval") + } +} + +func TestSchedulerSnapshotServicePollOutboxHealthyEmptyBatchSkipsLagHealthQueries(t *testing.T) { + cache := &outboxCleanupCache{} + repo := &outboxCleanupRepo{} + cfg := &config.Config{ + Gateway: config.GatewayConfig{ + Scheduling: config.GatewaySchedulingConfig{ + OutboxLagRebuildSeconds: 1, + OutboxLagRebuildFailures: 1, + OutboxBacklogRebuildRows: 1, + }, + }, + } + svc := NewSchedulerSnapshotService(cache, repo, nil, nil, cfg) + + svc.pollOutbox() + + if len(repo.firstCreatedAfterID) != 0 { + t.Fatalf("expected healthy empty poll to skip lag query, got watermarks %#v", repo.firstCreatedAfterID) + } + if repo.maxIDCalls != 0 { + t.Fatalf("expected healthy empty poll to skip backlog query, got %d calls", repo.maxIDCalls) + } +} + +func TestSchedulerSnapshotServiceEmptyPollDoesNotReleaseRunningRebuild(t *testing.T) { + baseCache := &outboxCleanupCache{ + watermark: 1, + listBuckets: []SchedulerBucket{{Platform: PlatformOpenAI, Mode: SchedulerModeSingle}}, + } + cache := &blockingOutboxCleanupCache{ + outboxCleanupCache: baseCache, + started: make(chan struct{}), + release: make(chan struct{}), + } + repo := &outboxCleanupRepo{ + events: []SchedulerOutboxEvent{{ID: 1, CreatedAt: time.Now().Add(-time.Hour)}}, + rows: []int64{1}, + } + cfg := &config.Config{ + Gateway: config.GatewayConfig{ + Scheduling: config.GatewaySchedulingConfig{ + OutboxLagRebuildSeconds: 1, + OutboxLagRebuildFailures: 1, + }, + }, + } + svc := NewSchedulerSnapshotService(cache, repo, &outboxCleanupAccountRepo{}, nil, cfg) + + firstDone := make(chan struct{}) + go func() { + svc.checkOutboxLag(context.Background(), 0) + close(firstDone) + }() + select { + case <-cache.started: + case <-time.After(time.Second): + t.Fatal("first rebuild did not start") + } + + // The empty batch proves recovery for episode/retry state, but it must not + // release ownership of the still-running rebuild. + svc.pollOutbox() + + secondDone := make(chan struct{}) + go func() { + svc.checkOutboxLag(context.Background(), 0) + close(secondDone) + }() + select { + case <-secondDone: + case <-time.After(200 * time.Millisecond): + close(cache.release) + <-firstDone + <-secondDone + t.Fatal("second lag check queued another rebuild while the first was running") + } + + close(cache.release) + <-firstDone + if calls := cache.listCalls(); calls != 1 { + t.Fatalf("expected one rebuild generation, got %d", calls) + } +} + func TestSchedulerSnapshotServiceCleanupSkipsNonPositiveWatermark(t *testing.T) { repo := &outboxCleanupRepo{ rows: []int64{1, 2, 3}, diff --git a/backend/internal/service/scheduler_snapshot_retirement_test.go b/backend/internal/service/scheduler_snapshot_retirement_test.go new file mode 100644 index 0000000000..3d24179758 --- /dev/null +++ b/backend/internal/service/scheduler_snapshot_retirement_test.go @@ -0,0 +1,263 @@ +//go:build unit + +package service + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +type retirementRaceCache struct { + SchedulerCache + + mu sync.Mutex + epochs map[string]int64 + retired map[string]bool + listBuckets []SchedulerBucket + captures []SchedulerBucket + reopens []SchedulerBucket + setAttempts map[string]int + published map[string]int + versions map[string]int + beforeSet func() +} + +func newRetirementRaceCache(buckets ...SchedulerBucket) *retirementRaceCache { + return &retirementRaceCache{ + epochs: make(map[string]int64), + retired: make(map[string]bool), + listBuckets: buckets, + setAttempts: make(map[string]int), + published: make(map[string]int), + versions: make(map[string]int), + } +} + +func (c *retirementRaceCache) GetSnapshot(context.Context, SchedulerBucket) ([]*Account, bool, error) { + return nil, false, nil +} + +func (c *retirementRaceCache) CaptureBucketWriteToken(_ context.Context, bucket SchedulerBucket) (SchedulerBucketWriteToken, error) { + c.mu.Lock() + defer c.mu.Unlock() + key := bucket.String() + c.captures = append(c.captures, bucket) + if c.retired[key] { + return SchedulerBucketWriteToken{}, ErrSchedulerBucketRetired + } + if c.epochs[key] == 0 { + c.epochs[key] = 1 + } + return SchedulerBucketWriteToken{Bucket: bucket, Epoch: c.epochs[key]}, nil +} + +func (c *retirementRaceCache) SetSnapshot(_ context.Context, bucket SchedulerBucket, token SchedulerBucketWriteToken, _ []Account) error { + if c.beforeSet != nil { + c.beforeSet() + } + c.mu.Lock() + defer c.mu.Unlock() + key := bucket.String() + c.setAttempts[key]++ + if !token.ValidFor(bucket) { + return ErrSchedulerBucketWriteFenced + } + if c.retired[key] { + return ErrSchedulerBucketRetired + } + if c.epochs[key] != token.Epoch { + return ErrSchedulerBucketWriteFenced + } + c.versions[key]++ + c.published[key]++ + return nil +} + +func (c *retirementRaceCache) RetireBucket(_ context.Context, bucket SchedulerBucket) error { + c.mu.Lock() + defer c.mu.Unlock() + key := bucket.String() + if !c.retired[key] { + c.epochs[key]++ + if c.epochs[key] < 1 { + c.epochs[key] = 1 + } + c.retired[key] = true + } + return nil +} + +func (c *retirementRaceCache) ReopenBucket(_ context.Context, bucket SchedulerBucket) (SchedulerBucketWriteToken, error) { + c.mu.Lock() + defer c.mu.Unlock() + key := bucket.String() + if c.epochs[key] == 0 { + c.epochs[key] = 1 + } + delete(c.retired, key) + c.reopens = append(c.reopens, bucket) + return SchedulerBucketWriteToken{Bucket: bucket, Epoch: c.epochs[key]}, nil +} + +func (c *retirementRaceCache) TryLockBucket(context.Context, SchedulerBucket, time.Duration) (bool, error) { + return true, nil +} + +func (c *retirementRaceCache) UnlockBucket(context.Context, SchedulerBucket) error { + return nil +} + +func (c *retirementRaceCache) ListBuckets(context.Context) ([]SchedulerBucket, error) { + return append([]SchedulerBucket(nil), c.listBuckets...), nil +} + +func (c *retirementRaceCache) counts(bucket SchedulerBucket) (setAttempts, published int) { + c.mu.Lock() + defer c.mu.Unlock() + return c.setAttempts[bucket.String()], c.published[bucket.String()] +} + +func (c *retirementRaceCache) captureAndReopenCounts() (captures, reopens int) { + c.mu.Lock() + defer c.mu.Unlock() + return len(c.captures), len(c.reopens) +} + +func (c *retirementRaceCache) version(bucket SchedulerBucket) int { + c.mu.Lock() + defer c.mu.Unlock() + return c.versions[bucket.String()] +} + +type retirementGroupRepo struct { + GroupRepository + groups []Group + err error +} + +func (r *retirementGroupRepo) ListActive(context.Context) ([]Group, error) { + return r.groups, r.err +} + +func TestSchedulerFullRebuildCapturesAllRegistryTokensBeforeDBLoad(t *testing.T) { + first := SchedulerBucket{GroupID: 61, Platform: PlatformOpenAI, Mode: SchedulerModeSingle} + queued := SchedulerBucket{GroupID: 61, Platform: PlatformOpenAI, Mode: SchedulerModeForced} + cache := newRetirementRaceCache(first, queued) + dbStarted := make(chan struct{}) + releaseDB := make(chan struct{}) + var firstDB sync.Once + repo := &mockAccountRepoForPlatform{ + listPlatformFunc: func(context.Context, string) ([]Account, error) { + firstDB.Do(func() { + close(dbStarted) + <-releaseDB + }) + return []Account{{ID: 6101, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true}}, nil + }, + } + svc := NewSchedulerSnapshotService(cache, nil, repo, &retirementGroupRepo{groups: []Group{{ID: 61, Status: StatusActive}}}, &config.Config{ + RunMode: config.RunModeStandard, + Gateway: config.GatewayConfig{Scheduling: config.GatewaySchedulingConfig{ + DbFallbackEnabled: true, + }}, + }) + + result := make(chan error, 1) + go func() { result <- svc.triggerFullRebuild("retirement_race_a") }() + select { + case <-dbStarted: + case <-time.After(time.Second): + t.Fatal("first DB load did not start") + } + + captures, reopens := cache.captureAndReopenCounts() + require.Equal(t, 24, captures, "group0 and active-group canonical tokens must be captured before the first DB load") + require.Zero(t, reopens) + require.NoError(t, cache.RetireBucket(context.Background(), queued)) + _, err := cache.ReopenBucket(context.Background(), queued) + require.NoError(t, err) + close(releaseDB) + require.NoError(t, <-result) + + _, firstPublished := cache.counts(first) + queuedAttempts, queuedPublished := cache.counts(queued) + require.Equal(t, 1, firstPublished) + require.Equal(t, 1, queuedAttempts) + require.Zero(t, queuedPublished, "queued registry task must not adopt the reopened epoch") +} + +func TestSchedulerRebuildRetireAfterDBLoadFencesPublish(t *testing.T) { + bucket := SchedulerBucket{GroupID: 62, Platform: PlatformOpenAI, Mode: SchedulerModeSingle} + cache := newRetirementRaceCache() + dbReturned := make(chan struct{}) + setEntered := make(chan struct{}) + releaseSet := make(chan struct{}) + cache.beforeSet = func() { + close(setEntered) + <-releaseSet + } + repo := &mockAccountRepoForPlatform{ + listPlatformFunc: func(context.Context, string) ([]Account, error) { + close(dbReturned) + return []Account{{ID: 6201, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true}}, nil + }, + } + svc := NewSchedulerSnapshotService(cache, nil, repo, nil, &config.Config{ + RunMode: config.RunModeStandard, + Gateway: config.GatewayConfig{Scheduling: config.GatewaySchedulingConfig{ + DbFallbackEnabled: true, + }}, + }) + + result := make(chan error, 1) + go func() { + result <- svc.rebuildBuckets(context.Background(), []SchedulerBucket{bucket}, "retirement_race_b") + }() + select { + case <-dbReturned: + case <-time.After(time.Second): + t.Fatal("DB load did not return") + } + select { + case <-setEntered: + case <-time.After(time.Second): + t.Fatal("snapshot writer did not reach allocation boundary") + } + require.NoError(t, cache.RetireBucket(context.Background(), bucket)) + close(releaseSet) + require.NoError(t, <-result) + + setAttempts, published := cache.counts(bucket) + require.Equal(t, 1, setAttempts) + require.Zero(t, published) + require.Zero(t, cache.version(bucket), "retirement before allocation must not advance the snapshot version") +} + +func TestSchedulerFallbackReturnsDBAccountsWhenBucketRetired(t *testing.T) { + bucket := SchedulerBucket{GroupID: 63, Platform: PlatformOpenAI, Mode: SchedulerModeSingle} + cache := newRetirementRaceCache() + require.NoError(t, cache.RetireBucket(context.Background(), bucket)) + repo := &mockAccountRepoForPlatform{ + accounts: []Account{{ID: 6301, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true}}, + } + svc := NewSchedulerSnapshotService(cache, nil, repo, nil, &config.Config{ + RunMode: config.RunModeStandard, + Gateway: config.GatewayConfig{Scheduling: config.GatewaySchedulingConfig{ + DbFallbackEnabled: true, + }}, + }) + groupID := bucket.GroupID + + accounts, useMixed, err := svc.ListSchedulableAccounts(context.Background(), &groupID, bucket.Platform, false) + require.NoError(t, err) + require.False(t, useMixed) + require.Len(t, accounts, 1) + setAttempts, published := cache.counts(bucket) + require.Zero(t, setAttempts) + require.Zero(t, published) +} diff --git a/backend/internal/service/scheduler_snapshot_service.go b/backend/internal/service/scheduler_snapshot_service.go index 77bef26edf..a5bccdb265 100644 --- a/backend/internal/service/scheduler_snapshot_service.go +++ b/backend/internal/service/scheduler_snapshot_service.go @@ -4,7 +4,9 @@ import ( "context" "encoding/json" "errors" + "fmt" "log/slog" + "sort" "strconv" "sync" "time" @@ -14,35 +16,116 @@ import ( ) var ( - ErrSchedulerCacheNotReady = errors.New("scheduler cache not ready") - ErrSchedulerFallbackLimited = errors.New("scheduler db fallback limited") + ErrSchedulerCacheNotReady = errors.New("scheduler cache not ready") + ErrSchedulerFallbackLimited = errors.New("scheduler db fallback limited") + ErrSchedulerGroupLifecycleLeaseBusy = errors.New("scheduler group lifecycle lease busy") + ErrSchedulerBucketRebuildBusy = errors.New("scheduler bucket rebuild busy") ) const ( - outboxEventTimeout = 2 * time.Minute - schedulerOutboxCleanupBatch = 5000 + outboxEventTimeout = 2 * time.Minute + schedulerOutboxCleanupBatch = 5000 + schedulerGroupLifecycleTimeout = 30 * time.Second + schedulerGroupLifecycleLeaseTTL = 60 * time.Second + schedulerGroupLifecycleReleaseTimeout = 2 * time.Second + outboxRebuildRetryBaseDelay = 5 * time.Second + outboxRebuildRetryMaxDelay = 5 * time.Minute + outboxMaxIDErrorLogSampleInterval = time.Minute ) -// batchSeenKey tracks which (groupID, platform) bucket sets have already been -// rebuilt within a single pollOutbox call, to avoid redundant work when multiple -// account_changed events share the same groups. +// batchSeenKey tracks completed per-platform rebuilds and group lifecycle work +// within one pollOutbox call. type batchSeenKey struct { + groupID int64 + platform string + lifecycle bool +} + +type schedulerBucketWriteTask struct { + bucket SchedulerBucket + token SchedulerBucketWriteToken +} + +type schedulerAccountQueryKey struct { groupID int64 platform string } +// 查询结果只在一次 rebuild batch 内,按原始 groupID+platform 复用成功的 single/forced 查询; +// mixed 与历史模式保持独立。每个 task 都用 defer 消费 remaining,最后一个消费者会立即释放结果, +// 避免把账号切片的生命周期扩大到整轮 full rebuild。 +type schedulerAccountQueryCache struct { + remaining map[schedulerAccountQueryKey]int + accounts map[schedulerAccountQueryKey][]Account +} + +func newSchedulerAccountQueryCache(taskSets ...[]schedulerBucketWriteTask) *schedulerAccountQueryCache { + queries := &schedulerAccountQueryCache{ + remaining: make(map[schedulerAccountQueryKey]int), + accounts: make(map[schedulerAccountQueryKey][]Account), + } + for _, tasks := range taskSets { + for _, task := range tasks { + if key, ok := schedulerAccountQueryKeyForBucket(task.bucket); ok { + queries.remaining[key]++ + } + } + } + return queries +} + +func schedulerAccountQueryKeyForBucket(bucket SchedulerBucket) (schedulerAccountQueryKey, bool) { + if bucket.Mode != SchedulerModeSingle && bucket.Mode != SchedulerModeForced { + return schedulerAccountQueryKey{}, false + } + return schedulerAccountQueryKey{groupID: bucket.GroupID, platform: bucket.Platform}, true +} + +func (c *schedulerAccountQueryCache) release(bucket SchedulerBucket) { + if c == nil { + return + } + key, ok := schedulerAccountQueryKeyForBucket(bucket) + if !ok { + return + } + remaining := c.remaining[key] - 1 + if remaining <= 0 { + delete(c.remaining, key) + delete(c.accounts, key) + return + } + c.remaining[key] = remaining +} + +type schedulerGroupLifecyclePlan struct { + active bool + tasks []schedulerBucketWriteTask +} + +type schedulerActiveGroupIDLister interface { + ListActiveIDs(ctx context.Context) ([]int64, error) +} + type SchedulerSnapshotService struct { - cache SchedulerCache - outboxRepo SchedulerOutboxRepository - accountRepo AccountRepository - groupRepo GroupRepository - cfg *config.Config - stopCh chan struct{} - stopOnce sync.Once - wg sync.WaitGroup - fallbackLimit *fallbackLimiter - lagMu sync.Mutex - lagFailures int + cache SchedulerCache + outboxRepo SchedulerOutboxRepository + accountRepo AccountRepository + groupRepo GroupRepository + cfg *config.Config + stopCh chan struct{} + stopOnce sync.Once + wg sync.WaitGroup + fallbackLimit *fallbackLimiter + lagMu sync.Mutex + lagFailures int + outboxRebuildLatched bool + outboxRebuildRunning bool + outboxRebuildFailures int + outboxRebuildRetryAt time.Time + outboxRebuildRetryReason string + outboxLagWarningActive bool + outboxMaxIDErrorLastLoggedAt time.Time fullRebuildRunMu sync.Mutex fullRebuildStateMu sync.Mutex @@ -117,6 +200,8 @@ func (s *SchedulerSnapshotService) ListSchedulableAccounts(ctx context.Context, useMixed := (platform == PlatformAnthropic || platform == PlatformGemini) && !hasForcePlatform mode := s.resolveMode(platform, hasForcePlatform) bucket := s.bucketFor(groupID, platform, mode) + var writeToken SchedulerBucketWriteToken + canPublish := false if s.cache != nil { cached, hit, err := s.cache.GetSnapshot(ctx, bucket) @@ -125,6 +210,17 @@ func (s *SchedulerSnapshotService) ListSchedulableAccounts(ctx context.Context, } else if hit { return derefAccounts(cached), useMixed, nil } + token, err := s.cache.CaptureBucketWriteToken(ctx, bucket) + if err != nil { + if errors.Is(err, ErrSchedulerBucketRetired) || errors.Is(err, ErrSchedulerBucketWriteFenced) { + slog.Debug("[Scheduler] cache publish fenced", "bucket", bucket.String()) + } else { + logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] cache publish token failed: bucket=%s err=%v", bucket.String(), err) + } + } else { + writeToken = token + canPublish = true + } } if err := s.guardFallback(ctx); err != nil { @@ -139,9 +235,13 @@ func (s *SchedulerSnapshotService) ListSchedulableAccounts(ctx context.Context, return nil, useMixed, err } - if s.cache != nil { - if err := s.cache.SetSnapshot(fallbackCtx, bucket, accounts); err != nil { - logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] cache write failed: bucket=%s err=%v", bucket.String(), err) + if s.cache != nil && canPublish { + if err := s.cache.SetSnapshot(fallbackCtx, bucket, writeToken, accounts); err != nil { + if errors.Is(err, ErrSchedulerBucketRetired) || errors.Is(err, ErrSchedulerBucketWriteFenced) { + slog.Debug("[Scheduler] cache publish fenced", "bucket", bucket.String()) + } else { + logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] cache write failed: bucket=%s err=%v", bucket.String(), err) + } } } @@ -192,18 +292,7 @@ func (s *SchedulerSnapshotService) runInitialRebuild() { _ = s.coalesceFullRebuild(func() error { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() - buckets, err := s.cache.ListBuckets(ctx) - if err != nil { - logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] list buckets failed: %v", err) - } - if len(buckets) == 0 { - buckets, err = s.defaultBuckets(ctx) - if err != nil { - logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] default buckets failed: %v", err) - return err - } - } - if err := s.rebuildBuckets(ctx, buckets, "startup"); err != nil { + if err := s.rebuildFullSnapshot(ctx, "startup"); err != nil { logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] rebuild startup failed: %v", err) return err } @@ -261,6 +350,10 @@ func (s *SchedulerSnapshotService) pollOutbox() { return } if len(events) == 0 { + // The outbox query itself proves there is no event after the watermark. + // Clear degraded/retry state without adding two more repository queries to + // the healthy one-second poll path. + s.clearOutboxDegradedEpisode() return } @@ -491,11 +584,125 @@ func (s *SchedulerSnapshotService) handleAccountEvent(ctx context.Context, accou } func (s *SchedulerSnapshotService) handleGroupEvent(ctx context.Context, groupID *int64, seen map[batchSeenKey]struct{}) error { - if groupID == nil || *groupID <= 0 { + if groupID == nil || *groupID <= 0 || s.isRunModeSimple() { return nil } - groupIDs := []int64{*groupID} - return s.rebuildByGroupIDs(ctx, groupIDs, "group_change", seen) + if seen != nil { + if _, ok := seen[batchSeenKey{groupID: *groupID, lifecycle: true}]; ok { + return nil + } + } + return s.reconcileGroupLifecycle(ctx, *groupID, seen) +} + +func (s *SchedulerSnapshotService) reconcileGroupLifecycle(ctx context.Context, groupID int64, seen map[batchSeenKey]struct{}) error { + plan, err := s.prepareGroupLifecycle(ctx, groupID, nil) + if err != nil { + return err + } + if plan.active { + queries := newSchedulerAccountQueryCache(plan.tasks) + for _, task := range plan.tasks { + if err := s.rebuildBucketWithTokenPolicyAndQueryCache(ctx, task, "group_change", true, queries); err != nil { + return err + } + } + } + markGroupLifecycleSeen(seen, groupID) + return nil +} + +// 生命周期决策必须在所有者安全的租约内读取 fresh 且完整的分组权威状态。 +// active 仅 Reopen canonical bucket;missing/inactive 同时 Retire canonical 与已登记历史 bucket; +// group event 路径只有在权威决策和后续重建全部成功后才会标记 seen。 +func (s *SchedulerSnapshotService) prepareGroupLifecycle(ctx context.Context, groupID int64, knownHistorical []SchedulerBucket) (plan schedulerGroupLifecyclePlan, retErr error) { + if groupID <= 0 || s.isRunModeSimple() { + return schedulerGroupLifecyclePlan{}, nil + } + if s.cache == nil || s.groupRepo == nil { + return schedulerGroupLifecyclePlan{}, ErrSchedulerCacheNotReady + } + + lifecycleCtx, cancel := context.WithTimeout(ctx, schedulerGroupLifecycleTimeout) + defer cancel() + lease, acquired, err := s.cache.TryAcquireGroupLifecycleLease(lifecycleCtx, groupID, schedulerGroupLifecycleLeaseTTL) + if err != nil { + return schedulerGroupLifecyclePlan{}, err + } + if !acquired { + return schedulerGroupLifecyclePlan{}, fmt.Errorf("%w: group=%d", ErrSchedulerGroupLifecycleLeaseBusy, groupID) + } + leaseHeld := true + defer func() { + if leaseHeld { + retErr = errors.Join(retErr, s.releaseGroupLifecycleLease(lease)) + } + }() + + group, err := s.groupRepo.GetByIDLite(lifecycleCtx, groupID) + missing := errors.Is(err, ErrGroupNotFound) + if err != nil && !missing { + return schedulerGroupLifecyclePlan{}, err + } + if err == nil && (group == nil || group.ID != groupID || !group.Hydrated) { + return schedulerGroupLifecyclePlan{}, fmt.Errorf("untrusted scheduler group lifecycle state: group=%d", groupID) + } + + plan = schedulerGroupLifecyclePlan{active: !missing && group.IsActive()} + if plan.active { + buckets := schedulerBucketsForGroup(groupID) + plan.tasks = make([]schedulerBucketWriteTask, 0, len(buckets)) + for _, bucket := range buckets { + token, err := s.cache.ReopenBucket(lifecycleCtx, bucket) + if err != nil { + return schedulerGroupLifecyclePlan{}, err + } + plan.tasks = append(plan.tasks, schedulerBucketWriteTask{bucket: bucket, token: token}) + } + } else { + registered := knownHistorical + if registered == nil { + registered, err = s.cache.ListBuckets(lifecycleCtx) + if err != nil { + return schedulerGroupLifecyclePlan{}, err + } + } + buckets := schedulerBucketsForGroup(groupID) + for _, bucket := range registered { + if bucket.GroupID == groupID { + buckets = append(buckets, bucket) + } + } + for _, bucket := range dedupeBuckets(buckets) { + if err := s.cache.RetireBucket(lifecycleCtx, bucket); err != nil { + return schedulerGroupLifecyclePlan{}, err + } + } + } + + releaseErr := s.releaseGroupLifecycleLease(lease) + leaseHeld = false + if releaseErr != nil { + return schedulerGroupLifecyclePlan{}, releaseErr + } + return plan, nil +} + +func (s *SchedulerSnapshotService) releaseGroupLifecycleLease(lease SchedulerGroupLifecycleLease) error { + // 请求取消后仍需尝试释放自己的租约,因此使用独立且有界的后台上下文。 + releaseCtx, cancel := context.WithTimeout(context.Background(), schedulerGroupLifecycleReleaseTimeout) + defer cancel() + return s.cache.ReleaseGroupLifecycleLease(releaseCtx, lease) +} + +func markGroupLifecycleSeen(seen map[batchSeenKey]struct{}, groupID int64) { + if seen == nil { + return + } + seen[batchSeenKey{groupID: groupID, lifecycle: true}] = struct{}{} + for _, platform := range schedulerSnapshotPlatforms() { + seen[batchSeenKey{groupID: groupID, platform: platform}] = struct{}{} + } } func (s *SchedulerSnapshotService) rebuildByAccount(ctx context.Context, account *Account, groupIDs []int64, reason string, seen map[batchSeenKey]struct{}) error { @@ -507,19 +714,38 @@ func (s *SchedulerSnapshotService) rebuildByAccount(ctx context.Context, account return nil } - var firstErr error - if err := s.rebuildBucketsForPlatform(ctx, account.Platform, groupIDs, reason, seen); err != nil && firstErr == nil { - firstErr = err - } + buckets := s.bucketsForPlatform(account.Platform, groupIDs, seen) if account.Platform == PlatformAntigravity && account.IsMixedSchedulingEnabled() { - if err := s.rebuildBucketsForPlatform(ctx, PlatformAnthropic, groupIDs, reason, seen); err != nil && firstErr == nil { - firstErr = err - } - if err := s.rebuildBucketsForPlatform(ctx, PlatformGemini, groupIDs, reason, seen); err != nil && firstErr == nil { - firstErr = err + buckets = append(buckets, s.bucketsForPlatform(PlatformAnthropic, groupIDs, seen)...) + buckets = append(buckets, s.bucketsForPlatform(PlatformGemini, groupIDs, seen)...) + } + return s.rebuildBuckets(ctx, buckets, reason) +} + +func schedulerSnapshotPlatforms() [5]string { + return [5]string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok} +} + +// 生命周期辅助函数有意排除 group0;full rebuild 构造 group0 canonical 集时必须显式调用 canonical helper。 +func schedulerBucketsForGroup(groupID int64) []SchedulerBucket { + if groupID <= 0 { + return nil + } + return schedulerCanonicalBuckets(groupID) +} + +func schedulerCanonicalBuckets(groupID int64) []SchedulerBucket { + buckets := make([]SchedulerBucket, 0, 12) + for _, platform := range schedulerSnapshotPlatforms() { + buckets = append(buckets, + SchedulerBucket{GroupID: groupID, Platform: platform, Mode: SchedulerModeSingle}, + SchedulerBucket{GroupID: groupID, Platform: platform, Mode: SchedulerModeForced}, + ) + if platform == PlatformAnthropic || platform == PlatformGemini { + buckets = append(buckets, SchedulerBucket{GroupID: groupID, Platform: platform, Mode: SchedulerModeMixed}) } } - return firstErr + return buckets } func (s *SchedulerSnapshotService) rebuildByGroupIDs(ctx context.Context, groupIDs []int64, reason string, seen map[batchSeenKey]struct{}) error { @@ -527,67 +753,108 @@ func (s *SchedulerSnapshotService) rebuildByGroupIDs(ctx context.Context, groupI if len(groupIDs) == 0 { return nil } - platforms := []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok} - var firstErr error - for _, platform := range platforms { - if err := s.rebuildBucketsForPlatform(ctx, platform, groupIDs, reason, seen); err != nil && firstErr == nil { - firstErr = err - } + buckets := make([]SchedulerBucket, 0, len(groupIDs)*12) + for _, platform := range schedulerSnapshotPlatforms() { + buckets = append(buckets, s.bucketsForPlatform(platform, groupIDs, seen)...) } - return firstErr + return s.rebuildBuckets(ctx, buckets, reason) } -func (s *SchedulerSnapshotService) rebuildBucketsForPlatform(ctx context.Context, platform string, groupIDs []int64, reason string, seen map[batchSeenKey]struct{}) error { +func (s *SchedulerSnapshotService) bucketsForPlatform(platform string, groupIDs []int64, seen map[batchSeenKey]struct{}) []SchedulerBucket { if platform == "" { return nil } - var firstErr error + buckets := make([]SchedulerBucket, 0, len(groupIDs)*3) for _, gid := range groupIDs { // Within a single poll batch, skip (groupID, platform) pairs that were // already rebuilt. The first rebuild loads fresh DB data for all accounts // in the group, so subsequent rebuilds for the same group+platform within // the same batch are redundant. if seen != nil { - key := batchSeenKey{gid, platform} + key := batchSeenKey{groupID: gid, platform: platform} if _, exists := seen[key]; exists { continue } seen[key] = struct{}{} } - if err := s.rebuildBucket(ctx, SchedulerBucket{GroupID: gid, Platform: platform, Mode: SchedulerModeSingle}, reason); err != nil && firstErr == nil { - firstErr = err - } - if err := s.rebuildBucket(ctx, SchedulerBucket{GroupID: gid, Platform: platform, Mode: SchedulerModeForced}, reason); err != nil && firstErr == nil { - firstErr = err - } + buckets = append(buckets, SchedulerBucket{GroupID: gid, Platform: platform, Mode: SchedulerModeSingle}) + buckets = append(buckets, SchedulerBucket{GroupID: gid, Platform: platform, Mode: SchedulerModeForced}) if platform == PlatformAnthropic || platform == PlatformGemini { - if err := s.rebuildBucket(ctx, SchedulerBucket{GroupID: gid, Platform: platform, Mode: SchedulerModeMixed}, reason); err != nil && firstErr == nil { - firstErr = err - } + buckets = append(buckets, SchedulerBucket{GroupID: gid, Platform: platform, Mode: SchedulerModeMixed}) } } - return firstErr + return buckets } func (s *SchedulerSnapshotService) rebuildBuckets(ctx context.Context, buckets []SchedulerBucket, reason string) error { + tasks, firstErr := s.prepareBucketWriteTasks(ctx, buckets) + queries := newSchedulerAccountQueryCache(tasks) + if err := s.rebuildPreparedBucketTasks(ctx, tasks, reason, false, queries); err != nil && firstErr == nil { + firstErr = err + } + return firstErr +} + +func (s *SchedulerSnapshotService) prepareBucketWriteTasks(ctx context.Context, buckets []SchedulerBucket) ([]schedulerBucketWriteTask, error) { + if s.cache == nil { + return nil, ErrSchedulerCacheNotReady + } + tasks := make([]schedulerBucketWriteTask, 0, len(buckets)) var firstErr error for _, bucket := range buckets { - if err := s.rebuildBucket(ctx, bucket, reason); err != nil && firstErr == nil { + token, err := s.cache.CaptureBucketWriteToken(ctx, bucket) + if err != nil { + if errors.Is(err, ErrSchedulerBucketRetired) || errors.Is(err, ErrSchedulerBucketWriteFenced) { + continue + } + if firstErr == nil { + firstErr = err + } + continue + } + tasks = append(tasks, schedulerBucketWriteTask{bucket: bucket, token: token}) + } + return tasks, firstErr +} + +func (s *SchedulerSnapshotService) rebuildPreparedBucketTasks( + ctx context.Context, + tasks []schedulerBucketWriteTask, + reason string, + strict bool, + queries *schedulerAccountQueryCache, +) error { + var firstErr error + for _, task := range tasks { + if err := s.rebuildBucketWithTokenPolicyAndQueryCache(ctx, task, reason, strict, queries); err != nil && firstErr == nil { firstErr = err } } return firstErr } -func (s *SchedulerSnapshotService) rebuildBucket(ctx context.Context, bucket SchedulerBucket, reason string) error { +func (s *SchedulerSnapshotService) rebuildBucketWithTokenPolicyAndQueryCache( + ctx context.Context, + task schedulerBucketWriteTask, + reason string, + strict bool, + queries *schedulerAccountQueryCache, +) error { + if queries != nil { + defer queries.release(task.bucket) + } if s.cache == nil { return ErrSchedulerCacheNotReady } + bucket := task.bucket ok, err := s.cache.TryLockBucket(ctx, bucket, 30*time.Second) if err != nil { return err } if !ok { + if strict { + return fmt.Errorf("%w: bucket=%s", ErrSchedulerBucketRebuildBusy, bucket.String()) + } return nil } defer func() { @@ -597,12 +864,19 @@ func (s *SchedulerSnapshotService) rebuildBucket(ctx context.Context, bucket Sch rebuildCtx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() - accounts, err := s.loadAccountsFromDB(rebuildCtx, bucket, bucket.Mode == SchedulerModeMixed) + accounts, err := s.loadAccountsForRebuild(rebuildCtx, bucket, queries) if err != nil { logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] rebuild failed: bucket=%s reason=%s err=%v", bucket.String(), reason, err) return err } - if err := s.cache.SetSnapshot(rebuildCtx, bucket, accounts); err != nil { + if err := s.cache.SetSnapshot(rebuildCtx, bucket, task.token, accounts); err != nil { + if errors.Is(err, ErrSchedulerBucketRetired) || errors.Is(err, ErrSchedulerBucketWriteFenced) { + slog.Debug("[Scheduler] rebuild fenced", "bucket", bucket.String(), "reason", reason) + if strict { + return err + } + return nil + } logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] rebuild cache failed: bucket=%s reason=%s err=%v", bucket.String(), reason, err) return err } @@ -617,21 +891,220 @@ func (s *SchedulerSnapshotService) triggerFullRebuild(reason string) error { return s.coalesceFullRebuild(func() error { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() + return s.rebuildFullSnapshot(ctx, reason) + }) +} - buckets, err := s.cache.ListBuckets(ctx) +func (s *SchedulerSnapshotService) rebuildFullSnapshot(ctx context.Context, reason string) error { + if s.cache == nil { + return ErrSchedulerCacheNotReady + } + + // 当前模式所需的全局读取必须先成功:桶注册表始终必需,standard 还需活跃分组 ID; + // 失败时不执行 Capture/Retire/Reopen 或 DB 查询。 + // simple 模式不获取分组生命周期权威;standard 的 stale candidate 仍须在租约内 fresh 确认后才能退休。 + registered, err := s.cache.ListBuckets(ctx) + if err != nil { + return err + } + registered = dedupeBuckets(registered) + + if s.isRunModeSimple() { + canonical := schedulerCanonicalBuckets(0) + captured, err := s.captureFullRebuildCanonicalTasks(ctx, canonical) if err != nil { - logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] list buckets failed: %v", err) return err } - if len(buckets) == 0 { - buckets, err = s.defaultBuckets(ctx) - if err != nil { - logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] default buckets failed: %v", err) - return err - } + ordinary := appendBucketsExcept(nil, registered, canonical) + return s.prepareAndRebuildFullSnapshot(ctx, captured, nil, ordinary, reason) + } + + activeGroupIDs, err := s.listActiveSchedulerGroupIDs(ctx) + if err != nil { + return err + } + activeGroups := make(map[int64]struct{}, len(activeGroupIDs)) + for _, groupID := range activeGroupIDs { + activeGroups[groupID] = struct{}{} + } + + registeredByGroup := make(map[int64][]SchedulerBucket) + for _, bucket := range registered { + registeredByGroup[bucket.GroupID] = append(registeredByGroup[bucket.GroupID], bucket) + } + + groupZeroCanonical := schedulerCanonicalBuckets(0) + capturedTasks, err := s.captureFullRebuildCanonicalTasks(ctx, groupZeroCanonical) + if err != nil { + return err + } + ordinaryBuckets := appendBucketsExcept(nil, registeredByGroup[0], groupZeroCanonical) + for groupID, buckets := range registeredByGroup { + if groupID < 0 { + ordinaryBuckets = append(ordinaryBuckets, buckets...) } - return s.rebuildBuckets(ctx, buckets, reason) - }) + } + + reopenedTasks := make([]schedulerBucketWriteTask, 0) + for _, groupID := range activeGroupIDs { + canonical := schedulerBucketsForGroup(groupID) + canonicalTasks, captureErr := s.captureFullRebuildCanonicalTasks(ctx, canonical) + if captureErr == nil { + capturedTasks = append(capturedTasks, canonicalTasks...) + ordinaryBuckets = appendBucketsExcept(ordinaryBuckets, registeredByGroup[groupID], canonical) + continue + } + if !errors.Is(captureErr, ErrSchedulerBucketRetired) && !errors.Is(captureErr, ErrSchedulerBucketWriteFenced) { + return captureErr + } + + // A prior full_rebuild event can observe the active state committed for a + // later group_changed event. Recover here under fresh authority so the + // earlier event cannot block the outbox watermark before that event runs. + knownHistorical := registeredByGroup[groupID] + if knownHistorical == nil { + knownHistorical = []SchedulerBucket{} + } + plan, err := s.prepareGroupLifecycle(ctx, groupID, knownHistorical) + if err != nil { + return err + } + if plan.active { + reopenedTasks = append(reopenedTasks, plan.tasks...) + ordinaryBuckets = appendBucketsExcept(ordinaryBuckets, registeredByGroup[groupID], canonical) + } + } + + staleGroupIDs := make([]int64, 0) + for groupID := range registeredByGroup { + if groupID <= 0 { + continue + } + if _, active := activeGroups[groupID]; !active { + staleGroupIDs = append(staleGroupIDs, groupID) + } + } + sort.Slice(staleGroupIDs, func(i, j int) bool { return staleGroupIDs[i] < staleGroupIDs[j] }) + + for _, groupID := range staleGroupIDs { + plan, err := s.prepareGroupLifecycle(ctx, groupID, registeredByGroup[groupID]) + if err != nil { + return err + } + if plan.active { + reopenedTasks = append(reopenedTasks, plan.tasks...) + ordinaryBuckets = appendBucketsExcept(ordinaryBuckets, registeredByGroup[groupID], schedulerBucketsForGroup(groupID)) + } + } + + return s.prepareAndRebuildFullSnapshot(ctx, capturedTasks, reopenedTasks, ordinaryBuckets, reason) +} + +func (s *SchedulerSnapshotService) listActiveSchedulerGroupIDs(ctx context.Context) ([]int64, error) { + if s.groupRepo == nil { + return nil, ErrSchedulerCacheNotReady + } + + // 轻量接口一旦实现,其错误直接失败;只有仓储不支持该接口时才回退完整 ListActive。 + var groupIDs []int64 + if lister, ok := s.groupRepo.(schedulerActiveGroupIDLister); ok { + ids, err := lister.ListActiveIDs(ctx) + if err != nil { + return nil, err + } + groupIDs = ids + } else { + groups, err := s.groupRepo.ListActive(ctx) + if err != nil { + return nil, err + } + groupIDs = make([]int64, 0, len(groups)) + for _, group := range groups { + groupIDs = append(groupIDs, group.ID) + } + } + + seen := make(map[int64]struct{}, len(groupIDs)) + normalized := make([]int64, 0, len(groupIDs)) + for _, groupID := range groupIDs { + if groupID <= 0 { + continue + } + if _, ok := seen[groupID]; ok { + continue + } + seen[groupID] = struct{}{} + normalized = append(normalized, groupID) + } + sort.Slice(normalized, func(i, j int) bool { return normalized[i] < normalized[j] }) + return normalized, nil +} + +func (s *SchedulerSnapshotService) prepareAndRebuildFullSnapshot( + ctx context.Context, + captured []schedulerBucketWriteTask, + reopened []schedulerBucketWriteTask, + ordinaryBuckets []SchedulerBucket, + reason string, +) error { + // 首个 DB 查询前必须完成全部普通 bucket 的 token 预备;任何预备错误都不会留下部分发布。 + // fresh Reopen task 保持严格锁与 fencing 语义,普通 captured task 继续沿用 lock busy/fence 跳过语义。 + preparedBuckets := make(map[SchedulerBucket]struct{}, len(captured)+len(reopened)) + for _, task := range captured { + preparedBuckets[task.bucket] = struct{}{} + } + for _, task := range reopened { + preparedBuckets[task.bucket] = struct{}{} + } + + ordinaryBuckets = dedupeBuckets(ordinaryBuckets) + toCapture := make([]SchedulerBucket, 0, len(ordinaryBuckets)) + for _, bucket := range ordinaryBuckets { + if _, ok := preparedBuckets[bucket]; !ok { + toCapture = append(toCapture, bucket) + } + } + ordinary, firstErr := s.prepareBucketWriteTasks(ctx, toCapture) + if firstErr != nil { + return firstErr + } + captured = append(captured, ordinary...) + queries := newSchedulerAccountQueryCache(reopened, captured) + if err := s.rebuildPreparedBucketTasks(ctx, reopened, reason, true, queries); err != nil { + firstErr = err + } + if err := s.rebuildPreparedBucketTasks(ctx, captured, reason, false, queries); err != nil && firstErr == nil { + firstErr = err + } + return firstErr +} + +func (s *SchedulerSnapshotService) captureFullRebuildCanonicalTasks(ctx context.Context, buckets []SchedulerBucket) ([]schedulerBucketWriteTask, error) { + if s.cache == nil { + return nil, ErrSchedulerCacheNotReady + } + tasks := make([]schedulerBucketWriteTask, 0, len(buckets)) + for _, bucket := range buckets { + token, err := s.cache.CaptureBucketWriteToken(ctx, bucket) + if err != nil { + return nil, err + } + tasks = append(tasks, schedulerBucketWriteTask{bucket: bucket, token: token}) + } + return tasks, nil +} + +func appendBucketsExcept(dst, buckets, excluded []SchedulerBucket) []SchedulerBucket { + excludedKeys := make(map[SchedulerBucket]struct{}, len(excluded)) + for _, bucket := range excluded { + excludedKeys[bucket] = struct{}{} + } + for _, bucket := range buckets { + if _, ok := excludedKeys[bucket]; !ok { + dst = append(dst, bucket) + } + } + return dst } func (s *SchedulerSnapshotService) coalesceFullRebuild(run func() error) error { @@ -667,58 +1140,184 @@ func (s *SchedulerSnapshotService) checkOutboxLag(ctx context.Context, watermark if s.cfg == nil || s.outboxRepo == nil { return } + now := time.Now() oldestCreatedAt, ok, err := s.outboxRepo.FirstCreatedAtAfter(ctx, watermark) if err != nil { logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] outbox pending event read failed: %v", err) return } - if !ok || oldestCreatedAt.IsZero() { - s.lagMu.Lock() + var lag time.Duration + if ok && !oldestCreatedAt.IsZero() { + lag = now.Sub(oldestCreatedAt) + } + lagSeconds := int(lag.Seconds()) + lagWarning := ok && !oldestCreatedAt.IsZero() && + s.cfg.Gateway.Scheduling.OutboxLagWarnSeconds > 0 && + lagSeconds >= s.cfg.Gateway.Scheduling.OutboxLagWarnSeconds + + lagDegraded := ok && !oldestCreatedAt.IsZero() && + s.cfg.Gateway.Scheduling.OutboxLagRebuildSeconds > 0 && + lagSeconds >= s.cfg.Gateway.Scheduling.OutboxLagRebuildSeconds + + backlogThreshold := s.cfg.Gateway.Scheduling.OutboxBacklogRebuildRows + backlogKnown := true + var backlog int64 + if backlogThreshold > 0 { + maxID, maxErr := s.outboxRepo.MaxID(ctx) + if maxErr != nil { + backlogKnown = false + if s.shouldLogOutboxMaxIDError(now) { + logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] outbox max id read failed: %v", maxErr) + } + } else { + backlog = maxID - watermark + } + } + backlogDegraded := backlogKnown && backlogThreshold > 0 && backlog >= int64(backlogThreshold) + + // A successful rebuild latches the degraded episode until recovery. A failed + // rebuild remains retryable, but only after an exponentially backed-off + // cooldown so a one-second poll cannot create a rebuild storm. + logLagWarning := s.shouldLogOutboxLagWarning(lagWarning) + s.lagMu.Lock() + fullyRecovered := !lagDegraded && backlogKnown && !backlogDegraded + if fullyRecovered { s.lagFailures = 0 - s.lagMu.Unlock() - return + s.outboxRebuildLatched = false + s.outboxRebuildFailures = 0 + s.outboxRebuildRetryAt = time.Time{} + s.outboxRebuildRetryReason = "" } - lag := time.Since(oldestCreatedAt) - if lagSeconds := int(lag.Seconds()); lagSeconds >= s.cfg.Gateway.Scheduling.OutboxLagWarnSeconds && s.cfg.Gateway.Scheduling.OutboxLagWarnSeconds > 0 { + if s.outboxRebuildRetryReason != "" { + retryReasonActive := (s.outboxRebuildRetryReason == "outbox_lag" && lagDegraded) || + (s.outboxRebuildRetryReason == "outbox_backlog" && (!backlogKnown || backlogDegraded)) + if !retryReasonActive { + s.outboxRebuildFailures = 0 + s.outboxRebuildRetryAt = time.Time{} + s.outboxRebuildRetryReason = "" + } + } + + lagRetryPending := s.outboxRebuildRetryReason == "outbox_lag" && !s.outboxRebuildRetryAt.IsZero() + if lagDegraded { + if !s.outboxRebuildLatched && !s.outboxRebuildRunning && !lagRetryPending { + s.lagFailures++ + } + } else { + s.lagFailures = 0 + } + failures := s.lagFailures + lagReady := lagDegraded && failures >= s.cfg.Gateway.Scheduling.OutboxLagRebuildFailures + retryDue := s.outboxRebuildRetryReason != "" && + !s.outboxRebuildRetryAt.IsZero() && !now.Before(s.outboxRebuildRetryAt) + + reason := "" + lagCanPreemptRetry := lagReady && s.outboxRebuildRetryReason != "outbox_lag" + if !s.outboxRebuildLatched && !s.outboxRebuildRunning && + (s.outboxRebuildRetryAt.IsZero() || retryDue || lagCanPreemptRetry) { + switch { + case lagReady || (retryDue && s.outboxRebuildRetryReason == "outbox_lag" && lagDegraded): + if s.outboxRebuildRetryReason != "" && s.outboxRebuildRetryReason != "outbox_lag" { + s.outboxRebuildFailures = 0 + s.outboxRebuildRetryAt = time.Time{} + s.outboxRebuildRetryReason = "" + } + reason = "outbox_lag" + s.lagFailures = 0 + case backlogDegraded && (s.outboxRebuildRetryReason == "" || + (retryDue && s.outboxRebuildRetryReason == "outbox_backlog")): + reason = "outbox_backlog" + } + if reason != "" { + s.outboxRebuildRunning = true + } + } + s.lagMu.Unlock() + + if logLagWarning { logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] outbox lag warning: %ds", lagSeconds) } - if s.cfg.Gateway.Scheduling.OutboxLagRebuildSeconds > 0 && int(lag.Seconds()) >= s.cfg.Gateway.Scheduling.OutboxLagRebuildSeconds { - s.lagMu.Lock() - s.lagFailures++ - failures := s.lagFailures - s.lagMu.Unlock() + if reason == "" { + return + } - if failures >= s.cfg.Gateway.Scheduling.OutboxLagRebuildFailures { - logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] outbox lag rebuild triggered: lag=%s failures=%d", lag, failures) - s.lagMu.Lock() - s.lagFailures = 0 - s.lagMu.Unlock() - if err := s.triggerFullRebuild("outbox_lag"); err != nil { - logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] outbox lag rebuild failed: %v", err) - } - } + var rebuildErr error + switch reason { + case "outbox_lag": + logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] outbox lag rebuild triggered: lag=%s failures=%d", lag, failures) + rebuildErr = s.triggerFullRebuild(reason) + case "outbox_backlog": + logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] outbox backlog rebuild triggered: backlog=%d", backlog) + rebuildErr = s.triggerFullRebuild(reason) + } + + s.lagMu.Lock() + s.outboxRebuildRunning = false + if rebuildErr == nil { + s.outboxRebuildLatched = true + s.outboxRebuildFailures = 0 + s.outboxRebuildRetryAt = time.Time{} + s.outboxRebuildRetryReason = "" } else { - s.lagMu.Lock() - s.lagFailures = 0 - s.lagMu.Unlock() + s.outboxRebuildLatched = false + s.outboxRebuildFailures++ + s.outboxRebuildRetryAt = time.Now().Add(outboxRebuildRetryDelay(s.outboxRebuildFailures)) + s.outboxRebuildRetryReason = reason } + s.lagMu.Unlock() - threshold := s.cfg.Gateway.Scheduling.OutboxBacklogRebuildRows - if threshold <= 0 { - return + if rebuildErr != nil { + logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] %s rebuild failed: %v", reason, rebuildErr) } - maxID, err := s.outboxRepo.MaxID(ctx) - if err != nil { - return - } - if maxID-watermark >= int64(threshold) { - logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] outbox backlog rebuild triggered: backlog=%d", maxID-watermark) - if err := s.triggerFullRebuild("outbox_backlog"); err != nil { - logger.LegacyPrintf("service.scheduler_snapshot", "[Scheduler] outbox backlog rebuild failed: %v", err) +} + +func outboxRebuildRetryDelay(failures int) time.Duration { + delay := outboxRebuildRetryBaseDelay + for i := 1; i < failures && delay < outboxRebuildRetryMaxDelay; i++ { + delay *= 2 + if delay >= outboxRebuildRetryMaxDelay { + return outboxRebuildRetryMaxDelay } } + return delay +} + +func (s *SchedulerSnapshotService) clearOutboxDegradedEpisode() { + if s == nil { + return + } + s.lagMu.Lock() + if s.lagFailures != 0 || s.outboxRebuildLatched || s.outboxRebuildRunning || + s.outboxRebuildFailures != 0 || !s.outboxRebuildRetryAt.IsZero() || + s.outboxRebuildRetryReason != "" || s.outboxLagWarningActive { + s.lagFailures = 0 + s.outboxRebuildLatched = false + s.outboxRebuildFailures = 0 + s.outboxRebuildRetryAt = time.Time{} + s.outboxRebuildRetryReason = "" + s.outboxLagWarningActive = false + } + s.lagMu.Unlock() +} + +func (s *SchedulerSnapshotService) shouldLogOutboxMaxIDError(now time.Time) bool { + s.lagMu.Lock() + defer s.lagMu.Unlock() + if !s.outboxMaxIDErrorLastLoggedAt.IsZero() && now.Sub(s.outboxMaxIDErrorLastLoggedAt) < outboxMaxIDErrorLogSampleInterval { + return false + } + s.outboxMaxIDErrorLastLoggedAt = now + return true +} + +func (s *SchedulerSnapshotService) shouldLogOutboxLagWarning(active bool) bool { + s.lagMu.Lock() + defer s.lagMu.Unlock() + shouldLog := active && !s.outboxLagWarningActive + s.outboxLagWarningActive = active + return shouldLog } func (s *SchedulerSnapshotService) loadAccountsFromDB(ctx context.Context, bucket SchedulerBucket, useMixed bool) ([]Account, error) { @@ -763,6 +1362,30 @@ func (s *SchedulerSnapshotService) loadAccountsFromDB(ctx context.Context, bucke return s.accountRepo.ListSchedulableUngroupedByPlatform(ctx, bucket.Platform) } +func (s *SchedulerSnapshotService) loadAccountsForRebuild( + ctx context.Context, + bucket SchedulerBucket, + queries *schedulerAccountQueryCache, +) ([]Account, error) { + key, cacheable := schedulerAccountQueryKeyForBucket(bucket) + if queries == nil || !cacheable { + return s.loadAccountsFromDB(ctx, bucket, bucket.Mode == SchedulerModeMixed) + } + + if accounts, ok := queries.accounts[key]; ok { + return accounts, nil + } + if queries.remaining[key] <= 1 { + return s.loadAccountsFromDB(ctx, bucket, false) + } + accounts, err := s.loadAccountsFromDB(ctx, bucket, false) + if err != nil { + return nil, err + } + queries.accounts[key] = accounts + return accounts, nil +} + func (s *SchedulerSnapshotService) bucketFor(groupID *int64, platform string, mode string) SchedulerBucket { return SchedulerBucket{ GroupID: s.normalizeGroupID(groupID), @@ -869,38 +1492,6 @@ func (s *SchedulerSnapshotService) fullRebuildInterval() time.Duration { return time.Duration(sec) * time.Second } -func (s *SchedulerSnapshotService) defaultBuckets(ctx context.Context) ([]SchedulerBucket, error) { - buckets := make([]SchedulerBucket, 0) - platforms := []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok} - for _, platform := range platforms { - buckets = append(buckets, SchedulerBucket{GroupID: 0, Platform: platform, Mode: SchedulerModeSingle}) - buckets = append(buckets, SchedulerBucket{GroupID: 0, Platform: platform, Mode: SchedulerModeForced}) - if platform == PlatformAnthropic || platform == PlatformGemini { - buckets = append(buckets, SchedulerBucket{GroupID: 0, Platform: platform, Mode: SchedulerModeMixed}) - } - } - - if s.isRunModeSimple() || s.groupRepo == nil { - return dedupeBuckets(buckets), nil - } - - groups, err := s.groupRepo.ListActive(ctx) - if err != nil { - return dedupeBuckets(buckets), nil - } - for _, group := range groups { - if group.Platform == "" { - continue - } - buckets = append(buckets, SchedulerBucket{GroupID: group.ID, Platform: group.Platform, Mode: SchedulerModeSingle}) - buckets = append(buckets, SchedulerBucket{GroupID: group.ID, Platform: group.Platform, Mode: SchedulerModeForced}) - if group.Platform == PlatformAnthropic || group.Platform == PlatformGemini { - buckets = append(buckets, SchedulerBucket{GroupID: group.ID, Platform: group.Platform, Mode: SchedulerModeMixed}) - } - } - return dedupeBuckets(buckets), nil -} - func dedupeBuckets(in []SchedulerBucket) []SchedulerBucket { seen := make(map[string]struct{}, len(in)) out := make([]SchedulerBucket, 0, len(in)) diff --git a/backend/internal/service/token_refresh_pool_health_test.go b/backend/internal/service/token_refresh_pool_health_test.go new file mode 100644 index 0000000000..f4950d879f --- /dev/null +++ b/backend/internal/service/token_refresh_pool_health_test.go @@ -0,0 +1,949 @@ +package service + +import ( + "context" + "errors" + "fmt" + "reflect" + "sort" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +type poolHealthAccountRepo struct { + AccountRepository + + mu sync.Mutex + pages map[int64][]Account + requests []OAuthRefreshPageOptions + updatedCredentialIDs []int64 + setErrorCalls int + setTempUnschedCalls int + getByIDErr error +} + +func (r *poolHealthAccountRepo) GetByID(_ context.Context, _ int64) (*Account, error) { + if r.getByIDErr != nil { + return nil, r.getByIDErr + } + return nil, ErrAccountNotFound +} + +func (r *poolHealthAccountRepo) ListOAuthRefreshCandidatePage(_ context.Context, options OAuthRefreshPageOptions) (*OAuthRefreshCandidatePage, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.requests = append(r.requests, options) + accounts := append([]Account(nil), r.pages[options.AfterID]...) + page := &OAuthRefreshCandidatePage{Accounts: accounts, HasMore: len(accounts) == options.Limit} + if len(accounts) > 0 { + page.NextAfterID = accounts[len(accounts)-1].ID + } + return page, nil +} + +func (r *poolHealthAccountRepo) UpdateCredentials(_ context.Context, id int64, _ map[string]any) error { + r.mu.Lock() + defer r.mu.Unlock() + r.updatedCredentialIDs = append(r.updatedCredentialIDs, id) + return nil +} + +func (r *poolHealthAccountRepo) UpdateGrokOAuthCredentialsIfUnchanged( + _ context.Context, + id int64, + _ map[string]any, + _ *int64, + _ map[string]any, +) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.updatedCredentialIDs = append(r.updatedCredentialIDs, id) + return true, nil +} + +func (r *poolHealthAccountRepo) SetError(context.Context, int64, string) error { + r.mu.Lock() + defer r.mu.Unlock() + r.setErrorCalls++ + return nil +} + +func (r *poolHealthAccountRepo) SetGrokOAuthErrorIfCredentialsUnchanged(context.Context, int64, map[string]any, string) (bool, error) { + return false, nil +} + +func (r *poolHealthAccountRepo) SetGrokOAuthRefreshErrorIfCredentialsUnchanged(context.Context, int64, map[string]any, *int64, string) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.setErrorCalls++ + return true, nil +} + +func (r *poolHealthAccountRepo) SetGrokOAuthRefreshTempUnschedulableIfCredentialsUnchanged(context.Context, int64, map[string]any, *int64, time.Time, string) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.setTempUnschedCalls++ + return true, nil +} + +func (r *poolHealthAccountRepo) SetTempUnschedulable(context.Context, int64, time.Time, string) error { + r.mu.Lock() + defer r.mu.Unlock() + r.setTempUnschedCalls++ + return nil +} + +func (r *poolHealthAccountRepo) snapshot() ([]OAuthRefreshPageOptions, []int64, int, int) { + r.mu.Lock() + defer r.mu.Unlock() + return append([]OAuthRefreshPageOptions(nil), r.requests...), append([]int64(nil), r.updatedCredentialIDs...), r.setErrorCalls, r.setTempUnschedCalls +} + +type poolHealthRefresher struct { + err error + delay time.Duration + startDelays []time.Duration + ignoreContext bool + cancel context.CancelFunc + newCredentials map[string]any + calls atomic.Int64 + active atomic.Int64 + maxActive atomic.Int64 + startMu sync.Mutex + startTimes []time.Time +} + +type countingRefreshAttemptGate struct { + calls atomic.Int64 +} + +type rejectedRefreshAttemptGate struct { + err error +} + +type poolHealthTokenCacheStub struct { + GeminiTokenCache +} + +type tripBeforeRateAdmissionGate struct { + state *tokenRefreshProviderState +} + +func (g *tripBeforeRateAdmissionGate) acquire(ctx context.Context) (func(), error) { + release, err := g.state.acquire(ctx) + if err != nil { + return nil, err + } + g.state.mu.Lock() + g.state.tripped = true + g.state.mu.Unlock() + return release, nil +} + +func (g *tripBeforeRateAdmissionGate) acquireRate(ctx context.Context) (func(), error) { + return g.state.acquireRate(ctx) +} + +type breakerTripAccountRepo struct { + *productionPathRateRepo + setErrorCalls atomic.Int64 + setTempCalls atomic.Int64 +} + +func (r *breakerTripAccountRepo) SetGrokOAuthRefreshErrorIfCredentialsUnchanged(context.Context, int64, map[string]any, *int64, string) (bool, error) { + r.setErrorCalls.Add(1) + return true, nil +} + +func (r *breakerTripAccountRepo) SetGrokOAuthRefreshTempUnschedulableIfCredentialsUnchanged(context.Context, int64, map[string]any, *int64, time.Time, string) (bool, error) { + r.setTempCalls.Add(1) + return true, nil +} + +func (g *rejectedRefreshAttemptGate) acquire(context.Context) (func(), error) { + return nil, g.err +} + +type productionPathRateRepo struct { + AccountRepository + + mu sync.Mutex + accounts map[int64]*Account +} + +func (r *productionPathRateRepo) GetByID(_ context.Context, id int64) (*Account, error) { + r.mu.Lock() + defer r.mu.Unlock() + account := r.accounts[id] + if account == nil { + return nil, ErrAccountNotFound + } + return snapshotOAuthRefreshAccount(account), nil +} + +func (r *productionPathRateRepo) UpdateCredentials(_ context.Context, id int64, credentials map[string]any) error { + r.mu.Lock() + defer r.mu.Unlock() + account := r.accounts[id] + if account == nil { + return ErrAccountNotFound + } + account.Credentials = shallowCopyMap(credentials) + return nil +} + +func (r *productionPathRateRepo) UpdateGrokOAuthCredentialsIfUnchanged( + _ context.Context, + id int64, + expectedCredentials map[string]any, + expectedProxyID *int64, + credentials map[string]any, +) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + account := r.accounts[id] + if account == nil || !reflect.DeepEqual(account.Credentials, expectedCredentials) || + !reflect.DeepEqual(account.ProxyID, expectedProxyID) { + return false, nil + } + account.Credentials = shallowCopyMap(credentials) + return true, nil +} + +type productionPathRefreshStart struct { + accountID int64 + at time.Time +} + +type productionPathRateExecutor struct { + firstStarted chan struct{} + releaseFirst chan struct{} + calls atomic.Int64 + startMu sync.Mutex + starts []productionPathRefreshStart +} + +func (e *productionPathRateExecutor) CacheKey(account *Account) string { + return fmt.Sprintf("production-path-rate:%d", account.ID) +} + +func (e *productionPathRateExecutor) CanRefresh(account *Account) bool { + return account != nil && account.IsGrokOAuth() +} + +func (e *productionPathRateExecutor) NeedsRefresh(account *Account, _ time.Duration) bool { + needsRefresh, _ := account.Credentials["needs_refresh"].(bool) + return needsRefresh +} + +func (e *productionPathRateExecutor) Refresh(ctx context.Context, account *Account) (map[string]any, error) { + call := e.calls.Add(1) + e.startMu.Lock() + e.starts = append(e.starts, productionPathRefreshStart{accountID: account.ID, at: time.Now()}) + e.startMu.Unlock() + if call == 1 { + close(e.firstStarted) + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-e.releaseFirst: + } + } + return map[string]any{ + "access_token": fmt.Sprintf("fresh-access-%d", account.ID), + "refresh_token": fmt.Sprintf("fresh-refresh-%d", account.ID), + "needs_refresh": false, + }, nil +} + +func (e *productionPathRateExecutor) startsSnapshot() []productionPathRefreshStart { + e.startMu.Lock() + defer e.startMu.Unlock() + return append([]productionPathRefreshStart(nil), e.starts...) +} + +func (g *countingRefreshAttemptGate) acquire(ctx context.Context) (func(), error) { + if err := ctx.Err(); err != nil { + return nil, err + } + g.calls.Add(1) + return func() {}, nil +} + +func (r *poolHealthRefresher) CacheKey(account *Account) string { + return fmt.Sprintf("pool-health:%d", account.ID) +} + +func (r *poolHealthRefresher) CanRefresh(account *Account) bool { + return account != nil && account.Platform == PlatformGrok && account.Type == AccountTypeOAuth +} + +func (r *poolHealthRefresher) NeedsRefresh(*Account, time.Duration) bool { return true } + +func (r *poolHealthRefresher) Refresh(ctx context.Context, _ *Account) (map[string]any, error) { + r.calls.Add(1) + active := r.active.Add(1) + defer r.active.Add(-1) + r.startMu.Lock() + startIndex := len(r.startTimes) + r.startTimes = append(r.startTimes, time.Now()) + delay := r.delay + if startIndex < len(r.startDelays) { + delay = r.startDelays[startIndex] + } + r.startMu.Unlock() + for { + maxActive := r.maxActive.Load() + if active <= maxActive || r.maxActive.CompareAndSwap(maxActive, active) { + break + } + } + if r.cancel != nil { + r.cancel() + } + if delay > 0 { + if r.ignoreContext { + time.Sleep(delay) + } else { + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-timer.C: + } + } + } + if r.err != nil { + return nil, r.err + } + if r.newCredentials != nil { + credentials := make(map[string]any, len(r.newCredentials)) + for key, value := range r.newCredentials { + credentials[key] = value + } + return credentials, nil + } + return map[string]any{"access_token": "new-token", "refresh_token": "new-refresh-token"}, nil +} + +func (r *poolHealthRefresher) startsSnapshot() []time.Time { + r.startMu.Lock() + defer r.startMu.Unlock() + return append([]time.Time(nil), r.startTimes...) +} + +func grokPoolAccount(id int64) Account { + return Account{ + ID: id, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Credentials: map[string]any{ + "access_token": "old-token", + "refresh_token": "refresh-token", + }, + } +} + +func newPoolHealthService(repo *poolHealthAccountRepo, refresher *poolHealthRefresher, cfg config.TokenRefreshConfig) *TokenRefreshService { + return &TokenRefreshService{ + accountRepo: repo, + candidatePager: repo, + registrations: []tokenRefreshRegistration{{ + platform: PlatformGrok, + refresher: refresher, + executor: refresher, + }}, + refreshPolicy: DefaultBackgroundRefreshPolicy(), + cfg: &cfg, + } +} + +func TestTokenRefreshService_RegistrationsAreCandidateEligibilitySource(t *testing.T) { + cfg := &config.Config{} + svc := NewTokenRefreshService(nil, nil, nil, nil, nil, nil, nil, cfg, nil) + + require.Equal(t, []string{ + PlatformAnthropic, + PlatformOpenAI, + PlatformGemini, + PlatformAntigravity, + PlatformGrok, + }, svc.eligiblePlatforms()) + require.Len(t, svc.registrations, 5) + for _, registration := range svc.registrations { + require.NotNil(t, registration.refresher) + require.NotNil(t, registration.executor) + } +} + +func TestTokenRefreshService_ProcessRefreshPagesByStableCursor(t *testing.T) { + repo := &poolHealthAccountRepo{pages: map[int64][]Account{ + 0: {grokPoolAccount(1), grokPoolAccount(2)}, + 2: {grokPoolAccount(3)}, + }} + refresher := &poolHealthRefresher{} + svc := newPoolHealthService(repo, refresher, config.TokenRefreshConfig{ + RefreshBeforeExpiryHours: 1, + MaxRetries: 1, + CandidatePageSize: 2, + ProviderConcurrency: 4, + ProviderQPS: 10000, + AttemptTimeoutSeconds: 1, + CycleTimeoutSeconds: 2, + }) + + svc.processRefreshContext(context.Background()) + + requests, updatedIDs, _, _ := repo.snapshot() + require.Len(t, requests, 2) + require.Equal(t, int64(0), requests[0].AfterID) + require.Equal(t, int64(2), requests[1].AfterID) + require.Equal(t, []string{PlatformGrok}, requests[0].Platforms) + require.True(t, requests[0].ActiveOnly) + require.True(t, requests[0].RequireRefreshToken) + require.True(t, requests[0].ExcludeRetryCooldown) + sort.Slice(updatedIDs, func(i, j int) bool { return updatedIDs[i] < updatedIDs[j] }) + require.Equal(t, []int64{1, 2, 3}, updatedIDs) + require.Zero(t, svc.candidateAfterID(), "a short final page must wrap the next cycle to the beginning") +} + +func TestTokenRefreshService_BoundsPerProviderConcurrency(t *testing.T) { + accounts := make([]Account, 0, 8) + for id := int64(1); id <= 8; id++ { + accounts = append(accounts, grokPoolAccount(id)) + } + repo := &poolHealthAccountRepo{pages: map[int64][]Account{0: accounts}} + refresher := &poolHealthRefresher{delay: 20 * time.Millisecond} + svc := newPoolHealthService(repo, refresher, config.TokenRefreshConfig{ + MaxRetries: 1, + CandidatePageSize: 20, + ProviderConcurrency: 2, + ProviderQPS: 10000, + AttemptTimeoutSeconds: 1, + CycleTimeoutSeconds: 2, + }) + + svc.processRefreshContext(context.Background()) + + require.Equal(t, int64(8), refresher.calls.Load()) + require.Equal(t, int64(2), refresher.maxActive.Load()) +} + +func TestTokenRefreshRateGate_ReservesSpacedSlotsAndHonorsCancellation(t *testing.T) { + const interval = 25 * time.Millisecond + gate := newTokenRefreshRateGateWithInterval(interval) + base := time.Unix(1_700_000_000, 0) + + require.Equal(t, base, gate.reserveSlot(base)) + require.Equal(t, base.Add(interval), gate.reserveSlot(base)) + require.Equal(t, base.Add(2*interval), gate.reserveSlot(base)) + jumped := base.Add(time.Second) + require.Equal(t, jumped, gate.reserveSlot(jumped), "an idle gate should not retain stale delay") + + cancelGate := newTokenRefreshRateGateWithInterval(time.Hour) + require.NoError(t, cancelGate.wait(context.Background()), "the first slot is immediately available") + ctx, cancel := context.WithCancel(context.Background()) + cancel() + started := time.Now() + require.ErrorIs(t, cancelGate.wait(ctx), context.Canceled) + require.Less(t, time.Since(started), 100*time.Millisecond, "cancellation must not wait for the reserved slot") +} + +func TestTokenRefreshService_RetriesAcquireRateSlotPerAttempt(t *testing.T) { + repo := &poolHealthAccountRepo{} + refresher := &poolHealthRefresher{err: errors.New("temporary provider failure")} + svc := newPoolHealthService(repo, refresher, config.TokenRefreshConfig{MaxRetries: 3}) + gate := &countingRefreshAttemptGate{} + account := grokPoolAccount(44) + + err := svc.refreshWithRetryWithRateGate(context.Background(), &account, refresher, nil, time.Hour, gate) + + require.Error(t, err) + require.Equal(t, int64(3), refresher.calls.Load()) + require.Equal(t, int64(3), gate.calls.Load(), "every upstream retry must consume a provider rate slot") +} + +func TestTokenRefreshService_ProcessProviderAccountsLegacyNilReleaseGateIsSafe(t *testing.T) { + repo := &poolHealthAccountRepo{} + refresher := &poolHealthRefresher{} + svc := newPoolHealthService(repo, refresher, config.TokenRefreshConfig{ + MaxRetries: 1, + ProviderConcurrency: 1, + }) + state := &tokenRefreshProviderState{ + service: svc, + registration: tokenRefreshRegistration{ + platform: PlatformGrok, + refresher: refresher, + // nil executor deliberately exercises the legacy/direct fallback. + executor: nil, + }, + // Admission rejection validly returns no release callback. The direct + // fallback must propagate the skip without dereferencing that nil handle. + rateGate: &rejectedRefreshAttemptGate{err: errRefreshSkipped}, + poolGate: nil, + } + account := grokPoolAccount(45) + + refreshed, skipped, failed := svc.processProviderAccounts( + context.Background(), + state, + []*Account{&account}, + time.Hour, + ) + + require.Zero(t, refreshed) + require.Equal(t, 1, skipped) + require.Zero(t, failed) + require.Zero(t, refresher.calls.Load(), "rejected rate admission must not reach the legacy upstream refresher") +} + +func TestTokenRefreshService_ProviderRateGateIsSharedAcrossRuns(t *testing.T) { + svc := &TokenRefreshService{cfg: &config.TokenRefreshConfig{ProviderQPS: 40}} + first := svc.providerRateGate(PlatformGrok) + second := svc.providerRateGate(PlatformGrok) + require.Same(t, first, second, "background cycles and reconciliation must share the process-local provider limiter") + + base := time.Unix(1_700_000_000, 0) + require.Equal(t, base, first.reserveSlot(base)) + require.Equal(t, base.Add(25*time.Millisecond), second.reserveSlot(base)) +} + +func TestTokenRefreshService_ProviderConcurrencyGateIsSharedAcrossBackgroundAndConcurrentAdminReconciliation(t *testing.T) { + accounts := []Account{ + grokPoolAccount(1), + grokPoolAccount(2), + grokPoolAccount(3), + grokPoolAccount(4), + } + repo := &poolHealthAccountRepo{pages: map[int64][]Account{0: accounts}} + refresher := &poolHealthRefresher{delay: 80 * time.Millisecond} + svc := newPoolHealthService(repo, refresher, config.TokenRefreshConfig{ + RefreshBeforeExpiryHours: 1, + MaxRetries: 1, + CandidatePageSize: 20, + ProviderConcurrency: 2, + ProviderQPS: 100, + ProviderFailureThreshold: 20, + AttemptTimeoutSeconds: 1, + CycleTimeoutSeconds: 3, + }) + + firstGate := svc.providerConcurrencyGate(PlatformGrok) + require.Same(t, firstGate, svc.providerConcurrencyGate(PlatformGrok)) + + start := make(chan struct{}) + adminErrors := make(chan error, 2) + var wg sync.WaitGroup + wg.Add(3) + go func() { + defer wg.Done() + <-start + svc.processRefreshContext(context.Background()) + }() + for i := 0; i < 2; i++ { + go func() { + defer wg.Done() + <-start + _, err := svc.ReconcileGrokOAuth(context.Background(), GrokOAuthReconcileInput{Apply: true, Limit: 20}) + adminErrors <- err + }() + } + close(start) + wg.Wait() + close(adminErrors) + + for err := range adminErrors { + require.NoError(t, err) + } + require.Equal(t, int64(12), refresher.calls.Load(), "background and both admin calls must all execute") + require.Equal(t, int64(2), refresher.maxActive.Load(), + "all entry points must share the configured per-provider upstream concurrency cap") +} + +func TestTokenRefreshService_SaturatedProviderPreservesConcurrencyAndActualQPSStartSpacing(t *testing.T) { + const ( + providerConcurrency = 2 + providerQPS = 20 + attemptCount = 8 + ) + repo := &poolHealthAccountRepo{} + refresher := &poolHealthRefresher{ + // The first two QPS-spaced attempts finish together. If queued callers + // reserve QPS slots before acquiring provider capacity, two expired + // reservations can then burst upstream at the same time. + startDelays: []time.Duration{ + 220 * time.Millisecond, + 170 * time.Millisecond, + 20 * time.Millisecond, + 20 * time.Millisecond, + 20 * time.Millisecond, + 20 * time.Millisecond, + 20 * time.Millisecond, + 20 * time.Millisecond, + }, + } + svc := newPoolHealthService(repo, refresher, config.TokenRefreshConfig{ + MaxRetries: 1, + ProviderConcurrency: providerConcurrency, + ProviderQPS: providerQPS, + AttemptTimeoutSeconds: 1, + }) + registration := svc.registrations[0] + sharedRateGate := svc.providerRateGate(PlatformGrok) + sharedPoolGate := svc.providerConcurrencyGate(PlatformGrok) + + start := make(chan struct{}) + errorsCh := make(chan error, attemptCount) + var wg sync.WaitGroup + for i := 0; i < attemptCount; i++ { + account := grokPoolAccount(int64(i + 1)) + state := &tokenRefreshProviderState{ + service: svc, + registration: registration, + rateGate: sharedRateGate, + poolGate: sharedPoolGate, + } + wg.Add(1) + go func() { + defer wg.Done() + <-start + errorsCh <- svc.refreshWithRetryWithRateGate(context.Background(), &account, refresher, nil, time.Hour, state) + }() + } + close(start) + wg.Wait() + close(errorsCh) + + for err := range errorsCh { + require.NoError(t, err) + } + require.Equal(t, int64(providerConcurrency), refresher.maxActive.Load(), + "the scripted attempts must actually saturate the provider semaphore") + starts := refresher.startsSnapshot() + require.Len(t, starts, attemptCount) + configuredSpacing := time.Second / time.Duration(providerQPS) + minimumObservedSpacing := configuredSpacing - 10*time.Millisecond + actualMinimumSpacing := starts[1].Sub(starts[0]) + for i := 1; i < len(starts); i++ { + spacing := starts[i].Sub(starts[i-1]) + if spacing < actualMinimumSpacing { + actualMinimumSpacing = spacing + } + require.GreaterOrEqualf(t, spacing, minimumObservedSpacing, + "upstream starts %d and %d violated configured QPS spacing", i-1, i) + } + t.Logf("max_active=%d configured_concurrency=%d minimum_start_spacing=%s configured_spacing=%s", + refresher.maxActive.Load(), providerConcurrency, actualMinimumSpacing, configuredSpacing) +} + +func TestTokenRefreshService_ProductionPathRatesOnlyActualRefreshAfterSameAccountContention(t *testing.T) { + const interval = 200 * time.Millisecond + accountOne := grokPoolAccount(71) + accountOne.Credentials["needs_refresh"] = true + accountTwo := grokPoolAccount(72) + accountTwo.Credentials["needs_refresh"] = true + firstSelection := snapshotOAuthRefreshAccount(&accountOne) + contendingSelection := snapshotOAuthRefreshAccount(&accountOne) + differentSelection := snapshotOAuthRefreshAccount(&accountTwo) + repo := &productionPathRateRepo{accounts: map[int64]*Account{ + accountOne.ID: snapshotOAuthRefreshAccount(&accountOne), + accountTwo.ID: snapshotOAuthRefreshAccount(&accountTwo), + }} + executor := &productionPathRateExecutor{ + firstStarted: make(chan struct{}), + releaseFirst: make(chan struct{}), + } + svc := &TokenRefreshService{ + accountRepo: repo, + refreshAPI: NewOAuthRefreshAPI(repo, nil), + refreshPolicy: DefaultBackgroundRefreshPolicy(), + cfg: &config.TokenRefreshConfig{MaxRetries: 1}, + attemptTimeoutOverride: 2 * time.Second, + } + state := &tokenRefreshProviderState{ + service: svc, + rateGate: newTokenRefreshRateGateWithInterval(interval), + poolGate: newTokenRefreshConcurrencyGate(2), + } + + errorsCh := make(chan error, 3) + go func() { + errorsCh <- svc.refreshWithRetryWithRateGate(context.Background(), firstSelection, executor, executor, time.Hour, state) + }() + select { + case <-executor.firstStarted: + case <-time.After(time.Second): + require.FailNow(t, "first production-path refresh did not reach the upstream executor") + } + + go func() { + errorsCh <- svc.refreshWithRetryWithRateGate(context.Background(), contendingSelection, executor, executor, time.Hour, state) + }() + require.Eventually(t, func() bool { + return len(state.poolGate.slots) == 2 + }, time.Second, time.Millisecond, "same-account contender must hold the second provider slot while waiting on the local refresh lock") + + go func() { + errorsCh <- svc.refreshWithRetryWithRateGate(context.Background(), differentSelection, executor, executor, time.Hour, state) + }() + close(executor.releaseFirst) + + skipped := 0 + for i := 0; i < 3; i++ { + err := <-errorsCh + if errors.Is(err, errRefreshSkipped) { + skipped++ + continue + } + require.NoError(t, err) + } + require.Equal(t, 1, skipped, "the same-account contender must reread the refreshed row and skip without upstream admission") + + starts := executor.startsSnapshot() + require.Len(t, starts, 2, "only the two accounts that actually refresh may consume QPS admission") + require.Equal(t, int64(71), starts[0].accountID) + require.Equal(t, int64(72), starts[1].accountID) + spacing := starts[1].at.Sub(starts[0].at) + require.GreaterOrEqual(t, spacing, interval-30*time.Millisecond) + require.Less(t, spacing, 350*time.Millisecond, + "a same-account lock waiter must not consume a rate slot and push the different-account refresh to the second interval") + t.Logf("actual_refresh_calls=%d actual_start_spacing=%s configured_spacing=%s", executor.calls.Load(), spacing, interval) +} + +func TestTokenRefreshService_ProviderTripBeforeRateAdmissionSkipsWithoutAccountMutation(t *testing.T) { + account := grokPoolAccount(73) + stored := snapshotOAuthRefreshAccount(&account) + repo := &breakerTripAccountRepo{productionPathRateRepo: &productionPathRateRepo{ + accounts: map[int64]*Account{account.ID: stored}, + }} + refresher := &poolHealthRefresher{} + svc := &TokenRefreshService{ + accountRepo: repo, + refreshAPI: NewOAuthRefreshAPI(repo, nil), + refreshPolicy: DefaultBackgroundRefreshPolicy(), + cfg: &config.TokenRefreshConfig{MaxRetries: 1}, + } + state := &tokenRefreshProviderState{ + service: svc, + rateGate: newTokenRefreshRateGate(1), + poolGate: newTokenRefreshConcurrencyGate(1), + } + gate := &tripBeforeRateAdmissionGate{state: state} + + err := svc.refreshWithRetryWithRateGate(context.Background(), &account, refresher, refresher, time.Hour, gate) + + require.ErrorIs(t, err, errRefreshSkipped) + require.Zero(t, refresher.calls.Load(), "a tripped provider must not reach upstream rate admission") + require.Zero(t, repo.setErrorCalls.Load()) + require.Zero(t, repo.setTempCalls.Load(), "provider skip must never fall through to per-account cooldown") +} + +func TestTokenRefreshService_ConfigBounds(t *testing.T) { + maxInt := int(^uint(0) >> 1) + svc := &TokenRefreshService{cfg: &config.TokenRefreshConfig{ + MaxRetries: maxInt, + RetryBackoffSeconds: maxInt, + ProviderFailureThreshold: maxInt, + AttemptTimeoutSeconds: maxInt, + CycleTimeoutSeconds: maxInt, + }} + + require.Equal(t, maxTokenRefreshMaxRetries, svc.maxRetries()) + require.Equal(t, maxTokenRefreshProviderFailureThreshold, svc.providerFailureThreshold()) + require.Equal(t, maxTokenRefreshAttemptTimeout, svc.attemptTimeout()) + require.Equal(t, maxTokenRefreshCycleTimeout, svc.cycleTimeout()) + require.LessOrEqual(t, svc.retryBackoff(1, maxTokenRefreshMaxRetries), maxTokenRefreshRetryBackoff) + require.Equal(t, maxGrokOAuthReconcilePageSize, svc.grokOAuthReconcileMaxPageSize()) +} + +func TestTokenRefreshService_AttemptTimeoutStaysInsideDistributedLockLease(t *testing.T) { + cache := &poolHealthTokenCacheStub{} + svc := &TokenRefreshService{ + cfg: &config.TokenRefreshConfig{AttemptTimeoutSeconds: int(maxTokenRefreshAttemptTimeout / time.Second)}, + refreshAPI: NewOAuthRefreshAPI(&poolHealthAccountRepo{}, cache), + } + + require.Equal(t, 55*time.Second, svc.attemptTimeout()) + require.Less(t, svc.attemptTimeout(), defaultRefreshLockTTL) +} + +func TestTokenRefreshService_SharedProviderFailureContainsCycleWithoutAccountMutation(t *testing.T) { + accounts := make([]Account, 0, 5) + for id := int64(1); id <= 5; id++ { + accounts = append(accounts, grokPoolAccount(id)) + } + repo := &poolHealthAccountRepo{pages: map[int64][]Account{0: accounts}} + refresher := &poolHealthRefresher{err: errors.New("invalid_client: provider configuration rejected")} + svc := newPoolHealthService(repo, refresher, config.TokenRefreshConfig{ + MaxRetries: 1, + CandidatePageSize: 10, + ProviderConcurrency: 4, + ProviderQPS: 10000, + ProviderFailureThreshold: 3, + AttemptTimeoutSeconds: 1, + CycleTimeoutSeconds: 2, + }) + + svc.processRefreshContext(context.Background()) + + _, _, setErrorCalls, setTempUnschedCalls := repo.snapshot() + require.Equal(t, int64(1), refresher.calls.Load(), "shared provider configuration failures must open the in-cycle breaker immediately") + require.Zero(t, setErrorCalls, "shared provider failures must not mass-disable accounts") + require.Zero(t, setTempUnschedCalls, "shared provider failures must not mutate per-account scheduling state") +} + +func TestTokenRefreshService_SharedDBRereadFailureContainsCycleWithoutAccountMutation(t *testing.T) { + accounts := []Account{grokPoolAccount(1), grokPoolAccount(2), grokPoolAccount(3)} + repo := &poolHealthAccountRepo{ + pages: map[int64][]Account{0: accounts}, + getByIDErr: errors.New("database unavailable"), + } + refresher := &poolHealthRefresher{} + svc := newPoolHealthService(repo, refresher, config.TokenRefreshConfig{ + MaxRetries: 3, + CandidatePageSize: 10, + ProviderConcurrency: 4, + ProviderQPS: 10000, + AttemptTimeoutSeconds: 1, + CycleTimeoutSeconds: 2, + }) + svc.refreshAPI = NewOAuthRefreshAPI(repo, nil) + + svc.processRefreshContext(context.Background()) + + _, _, setErrorCalls, setTempUnschedCalls := repo.snapshot() + require.Zero(t, refresher.calls.Load(), "refresh must fail closed before using stale account credentials") + require.Zero(t, setErrorCalls) + require.Zero(t, setTempUnschedCalls, "a shared DB outage must not mutate the selected account") +} + +func TestTokenRefreshService_GenericGrokForbiddenContainsCycleWithoutAccountMutation(t *testing.T) { + accounts := []Account{grokPoolAccount(1), grokPoolAccount(2), grokPoolAccount(3)} + repo := &poolHealthAccountRepo{pages: map[int64][]Account{0: accounts}} + refresher := &poolHealthRefresher{err: errors.New(`GROK_OAUTH_ENTITLEMENT_DENIED: token refresh failed: status 403, body: request blocked`)} + svc := newPoolHealthService(repo, refresher, config.TokenRefreshConfig{ + MaxRetries: 1, + CandidatePageSize: 10, + ProviderConcurrency: 4, + ProviderQPS: 10000, + ProviderFailureThreshold: 3, + AttemptTimeoutSeconds: 1, + CycleTimeoutSeconds: 2, + }) + + svc.processRefreshContext(context.Background()) + + _, _, setErrorCalls, setTempUnschedCalls := repo.snapshot() + require.Equal(t, int64(1), refresher.calls.Load(), "an ambiguous Grok 403 must contain the provider immediately") + require.Zero(t, setErrorCalls, "a generic 403 is not evidence that an account credential is permanently invalid") + require.Zero(t, setTempUnschedCalls, "provider containment must not mutate account scheduling state") +} + +func TestTokenRefreshService_ExplicitGrokEntitlementDenialIsPermanent(t *testing.T) { + repo := &poolHealthAccountRepo{pages: map[int64][]Account{0: {grokPoolAccount(1)}}} + refresher := &poolHealthRefresher{err: errors.New(`GROK_OAUTH_ENTITLEMENT_DENIED: token refresh failed: status 403, body: {"error":"subscription required"}`)} + svc := newPoolHealthService(repo, refresher, config.TokenRefreshConfig{ + MaxRetries: 1, + CandidatePageSize: 10, + ProviderConcurrency: 1, + ProviderQPS: 10000, + AttemptTimeoutSeconds: 1, + CycleTimeoutSeconds: 2, + }) + + svc.processRefreshContext(context.Background()) + + _, _, setErrorCalls, setTempUnschedCalls := repo.snapshot() + require.Equal(t, int64(1), refresher.calls.Load()) + require.Equal(t, 1, setErrorCalls, "explicit entitlement evidence is an account-permanent failure") + require.Zero(t, setTempUnschedCalls) +} + +func TestTokenRefreshService_AttemptTimeoutTripsRetryableProviderThreshold(t *testing.T) { + accounts := []Account{grokPoolAccount(1), grokPoolAccount(2), grokPoolAccount(3)} + repo := &poolHealthAccountRepo{pages: map[int64][]Account{0: accounts}} + refresher := &poolHealthRefresher{delay: time.Second} + svc := newPoolHealthService(repo, refresher, config.TokenRefreshConfig{ + MaxRetries: 1, + CandidatePageSize: 10, + ProviderConcurrency: 1, + ProviderQPS: 10000, + ProviderFailureThreshold: 2, + CycleTimeoutSeconds: 2, + }) + svc.attemptTimeoutOverride = 20 * time.Millisecond + + svc.processRefreshContext(context.Background()) + + _, _, setErrorCalls, setTempUnschedCalls := repo.snapshot() + require.Equal(t, int64(2), refresher.calls.Load(), "two attempt timeouts should trip the retryable provider threshold") + require.Zero(t, setErrorCalls) + require.Equal(t, 2, setTempUnschedCalls, "attempt timeouts remain account-transient failures before containment opens") +} + +func TestTokenRefreshService_ParentCancellationStopsRetryWithoutAccountMutation(t *testing.T) { + repo := &poolHealthAccountRepo{} + ctx, cancel := context.WithCancel(context.Background()) + refresher := &poolHealthRefresher{ + err: errors.New("temporary provider failure"), + cancel: cancel, + } + svc := newPoolHealthService(repo, refresher, config.TokenRefreshConfig{ + MaxRetries: 3, + RetryBackoffSeconds: 1, + AttemptTimeoutSeconds: 1, + }) + account := grokPoolAccount(42) + + err := svc.refreshWithRetry(ctx, &account, refresher, nil, time.Hour) + + require.ErrorIs(t, err, context.Canceled) + _, _, setErrorCalls, setTempUnschedCalls := repo.snapshot() + require.Zero(t, setErrorCalls) + require.Zero(t, setTempUnschedCalls) +} + +func TestTokenRefreshService_LateSuccessPastAttemptDeadlineIsRejected(t *testing.T) { + repo := &poolHealthAccountRepo{} + refresher := &poolHealthRefresher{ + delay: 30 * time.Millisecond, + ignoreContext: true, + } + svc := newPoolHealthService(repo, refresher, config.TokenRefreshConfig{MaxRetries: 1}) + svc.attemptTimeoutOverride = 10 * time.Millisecond + account := grokPoolAccount(43) + + err := svc.refreshWithRetry(context.Background(), &account, refresher, nil, time.Hour) + + var timeoutErr *refreshAttemptTimeoutError + require.ErrorAs(t, err, &timeoutErr) + _, updatedIDs, setErrorCalls, setTempUnschedCalls := repo.snapshot() + require.Empty(t, updatedIDs, "credentials returned after the deadline must not be persisted") + require.Zero(t, setErrorCalls) + require.Equal(t, 1, setTempUnschedCalls) +} + +func TestTokenRefreshService_NonRetryableGrokFailureInvalidatesTokenCache(t *testing.T) { + repo := &poolHealthAccountRepo{} + invalidator := &reconcileInvalidator{} + refresher := &poolHealthRefresher{err: errors.New("invalid_grant: revoked")} + svc := newPoolHealthService(repo, refresher, config.TokenRefreshConfig{MaxRetries: 1}) + svc.cacheInvalidator = invalidator + account := grokPoolAccount(77) + + err := svc.refreshWithRetry(context.Background(), &account, refresher, nil, time.Hour) + + require.Error(t, err) + _, _, setErrorCalls, setTempUnschedCalls := repo.snapshot() + require.Equal(t, 1, setErrorCalls) + require.Zero(t, setTempUnschedCalls) + require.Equal(t, 1, invalidator.count()) +} diff --git a/backend/internal/service/token_refresh_service.go b/backend/internal/service/token_refresh_service.go index 2d4a026692..31d2e19909 100644 --- a/backend/internal/service/token_refresh_service.go +++ b/backend/internal/service/token_refresh_service.go @@ -10,18 +10,54 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/config" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" "github.com/Wei-Shaw/sub2api/internal/util/logredact" ) // tokenRefreshTempUnschedDuration token 刷新重试耗尽后临时不可调度的持续时间 const tokenRefreshTempUnschedDuration = 10 * time.Minute +const ( + defaultTokenRefreshCandidatePageSize = 200 + maxTokenRefreshCandidatePageSize = 1000 + defaultTokenRefreshProviderConcurrency = 4 + maxTokenRefreshProviderConcurrency = 32 + defaultTokenRefreshProviderQPS = 2 + maxTokenRefreshProviderQPS = 100 + defaultTokenRefreshProviderFailureThreshold = 3 + maxTokenRefreshProviderFailureThreshold = 100 + defaultTokenRefreshMaxRetries = 1 + maxTokenRefreshMaxRetries = 10 + maxTokenRefreshRetryBackoff = 30 * time.Second + defaultTokenRefreshAttemptTimeout = 15 * time.Second + maxTokenRefreshAttemptTimeout = 5 * time.Minute + maxTokenRefreshLockSafetyMargin = 5 * time.Second + defaultTokenRefreshCycleTimeout = 4 * time.Minute + maxTokenRefreshCycleTimeout = time.Hour + defaultTokenRefreshCleanupTimeout = 2 * time.Second +) + +type tokenRefreshRegistration struct { + platform string + refresher TokenRefresher + executor OAuthRefreshExecutor +} + +// GrokOAuthRefreshMutationRepository protects background refresh failure +// mutations with the exact credential document used by the upstream attempt. +// This contract is intentionally Grok-only; existing provider behavior remains +// unchanged. +type GrokOAuthRefreshMutationRepository interface { + SetGrokOAuthRefreshErrorIfCredentialsUnchanged(ctx context.Context, id int64, expectedCredentials map[string]any, expectedProxyID *int64, errorMsg string) (bool, error) + SetGrokOAuthRefreshTempUnschedulableIfCredentialsUnchanged(ctx context.Context, id int64, expectedCredentials map[string]any, expectedProxyID *int64, until time.Time, reason string) (bool, error) +} + // TokenRefreshService OAuth token自动刷新服务 // 定期检查并刷新即将过期的token type TokenRefreshService struct { accountRepo AccountRepository - refreshers []TokenRefresher - executors []OAuthRefreshExecutor // 与 refreshers 一一对应的 executor(带 CacheKey) + candidatePager OAuthRefreshCandidatePager + registrations []tokenRefreshRegistration refreshPolicy BackgroundRefreshPolicy cfg *config.TokenRefreshConfig cacheInvalidator TokenCacheInvalidator @@ -34,9 +70,19 @@ type TokenRefreshService struct { privacyClientFactory PrivacyClientFactory proxyRepo ProxyRepository - stopCh chan struct{} - stopOnce sync.Once - wg sync.WaitGroup + stopCh chan struct{} + stopOnce sync.Once + wg sync.WaitGroup + runCtx context.Context + runCancel context.CancelFunc + candidateMu sync.Mutex + afterID int64 + providerMu sync.Mutex + providerGates map[string]*tokenRefreshRateGate + providerPools map[string]*tokenRefreshConcurrencyGate + + // Test-only duration seam; production uses TokenRefreshConfig seconds. + attemptTimeoutOverride time.Duration } // NewTokenRefreshService 创建token刷新服务 @@ -52,14 +98,24 @@ func NewTokenRefreshService( tempUnschedCache TempUnschedCache, grokOAuthServices ...*GrokOAuthService, ) *TokenRefreshService { + refreshCfg := &config.TokenRefreshConfig{} + if cfg != nil { + refreshCfg = &cfg.TokenRefresh + } + runCtx, runCancel := context.WithCancel(context.Background()) s := &TokenRefreshService{ accountRepo: accountRepo, refreshPolicy: DefaultBackgroundRefreshPolicy(), - cfg: &cfg.TokenRefresh, + cfg: refreshCfg, cacheInvalidator: cacheInvalidator, schedulerCache: schedulerCache, tempUnschedCache: tempUnschedCache, stopCh: make(chan struct{}), + runCtx: runCtx, + runCancel: runCancel, + } + if pager, ok := accountRepo.(OAuthRefreshCandidatePager); ok { + s.candidatePager = pager } openAIRefresher := NewOpenAITokenRefresher(openaiOAuthService, accountRepo) @@ -73,27 +129,41 @@ func NewTokenRefreshService( } grokRefresher := NewGrokTokenRefresher(grokOAuthService) - // 注册平台特定的刷新器(TokenRefresher 接口) - s.refreshers = []TokenRefresher{ - claudeRefresher, - openAIRefresher, - geminiRefresher, - agRefresher, - grokRefresher, - } - - // 注册对应的 OAuthRefreshExecutor(带 CacheKey 方法) - s.executors = []OAuthRefreshExecutor{ - claudeRefresher, - openAIRefresher, - geminiRefresher, - agRefresher, - grokRefresher, + // Each provider is registered exactly once. The same registry supplies both + // execution and repository eligibility, preventing future platform drift. + s.registrations = []tokenRefreshRegistration{ + {platform: PlatformAnthropic, refresher: claudeRefresher, executor: claudeRefresher}, + {platform: PlatformOpenAI, refresher: openAIRefresher, executor: openAIRefresher}, + {platform: PlatformGemini, refresher: geminiRefresher, executor: geminiRefresher}, + {platform: PlatformAntigravity, refresher: agRefresher, executor: agRefresher}, + {platform: PlatformGrok, refresher: grokRefresher, executor: grokRefresher}, } return s } +func (s *TokenRefreshService) eligiblePlatforms() []string { + platforms := make([]string, 0, len(s.registrations)) + for _, registration := range s.registrations { + if registration.platform != "" && registration.refresher != nil { + platforms = append(platforms, registration.platform) + } + } + return platforms +} + +func (s *TokenRefreshService) candidateAfterID() int64 { + s.candidateMu.Lock() + defer s.candidateMu.Unlock() + return s.afterID +} + +func (s *TokenRefreshService) setCandidateAfterID(afterID int64) { + s.candidateMu.Lock() + s.afterID = afterID + s.candidateMu.Unlock() +} + // SetPrivacyDeps 注入 OpenAI privacy opt-out 所需依赖 func (s *TokenRefreshService) SetPrivacyDeps(factory PrivacyClientFactory, proxyRepo ProxyRepository) { s.privacyClientFactory = factory @@ -130,7 +200,7 @@ func (s *TokenRefreshService) notifyAccountSchedulingBlockCleared(accountID int6 // Start 启动后台刷新服务 func (s *TokenRefreshService) Start() { - if !s.cfg.Enabled { + if s.cfg == nil || !s.cfg.Enabled { slog.Info("token_refresh.service_disabled") return } @@ -147,6 +217,9 @@ func (s *TokenRefreshService) Start() { // Stop 停止刷新服务(可安全多次调用) func (s *TokenRefreshService) Stop() { s.stopOnce.Do(func() { + if s.runCancel != nil { + s.runCancel() + } close(s.stopCh) }) s.wg.Wait() @@ -156,6 +229,10 @@ func (s *TokenRefreshService) Stop() { // refreshLoop 刷新循环 func (s *TokenRefreshService) refreshLoop() { defer s.wg.Done() + ctx := s.runCtx + if ctx == nil { + ctx = context.Background() + } // 计算检查间隔 checkInterval := time.Duration(s.cfg.CheckIntervalMinutes) * time.Minute @@ -167,183 +244,841 @@ func (s *TokenRefreshService) refreshLoop() { defer ticker.Stop() // 启动时立即执行一次检查 - s.processRefresh() + s.processRefreshContext(ctx) for { select { case <-ticker.C: - s.processRefresh() + s.processRefreshContext(ctx) + case <-ctx.Done(): + return case <-s.stopCh: return } } } -// processRefresh 执行一次刷新检查 -func (s *TokenRefreshService) processRefresh() { - ctx := context.Background() +type tokenRefreshPageStats struct { + total int + oauth int + needsRefresh int + refreshed int + skipped int + failed int +} - // 计算刷新窗口 - refreshWindow := time.Duration(s.cfg.RefreshBeforeExpiryHours * float64(time.Hour)) +type tokenRefreshProviderState struct { + service *TokenRefreshService + registration tokenRefreshRegistration + rateGate refreshAttemptGate + poolGate *tokenRefreshConcurrencyGate - // 获取所有active状态的账号 - accounts, err := s.listActiveAccounts(ctx) + mu sync.Mutex + consecutiveFailures int + tripped bool +} + +type tokenRefreshRateGate struct { + mu sync.Mutex + next time.Time + interval time.Duration +} + +type tokenRefreshConcurrencyGate struct { + slots chan struct{} +} + +type refreshAttemptGate interface { + acquire(ctx context.Context) (release func(), err error) +} + +type providerRefreshAttemptGate interface { + refreshAttemptGate + acquireRate(ctx context.Context) (release func(), err error) +} + +type rateLimitedOAuthRefreshExecutor struct { + OAuthRefreshExecutor + acquireRate func(context.Context) (func(), error) +} + +func (e *rateLimitedOAuthRefreshExecutor) Refresh(ctx context.Context, account *Account) (map[string]any, error) { + if e == nil || e.OAuthRefreshExecutor == nil { + return nil, errors.New("OAuth refresh executor is not configured") + } + release := func() {} + if e.acquireRate != nil { + var err error + release, err = e.acquireRate(ctx) + if err != nil { + return nil, err + } + } + defer release() + return e.OAuthRefreshExecutor.Refresh(ctx, account) +} + +func newTokenRefreshRateGate(qps int) *tokenRefreshRateGate { + if qps <= 0 { + return &tokenRefreshRateGate{} + } + return newTokenRefreshRateGateWithInterval(time.Second / time.Duration(qps)) +} + +// newTokenRefreshRateGateWithInterval is a narrow duration seam used to test +// slot reservation and cancellation without waiting on production-scale QPS. +func newTokenRefreshRateGateWithInterval(interval time.Duration) *tokenRefreshRateGate { + return &tokenRefreshRateGate{interval: interval} +} + +func (g *tokenRefreshRateGate) reserveSlot(now time.Time) time.Time { + g.mu.Lock() + defer g.mu.Unlock() + if g.next.Before(now) { + g.next = now + } + slot := g.next + g.next = g.next.Add(g.interval) + return slot +} + +func (g *tokenRefreshRateGate) wait(ctx context.Context) error { + if g == nil || g.interval <= 0 { + return nil + } + slot := g.reserveSlot(time.Now()) + + wait := time.Until(slot) + if wait <= 0 { + return nil + } + timer := time.NewTimer(wait) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + return nil + } +} + +func (g *tokenRefreshRateGate) acquire(ctx context.Context) (func(), error) { + if err := g.wait(ctx); err != nil { + return nil, err + } + return func() {}, nil +} + +func newTokenRefreshConcurrencyGate(concurrency int) *tokenRefreshConcurrencyGate { + if concurrency < 1 { + concurrency = 1 + } + return &tokenRefreshConcurrencyGate{slots: make(chan struct{}, concurrency)} +} + +func (g *tokenRefreshConcurrencyGate) acquire(ctx context.Context) (func(), error) { + if g == nil { + return func() {}, nil + } + select { + case g.slots <- struct{}{}: + return func() { <-g.slots }, nil + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +func (p *tokenRefreshProviderState) isTripped() bool { + p.mu.Lock() + defer p.mu.Unlock() + return p.tripped +} + +func (p *tokenRefreshProviderState) acquire(ctx context.Context) (func(), error) { + if p == nil || p.isTripped() { + return nil, errRefreshSkipped + } + release, err := p.poolGate.acquire(ctx) if err != nil { - slog.Error("token_refresh.list_accounts_failed", "error", err) + return nil, err + } + if p.isTripped() { + release() + return nil, errRefreshSkipped + } + return release, nil +} + +func (p *tokenRefreshProviderState) acquireRate(ctx context.Context) (func(), error) { + if p == nil || p.isTripped() { + return nil, errRefreshSkipped + } + release := func() {} + if p.rateGate != nil { + var err error + release, err = p.rateGate.acquire(ctx) + if err != nil { + return nil, err + } + } + if p.isTripped() { + release() + return nil, errRefreshSkipped + } + return release, nil +} + +func (p *tokenRefreshProviderState) recordResult(err error) { + p.mu.Lock() + defer p.mu.Unlock() + + if err == nil { + p.consecutiveFailures = 0 + return + } + if errors.Is(err, errRefreshSkipped) || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + var attemptTimeoutErr *refreshAttemptTimeoutError + if !errors.As(err, &attemptTimeoutErr) { + return + } + } + var attemptTimeoutErr *refreshAttemptTimeoutError + if errors.As(err, &attemptTimeoutErr) { + p.consecutiveFailures++ + if p.consecutiveFailures >= p.service.providerFailureThreshold() { + p.tripped = true + } + return + } + var providerErr *providerConfigurationRefreshError + if errors.As(err, &providerErr) { + p.tripped = true + return + } + var containmentErr *providerCycleContainmentRefreshError + if errors.As(err, &containmentErr) { + p.tripped = true + return + } + var permanentErr *accountPermanentRefreshError + if errors.As(err, &permanentErr) { + p.consecutiveFailures = 0 + return + } + if isNonRetryableRefreshError(err) { + // A permanent account credential failure is isolated to that account and + // does not imply the provider is unhealthy. + p.consecutiveFailures = 0 + return + } + p.consecutiveFailures++ + if p.consecutiveFailures >= p.service.providerFailureThreshold() { + p.tripped = true + } +} + +// processRefresh preserves the existing test/internal call surface while the +// production loop supplies a cancelable parent context. +func (s *TokenRefreshService) processRefresh() { + s.processRefreshContext(context.Background()) +} + +// processRefreshContext executes one bounded, cursor-resumable refresh cycle. +func (s *TokenRefreshService) processRefreshContext(parent context.Context) { + if parent == nil { + parent = context.Background() + } + ctx, cancel := context.WithTimeout(parent, s.cycleTimeout()) + defer cancel() + + pager := s.candidatePager + if pager == nil { + pager, _ = s.accountRepo.(OAuthRefreshCandidatePager) + } + if pager == nil { + slog.Error("token_refresh.candidate_pager_missing") + return + } + platforms := s.eligiblePlatforms() + if len(platforms) == 0 { + slog.Error("token_refresh.provider_registry_empty") return } - totalAccounts := len(accounts) - oauthAccounts := 0 // 可刷新的OAuth账号数 - needsRefresh := 0 // 需要刷新的账号数 - refreshed, failed, skipped := 0, 0, 0 + refreshWindow := time.Duration(s.cfg.RefreshBeforeExpiryHours * float64(time.Hour)) + pageSize := s.candidatePageSize() + providerStates := make(map[string]*tokenRefreshProviderState, len(s.registrations)) + for i := range s.registrations { + registration := s.registrations[i] + providerStates[registration.platform] = &tokenRefreshProviderState{ + service: s, + registration: registration, + rateGate: s.providerRateGate(registration.platform), + poolGate: s.providerConcurrencyGate(registration.platform), + } + } - for i := range accounts { - account := &accounts[i] + stats := tokenRefreshPageStats{} + afterID := s.candidateAfterID() + for { + if ctx.Err() != nil { + slog.Warn("token_refresh.cycle_stopped", "error", ctx.Err(), "resume_after_id", afterID) + break + } + page, err := pager.ListOAuthRefreshCandidatePage(ctx, OAuthRefreshPageOptions{ + Platforms: platforms, + AfterID: afterID, + Limit: pageSize, + ActiveOnly: true, + IncludeSetupToken: true, + RequireRefreshToken: true, + ExcludeRetryCooldown: true, + }) + if err != nil { + slog.Error("token_refresh.list_accounts_failed", "error", err, "after_id", afterID) + break + } + if page == nil { + slog.Error("token_refresh.nil_candidate_page", "after_id", afterID) + break + } + accounts := page.Accounts + if !page.HasMore && page.NextAfterID == 0 && len(accounts) == 0 { + s.setCandidateAfterID(0) + break + } + if page.NextAfterID <= afterID { + slog.Error("token_refresh.invalid_candidate_page_metadata", "after_id", afterID) + break + } + if !isStrictlyIncreasingAccountPage(accounts, afterID) { + slog.Error("token_refresh.invalid_candidate_page", "after_id", afterID, "count", len(accounts)) + break + } - // 遍历所有刷新器,找到能处理此账号的 - for idx, refresher := range s.refreshers { - if !refresher.CanRefresh(account) { - continue - } + pageStats := s.processCandidatePage(ctx, accounts, providerStates, refreshWindow) + stats.total += pageStats.total + stats.oauth += pageStats.oauth + stats.needsRefresh += pageStats.needsRefresh + stats.refreshed += pageStats.refreshed + stats.skipped += pageStats.skipped + stats.failed += pageStats.failed - oauthAccounts++ - - // 检查是否需要刷新 - if !refresher.NeedsRefresh(account, refreshWindow) { - break // 不需要刷新,跳过 - } - - needsRefresh++ - - // 获取对应的 executor - var executor OAuthRefreshExecutor - if idx < len(s.executors) { - executor = s.executors[idx] - } - - // 执行刷新 - if err := s.refreshWithRetry(ctx, account, refresher, executor, refreshWindow); err != nil { - if errors.Is(err, errRefreshSkipped) { - skipped++ - } else { - slog.Warn("token_refresh.account_refresh_failed", - "account_id", account.ID, - "account_name", account.Name, - "error", err, - ) - failed++ - } - } else { - slog.Info("token_refresh.account_refreshed", - "account_id", account.ID, - "account_name", account.Name, - ) - refreshed++ - } - - // 每个账号只由一个refresher处理 + // Never advance past a partially processed page. Re-reading a page is + // safe because OAuthRefreshAPI re-reads DB state and checks expiry again. + if ctx.Err() != nil { + break + } + afterID = page.NextAfterID + s.setCandidateAfterID(afterID) + if !page.HasMore { + s.setCandidateAfterID(0) break } } - // 无刷新活动时降级为 Debug,有实际刷新活动时保持 Info - if needsRefresh == 0 && failed == 0 { + if stats.needsRefresh == 0 && stats.failed == 0 { slog.Debug("token_refresh.cycle_completed", - "total", totalAccounts, "oauth", oauthAccounts, - "needs_refresh", needsRefresh, "refreshed", refreshed, "skipped", skipped, "failed", failed) + "total", stats.total, "oauth", stats.oauth, + "needs_refresh", stats.needsRefresh, "refreshed", stats.refreshed, + "skipped", stats.skipped, "failed", stats.failed) } else { slog.Info("token_refresh.cycle_completed", - "total", totalAccounts, - "oauth", oauthAccounts, - "needs_refresh", needsRefresh, - "refreshed", refreshed, - "skipped", skipped, - "failed", failed, - ) + "total", stats.total, "oauth", stats.oauth, + "needs_refresh", stats.needsRefresh, "refreshed", stats.refreshed, + "skipped", stats.skipped, "failed", stats.failed) } } -// listActiveAccounts 获取后台 OAuth token 刷新候选账号。 -func (s *TokenRefreshService) listActiveAccounts(ctx context.Context) ([]Account, error) { - return s.accountRepo.ListOAuthRefreshCandidates(ctx) +func isStrictlyIncreasingAccountPage(accounts []Account, afterID int64) bool { + previous := afterID + for i := range accounts { + if accounts[i].ID <= previous { + return false + } + previous = accounts[i].ID + } + return true +} + +func (s *TokenRefreshService) processCandidatePage( + ctx context.Context, + accounts []Account, + providerStates map[string]*tokenRefreshProviderState, + refreshWindow time.Duration, +) tokenRefreshPageStats { + stats := tokenRefreshPageStats{total: len(accounts)} + groups := make(map[string][]*Account) + for i := range accounts { + account := &accounts[i] + state := providerStates[account.Platform] + if state == nil || state.registration.refresher == nil || !state.registration.refresher.CanRefresh(account) { + continue + } + stats.oauth++ + if !state.registration.refresher.NeedsRefresh(account, refreshWindow) { + continue + } + stats.needsRefresh++ + groups[account.Platform] = append(groups[account.Platform], account) + } + + type providerResult struct { + refreshed int + skipped int + failed int + } + results := make(chan providerResult, len(groups)) + var wg sync.WaitGroup + for platform, group := range groups { + state := providerStates[platform] + wg.Add(1) + go func() { + defer wg.Done() + refreshed, skipped, failed := s.processProviderAccounts(ctx, state, group, refreshWindow) + results <- providerResult{refreshed: refreshed, skipped: skipped, failed: failed} + }() + } + wg.Wait() + close(results) + for result := range results { + stats.refreshed += result.refreshed + stats.skipped += result.skipped + stats.failed += result.failed + } + return stats +} + +func (s *TokenRefreshService) processProviderAccounts( + ctx context.Context, + state *tokenRefreshProviderState, + accounts []*Account, + refreshWindow time.Duration, +) (refreshed, skipped, failed int) { + if state == nil || len(accounts) == 0 { + return 0, 0, 0 + } + type refreshResult struct { + accountID int64 + err error + } + jobs := make(chan *Account, len(accounts)) + results := make(chan refreshResult, len(accounts)) + workerCount := s.providerConcurrency() + if workerCount > len(accounts) { + workerCount = len(accounts) + } + var wg sync.WaitGroup + for i := 0; i < workerCount; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for account := range jobs { + if ctx.Err() != nil || state.isTripped() { + results <- refreshResult{accountID: account.ID, err: errRefreshSkipped} + continue + } + if state.isTripped() { + results <- refreshResult{accountID: account.ID, err: errRefreshSkipped} + continue + } + err := s.refreshWithRetryWithRateGate(ctx, account, state.registration.refresher, state.registration.executor, refreshWindow, state) + state.recordResult(err) + results <- refreshResult{accountID: account.ID, err: err} + } + }() + } + for _, account := range accounts { + jobs <- account + } + close(jobs) + wg.Wait() + close(results) + + for result := range results { + switch { + case result.err == nil: + refreshed++ + slog.Info("token_refresh.account_refreshed", "account_id", result.accountID, "platform", state.registration.platform) + case errors.Is(result.err, errRefreshSkipped): + skipped++ + default: + failed++ + slog.Warn("token_refresh.account_refresh_failed", "account_id", result.accountID, "platform", state.registration.platform, "error", logredact.RedactText(result.err.Error())) + } + } + return refreshed, skipped, failed +} + +func (s *TokenRefreshService) candidatePageSize() int { + if s.cfg != nil && s.cfg.CandidatePageSize > 0 { + return min(s.cfg.CandidatePageSize, maxTokenRefreshCandidatePageSize) + } + return defaultTokenRefreshCandidatePageSize +} + +func (s *TokenRefreshService) providerConcurrency() int { + if s.cfg != nil && s.cfg.ProviderConcurrency > 0 { + return min(s.cfg.ProviderConcurrency, maxTokenRefreshProviderConcurrency) + } + return defaultTokenRefreshProviderConcurrency +} + +func (s *TokenRefreshService) providerQPS() int { + if s.cfg != nil && s.cfg.ProviderQPS > 0 { + return min(s.cfg.ProviderQPS, maxTokenRefreshProviderQPS) + } + return defaultTokenRefreshProviderQPS +} + +// providerRateGate returns the process-local limiter shared by background +// cycles and admin reconciliation. Sharing it prevents concurrent entry points +// or retries from multiplying the configured per-provider request rate. +func (s *TokenRefreshService) providerRateGate(platform string) *tokenRefreshRateGate { + s.providerMu.Lock() + defer s.providerMu.Unlock() + if s.providerGates == nil { + s.providerGates = make(map[string]*tokenRefreshRateGate) + } + if gate := s.providerGates[platform]; gate != nil { + return gate + } + gate := newTokenRefreshRateGate(s.providerQPS()) + s.providerGates[platform] = gate + return gate +} + +// providerConcurrencyGate returns the process-local semaphore shared by every +// background cycle and admin reconciliation call for a provider. It is +// acquired and released around each upstream retry attempt, so parallel entry +// points cannot multiply ProviderConcurrency. +func (s *TokenRefreshService) providerConcurrencyGate(platform string) *tokenRefreshConcurrencyGate { + s.providerMu.Lock() + defer s.providerMu.Unlock() + if s.providerPools == nil { + s.providerPools = make(map[string]*tokenRefreshConcurrencyGate) + } + if gate := s.providerPools[platform]; gate != nil { + return gate + } + gate := newTokenRefreshConcurrencyGate(s.providerConcurrency()) + s.providerPools[platform] = gate + return gate +} + +func (s *TokenRefreshService) providerFailureThreshold() int { + if s.cfg != nil && s.cfg.ProviderFailureThreshold > 0 { + return min(s.cfg.ProviderFailureThreshold, maxTokenRefreshProviderFailureThreshold) + } + return defaultTokenRefreshProviderFailureThreshold +} + +func (s *TokenRefreshService) attemptTimeout() time.Duration { + timeout := defaultTokenRefreshAttemptTimeout + if s.attemptTimeoutOverride > 0 { + timeout = s.attemptTimeoutOverride + } else if s.cfg != nil && s.cfg.AttemptTimeoutSeconds > 0 { + seconds := min(s.cfg.AttemptTimeoutSeconds, int(maxTokenRefreshAttemptTimeout/time.Second)) + timeout = time.Duration(seconds) * time.Second + } + if s.refreshAPI != nil && s.refreshAPI.tokenCache != nil { + timeout = clampRefreshAttemptToLockLease(timeout, s.refreshAPI.lockTTL) + } + return timeout +} + +func clampRefreshAttemptToLockLease(timeout, lease time.Duration) time.Duration { + if timeout <= 0 || lease <= 0 { + return timeout + } + margin := lease / 10 + if margin > maxTokenRefreshLockSafetyMargin { + margin = maxTokenRefreshLockSafetyMargin + } + if margin <= 0 { + margin = time.Nanosecond + } + leaseBudget := lease - margin + if leaseBudget <= 0 { + leaseBudget = lease / 2 + } + if leaseBudget > 0 && timeout > leaseBudget { + return leaseBudget + } + return timeout +} + +func (s *TokenRefreshService) cycleTimeout() time.Duration { + if s.cfg != nil && s.cfg.CycleTimeoutSeconds > 0 { + seconds := min(s.cfg.CycleTimeoutSeconds, int(maxTokenRefreshCycleTimeout/time.Second)) + return time.Duration(seconds) * time.Second + } + return defaultTokenRefreshCycleTimeout +} + +func (s *TokenRefreshService) maxRetries() int { + if s.cfg != nil && s.cfg.MaxRetries > 0 { + return min(s.cfg.MaxRetries, maxTokenRefreshMaxRetries) + } + return defaultTokenRefreshMaxRetries } // refreshWithRetry 带重试的刷新 func (s *TokenRefreshService) refreshWithRetry(ctx context.Context, account *Account, refresher TokenRefresher, executor OAuthRefreshExecutor, refreshWindow time.Duration) error { - var lastErr error + return s.refreshWithRetryWithRateGate(ctx, account, refresher, executor, refreshWindow, nil) +} - for attempt := 1; attempt <= s.cfg.MaxRetries; attempt++ { +func (s *TokenRefreshService) refreshWithRetryWithRateGate( + ctx context.Context, + account *Account, + refresher TokenRefresher, + executor OAuthRefreshExecutor, + refreshWindow time.Duration, + gate refreshAttemptGate, +) error { + var lastErr error + maxRetries := s.maxRetries() + + for attempt := 1; attempt <= maxRetries; attempt++ { + if err := ctx.Err(); err != nil { + return err + } + releaseAttempt := func() {} + var acquireRate func(context.Context) (func(), error) + if gate != nil { + if providerGate, ok := gate.(providerRefreshAttemptGate); ok { + var err error + releaseAttempt, err = providerGate.acquire(ctx) + if err != nil { + return err + } + acquireRate = providerGate.acquireRate + } else { + // Compatibility gates are rate-admission gates. Acquire them only + // when an upstream Refresh call is actually about to start. + acquireRate = gate.acquire + } + } + attemptCtx, cancelAttempt := context.WithTimeout(ctx, s.attemptTimeout()) var newCredentials map[string]any var err error + shortCircuit := false + credentialsPersisted := false // 优先使用统一 API(带分布式锁 + DB 重读保护) if s.refreshAPI != nil && executor != nil { - result, refreshErr := s.refreshAPI.RefreshIfNeeded(ctx, account, executor, refreshWindow) + actualExecutor := executor + if acquireRate != nil { + actualExecutor = &rateLimitedOAuthRefreshExecutor{ + OAuthRefreshExecutor: executor, + acquireRate: acquireRate, + } + } + result, refreshErr := s.refreshAPI.RefreshIfNeeded(attemptCtx, account, actualExecutor, refreshWindow) + if result != nil && result.Account != nil { + account = result.Account + } if refreshErr != nil { err = refreshErr } else if result.LockHeld { // 锁被其他 worker 持有,由调用侧策略决定如何计数 - return s.refreshPolicy.handleLockHeld() + err = s.refreshPolicy.handleLockHeld() + shortCircuit = true } else if !result.Refreshed { // 已被其他路径刷新,由调用侧策略决定如何计数 - return s.refreshPolicy.handleAlreadyRefreshed() + err = s.refreshPolicy.handleAlreadyRefreshed() + shortCircuit = true } else { - account = result.Account + credentialsPersisted = result.NewCredentials != nil _ = result.NewCredentials // 统一 API 已设置 _token_version 并更新 DB,无需重复操作 } } else { // 降级:直接调用 refresher(兼容旧路径) - newCredentials, err = refresher.Refresh(ctx, account) - if newCredentials != nil { + releaseRate := func() {} + if acquireRate != nil { + releaseRate, err = acquireRate(attemptCtx) + } + if err == nil { + newCredentials, err = refresher.Refresh(attemptCtx, account) + } + if releaseRate != nil { + releaseRate() + } + attemptTimedOut := errors.Is(attemptCtx.Err(), context.DeadlineExceeded) && ctx.Err() == nil + if err == nil && newCredentials != nil && !attemptTimedOut { newCredentials["_token_version"] = time.Now().UnixMilli() - if saveErr := persistAccountCredentials(ctx, s.accountRepo, account, newCredentials); saveErr != nil { - return fmt.Errorf("failed to save credentials: %w", saveErr) + if saveErr := persistAccountCredentials(attemptCtx, s.accountRepo, account, newCredentials); saveErr != nil { + err = fmt.Errorf("failed to save credentials: %w", saveErr) + } else { + credentialsPersisted = true } } } + attemptTimedOut := errors.Is(attemptCtx.Err(), context.DeadlineExceeded) && ctx.Err() == nil + cancelAttempt() + releaseAttempt() + persistedAfterAttemptDeadline := attemptTimedOut && credentialsPersisted && err == nil + if attemptTimedOut && !persistedAfterAttemptDeadline && !isProviderScopedTerminalRefreshError(err) { + cause := err + if cause == nil { + cause = context.DeadlineExceeded + } + err = &refreshAttemptTimeoutError{err: cause} + shortCircuit = false + if credentialsPersisted { + s.postRefreshStateSyncWithCleanup(ctx, account) + } + } + if shortCircuit { + return err + } if err == nil { + if ctxErr := ctx.Err(); ctxErr != nil { + if credentialsPersisted { + s.postRefreshStateSyncWithCleanup(ctx, account) + } + return ctxErr + } + if persistedAfterAttemptDeadline { + // The provider result and exact-state CAS are already durable. Only + // the internal attempt budget elapsed while bounded detached cleanup + // completed; do not convert that success into retry/cooldown/breaker + // evidence. Publish cache state with a fresh cleanup context and stop. + s.postRefreshStateSyncWithCleanup(ctx, account) + return nil + } s.postRefreshActions(ctx, account) return nil } + if ctxErr := ctx.Err(); ctxErr != nil { + if credentialsPersisted { + s.postRefreshStateSyncWithCleanup(ctx, account) + } + return ctxErr + } + if errors.Is(err, errRefreshSkipped) { + return errRefreshSkipped + } + if isProviderScopedTerminalRefreshError(err) { + return err + } + var stateUnavailableErr *oauthRefreshStateUnavailableError + if errors.As(err, &stateUnavailableErr) { + return &providerCycleContainmentRefreshError{err: err} + } + if isAmbiguousGrokEntitlementRefreshError(account, err) { + // The current Grok client labels every token-endpoint 403 as an + // entitlement denial. Without explicit entitlement evidence, contain + // the provider for this cycle instead of disabling an account on a + // possible WAF or shared provider failure. + return &providerCycleContainmentRefreshError{err: err} + } + + // Provider-wide OAuth client/scope failures are not evidence that every + // account is invalid. Return a typed internal signal so the cycle contains + // the provider without mutating account state. + if isSharedProviderRefreshError(err) { + return &providerConfigurationRefreshError{err: err} + } // 不可重试错误(invalid_grant/invalid_client 等)直接标记 error 状态并返回 if isNonRetryableRefreshError(err) { errorMsg := "Token refresh failed (non-retryable): " + logredact.RedactText(err.Error()) - s.notifyAccountSchedulingBlocked(account, time.Time{}, "token_refresh_non_retryable") + isGrokOAuth := account.IsGrokOAuth() + if !isGrokOAuth { + s.notifyAccountSchedulingBlocked(account, time.Time{}, "token_refresh_non_retryable") + } s.clearAntigravityForceTokenRefresh(ctx, account, "non_retryable") - if setErr := s.accountRepo.SetError(ctx, account.ID, errorMsg); setErr != nil { + persistentlyBlocked := false + var setErr error + if isGrokOAuth { + conditionalRepo, ok := s.accountRepo.(GrokOAuthRefreshMutationRepository) + if !ok { + return &providerConfigurationRefreshError{ + err: errors.New("grok OAuth conditional refresh mutation repository is not configured"), + } + } else { + persistentlyBlocked, setErr = conditionalRepo.SetGrokOAuthRefreshErrorIfCredentialsUnchanged( + ctx, + account.ID, + account.Credentials, + account.ProxyID, + errorMsg, + ) + if setErr == nil && !persistentlyBlocked { + slog.Info("token_refresh.grok_error_status_skipped_stale_credentials", "account_id", account.ID) + return errRefreshSkipped + } + } + } else { + setErr = s.accountRepo.SetError(ctx, account.ID, errorMsg) + persistentlyBlocked = setErr == nil + } + if setErr != nil { slog.Error("token_refresh.set_error_status_failed", "account_id", account.ID, "error", setErr, ) + if isGrokOAuth { + return &providerCycleContainmentRefreshError{ + err: fmt.Errorf("failed to conditionally persist Grok OAuth refresh failure: %w", setErr), + } + } + } else if isGrokOAuth && persistentlyBlocked { + s.notifyAccountSchedulingBlocked(account, time.Time{}, "token_refresh_non_retryable") + } + cacheInvalidationFailed := false + if account.Type == AccountTypeOAuth && (!isGrokOAuth || persistentlyBlocked) { + if s.cacheInvalidator == nil { + cacheInvalidationFailed = true + } else if invalidateErr := s.cacheInvalidator.InvalidateToken(ctx, account); invalidateErr != nil { + cacheInvalidationFailed = true + slog.Warn("token_refresh.invalidate_failed_token_cache_failed", + "account_id", account.ID, + "error", logredact.RedactText(invalidateErr.Error()), + ) + } + } + return &accountPermanentRefreshError{ + err: err, + persistentlyBlocked: persistentlyBlocked, + cacheInvalidationFailed: cacheInvalidationFailed, } - return err } lastErr = err slog.Warn("token_refresh.retry_attempt_failed", "account_id", account.ID, "attempt", attempt, - "max_retries", s.cfg.MaxRetries, - "error", err, + "max_retries", maxRetries, + "error", logredact.RedactText(err.Error()), ) // 如果还有重试机会,等待后重试 - if attempt < s.cfg.MaxRetries { - // 指数退避:2^(attempt-1) * baseSeconds - backoff := time.Duration(s.cfg.RetryBackoffSeconds) * time.Second * time.Duration(1<<(attempt-1)) - time.Sleep(backoff) + if attempt < maxRetries { + backoff := s.retryBackoff(account.ID, attempt) + if backoff > 0 { + timer := time.NewTimer(backoff) + select { + case <-ctx.Done(): + timer.Stop() + return ctx.Err() + case <-timer.C: + } + } } } + if err := ctx.Err(); err != nil { + return err + } // 可重试错误耗尽:临时标记账号不可调度,避免请求路径反复命中已知失败的账号 slog.Warn("token_refresh.retry_exhausted", "account_id", account.ID, "platform", account.Platform, - "max_retries", s.cfg.MaxRetries, - "error", lastErr, + "max_retries", maxRetries, + "error", logredact.RedactText(lastErr.Error()), ) // 设置临时不可调度 10 分钟(不标记 error,保持 status=active 让下个刷新周期能继续尝试) @@ -352,6 +1087,42 @@ func (s *TokenRefreshService) refreshWithRetry(ctx context.Context, account *Acc if lastErr != nil { reason += ": " + logredact.RedactText(lastErr.Error()) } + if account.IsGrokOAuth() { + conditionalRepo, ok := s.accountRepo.(GrokOAuthRefreshMutationRepository) + if !ok { + return &providerConfigurationRefreshError{ + err: errors.New("grok OAuth conditional refresh mutation repository is not configured"), + } + } + applied, setErr := conditionalRepo.SetGrokOAuthRefreshTempUnschedulableIfCredentialsUnchanged( + ctx, + account.ID, + account.Credentials, + account.ProxyID, + until, + reason, + ) + if setErr != nil { + slog.Warn("token_refresh.set_temp_unschedulable_failed", + "account_id", account.ID, + "error", setErr, + ) + return &providerCycleContainmentRefreshError{ + err: fmt.Errorf("failed to conditionally persist Grok OAuth refresh cooldown: %w", setErr), + } + } else if !applied { + slog.Info("token_refresh.grok_temp_unschedulable_skipped_stale_credentials", "account_id", account.ID) + return errRefreshSkipped + } else { + s.notifyAccountSchedulingBlocked(account, until, "token_refresh_retry_exhausted") + slog.Info("token_refresh.temp_unschedulable_set", + "account_id", account.ID, + "until", until.Format(time.RFC3339), + ) + } + return lastErr + } + s.notifyAccountSchedulingBlocked(account, until, "token_refresh_retry_exhausted") if setErr := s.accountRepo.SetTempUnschedulable(ctx, account.ID, until, reason); setErr != nil { slog.Warn("token_refresh.set_temp_unschedulable_failed", @@ -368,6 +1139,23 @@ func (s *TokenRefreshService) refreshWithRetry(ctx context.Context, account *Acc return lastErr } +func (s *TokenRefreshService) retryBackoff(accountID int64, attempt int) time.Duration { + if s.cfg == nil || s.cfg.RetryBackoffSeconds <= 0 { + return 0 + } + shift := attempt - 1 + if shift > 10 { + shift = 10 + } + baseSeconds := min(s.cfg.RetryBackoffSeconds, int(maxTokenRefreshRetryBackoff/time.Second)) + base := time.Duration(baseSeconds) * time.Second * time.Duration(1<= 0 { + body := msg[bodyIndex+len("body:"):] + for _, evidence := range []string{ + "entitlement_denied", + "entitlement denied", + "subscription_required", + "no_active_subscription", + } { + if strings.Contains(body, evidence) { + return false + } + } + } + return true +} + +func (e *providerConfigurationRefreshError) Unwrap() error { + if e == nil { + return nil + } + return e.err +} + +func isSharedProviderRefreshError(err error) bool { + if err == nil { + return false + } + msg := strings.ToLower(err.Error()) + for _, needle := range []string{ + "invalid_client", + "unauthorized_client", + "invalid_scope", + "unknown scope", + } { + if strings.Contains(msg, needle) { + return true + } + } + return false +} + // isNonRetryableRefreshError 判断是否为不可重试的刷新错误 // 这些错误通常表示凭证已失效或配置确实缺失,需要用户重新授权 // 注意:missing_project_id 错误只在真正缺失(从未获取过)时返回,临时获取失败不会返回此错误 diff --git a/backend/internal/service/token_refresh_service_candidates_test.go b/backend/internal/service/token_refresh_service_candidates_test.go index 5e2c8cc4aa..ac4e3cf4f0 100644 --- a/backend/internal/service/token_refresh_service_candidates_test.go +++ b/backend/internal/service/token_refresh_service_candidates_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "strings" + "sync" "testing" "time" @@ -14,6 +15,7 @@ import ( type tokenRefreshCandidateRepo struct { AccountRepository + mu sync.Mutex accounts []Account updatedCredentialIDs []int64 setErrorCalls int @@ -24,60 +26,78 @@ type tokenRefreshCandidateRepo struct { } func (r *tokenRefreshCandidateRepo) ListActive(context.Context) ([]Account, error) { + r.mu.Lock() + defer r.mu.Unlock() r.listActiveCalls++ return r.accounts, nil } -func (r *tokenRefreshCandidateRepo) ListOAuthRefreshCandidates(context.Context) ([]Account, error) { +func (r *tokenRefreshCandidateRepo) ListOAuthRefreshCandidatePage(_ context.Context, options OAuthRefreshPageOptions) (*OAuthRefreshCandidatePage, error) { candidates := make([]Account, 0, len(r.accounts)) now := time.Now() for _, account := range r.accounts { + if account.ID <= options.AfterID { + continue + } refreshToken, _ := account.Credentials["refresh_token"].(string) inRetryCooldown := account.TempUnschedulableUntil != nil && account.TempUnschedulableUntil.After(now) && strings.HasPrefix(account.TempUnschedulableReason, "token refresh retry exhausted:") - if account.Status != StatusActive || + platformAllowed := false + for _, platform := range options.Platforms { + if account.Platform == platform { + platformAllowed = true + break + } + } + if options.ActiveOnly && account.Status != StatusActive || account.Type != AccountTypeOAuth || - !isOAuthRefreshPlatform(account.Platform) || - strings.TrimSpace(refreshToken) == "" || - inRetryCooldown { + !platformAllowed || + options.RequireRefreshToken && strings.TrimSpace(refreshToken) == "" || + options.ExcludeRetryCooldown && inRetryCooldown { continue } candidates = append(candidates, account) + if len(candidates) == options.Limit { + break + } } - return candidates, nil + page := &OAuthRefreshCandidatePage{Accounts: candidates, HasMore: len(candidates) == options.Limit} + if len(candidates) > 0 { + page.NextAfterID = candidates[len(candidates)-1].ID + } + return page, nil } func (r *tokenRefreshCandidateRepo) UpdateCredentials(_ context.Context, id int64, _ map[string]any) error { + r.mu.Lock() + defer r.mu.Unlock() r.updatedCredentialIDs = append(r.updatedCredentialIDs, id) return nil } func (r *tokenRefreshCandidateRepo) SetError(context.Context, int64, string) error { + r.mu.Lock() + defer r.mu.Unlock() r.setErrorCalls++ return nil } func (r *tokenRefreshCandidateRepo) SetTempUnschedulable(_ context.Context, _ int64, _ time.Time, reason string) error { + r.mu.Lock() + defer r.mu.Unlock() r.setTempUnschedCalls++ r.lastTempUnschedReason = reason return nil } func (r *tokenRefreshCandidateRepo) ClearTempUnschedulable(context.Context, int64) error { + r.mu.Lock() + defer r.mu.Unlock() r.clearTempCalls++ return nil } -func isOAuthRefreshPlatform(platform string) bool { - switch platform { - case PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity: - return true - default: - return false - } -} - type tokenRefreshTestRefresher struct { err error } @@ -147,8 +167,13 @@ func TestTokenRefreshService_ProcessRefreshUsesOAuthRefreshCandidates(t *testing }, } svc := &TokenRefreshService{ - accountRepo: repo, - refreshers: []TokenRefresher{&tokenRefreshTestRefresher{}}, + accountRepo: repo, + candidatePager: repo, + registrations: []tokenRefreshRegistration{ + {platform: PlatformOpenAI, refresher: &tokenRefreshTestRefresher{}}, + {platform: PlatformGemini, refresher: &tokenRefreshTestRefresher{}}, + {platform: PlatformAntigravity, refresher: &tokenRefreshTestRefresher{}}, + }, refreshPolicy: DefaultBackgroundRefreshPolicy(), cfg: &config.TokenRefreshConfig{RefreshBeforeExpiryHours: 1, MaxRetries: 1}, } @@ -156,7 +181,7 @@ func TestTokenRefreshService_ProcessRefreshUsesOAuthRefreshCandidates(t *testing svc.processRefresh() require.Zero(t, repo.listActiveCalls, "TokenRefreshService should not use the broad active-account query") - require.Equal(t, []int64{1, 6}, repo.updatedCredentialIDs) + require.ElementsMatch(t, []int64{1, 6}, repo.updatedCredentialIDs) require.Equal(t, 1, repo.clearTempCalls, "successful refresh should clear the OAuth 401 temp-unschedulable state") } diff --git a/backend/internal/service/token_refresh_service_test.go b/backend/internal/service/token_refresh_service_test.go index bd6a521576..75a84bfbcc 100644 --- a/backend/internal/service/token_refresh_service_test.go +++ b/backend/internal/service/token_refresh_service_test.go @@ -5,6 +5,7 @@ package service import ( "context" "errors" + "reflect" "testing" "time" @@ -14,18 +15,37 @@ import ( type tokenRefreshAccountRepo struct { mockAccountRepoForGemini - updateCalls int - fullUpdateCalls int - updateCredentialsCalls int - setErrorCalls int - clearTempCalls int - setTempUnschedCalls int - updateExtraCalls int - lastErrorMessage string - lastTempUnschedReason string - lastExtraUpdates map[string]any - lastAccount *Account - updateErr error + updateCalls int + fullUpdateCalls int + updateCredentialsCalls int + setErrorCalls int + clearTempCalls int + setTempUnschedCalls int + updateExtraCalls int + lastErrorMessage string + lastTempUnschedReason string + lastExtraUpdates map[string]any + lastAccount *Account + updateErr error + cancelOnUpdate context.CancelFunc + conditionalErrorCalls int + conditionalTempCalls int + conditionalSuccessCalls int + conditionalErrorErr error + conditionalTempErr error + conditionalSuccessErr error + snapshotReads bool + respectReadContext bool + getByIDCalls int + durableReadDelay time.Duration + mutateSchedulingOnSuccessCAS bool + reauthorizeOnErrorCAS bool + reauthorizeOnTempCAS bool + repairProxyOnErrorCAS bool + repairProxyOnTempCAS bool + setErrorErr error + setTempUnschedErr error + beforeConditionalState func() } func (r *tokenRefreshAccountRepo) Update(ctx context.Context, account *Account) error { @@ -46,17 +66,44 @@ func (r *tokenRefreshAccountRepo) UpdateCredentials(ctx context.Context, id int6 if acc, ok := r.accountsByID[id]; ok && acc != nil { acc.Credentials = cloned r.lastAccount = acc + if r.cancelOnUpdate != nil { + r.cancelOnUpdate() + } return nil } } r.lastAccount = &Account{ID: id, Credentials: cloned} + if r.cancelOnUpdate != nil { + r.cancelOnUpdate() + } return nil } +func (r *tokenRefreshAccountRepo) GetByID(ctx context.Context, id int64) (*Account, error) { + if r.respectReadContext && ctx.Err() != nil { + return nil, ctx.Err() + } + r.getByIDCalls++ + if r.getByIDCalls > 1 && r.durableReadDelay > 0 { + timer := time.NewTimer(r.durableReadDelay) + defer timer.Stop() + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-timer.C: + } + } + account, err := r.mockAccountRepoForGemini.GetByID(ctx, id) + if err != nil || !r.snapshotReads { + return account, err + } + return snapshotOAuthRefreshAccount(account), nil +} + func (r *tokenRefreshAccountRepo) SetError(ctx context.Context, id int64, errorMsg string) error { r.setErrorCalls++ r.lastErrorMessage = errorMsg - return nil + return r.setErrorErr } func (r *tokenRefreshAccountRepo) ClearTempUnschedulable(ctx context.Context, id int64) error { @@ -67,7 +114,184 @@ func (r *tokenRefreshAccountRepo) ClearTempUnschedulable(ctx context.Context, id func (r *tokenRefreshAccountRepo) SetTempUnschedulable(ctx context.Context, id int64, until time.Time, reason string) error { r.setTempUnschedCalls++ r.lastTempUnschedReason = reason - return nil + return r.setTempUnschedErr +} + +func (r *tokenRefreshAccountRepo) SetGrokCredentialErrorIfMatch( + _ context.Context, + id int64, + snapshot GrokCredentialMutationSnapshot, + errorMsg string, +) (bool, error) { + if r.beforeConditionalState != nil { + hook := r.beforeConditionalState + r.beforeConditionalState = nil + hook() + } + account := r.accountsByID[id] + if !grokCredentialSnapshotMatchesAccount(account, snapshot) || + (errorMsg == string(GrokCredentialReasonProxyInvalid) && account.Proxy != nil) { + return false, nil + } + r.setErrorCalls++ + r.lastErrorMessage = errorMsg + if r.setErrorErr != nil { + return false, r.setErrorErr + } + account.Status = StatusError + account.Schedulable = false + account.ErrorMessage = errorMsg + return true, nil +} + +func (r *tokenRefreshAccountRepo) SetGrokCredentialTempUnschedulableIfMatch( + _ context.Context, + id int64, + snapshot GrokCredentialMutationSnapshot, + until time.Time, + reason string, +) (bool, error) { + if r.beforeConditionalState != nil { + hook := r.beforeConditionalState + r.beforeConditionalState = nil + hook() + } + account := r.accountsByID[id] + if !grokCredentialSnapshotMatchesAccount(account, snapshot) { + return false, nil + } + r.setTempUnschedCalls++ + r.lastTempUnschedReason = reason + if r.setTempUnschedErr != nil { + return false, r.setTempUnschedErr + } + value := until + account.TempUnschedulableUntil = &value + return true, nil +} + +func grokCredentialSnapshotMatchesAccount(account *Account, snapshot GrokCredentialMutationSnapshot) bool { + return account != nil && account.IsGrokOAuth() && account.IsSchedulable() && + grokCredentialMutationSnapshot(account).CredentialsJSON == snapshot.CredentialsJSON && + grokCredentialProxyIDsEqual(account.ProxyID, snapshot.ProxyID) +} + +func (r *tokenRefreshAccountRepo) SetGrokOAuthRefreshErrorIfCredentialsUnchanged( + _ context.Context, + id int64, + expectedCredentials map[string]any, + expectedProxyID *int64, + errorMsg string, +) (bool, error) { + r.conditionalErrorCalls++ + if r.conditionalErrorErr != nil { + return false, r.conditionalErrorErr + } + account := r.accountsByID[id] + if account == nil { + return false, nil + } + if r.reauthorizeOnErrorCAS { + r.reauthorizeOnErrorCAS = false + account.Credentials = map[string]any{ + "access_token": "fresh-access", + "refresh_token": "fresh-refresh", + "_token_version": int64(2), + } + account.Status = StatusActive + account.Schedulable = true + } + if r.repairProxyOnErrorCAS { + r.repairProxyOnErrorCAS = false + proxyID := int64(902) + account.ProxyID = &proxyID + } + if account.Status != StatusActive || account.Platform != PlatformGrok || account.Type != AccountTypeOAuth || + !reflect.DeepEqual(account.Credentials, expectedCredentials) || !reflect.DeepEqual(account.ProxyID, expectedProxyID) { + return false, nil + } + r.setErrorCalls++ + r.lastErrorMessage = errorMsg + account.Status = StatusError + account.Schedulable = false + account.ErrorMessage = errorMsg + return true, nil +} + +func (r *tokenRefreshAccountRepo) UpdateGrokOAuthCredentialsIfUnchanged( + _ context.Context, + id int64, + expectedCredentials map[string]any, + expectedProxyID *int64, + credentials map[string]any, +) (bool, error) { + r.conditionalSuccessCalls++ + if r.conditionalSuccessErr != nil { + return false, r.conditionalSuccessErr + } + account := r.accountsByID[id] + if account != nil && r.mutateSchedulingOnSuccessCAS { + r.mutateSchedulingOnSuccessCAS = false + account.Status = StatusDisabled + account.Schedulable = false + resetAt := time.Now().Add(30 * time.Minute) + account.RateLimitResetAt = &resetAt + } + if account == nil || account.Platform != PlatformGrok || + account.Type != AccountTypeOAuth || !reflect.DeepEqual(account.Credentials, expectedCredentials) || + !reflect.DeepEqual(account.ProxyID, expectedProxyID) { + return false, nil + } + r.updateCalls++ + r.updateCredentialsCalls++ + account.Credentials = shallowCopyMap(credentials) + r.lastAccount = account + if r.cancelOnUpdate != nil { + r.cancelOnUpdate() + } + return true, nil +} + +func (r *tokenRefreshAccountRepo) SetGrokOAuthRefreshTempUnschedulableIfCredentialsUnchanged( + _ context.Context, + id int64, + expectedCredentials map[string]any, + expectedProxyID *int64, + until time.Time, + reason string, +) (bool, error) { + r.conditionalTempCalls++ + if r.conditionalTempErr != nil { + return false, r.conditionalTempErr + } + account := r.accountsByID[id] + if account == nil { + return false, nil + } + if r.reauthorizeOnTempCAS { + r.reauthorizeOnTempCAS = false + account.Credentials = map[string]any{ + "access_token": "fresh-access", + "refresh_token": "fresh-refresh", + "_token_version": int64(2), + } + account.Status = StatusActive + account.Schedulable = true + } + if r.repairProxyOnTempCAS { + r.repairProxyOnTempCAS = false + proxyID := int64(902) + account.ProxyID = &proxyID + } + if account.Status != StatusActive || account.Platform != PlatformGrok || account.Type != AccountTypeOAuth || + !reflect.DeepEqual(account.Credentials, expectedCredentials) || !reflect.DeepEqual(account.ProxyID, expectedProxyID) { + return false, nil + } + r.setTempUnschedCalls++ + r.lastTempUnschedReason = reason + account.TempUnschedulableUntil = &until + account.TempUnschedulableReason = reason + return true, nil } func (r *tokenRefreshAccountRepo) UpdateExtra(ctx context.Context, id int64, updates map[string]any) error { @@ -87,15 +311,46 @@ func (r *tokenRefreshAccountRepo) UpdateExtra(ctx context.Context, id int64, upd } type tokenCacheInvalidatorStub struct { - calls int - err error + calls int + err error + ctxErr error + lastAccount *Account +} + +type tokenRefreshRuntimeBlocker struct { + blockCalls int + clearCalls int +} + +func (b *tokenRefreshRuntimeBlocker) BlockAccountScheduling(*Account, time.Time, string) { + b.blockCalls++ +} + +func (b *tokenRefreshRuntimeBlocker) ClearAccountSchedulingBlock(int64) { + b.clearCalls++ } func (s *tokenCacheInvalidatorStub) InvalidateToken(ctx context.Context, account *Account) error { s.calls++ + s.ctxErr = ctx.Err() + s.lastAccount = snapshotOAuthRefreshAccount(account) return s.err } +type tokenRefreshSchedulerCache struct { + SchedulerCache + setAccountCalls int + ctxErr error + lastAccount *Account +} + +func (s *tokenRefreshSchedulerCache) SetAccount(ctx context.Context, account *Account) error { + s.setAccountCalls++ + s.ctxErr = ctx.Err() + s.lastAccount = snapshotOAuthRefreshAccount(account) + return nil +} + type tempUnschedCacheStub struct { deleteCalls int setCalls int @@ -120,6 +375,7 @@ func (s *tempUnschedCacheStub) DeleteTempUnsched(ctx context.Context, accountID type tokenRefresherStub struct { credentials map[string]any err error + calls int } func (r *tokenRefresherStub) CanRefresh(account *Account) bool { @@ -131,6 +387,7 @@ func (r *tokenRefresherStub) NeedsRefresh(account *Account, refreshWindowDuratio } func (r *tokenRefresherStub) Refresh(ctx context.Context, account *Account) (map[string]any, error) { + r.calls++ if r.err != nil { return nil, r.err } @@ -562,7 +819,7 @@ func TestTokenRefreshService_RefreshWithRetry_AntigravityNonRetryableError(t *te err := service.refreshWithRetry(context.Background(), account, refresher, refresher, time.Hour) require.Error(t, err) require.Equal(t, 0, repo.updateCalls) - require.Equal(t, 0, invalidator.calls) + require.Equal(t, 1, invalidator.calls) require.Equal(t, 1, repo.setErrorCalls) // 不可重试错误应设置错误状态 } @@ -701,6 +958,8 @@ type mockTokenCacheForRefreshAPI struct { lockResult bool lockErr error releaseCalls int + deleteCalls int + deleteCtxErr error } func (m *mockTokenCacheForRefreshAPI) GetAccessToken(_ context.Context, _ string) (string, error) { @@ -711,7 +970,9 @@ func (m *mockTokenCacheForRefreshAPI) SetAccessToken(_ context.Context, _ string return nil } -func (m *mockTokenCacheForRefreshAPI) DeleteAccessToken(_ context.Context, _ string) error { +func (m *mockTokenCacheForRefreshAPI) DeleteAccessToken(ctx context.Context, _ string) error { + m.deleteCalls++ + m.deleteCtxErr = ctx.Err() return nil } @@ -726,6 +987,11 @@ func (m *mockTokenCacheForRefreshAPI) ReleaseRefreshLock(_ context.Context, _ st // buildPathAService 构建注入了 refreshAPI 的 service(Path A 测试辅助) func buildPathAService(repo *tokenRefreshAccountRepo, cache GeminiTokenCache, invalidator TokenCacheInvalidator) (*TokenRefreshService, *tokenRefresherStub) { + for _, account := range repo.accountsByID { + if account != nil && account.Status == "" { + account.Status = StatusActive + } + } cfg := &config.Config{ TokenRefresh: config.TokenRefreshConfig{ MaxRetries: 1, @@ -750,6 +1016,7 @@ func TestPathA_Success(t *testing.T) { ID: 100, Platform: PlatformGemini, Type: AccountTypeOAuth, + Status: StatusActive, } repo := &tokenRefreshAccountRepo{} repo.accountsByID = map[int64]*Account{account.ID: account} @@ -765,12 +1032,217 @@ func TestPathA_Success(t *testing.T) { require.Equal(t, 1, cache.releaseCalls) // 锁被释放 } +func TestPathA_GrokSuccessPersistenceFailureContainsProviderWithoutRetryOrMutation(t *testing.T) { + account := &Account{ + ID: 110, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Credentials: map[string]any{ + "access_token": "attempted-access", + "refresh_token": "attempted-refresh", + }, + } + repo := &tokenRefreshAccountRepo{ + conditionalSuccessErr: errors.New("database unavailable after provider success"), + } + repo.accountsByID = map[int64]*Account{account.ID: account} + cfg := &config.Config{TokenRefresh: config.TokenRefreshConfig{ + MaxRetries: 3, + RetryBackoffSeconds: 0, + }} + svc := NewTokenRefreshService(repo, nil, nil, nil, nil, nil, nil, cfg, nil) + svc.SetRefreshAPI(NewOAuthRefreshAPI(repo, nil)) + refresher := &tokenRefresherStub{credentials: map[string]any{ + "access_token": "provider-access", + "refresh_token": "provider-refresh", + }} + + err := svc.refreshWithRetry(context.Background(), account, refresher, refresher, time.Hour) + + var containmentErr *providerCycleContainmentRefreshError + require.ErrorAs(t, err, &containmentErr) + require.Equal(t, 1, refresher.calls, "a provider-issued rotated token must never be retried after persistence fails") + require.Equal(t, 1, repo.conditionalSuccessCalls) + require.Zero(t, repo.conditionalErrorCalls) + require.Zero(t, repo.conditionalTempCalls) + require.Equal(t, StatusActive, account.Status) + require.Equal(t, "attempted-refresh", account.GetGrokRefreshToken()) +} + +func TestPathA_GrokSuccessPublishesDurableSchedulingState(t *testing.T) { + account := &Account{ + ID: 111, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{ + "access_token": "attempted-access", + "refresh_token": "attempted-refresh", + }, + } + repo := &tokenRefreshAccountRepo{ + snapshotReads: true, + mutateSchedulingOnSuccessCAS: true, + } + repo.accountsByID = map[int64]*Account{account.ID: account} + scheduler := &tokenRefreshSchedulerCache{} + cfg := &config.Config{TokenRefresh: config.TokenRefreshConfig{MaxRetries: 1}} + svc := NewTokenRefreshService(repo, nil, nil, nil, nil, nil, scheduler, cfg, nil) + svc.SetRefreshAPI(NewOAuthRefreshAPI(repo, nil)) + refresher := &tokenRefresherStub{credentials: map[string]any{ + "access_token": "provider-access", + "refresh_token": "provider-refresh", + }} + + err := svc.refreshWithRetry(context.Background(), account, refresher, refresher, time.Hour) + + require.NoError(t, err) + require.Equal(t, StatusDisabled, repo.accountsByID[account.ID].Status) + require.False(t, repo.accountsByID[account.ID].Schedulable) + require.NotNil(t, repo.accountsByID[account.ID].RateLimitResetAt) + require.Equal(t, 1, scheduler.setAccountCalls) + require.NotNil(t, scheduler.lastAccount) + require.Equal(t, StatusDisabled, scheduler.lastAccount.Status) + require.False(t, scheduler.lastAccount.Schedulable) + require.NotNil(t, scheduler.lastAccount.RateLimitResetAt, + "post-refresh cache publication must preserve the durable concurrent exclusion state") +} + +func TestPathA_GrokCancelAfterSuccessCASUsesDetachedDurableStateAndInvalidatesCache(t *testing.T) { + account := &Account{ + ID: 112, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{ + "access_token": "attempted-access", + "refresh_token": "attempted-refresh", + }, + } + ctx, cancel := context.WithCancel(context.Background()) + repo := &tokenRefreshAccountRepo{ + cancelOnUpdate: cancel, + snapshotReads: true, + respectReadContext: true, + mutateSchedulingOnSuccessCAS: true, + } + repo.accountsByID = map[int64]*Account{account.ID: account} + invalidator := &tokenCacheInvalidatorStub{} + scheduler := &tokenRefreshSchedulerCache{} + cache := &mockTokenCacheForRefreshAPI{lockResult: true} + cfg := &config.Config{TokenRefresh: config.TokenRefreshConfig{MaxRetries: 1}} + svc := NewTokenRefreshService(repo, nil, nil, nil, nil, invalidator, scheduler, cfg, nil) + svc.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache)) + refresher := &tokenRefresherStub{credentials: map[string]any{ + "access_token": "provider-access", + "refresh_token": "provider-refresh", + }} + + err := svc.refreshWithRetry(ctx, account, refresher, refresher, time.Hour) + + require.ErrorIs(t, err, context.Canceled) + require.Equal(t, 1, repo.conditionalSuccessCalls) + require.Equal(t, "provider-refresh", repo.accountsByID[account.ID].GetGrokRefreshToken()) + require.Equal(t, 1, cache.deleteCalls) + require.NoError(t, cache.deleteCtxErr) + require.Equal(t, 1, invalidator.calls, "the pre-rotation access-token cache must be invalidated after committed CAS") + require.NoError(t, invalidator.ctxErr) + require.NotNil(t, invalidator.lastAccount) + require.Equal(t, "provider-refresh", invalidator.lastAccount.GetGrokRefreshToken()) + require.Equal(t, StatusDisabled, invalidator.lastAccount.Status) + require.Equal(t, 1, scheduler.setAccountCalls) + require.NoError(t, scheduler.ctxErr) + require.NotNil(t, scheduler.lastAccount) + require.Equal(t, StatusDisabled, scheduler.lastAccount.Status) + require.False(t, scheduler.lastAccount.Schedulable) + require.NotNil(t, scheduler.lastAccount.RateLimitResetAt) +} + +func TestTokenRefreshService_PersistedSuccessCrossingAttemptDeadlineStaysSuccessful(t *testing.T) { + account := &Account{ + ID: 113, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{ + "access_token": "attempted-access", + "refresh_token": "attempted-refresh", + }, + } + repo := &tokenRefreshAccountRepo{ + snapshotReads: true, + durableReadDelay: 30 * time.Millisecond, + } + repo.accountsByID = map[int64]*Account{account.ID: account} + scheduler := &tokenRefreshSchedulerCache{} + svc := &TokenRefreshService{ + accountRepo: repo, + refreshAPI: NewOAuthRefreshAPI(repo, nil), + refreshPolicy: DefaultBackgroundRefreshPolicy(), + cfg: &config.TokenRefreshConfig{MaxRetries: 1, ProviderFailureThreshold: 1}, + schedulerCache: scheduler, + attemptTimeoutOverride: 10 * time.Millisecond, + } + refresher := &tokenRefresherStub{credentials: map[string]any{ + "access_token": "provider-access", + "refresh_token": "provider-refresh", + }} + state := &tokenRefreshProviderState{ + service: svc, + rateGate: newTokenRefreshRateGate(10000), + poolGate: newTokenRefreshConcurrencyGate(1), + } + + err := svc.refreshWithRetryWithRateGate(context.Background(), account, refresher, refresher, time.Hour, state) + state.recordResult(err) + + require.NoError(t, err) + require.Equal(t, 1, refresher.calls, "durably persisted success must not retry after only the internal attempt deadline elapsed") + require.Equal(t, 1, repo.conditionalSuccessCalls) + require.Zero(t, repo.conditionalTempCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.False(t, state.isTripped(), "a durable success must not count toward the provider breaker") + require.Equal(t, "provider-refresh", repo.accountsByID[account.ID].GetGrokRefreshToken()) + require.Equal(t, 1, scheduler.setAccountCalls) +} + +func TestPathA_ParentCancellationAfterPersistStillSynchronizesCacheState(t *testing.T) { + account := &Account{ + ID: 109, + Platform: PlatformGemini, + Type: AccountTypeOAuth, + Status: StatusActive, + } + ctx, cancel := context.WithCancel(context.Background()) + repo := &tokenRefreshAccountRepo{cancelOnUpdate: cancel} + repo.accountsByID = map[int64]*Account{account.ID: account} + invalidator := &tokenCacheInvalidatorStub{} + scheduler := &tokenRefreshSchedulerCache{} + cache := &mockTokenCacheForRefreshAPI{lockResult: true} + service, refresher := buildPathAService(repo, cache, invalidator) + service.schedulerCache = scheduler + + err := service.refreshWithRetry(ctx, account, refresher, refresher, time.Hour) + + require.ErrorIs(t, err, context.Canceled) + require.Equal(t, 1, repo.updateCredentialsCalls, "credentials were durably persisted before cancellation") + require.Equal(t, 1, invalidator.calls) + require.NoError(t, invalidator.ctxErr, "post-persist invalidation must use bounded cleanup context") + require.Equal(t, 1, scheduler.setAccountCalls) + require.NoError(t, scheduler.ctxErr, "scheduler sync must use bounded cleanup context") +} + // TestPathA_LockHeld 锁被其他 worker 持有 → 返回 errRefreshSkipped func TestPathA_LockHeld(t *testing.T) { account := &Account{ ID: 101, Platform: PlatformGemini, Type: AccountTypeOAuth, + Status: StatusActive, } repo := &tokenRefreshAccountRepo{} invalidator := &tokenCacheInvalidatorStub{} @@ -791,6 +1263,7 @@ func TestPathA_AlreadyRefreshed(t *testing.T) { ID: 102, Platform: PlatformGemini, Type: AccountTypeOAuth, + Status: StatusActive, } repo := &tokenRefreshAccountRepo{} repo.accountsByID = map[int64]*Account{account.ID: account} @@ -830,6 +1303,7 @@ func TestPathA_NonRetryableError(t *testing.T) { ID: 103, Platform: PlatformGemini, Type: AccountTypeOAuth, + Status: StatusActive, } repo := &tokenRefreshAccountRepo{} repo.accountsByID = map[int64]*Account{account.ID: account} @@ -846,7 +1320,7 @@ func TestPathA_NonRetryableError(t *testing.T) { require.Error(t, err) require.Equal(t, 1, repo.setErrorCalls) // 应标记 error 状态 require.Equal(t, 0, repo.updateCalls) // 不应更新 credentials - require.Equal(t, 0, invalidator.calls) // 不应触发缓存失效 + require.Equal(t, 1, invalidator.calls) // 永久凭证失败后必须失效旧 token 缓存 } // TestPathA_RetryableErrorExhausted 统一 API 路径可重试错误耗尽 → 不标记 error @@ -855,6 +1329,7 @@ func TestPathA_RetryableErrorExhausted(t *testing.T) { ID: 104, Platform: PlatformGemini, Type: AccountTypeOAuth, + Status: StatusActive, } repo := &tokenRefreshAccountRepo{} repo.accountsByID = map[int64]*Account{account.ID: account} @@ -882,12 +1357,263 @@ func TestPathA_RetryableErrorExhausted(t *testing.T) { require.Equal(t, 0, invalidator.calls) // 不应触发缓存失效 } +func TestPathA_GrokPermanentFailureCASLetsConcurrentAccountRepairWin(t *testing.T) { + tests := []struct { + name string + configure func(*tokenRefreshAccountRepo) + assert func(*testing.T, *Account) + }{ + { + name: "credential reauthorization", + configure: func(repo *tokenRefreshAccountRepo) { + repo.reauthorizeOnErrorCAS = true + }, + assert: func(t *testing.T, account *Account) { + require.Equal(t, "fresh-refresh", account.GetGrokRefreshToken()) + }, + }, + { + name: "proxy repair", + configure: func(repo *tokenRefreshAccountRepo) { + repo.repairProxyOnErrorCAS = true + }, + assert: func(t *testing.T, account *Account) { + require.NotNil(t, account.ProxyID) + require.Equal(t, int64(902), *account.ProxyID) + require.Equal(t, "attempted-refresh", account.GetGrokRefreshToken(), + "proxy-only repair must prove the proxy fingerprint independently of credentials") + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + proxyID := int64(901) + account := &Account{ + ID: 120, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + ProxyID: &proxyID, + Credentials: map[string]any{ + "access_token": "attempted-access", + "refresh_token": "attempted-refresh", + "_token_version": int64(1), + }, + } + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + tt.configure(repo) + invalidator := &tokenCacheInvalidatorStub{} + cache := &mockTokenCacheForRefreshAPI{lockResult: true} + service, _ := buildPathAService(repo, cache, invalidator) + blocker := &tokenRefreshRuntimeBlocker{} + service.SetAccountRuntimeBlocker(blocker) + refresher := &tokenRefresherStub{err: errors.New("invalid_grant: revoked")} + + err := service.refreshWithRetry(context.Background(), account, refresher, refresher, time.Hour) + + require.ErrorIs(t, err, errRefreshSkipped) + require.Equal(t, 1, repo.conditionalErrorCalls) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, blocker.blockCalls) + require.Zero(t, invalidator.calls, "a stale permanent failure must not invalidate newly repaired credentials") + require.Equal(t, StatusActive, account.Status) + require.True(t, account.Schedulable) + tt.assert(t, account) + }) + } +} + +func TestPathA_GrokTransientFailureCASLetsConcurrentAccountRepairWin(t *testing.T) { + tests := []struct { + name string + configure func(*tokenRefreshAccountRepo) + assert func(*testing.T, *Account) + }{ + { + name: "credential reauthorization", + configure: func(repo *tokenRefreshAccountRepo) { + repo.reauthorizeOnTempCAS = true + }, + assert: func(t *testing.T, account *Account) { + require.Equal(t, "fresh-refresh", account.GetGrokRefreshToken()) + }, + }, + { + name: "proxy repair", + configure: func(repo *tokenRefreshAccountRepo) { + repo.repairProxyOnTempCAS = true + }, + assert: func(t *testing.T, account *Account) { + require.NotNil(t, account.ProxyID) + require.Equal(t, int64(902), *account.ProxyID) + require.Equal(t, "attempted-refresh", account.GetGrokRefreshToken(), + "proxy-only repair must prove the proxy fingerprint independently of credentials") + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + proxyID := int64(901) + account := &Account{ + ID: 121, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + ProxyID: &proxyID, + Credentials: map[string]any{ + "access_token": "attempted-access", + "refresh_token": "attempted-refresh", + "_token_version": int64(1), + }, + } + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + tt.configure(repo) + invalidator := &tokenCacheInvalidatorStub{} + cache := &mockTokenCacheForRefreshAPI{lockResult: true} + service, _ := buildPathAService(repo, cache, invalidator) + blocker := &tokenRefreshRuntimeBlocker{} + service.SetAccountRuntimeBlocker(blocker) + refresher := &tokenRefresherStub{err: errors.New("temporary provider timeout")} + + err := service.refreshWithRetry(context.Background(), account, refresher, refresher, time.Hour) + + require.ErrorIs(t, err, errRefreshSkipped) + require.Equal(t, 1, repo.conditionalTempCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Zero(t, blocker.blockCalls) + require.Equal(t, StatusActive, account.Status) + require.True(t, account.Schedulable) + require.Nil(t, account.TempUnschedulableUntil) + tt.assert(t, account) + }) + } +} + +func TestTokenRefreshService_GrokMissingConditionalMutationContractContainsProviderCycle(t *testing.T) { + tests := []struct { + name string + refreshErr error + }{ + {name: "permanent failure", refreshErr: errors.New("invalid_grant: revoked")}, + {name: "transient failure", refreshErr: errors.New("temporary provider timeout")}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + svc := &TokenRefreshService{ + accountRepo: &mockAccountRepoForGemini{}, + refreshPolicy: DefaultBackgroundRefreshPolicy(), + cfg: &config.TokenRefreshConfig{MaxRetries: 1}, + } + account := &Account{ + ID: 122, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{"refresh_token": "attempted"}, + } + refresher := &tokenRefresherStub{err: tt.refreshErr} + + err := svc.refreshWithRetry(context.Background(), account, refresher, nil, time.Hour) + + var providerErr *providerConfigurationRefreshError + require.ErrorAs(t, err, &providerErr) + state := &tokenRefreshProviderState{service: svc} + state.recordResult(err) + require.True(t, state.isTripped(), "a missing safety contract must stop the provider cycle") + require.Equal(t, StatusActive, account.Status) + require.True(t, account.Schedulable) + }) + } +} + +func TestTokenRefreshService_GrokConditionalMutationErrorsContainProviderCycle(t *testing.T) { + tests := []struct { + name string + upstreamErr error + configureRepo func(*tokenRefreshAccountRepo, error) + expectedCASCalls func(*tokenRefreshAccountRepo) int + }{ + { + name: "permanent failure", + upstreamErr: errors.New("invalid_grant: revoked"), + configureRepo: func(repo *tokenRefreshAccountRepo, casErr error) { + repo.conditionalErrorErr = casErr + }, + expectedCASCalls: func(repo *tokenRefreshAccountRepo) int { return repo.conditionalErrorCalls }, + }, + { + name: "transient failure", + upstreamErr: errors.New("temporary provider timeout"), + configureRepo: func(repo *tokenRefreshAccountRepo, casErr error) { + repo.conditionalTempErr = casErr + }, + expectedCASCalls: func(repo *tokenRefreshAccountRepo) int { return repo.conditionalTempCalls }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := &Account{ + ID: 123, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{"refresh_token": "attempted"}, + } + casErr := errors.New("conditional account mutation unavailable") + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + tt.configureRepo(repo, casErr) + invalidator := &tokenCacheInvalidatorStub{} + blocker := &tokenRefreshRuntimeBlocker{} + svc := &TokenRefreshService{ + accountRepo: repo, + refreshPolicy: DefaultBackgroundRefreshPolicy(), + cfg: &config.TokenRefreshConfig{MaxRetries: 1}, + cacheInvalidator: invalidator, + } + svc.SetAccountRuntimeBlocker(blocker) + refresher := &tokenRefresherStub{err: tt.upstreamErr} + + err := svc.refreshWithRetry(context.Background(), account, refresher, nil, time.Hour) + + var containmentErr *providerCycleContainmentRefreshError + require.ErrorAs(t, err, &containmentErr) + require.ErrorIs(t, err, casErr) + require.NotErrorIs(t, err, tt.upstreamErr, "a CAS execution failure must replace the stale upstream classification") + var permanentErr *accountPermanentRefreshError + require.False(t, errors.As(err, &permanentErr)) + require.Equal(t, 1, tt.expectedCASCalls(repo)) + + state := &tokenRefreshProviderState{service: svc} + state.recordResult(err) + require.True(t, state.isTripped(), "an unsafe mutation result must stop the provider cycle immediately") + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Zero(t, blocker.blockCalls) + require.Zero(t, invalidator.calls) + require.Equal(t, StatusActive, account.Status) + require.True(t, account.Schedulable) + }) + } +} + // TestPathA_DBUpdateFailed 统一 API 路径 DB 更新失败 → 返回 error,不执行 postRefreshActions func TestPathA_DBUpdateFailed(t *testing.T) { account := &Account{ ID: 105, Platform: PlatformGemini, Type: AccountTypeOAuth, + Status: StatusActive, } repo := &tokenRefreshAccountRepo{updateErr: errors.New("db connection lost")} repo.accountsByID = map[int64]*Account{account.ID: account} @@ -898,7 +1624,7 @@ func TestPathA_DBUpdateFailed(t *testing.T) { err := service.refreshWithRetry(context.Background(), account, refresher, refresher, time.Hour) require.Error(t, err) - require.Contains(t, err.Error(), "DB update failed") + require.ErrorIs(t, err, errOAuthRefreshCredentialPersist) require.Equal(t, 1, repo.updateCalls) // DB 更新被尝试 require.Equal(t, 0, invalidator.calls) // DB 失败时不应触发缓存失效 } diff --git a/backend/internal/service/wire.go b/backend/internal/service/wire.go index d5d9124ec2..e4318e6079 100644 --- a/backend/internal/service/wire.go +++ b/backend/internal/service/wire.go @@ -131,8 +131,67 @@ func ProvideOpenAIQuotaService( proxyRepo ProxyRepository, tokenProvider *OpenAITokenProvider, privacyClientFactory PrivacyClientFactory, + openAIGatewayService *OpenAIGatewayService, ) *OpenAIQuotaService { - return NewOpenAIQuotaService(accountRepo, proxyRepo, tokenProvider, privacyClientFactory) + service := NewOpenAIQuotaService(accountRepo, proxyRepo, tokenProvider, privacyClientFactory) + service.agentIdentityWS = openAIGatewayService + return service +} + +func ProvideAccountUsageService( + accountRepo AccountRepository, + usageLogRepo UsageLogRepository, + usageFetcher ClaudeUsageFetcher, + geminiQuotaService *GeminiQuotaService, + antigravityQuotaFetcher *AntigravityQuotaFetcher, + grokQuotaFetcher *GrokQuotaFetcher, + grokQuotaService *GrokQuotaService, + openAIQuotaService *OpenAIQuotaService, + cache *UsageCache, + identityCache IdentityCache, + tlsFPProfileService *TLSFingerprintProfileService, + openAIGatewayService *OpenAIGatewayService, +) *AccountUsageService { + service := NewAccountUsageService( + accountRepo, + usageLogRepo, + usageFetcher, + geminiQuotaService, + antigravityQuotaFetcher, + grokQuotaFetcher, + grokQuotaService, + openAIQuotaService, + cache, + identityCache, + tlsFPProfileService, + ) + service.agentIdentityWS = openAIGatewayService + return service +} + +func ProvideAccountTestService( + accountRepo AccountRepository, + geminiTokenProvider *GeminiTokenProvider, + claudeTokenProvider *ClaudeTokenProvider, + grokTokenProvider *GrokTokenProvider, + antigravityGatewayService *AntigravityGatewayService, + httpUpstream HTTPUpstream, + cfg *config.Config, + tlsFPProfileService *TLSFingerprintProfileService, + openAIGatewayService *OpenAIGatewayService, +) *AccountTestService { + service := NewAccountTestService( + accountRepo, + geminiTokenProvider, + claudeTokenProvider, + grokTokenProvider, + antigravityGatewayService, + httpUpstream, + cfg, + tlsFPProfileService, + ) + service.agentIdentityWS = openAIGatewayService + return service } func ProvideGrokQuotaService( @@ -186,7 +245,7 @@ func ProvideGrokTokenProvider( p := NewGrokTokenProvider(accountRepo, tokenCache) executor := NewGrokTokenRefresher(grokOAuthService) p.SetRefreshAPI(refreshAPI, executor) - p.SetRefreshPolicy(AntigravityProviderRefreshPolicy()) + p.SetRefreshPolicy(GrokProviderRefreshPolicy()) p.SetTempUnschedCache(tempUnschedCache) return p } @@ -602,8 +661,8 @@ var ProviderSet = wire.NewSet( ProvideClaudeTokenProvider, NewAntigravityGatewayService, ProvideRateLimitService, - NewAccountUsageService, - NewAccountTestService, + ProvideAccountUsageService, + ProvideAccountTestService, ProvideSettingService, NewDataManagementService, ProvideBackupService, @@ -628,6 +687,7 @@ var ProviderSet = wire.NewSet( NewCRSSyncService, ProvideUpdateService, ProvideTokenRefreshService, + wire.Bind(new(GrokOAuthReconciler), new(*TokenRefreshService)), ProvideAccountExpiryService, ProvideProxyExpiryService, ProvideSubscriptionExpiryService, diff --git a/backend/internal/web/embed_on.go b/backend/internal/web/embed_on.go index 716fb77e75..4bd984301b 100644 --- a/backend/internal/web/embed_on.go +++ b/backend/internal/web/embed_on.go @@ -136,7 +136,6 @@ func (s *FrontendServer) tryServeOverride(c *gin.Context, cleanPath string) bool if err != nil || info.IsDir() { return false } - applyStaticAssetCacheHeaders(c.Writer.Header(), cleanPath) c.File(filePath) c.Abort() return true @@ -295,7 +294,6 @@ func tryServeOverrideFile(c *gin.Context, overrideDir, cleanPath string) bool { if err != nil || info.IsDir() { return false } - applyStaticAssetCacheHeaders(c.Writer.Header(), cleanPath) c.File(filePath) c.Abort() return true @@ -310,6 +308,7 @@ func shouldBypassEmbeddedFrontend(path string) bool { strings.HasPrefix(trimmed, "/antigravity/") || strings.HasPrefix(trimmed, "/setup/") || trimmed == "/health" || + trimmed == "/models" || trimmed == "/responses" || strings.HasPrefix(trimmed, "/responses/") || trimmed == "/alpha/search" || diff --git a/backend/internal/web/embed_test.go b/backend/internal/web/embed_test.go index b27bbfc9dc..769b856ac1 100644 --- a/backend/internal/web/embed_test.go +++ b/backend/internal/web/embed_test.go @@ -5,8 +5,11 @@ package web import ( "bytes" "context" + "io/fs" "net/http" "net/http/httptest" + "os" + "path/filepath" "strings" "testing" @@ -440,6 +443,37 @@ func TestFrontendServer_InvalidateCache(t *testing.T) { }) } +func TestOverrideFilesNeverReceiveImmutableCacheHeaders(t *testing.T) { + t.Parallel() + + overrideDir := t.TempDir() + cleanPath := "assets/index-AbCd1234.js" + filePath := filepath.Join(overrideDir, cleanPath) + require.NoError(t, os.MkdirAll(filepath.Dir(filePath), 0o755)) + require.NoError(t, os.WriteFile(filePath, []byte("override"), 0o644)) + + t.Run("frontend_server_override", func(t *testing.T) { + t.Parallel() + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodGet, "/"+cleanPath, nil) + + server := &FrontendServer{overrideDir: overrideDir} + assert.True(t, server.tryServeOverride(c, cleanPath)) + assert.Empty(t, w.Header().Get("Cache-Control")) + }) + + t.Run("legacy_override", func(t *testing.T) { + t.Parallel() + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodGet, "/"+cleanPath, nil) + + assert.True(t, tryServeOverrideFile(c, overrideDir, cleanPath)) + assert.Empty(t, w.Header().Get("Cache-Control")) + }) +} + func TestFrontendServer_Middleware(t *testing.T) { t.Run("skips_api_routes", func(t *testing.T) { provider := &mockSettingsProvider{ @@ -451,6 +485,7 @@ func TestFrontendServer_Middleware(t *testing.T) { apiPaths := []string{ "/api/v1/users", + "/models", "/v1/models", "/v1beta/chat", "/backend-api/codex/responses", @@ -585,6 +620,26 @@ func TestFrontendServer_Middleware(t *testing.T) { assert.Equal(t, http.StatusOK, w.Code) assert.Contains(t, w.Header().Get("Content-Type"), "image/png") + assert.Empty(t, w.Header().Get("Cache-Control")) + + entries, err := fs.ReadDir(server.distFS, "assets") + require.NoError(t, err) + fingerprintedPath := "" + for _, entry := range entries { + candidate := "assets/" + entry.Name() + if !entry.IsDir() && isFingerprintedEmbeddedAssetPath(candidate) { + fingerprintedPath = candidate + break + } + } + require.NotEmpty(t, fingerprintedPath) + + assetWriter := httptest.NewRecorder() + assetRequest := httptest.NewRequest(http.MethodGet, "/"+fingerprintedPath, nil) + router.ServeHTTP(assetWriter, assetRequest) + + assert.Equal(t, http.StatusOK, assetWriter.Code) + assert.Equal(t, staticAssetsCacheControl, assetWriter.Header().Get("Cache-Control")) }) } @@ -692,6 +747,7 @@ func TestServeEmbeddedFrontend(t *testing.T) { apiPaths := []string{ "/api/users", + "/models", "/v1/models", "/v1beta/chat", "/backend-api/codex/responses", diff --git a/backend/internal/web/static_cache.go b/backend/internal/web/static_cache.go index 09abc8642a..e5736d1660 100644 --- a/backend/internal/web/static_cache.go +++ b/backend/internal/web/static_cache.go @@ -4,27 +4,49 @@ package web import ( "net/http" + "path" "strings" ) -// staticAssetsCacheControl matches deploy/Caddyfile for hashed frontend assets. -// Vite emits content-hashed filenames under assets/, so long-lived immutable -// caching is safe without relying on a reverse proxy. +// Vite emits content-hashed filenames under assets/, so the backend can apply +// immutable caching without relying on a reverse proxy to classify paths. const staticAssetsCacheControl = "public, max-age=31536000, immutable" -// isLongCacheStaticPath reports whether a cleaned URL path (no leading slash) -// should receive long-lived Cache-Control headers. Aligned with deploy/Caddyfile. -func isLongCacheStaticPath(cleanPath string) bool { +// isFingerprintedEmbeddedAssetPath reports whether a cleaned URL path refers to +// a Vite asset whose filename contains the default eight-character build hash. +func isFingerprintedEmbeddedAssetPath(cleanPath string) bool { cleanPath = strings.TrimPrefix(cleanPath, "/") - return strings.HasPrefix(cleanPath, "assets/") || - cleanPath == "logo.png" || - cleanPath == "favicon.ico" + if !strings.HasPrefix(cleanPath, "assets/") { + return false + } + + filename := path.Base(cleanPath) + extension := path.Ext(filename) + stem := strings.TrimSuffix(filename, extension) + const fingerprintLength = 8 + delimiterIndex := len(stem) - fingerprintLength - 1 + if extension == "" || delimiterIndex < 1 || stem[delimiterIndex] != '-' { + return false + } + + // Vite hashes use URL-safe characters and are stable for immutable caching. + fingerprint := stem[delimiterIndex+1:] + for _, char := range fingerprint { + if (char >= 'a' && char <= 'z') || + (char >= 'A' && char <= 'Z') || + (char >= '0' && char <= '9') || + char == '_' || char == '-' { + continue + } + return false + } + return true } // applyStaticAssetCacheHeaders sets Cache-Control for long-cacheable static paths. // index.html / SPA routes must keep no-cache and are not handled here. func applyStaticAssetCacheHeaders(header http.Header, cleanPath string) { - if header == nil || !isLongCacheStaticPath(cleanPath) { + if header == nil || !isFingerprintedEmbeddedAssetPath(cleanPath) { return } header.Set("Cache-Control", staticAssetsCacheControl) diff --git a/backend/internal/web/static_cache_test.go b/backend/internal/web/static_cache_test.go index 130347c41e..dae683c3e3 100644 --- a/backend/internal/web/static_cache_test.go +++ b/backend/internal/web/static_cache_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/assert" ) -func TestIsLongCacheStaticPath(t *testing.T) { +func TestIsFingerprintedEmbeddedAssetPath(t *testing.T) { t.Parallel() cases := []struct { @@ -17,12 +17,16 @@ func TestIsLongCacheStaticPath(t *testing.T) { path string want bool }{ - {name: "hashed_js", path: "assets/index-abc123.js", want: true}, - {name: "hashed_css", path: "assets/app-def456.css", want: true}, - {name: "nested_asset", path: "assets/vendor/chunk.js", want: true}, - {name: "leading_slash_asset", path: "/assets/index.js", want: true}, - {name: "logo", path: "logo.png", want: true}, - {name: "favicon", path: "favicon.ico", want: true}, + {name: "fingerprinted_js", path: "assets/index-AbCd1234.js", want: true}, + {name: "fingerprinted_css", path: "assets/app-a1B2c3D4.css", want: true}, + {name: "fingerprinted_url_safe_hash", path: "assets/app-aB1-2_Cd.css", want: true}, + {name: "nested_fingerprinted_asset", path: "assets/vendor/chunk-AbCd1234.js", want: true}, + {name: "leading_slash_fingerprinted_asset", path: "/assets/index-AbCd1234.js", want: true}, + {name: "unhashed_asset", path: "assets/index.js", want: false}, + {name: "short_suffix", path: "assets/index-abc123.js", want: false}, + {name: "logo", path: "logo.png", want: false}, + {name: "favicon", path: "favicon.ico", want: false}, + {name: "fingerprint_outside_assets", path: "downloads/index-AbCd1234.js", want: false}, {name: "index_html", path: "index.html", want: false}, {name: "spa_route", path: "dashboard", want: false}, {name: "assets_prefix_only", path: "assets", want: false}, @@ -33,7 +37,7 @@ func TestIsLongCacheStaticPath(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { t.Parallel() - assert.Equal(t, tc.want, isLongCacheStaticPath(tc.path)) + assert.Equal(t, tc.want, isFingerprintedEmbeddedAssetPath(tc.path)) }) } } @@ -41,31 +45,27 @@ func TestIsLongCacheStaticPath(t *testing.T) { func TestApplyStaticAssetCacheHeaders(t *testing.T) { t.Parallel() - t.Run("sets_immutable_cache_for_assets", func(t *testing.T) { + t.Run("sets_immutable_cache_for_fingerprinted_asset", func(t *testing.T) { t.Parallel() header := make(http.Header) - applyStaticAssetCacheHeaders(header, "assets/index-abc.js") + applyStaticAssetCacheHeaders(header, "assets/index-AbCd1234.js") assert.Equal(t, staticAssetsCacheControl, header.Get("Cache-Control")) }) - t.Run("sets_immutable_cache_for_logo", func(t *testing.T) { - t.Parallel() - header := make(http.Header) - applyStaticAssetCacheHeaders(header, "logo.png") - assert.Equal(t, staticAssetsCacheControl, header.Get("Cache-Control")) - }) - - t.Run("skips_index_html", func(t *testing.T) { - t.Parallel() - header := make(http.Header) - applyStaticAssetCacheHeaders(header, "index.html") - assert.Empty(t, header.Get("Cache-Control")) - }) + for _, path := range []string{"assets/index.js", "logo.png", "favicon.ico", "index.html"} { + path := path + t.Run("skips_"+path, func(t *testing.T) { + t.Parallel() + header := make(http.Header) + applyStaticAssetCacheHeaders(header, path) + assert.Empty(t, header.Get("Cache-Control")) + }) + } t.Run("nil_header_is_noop", func(t *testing.T) { t.Parallel() assert.NotPanics(t, func() { - applyStaticAssetCacheHeaders(nil, "assets/x.js") + applyStaticAssetCacheHeaders(nil, "assets/index-AbCd1234.js") }) }) } diff --git a/deploy/Caddyfile b/deploy/Caddyfile index b643fe9b84..7da36ac8cb 100644 --- a/deploy/Caddyfile +++ b/deploy/Caddyfile @@ -1,21 +1,5 @@ # 修改为你的域名 api.sub2api.com { - # ========================================================================= - # 静态资源长期缓存(高优先级,放在最前面) - # 带 hash 的文件可以永久缓存,浏览器和 CDN 都会缓存 - # ========================================================================= - @static { - path /assets/* - path /logo.png - path /favicon.ico - } - header @static { - Cache-Control "public, max-age=31536000, immutable" - # 移除可能干扰缓存的头 - -Pragma - -Expires - } - # ========================================================================= # TLS 安全配置 # ========================================================================= diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index 4cf759497f..93fa6a2b59 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -155,6 +155,15 @@ gateway: # OpenAI/Codex upstream response header timeout (seconds, 0=disabled) # OpenAI/Codex 等待上游响应头超时时间(秒,0=禁用本地响应头超时) openai_response_header_timeout: 0 + # Native OpenAI HTTP Responses first semantic output timeout (seconds, 0=disabled) + # Includes response-header wait; does not apply to passthrough or WebSocket transports. + # A timed-out request may already have incurred upstream usage; account failover can therefore duplicate upstream billing. + # 超时请求可能已产生上游用量;切换账号重试可能导致上游重复计费。 + # Pre-output attempt staging is capped at 8 MiB; overflow fails over without exposing partial SSE data. + # 首次输出前的单次尝试暂存上限为 8 MiB;溢出时切号且不暴露不完整 SSE 数据。 + openai_first_output_timeout_seconds: 0 + # Optional high/xhigh/max override (seconds, 0=use the standard timeout) + openai_high_effort_first_output_timeout_seconds: 0 # Max request body size in bytes (default: 256MB) # 请求体最大字节数(默认 256MB) max_body_size: 268435456 @@ -257,6 +266,8 @@ gateway: # ingress 默认模式:off|ctx_pool|passthrough|http_bridge(仅 mode_router_v2_enabled=true 生效) # 兼容旧值:shared/dedicated 会按 ctx_pool 处理。 ingress_mode_default: ctx_pool + # 完整读取并解压首条客户端消息的总超时(秒);大请求或慢链路可调高到 120-300。 + client_first_message_timeout_seconds: 30 # Close a client WebSocket that stays idle between completed turns (seconds). Set 0 to disable. ingress_inter_turn_idle_timeout_seconds: 300 # Limit live client WebSocket ingress sessions per API key across all instances. Set 0 to disable. @@ -653,6 +664,24 @@ token_refresh: # Whether OpenAI refresh flow is allowed to sync linked Sora accounts # 是否允许 OpenAI 刷新流程同步覆盖 linked_openai_account_id 关联的 Sora 账号 token sync_linked_sora_accounts: false + # Candidate accounts loaded per cursor page (maximum 1000) + # 每个游标分页加载的候选账号数量(最大 1000) + candidate_page_size: 200 + # Maximum concurrent refresh attempts per provider (maximum 32) + # 每个平台的最大并发刷新数(最大 32) + provider_concurrency: 4 + # Per-provider refresh requests per second in each server process (maximum 100) + # 每个服务进程中每个平台每秒允许的刷新请求数(最大 100) + provider_qps: 2 + # Consecutive transient failures that contain a provider for the current cycle (maximum 100) + # 当前周期内触发平台级熔断的连续临时失败次数(最大 100) + provider_failure_threshold: 3 + # Timeout for one upstream refresh attempt, in seconds (maximum 300) + # 单次上游刷新尝试的超时时间(秒,最大 300) + attempt_timeout_seconds: 15 + # Total timeout for one background refresh cycle, in seconds (maximum 3600) + # 单个后台刷新周期的总超时时间(秒,最大 3600) + cycle_timeout_seconds: 240 # ============================================================================= # API Key Auth Cache Configuration diff --git a/deploy/test-caddyfile-cache.sh b/deploy/test-caddyfile-cache.sh new file mode 100755 index 0000000000..789e48ee2e --- /dev/null +++ b/deploy/test-caddyfile-cache.sh @@ -0,0 +1,18 @@ +#!/bin/sh +set -eu + +repo_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +caddyfile="$repo_root/deploy/Caddyfile" +active_config=$(sed 's/[[:space:]]*#.*$//' "$caddyfile") + +if printf '%s\n' "$active_config" | grep -Eiq 'Cache-Control.*immutable'; then + echo "Caddyfile must not force immutable caching; the backend owns asset cache policy" >&2 + exit 1 +fi + +if ! printf '%s\n' "$active_config" | grep -Eq '^[[:space:]]*reverse_proxy[[:space:]]+localhost:8080'; then + echo "Caddyfile must continue proxying all application routes to localhost:8080" >&2 + exit 1 +fi + +echo "Caddyfile preserves backend Cache-Control policy and reverse_proxy routing" diff --git a/frontend/src/api/__tests__/admin.accounts.duplicate.spec.ts b/frontend/src/api/__tests__/admin.accounts.duplicate.spec.ts new file mode 100644 index 0000000000..f6bc22c266 --- /dev/null +++ b/frontend/src/api/__tests__/admin.accounts.duplicate.spec.ts @@ -0,0 +1,59 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { post } = vi.hoisted(() => ({ + post: vi.fn() +})) + +vi.mock('@/api/client', () => ({ + apiClient: { post } +})) + +import { duplicate } from '@/api/admin/accounts' + +describe('admin account duplicate API', () => { + beforeEach(() => { + sessionStorage.clear() + post.mockReset() + post.mockResolvedValue({ data: { id: 43, name: 'primary (Copy)' } }) + vi.spyOn(globalThis.crypto, 'randomUUID').mockReturnValue('11111111-1111-4111-8111-111111111111') + }) + + it('sends a stable idempotency key with the duplicate request', async () => { + const account = await duplicate(42) + + expect(post).toHaveBeenCalledWith('/admin/accounts/42/duplicate', undefined, { + headers: { + 'Idempotency-Key': 'account-duplicate-42-11111111-1111-4111-8111-111111111111' + } + }) + expect(account).toEqual({ id: 43, name: 'primary (Copy)' }) + }) + + it('reuses the operation key after an ambiguous failed request', async () => { + post.mockRejectedValueOnce(new Error('network timeout')) + await expect(duplicate(99)).rejects.toThrow('network timeout') + + post.mockResolvedValueOnce({ data: { id: 100, name: 'retry (Copy)' } }) + await duplicate(99) + + expect(post).toHaveBeenCalledTimes(2) + const firstHeaders = post.mock.calls[0][2].headers + const secondHeaders = post.mock.calls[1][2].headers + expect(secondHeaders).toEqual(firstHeaders) + }) + + it('reuses the operation key after a page reload', async () => { + post.mockRejectedValueOnce(new Error('network timeout')) + await expect(duplicate(77)).rejects.toThrow('network timeout') + const firstHeaders = post.mock.calls[0][2].headers + + vi.resetModules() + post.mockResolvedValueOnce({ data: { id: 78, name: 'reload (Copy)' } }) + const { duplicate: duplicateAfterReload } = await import('@/api/admin/accounts') + await duplicateAfterReload(77) + + expect(post).toHaveBeenCalledTimes(2) + expect(post.mock.calls[1][2].headers).toEqual(firstHeaders) + expect(sessionStorage.length).toBe(0) + }) +}) diff --git a/frontend/src/api/__tests__/adminUIRequest.spec.ts b/frontend/src/api/__tests__/adminUIRequest.spec.ts index 9064a52f1a..fba7b3b180 100644 --- a/frontend/src/api/__tests__/adminUIRequest.spec.ts +++ b/frontend/src/api/__tests__/adminUIRequest.spec.ts @@ -2,7 +2,10 @@ import { describe, expect, it } from 'vitest' import { ADMIN_UI_REQUEST_HEADER, + USER_UI_REQUEST_HEADER, + isUserTimingAPIPath, shouldMarkAdminUIRequest, + shouldMarkUserUIRequest, } from '@/api/adminUIRequest' describe('Admin UI request marker', () => { @@ -36,3 +39,62 @@ describe('Admin UI request marker', () => { expect(shouldMarkAdminUIRequest(requestURL, pagePath)).toBe(false) }) }) + +describe('User UI request marker', () => { + it('uses the stable request header name', () => { + expect(USER_UI_REQUEST_HEADER).toBe('X-User-UI-Request') + }) + + it.each([ + '/auth/me', + '/auth/revoke-all-sessions', + '/auth/oauth/bind-token', + '/user', + '/user/profile', + '/user/password', + '/user/notify-email/send-code', + '/user/totp/status', + '/user/aff', + '/user/platform-quotas', + '/keys', + '/keys/12', + '/groups/available', + '/groups/rates', + '/channels/available', + '/usage', + '/usage/stats', + '/usage/dashboard/snapshot-v2', + '/announcements', + '/announcements/3/read', + '/redeem', + '/redeem/history', + '/subscriptions', + '/subscriptions/active', + '/channel-monitors', + '/channel-monitors/9/status', + '/payment/config', + '/payment/plans', + '/payment/orders', + '/payment/orders/my', + '/api/v1/auth/me', + '/api/v1/keys?page=1', + 'https://api.example.test/api/v1/payment/orders/1', + ])('marks user timing API %s', (requestURL) => { + expect(shouldMarkUserUIRequest(requestURL)).toBe(true) + expect(isUserTimingAPIPath(requestURL)).toBe(true) + }) + + it.each([ + '/auth/login', + '/settings/public', + '/admin/users', + '/groups', + '/channels', + '/payment/public/orders/verify', + '/payment/webhook/stripe', + '/api/v1/payment/public/orders/resolve', + '', + ])('does not mark non-user timing API %s', (requestURL) => { + expect(shouldMarkUserUIRequest(requestURL)).toBe(false) + }) +}) diff --git a/frontend/src/api/__tests__/client.spec.ts b/frontend/src/api/__tests__/client.spec.ts index b275cca34b..d1b619027e 100644 --- a/frontend/src/api/__tests__/client.spec.ts +++ b/frontend/src/api/__tests__/client.spec.ts @@ -170,6 +170,58 @@ describe('API Client', () => { const config = adapter.mock.calls[0][0] expect(config.headers.get('X-Admin-UI-Request')).toBeFalsy() }) + + it('用户侧 timing API 自动带 User UI 标记', async () => { + const adapter = vi.fn().mockResolvedValue({ + status: 200, + data: { code: 0, data: {} }, + headers: {}, + config: {}, + statusText: 'OK', + }) + apiClient.defaults.adapter = adapter + + await apiClient.get('/auth/me') + + const config = adapter.mock.calls[0][0] + expect(config.headers.get('X-User-UI-Request')).toBe('1') + expect(config.headers.get('X-Admin-UI-Request')).toBeFalsy() + }) + + it('支付用户 API 带 User UI 标记,公开支付 API 不带', async () => { + const adapter = vi.fn().mockResolvedValue({ + status: 200, + data: { code: 0, data: {} }, + headers: {}, + config: {}, + statusText: 'OK', + }) + apiClient.defaults.adapter = adapter + + await apiClient.get('/payment/plans') + expect(adapter.mock.calls[0][0].headers.get('X-User-UI-Request')).toBe('1') + + await apiClient.post('/payment/public/orders/verify', {}) + expect(adapter.mock.calls[1][0].headers.get('X-User-UI-Request')).toBeFalsy() + }) + + it('管理页调用共享 API 时同时带 Admin 与 User UI 标记', async () => { + window.history.replaceState({}, '', '/admin/dashboard') + const adapter = vi.fn().mockResolvedValue({ + status: 200, + data: { code: 0, data: {} }, + headers: {}, + config: {}, + statusText: 'OK', + }) + apiClient.defaults.adapter = adapter + + await apiClient.get('/keys') + + const config = adapter.mock.calls[0][0] + expect(config.headers.get('X-Admin-UI-Request')).toBe('1') + expect(config.headers.get('X-User-UI-Request')).toBe('1') + }) }) // --- 响应拦截器 --- diff --git a/frontend/src/api/admin/accounts.ts b/frontend/src/api/admin/accounts.ts index 2f9625b430..64a47a50fb 100644 --- a/frontend/src/api/admin/accounts.ts +++ b/frontend/src/api/admin/accounts.ts @@ -138,6 +138,50 @@ export async function create(accountData: CreateAccountRequest): Promise() + +function duplicateOperationStorageKey(id: number): string { + return `sub2api:admin:account-duplicate:${id}` +} + +function getStoredDuplicateOperationKey(id: number): string | null { + try { + return globalThis.sessionStorage?.getItem(duplicateOperationStorageKey(id)) ?? null + } catch { + return null + } +} + +function storeDuplicateOperationKey(id: number, key: string | null): void { + try { + if (key) globalThis.sessionStorage?.setItem(duplicateOperationStorageKey(id), key) + else globalThis.sessionStorage?.removeItem(duplicateOperationStorageKey(id)) + } catch { + // In-memory retry protection still works when browser storage is unavailable. + } +} + +export async function duplicate(id: number): Promise { + let idempotencyKey = duplicateOperationKeys.get(id) ?? getStoredDuplicateOperationKey(id) + if (!idempotencyKey) { + const requestID = globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}` + idempotencyKey = `account-duplicate-${id}-${requestID}` + } + duplicateOperationKeys.set(id, idempotencyKey) + storeDuplicateOperationKey(id, idempotencyKey) + const { data } = await apiClient.post(`/admin/accounts/${id}/duplicate`, undefined, { + headers: { 'Idempotency-Key': idempotencyKey } + }) + duplicateOperationKeys.delete(id) + storeDuplicateOperationKey(id, null) + return data +} + /** * Update account * @param id - Account ID @@ -809,6 +853,7 @@ export const accountsAPI = { listWithEtag, getById, create, + duplicate, update, checkMixedChannelRisk, delete: deleteAccount, diff --git a/frontend/src/api/adminUIRequest.ts b/frontend/src/api/adminUIRequest.ts index 2d60e2987d..0964c75747 100644 --- a/frontend/src/api/adminUIRequest.ts +++ b/frontend/src/api/adminUIRequest.ts @@ -1,4 +1,5 @@ export const ADMIN_UI_REQUEST_HEADER = 'X-Admin-UI-Request' +export const USER_UI_REQUEST_HEADER = 'X-User-UI-Request' function isAdminPath(path: string): boolean { return ( @@ -20,8 +21,58 @@ function requestPath(rawURL: string): string { } } +/** Normalize Axios relative paths and absolute API paths to a comparable form. */ +function normalizeAPIPath(path: string): string { + const raw = requestPath(path) + if (!raw) return '' + if (raw === '/api/v1' || raw.startsWith('/api/v1/')) { + return raw.slice('/api/v1'.length) || '/' + } + if (raw.startsWith('/')) { + return raw + } + return `/${raw}` +} + +/** + * User-facing web APIs that may emit Server-Timing when ENABLE_SERVER_TIMING is on. + * Mirrors backend isUserTimingPath allowlist (excluding public payment surfaces). + */ +export function isUserTimingAPIPath(requestURL: string): boolean { + const path = normalizeAPIPath(requestURL) + if (!path) return false + + if ( + path === '/auth/me' || + path === '/auth/revoke-all-sessions' || + path === '/auth/oauth/bind-token' + ) { + return true + } + if (path === '/user' || path.startsWith('/user/')) return true + if (path === '/keys' || path.startsWith('/keys/')) return true + if (path === '/groups/available' || path === '/groups/rates') return true + if (path === '/channels/available') return true + if (path === '/usage' || path.startsWith('/usage/')) return true + if (path === '/announcements' || path.startsWith('/announcements/')) return true + if (path === '/redeem' || path.startsWith('/redeem/')) return true + if (path === '/subscriptions' || path.startsWith('/subscriptions/')) return true + if (path === '/channel-monitors' || path.startsWith('/channel-monitors/')) return true + if (path.startsWith('/payment/')) { + if (path.startsWith('/payment/public') || path.startsWith('/payment/webhook')) { + return false + } + return true + } + return false +} + export function shouldMarkAdminUIRequest(requestURL: string, pagePath?: string): boolean { const currentPath = pagePath ?? (typeof window !== 'undefined' ? window.location.pathname : '') return isAdminPath(requestPath(requestURL)) || isAdminPath(currentPath) } + +export function shouldMarkUserUIRequest(requestURL: string): boolean { + return isUserTimingAPIPath(requestURL) +} diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index a2b4d2f650..8375cf8763 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -6,7 +6,12 @@ import axios, { AxiosInstance, AxiosError, InternalAxiosRequestConfig, AxiosResponse } from 'axios' import type { ApiResponse } from '@/types' import { getLocale } from '@/i18n' -import { ADMIN_UI_REQUEST_HEADER, shouldMarkAdminUIRequest } from './adminUIRequest' +import { + ADMIN_UI_REQUEST_HEADER, + USER_UI_REQUEST_HEADER, + shouldMarkAdminUIRequest, + shouldMarkUserUIRequest, +} from './adminUIRequest' import { getAPIBaseURL } from './url' export { buildApiUrl, buildGatewayUrl } from './url' @@ -75,8 +80,14 @@ apiClient.interceptors.request.use( config.params.timezone = getUserTimezone() } - if (config.headers && shouldMarkAdminUIRequest(String(config.url || ''))) { - config.headers[ADMIN_UI_REQUEST_HEADER] = '1' + if (config.headers) { + const requestURL = String(config.url || '') + if (shouldMarkAdminUIRequest(requestURL)) { + config.headers[ADMIN_UI_REQUEST_HEADER] = '1' + } + if (shouldMarkUserUIRequest(requestURL)) { + config.headers[USER_UI_REQUEST_HEADER] = '1' + } } return config diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index ea9deb7ba6..206c1f1494 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -5728,7 +5728,7 @@ const handleAntigravityValidateRT = async (refreshTokenInput: string) => { continue } - const credentials = antigravityOAuth.buildCredentials(tokenInfo) + const credentials = antigravityOAuth.buildCredentials(tokenInfo, refreshTokens[i]) applyAntigravityProjectID(credentials, antigravityProjectId.value, 'create') // Generate account name with index for batch diff --git a/frontend/src/components/account/OAuthAuthorizationFlow.vue b/frontend/src/components/account/OAuthAuthorizationFlow.vue index a23ec798d2..395b4ae923 100644 --- a/frontend/src/components/account/OAuthAuthorizationFlow.vue +++ b/frontend/src/components/account/OAuthAuthorizationFlow.vue @@ -276,7 +276,7 @@ - +
{{ t('admin.scheduledTests.schedule') }} + + +