diff --git a/.github/workflows/backend-ci.yml b/.github/workflows/backend-ci.yml index d1b420aa94..751f1fb0fd 100644 --- a/.github/workflows/backend-ci.yml +++ b/.github/workflows/backend-ci.yml @@ -35,7 +35,7 @@ jobs: cache-dependency-path: backend/go.sum - name: Verify Go version run: | - go version | grep -q 'go1.27.3' + go version | grep -q 'go1.27.4' - name: Unit tests working-directory: backend run: make test-unit @@ -75,7 +75,7 @@ jobs: cache-dependency-path: backend/go.sum - name: Verify Go version run: | - go version | grep -q 'go1.27.3' + go version | grep -q 'go1.27.4' - name: golangci-lint uses: golangci/golangci-lint-action@v9 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9f2ef5dd7d..b5780a6be5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -137,7 +137,7 @@ jobs: check-latest: false cache: false - name: Verify Go version - run: go version | grep -q 'go1.27.3' + run: go version | grep -q 'go1.27.4' - name: Restore target-specific Go cache id: go-cache uses: actions/cache/restore@v6 diff --git a/.github/workflows/security-scan.yml b/.github/workflows/security-scan.yml index 703e10354a..19893aae97 100644 --- a/.github/workflows/security-scan.yml +++ b/.github/workflows/security-scan.yml @@ -23,7 +23,7 @@ jobs: cache-dependency-path: backend/go.sum - name: Verify Go version run: | - go version | grep -q 'go1.27.3' + go version | grep -q 'go1.27.4' - name: Run govulncheck working-directory: backend run: | diff --git a/DEV_GUIDE.md b/DEV_GUIDE.md index 2f440d0f62..f01d59e48c 100644 --- a/DEV_GUIDE.md +++ b/DEV_GUIDE.md @@ -53,7 +53,7 @@ npm install -g pnpm ### CI 要求 -- Go 版本必须是 **1.27.0**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.27.0'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。 +- Go 版本必须是 **1.27.4**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.27.4'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。 - 前端使用 `pnpm install --frozen-lockfile`,必须提交 `pnpm-lock.yaml` ### 本地测试命令 diff --git a/Dockerfile b/Dockerfile index 0242d6f13e..0c9e438850 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,7 +8,7 @@ # ============================================================================= ARG NODE_IMAGE=node:24-alpine -ARG GOLANG_IMAGE=golang:1.27.3-alpine +ARG GOLANG_IMAGE=golang:1.27.4-alpine ARG ALPINE_IMAGE=alpine:3.21 ARG POSTGRES_IMAGE=postgres:18-alpine ARG GOPROXY=https://goproxy.cn,direct diff --git a/Makefile b/Makefile index 4a853cefdd..df5b97fb8b 100644 --- a/Makefile +++ b/Makefile @@ -11,6 +11,7 @@ FRONTEND_CRITICAL_VITEST := \ src/components/account/__tests__/OpenAIQuotaResetCell.spark_shadow.spec.ts \ src/constants/__tests__/platforms.spec.ts \ src/components/account/__tests__/credentialsBuilder.platformCatalog.spec.ts \ + src/components/account/__tests__/CNProviderQuotaCell.spec.ts \ src/components/account/__tests__/CreateAccountModal.spec.ts \ src/components/account/__tests__/EditAccountModal.spec.ts \ src/components/account/__tests__/credentialsBuilder.spec.ts \ diff --git a/backend/Dockerfile b/backend/Dockerfile index 40e228cd37..52bcb43dcc 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.27.2-alpine +FROM golang:1.27.4-alpine WORKDIR /app diff --git a/backend/go.mod b/backend/go.mod index 91db5d03b4..8163fbea14 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -1,6 +1,6 @@ module github.com/Wei-Shaw/sub2api -go 1.27.3 +go 1.27.4 require ( entgo.io/ent v0.14.5 diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index baf3260dc9..3e264053d3 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -1025,7 +1025,7 @@ type CircuitBreakerConfig struct { } type ConcurrencyConfig struct { - // PingInterval: 并发等待期间的 SSE ping 间隔(秒) + // PingInterval: 并发等待期间的 SSE ping 间隔(秒),0 禁用 ping PingInterval int `mapstructure:"ping_interval"` } @@ -3887,8 +3887,8 @@ func (c *Config) Validate() error { if c.Ops.Cleanup.Enabled && strings.TrimSpace(c.Ops.Cleanup.Schedule) == "" { return fmt.Errorf("ops.cleanup.schedule is required when ops.cleanup.enabled=true") } - if c.Concurrency.PingInterval < 5 || c.Concurrency.PingInterval > 30 { - return fmt.Errorf("concurrency.ping_interval must be between 5-30 seconds") + if c.Concurrency.PingInterval != 0 && (c.Concurrency.PingInterval < 5 || c.Concurrency.PingInterval > 30) { + return fmt.Errorf("concurrency.ping_interval must be 0 (disabled) or between 5-30 seconds") } if c.Gateway.Grok.FreeQuotaSoftGateEnabled { if c.Gateway.Grok.FreeQuotaTokenLimit <= 0 { diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go index 33a8f13d86..9c17de959b 100644 --- a/backend/internal/config/config_test.go +++ b/backend/internal/config/config_test.go @@ -1577,18 +1577,20 @@ func TestValidateOpsCleanupScheduleRequired(t *testing.T) { func TestValidateConcurrencyPingInterval(t *testing.T) { resetViperWithJWTSecret(t) - - cfg, err := Load() - if err != nil { - t.Fatalf("Load() error: %v", err) - } - cfg.Concurrency.PingInterval = 3 - err = cfg.Validate() - if err == nil { - t.Fatalf("Validate() expected error for concurrency.ping_interval") - } - if !strings.Contains(err.Error(), "concurrency.ping_interval") { - t.Fatalf("Validate() expected concurrency.ping_interval error, got: %v", err) + for _, interval := range []int{-1, 0, 1, 3, 4, 5, 10, 30, 31} { + cfg, err := Load() + if err != nil { + t.Fatalf("Load() error: %v", err) + } + cfg.Concurrency.PingInterval = interval + err = cfg.Validate() + valid := interval == 0 || (interval >= 5 && interval <= 30) + if valid && err != nil { + t.Errorf("Validate() interval %d: %v", interval, err) + } + if !valid && (err == nil || !strings.Contains(err.Error(), "concurrency.ping_interval")) { + t.Errorf("Validate() interval %d: expected concurrency.ping_interval error, got %v", interval, err) + } } } diff --git a/backend/internal/handler/gateway_compat_effort_policy_test.go b/backend/internal/handler/gateway_compat_effort_policy_test.go new file mode 100644 index 0000000000..3f13c33da0 --- /dev/null +++ b/backend/internal/handler/gateway_compat_effort_policy_test.go @@ -0,0 +1,163 @@ +//go:build unit + +package handler + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + 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" + "github.com/tidwall/gjson" +) + +type compatEffortPolicyUpstream struct { + service.HTTPUpstream + bodies [][]byte +} + +func (u *compatEffortPolicyUpstream) DoWithTLS(req *http.Request, _ string, _ int64, _ int, _ *tlsfingerprint.Profile) (*http.Response, error) { + body, err := io.ReadAll(req.Body) + if err != nil { + return nil, err + } + u.bodies = append(u.bodies, body) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(compatStreamUsagePartialStream + compatStreamUsageCompletion)), + }, nil +} + +func TestGatewayCompatibilityHandlersReasoningEffortPolicy(t *testing.T) { + gin.SetMode(gin.TestMode) + const model = "claude-sonnet-4.5" + for _, endpoint := range []string{"chat/completions", "responses"} { + for _, platform := range []string{service.PlatformAnthropic, service.PlatformComposite} { + for _, stream := range []bool{false, true} { + for _, tc := range []struct { + name string + effort string + ceiling string + overLimit string + mappings []service.ReasoningEffortMapping + want string + denied bool + }{ + {name: "ceiling", effort: "high", ceiling: "medium", want: "medium"}, + {name: "mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "low"}}, want: "low"}, + {name: "mapping then ceiling", effort: "low", ceiling: "medium", mappings: []service.ReasoningEffortMapping{{From: "low", To: "high"}}, want: "medium"}, + {name: "model mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "low", MatchType: "exact", Model: model}}, want: "low"}, + {name: "other model mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "low", MatchType: "exact", Model: "other-model"}}, want: "high"}, + {name: "deny ceiling", effort: "high", ceiling: "medium", overLimit: service.ReasoningEffortOverLimitDeny, denied: true}, + {name: "deny mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "deny"}}, denied: true}, + {name: "within ceiling", effort: "low", ceiling: "medium", want: "low"}, + {name: "no policy", effort: "high", want: "high"}, + {name: "omitted", ceiling: "medium"}, + } { + t.Run(fmt.Sprintf("%s/%s/stream=%t/%s", endpoint, platform, stream, tc.name), func(t *testing.T) { + cfg := &config.Config{} + groupID := int64(9400) + group := &service.Group{ + ID: groupID, Hydrated: true, Platform: platform, Status: service.StatusActive, RateMultiplier: 1, + MaxReasoningEffort: tc.ceiling, MaxReasoningEffortOverLimit: tc.overLimit, ReasoningEffortMappings: tc.mappings, + } + account := &service.Account{ + ID: 9401, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, + Credentials: map[string]any{"api_key": "test-key"}, + AccountGroups: []service.AccountGroup{{AccountID: 9401, GroupID: groupID}}, + } + cache := &countingGatewaySchedulerCache{fakeSchedulerCache: &fakeSchedulerCache{accounts: []*service.Account{account}}} + snapshot := service.NewSchedulerSnapshotService(cache, nil, nil, nil, nil) + upstream := &compatEffortPolicyUpstream{} + usageRepo := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 1)} + billingRepo := &compatStreamUsageBillingRepo{} + billingCache := service.NewBillingCacheService(newHandlerInflightCache(100), nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCache.Stop) + gateway := service.NewGatewayService( + nil, &fakeGroupRepo{group: group}, usageRepo, billingRepo, nil, nil, nil, nil, cfg, + snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, upstream, + &service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + h := &GatewayHandler{ + gatewayService: gateway, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), + } + + request := map[string]any{"model": model, "stream": stream} + if endpoint == "chat/completions" { + request["messages"] = []map[string]string{{"role": "user", "content": "hello"}} + if tc.effort != "" { + request["reasoning_effort"] = tc.effort + } + } else { + request["input"] = "hello" + if tc.effort != "" { + request["reasoning"] = map[string]string{"effort": tc.effort} + } + } + body, err := json.Marshal(request) + require.NoError(t, err) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + ctx := context.WithValue(context.Background(), ctxkey.Group, group) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/"+endpoint, bytes.NewReader(body)).WithContext(ctx) + c.Request.Header.Set("Content-Type", "application/json") + apiKey := &service.APIKey{ + ID: 9402, UserID: 9403, GroupID: &groupID, Group: group, + User: &service.User{ID: 9403, Balance: 100}, + } + c.Set(string(middleware.ContextKeyAPIKey), apiKey) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9403}) + if endpoint == "chat/completions" { + h.ChatCompletions(c) + } else { + h.Responses(c) + } + + if tc.denied { + require.Equal(t, http.StatusForbidden, recorder.Code, recorder.Body.String()) + errorField := "error.type" + if endpoint == "responses" { + errorField = "error.code" + } + require.Equal(t, "permission_error", gjson.Get(recorder.Body.String(), errorField).String()) + require.Empty(t, upstream.bodies) + require.Zero(t, cache.snapshotCalls.Load(), "local policy denial precedes account selection") + require.Empty(t, usageRepo.created) + require.Empty(t, billingRepo.commands) + return + } + // Check the final Anthropic request, beyond handler parsing and both protocol conversions. + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Len(t, upstream.bodies, 1) + require.Equal(t, tc.want, gjson.GetBytes(upstream.bodies[0], "output_config.effort").String()) + require.Equal(t, model, gjson.GetBytes(upstream.bodies[0], "model").String()) + require.Contains(t, recorder.Body.String(), "partial") + require.Len(t, usageRepo.created, 1) + usage := <-usageRepo.created + if tc.effort == "" { + require.Nil(t, usage.RequestedReasoningEffort) + } else { + require.Equal(t, &tc.effort, usage.RequestedReasoningEffort) + require.Equal(t, &tc.want, usage.ReasoningEffort) + } + }) + } + } + } + } +} diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 6ec51d5430..d3921ef932 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -80,7 +80,7 @@ func NewGatewayHandler( cfg *config.Config, settingService *service.SettingService, ) *GatewayHandler { - pingInterval := time.Duration(0) + pingInterval := defaultPingInterval maxAccountSwitches := 10 maxAccountSwitchesGemini := 3 if cfg != nil { @@ -915,6 +915,10 @@ func (h *GatewayHandler) Messages(c *gin.Context) { if fs.ForceCacheBilling { requestCtx = service.WithForceCacheBilling(requestCtx) } + if channelMapping.Mapped { + // 选号按客户端模型,转发按渠道映射后的模型:模型级账号状态按选号模型记录。 + requestCtx = service.WithGatewaySchedulingModel(requestCtx, reqModel) + } // 记录 Forward 前已写入字节数,Forward 后若增加则说明 SSE 内容已发,禁止 failover writerSizeBeforeForward := c.Writer.Size() if account.Platform == service.PlatformAntigravity && account.Type != service.AccountTypeAPIKey { @@ -1127,8 +1131,12 @@ func (h *GatewayHandler) Messages(c *gin.Context) { // - 粘性账号因负载/RPM 被跳过、选中了其他账号:不覆盖原绑定, // 下次请求粘性账号恢复后仍可命中 if sessionKey != "" && (sessionBoundAccountID == 0 || sessionBoundAccountID == account.ID) { - if err := h.gatewayService.BindStickySession(c.Request.Context(), currentAPIKey.GroupID, sessionKey, account.ID); err != nil { - reqLog.Warn("gateway.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(err)) + // Forward has completed; finish the bounded write even if the client disconnects. + bindCtx, cancelBind := context.WithTimeout(context.WithoutCancel(c.Request.Context()), 5*time.Second) + bindErr := h.gatewayService.BindStickySession(bindCtx, currentAPIKey.GroupID, sessionKey, account.ID) + cancelBind() + if bindErr != nil { + reqLog.Warn("gateway.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(bindErr)) } } diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 1db2e0584a..0b982a961b 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -85,6 +85,12 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { if rejectSystemOneOnlyPlatform(c, apiKey, h.chatCompletionsErrorResponse) { return } + if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil { + respondOpenAIReasoningEffortPolicyError(c, err, h.chatCompletionsErrorResponse) + return + } else if changed { + body = cappedBody + } reqStream, ok := parseOpenAICompatibleStream(body) if !ok { h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage) @@ -390,6 +396,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated), zap.Error(err), ) + h.gatewayService.ReleaseStickySessionAfterCommittedNoContent(context.WithoutCancel(c.Request.Context()), apiKey.GroupID, selectionSessionHash, account.ID, err) if result != nil { submitForwardUsage(result) } diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 79544a48de..165b57867d 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -85,6 +85,12 @@ func (h *GatewayHandler) Responses(c *gin.Context) { if rejectSystemOneOnlyPlatform(c, apiKey, h.responsesErrorResponse) { return } + if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil { + respondOpenAIReasoningEffortPolicyError(c, err, h.responsesErrorResponse) + return + } else if changed { + body = cappedBody + } reqStream, ok := parseOpenAICompatibleStream(body) if !ok { h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage) @@ -373,6 +379,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) { zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated), zap.Error(err), ) + // The response is already committed, so the client retries; send that + // retry through scheduling again instead of back to this account. + h.gatewayService.ReleaseStickySessionAfterCommittedNoContent(context.WithoutCancel(requestCtx), apiKey.GroupID, sessionHash, account.ID, err) if result != nil { submitForwardUsage(result) } diff --git a/backend/internal/handler/gateway_helper.go b/backend/internal/handler/gateway_helper.go index 02c275e2b0..8fdf726f10 100644 --- a/backend/internal/handler/gateway_helper.go +++ b/backend/internal/handler/gateway_helper.go @@ -172,7 +172,7 @@ type ConcurrencyHelper struct { // NewConcurrencyHelper creates a new ConcurrencyHelper func NewConcurrencyHelper(concurrencyService *service.ConcurrencyService, pingFormat SSEPingFormat, pingInterval time.Duration) *ConcurrencyHelper { - if pingInterval <= 0 { + if pingInterval < 0 { pingInterval = defaultPingInterval } return &ConcurrencyHelper{ @@ -380,7 +380,7 @@ func (h *ConcurrencyHelper) waitForSlotWithPingTimeout(c *gin.Context, slotType } // Determine if ping is needed (streaming + ping format defined) - needPing := isStream && h.pingFormat != "" + needPing := isStream && h.pingFormat != "" && h.pingInterval > 0 var flusher http.Flusher if needPing { diff --git a/backend/internal/handler/gateway_helper_ping_test.go b/backend/internal/handler/gateway_helper_ping_test.go new file mode 100644 index 0000000000..051b8f357e --- /dev/null +++ b/backend/internal/handler/gateway_helper_ping_test.go @@ -0,0 +1,67 @@ +package handler + +import ( + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestConcurrencyWaitPingInterval(t *testing.T) { + for _, slotType := range []string{"user", "account"} { + for _, format := range []SSEPingFormat{SSEPingFormatClaude, SSEPingFormatComment} { + for _, interval := range []time.Duration{0, time.Millisecond} { + t.Run(slotType+"/"+string(format)+"/"+interval.String(), func(t *testing.T) { + cache := &helperConcurrencyCacheStub{} + helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), format, interval) + require.Equal(t, interval, helper.pingInterval) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/", nil) + started := false + _, err := helper.waitForSlotWithPingTimeout(c, slotType, 1, 1, 150*time.Millisecond, true, &started, false) + var concurrencyErr *ConcurrencyError + require.ErrorAs(t, err, &concurrencyErr) + require.True(t, concurrencyErr.IsTimeout) + if interval == 0 { + require.False(t, started) + require.False(t, c.Writer.Written()) + require.False(t, recorder.Flushed) + require.Empty(t, recorder.Body.String()) + require.Empty(t, recorder.Header().Get("Content-Type")) + c.JSON(http.StatusTooManyRequests, gin.H{"error": "busy"}) + require.Equal(t, http.StatusTooManyRequests, recorder.Code) + } else { + require.True(t, started) + require.True(t, recorder.Flushed) + require.Contains(t, recorder.Body.String(), string(format)) + } + }) + } + } + } +} + +func TestConcurrencyWaitWithoutPingAcquiresSlot(t *testing.T) { + for _, slotType := range []string{"user", "account"} { + t.Run(slotType, func(t *testing.T) { + cache := &helperConcurrencyCacheStub{userSeq: []bool{true}, accountSeq: []bool{true}} + helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatClaude, 0) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/", nil) + started := false + release, err := helper.waitForSlotWithPingTimeout(c, slotType, 1, 1, time.Second, true, &started, false) + require.NoError(t, err) + require.NotNil(t, release) + release() + require.False(t, started) + require.False(t, c.Writer.Written()) + require.Empty(t, recorder.Body.String()) + }) + } +} diff --git a/backend/internal/handler/gateway_sticky_writeback_test.go b/backend/internal/handler/gateway_sticky_writeback_test.go new file mode 100644 index 0000000000..2045f2792f --- /dev/null +++ b/backend/internal/handler/gateway_sticky_writeback_test.go @@ -0,0 +1,186 @@ +//go:build unit + +package handler + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + 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 stickyWritebackContextKey struct{} + +type stickyWritebackCall struct { + err error + groupID int64 + account int64 + session string + ttl time.Duration + value any + deadline time.Time +} + +type stickyWritebackCache struct { + service.GatewayCache + accountID int64 + finished bool + calls []stickyWritebackCall +} + +func (s *stickyWritebackCache) GetSessionAccountID(context.Context, int64, string) (int64, error) { + return s.accountID, nil +} + +func (s *stickyWritebackCache) SetSessionAccountID(ctx context.Context, groupID int64, session string, account int64, ttl time.Duration) error { + if s.finished { + deadline, _ := ctx.Deadline() + s.calls = append(s.calls, stickyWritebackCall{ + err: ctx.Err(), groupID: groupID, account: account, session: session, ttl: ttl, + value: ctx.Value(stickyWritebackContextKey{}), deadline: deadline, + }) + } + if err := ctx.Err(); err != nil { + return err + } + s.accountID = account + return nil +} + +func (s *stickyWritebackCache) RefreshSessionTTL(context.Context, int64, string, time.Duration) error { + return nil +} + +func (s *stickyWritebackCache) DeleteSessionAccountID(context.Context, int64, string) error { + s.accountID = 0 + return nil +} + +type stickyWritebackBody struct { + io.Reader + finish func() +} + +func (b *stickyWritebackBody) Close() error { + b.finish() + return nil +} + +func TestGatewayMessagesStickyWritebackAfterForward(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, stream := range []bool{false, true} { + name := "buffered" + if stream { + name = "streaming" + } + for _, tt := range []struct { + name string + bound int64 + cancel bool + fail bool + wantWrites int + }{ + {name: "new binding", wantWrites: 1}, + {name: "new binding after disconnect", cancel: true, wantWrites: 1}, + {name: "refresh binding", bound: 9401, wantWrites: 1}, + {name: "refresh after disconnect", bound: 9401, cancel: true, wantWrites: 1}, + {name: "different binding", bound: 9499, cancel: true}, + {name: "forward failed", cancel: true, fail: true}, + } { + t.Run(name+"/"+tt.name, func(t *testing.T) { + groupID := int64(9400) + group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive, RateMultiplier: 1} + account := &service.Account{ + ID: 9401, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, + Credentials: map[string]any{"api_key": "test-key"}, + Extra: map[string]any{"anthropic_passthrough": true}, + AccountGroups: []service.AccountGroup{{AccountID: 9401, GroupID: groupID}}, + } + cache := &stickyWritebackCache{accountID: tt.bound} + ctx := context.WithValue(context.Background(), stickyWritebackContextKey{}, "request-scoped value") + ctx, cancel := context.WithTimeout(ctx, 4*time.Second) + t.Cleanup(cancel) + responseBody := `{"id":"msg_1","type":"message","role":"assistant","model":"claude-sonnet-4.5","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}` + contentType := "application/json" + if stream { + responseBody = compatStreamUsagePartialStream + compatStreamUsageCompletion + contentType = "text/event-stream" + } + status := http.StatusOK + if tt.fail { + status = http.StatusBadRequest + responseBody = `{"type":"error","error":{"type":"invalid_request_error","message":"invalid input"}}` + } + upstream := &compatStreamUsageUpstream{response: &http.Response{ + StatusCode: status, + Header: http.Header{"Content-Type": []string{contentType}}, + Body: &stickyWritebackBody{Reader: strings.NewReader(responseBody), finish: func() { + // Forward closes its upstream body on return. Cancel precisely + // after that work, before the handler's terminal sticky write. + cache.finished = true + if tt.cancel { + cancel() + } + }}, + }} + cfg := &config.Config{RunMode: config.RunModeSimple} + other := *account + other.ID = 9499 + other.Schedulable = false + snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account, &other}}, nil, nil, nil, nil) + gw := service.NewGatewayService( + nil, &fakeGroupRepo{group: group}, nil, nil, nil, nil, nil, cache, cfg, + snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, upstream, + &service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCache.Stop) + h := &GatewayHandler{ + gatewayService: gw, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), + } + requestBody := `{"model":"claude-sonnet-4.5","max_tokens":16,"stream":false,"messages":[{"role":"user","content":"sticky writeback test"}]}` + if stream { + requestBody = strings.Replace(requestBody, `"stream":false`, `"stream":true`, 1) + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(requestBody)).WithContext(ctx) + c.Request.Header.Set("Content-Type", "application/json") + key := &service.APIKey{ID: 9402, UserID: 9403, GroupID: &groupID, Group: group, User: &service.User{ID: 9403, Balance: 100}} + c.Set(string(middleware.ContextKeyAPIKey), key) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9403}) + + h.Messages(c) + + require.Equal(t, 1, upstream.calls) + require.True(t, cache.finished) + require.Equal(t, status, rec.Code) + if tt.cancel { + require.ErrorIs(t, ctx.Err(), context.Canceled) + } + require.Len(t, cache.calls, tt.wantWrites) + for _, call := range cache.calls { + require.NoError(t, call.err, "a completed upstream request must retain its terminal sticky write") + require.Equal(t, groupID, call.groupID) + require.Equal(t, account.ID, call.account) + require.NotEmpty(t, call.session) + require.Positive(t, call.ttl) + require.Equal(t, "request-scoped value", call.value) + require.False(t, call.deadline.IsZero(), "the detached cache write must have a deadline") + require.WithinDuration(t, time.Now(), call.deadline, 5*time.Second) + } + }) + } + } +} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index f70bce78b2..ec7ad12e3c 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -364,7 +364,7 @@ func NewOpenAIGatewayHandler( opsService *service.OpsService, cfg *config.Config, ) *OpenAIGatewayHandler { - pingInterval := time.Duration(0) + pingInterval := defaultPingInterval maxAccountSwitches := 3 if cfg != nil { pingInterval = time.Duration(cfg.Concurrency.PingInterval) * time.Second @@ -489,9 +489,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { } else if changed { body = cappedBody } - if normalizedBody, changed := normalizeCodexPageContext(body); changed { + if normalizedBody, changed := normalizeCodexUntrustedContext(body); changed { body = normalizedBody - reqLog.Info("openai.codex_page_context_normalized", + reqLog.Info("openai.codex_untrusted_context_normalized", zap.String("normalization", "call_output_to_user_message"), ) } @@ -1413,7 +1413,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { defaultMappedModel := strings.TrimSpace(effectiveMappedModel) // 应用渠道模型映射到请求体 forwardBody := mappedBodyForMessages(channelMappingMsg.Mapped, channelMappingMsg.MappedModel) - writerSizeBeforeForward := c.Writer.Size() + writerSizeBeforeForward := service.OpenAICompactKeepaliveAdjustedWrittenSize(c) result, err := func() (*service.OpenAIForwardResult, error) { defer func() { if accountReleaseFunc != nil { @@ -1501,11 +1501,16 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { ) return } - if c.Writer.Size() != writerSizeBeforeForward { + if !openAIForwardMayFailover(c, writerSizeBeforeForward, failoverErr) { h.gatewayService.ObserveOpenAIAccountHealthFailure(c.Request.Context(), account, err) h.handleAnthropicFailoverExhausted(c, failoverErr, true) return } + // Only keepalive bytes were written, so failover may continue, but + // every later error must be written as an SSE event. + if c.Writer.Written() { + streamStarted = true + } if failoverErr.ShouldReportAccountScheduleFailure() { h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, currentRoutingModel, false, nil), false, nil, err) } @@ -1663,16 +1668,24 @@ func (h *OpenAIGatewayHandler) handleAnthropicFailoverExhausted(c *gin.Context, h.anthropicStreamingAwareError(c, status, "api_error", failoverErr.ClientMessage, streamStarted) return } + // A failed or error frame that triggered the failover no longer reaches the + // client in-band, so its error passthrough rule is applied here instead. + if status, errType, msg, ok := service.ApplyOpenAIStreamFailedFrameRule(c, failoverErr); ok { + h.anthropicStreamingAwareError(c, status, errType, msg, streamStarted) + return + } status, errType, errMsg := h.mapUpstreamError(failoverErr.StatusCode) h.anthropicStreamingAwareError(c, status, errType, errMsg, streamStarted) } // ensureAnthropicErrorResponse writes a fallback Anthropic error if no response was written. func (h *OpenAIGatewayHandler) ensureAnthropicErrorResponse(c *gin.Context, streamStarted bool) bool { - if c == nil || c.Writer == nil || c.Writer.Written() { + // Keepalive pings alone do not count as a written response, but they do + // commit the response as SSE, so the fallback must then be an SSE event. + if c == nil || c.Writer == nil || service.OpenAICompactKeepaliveAdjustedWrittenSize(c) >= 0 { return false } - h.anthropicStreamingAwareError(c, http.StatusBadGateway, "api_error", "Upstream request failed", streamStarted) + h.anthropicStreamingAwareError(c, http.StatusBadGateway, "api_error", "Upstream request failed", streamStarted || c.Writer.Written()) return true } diff --git a/backend/internal/handler/openai_gateway_messages_pre_content_failover_test.go b/backend/internal/handler/openai_gateway_messages_pre_content_failover_test.go new file mode 100644 index 0000000000..d20ea235be --- /dev/null +++ b/backend/internal/handler/openai_gateway_messages_pre_content_failover_test.go @@ -0,0 +1,336 @@ +//go:build unit + +package handler + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/model" + "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" + "go.uber.org/zap" +) + +const ( + preContentHandlerCreated = `data: {"type":"response.created","response":{"id":"resp_pc","object":"response","model":"gpt-5.4","status":"in_progress","output":[]}}` + "\n\n" + preContentHandlerFailed = `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"server_error","message":"An error occurred while processing your request."}}}` + "\n\n" + preContentHandlerSuccess = preContentHandlerCreated + + `data: {"type":"response.output_item.added","output_index":0,"item":{"id":"msg_1","type":"message","role":"assistant","content":[]}}` + "\n\n" + + `data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"answer from second account"}` + "\n\n" + + `data: {"type":"response.completed","response":{"id":"resp_pc","object":"response","model":"gpt-5.4","status":"completed","output":[],"usage":{"input_tokens":3,"output_tokens":4,"total_tokens":7}}}` + "\n\n" +) + +// preContentFailoverUpstream hands each upstream request to respond, which +// gets the 1-based call number. +type preContentFailoverUpstream struct { + service.HTTPUpstream + mu sync.Mutex + hits []int64 + respond func(call int) (*http.Response, error) +} + +func (u *preContentFailoverUpstream) Do(req *http.Request, _ string, accountID int64, _ int) (*http.Response, error) { + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } + u.mu.Lock() + u.hits = append(u.hits, accountID) + call := len(u.hits) + u.mu.Unlock() + return u.respond(call) +} + +func (u *preContentFailoverUpstream) calls() int { + u.mu.Lock() + defer u.mu.Unlock() + return len(u.hits) +} + +func preContentSSEResponse(body io.ReadCloser) *http.Response { + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: body} +} + +// preContentStallThenFail stalls past one keepalive tick after the first event +// and then fails with failed. +func preContentStallThenFail(failed string) *http.Response { + pr, pw := io.Pipe() + go func() { + _, _ = io.WriteString(pw, preContentHandlerCreated) + time.Sleep(1300 * time.Millisecond) + _, _ = io.WriteString(pw, failed) + _ = pw.Close() + }() + return preContentSSEResponse(pr) +} + +type unexpectedEOFReader struct{} + +func (unexpectedEOFReader) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF } + +type preContentFailoverScenario struct { + accounts []service.Account + respond func(call int) (*http.Response, error) + passthrough *service.ErrorPassthroughService + requestBody string +} + +func preContentAccounts(count int) []service.Account { + accounts := make([]service.Account, 0, count) + for i := 0; i < count; i++ { + accounts = append(accounts, service.Account{ + ID: int64(9201 + i), Name: "openai-apikey", Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, Priority: i + 1, + Credentials: map[string]any{"api_key": "sk-test", "base_url": "http://upstream.example"}, + }) + } + return accounts +} + +func servePreContentFailoverMessages(t *testing.T, accountCount int) (*httptest.ResponseRecorder, *preContentFailoverUpstream) { + t.Helper() + return serveMessagesScenario(t, preContentFailoverScenario{ + accounts: preContentAccounts(accountCount), + respond: func(call int) (*http.Response, error) { + if call == 1 { + return preContentStallThenFail(preContentHandlerFailed), nil + } + return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentHandlerSuccess))), nil + }, + }) +} + +func serveMessagesScenario(t *testing.T, sc preContentFailoverScenario) (*httptest.ResponseRecorder, *preContentFailoverUpstream) { + t.Helper() + gin.SetMode(gin.TestMode) + groupID := int64(9101) + repo := &grokCredentialHandlerRepo{accounts: sc.accounts, missingOnGet: map[int64]bool{}} + upstream := &preContentFailoverUpstream{respond: sc.respond} + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Gateway.MaxAccountSwitches = 3 + cfg.Gateway.StreamKeepaliveInterval = 1 + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCache.Stop) + gateway := service.NewOpenAIGatewayService( + repo, nil, nil, nil, nil, nil, nil, cfg, nil, nil, + service.NewBillingService(cfg, nil), nil, billingCache, upstream, + &service.DeferredService{}, nil, nil, 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, sc.passthrough, nil, nil, cfg) + apiKey := &service.APIKey{ + ID: 9102, GroupID: &groupID, + User: &service.User{ID: 9103, Status: service.StatusActive}, + Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive, AllowMessagesDispatch: true}, + } + 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}) + service.BindErrorPassthroughService(c, sc.passthrough) + c.Next() + }) + router.POST("/v1/messages", h.Messages) + + rec := httptest.NewRecorder() + requestBody := sc.requestBody + if requestBody == "" { + requestBody = `{"model":"gpt-5.4","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":true}` + } + req := httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewBufferString(requestBody)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(rec, req) + return rec, upstream +} + +// requireEndsWithSSEError checks that a response already committed as SSE ends +// with an Anthropic error event and never carries a bare JSON line. +func requireEndsWithSSEError(t *testing.T, body string) { + t.Helper() + lastEvent := body[strings.LastIndex(strings.TrimRight(body, "\n"), "\n\n")+2:] + require.True(t, strings.HasPrefix(lastEvent, "event: error\ndata: {"), "last event: %q", lastEvent) + require.Contains(t, lastEvent, `"type":"error"`) + for _, line := range strings.Split(body, "\n") { + require.False(t, strings.HasPrefix(line, "{"), "bare JSON line in SSE body: %q", line) + } +} + +func TestOpenAIMessagesFailsOverAfterKeepaliveOnlyWrite(t *testing.T) { + rec, upstream := servePreContentFailoverMessages(t, 2) + + body := rec.Body.String() + require.Equal(t, 2, upstream.calls(), "body: %q", body) + require.Equal(t, 1, strings.Count(body, "event: message_start"), "body: %q", body) + require.Contains(t, body, "answer from second account") +} + +func TestOpenAIMessagesKeepaliveThenFailoverExhaustedEndsWithSSEError(t *testing.T) { + rec, upstream := servePreContentFailoverMessages(t, 1) + + body := rec.Body.String() + require.Equal(t, 1, upstream.calls(), "body: %q", body) + require.Contains(t, body, "event: ping") + requireEndsWithSSEError(t, body) +} + +func TestOpenAIMessagesFailoverThenSecondAccountReadErrorEndsWithSSEError(t *testing.T) { + rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{ + accounts: preContentAccounts(2), + respond: func(call int) (*http.Response, error) { + if call == 1 { + return preContentStallThenFail(preContentHandlerFailed), nil + } + return preContentSSEResponse(io.NopCloser(unexpectedEOFReader{})), nil + }, + }) + + body := rec.Body.String() + require.Equal(t, 2, upstream.calls(), "body: %q", body) + require.NotContains(t, body, "message_start") + requireEndsWithSSEError(t, body) +} + +func TestOpenAIMessagesFailoverThenSecondAccountCredentialErrorEndsWithSSEError(t *testing.T) { + accounts := preContentAccounts(2) + accounts[1].Credentials = map[string]any{"base_url": "http://upstream.example"} + rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{ + accounts: accounts, + respond: func(call int) (*http.Response, error) { + return preContentStallThenFail(preContentHandlerFailed), nil + }, + }) + + body := rec.Body.String() + require.Equal(t, 1, upstream.calls(), "body: %q", body) + require.NotContains(t, body, "message_start") + requireEndsWithSSEError(t, body) +} + +func TestOpenAIMessagesSlotAcquireFailureAfterKeepaliveIsSSE(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + c.Header("Content-Type", "text/event-stream") + _, err := io.WriteString(c.Writer, "event: ping\ndata: {\"type\":\"ping\"}\n\n") + require.NoError(t, err) + streamStarted := true + + h := &OpenAIGatewayHandler{} + selection := &service.AccountSelectionResult{Account: &service.Account{ID: 9201}} + _, result := h.acquireResponsesAccountSlot(c, nil, "", selection, true, &streamStarted, zap.NewNop()) + + require.Equal(t, openAISlotAcquireFailed, result) + body := rec.Body.String() + lastEvent := body[strings.LastIndex(strings.TrimRight(body, "\n"), "\n\n")+2:] + require.True(t, strings.HasPrefix(lastEvent, "event: error\ndata: {"), "last event: %q", lastEvent) +} + +func newFailedFrameCodeRule(code string) *service.ErrorPassthroughService { + status := http.StatusTeapot + rule := &model.ErrorPassthroughRule{ + ID: 1, Name: "frame code rule", Enabled: true, Priority: 1, + Keywords: []string{code}, MatchMode: model.MatchModeAny, + Platforms: []string{model.PlatformOpenAI}, ResponseCode: &status, PassthroughBody: true, + } + return service.NewErrorPassthroughService(&errorPassthroughRepoStub{rules: []*model.ErrorPassthroughRule{rule}}, nil) +} + +// A failed frame that triggers a failover is no longer written in-band, so its +// passthrough rule has to apply once the failover is exhausted. The rule is +// keyed on the frame's own code, which the generic failover envelope lacks. +func TestOpenAIMessagesFailoverExhaustedAppliesFailedFrameRule(t *testing.T) { + rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{ + accounts: preContentAccounts(1), + passthrough: newFailedFrameCodeRule("rate_limit_exceeded"), + respond: func(call int) (*http.Response, error) { + failed := `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.4"}}}` + "\n\n" + return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentHandlerCreated + failed))), nil + }, + }) + + body := rec.Body.String() + t.Logf("status=%d body=%q", rec.Code, body) + require.Equal(t, 1, upstream.calls(), "body: %q", body) + require.Equal(t, http.StatusTeapot, rec.Code, "body: %q", body) + require.Equal(t, "upstream_error", gjson.Get(body, "error.type").String(), "body: %q", body) + require.Equal(t, "Rate limit reached for gpt-5.4", gjson.Get(body, "error.message").String(), "body: %q", body) +} + +const preContentRateLimitFailed = `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.4"}}}` + "\n\n" + +func requireFailedFrameRuleJSON(t *testing.T, rec *httptest.ResponseRecorder) { + t.Helper() + body := rec.Body.String() + t.Logf("status=%d content-type=%q body=%q", rec.Code, rec.Header().Get("Content-Type"), body) + require.Equal(t, http.StatusTeapot, rec.Code, "body: %q", body) + require.Contains(t, rec.Header().Get("Content-Type"), "application/json") + require.Equal(t, "upstream_error", gjson.Get(body, "error.type").String(), "body: %q", body) + require.Equal(t, "Rate limit reached for gpt-5.4", gjson.Get(body, "error.message").String(), "body: %q", body) +} + +// The failed frame is the first event of the stream, so it triggers the +// failover before any output and used to reach the generic mapping unchecked. +func TestOpenAIMessagesFirstEventFailedFrameExhaustedAppliesRule(t *testing.T) { + rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{ + accounts: preContentAccounts(1), + passthrough: newFailedFrameCodeRule("rate_limit_exceeded"), + respond: func(call int) (*http.Response, error) { + return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentRateLimitFailed))), nil + }, + }) + + require.Equal(t, 1, upstream.calls()) + requireFailedFrameRuleJSON(t, rec) +} + +func TestOpenAIMessagesNonStreamFailedFrameExhaustedAppliesRule(t *testing.T) { + rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{ + accounts: preContentAccounts(1), + passthrough: newFailedFrameCodeRule("rate_limit_exceeded"), + requestBody: `{"model":"gpt-5.4","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":false}`, + respond: func(call int) (*http.Response, error) { + return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentHandlerCreated + preContentRateLimitFailed))), nil + }, + }) + + require.Equal(t, 1, upstream.calls()) + requireFailedFrameRuleJSON(t, rec) +} + +// A failover triggered by an HTTP status keeps the built-in exhaustion mapping: +// no passthrough rule is looked up for it. +func TestOpenAIMessagesHTTPStatusFailoverExhaustedIgnoresPassthroughRule(t *testing.T) { + rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{ + accounts: preContentAccounts(1), + passthrough: newFailedFrameCodeRule("rate_limit_exceeded"), + respond: func(call int) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusBadGateway, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.4"}}`)), + }, nil + }, + }) + + body := rec.Body.String() + t.Logf("status=%d body=%q", rec.Code, body) + require.Equal(t, 1, upstream.calls(), "body: %q", body) + require.NotEqual(t, http.StatusTeapot, rec.Code, "body: %q", body) + require.Equal(t, "Upstream service temporarily unavailable", gjson.Get(body, "error.message").String(), "body: %q", body) +} diff --git a/backend/internal/handler/openai_native_anthropic_endpoint_test.go b/backend/internal/handler/openai_native_anthropic_endpoint_test.go new file mode 100644 index 0000000000..f2a193c213 --- /dev/null +++ b/backend/internal/handler/openai_native_anthropic_endpoint_test.go @@ -0,0 +1,143 @@ +//go:build unit + +package handler + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "testing/iotest" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +type nativeEndpointUpstream struct { + service.HTTPUpstream + mode string + paths []string +} + +func (u *nativeEndpointUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) { + u.paths = append(u.paths, req.URL.Path) + if u.mode == "transport error" { + return nil, errors.New("synthetic upstream transport failure") + } + body, err := io.ReadAll(req.Body) + if err != nil { + return nil, err + } + response := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}} + switch u.mode { + case "HTTP error": + response.StatusCode = http.StatusBadRequest + response.Body = io.NopCloser(strings.NewReader(`{"error":{"type":"invalid_request_error","message":"synthetic rejection"}}`)) + case "body read error": + response.Body = io.NopCloser(iotest.ErrReader(errors.New("synthetic body read failure"))) + default: + if gjson.GetBytes(body, "stream").Bool() { + response.Header.Set("Content-Type", "text/event-stream") + response.Body = io.NopCloser(strings.NewReader(compatStreamUsagePartialStream + compatStreamUsageCompletion)) + } else { + response.Body = io.NopCloser(strings.NewReader(`{"id":"msg_1","type":"message","role":"assistant","model":"k3","content":[{"type":"text","text":"partial"}],"stop_reason":"end_turn","usage":{"input_tokens":12,"output_tokens":7}}`)) + } + } + return response, nil +} + +func (u *nativeEndpointUpstream) DoWithTLS(req *http.Request, proxy string, accountID int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return u.Do(req, proxy, accountID, concurrency) +} + +func TestOpenAINativeAnthropicEndpointDiagnostics(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, route := range []struct { + name string + path string + protocol string + platform string + }{ + {"messages", "/v1/messages", service.APIProtocolAnthropic, service.PlatformKimi}, + {"chat", "/v1/chat/completions", service.APIProtocolAnthropic, service.PlatformKimi}, + {"responses", "/v1/responses", service.APIProtocolAnthropic, service.PlatformKimi}, + {"adaptive messages", "/v1/messages", service.APIProtocolAdaptive, service.PlatformZhipu}, + } { + for _, stream := range []bool{false, true} { + for _, mode := range []string{"transport error", "HTTP error", "body read error", "success"} { + t.Run(fmt.Sprintf("%s/stream=%t/%s", route.name, stream, mode), func(t *testing.T) { + upstream := &nativeEndpointUpstream{mode: mode} + cfg := &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{AllowInsecureHTTP: true}}} + gateway := service.NewOpenAIGatewayService( + nil, nil, nil, nil, nil, nil, nil, cfg, nil, nil, nil, nil, nil, upstream, + nil, nil, nil, nil, nil, nil, nil, nil, + ) + account := &service.Account{ + ID: 9501, Platform: route.platform, Type: service.AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "test-key", "api_protocol": route.protocol, + "base_url": "http://anthropic.example", + "api_base_urls": map[string]any{ + service.APIProtocolAnthropic: "http://anthropic.example", + service.APIProtocolChatCompletions: "http://chat.example", + }, + }, + } + model := "k3" + if route.protocol == service.APIProtocolAdaptive { + require.False(t, account.SupportsNativeCNResponses()) + model = "glm-5.3" + } + request := map[string]any{"model": model, "stream": stream} + if route.path == "/v1/responses" { + request["input"] = "hello" + } else { + request["messages"] = []map[string]string{{"role": "user", "content": "hello"}} + request["max_tokens"] = 32 + } + body, err := json.Marshal(request) + require.NoError(t, err) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, route.path, strings.NewReader(string(body))) + // The same Gin context can retain an earlier attempt's protocol. + service.SetActualOpenAIUpstreamEndpoint(c, EndpointChatCompletions) + var result *service.OpenAIForwardResult + switch route.path { + case "/v1/messages": + result, err = gateway.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + case "/v1/chat/completions": + result, err = gateway.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + default: + result, err = gateway.Forward(context.Background(), c, account, body) + } + if mode == "success" { + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, EndpointMessages, result.UpstreamEndpoint) + require.Contains(t, recorder.Body.String(), "partial") + } else { + require.Error(t, err) + if mode != "body read error" { + require.Nil(t, result, "error diagnostics must work without a forward result") + } + } + require.Len(t, upstream.paths, 1) + require.True(t, strings.HasSuffix(upstream.paths[0], EndpointMessages), "the request actually used native Anthropic: %v", upstream.paths) + // This is the endpoint reader used when writing operations errors and result-less usage. + require.Equal(t, EndpointMessages, GetUpstreamEndpoint(c, account.Platform)) + require.Equal(t, EndpointMessages, service.GetActualOpenAIUpstreamEndpoint(c)) + }) + } + } + } +} diff --git a/backend/internal/handler/openai_page_context.go b/backend/internal/handler/openai_page_context.go index c61e830425..7313852f6a 100644 --- a/backend/internal/handler/openai_page_context.go +++ b/backend/internal/handler/openai_page_context.go @@ -11,10 +11,10 @@ import ( var codexSelectedPageName = regexp.MustCompile(`^codex_apps_selected_page_part_([1-9][0-9]*)_of_([1-9][0-9]*)$`) -// Desktop injects page snapshots as standalone outputs, without a model tool call. -// Keep them as untrusted user text, including on history replay and mixed bootstrap turns. -func normalizeCodexPageContext(body []byte) ([]byte, bool) { - if !mayContainCodexCallOutputCandidate(body, "codex_apps_open_page", "codex_apps_selected_page_part_") || !hasUniqueJSONMembers(body) { +// Codex injects external context as standalone outputs, without a model tool call. +// Use the legacy user-message representation for HTTP Responses interoperability. +func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) { + if !mayContainCodexCallOutputCandidate(body, "codex_apps_open_page", "codex_apps_selected_page_part_", "browser_info", "goal_objective", "untrusted_context") || !hasUniqueJSONMembers(body) { return body, false } var request map[string]json.RawMessage @@ -46,15 +46,19 @@ func normalizeCodexPageContext(body []byte) ([]byte, bool) { } } name, output := readString("name"), readString("output") - if !validCodexPageContext(name, output) { + if !validCodexUntrustedContext(name, output) { continue } + text := "" + output + "" + if validCodexPageContext(name, output) { + text = "\n" + output + "\n" + } message := map[string]any{ "type": "message", "role": "user", "content": []map[string]string{{ "type": "input_text", - "text": "\n" + output + "\n", + "text": text, }}, } encoded, err := json.Marshal(message) @@ -79,6 +83,15 @@ func normalizeCodexPageContext(body []byte) ([]byte, bool) { return encoded, true } +func validCodexUntrustedContext(name, output string) bool { + switch name { + case "browser_info", "goal_objective", "untrusted_context": + return strings.TrimSpace(output) != "" + default: + return validCodexPageContext(name, output) + } +} + func validCodexPageContext(name, output string) bool { if name == "codex_apps_open_page" { return validCodexPageSnapshot(output) diff --git a/backend/internal/handler/openai_page_context_test.go b/backend/internal/handler/openai_page_context_test.go index dccdc6fd82..2eb204ac90 100644 --- a/backend/internal/handler/openai_page_context_test.go +++ b/backend/internal/handler/openai_page_context_test.go @@ -34,7 +34,7 @@ func TestNormalizeCodexPageContextFirstMessage(t *testing.T) { require.Equal(t, 400, w.Code) require.Contains(t, w.Body.String(), "function_call_output requires call_id") - got, changed := normalizeCodexPageContext(body) + got, changed := normalizeCodexUntrustedContext(body) require.True(t, changed) w = httptest.NewRecorder() c, _ = gin.CreateTestContext(w) @@ -49,14 +49,130 @@ func TestNormalizeCodexPageContextFirstMessage(t *testing.T) { require.False(t, item.Get("id").Exists()) } require.Equal(t, "hello", gjson.GetBytes(got, "input.2.content").String()) - again, changed := normalizeCodexPageContext(got) + again, changed := normalizeCodexUntrustedContext(got) require.False(t, changed) require.Equal(t, got, again) } +func TestNormalizeCodexAdditionalUntrustedContext(t *testing.T) { + // AdditionalContextToolOutput derives names from caller-provided context keys. + // Codex 0.169.0 enables this representation by default (openai/codex#60487). + for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} { + t.Run(name, func(t *testing.T) { + output := "external context\nline two" + body := pageContextRequest(t, pageContextItem(name, output), + map[string]any{"role": "user", "content": "continue"}) + h := &OpenAIGatewayHandler{} + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop())) + + got, changed := normalizeCodexUntrustedContext(body) + require.True(t, changed) + w = httptest.NewRecorder() + c, _ = gin.CreateTestContext(w) + require.True(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop())) + require.False(t, c.Writer.Written()) + item := gjson.GetBytes(got, "input.0") + require.Equal(t, "message", item.Get("type").String()) + require.Equal(t, "user", item.Get("role").String()) + require.Equal(t, ""+output+"", item.Get("content.0.text").String()) + require.False(t, item.Get("call_id").Exists()) + require.Equal(t, "continue", gjson.GetBytes(got, "input.1.content").String()) + again, changed := normalizeCodexUntrustedContext(got) + require.False(t, changed) + require.Equal(t, got, again) + }) + } +} + +func TestNormalizeCodexAdditionalUntrustedContextPreservesRealAndMalformedOutputs(t *testing.T) { + for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} { + for _, override := range []map[string]any{ + {"call_id": "call_real"}, + {"call_id": nil}, + {"call_id": 42}, + {"namespace": "other"}, + {"namespace": nil}, + {"namespace": 42}, + {"output": []any{map[string]any{"type": "encrypted_content", "encrypted_content": "sealed"}}}, + {"output": " "}, + {"output": nil}, + } { + item := pageContextItem(name, "context") + for key, value := range override { + item[key] = value + } + body := pageContextRequest(t, item) + got, changed := normalizeCodexUntrustedContext(body) + require.False(t, changed, "name=%s override=%v", name, override) + require.Equal(t, body, got) + } + item := pageContextItem(name, "context") + delete(item, "namespace") + body := pageContextRequest(t, item) + got, changed := normalizeCodexUntrustedContext(body) + require.False(t, changed) + require.Equal(t, body, got) + } + // Recognized external context cannot make an unrelated tool result valid. + body := pageContextRequest(t, pageContextItem("browser_info", "tab"), + pageContextItem("read_file", "result")) + got, changed := normalizeCodexUntrustedContext(body) + require.True(t, changed) + h := &OpenAIGatewayHandler{} + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + require.False(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop())) + require.Equal(t, 400, w.Code) + + // Keep historical calls, prior response and exact numeric metadata intact. + body = []byte(`{"model":"gpt-5","previous_response_id":"resp_history","metadata":{"large":9007199254740993},"input":[{"type":"function_call","name":"read_file","call_id":"call_real","arguments":"{}"},{"type":"function_call_output","call_id":"call_real","output":"result"},{"type":"function_call_output","namespace":"agent","name":"goal_objective","output":"finish"}]}`) + got, changed = normalizeCodexUntrustedContext(body) + require.True(t, changed) + require.Equal(t, "resp_history", gjson.GetBytes(got, "previous_response_id").String()) + require.Equal(t, "9007199254740993", gjson.GetBytes(got, "metadata.large").Raw) + for _, index := range []string{"input.0", "input.1"} { + require.JSONEq(t, gjson.GetBytes(body, index).Raw, gjson.GetBytes(got, index).Raw) + } +} + +func TestNormalizeCodexAdditionalUntrustedContextBlankCallIDsAndMixedInput(t *testing.T) { + names := []string{"browser_info", "goal_objective", "untrusted_context"} + for _, callID := range []string{"", " \t\n"} { + items := make([]any, 0, len(names)) + for _, name := range names { + item := pageContextItem(name, "context for "+name) + item["call_id"] = callID + delete(item, "id") + items = append(items, item) + } + got, changed := normalizeCodexUntrustedContext(pageContextRequest(t, items...)) + require.True(t, changed) + require.Len(t, gjson.GetBytes(got, "input").Array(), len(names)) + for i, item := range gjson.GetBytes(got, "input").Array() { + require.Equal(t, "user", item.Get("role").String()) + require.Equal(t, "context for "+names[i]+"", item.Get("content.0.text").String()) + } + } +} + +func TestNormalizeCodexAdditionalUntrustedContextRejectsDuplicateMembers(t *testing.T) { + for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} { + for _, body := range []string{ + `{"input":[{"type":"function_call_output","namespace":"agent","name":"` + name + `","call_id":"real","call_id":"","output":"context"}]}`, + `{"input":[{"type":"function_call_output","namespace":"agent","name":"` + name + `","output":"first","output":"second"}]}`, + } { + got, changed := normalizeCodexUntrustedContext([]byte(body)) + require.False(t, changed) + require.Equal(t, body, string(got)) + } + } +} + func TestNormalizeCodexPageContextPreservesHistoryAndToolValidation(t *testing.T) { body := []byte(`{"model":"gpt-5","previous_response_id":"resp_history","metadata":{"large":9007199254740993},"input":[{"type":"function_call","name":"read_file","call_id":"call_real","arguments":"{}"},{"type":"function_call_output","call_id":"call_real","output":"result"},{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","output":"{\"page_id\":\"page_1\"}"}]}`) - got, changed := normalizeCodexPageContext(body) + got, changed := normalizeCodexUntrustedContext(body) require.True(t, changed) require.Equal(t, "resp_history", gjson.GetBytes(got, "previous_response_id").String()) require.Equal(t, "9007199254740993", gjson.GetBytes(got, "metadata.large").Raw) @@ -66,7 +182,7 @@ func TestNormalizeCodexPageContextPreservesHistoryAndToolValidation(t *testing.T badTool := pageContextItem("read_file", "result") body = pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), badTool) - got, changed = normalizeCodexPageContext(body) + got, changed = normalizeCodexUntrustedContext(body) require.True(t, changed) require.True(t, service.ValidateFunctionCallOutputContextBytes(got).HasFunctionCallOutputMissingCallID) } @@ -77,7 +193,7 @@ func TestNormalizeCodexPageContextMixedBootstrap(t *testing.T) { {"type": "function_call_output", "namespace": "codex_app", "name": "automation_update", "output": "test"}, } { body := pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), item) - got, changed := normalizeCodexPageContext(body) + got, changed := normalizeCodexUntrustedContext(body) require.True(t, changed) got, _ = normalizeCodexAutomationBootstrap(got) got, _ = normalizeCodexDelegationBootstrap(got) @@ -89,7 +205,7 @@ func TestNormalizeCodexPageContextMultipart(t *testing.T) { first := "Companion Page snapshot part 1 of 2:\n" + `{"page_id":"page1","document_view":"hello` second := "Companion Page snapshot part 2 of 2:\n" + ` world"}` body := pageContextRequest(t, pageContextItem("codex_apps_selected_page_part_1_of_2", first), pageContextItem("codex_apps_selected_page_part_2_of_2", second)) - got, changed := normalizeCodexPageContext(body) + got, changed := normalizeCodexUntrustedContext(body) require.True(t, changed) require.Contains(t, gjson.GetBytes(got, "input.0.content.0.text").String(), first) require.Contains(t, gjson.GetBytes(got, "input.1.content.0.text").String(), second) @@ -119,7 +235,7 @@ func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T) item := pageContextItem("codex_apps_open_page", `{"page_id":null}`) item[tc.key] = tc.value body := pageContextRequest(t, item) - got, changed := normalizeCodexPageContext(body) + got, changed := normalizeCodexUntrustedContext(body) require.False(t, changed) require.Equal(t, body, got) }) @@ -128,7 +244,7 @@ func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T) `{"input":[{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","call_id":"real","call_id":"","output":"{\"page_id\":null}"}]}`, `{"input":[{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","output":"{\"page_id\":null}"}]} trailing`, } { - got, changed := normalizeCodexPageContext([]byte(body)) + got, changed := normalizeCodexUntrustedContext([]byte(body)) require.False(t, changed) require.Equal(t, body, string(got)) } diff --git a/backend/internal/handler/usage_handler.go b/backend/internal/handler/usage_handler.go index 987092ca46..eb212679cc 100644 --- a/backend/internal/handler/usage_handler.go +++ b/backend/internal/handler/usage_handler.go @@ -417,6 +417,9 @@ func (h *UsageHandler) Stats(c *gin.Context) { return } stats.TotalAccountCost = nil + for i := range stats.Endpoints { + stats.Endpoints[i].AccountCost = 0 + } stats.UpstreamEndpoints = nil stats.EndpointPaths = nil diff --git a/backend/internal/handler/user_msg_queue_helper.go b/backend/internal/handler/user_msg_queue_helper.go index 839b14cbb6..831715495e 100644 --- a/backend/internal/handler/user_msg_queue_helper.go +++ b/backend/internal/handler/user_msg_queue_helper.go @@ -27,7 +27,7 @@ func NewUserMsgQueueHelper( pingFormat SSEPingFormat, pingInterval time.Duration, ) *UserMsgQueueHelper { - if pingInterval <= 0 { + if pingInterval < 0 { pingInterval = defaultPingInterval } return &UserMsgQueueHelper{ @@ -86,7 +86,7 @@ func (h *UserMsgQueueHelper) waitForLockWithPing( streamStarted *bool, reqLog *zap.Logger, ) (func(), error) { - needPing := isStream && h.pingFormat != "" + needPing := isStream && h.pingFormat != "" && h.pingInterval > 0 var flusher http.Flusher if needPing { @@ -196,7 +196,7 @@ func (h *UserMsgQueueHelper) ThrottleWithPing( ) // 延迟期间发送 SSE ping(复用 waitForLockWithPing 的 ping 逻辑) - needPing := isStream && h.pingFormat != "" + needPing := isStream && h.pingFormat != "" && h.pingInterval > 0 var flusher http.Flusher if needPing { flusher, _ = c.Writer.(http.Flusher) diff --git a/backend/internal/payment/provider/alipay.go b/backend/internal/payment/provider/alipay.go index dbd0e9cccb..555913b086 100644 --- a/backend/internal/payment/provider/alipay.go +++ b/backend/internal/payment/provider/alipay.go @@ -348,7 +348,7 @@ func (a *Alipay) Refund(ctx context.Context, req payment.RefundRequest) (*paymen return nil, err } - outRequestNo := fmt.Sprintf("%s%s%d", req.OrderID, alipayRefundRequestSep, time.Now().UnixNano()) + outRequestNo := fmt.Sprintf("%s%s%s", req.OrderID, alipayRefundRequestSep, alipayRefundRequestNoSuffix(req.Amount)) result, err := alipayTradeRefund(ctx, client, alipay.TradeRefund{ OutTradeNo: req.OrderID, RefundAmount: req.Amount, @@ -374,6 +374,18 @@ func (a *Alipay) Refund(ctx context.Context, req payment.RefundRequest) (*paymen }, nil } +// alipayRefundRequestNoSuffix 生成跨重试稳定的 out_request_no 后缀。 +// 支付宝把相同的 out_request_no 视为同一次退款请求;如果重试换号, +// "网关已受理但返回错误"后的重试会变成第二笔真实退款。 +// 与 wxpayRefundID 一致,用金额区分同一订单的不同退款金额。 +func alipayRefundRequestNoSuffix(amount string) string { + normalized := strings.NewReplacer(".", "", "-", "").Replace(strings.TrimSpace(amount)) + if normalized == "" { + return "0" + } + return normalized +} + // QueryRefund 通过 alipay.trade.fastpay.refund.query 查询退款终态。refund_status 为 REFUND_SUCCESS // 表示成功;退款发起超过宽限期仍查不到记录表示支付宝未受理或退款失败;其余情况视为仍在处理中。 func (a *Alipay) QueryRefund(ctx context.Context, req payment.RefundQueryRequest) (*payment.RefundResponse, error) { diff --git a/backend/internal/payment/provider/alipay_test.go b/backend/internal/payment/provider/alipay_test.go index a2264b2eef..4e5751b9ad 100644 --- a/backend/internal/payment/provider/alipay_test.go +++ b/backend/internal/payment/provider/alipay_test.go @@ -480,6 +480,67 @@ func TestAlipayRefundRecordsOutRequestNoAsRefundID(t *testing.T) { } } +// out_request_no 必须跨重试稳定:支付宝把相同的 out_request_no 视为同一次退款请求。 +// 如果重试生成新的请求号,一次"网关已受理但返回错误"的重试会退两次。 +func TestAlipayRefundOutRequestNoIsStableAcrossRetries(t *testing.T) { + origRefund := alipayTradeRefund + t.Cleanup(func() { alipayTradeRefund = origRefund }) + + var outRequestNos []string + alipayTradeRefund = func(_ context.Context, _ *alipay.Client, param alipay.TradeRefund) (*alipay.TradeRefundRsp, error) { + outRequestNos = append(outRequestNos, param.OutRequestNo) + return &alipay.TradeRefundRsp{TradeNo: "2026101522001", FundChange: alipayFundChangeYes}, nil + } + + provider := &Alipay{client: &alipay.Client{}} + req := payment.RefundRequest{OrderID: "sub2_7", Amount: "12.50", Reason: "r"} + for i := 0; i < 2; i++ { + if _, err := provider.Refund(context.Background(), req); err != nil { + t.Fatalf("Refund() error = %v", err) + } + } + + if len(outRequestNos) != 2 { + t.Fatalf("got %d refund calls, want 2", len(outRequestNos)) + } + if outRequestNos[0] != "sub2_7-refund-1250" { + t.Fatalf("out_request_no = %q, want sub2_7-refund-1250", outRequestNos[0]) + } + if outRequestNos[0] != outRequestNos[1] { + t.Fatalf("out_request_no changed across retries: %q != %q", outRequestNos[0], outRequestNos[1]) + } +} + +// 模拟支付宝的幂等语义:相同的 out_request_no 只产生一笔真实退款。 +// 重试时如果请求号变了,钱会被退两次;稳定请求号下只退一次。 +func TestAlipayRefundRetryDoesNotDoubleRefund(t *testing.T) { + origRefund := alipayTradeRefund + t.Cleanup(func() { alipayTradeRefund = origRefund }) + + const refundCents = 1250 + refundedCents := 0 + seen := make(map[string]struct{}) + alipayTradeRefund = func(_ context.Context, _ *alipay.Client, param alipay.TradeRefund) (*alipay.TradeRefundRsp, error) { + if _, ok := seen[param.OutRequestNo]; !ok { + seen[param.OutRequestNo] = struct{}{} + refundedCents += refundCents + } + return &alipay.TradeRefundRsp{TradeNo: "2026101522001", FundChange: alipayFundChangeYes}, nil + } + + provider := &Alipay{client: &alipay.Client{}} + req := payment.RefundRequest{OrderID: "sub2_7", Amount: "12.50", Reason: "r"} + for i := 0; i < 2; i++ { + if _, err := provider.Refund(context.Background(), req); err != nil { + t.Fatalf("Refund() error = %v", err) + } + } + + if refundedCents != refundCents { + t.Fatalf("retry refunded %d cents, want %d (one refund only)", refundedCents, refundCents) + } +} + func TestAlipayQueryRefundMapsStatus(t *testing.T) { origQuery := alipayTradeFastPayRefundQuery t.Cleanup(func() { alipayTradeFastPayRefundQuery = origQuery }) diff --git a/backend/internal/pkg/antigravity/schema_cleaner.go b/backend/internal/pkg/antigravity/schema_cleaner.go index 73cf362561..75b5fa1e1d 100644 --- a/backend/internal/pkg/antigravity/schema_cleaner.go +++ b/backend/internal/pkg/antigravity/schema_cleaner.go @@ -376,24 +376,15 @@ func cleanJSONSchemaRecursive(value any) any { } } - // 8. [SAFETY] 处理缺失 items 的 Array (Gemini 严苛要求 array 必须声明 items Schema) + // 8. Gemini 只允许 array 携带 items,且 items 必须是非空 Schema 对象。 if t, _ := schemaMap["type"].(string); t == "array" { - itemsVal, hasItems := schemaMap["items"] - needDefaultItems := false - if !hasItems || itemsVal == nil { - needDefaultItems = true - } else if itemsMap, ok := itemsVal.(map[string]any); ok { - if len(itemsMap) == 0 { - needDefaultItems = true - } - } else if _, isBool := itemsVal.(bool); isBool { - needDefaultItems = true - } - if needDefaultItems { + if items, ok := schemaMap["items"].(map[string]any); !ok || len(items) == 0 { schemaMap["items"] = map[string]any{ "type": "string", } } + } else { + delete(schemaMap, "items") } // 9. [SAFETY] Required 字段对齐 diff --git a/backend/internal/pkg/apicompat/anthropic_to_responses.go b/backend/internal/pkg/apicompat/anthropic_to_responses.go index b326241aa9..6cd8c2f18a 100644 --- a/backend/internal/pkg/apicompat/anthropic_to_responses.go +++ b/backend/internal/pkg/apicompat/anthropic_to_responses.go @@ -206,6 +206,16 @@ func anthropicMsgToResponsesItems(m AnthropicMessage) ([]ResponsesInputItem, err return anthropicUserToResponses(m.Content) case "assistant": return anthropicAssistantToResponses(m.Content) + case "system": + // Mid-conversation system turns (e.g. hook output) keep system-level + // authority: Responses uses developer for them, not user. + items, err := anthropicUserToResponses(m.Content) + for i := range items { + if items[i].Role == "user" { + items[i].Role = "developer" + } + } + return items, err default: return anthropicUserToResponses(m.Content) } diff --git a/backend/internal/pkg/apicompat/anthropic_translation_fidelity_test.go b/backend/internal/pkg/apicompat/anthropic_translation_fidelity_test.go new file mode 100644 index 0000000000..d0fe376287 --- /dev/null +++ b/backend/internal/pkg/apicompat/anthropic_translation_fidelity_test.go @@ -0,0 +1,32 @@ +package apicompat + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// A system message in the middle of an Anthropic conversation (e.g. hook +// output) must reach Responses as a developer item, not as user input. +func TestAnthropicToResponses_MidConversationSystemBecomesDeveloper(t *testing.T) { + out, err := AnthropicToResponses(&AnthropicRequest{ + Model: "gpt-5.2", + MaxTokens: 64, + Messages: []AnthropicMessage{ + {Role: "user", Content: json.RawMessage(`"hi"`)}, + {Role: "system", Content: json.RawMessage(`[{"type":"text","text":"hook output"}]`)}, + {Role: "system", Content: json.RawMessage(`"extra context"`)}, + }, + }) + require.NoError(t, err) + + input := gjson.ParseBytes(out.Input).Array() + require.Len(t, input, 3) + require.Equal(t, "user", input[0].Get("role").String()) + require.Equal(t, "developer", input[1].Get("role").String()) + require.Equal(t, "hook output", input[1].Get("content.0.text").String()) + require.Equal(t, "developer", input[2].Get("role").String()) + require.Equal(t, "extra context", input[2].Get("content.0.text").String()) +} diff --git a/backend/internal/pkg/apicompat/chatcompletions_responses_test.go b/backend/internal/pkg/apicompat/chatcompletions_responses_test.go index b94bc5c394..21a8c05d36 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_responses_test.go +++ b/backend/internal/pkg/apicompat/chatcompletions_responses_test.go @@ -445,6 +445,38 @@ func TestChatCompletionsToResponses_ResponseFormatJsonSchema(t *testing.T) { }`, string(resp.Text.Format)) } +func TestChatCompletionsToResponses_ResponseFormatJsonSchemaDefaultsStrictFalse(t *testing.T) { + req := &ChatCompletionsRequest{ + Model: "gpt-4o", + Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"Return structured JSON"`)}}, + ResponseFormat: json.RawMessage(`{ + "type":"json_schema", + "json_schema":{ + "name":"answer", + "schema":{ + "type":"object", + "properties":{"ok":{"type":"boolean"}}, + "required":["ok"] + } + } + }`), + } + + resp, err := ChatCompletionsToResponses(req) + require.NoError(t, err) + require.NotNil(t, resp.Text) + assert.JSONEq(t, `{ + "type":"json_schema", + "name":"answer", + "schema":{ + "type":"object", + "properties":{"ok":{"type":"boolean"}}, + "required":["ok"] + }, + "strict":false + }`, string(resp.Text.Format)) +} + func TestChatCompletionsToResponses_ImageURL(t *testing.T) { content := `[{"type":"text","text":"Describe this"},{"type":"image_url","image_url":{"url":"data:image/png;base64,abc123"}}]` req := &ChatCompletionsRequest{ diff --git a/backend/internal/pkg/apicompat/response_format.go b/backend/internal/pkg/apicompat/response_format.go index afb5c3e2fd..ce12311102 100644 --- a/backend/internal/pkg/apicompat/response_format.go +++ b/backend/internal/pkg/apicompat/response_format.go @@ -23,6 +23,11 @@ func chatResponseFormatToResponsesTextFormat(raw json.RawMessage) json.RawMessag return raw } schema["type"] = rawJSONString("json_schema") + // Chat Completions defaults strict to false while Responses defaults to strict, + // so make the intended mode explicit to avoid the upstream rejecting the schema. + if _, ok := schema["strict"]; !ok { + schema["strict"] = json.RawMessage("false") + } out, err := json.Marshal(schema) if err != nil { diff --git a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go index f33d4792b1..e1a7b88c77 100644 --- a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go +++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go @@ -503,6 +503,7 @@ type bufferedFuncCall struct { Name string Namespace string EncryptedFunctionArgs json.RawMessage + EncryptedContent string Args strings.Builder } @@ -547,6 +548,7 @@ func (a *BufferedResponseAccumulator) ProcessEvent(event *ResponsesStreamEvent) Name: event.Item.Name, Namespace: event.Item.Namespace, EncryptedFunctionArgs: event.Item.EncryptedFunctionArgs, + EncryptedContent: event.Item.EncryptedContent, }) } case "response.function_call_arguments.delta", "response.custom_tool_call_input.delta": @@ -616,6 +618,7 @@ func (a *BufferedResponseAccumulator) BuildOutput() []ResponsesOutput { Name: a.funcCalls[i].Name, Namespace: a.funcCalls[i].Namespace, EncryptedFunctionArgs: a.funcCalls[i].EncryptedFunctionArgs, + EncryptedContent: a.funcCalls[i].EncryptedContent, Arguments: a.funcCalls[i].Args.String(), }) } diff --git a/backend/internal/pkg/claude/constants.go b/backend/internal/pkg/claude/constants.go index 17c864328d..601f490c8a 100644 --- a/backend/internal/pkg/claude/constants.go +++ b/backend/internal/pkg/claude/constants.go @@ -31,6 +31,7 @@ const ( BetaContextManagement = "context-management-2025-06-27" BetaThinkingBindingControls = "thinking-binding-controls-2026-08-01" BetaMidConversationOutputConfig = "mid-conversation-output-config-2026-07-01" + BetaPerTurnControl = "per-turn-control-2026-07-01" BetaExtendedCacheTTL = "extended-cache-ttl-2025-04-11" // server-side refusal fallback beta 字段族(beta Messages API 专有)。 @@ -253,7 +254,7 @@ func DefaultModelIDs() []string { } // DefaultTestModel 测试时使用的默认模型 -const DefaultTestModel = "claude-sonnet-4-5-20250929" +const DefaultTestModel = "claude-sonnet-4-6" // ModelIDOverrides Claude OAuth 请求需要的模型 ID 映射 var ModelIDOverrides = map[string]string{ diff --git a/backend/internal/pkg/usagestats/usage_log_types.go b/backend/internal/pkg/usagestats/usage_log_types.go index 9d651d85a0..9b9c4cb668 100644 --- a/backend/internal/pkg/usagestats/usage_log_types.go +++ b/backend/internal/pkg/usagestats/usage_log_types.go @@ -111,8 +111,9 @@ type EndpointStat struct { Endpoint string `json:"endpoint"` Requests int64 `json:"requests"` TotalTokens int64 `json:"total_tokens"` - Cost float64 `json:"cost"` // 标准计费 - ActualCost float64 `json:"actual_cost"` // 实际扣除 + Cost float64 `json:"cost"` // 标准计费 + ActualCost float64 `json:"actual_cost"` // 实际扣除 + AccountCost float64 `json:"account_cost,omitempty"` // 账号成本(仅管理员接口返回) } // GroupUsageSummary represents today's, yesterday's, and cumulative cost for a single group. diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index 733ff9034b..eddd4614db 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -2690,6 +2690,49 @@ func (r *accountRepository) ClearModelRateLimits(ctx context.Context, id int64) return nil } +// ClearModelRateLimit 删除 model_rate_limits 中指定的单个 scope。 +// 与 ClearModelRateLimits 的全量清除不同,这里只解封一个模型窗口, +// 不会把其他模型或并发新写入的限流一起抹掉。 +func (r *accountRepository) ClearModelRateLimit(ctx context.Context, id int64, scope string) error { + if strings.TrimSpace(scope) == "" { + return nil + } + if scoped := r.accountTransactionScope(ctx); scoped != r { + return scoped.ClearModelRateLimit(ctx, id, scope) + } + client := clientFromContext(ctx, r.client) + result, err := client.ExecContext( + ctx, + `UPDATE accounts SET + extra = jsonb_set( + COALESCE(extra, '{}'::jsonb), + '{model_rate_limits}'::text[], + COALESCE(extra->'model_rate_limits', '{}'::jsonb) - $1::text, + true + ), + updated_at = NOW() + WHERE id = $2 AND deleted_at IS NULL`, + strings.TrimSpace(scope), + id, + ) + if err != nil { + return err + } + + affected, err := result.RowsAffected() + if err != nil { + return err + } + if affected == 0 { + return service.ErrAccountNotFound + } + if err := enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventAccountChanged, &id, nil, nil); err != nil { + logger.LegacyPrintf("repository.account", "[SchedulerOutbox] enqueue clear model rate limit scope failed: account=%d err=%v", id, err) + } + r.syncSchedulerAccountSnapshot(ctx, id) + return nil +} + func (r *accountRepository) UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error { builder := r.client.Account.Update(). Where(dbaccount.IDEQ(id)). @@ -2714,8 +2757,11 @@ func (r *accountRepository) UpdateSessionWindow(ctx context.Context, id int64, s } func (r *accountRepository) UpdateSessionWindowEnd(ctx context.Context, id int64, end time.Time) error { + // Active five-hour quota reads must advance both bounds. Keeping the old + // start would charge the previous window against the new window's cost limit. _, err := r.client.Account.Update(). Where(dbaccount.IDEQ(id)). + SetSessionWindowStart(end.Add(-5 * time.Hour)). SetSessionWindowEnd(end). Save(ctx) if err != nil { diff --git a/backend/internal/repository/claude_usage_service_test.go b/backend/internal/repository/claude_usage_service_test.go index cbd0b6d3ea..f8235c379e 100644 --- a/backend/internal/repository/claude_usage_service_test.go +++ b/backend/internal/repository/claude_usage_service_test.go @@ -2,11 +2,15 @@ package repository import ( "context" + "fmt" "io" "net/http" "net/http/httptest" "testing" + "time" + "github.com/Wei-Shaw/sub2api/internal/pkg/usagestats" + "github.com/Wei-Shaw/sub2api/internal/service" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" ) @@ -61,6 +65,87 @@ func (s *ClaudeUsageServiceSuite) TestFetchUsage_Success() { require.Equal(s.T(), "oauth-2025-04-20", captured.anthropicBeta, "anthropic-beta header mismatch") } +type claudeUsageWindowAccountRepo struct { + service.AccountRepository + account *service.Account +} + +func (r *claudeUsageWindowAccountRepo) GetByID(context.Context, int64) (*service.Account, error) { + return r.account, nil +} + +func (r *claudeUsageWindowAccountRepo) UpdateExtra(_ context.Context, _ int64, updates map[string]any) error { + for key, value := range updates { + r.account.Extra[key] = value + } + return nil +} + +type claudeUsageWindowLogRepo struct { + service.UsageLogRepository +} + +func (*claudeUsageWindowLogRepo) GetAccountWindowStats(context.Context, int64, time.Time) (*usagestats.AccountStats, error) { + return &usagestats.AccountStats{}, nil +} + +func TestClaudeUsageFetcher_ScopedFableRoundTrip(t *testing.T) { + resetAt := time.Now().Add(72 * time.Hour).UTC().Truncate(time.Microsecond) + for _, tc := range []struct { + name string + percent string + legacy string + wantUsage float64 + }{ + {name: "scoped", percent: "5.25", wantUsage: 5.25}, + {name: "zero overrides passive", percent: "0", wantUsage: 0}, + {name: "missing falls back to passive", percent: "null", wantUsage: 87}, + {name: "legacy takes precedence", percent: "5.25", legacy: fmt.Sprintf(`{"utilization":56,"resets_at":%q}`, resetAt.Format(time.RFC3339Nano)), wantUsage: 56}, + } { + t.Run(tc.name, func(t *testing.T) { + legacy := tc.legacy + if legacy == "" { + legacy = "null" + } + requests := make(chan [2]string, 2) + srv := newLocalTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests <- [2]string{r.Method, r.URL.Path} + w.Header().Set("Content-Type", "application/json") + _, _ = fmt.Fprintf(w, `{"five_hour":{"utilization":12},"seven_day_overage_included":%s,"limits":[{"kind":"weekly_scoped","group":"weekly","percent":%s,"resets_at":%q,"scope":{"model":{"display_name":"Fable"},"surface":null},"is_active":false}]}`, legacy, tc.percent, resetAt.Format(time.RFC3339Nano)) + })) + defer srv.Close() + fetcher := &claudeUsageService{usageURL: srv.URL + "/api/oauth/usage", allowPrivateHosts: true} + account := &service.Account{ + ID: 1, Platform: service.PlatformAnthropic, Type: service.AccountTypeOAuth, + Status: service.StatusActive, Credentials: map[string]any{"access_token": "test-token"}, + Extra: map[string]any{ + "passive_usage_7d_oi_utilization": 0.87, + "passive_usage_7d_oi_reset": resetAt.Unix(), + }, + } + repo := &claudeUsageWindowAccountRepo{account: account} + svc := service.NewAccountUsageService(repo, &claudeUsageWindowLogRepo{}, fetcher, + nil, nil, nil, nil, nil, service.NewUsageCache(), nil, nil) + for range 2 { + usage, err := svc.GetUsageForAccount(t.Context(), account) + require.NoError(t, err) + require.NotNil(t, usage.SevenDayFable) + require.Equal(t, tc.wantUsage, usage.SevenDayFable.Utilization) + require.NotNil(t, usage.SevenDayFable.ResetsAt) + require.Equal(t, resetAt.Unix(), usage.SevenDayFable.ResetsAt.Unix()) + } + passive, err := svc.GetPassiveUsage(t.Context(), account.ID) + require.NoError(t, err) + require.NotNil(t, passive.SevenDayFable) + require.InDelta(t, tc.wantUsage, passive.SevenDayFable.Utilization, 1e-9) + require.Equal(t, resetAt.Unix(), passive.SevenDayFable.ResetsAt.Unix()) + require.InDelta(t, tc.wantUsage/100, account.Extra["passive_usage_7d_oi_utilization"], 1e-9) + require.Len(t, requests, 1, "the second query must reuse the decoded API response") + require.Equal(t, [2]string{"GET", "/api/oauth/usage"}, <-requests) + }) + } +} + func (s *ClaudeUsageServiceSuite) TestFetchUsage_NonOK() { s.srv = newLocalTestServer(s.T(), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusUnauthorized) diff --git a/backend/internal/repository/custom_group_usage_rollup_repo.go b/backend/internal/repository/custom_group_usage_rollup_repo.go index 1b0e1b2920..f6f61f783b 100644 --- a/backend/internal/repository/custom_group_usage_rollup_repo.go +++ b/backend/internal/repository/custom_group_usage_rollup_repo.go @@ -3,6 +3,8 @@ package repository import ( "context" "database/sql" + "database/sql/driver" + "errors" "fmt" "time" @@ -17,36 +19,43 @@ type groupUsageRollupSnapshot struct { valid bool closedBefore string // date,历史日桶的右开边界 retainedDate string // retained_from 在服务端时区内的日期,历史日桶的左闭边界 - tailStart time.Time // 尾段(还没进日桶的那部分 usage_logs)的起点 + tailStart time.Time // 尾段(还没进日桶的那部分 usage_logs)的起点,不早于 expired_before } // readGroupUsageRollupSnapshot 读一次汇总水位并在 Go 侧判定有效性。 // // 判定条件与原先 SQL 里的 state_values CTE 完全一致: // 恰好一行、时区名与当前服务端配置相同、且水位不在未来。 +// expired_before 之前的 usage_logs 已超出保留期:无论水位是否有效都不进入尾段, +// 其所在日之前的日桶也不读取。 func (r *usageLogRepository) readGroupUsageRollupSnapshot(ctx context.Context, timezoneName, todayDate string) (groupUsageRollupSnapshot, error) { - epoch := time.Unix(0, 0).UTC() - invalid := groupUsageRollupSnapshot{ - closedBefore: "1970-01-01", - retainedDate: "1970-01-01", - tailStart: epoch, - } - var rowCount int var closedBefore sql.NullString var retainedFrom sql.NullTime var stateTimezone sql.NullString + var expiredBefore sql.NullTime if err := scanSingleRow(ctx, r.sql, ` SELECT COUNT(*), MAX(closed_before)::text, MAX(retained_from), - MAX(timezone_name) + MAX(timezone_name), + MAX(expired_before) FROM usage_group_rollup_state WHERE id = 1 - `, nil, &rowCount, &closedBefore, &retainedFrom, &stateTimezone); err != nil { + `, nil, &rowCount, &closedBefore, &retainedFrom, &stateTimezone, &expiredBefore); err != nil { return groupUsageRollupSnapshot{}, fmt.Errorf("读取分组用量汇总水位: %w", err) } + + tailFloor := time.Unix(0, 0).UTC() + if rowCount == 1 && expiredBefore.Valid && expiredBefore.Time.After(tailFloor) { + tailFloor = expiredBefore.Time.UTC() + } + invalid := groupUsageRollupSnapshot{ + closedBefore: "1970-01-01", + retainedDate: "1970-01-01", + tailStart: tailFloor, + } if rowCount != 1 || !closedBefore.Valid || !retainedFrom.Valid || !stateTimezone.Valid || stateTimezone.String != timezoneName || closedBefore.String > todayDate { @@ -58,11 +67,19 @@ func (r *usageLogRepository) readGroupUsageRollupSnapshot(ctx context.Context, t // 水位值解析不出来,按无效处理:宁可多扫一次,也不要算错钱。 return invalid, nil //nolint:nilerr // 与上面的 valid 判定同语义,均降级为全量重算 } + tailStart = tailStart.UTC() + if tailFloor.After(tailStart) { + tailStart = tailFloor + } + retainedDate := service.GroupUsageDate(retainedFrom.Time) + if expiredDate := service.GroupUsageDate(tailFloor); expiredDate > retainedDate { + retainedDate = expiredDate + } return groupUsageRollupSnapshot{ valid: true, closedBefore: closedBefore.String, - retainedDate: service.GroupUsageDate(retainedFrom.Time), - tailStart: tailStart.UTC(), + retainedDate: retainedDate, + tailStart: tailStart, }, nil } @@ -162,94 +179,287 @@ func (r *usageLogRepository) getAllGroupUsageSummaryFromRollups(ctx context.Cont return results, nil } +const ( + groupUsageRollupBuildLockSQL = "SELECT pg_try_advisory_lock(hashtext('usage_group_daily_rollups:build'))" + groupUsageRollupBuildUnlockSQL = "SELECT pg_advisory_unlock(hashtext('usage_group_daily_rollups:build'))" + // groupUsageRollupBuildMaxRounds 限定一次同步内因并发变更重算脏区间的轮数; + // 未收敛的部分保持未发布,由下一次同步继续。 + groupUsageRollupBuildMaxRounds = 3 +) + +var errGroupUsageRollupBuildPreempted = errors.New("分组用量汇总重建登记已被替换") + +// groupUsageRollupBuildPlan 是一轮日桶重建:用 [rowsFrom, rowsBefore) 的 usage_logs +// 重算 [startDate, targetDate) 的日桶,并清理 retainedDate 之前的日桶。 +type groupUsageRollupBuildPlan struct { + startDate string + targetDate string + retainedDate string + rowsFrom time.Time + rowsBefore time.Time + timezoneName string +} + +// groupUsageRollupTxRunner 在一个事务里执行 fn。 +type groupUsageRollupTxRunner func(ctx context.Context, fn func(q sqlExecutor) error) error + // SyncGroupUsageRollups 将服务端配置时区今日以前的用量发布为分组日桶。 +// +// 每轮分三个事务:登记(FOR UPDATE,写入 building_until)、计算(FOR KEY SHARE,重算日桶)、 +// 发布(FOR UPDATE,水位推进到 build_dirty_from 或目标日期)。usage_logs 写入与失效触发器只持 +// FOR KEY SHARE,因此只与登记、发布这两个短事务串行,计算阶段不阻塞写入。 +// 以 *sql.DB 构造时,整个过程持有会话级 advisory lock,同一时刻只有一个重建; +// 以事务构造时,三个阶段在调用方事务内顺序执行。 func (r *dashboardAggregationRepository) SyncGroupUsageRollups(ctx context.Context, todayStart time.Time) error { if r == nil || r.sql == nil { return nil } todayStart = service.GroupUsageTodayStart(todayStart) - if db, ok := r.sql.(*sql.DB); ok { - tx, err := db.BeginTx(ctx, nil) + db, ok := r.sql.(*sql.DB) + if !ok { + return syncGroupUsageRollupRounds(ctx, func(ctx context.Context, fn func(q sqlExecutor) error) error { + return fn(r.sql) + }, todayStart) + } + + upToDate, err := groupUsageRollupsUpToDate(ctx, db, todayStart) + if err != nil { + return err + } + if upToDate { + return nil + } + + conn, err := db.Conn(ctx) + if err != nil { + return err + } + var locked bool + if err := scanSingleRow(ctx, conn, groupUsageRollupBuildLockSQL, nil, &locked); err != nil { + // 查询出错时服务端可能已授予锁,丢弃该物理连接以免锁随连接回到连接池。 + discardGroupUsageRollupBuildConn(conn) + return fmt.Errorf("获取分组用量汇总重建锁: %w", err) + } + if !locked { + return conn.Close() + } + defer releaseGroupUsageRollupBuildLock(conn) + + return syncGroupUsageRollupRounds(ctx, func(ctx context.Context, fn func(q sqlExecutor) error) error { + tx, err := conn.BeginTx(ctx, nil) if err != nil { return err } - txRepo := newDashboardAggregationRepositoryWithSQL(tx) - if err := txRepo.syncGroupUsageRollupsInTx(ctx, todayStart); err != nil { + if err := fn(tx); err != nil { _ = tx.Rollback() return err } return tx.Commit() - } - return r.syncGroupUsageRollupsInTx(ctx, todayStart) + }, todayStart) } -func (r *dashboardAggregationRepository) syncGroupUsageRollupsInTx(ctx context.Context, todayStart time.Time) error { +// releaseGroupUsageRollupBuildLock 释放重建锁;释放失败时丢弃该物理连接,由服务端随会话结束释放锁, +// 避免锁随连接回到连接池。 +func releaseGroupUsageRollupBuildLock(conn *sql.Conn) { + unlockCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + var unlocked bool + if err := scanSingleRow(unlockCtx, conn, groupUsageRollupBuildUnlockSQL, nil, &unlocked); err != nil || !unlocked { + discardGroupUsageRollupBuildConn(conn) + return + } + _ = conn.Close() +} + +// discardGroupUsageRollupBuildConn 关闭底层物理连接而不是归还连接池,会话级锁随会话结束释放。 +func discardGroupUsageRollupBuildConn(conn *sql.Conn) { + _ = conn.Raw(func(any) error { return driver.ErrBadConn }) + _ = conn.Close() +} + +// groupUsageRollupsUpToDate 不加锁地判断今日以前的日桶是否已全部发布。 +func groupUsageRollupsUpToDate(ctx context.Context, q sqlQueryer, todayStart time.Time) (bool, error) { var closedBefore string - var previousRetainedFrom time.Time var stateTimezoneName string - if err := scanSingleRow(ctx, r.sql, ` - SELECT closed_before::text, retained_from, timezone_name + var idle bool + err := scanSingleRow(ctx, q, ` + SELECT closed_before::text, timezone_name, building_until IS NULL + FROM usage_group_rollup_state + WHERE id = 1 + `, nil, &closedBefore, &stateTimezoneName, &idle) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("读取分组用量汇总水位: %w", err) + } + return idle && + closedBefore == service.GroupUsageDate(todayStart) && + stateTimezoneName == service.GroupUsageTimezoneName(), nil +} + +func syncGroupUsageRollupRounds(ctx context.Context, run groupUsageRollupTxRunner, todayStart time.Time) error { + for range groupUsageRollupBuildMaxRounds { + var plan *groupUsageRollupBuildPlan + if err := run(ctx, func(q sqlExecutor) error { + var err error + plan, err = beginGroupUsageRollupBuild(ctx, q, todayStart) + return err + }); err != nil { + return err + } + if plan == nil { + return nil + } + if err := run(ctx, func(q sqlExecutor) error { + return buildGroupUsageRollups(ctx, q, plan) + }); err != nil { + return err + } + var dirty bool + if err := run(ctx, func(q sqlExecutor) error { + var err error + dirty, err = publishGroupUsageRollups(ctx, q, plan) + return err + }); err != nil { + return err + } + if !dirty { + return nil + } + } + return nil +} + +// beginGroupUsageRollupBuild 在 FOR UPDATE 下确定重建区间并登记 building_until。 +// 日桶已发布到今日时返回 nil。 +func beginGroupUsageRollupBuild(ctx context.Context, q sqlExecutor, todayStart time.Time) (*groupUsageRollupBuildPlan, error) { + var closedBefore string + var retainedFrom time.Time + var stateTimezoneName string + var expiredBefore time.Time + var buildingUntil sql.NullString + if err := scanSingleRow(ctx, q, ` + SELECT closed_before::text, retained_from, timezone_name, expired_before, building_until::text FROM usage_group_rollup_state WHERE id = 1 FOR UPDATE - `, nil, &closedBefore, &previousRetainedFrom, &stateTimezoneName); err != nil { - return fmt.Errorf("读取分组用量汇总水位: %w", err) + `, nil, &closedBefore, &retainedFrom, &stateTimezoneName, &expiredBefore, &buildingUntil); err != nil { + return nil, fmt.Errorf("读取分组用量汇总水位: %w", err) } todayDate := service.GroupUsageDate(todayStart) timezoneName := service.GroupUsageTimezoneName() timezoneChanged := stateTimezoneName != timezoneName - var closedTime time.Time if !timezoneChanged { - var err error - closedTime, err = service.ParseGroupUsageDate(closedBefore) + closedTime, err := service.ParseGroupUsageDate(closedBefore) if err != nil { - return fmt.Errorf("解析分组用量汇总水位 %q: %w", closedBefore, err) + return nil, fmt.Errorf("解析分组用量汇总水位 %q: %w", closedBefore, err) } todayDateTime, err := service.ParseGroupUsageDate(todayDate) if err != nil { - return err + return nil, err } if closedTime.After(todayDateTime) { - return fmt.Errorf("分组用量汇总水位位于未来: %s", closedBefore) + return nil, fmt.Errorf("分组用量汇总水位位于未来: %s", closedBefore) } if closedBefore == todayDate { - return nil + if buildingUntil.Valid { + if _, err := q.ExecContext(ctx, ` + UPDATE usage_group_rollup_state + SET building_until = NULL, + build_dirty_from = NULL, + updated_at = NOW() + WHERE id = 1 + `); err != nil { + return nil, fmt.Errorf("清除分组用量汇总重建登记: %w", err) + } + } + return nil, nil } } - var earliest sql.NullTime - if err := scanSingleRow(ctx, r.sql, "SELECT MIN(created_at) FROM usage_logs", nil, &earliest); err != nil { - return fmt.Errorf("读取最早用量记录: %w", err) - } - retainedFrom := todayStart - if earliest.Valid { - retainedFrom = earliest.Time.UTC() + // 可读日桶从 retained_from 所在日开始,且不早于保留下界。 + if retainedFrom.Before(expiredBefore) { + retainedFrom = expiredBefore } + // closed_before 不晚于保留起点时,可读日桶为空,按保留起点全量重建;否则从水位续建。 retainedDate := service.GroupUsageDate(retainedFrom) - retainedDateTime, err := service.ParseGroupUsageDate(retainedDate) - if err != nil { - return err - } - rebuildStartDate := retainedDate - if !timezoneChanged && closedTime.After(retainedDateTime) { - rebuildStartDate = closedBefore - } - rebuildStart, err := service.ParseGroupUsageDate(rebuildStartDate) - if err != nil { - return err + startDate := closedBefore + if timezoneChanged || closedBefore <= retainedDate { + var earliest sql.NullTime + if err := scanSingleRow(ctx, q, ` + SELECT MIN(created_at) + FROM usage_logs + WHERE created_at >= $1 + `, []any{expiredBefore.UTC()}, &earliest); err != nil { + return nil, fmt.Errorf("读取最早用量记录: %w", err) + } + retainedFrom = todayStart + if earliest.Valid { + retainedFrom = earliest.Time.UTC() + } + retainedDate = service.GroupUsageDate(retainedFrom) + startDate = retainedDate } - if _, err := r.sql.ExecContext(ctx, ` + if _, err := q.ExecContext(ctx, ` + UPDATE usage_group_rollup_state + SET closed_before = $1::date, + retained_from = $2, + timezone_name = $3, + building_until = $4::date, + build_dirty_from = NULL, + updated_at = NOW() + WHERE id = 1 + `, startDate, retainedFrom.UTC(), timezoneName, todayDate); err != nil { + return nil, fmt.Errorf("登记分组用量汇总重建: %w", err) + } + + startTime, err := service.ParseGroupUsageDate(startDate) + if err != nil { + return nil, err + } + rowsFrom := startTime.UTC() + if expiredBefore.After(rowsFrom) { + rowsFrom = expiredBefore.UTC() + } + return &groupUsageRollupBuildPlan{ + startDate: startDate, + targetDate: todayDate, + retainedDate: retainedDate, + rowsFrom: rowsFrom, + rowsBefore: todayStart.UTC(), + timezoneName: timezoneName, + }, nil +} + +// buildGroupUsageRollups 重算 [startDate, targetDate) 的日桶,只写入本地日期不早于 startDate 的桶。 +// 状态行只持 FOR KEY SHARE,与 usage_logs 写入和失效触发器兼容;登记与发布的 FOR UPDATE 须等待本事务结束。 +func buildGroupUsageRollups(ctx context.Context, q sqlExecutor, plan *groupUsageRollupBuildPlan) error { + var buildingUntil sql.NullString + var stateTimezoneName string + if err := scanSingleRow(ctx, q, ` + SELECT building_until::text, timezone_name + FROM usage_group_rollup_state + WHERE id = 1 + FOR KEY SHARE + `, nil, &buildingUntil, &stateTimezoneName); err != nil { + return fmt.Errorf("读取分组用量汇总重建登记: %w", err) + } + if !buildingUntil.Valid || buildingUntil.String != plan.targetDate || stateTimezoneName != plan.timezoneName { + return errGroupUsageRollupBuildPreempted + } + + if _, err := q.ExecContext(ctx, ` DELETE FROM usage_group_daily_rollups WHERE bucket_date < $1::date - OR (bucket_date >= $2::date AND bucket_date < $3::date) - OR bucket_date >= $3::date - `, retainedDate, rebuildStartDate, todayDate); err != nil { + OR bucket_date >= $2::date + `, plan.retainedDate, plan.startDate); err != nil { return fmt.Errorf("清理分组用量日桶: %w", err) } - if _, err := r.sql.ExecContext(ctx, ` + if _, err := q.ExecContext(ctx, ` INSERT INTO usage_group_daily_rollups (bucket_date, group_id, actual_cost, computed_at) SELECT (created_at AT TIME ZONE $3::text)::date AS bucket_date, @@ -260,51 +470,82 @@ func (r *dashboardAggregationRepository) syncGroupUsageRollupsInTx(ctx context.C WHERE group_id IS NOT NULL AND created_at >= $1 AND created_at < $2 + AND (created_at AT TIME ZONE $3::text)::date >= $4::date GROUP BY 1, 2 ON CONFLICT (bucket_date, group_id) DO UPDATE SET actual_cost = EXCLUDED.actual_cost, computed_at = EXCLUDED.computed_at - `, rebuildStart.UTC(), todayStart.UTC(), timezoneName); err != nil { + `, plan.rowsFrom, plan.rowsBefore, plan.timezoneName, plan.startDate); err != nil { return fmt.Errorf("重建分组用量日桶: %w", err) } - - if _, err := r.sql.ExecContext(ctx, ` - UPDATE usage_group_rollup_state - SET closed_before = $1::date, - retained_from = $2, - timezone_name = $3, - updated_at = NOW() - WHERE id = 1 - `, todayDate, retainedFrom, timezoneName); err != nil { - return fmt.Errorf("更新分组用量汇总水位: %w", err) - } return nil } -func lockGroupUsageRollupState(ctx context.Context, tx *sql.Tx) error { - var id int16 - if err := tx.QueryRowContext(ctx, ` - SELECT id +// publishGroupUsageRollups 在 FOR UPDATE 下发布本轮结果并清除登记,返回是否存在需要重算的脏区间。 +// +// 登记之后 [startDate, targetDate) 内的源记录变更都记入了 build_dirty_from,[startDate, build_dirty_from) +// 的日桶与计算快照一致;水位低于 startDate 说明有未记脏的失效,此时发布不越过当前水位。 +func publishGroupUsageRollups(ctx context.Context, q sqlExecutor, plan *groupUsageRollupBuildPlan) (bool, error) { + var closedBefore string + var buildingUntil sql.NullString + var dirtyFrom sql.NullString + if err := scanSingleRow(ctx, q, ` + SELECT closed_before::text, building_until::text, build_dirty_from::text FROM usage_group_rollup_state WHERE id = 1 FOR UPDATE - `).Scan(&id); err != nil { - return fmt.Errorf("锁定分组用量汇总水位: %w", err) + `, nil, &closedBefore, &buildingUntil, &dirtyFrom); err != nil { + return false, fmt.Errorf("读取分组用量汇总重建登记: %w", err) + } + if !buildingUntil.Valid || buildingUntil.String != plan.targetDate { + return false, errGroupUsageRollupBuildPreempted + } + + publishBefore := plan.targetDate + dirty := false + if dirtyFrom.Valid && dirtyFrom.String < publishBefore { + publishBefore = dirtyFrom.String + dirty = true + } + if closedBefore < plan.startDate && closedBefore < publishBefore { + publishBefore = closedBefore + dirty = true + } + + if _, err := q.ExecContext(ctx, ` + UPDATE usage_group_rollup_state + SET closed_before = $1::date, + building_until = NULL, + build_dirty_from = NULL, + updated_at = NOW() + WHERE id = 1 + `, publishBefore); err != nil { + return false, fmt.Errorf("发布分组用量汇总水位: %w", err) + } + return dirty, nil +} + +// expireGroupUsageRollupsBefore 把保留下界推进到 cutoff:早于 cutoff 的 usage_logs 不属于任何可读日桶, +// 删除它们不触发失效。cutoff 须为服务端配置时区的自然日零点,使边界日桶不包含被删除的记录。 +func expireGroupUsageRollupsBefore(ctx context.Context, q sqlExecutor, cutoff time.Time) error { + if _, err := q.ExecContext(ctx, ` + UPDATE usage_group_rollup_state + SET expired_before = GREATEST(expired_before, $1), + retained_from = GREATEST(retained_from, $1), + updated_at = NOW() + WHERE id = 1 + `, cutoff.UTC()); err != nil { + return fmt.Errorf("推进分组用量汇总保留下界: %w", err) } return nil } -func invalidateGroupUsageRollupsAt(ctx context.Context, tx *sql.Tx, affectedAt time.Time) error { - timezoneName := service.GroupUsageTimezoneName() - _, err := tx.ExecContext(ctx, ` - UPDATE usage_group_rollup_state - SET closed_before = LEAST( - closed_before, - ($1::timestamptz AT TIME ZONE $2::text)::date - ), - updated_at = NOW() - WHERE id = 1 - `, affectedAt.UTC(), timezoneName) +// invalidateGroupUsageRollupsAt 使 affectedAt 所在自然日及之后的日桶失效;早于保留下界的时刻不生效。 +func invalidateGroupUsageRollupsAt(ctx context.Context, q sqlExecutor, affectedAt time.Time) error { + _, err := q.ExecContext(ctx, + "SELECT invalidate_group_usage_rollups_at($1, $2)", + affectedAt.UTC(), service.GroupUsageTimezoneName(), + ) return err } diff --git a/backend/internal/repository/dashboard_aggregation_group_usage_test.go b/backend/internal/repository/dashboard_aggregation_group_usage_test.go index 40bca32bc4..31365c156b 100644 --- a/backend/internal/repository/dashboard_aggregation_group_usage_test.go +++ b/backend/internal/repository/dashboard_aggregation_group_usage_test.go @@ -5,61 +5,146 @@ package repository import ( "context" "database/sql" + "database/sql/driver" "errors" "testing" "time" "github.com/DATA-DOG/go-sqlmock" "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/lib/pq" "github.com/stretchr/testify/require" ) -func TestDashboardAggregationRepositorySyncGroupUsageRollupsNoopsAtCurrentDate(t *testing.T) { +const ( + groupRollupPrecheckQuery = `SELECT closed_before::text, timezone_name, building_until IS NULL` + groupRollupLockQuery = `SELECT pg_try_advisory_lock\(hashtext\('usage_group_daily_rollups:build'\)\)` + groupRollupUnlockQuery = `SELECT pg_advisory_unlock\(hashtext\('usage_group_daily_rollups:build'\)\)` + groupRollupBeginQuery = `(?s)SELECT closed_before::text, retained_from, timezone_name, expired_before, building_until::text.*FOR UPDATE` + groupRollupBuildQuery = `(?s)SELECT building_until::text, timezone_name.*FOR KEY SHARE` + groupRollupPublishQuery = `(?s)SELECT closed_before::text, building_until::text, build_dirty_from::text.*FOR UPDATE` + groupRollupRegisterExec = `(?s)UPDATE usage_group_rollup_state.*building_until = \$4::date` + groupRollupPublishExec = `(?s)UPDATE usage_group_rollup_state.*SET closed_before = \$1::date,\s+building_until = NULL` + groupRollupExpireExec = `(?s)UPDATE usage_group_rollup_state.*expired_before = GREATEST\(expired_before, \$1\)` + groupRollupInvalidateSQL = `SELECT invalidate_group_usage_rollups_at\(\$1, \$2\)` +) + +var groupRollupEpoch = time.Unix(0, 0).UTC() + +func expectGroupRollupPrecheck(mock sqlmock.Sqlmock, closedBefore, timezoneName string, idle bool) { + mock.ExpectQuery(groupRollupPrecheckQuery). + WillReturnRows(sqlmock.NewRows([]string{"closed_before", "timezone_name", "idle"}). + AddRow(closedBefore, timezoneName, idle)) +} + +func expectGroupRollupLock(mock sqlmock.Sqlmock, locked bool) { + mock.ExpectQuery(groupRollupLockQuery). + WillReturnRows(sqlmock.NewRows([]string{"locked"}).AddRow(locked)) +} + +func expectGroupRollupUnlock(mock sqlmock.Sqlmock) { + mock.ExpectQuery(groupRollupUnlockQuery). + WillReturnRows(sqlmock.NewRows([]string{"unlocked"}).AddRow(true)) +} + +func groupRollupBeginRows(closedBefore string, retainedFrom time.Time, timezoneName string, expiredBefore time.Time, buildingUntil any) *sqlmock.Rows { + return sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name", "expired_before", "building_until"}). + AddRow(closedBefore, retainedFrom, timezoneName, expiredBefore, buildingUntil) +} + +// expectGroupRollupRound 期望一轮完整的登记、计算、发布。 +func expectGroupRollupRound( + mock sqlmock.Sqlmock, + begin *sqlmock.Rows, + minCreatedAt *sqlmock.Rows, + minCreatedAfter time.Time, + register []any, + deleteArgs []any, + insertArgs []any, + publishRows *sqlmock.Rows, + publishBefore string, +) { + mock.ExpectBegin() + mock.ExpectQuery(groupRollupBeginQuery).WillReturnRows(begin) + if minCreatedAt != nil { + mock.ExpectQuery(`(?s)SELECT MIN\(created_at\)\s+FROM usage_logs\s+WHERE created_at >= \$1`). + WithArgs(minCreatedAfter). + WillReturnRows(minCreatedAt) + } + mock.ExpectExec(groupRollupRegisterExec). + WithArgs(toDriverValues(register)...). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectCommit() + + mock.ExpectBegin() + mock.ExpectQuery(groupRollupBuildQuery). + WillReturnRows(sqlmock.NewRows([]string{"building_until", "timezone_name"}).AddRow(register[3], register[2])) + mock.ExpectExec(`DELETE FROM usage_group_daily_rollups`). + WithArgs(toDriverValues(deleteArgs)...). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec(`INSERT INTO usage_group_daily_rollups`). + WithArgs(toDriverValues(append(append([]any{}, insertArgs...), register[0]))...). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectCommit() + + mock.ExpectBegin() + mock.ExpectQuery(groupRollupPublishQuery).WillReturnRows(publishRows) + mock.ExpectExec(groupRollupPublishExec). + WithArgs(publishBefore). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectCommit() +} + +func toDriverValues(values []any) []driver.Value { + args := make([]driver.Value, 0, len(values)) + for _, value := range values { + args = append(args, sqlmockValue{value: value}) + } + return args +} + +// sqlmockValue 按时刻比较 time.Time(忽略 Location),其余值按相等比较。 +type sqlmockValue struct{ value any } + +func (v sqlmockValue) Match(actual driver.Value) bool { + if expectedTime, ok := v.value.(time.Time); ok { + actualTime, ok := actual.(time.Time) + return ok && actualTime.Equal(expectedTime) + } + return actual == v.value +} + +func publishRows(closedBefore, buildingUntil string, dirtyFrom any) *sqlmock.Rows { + return sqlmock.NewRows([]string{"closed_before", "building_until", "build_dirty_from"}). + AddRow(closedBefore, buildingUntil, dirtyFrom) +} + +func TestDashboardAggregationRepositorySyncGroupUsageRollupsNoopsWithoutLockingAtCurrentDate(t *testing.T) { setGroupUsageRollupTestTimezone(t) db, mock := newSQLMock(t) repo := newDashboardAggregationRepositoryWithSQL(db) todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) - mock.ExpectBegin() - mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}). - AddRow("2026-08-14", time.Unix(0, 0).UTC(), "Asia/Shanghai")) - mock.ExpectCommit() + expectGroupRollupPrecheck(mock, "2026-08-14", "Asia/Shanghai", true) require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) require.NoError(t, mock.ExpectationsWereMet()) } -func TestDashboardAggregationRepositorySyncGroupUsageRollupsRebuildsWhenTimezoneChanges(t *testing.T) { - useGroupUsageRepositoryTestTimezone(t, "America/New_York") - +func TestDashboardAggregationRepositorySyncGroupUsageRollupsSkipsWhenAnotherBuildHoldsLock(t *testing.T) { + setGroupUsageRollupTestTimezone(t) db, mock := newSQLMock(t) repo := newDashboardAggregationRepositoryWithSQL(db) - todayStart := time.Date(2026, 3, 9, 4, 0, 0, 0, time.UTC) - retainedFrom := time.Date(2026, 3, 1, 5, 0, 0, 0, time.UTC) + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) - mock.ExpectBegin() - mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}). - AddRow("2026-03-09", time.Unix(0, 0).UTC(), "Asia/Shanghai")) - mock.ExpectQuery(`SELECT MIN\(created_at\) FROM usage_logs`). - WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(retainedFrom)) - mock.ExpectExec(`DELETE FROM usage_group_daily_rollups`). - WithArgs("2026-03-01", "2026-03-01", "2026-03-09"). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectExec(`INSERT INTO usage_group_daily_rollups`). - WithArgs(retainedFrom, todayStart, "America/New_York"). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs("2026-03-09", retainedFrom, "America/New_York"). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectCommit() + expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true) + expectGroupRollupLock(mock, false) require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) require.NoError(t, mock.ExpectationsWereMet()) } -func TestDashboardAggregationRepositorySyncGroupUsageRollupsPublishesWatermarkLast(t *testing.T) { +func TestDashboardAggregationRepositorySyncGroupUsageRollupsBuildsAndPublishesInSeparateTransactions(t *testing.T) { setGroupUsageRollupTestTimezone(t) db, mock := newSQLMock(t) repo := newDashboardAggregationRepositoryWithSQL(db) @@ -67,22 +152,209 @@ func TestDashboardAggregationRepositorySyncGroupUsageRollupsPublishesWatermarkLa retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC) rebuildStart := time.Date(2026, 8, 12, 16, 0, 0, 0, time.UTC) + expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true) + expectGroupRollupLock(mock, true) + expectGroupRollupRound(mock, + groupRollupBeginRows("2026-08-13", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil), + nil, time.Time{}, + []any{"2026-08-13", retainedFrom, "Asia/Shanghai", "2026-08-14"}, + []any{"2026-05-01", "2026-08-13"}, + []any{rebuildStart, todayStart, "Asia/Shanghai"}, + publishRows("2026-08-13", "2026-08-14", nil), + "2026-08-14", + ) + expectGroupRollupUnlock(mock) + + require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestDashboardAggregationRepositorySyncGroupUsageRollupsRebuildsDirtyRangeBeforeFullPublish(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC) + + expectGroupRollupPrecheck(mock, "2026-08-11", "Asia/Shanghai", true) + expectGroupRollupLock(mock, true) + // 第一轮计算期间有 08-12 的迟到写入:只发布到 08-12。 + expectGroupRollupRound(mock, + groupRollupBeginRows("2026-08-11", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil), + nil, time.Time{}, + []any{"2026-08-11", retainedFrom, "Asia/Shanghai", "2026-08-14"}, + []any{"2026-05-01", "2026-08-11"}, + []any{time.Date(2026, 8, 10, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"}, + publishRows("2026-08-11", "2026-08-14", "2026-08-12"), + "2026-08-12", + ) + // 第二轮只重算脏日期之后的区间。 + expectGroupRollupRound(mock, + groupRollupBeginRows("2026-08-12", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil), + nil, time.Time{}, + []any{"2026-08-12", retainedFrom, "Asia/Shanghai", "2026-08-14"}, + []any{"2026-05-01", "2026-08-12"}, + []any{time.Date(2026, 8, 11, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"}, + publishRows("2026-08-12", "2026-08-14", nil), + "2026-08-14", + ) + expectGroupRollupUnlock(mock) + + require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestDashboardAggregationRepositorySyncGroupUsageRollupsStopsAfterMaxRoundsWithoutOverPublishing(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC) + + expectGroupRollupPrecheck(mock, "2026-08-12", "Asia/Shanghai", true) + expectGroupRollupLock(mock, true) + for range groupUsageRollupBuildMaxRounds { + expectGroupRollupRound(mock, + groupRollupBeginRows("2026-08-12", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil), + nil, time.Time{}, + []any{"2026-08-12", retainedFrom, "Asia/Shanghai", "2026-08-14"}, + []any{"2026-05-01", "2026-08-12"}, + []any{time.Date(2026, 8, 11, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"}, + publishRows("2026-08-12", "2026-08-14", "2026-08-12"), + "2026-08-12", + ) + } + expectGroupRollupUnlock(mock) + + require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestDashboardAggregationRepositorySyncGroupUsageRollupsPublishKeepsUnmarkedInvalidation(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC) + + expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true) + expectGroupRollupLock(mock, true) + // 计算期间水位被后退到 08-10 而没有记脏:发布不越过 08-10。 + expectGroupRollupRound(mock, + groupRollupBeginRows("2026-08-13", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil), + nil, time.Time{}, + []any{"2026-08-13", retainedFrom, "Asia/Shanghai", "2026-08-14"}, + []any{"2026-05-01", "2026-08-13"}, + []any{time.Date(2026, 8, 12, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"}, + publishRows("2026-08-10", "2026-08-14", nil), + "2026-08-10", + ) + expectGroupRollupRound(mock, + groupRollupBeginRows("2026-08-10", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil), + nil, time.Time{}, + []any{"2026-08-10", retainedFrom, "Asia/Shanghai", "2026-08-14"}, + []any{"2026-05-01", "2026-08-10"}, + []any{time.Date(2026, 8, 9, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"}, + publishRows("2026-08-10", "2026-08-14", nil), + "2026-08-14", + ) + expectGroupRollupUnlock(mock) + + require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestDashboardAggregationRepositorySyncGroupUsageRollupsRebuildsWhenTimezoneChanges(t *testing.T) { + useGroupUsageRepositoryTestTimezone(t, "America/New_York") + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + todayStart := time.Date(2026, 3, 9, 4, 0, 0, 0, time.UTC) + retainedFrom := time.Date(2026, 3, 1, 5, 0, 0, 0, time.UTC) + + expectGroupRollupPrecheck(mock, "2026-03-09", "Asia/Shanghai", true) + expectGroupRollupLock(mock, true) + expectGroupRollupRound(mock, + groupRollupBeginRows("2026-03-09", groupRollupEpoch, "Asia/Shanghai", groupRollupEpoch, nil), + sqlmock.NewRows([]string{"min"}).AddRow(retainedFrom), groupRollupEpoch, + []any{"2026-03-01", retainedFrom, "America/New_York", "2026-03-09"}, + []any{"2026-03-01", "2026-03-01"}, + []any{retainedFrom, todayStart, "America/New_York"}, + publishRows("2026-03-01", "2026-03-09", nil), + "2026-03-09", + ) + expectGroupRollupUnlock(mock) + + require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestDashboardAggregationRepositorySyncGroupUsageRollupsFullRebuildExcludesExpiredRows(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + // 保留下界不在 Asia/Shanghai 的日界上(例如在其他时区下推进):重建只计入下界之后的记录。 + expiredBefore := time.Date(2026, 5, 1, 18, 0, 0, 0, time.UTC) + earliestRetained := time.Date(2026, 5, 1, 19, 0, 0, 0, time.UTC) + + expectGroupRollupPrecheck(mock, "1970-01-01", "Asia/Shanghai", true) + expectGroupRollupLock(mock, true) + expectGroupRollupRound(mock, + groupRollupBeginRows("1970-01-01", groupRollupEpoch, "Asia/Shanghai", expiredBefore, nil), + sqlmock.NewRows([]string{"min"}).AddRow(earliestRetained), expiredBefore, + []any{"2026-05-02", earliestRetained, "Asia/Shanghai", "2026-08-14"}, + []any{"2026-05-02", "2026-05-02"}, + []any{expiredBefore, todayStart, "Asia/Shanghai"}, + publishRows("2026-05-02", "2026-08-14", nil), + "2026-08-14", + ) + expectGroupRollupUnlock(mock) + + require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestDashboardAggregationRepositorySyncGroupUsageRollupsKeepsRetainedFromAtExpiredFloor(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + staleRetainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC) + expiredBefore := time.Date(2026, 5, 14, 16, 0, 0, 0, time.UTC) + + expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true) + expectGroupRollupLock(mock, true) + // retained_from 早于保留下界(例如被其他版本的同步改写):登记与清理都以保留下界为起点。 + expectGroupRollupRound(mock, + groupRollupBeginRows("2026-08-13", staleRetainedFrom, "Asia/Shanghai", expiredBefore, nil), + nil, time.Time{}, + []any{"2026-08-13", expiredBefore, "Asia/Shanghai", "2026-08-14"}, + []any{"2026-05-15", "2026-08-13"}, + []any{time.Date(2026, 8, 12, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"}, + publishRows("2026-08-13", "2026-08-14", nil), + "2026-08-14", + ) + expectGroupRollupUnlock(mock) + + require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestDashboardAggregationRepositorySyncGroupUsageRollupsClearsStaleBuildMarkWhenPublished(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + + expectGroupRollupPrecheck(mock, "2026-08-14", "Asia/Shanghai", false) + expectGroupRollupLock(mock, true) mock.ExpectBegin() - mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}). - AddRow("2026-08-13", time.Unix(0, 0).UTC(), "Asia/Shanghai")) - mock.ExpectQuery(`SELECT MIN\(created_at\) FROM usage_logs`). - WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(retainedFrom)) - mock.ExpectExec(`DELETE FROM usage_group_daily_rollups`). - WithArgs("2026-05-01", "2026-08-13", "2026-08-14"). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectExec(`INSERT INTO usage_group_daily_rollups`). - WithArgs(rebuildStart, todayStart, "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 2)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs("2026-08-14", retainedFrom, "Asia/Shanghai"). + mock.ExpectQuery(groupRollupBeginQuery). + WillReturnRows(groupRollupBeginRows("2026-08-14", groupRollupEpoch, "Asia/Shanghai", groupRollupEpoch, "2026-08-14")) + mock.ExpectExec(`(?s)UPDATE usage_group_rollup_state\s+SET building_until = NULL`). WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectCommit() + expectGroupRollupUnlock(mock) require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart)) require.NoError(t, mock.ExpectationsWereMet()) @@ -94,17 +366,44 @@ func TestDashboardAggregationRepositorySyncGroupUsageRollupsRejectsFutureWaterma repo := newDashboardAggregationRepositoryWithSQL(db) todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + expectGroupRollupPrecheck(mock, "2026-08-15", "Asia/Shanghai", true) + expectGroupRollupLock(mock, true) mock.ExpectBegin() - mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}). - AddRow("2026-08-15", time.Unix(0, 0).UTC(), "Asia/Shanghai")) + mock.ExpectQuery(groupRollupBeginQuery). + WillReturnRows(groupRollupBeginRows("2026-08-15", groupRollupEpoch, "Asia/Shanghai", groupRollupEpoch, nil)) mock.ExpectRollback() + expectGroupRollupUnlock(mock) err := repo.SyncGroupUsageRollups(context.Background(), todayStart) require.ErrorContains(t, err, "未来") require.NoError(t, mock.ExpectationsWereMet()) } +func TestDashboardAggregationRepositorySyncGroupUsageRollupsAbortsWhenBuildMarkReplaced(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC) + + expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true) + expectGroupRollupLock(mock, true) + mock.ExpectBegin() + mock.ExpectQuery(groupRollupBeginQuery). + WillReturnRows(groupRollupBeginRows("2026-08-13", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil)) + mock.ExpectExec(groupRollupRegisterExec).WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectCommit() + mock.ExpectBegin() + mock.ExpectQuery(groupRollupBuildQuery). + WillReturnRows(sqlmock.NewRows([]string{"building_until", "timezone_name"}).AddRow(nil, "Asia/Shanghai")) + mock.ExpectRollback() + expectGroupRollupUnlock(mock) + + err := repo.SyncGroupUsageRollups(context.Background(), todayStart) + require.ErrorIs(t, err, errGroupUsageRollupBuildPreempted) + require.NoError(t, mock.ExpectationsWereMet()) +} + func TestDashboardAggregationRepositoryRecomputeRangeInvalidatesGroupRollupsBeforeDashboardRebuild(t *testing.T) { setGroupUsageRollupTestTimezone(t) db, mock := newSQLMock(t) @@ -112,12 +411,10 @@ func TestDashboardAggregationRepositoryRecomputeRangeInvalidatesGroupRollupsBefo start := time.Date(2026, 8, 1, 3, 0, 0, 0, time.UTC) end := start.Add(time.Hour) - mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). + mock.ExpectExec(groupRollupInvalidateSQL). WithArgs(start, "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 1)) + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectBegin() mock.ExpectExec(`DELETE FROM usage_dashboard_hourly`). WillReturnError(sql.ErrConnDone) mock.ExpectRollback() @@ -127,25 +424,17 @@ func TestDashboardAggregationRepositoryRecomputeRangeInvalidatesGroupRollupsBefo require.NoError(t, mock.ExpectationsWereMet()) } -func TestDashboardAggregationRepositoryRecomputeRangeRebuildsGroupRollupsBeforeCommit(t *testing.T) { +func TestDashboardAggregationRepositoryRecomputeRangeLeavesGroupRollupRebuildToSync(t *testing.T) { setGroupUsageRollupTestTimezone(t) db, mock := newSQLMock(t) repo := newDashboardAggregationRepositoryWithSQL(db) start := time.Date(2026, 8, 1, 3, 0, 0, 0, time.UTC) end := start.Add(time.Hour) - fixedNow := time.Date(2026, 8, 14, 8, 0, 0, 0, time.UTC) - repo.clock = func() time.Time { return fixedNow } - todayStart := service.GroupUsageTodayStart(fixedNow) - startDate := service.GroupUsageDate(start) - rebuildStart, err := service.ParseGroupUsageDate(startDate) - require.NoError(t, err) - mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). + mock.ExpectExec(groupRollupInvalidateSQL). WithArgs(start, "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 1)) + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectBegin() for _, query := range []string{ `DELETE FROM usage_dashboard_hourly WHERE`, `DELETE FROM usage_dashboard_hourly_users WHERE`, @@ -158,71 +447,67 @@ func TestDashboardAggregationRepositoryRecomputeRangeRebuildsGroupRollupsBeforeC } { mock.ExpectExec(query).WillReturnResult(sqlmock.NewResult(0, 1)) } - mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}). - AddRow(startDate, time.Unix(0, 0).UTC(), "Asia/Shanghai")) - mock.ExpectQuery(`SELECT MIN\(created_at\) FROM usage_logs`). - WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(start)) - mock.ExpectExec(`DELETE FROM usage_group_daily_rollups`). - WithArgs(startDate, startDate, service.GroupUsageDate(todayStart)). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectExec(`INSERT INTO usage_group_daily_rollups`). - WithArgs(rebuildStart.UTC(), todayStart.UTC(), "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs(service.GroupUsageDate(todayStart), start, "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectCommit() require.NoError(t, repo.RecomputeRange(context.Background(), start, end)) require.NoError(t, mock.ExpectationsWereMet()) } -func TestDashboardAggregationRepositoryCleanupUsageLogsNonPartitionedInvalidatesEachBatchAndSyncs(t *testing.T) { +func TestDashboardAggregationRepositoryRecomputeRangeStopsWhenInvalidationFails(t *testing.T) { setGroupUsageRollupTestTimezone(t) db, mock := newSQLMock(t) repo := newDashboardAggregationRepositoryWithSQL(db) - cutoff := time.Date(2026, 7, 1, 0, 0, 0, 0, time.UTC) - earliestDeletedAt := time.Date(2026, 5, 3, 2, 0, 0, 0, time.UTC) + start := time.Date(2026, 8, 1, 3, 0, 0, 0, time.UTC) + + mock.ExpectExec(groupRollupInvalidateSQL). + WithArgs(start, "Asia/Shanghai"). + WillReturnError(sql.ErrConnDone) + + err := repo.RecomputeRange(context.Background(), start, start.Add(time.Hour)) + require.ErrorIs(t, err, sql.ErrConnDone) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestDashboardAggregationRepositoryCleanupUsageLogsExpiresWholeDaysBeforeDeleting(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + // 2026-07-01 13:00 +08 对齐到 2026-07-01 00:00 +08。 + cutoff := time.Date(2026, 7, 1, 5, 0, 0, 0, time.UTC) + alignedCutoff := time.Date(2026, 6, 30, 16, 0, 0, 0, time.UTC) fixedNow := time.Date(2026, 8, 14, 8, 0, 0, 0, time.UTC) repo.clock = func() time.Time { return fixedNow } - todayStart := service.GroupUsageTodayStart(fixedNow) + mock.ExpectExec(groupRollupExpireExec). + WithArgs(alignedCutoff). + WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectQuery(`SELECT EXISTS`). WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(false)) - mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) - mock.ExpectQuery(`(?s)DELETE FROM usage_logs.*RETURNING created_at`). - WithArgs(cutoff, usageLogsCleanupBatchSize). - WillReturnRows(sqlmock.NewRows([]string{"created_at"}). - AddRow(earliestDeletedAt.Add(time.Hour)). - AddRow(earliestDeletedAt)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs(earliestDeletedAt, "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectCommit() - mock.ExpectBegin() - mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}). - AddRow(service.GroupUsageDate(todayStart), time.Unix(0, 0).UTC(), "Asia/Shanghai")) - mock.ExpectCommit() + mock.ExpectExec(`(?s)SELECT tableoid, ctid.*ORDER BY created_at ASC, id ASC.*DELETE FROM usage_logs`). + WithArgs(alignedCutoff, usageLogsCleanupBatchSize). + WillReturnResult(sqlmock.NewResult(0, usageLogsCleanupBatchSize)) + mock.ExpectExec(`(?s)SELECT tableoid, ctid.*DELETE FROM usage_logs`). + WithArgs(alignedCutoff, usageLogsCleanupBatchSize). + WillReturnResult(sqlmock.NewResult(0, 3)) + expectGroupRollupPrecheck(mock, service.GroupUsageDate(service.GroupUsageTodayStart(fixedNow)), "Asia/Shanghai", true) require.NoError(t, repo.CleanupUsageLogs(context.Background(), cutoff)) require.NoError(t, mock.ExpectationsWereMet()) } -func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionedSortsAndInvalidatesEachDropBeforeSync(t *testing.T) { - setGroupUsageRollupTestTimezone(t) +func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionedInvalidatesRetainedRowsAfterDrop(t *testing.T) { + useGroupUsageRepositoryTestTimezone(t, "UTC") db, mock := newSQLMock(t) repo := newDashboardAggregationRepositoryWithSQL(db) - cutoff := time.Date(2026, 7, 18, 0, 0, 0, 0, time.UTC) - aprilStart := time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC) - juneStart := time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC) - fixedNow := time.Date(2026, 8, 14, 8, 0, 0, 0, time.UTC) + cutoff := time.Date(2026, 7, 1, 0, 0, 0, 0, time.UTC) + fixedNow := time.Date(2026, 9, 29, 8, 0, 0, 0, time.UTC) repo.clock = func() time.Time { return fixedNow } - todayStart := service.GroupUsageTodayStart(fixedNow) + // 6 月分区建于 UTC-5 会话时区,上界是 07-01 05:00 UTC,包含保留下界之后的记录。 + retainedInJunePartition := time.Date(2026, 7, 1, 3, 0, 0, 0, time.UTC) + mock.ExpectExec(groupRollupExpireExec). + WithArgs(cutoff). + WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectQuery(`SELECT EXISTS`). WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true)) mock.ExpectQuery(`SELECT c.relname`). @@ -232,78 +517,120 @@ func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionedSortsAndInvali AddRow("usage_logs_202604"). AddRow("usage_logs_202607")) - for _, partition := range []struct { - name string - start time.Time - }{ - {name: "usage_logs_202604", start: aprilStart}, - {name: "usage_logs_202606", start: juneStart}, - } { - mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs(partition.start, "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectExec(`DROP TABLE IF EXISTS "` + partition.name + `"`). - WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectCommit() - } - // The boundary partition is pruned by exact timestamp. tableoid is required - // because ctid alone can also identify a retained row in another partition. + // 4 月分区全部早于保留下界:直接删除。 mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) - mock.ExpectQuery(`(?s)SELECT tableoid, ctid.*WHERE created_at < \$1.*WHERE \(tableoid, ctid\) IN.*RETURNING created_at`). + mock.ExpectExec(`SET LOCAL lock_timeout = '3000ms'`).WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectQuery(`(?s)SELECT expired_before\s+FROM usage_group_rollup_state.*FOR KEY SHARE`). + WillReturnRows(sqlmock.NewRows([]string{"expired_before"}).AddRow(cutoff)) + mock.ExpectQuery(`SELECT MIN\(created_at\) FROM "usage_logs_202604" WHERE created_at >= \$1`). + WithArgs(cutoff). + WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(nil)) + mock.ExpectExec(`DROP TABLE IF EXISTS "usage_logs_202604"`). + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectCommit() + // 6 月分区含保留下界之后的记录:删除后按其中最早时刻失效。 + mock.ExpectBegin() + mock.ExpectExec(`SET LOCAL lock_timeout = '3000ms'`).WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectQuery(`(?s)SELECT expired_before\s+FROM usage_group_rollup_state.*FOR KEY SHARE`). + WillReturnRows(sqlmock.NewRows([]string{"expired_before"}).AddRow(cutoff)) + mock.ExpectQuery(`SELECT MIN\(created_at\) FROM "usage_logs_202606" WHERE created_at >= \$1`). + WithArgs(cutoff). + WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(retainedInJunePartition)) + mock.ExpectExec(`DROP TABLE IF EXISTS "usage_logs_202606"`). + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec(groupRollupInvalidateSQL). + WithArgs(retainedInJunePartition, "UTC"). + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectCommit() + // 边界分区按精确时间删除;tableoid 区分不同分区里相同的 ctid。 + mock.ExpectExec(`(?s)SELECT tableoid, ctid.*WHERE created_at < \$1.*WHERE \(tableoid, ctid\) IN`). WithArgs(cutoff, usageLogsCleanupBatchSize). - WillReturnRows(sqlmock.NewRows([]string{"created_at"}).AddRow(cutoff.Add(-time.Hour))) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs(cutoff.Add(-time.Hour), "Asia/Shanghai"). WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectCommit() - mock.ExpectBegin() - mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}). - AddRow(service.GroupUsageDate(todayStart), time.Unix(0, 0).UTC(), "Asia/Shanghai")) - mock.ExpectCommit() + expectGroupRollupPrecheck(mock, service.GroupUsageDate(service.GroupUsageTodayStart(fixedNow)), "UTC", true) require.NoError(t, repo.CleanupUsageLogs(context.Background(), cutoff)) require.NoError(t, mock.ExpectationsWereMet()) } -func TestDashboardAggregationRepositoryCleanupUsageLogsNonPartitionedFailureRollsBackWithoutSync(t *testing.T) { +func TestDashboardAggregationRepositoryCleanupUsageLogsStopsWhenExpireFails(t *testing.T) { setGroupUsageRollupTestTimezone(t) db, mock := newSQLMock(t) repo := newDashboardAggregationRepositoryWithSQL(db) - cutoff := time.Date(2026, 7, 1, 0, 0, 0, 0, time.UTC) - deletedAt := time.Date(2026, 5, 3, 2, 0, 0, 0, time.UTC) + cutoff := time.Date(2026, 6, 30, 16, 0, 0, 0, time.UTC) - mock.ExpectQuery(`SELECT EXISTS`). - WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(false)) - mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) - mock.ExpectQuery(`(?s)SELECT tableoid, ctid.*ORDER BY created_at ASC, id ASC.*DELETE FROM usage_logs.*RETURNING created_at`). - WithArgs(cutoff, usageLogsCleanupBatchSize). - WillReturnRows(sqlmock.NewRows([]string{"created_at"}).AddRow(deletedAt)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs(deletedAt, "Asia/Shanghai"). + mock.ExpectExec(groupRollupExpireExec). + WithArgs(cutoff). WillReturnError(sql.ErrConnDone) - mock.ExpectRollback() err := repo.CleanupUsageLogs(context.Background(), cutoff) require.ErrorIs(t, err, sql.ErrConnDone) require.NoError(t, mock.ExpectationsWereMet()) } +func TestDashboardAggregationRepositoryCleanupUsageLogsBatchFailureStopsWithoutSync(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + cutoff := time.Date(2026, 6, 30, 16, 0, 0, 0, time.UTC) + + mock.ExpectExec(groupRollupExpireExec). + WithArgs(cutoff). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectQuery(`SELECT EXISTS`). + WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(false)) + mock.ExpectExec(`(?s)SELECT tableoid, ctid.*DELETE FROM usage_logs`). + WithArgs(cutoff, usageLogsCleanupBatchSize). + WillReturnError(sql.ErrConnDone) + + err := repo.CleanupUsageLogs(context.Background(), cutoff) + require.ErrorIs(t, err, sql.ErrConnDone) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestDashboardAggregationRepositoryCleanupUsageLogsSkipsPartitionWhenDropLockTimesOut(t *testing.T) { + setGroupUsageRollupTestTimezone(t) + db, mock := newSQLMock(t) + repo := newDashboardAggregationRepositoryWithSQL(db) + cutoff := time.Date(2026, 7, 17, 16, 0, 0, 0, time.UTC) + fixedNow := time.Date(2026, 8, 14, 8, 0, 0, 0, time.UTC) + repo.clock = func() time.Time { return fixedNow } + + mock.ExpectExec(groupRollupExpireExec). + WithArgs(cutoff). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectQuery(`SELECT EXISTS`). + WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true)) + mock.ExpectQuery(`SELECT c.relname`). + WillReturnRows(sqlmock.NewRows([]string{"relname"}).AddRow("usage_logs_202604")) + mock.ExpectBegin() + mock.ExpectExec(`SET LOCAL lock_timeout`).WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectQuery(`(?s)SELECT expired_before\s+FROM usage_group_rollup_state.*FOR KEY SHARE`). + WillReturnRows(sqlmock.NewRows([]string{"expired_before"}).AddRow(cutoff)) + mock.ExpectQuery(`SELECT MIN\(created_at\) FROM "usage_logs_202604"`). + WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(nil)) + mock.ExpectExec(`DROP TABLE IF EXISTS "usage_logs_202604"`). + WillReturnError(&pq.Error{Code: "55P03", Message: "canceling statement due to lock timeout"}) + mock.ExpectRollback() + // 分区保留,其中的过期记录由按行删除清理。 + mock.ExpectExec(`(?s)SELECT tableoid, ctid.*DELETE FROM usage_logs`). + WithArgs(cutoff, usageLogsCleanupBatchSize). + WillReturnResult(sqlmock.NewResult(0, 5)) + expectGroupRollupPrecheck(mock, service.GroupUsageDate(service.GroupUsageTodayStart(fixedNow)), "Asia/Shanghai", true) + + require.NoError(t, repo.CleanupUsageLogs(context.Background(), cutoff)) + require.NoError(t, mock.ExpectationsWereMet()) +} + func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionFailureRollsBackAndStops(t *testing.T) { setGroupUsageRollupTestTimezone(t) db, mock := newSQLMock(t) repo := newDashboardAggregationRepositoryWithSQL(db) - cutoff := time.Date(2026, 7, 18, 0, 0, 0, 0, time.UTC) - aprilStart := time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC) + cutoff := time.Date(2026, 7, 17, 16, 0, 0, 0, time.UTC) dropErr := errors.New("drop partition failed") + mock.ExpectExec(groupRollupExpireExec). + WithArgs(cutoff). + WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectQuery(`SELECT EXISTS`). WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true)) mock.ExpectQuery(`SELECT c.relname`). @@ -311,11 +638,11 @@ func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionFailureRollsBack AddRow("usage_logs_202606"). AddRow("usage_logs_202604")) mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs(aprilStart, "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec(`SET LOCAL lock_timeout`).WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectQuery(`(?s)SELECT expired_before\s+FROM usage_group_rollup_state.*FOR KEY SHARE`). + WillReturnRows(sqlmock.NewRows([]string{"expired_before"}).AddRow(cutoff)) + mock.ExpectQuery(`SELECT MIN\(created_at\) FROM "usage_logs_202604"`). + WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(nil)) mock.ExpectExec(`DROP TABLE IF EXISTS "usage_logs_202604"`). WillReturnError(dropErr) mock.ExpectRollback() diff --git a/backend/internal/repository/dashboard_aggregation_repo.go b/backend/internal/repository/dashboard_aggregation_repo.go index 347600df05..7a0351f7f4 100644 --- a/backend/internal/repository/dashboard_aggregation_repo.go +++ b/backend/internal/repository/dashboard_aggregation_repo.go @@ -3,6 +3,7 @@ package repository import ( "context" "database/sql" + "errors" "fmt" "log" "sort" @@ -20,6 +21,9 @@ type dashboardAggregationRepository struct { } const usageLogsCleanupBatchSize = 10000 + +// usageLogsPartitionDropLockTimeout 限定删除分区时等待父表锁的时长。 +const usageLogsPartitionDropLockTimeout = 3 * time.Second const usageBillingDedupCleanupBatchSize = 10000 // NewDashboardAggregationRepository 创建仪表盘预聚合仓储。 @@ -131,29 +135,22 @@ func (r *dashboardAggregationRepository) RecomputeRange(ctx context.Context, sta dayEnd = dayEnd.Add(24 * time.Hour) } + // 分组日桶从 start 所在自然日起失效,由后台同步重建;失效语句独立提交,不与看板重算共享事务。 + if err := invalidateGroupUsageRollupsAt(ctx, r.sql, start); err != nil { + return err + } + // 尽量使用事务保证范围内的一致性(允许在非 *sql.DB 的情况下退化为非事务执行)。 if db, ok := r.sql.(*sql.DB); ok { tx, err := db.BeginTx(ctx, nil) if err != nil { return err } - if err := lockGroupUsageRollupState(ctx, tx); err != nil { - _ = tx.Rollback() - return err - } - if err := invalidateGroupUsageRollupsAt(ctx, tx, start); err != nil { - _ = tx.Rollback() - return err - } txRepo := newDashboardAggregationRepositoryWithSQL(tx) if err := txRepo.recomputeRangeInTx(ctx, hourStart, hourEnd, dayStart, dayEnd); err != nil { _ = tx.Rollback() return err } - if err := txRepo.syncGroupUsageRollupsInTx(ctx, service.GroupUsageTodayStart(r.now())); err != nil { - _ = tx.Rollback() - return err - } return tx.Commit() } return r.recomputeRangeInTx(ctx, hourStart, hourEnd, dayStart, dayEnd) @@ -230,7 +227,13 @@ func (r *dashboardAggregationRepository) CleanupAggregates(ctx context.Context, return nil } +// CleanupUsageLogs 删除服务端配置时区内 cutoff 所在自然日零点之前的 usage_logs。 +// 删除前先把分组日汇总的保留下界推进到该零点,被删除的记录不触发日桶失效。 func (r *dashboardAggregationRepository) CleanupUsageLogs(ctx context.Context, cutoff time.Time) error { + cutoff = service.GroupUsageTodayStart(cutoff) + if err := expireGroupUsageRollupsBefore(ctx, r.sql, cutoff); err != nil { + return err + } isPartitioned, err := r.isUsageLogsPartitioned(ctx) if err != nil { return err @@ -249,19 +252,7 @@ func (r *dashboardAggregationRepository) CleanupUsageLogs(ctx context.Context, c } func (r *dashboardAggregationRepository) cleanupUsageLogsBatches(ctx context.Context, cutoff time.Time) error { - db, transactional := r.sql.(*sql.DB) for { - if transactional { - affected, err := cleanupUsageLogsBatchWithRollupInvalidation(ctx, db, cutoff) - if err != nil { - return err - } - if affected < usageLogsCleanupBatchSize { - return nil - } - continue - } - res, err := r.sql.ExecContext(ctx, ` WITH victims AS ( SELECT tableoid, ctid @@ -286,66 +277,6 @@ func (r *dashboardAggregationRepository) cleanupUsageLogsBatches(ctx context.Con } } -func cleanupUsageLogsBatchWithRollupInvalidation(ctx context.Context, db *sql.DB, cutoff time.Time) (int64, error) { - tx, err := db.BeginTx(ctx, nil) - if err != nil { - return 0, err - } - rollback := func(err error) (int64, error) { - _ = tx.Rollback() - return 0, err - } - - if err := lockGroupUsageRollupState(ctx, tx); err != nil { - return rollback(err) - } - rows, err := tx.QueryContext(ctx, ` - WITH victims AS ( - SELECT tableoid, ctid - FROM usage_logs - WHERE created_at < $1 - ORDER BY created_at ASC, id ASC - LIMIT $2 - ) - DELETE FROM usage_logs - WHERE (tableoid, ctid) IN (SELECT tableoid, ctid FROM victims) - RETURNING created_at - `, cutoff.UTC(), usageLogsCleanupBatchSize) - if err != nil { - return rollback(err) - } - - var affected int64 - var earliestDeletedAt time.Time - for rows.Next() { - var deletedAt time.Time - if err := rows.Scan(&deletedAt); err != nil { - _ = rows.Close() - return rollback(err) - } - affected++ - if earliestDeletedAt.IsZero() || deletedAt.Before(earliestDeletedAt) { - earliestDeletedAt = deletedAt - } - } - if err := rows.Err(); err != nil { - _ = rows.Close() - return rollback(err) - } - if err := rows.Close(); err != nil { - return rollback(err) - } - if affected > 0 { - if err := invalidateGroupUsageRollupsAt(ctx, tx, earliestDeletedAt); err != nil { - return rollback(err) - } - } - if err := tx.Commit(); err != nil { - return 0, err - } - return affected, nil -} - func (r *dashboardAggregationRepository) CleanupUsageBillingDedup(ctx context.Context, cutoff time.Time) error { for { res, err := r.sql.ExecContext(ctx, ` @@ -630,40 +561,69 @@ func (r *dashboardAggregationRepository) dropUsageLogsPartitions(ctx context.Con sort.Slice(partitions, func(i, j int) bool { return partitions[i].month.Before(partitions[j].month) }) - if db, ok := r.sql.(*sql.DB); ok { - for _, partition := range partitions { - if err := dropUsageLogsPartitionWithRollupInvalidation(ctx, db, partition.name, partition.month); err != nil { - return err - } - } - return nil - } for _, partition := range partitions { - if _, err := r.sql.ExecContext(ctx, fmt.Sprintf("DROP TABLE IF EXISTS %s", pq.QuoteIdentifier(partition.name))); err != nil { + if err := r.dropUsageLogsPartition(ctx, partition.name); err != nil { + // 父表锁等待超时:保留该分区,其中的过期记录由随后的按行删除清理,空分区在下次清理时删除。 + if isPostgresLockNotAvailable(err) { + log.Printf("[DashboardAggregation] 删除分区 %s 等待锁超时,本次改为按行删除", partition.name) + continue + } return err } } return nil } -func dropUsageLogsPartitionWithRollupInvalidation(ctx context.Context, db *sql.DB, name string, monthStart time.Time) error { +func isPostgresLockNotAvailable(err error) bool { + var pqErr *pq.Error + return errors.As(err, &pqErr) && pqErr.Code == "55P03" +} + +// dropUsageLogsPartition 删除一个 usage_logs 月分区。分区内不早于保留下界的记录参与分组日汇总, +// 删除后按其中最早的时刻使日桶失效;状态行的 FOR KEY SHARE 使失效与重建的登记、发布串行。 +// DROP 需要父表 ACCESS EXCLUSIVE 锁,排队期间会挡住 usage_logs 写入,因此限定锁等待时长。 +func (r *dashboardAggregationRepository) dropUsageLogsPartition(ctx context.Context, name string) error { + drop := func(q sqlExecutor) error { + var expiredBefore time.Time + if err := scanSingleRow(ctx, q, ` + SELECT expired_before + FROM usage_group_rollup_state + WHERE id = 1 + FOR KEY SHARE + `, nil, &expiredBefore); err != nil { + return fmt.Errorf("读取分组用量汇总保留下界: %w", err) + } + var earliestRetained sql.NullTime + if err := scanSingleRow(ctx, q, + fmt.Sprintf("SELECT MIN(created_at) FROM %s WHERE created_at >= $1", pq.QuoteIdentifier(name)), + []any{expiredBefore.UTC()}, &earliestRetained, + ); err != nil { + return err + } + if _, err := q.ExecContext(ctx, fmt.Sprintf("DROP TABLE IF EXISTS %s", pq.QuoteIdentifier(name))); err != nil { + return err + } + if earliestRetained.Valid { + return invalidateGroupUsageRollupsAt(ctx, q, earliestRetained.Time) + } + return nil + } + + db, ok := r.sql.(*sql.DB) + if !ok { + return drop(r.sql) + } tx, err := db.BeginTx(ctx, nil) if err != nil { return err } - rollback := func(err error) error { + if _, err := tx.ExecContext(ctx, fmt.Sprintf("SET LOCAL lock_timeout = '%dms'", usageLogsPartitionDropLockTimeout.Milliseconds())); err != nil { _ = tx.Rollback() return err } - - if err := lockGroupUsageRollupState(ctx, tx); err != nil { - return rollback(err) - } - if err := invalidateGroupUsageRollupsAt(ctx, tx, monthStart); err != nil { - return rollback(err) - } - if _, err := tx.ExecContext(ctx, fmt.Sprintf("DROP TABLE IF EXISTS %s", pq.QuoteIdentifier(name))); err != nil { - return rollback(err) + if err := drop(tx); err != nil { + _ = tx.Rollback() + return err } return tx.Commit() } diff --git a/backend/internal/repository/group_usage_rollup_nonblocking_integration_test.go b/backend/internal/repository/group_usage_rollup_nonblocking_integration_test.go new file mode 100644 index 0000000000..1aec81eb0e --- /dev/null +++ b/backend/internal/repository/group_usage_rollup_nonblocking_integration_test.go @@ -0,0 +1,652 @@ +//go:build integration + +package repository + +import ( + "context" + "database/sql" + "fmt" + "net/url" + "testing" + "time" + + "github.com/lib/pq" + "github.com/stretchr/testify/require" +) + +// 计算阶段持有状态行 FOR KEY SHARE 期间,usage_logs 的当天写入、迟到写入与窗口内删除都不等待; +// 迟到写入与删除记入 build_dirty_from,同步重算脏区间后发布到今日,日桶与明细逐日一致。 +func TestGroupUsageRollupSyncDoesNotBlockUsageWritesDuringBuild(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai") + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false) + db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai") + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + + execGroupUsageRollupSQL(t, ctx, db, ` + INSERT INTO groups (id) VALUES (10), (20); + INSERT INTO users (id) VALUES (1); + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES + (1, 1, 10, 1, TIMESTAMPTZ '2026-08-10 09:00:00+08'), + (2, 1, 10, 2, TIMESTAMPTZ '2026-08-11 09:00:00+08'), + (3, 1, 20, 4, TIMESTAMPTZ '2026-08-12 09:00:00+08'), + (4, 1, 10, 8, TIMESTAMPTZ '2026-08-13 09:00:00+08'); + INSERT INTO usage_group_daily_rollups (bucket_date, group_id, actual_cost) + VALUES (DATE '2026-08-10', 10, 1); + UPDATE usage_group_rollup_state + SET closed_before = DATE '2026-08-11', + retained_from = TIMESTAMPTZ '2026-08-10 09:00:00+08', + timezone_name = 'Asia/Shanghai' + WHERE id = 1; + `) + + // 让计算阶段停在清理日桶这一步:此时它已持有状态行的 FOR KEY SHARE。 + blocker, err := db.BeginTx(ctx, nil) + require.NoError(t, err) + defer func() { _ = blocker.Rollback() }() + _, err = blocker.ExecContext(ctx, "LOCK TABLE usage_group_daily_rollups IN SHARE MODE") + require.NoError(t, err) + + repo := newDashboardAggregationRepositoryWithSQL(db) + syncDone := make(chan error, 1) + go func() { syncDone <- repo.SyncGroupUsageRollups(ctx, todayStart) }() + waitForBlockedGroupUsageRollupStatement(t, ctx, "DELETE FROM usage_group_daily_rollups") + + writeCtx, writeCancel := context.WithTimeout(ctx, 3*time.Second) + defer writeCancel() + execGroupUsageRollupSQL(t, writeCtx, db, ` + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + VALUES (5, 1, 20, 16, TIMESTAMPTZ '2026-08-12 18:00:00+08') + `) + execGroupUsageRollupSQL(t, writeCtx, db, ` + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + VALUES (6, 1, 10, 32, TIMESTAMPTZ '2026-08-14 09:00:00+08') + `) + execGroupUsageRollupSQL(t, writeCtx, db, `DELETE FROM usage_logs WHERE id = 2`) + + state := readGroupUsageRollupTestState(t, ctx, db) + require.Equal(t, "2026-08-11", state.closedBefore) + require.Equal(t, "2026-08-14", state.buildingUntil.String) + require.Equal(t, "2026-08-11", state.buildDirtyFrom.String) + + require.NoError(t, blocker.Rollback()) + select { + case err := <-syncDone: + require.NoError(t, err) + case <-ctx.Done(): + t.Fatal("等待分组日桶同步完成超时") + } + + state = readGroupUsageRollupTestState(t, ctx, db) + require.Equal(t, "2026-08-14", state.closedBefore) + require.False(t, state.buildingUntil.Valid) + require.False(t, state.buildDirtyFrom.Valid) + requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "Asia/Shanghai", state.retainedFrom, todayStart) + + summary := groupUsageSummaryByGroup(t, ctx, db, todayStart) + require.InDelta(t, 41, summary[10][0], 1e-9) + require.InDelta(t, 32, summary[10][1], 1e-9) + require.InDelta(t, 8, summary[10][2], 1e-9) + require.InDelta(t, 20, summary[20][0], 1e-9) + require.InDelta(t, 0, summary[20][1], 1e-9) + require.InDelta(t, 0, summary[20][2], 1e-9) +} + +// 保留期清理按整日推进保留下界后删除:发布水位不动,过期记录的写入不触发失效, +// 窗口内的删除照常使日桶失效。 +func TestGroupUsageRollupRetentionCleanupKeepsPublishedWatermark(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai") + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false) + db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai") + todayStart := time.Date(2026, 8, 9, 16, 0, 0, 0, time.UTC) + + execGroupUsageRollupSQL(t, ctx, db, ` + INSERT INTO groups (id) VALUES (10), (20); + INSERT INTO users (id) VALUES (1); + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES + (1, 1, 10, 1, TIMESTAMPTZ '2026-08-01 10:00:00+08'), + (2, 1, 10, 2, TIMESTAMPTZ '2026-08-02 05:00:00+08'), + (3, 1, 10, 4, TIMESTAMPTZ '2026-08-02 20:00:00+08'), + (4, 1, 20, 8, TIMESTAMPTZ '2026-08-05 12:00:00+08'), + (5, 1, 10, 16, TIMESTAMPTZ '2026-08-10 08:00:00+08'); + `) + + repo := newDashboardAggregationRepositoryWithSQL(db) + repo.clock = func() time.Time { return todayStart.Add(10 * time.Hour) } + require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart)) + require.Equal(t, "2026-08-10", readGroupUsageRollupTestState(t, ctx, db).closedBefore) + + shanghai, err := time.LoadLocation("Asia/Shanghai") + require.NoError(t, err) + require.NoError(t, repo.CleanupUsageLogs(ctx, time.Date(2026, 8, 2, 12, 0, 0, 0, shanghai))) + + alignedCutoff := time.Date(2026, 8, 2, 0, 0, 0, 0, shanghai) + state := readGroupUsageRollupTestState(t, ctx, db) + require.Equal(t, "2026-08-10", state.closedBefore) + require.True(t, state.expiredBefore.Equal(alignedCutoff), "expired_before=%s", state.expiredBefore) + require.True(t, state.retainedFrom.Equal(alignedCutoff), "retained_from=%s", state.retainedFrom) + require.False(t, state.buildingUntil.Valid) + + var remaining []int64 + rows, err := db.QueryContext(ctx, "SELECT id FROM usage_logs ORDER BY id") + require.NoError(t, err) + for rows.Next() { + var id int64 + require.NoError(t, rows.Scan(&id)) + remaining = append(remaining, id) + } + require.NoError(t, rows.Err()) + require.NoError(t, rows.Close()) + require.Equal(t, []int64{2, 3, 4, 5}, remaining) + + requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "Asia/Shanghai", alignedCutoff, todayStart) + summary := groupUsageSummaryByGroup(t, ctx, db, todayStart) + require.InDelta(t, 22, summary[10][0], 1e-9) + require.InDelta(t, 16, summary[10][1], 1e-9) + require.InDelta(t, 8, summary[20][0], 1e-9) + + execGroupUsageRollupSQL(t, ctx, db, ` + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + VALUES (6, 1, 10, 100, TIMESTAMPTZ '2026-08-01 12:00:00+08') + `) + require.Equal(t, "2026-08-10", readGroupUsageRollupTestState(t, ctx, db).closedBefore) + summary = groupUsageSummaryByGroup(t, ctx, db, todayStart) + require.InDelta(t, 22, summary[10][0], 1e-9) + + execGroupUsageRollupSQL(t, ctx, db, `DELETE FROM usage_logs WHERE id = 4`) + require.Equal(t, "2026-08-05", readGroupUsageRollupTestState(t, ctx, db).closedBefore) + summary = groupUsageSummaryByGroup(t, ctx, db, todayStart) + require.InDelta(t, 0, summary[20][0], 1e-9) + require.InDelta(t, 22, summary[10][0], 1e-9) +} + +func TestGroupUsageRollupTriggersIgnoreRowsBeforeExpiredFloor(t *testing.T) { + for _, partitioned := range []bool{false, true} { + name := "ordinary" + if partitioned { + name = "partitioned" + } + t.Run(name, func(t *testing.T) { + ctx := context.Background() + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, partitioned) + tx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema) + defer func() { _ = tx.Rollback() }() + require.NoError(t, setGroupUsageRollupTriggerTimeZone(ctx, tx, "Asia/Shanghai")) + + _, err := tx.ExecContext(ctx, ` + INSERT INTO groups (id) VALUES (10); + INSERT INTO users (id) VALUES (1); + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES + (1, 1, 10, 1, TIMESTAMPTZ '2020-01-15 08:00:00+08'), + (2, 1, 10, 2, TIMESTAMPTZ '2020-02-05 08:00:00+08'); + UPDATE usage_group_rollup_state + SET closed_before = DATE '2020-03-01', + expired_before = TIMESTAMPTZ '2020-02-01 00:00:00+08' + WHERE id = 1; + DELETE FROM usage_logs WHERE id = 1; + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + VALUES (3, 1, 10, 4, TIMESTAMPTZ '2020-01-20 08:00:00+08'); + UPDATE usage_logs SET actual_cost = 5 WHERE id = 3; + `) + require.NoError(t, err) + require.Equal(t, "2020-03-01", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore) + + // 把过期记录改到保留窗口内,按新日期失效。 + _, err = tx.ExecContext(ctx, ` + UPDATE usage_logs SET created_at = TIMESTAMPTZ '2020-02-20 08:00:00+08' WHERE id = 3 + `) + require.NoError(t, err) + require.Equal(t, "2020-02-20", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore) + + _, err = tx.ExecContext(ctx, `DELETE FROM usage_logs WHERE id = 2`) + require.NoError(t, err) + require.Equal(t, "2020-02-05", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore) + }) + } +} + +func TestGroupUsageRollupTriggersMarkDirtyDuringBuild(t *testing.T) { + ctx := context.Background() + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false) + tx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema) + defer func() { _ = tx.Rollback() }() + require.NoError(t, setGroupUsageRollupTriggerTimeZone(ctx, tx, "Asia/Shanghai")) + + _, err := tx.ExecContext(ctx, ` + INSERT INTO groups (id) VALUES (10); + INSERT INTO users (id) VALUES (1); + UPDATE usage_group_rollup_state + SET closed_before = DATE '2020-01-05', + building_until = DATE '2020-01-10' + WHERE id = 1; + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + VALUES (1, 1, 10, 1, TIMESTAMPTZ '2020-01-12 08:00:00+08'); + `) + require.NoError(t, err) + state := readGroupUsageRollupTestStateTx(t, ctx, tx) + require.Equal(t, "2020-01-05", state.closedBefore) + require.False(t, state.buildDirtyFrom.Valid) + + _, err = tx.ExecContext(ctx, ` + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + VALUES (2, 1, 10, 1, TIMESTAMPTZ '2020-01-07 08:00:00+08') + `) + require.NoError(t, err) + state = readGroupUsageRollupTestStateTx(t, ctx, tx) + require.Equal(t, "2020-01-05", state.closedBefore) + require.Equal(t, "2020-01-07", state.buildDirtyFrom.String) + + _, err = tx.ExecContext(ctx, ` + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + VALUES (3, 1, 10, 1, TIMESTAMPTZ '2020-01-03 08:00:00+08') + `) + require.NoError(t, err) + state = readGroupUsageRollupTestStateTx(t, ctx, tx) + require.Equal(t, "2020-01-03", state.closedBefore) + require.Equal(t, "2020-01-03", state.buildDirtyFrom.String) + + _, err = tx.ExecContext(ctx, `DELETE FROM usage_logs WHERE id = 1`) + require.NoError(t, err) + state = readGroupUsageRollupTestStateTx(t, ctx, tx) + require.Equal(t, "2020-01-03", state.buildDirtyFrom.String) +} + +// 计算阶段对状态行只持 FOR KEY SHARE:迟到写入与窗口内删除都不等待它。 +func TestGroupUsageRollupBuildKeyShareDoesNotBlockLateWrites(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false) + seedTx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema) + _, err := seedTx.ExecContext(ctx, ` + INSERT INTO groups (id) VALUES (10); + INSERT INTO users (id) VALUES (1); + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + VALUES (1, 1, 10, 1, TIMESTAMPTZ '2020-01-08 08:00:00+08'); + UPDATE usage_group_rollup_state + SET closed_before = DATE '2020-01-05', + building_until = DATE '2020-01-10' + WHERE id = 1; + `) + require.NoError(t, err) + require.NoError(t, seedTx.Commit()) + + buildTx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema) + defer func() { _ = buildTx.Rollback() }() + var stateID int16 + require.NoError(t, buildTx.QueryRowContext(ctx, ` + SELECT id FROM usage_group_rollup_state WHERE id = 1 FOR KEY SHARE + `).Scan(&stateID)) + + for _, statement := range []string{ + `INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + VALUES (2, 1, 10, 1, TIMESTAMPTZ '2020-01-07 08:00:00+08')`, + `DELETE FROM usage_logs WHERE id = 1`, + } { + writeTx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema) + require.NoError(t, setGroupUsageRollupTriggerTimeZone(ctx, writeTx, "Asia/Shanghai")) + var writePID int + require.NoError(t, writeTx.QueryRowContext(ctx, "SELECT pg_backend_pid()").Scan(&writePID)) + result := make(chan error, 1) + go func(statement string) { + _, execErr := writeTx.ExecContext(ctx, statement) + result <- execErr + }(statement) + blocked, err := waitForGroupUsageRollupStateLock(ctx, writePID, result) + require.NoError(t, err) + require.False(t, blocked, "计算阶段不得阻塞: %s", statement) + require.NoError(t, writeTx.Commit()) + } + + require.NoError(t, buildTx.Commit()) + var dirtyFrom string + require.NoError(t, integrationDB.QueryRowContext(ctx, fmt.Sprintf( + "SELECT build_dirty_from::text FROM %s.usage_group_rollup_state WHERE id = 1", + pq.QuoteIdentifier(schema), + )).Scan(&dirtyFrom)) + require.Equal(t, "2020-01-07", dirtyFrom) +} + +func TestGroupUsageRollupSyncSkipsWhileAnotherBuildHoldsLock(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai") + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false) + db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai") + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + + holder, err := integrationDB.Conn(ctx) + require.NoError(t, err) + defer func() { _ = holder.Close() }() + var locked bool + require.NoError(t, holder.QueryRowContext(ctx, groupUsageRollupBuildLockSQL).Scan(&locked)) + require.True(t, locked) + defer func() { _, _ = holder.ExecContext(context.Background(), groupUsageRollupBuildUnlockSQL) }() + + repo := newDashboardAggregationRepositoryWithSQL(db) + require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart)) + state := readGroupUsageRollupTestState(t, ctx, db) + require.Equal(t, "1970-01-01", state.closedBefore) + require.False(t, state.buildingUntil.Valid) +} + +// 上一次重建在登记之后中断:下一次同步覆盖遗留登记并发布到今日。 +func TestGroupUsageRollupSyncRecoversFromInterruptedBuild(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai") + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false) + db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai") + todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC) + + execGroupUsageRollupSQL(t, ctx, db, ` + INSERT INTO groups (id) VALUES (10); + INSERT INTO users (id) VALUES (1); + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES + (1, 1, 10, 1, TIMESTAMPTZ '2026-08-11 09:00:00+08'), + (2, 1, 10, 2, TIMESTAMPTZ '2026-08-12 09:00:00+08'), + (3, 1, 10, 4, TIMESTAMPTZ '2026-08-13 09:00:00+08'); + INSERT INTO usage_group_daily_rollups (bucket_date, group_id, actual_cost) VALUES + (DATE '2026-08-11', 10, 1), + (DATE '2026-08-12', 10, 999); + UPDATE usage_group_rollup_state + SET closed_before = DATE '2026-08-12', + retained_from = TIMESTAMPTZ '2026-08-11 09:00:00+08', + timezone_name = 'Asia/Shanghai', + building_until = DATE '2026-08-14', + build_dirty_from = DATE '2026-08-13' + WHERE id = 1; + `) + + repo := newDashboardAggregationRepositoryWithSQL(db) + require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart)) + + state := readGroupUsageRollupTestState(t, ctx, db) + require.Equal(t, "2026-08-14", state.closedBefore) + require.False(t, state.buildingUntil.Valid) + require.False(t, state.buildDirtyFrom.Valid) + requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "Asia/Shanghai", state.retainedFrom, todayStart) +} + +type groupUsageRollupTestState struct { + closedBefore string + retainedFrom time.Time + expiredBefore time.Time + buildingUntil sql.NullString + buildDirtyFrom sql.NullString +} + +const groupUsageRollupTestStateQuery = ` + SELECT closed_before::text, retained_from, expired_before, building_until::text, build_dirty_from::text + FROM usage_group_rollup_state + WHERE id = 1 +` + +func readGroupUsageRollupTestState(t *testing.T, ctx context.Context, q sqlQueryer) groupUsageRollupTestState { + t.Helper() + var state groupUsageRollupTestState + require.NoError(t, scanSingleRow(ctx, q, groupUsageRollupTestStateQuery, nil, + &state.closedBefore, &state.retainedFrom, &state.expiredBefore, &state.buildingUntil, &state.buildDirtyFrom)) + return state +} + +func readGroupUsageRollupTestStateTx(t *testing.T, ctx context.Context, tx *sql.Tx) groupUsageRollupTestState { + t.Helper() + return readGroupUsageRollupTestState(t, ctx, tx) +} + +// openGroupUsageRollupSchemaDB 打开一个 search_path 指向 schema 的连接池,供仓储以 *sql.DB 方式运行。 +func openGroupUsageRollupSchemaDB(t *testing.T, schema, timezoneName string) *sql.DB { + t.Helper() + dsn, err := url.Parse(integrationDSN) + require.NoError(t, err) + query := dsn.Query() + query.Set("search_path", schema) + query.Set("TimeZone", timezoneName) + dsn.RawQuery = query.Encode() + db, err := sql.Open("postgres", dsn.String()) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + require.NoError(t, db.PingContext(context.Background())) + return db +} + +func execGroupUsageRollupSQL(t *testing.T, ctx context.Context, db *sql.DB, query string) { + t.Helper() + _, err := db.ExecContext(ctx, query) + require.NoError(t, err) +} + +// waitForBlockedGroupUsageRollupStatement 等待某个后端在执行包含 fragment 的语句时进入锁等待。 +func waitForBlockedGroupUsageRollupStatement(t *testing.T, ctx context.Context, fragment string) { + t.Helper() + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + for { + var blocked bool + require.NoError(t, integrationDB.QueryRowContext(ctx, ` + SELECT EXISTS ( + SELECT 1 + FROM pg_stat_activity + WHERE wait_event_type = 'Lock' + AND position($1 in query) > 0 + ) + `, fragment).Scan(&blocked)) + if blocked { + return + } + select { + case <-ticker.C: + case <-ctx.Done(): + t.Fatalf("等待语句进入锁等待超时: %s", fragment) + } + } +} + +// requireGroupUsageRollupsMatchUsageLogs 断言 [retainedFrom 所在日, todayStart) 的日桶与 usage_logs 明细逐日一致。 +func requireGroupUsageRollupsMatchUsageLogs(t *testing.T, ctx context.Context, db *sql.DB, timezoneName string, retainedFrom, todayStart time.Time) { + t.Helper() + expected := collectGroupUsageRollupBuckets(t, ctx, db, ` + SELECT (created_at AT TIME ZONE $3::text)::date::text, group_id, SUM(actual_cost)::float8 + FROM usage_logs + WHERE group_id IS NOT NULL + AND created_at >= $1 + AND created_at < $2 + GROUP BY 1, 2 + `, retainedFrom, todayStart, timezoneName) + actual := collectGroupUsageRollupBuckets(t, ctx, db, ` + SELECT bucket_date::text, group_id, actual_cost::float8 + FROM usage_group_daily_rollups + WHERE bucket_date >= ($1::timestamptz AT TIME ZONE $3::text)::date + AND bucket_date < ($2::timestamptz AT TIME ZONE $3::text)::date + `, retainedFrom, todayStart, timezoneName) + require.Equal(t, expected, actual) +} + +func collectGroupUsageRollupBuckets(t *testing.T, ctx context.Context, db *sql.DB, query string, args ...any) map[string]float64 { + t.Helper() + rows, err := db.QueryContext(ctx, query, args...) + require.NoError(t, err) + defer func() { _ = rows.Close() }() + buckets := make(map[string]float64) + for rows.Next() { + var bucketDate string + var groupID int64 + var cost float64 + require.NoError(t, rows.Scan(&bucketDate, &groupID, &cost)) + buckets[fmt.Sprintf("%s/%d", bucketDate, groupID)] = cost + } + require.NoError(t, rows.Err()) + return buckets +} + +// groupUsageSummaryByGroup 返回 group_id → [total, today, yesterday]。 +func groupUsageSummaryByGroup(t *testing.T, ctx context.Context, db *sql.DB, todayStart time.Time) map[int64][3]float64 { + t.Helper() + result, err := newUsageLogRepositoryWithSQL(nil, db).GetAllGroupUsageSummary(ctx, todayStart) + require.NoError(t, err) + summary := make(map[int64][3]float64, len(result)) + for _, row := range result { + summary[row.GroupID] = [3]float64{row.TotalCost, row.TodayCost, row.YesterdayCost} + } + return summary +} + +// 重建进行中的大批量删除:脏日期已覆盖的行不写状态行,状态行在事务内只更新一次。 +func TestGroupUsageRollupBulkDeleteDuringBuildWritesStateOnce(t *testing.T) { + ctx := context.Background() + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false) + tx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema) + defer func() { _ = tx.Rollback() }() + require.NoError(t, setGroupUsageRollupTriggerTimeZone(ctx, tx, "Asia/Shanghai")) + + _, err := tx.ExecContext(ctx, ` + INSERT INTO groups (id) VALUES (10); + INSERT INTO users (id) VALUES (1); + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) + SELECT n, 1, 10, 1, TIMESTAMPTZ '2020-01-15 08:00:00+08' + n * INTERVAL '1 second' + FROM generate_series(1, 2000) AS n; + UPDATE usage_group_rollup_state + SET closed_before = DATE '2020-01-10', + building_until = DATE '2020-02-01' + WHERE id = 1; + `) + require.NoError(t, err) + + var updatesBefore int64 + require.NoError(t, tx.QueryRowContext(ctx, ` + SELECT n_tup_upd FROM pg_stat_xact_user_tables + WHERE schemaname = current_schema() AND relname = 'usage_group_rollup_state' + `).Scan(&updatesBefore)) + + _, err = tx.ExecContext(ctx, `DELETE FROM usage_logs`) + require.NoError(t, err) + + var updatesAfter int64 + require.NoError(t, tx.QueryRowContext(ctx, ` + SELECT n_tup_upd FROM pg_stat_xact_user_tables + WHERE schemaname = current_schema() AND relname = 'usage_group_rollup_state' + `).Scan(&updatesAfter)) + require.Equal(t, int64(1), updatesAfter-updatesBefore) + + state := readGroupUsageRollupTestStateTx(t, ctx, tx) + require.Equal(t, "2020-01-10", state.closedBefore) + require.Equal(t, "2020-01-15", state.buildDirtyFrom.String) +} + +// 应用侧失效的起点早于保留下界时,从保留下界所在日开始失效。 +func TestGroupUsageRollupInvalidateAtStartsFromExpiredFloor(t *testing.T) { + ctx := context.Background() + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false) + tx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema) + defer func() { _ = tx.Rollback() }() + + _, err := tx.ExecContext(ctx, ` + UPDATE usage_group_rollup_state + SET closed_before = DATE '2020-03-01', + expired_before = TIMESTAMPTZ '2020-02-01 00:00:00+08' + WHERE id = 1; + SELECT invalidate_group_usage_rollups_at(TIMESTAMPTZ '2020-01-10 08:00:00+08', 'Asia/Shanghai'); + `) + require.NoError(t, err) + require.Equal(t, "2020-02-01", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore) + + _, err = tx.ExecContext(ctx, ` + SELECT invalidate_group_usage_rollups_at(TIMESTAMPTZ '2020-02-10 08:00:00+08', 'Asia/Shanghai') + `) + require.NoError(t, err) + require.Equal(t, "2020-02-01", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore) +} + +// 夏令时在零点跳变的日期(America/Santiago 2026-09-06 没有 00:00):从该日续建时不覆盖前一天的日桶。 +func TestGroupUsageRollupSyncKeepsPreviousDayBucketAcrossMidnightDSTGap(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + useGroupUsageRepositoryTestTimezone(t, "America/Santiago") + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false) + db := openGroupUsageRollupSchemaDB(t, schema, "America/Santiago") + santiago, err := time.LoadLocation("America/Santiago") + require.NoError(t, err) + todayStart := time.Date(2026, 9, 8, 0, 0, 0, 0, santiago) + + execGroupUsageRollupSQL(t, ctx, db, ` + INSERT INTO groups (id) VALUES (10); + INSERT INTO users (id) VALUES (1); + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES + (1, 1, 10, 1, TIMESTAMPTZ '2026-09-06 02:30:00+00'), + (2, 1, 10, 2, TIMESTAMPTZ '2026-09-06 03:30:00+00'), + (3, 1, 10, 4, TIMESTAMPTZ '2026-09-06 05:00:00+00'), + (4, 1, 10, 8, TIMESTAMPTZ '2026-09-07 13:00:00+00'); + INSERT INTO usage_group_daily_rollups (bucket_date, group_id, actual_cost) + VALUES (DATE '2026-09-05', 10, 3); + UPDATE usage_group_rollup_state + SET closed_before = DATE '2026-09-06', + retained_from = TIMESTAMPTZ '2026-09-06 02:30:00+00', + timezone_name = 'America/Santiago' + WHERE id = 1; + `) + + repo := newDashboardAggregationRepositoryWithSQL(db) + require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart)) + + state := readGroupUsageRollupTestState(t, ctx, db) + require.Equal(t, "2026-09-08", state.closedBefore) + requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "America/Santiago", state.retainedFrom, todayStart) + var previousDay float64 + require.NoError(t, db.QueryRowContext(ctx, ` + SELECT actual_cost::float8 FROM usage_group_daily_rollups + WHERE bucket_date = DATE '2026-09-05' AND group_id = 10 + `).Scan(&previousDay)) + require.InDelta(t, 3, previousDay, 1e-9) +} + +// 有长读者持有 usage_logs 的 ACCESS SHARE 时,删除分区在锁等待超时后跳过; +// 过期记录由按行删除清理,清理整体成功,分组日汇总保持一致。 +func TestGroupUsageRollupRetentionCleanupSkipsPartitionDropOnLockTimeout(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai") + schema := createGroupUsageRollupTriggerTestSchema(t, ctx, true) + db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai") + todayStart := time.Date(2026, 8, 9, 16, 0, 0, 0, time.UTC) + + execGroupUsageRollupSQL(t, ctx, db, ` + CREATE TABLE usage_logs_202605 PARTITION OF usage_logs + FOR VALUES FROM ('2026-05-01') TO ('2026-06-01'); + INSERT INTO groups (id) VALUES (10); + INSERT INTO users (id) VALUES (1); + INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES + (1, 1, 10, 1, TIMESTAMPTZ '2026-05-10 10:00:00+08'), + (2, 1, 10, 2, TIMESTAMPTZ '2026-07-20 10:00:00+08'), + (3, 1, 10, 4, TIMESTAMPTZ '2026-08-05 10:00:00+08'); + `) + repo := newDashboardAggregationRepositoryWithSQL(db) + repo.clock = func() time.Time { return todayStart.Add(10 * time.Hour) } + require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart)) + + reader, err := db.BeginTx(ctx, nil) + require.NoError(t, err) + defer func() { _ = reader.Rollback() }() + var count int + require.NoError(t, reader.QueryRowContext(ctx, "SELECT COUNT(*) FROM usage_logs").Scan(&count)) + require.Equal(t, 3, count) + + shanghai, err := time.LoadLocation("Asia/Shanghai") + require.NoError(t, err) + require.NoError(t, repo.CleanupUsageLogs(ctx, time.Date(2026, 7, 1, 0, 0, 0, 0, shanghai))) + require.NoError(t, reader.Rollback()) + + var partitionExists bool + require.NoError(t, db.QueryRowContext(ctx, "SELECT to_regclass('usage_logs_202605') IS NOT NULL").Scan(&partitionExists)) + require.True(t, partitionExists) + require.NoError(t, db.QueryRowContext(ctx, "SELECT COUNT(*) FROM usage_logs").Scan(&count)) + require.Equal(t, 2, count) + + state := readGroupUsageRollupTestState(t, ctx, db) + require.Equal(t, "2026-08-10", state.closedBefore) + requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "Asia/Shanghai", state.retainedFrom, todayStart) + summary := groupUsageSummaryByGroup(t, ctx, db, todayStart) + require.InDelta(t, 6, summary[10][0], 1e-9) +} diff --git a/backend/internal/repository/group_usage_rollup_trigger_integration_test.go b/backend/internal/repository/group_usage_rollup_trigger_integration_test.go index 32016e3c0a..c145bef4eb 100644 --- a/backend/internal/repository/group_usage_rollup_trigger_integration_test.go +++ b/backend/internal/repository/group_usage_rollup_trigger_integration_test.go @@ -451,6 +451,7 @@ func createGroupUsageRollupTriggerTestSchema(t *testing.T, ctx context.Context, for _, migrationName := range []string{ "222_group_usage_daily_rollups.sql", "223_group_usage_rollup_timezone.sql", + "251_group_usage_rollup_nonblocking_build.sql", } { migrationSQL, readErr := migrations.FS.ReadFile(migrationName) require.NoError(t, readErr) diff --git a/backend/internal/repository/http_upstream.go b/backend/internal/repository/http_upstream.go index e830b43380..af965e15ac 100644 --- a/backend/internal/repository/http_upstream.go +++ b/backend/internal/repository/http_upstream.go @@ -63,8 +63,6 @@ const ( // 上游域名被解析到 443 不可达的 IP 时(DNS 污染/路由异常),单个账号就要卡满 // 内核超时;而多账号故障转移是串行的,一次请求会阻塞数分钟且不写中间错误。 defaultUpstreamDialTimeout = 10 * time.Second - // defaultUpstreamDialKeepAlive: TCP keepalive 探测间隔,与 Go 默认值保持一致 - defaultUpstreamDialKeepAlive = 30 * time.Second // defaultUpstreamTLSHandshakeTimeout: TLS 握手超时(10秒) // 与建连超时同量级,避免 TCP 已连通但对端不推进握手时无限等待 defaultUpstreamTLSHandshakeTimeout = 10 * time.Second @@ -1365,8 +1363,14 @@ func defaultPoolSettings(cfg *config.Config) poolSettings { // 建连没有任何超时上限,只能等内核 TCP 重传耗尽(Linux 约 130 秒)。 func newUpstreamDialer() *net.Dialer { return &net.Dialer{ - Timeout: defaultUpstreamDialTimeout, - KeepAlive: defaultUpstreamDialKeepAlive, + Timeout: defaultUpstreamDialTimeout, + KeepAliveConfig: net.KeepAliveConfig{ + Enable: true, + Idle: upstreamKeepAliveIdle, + Interval: upstreamKeepAliveInterval, + Count: upstreamKeepAliveCount, + }, + Control: upstreamDialControl, } } diff --git a/backend/internal/repository/http_upstream_dial_timeout_test.go b/backend/internal/repository/http_upstream_dial_timeout_test.go index 00d6ce1a41..9660624f7b 100644 --- a/backend/internal/repository/http_upstream_dial_timeout_test.go +++ b/backend/internal/repository/http_upstream_dial_timeout_test.go @@ -30,7 +30,7 @@ func TestNewUpstreamDialerHasBoundedTimeout(t *testing.T) { require.Greater(t, dialer.Timeout, time.Duration(0), "建连超时必须有上限") require.Equal(t, defaultUpstreamDialTimeout, dialer.Timeout) - require.Equal(t, defaultUpstreamDialKeepAlive, dialer.KeepAlive) + require.Equal(t, net.KeepAliveConfig{Enable: true, Idle: 15 * time.Second, Interval: 5 * time.Second, Count: 3}, dialer.KeepAliveConfig) } // 建连超时对 HTTP 代理同样生效:Transport.Proxy 走的仍是 DialContext, diff --git a/backend/internal/repository/http_upstream_keepalive.go b/backend/internal/repository/http_upstream_keepalive.go new file mode 100644 index 0000000000..51fb8cb8c1 --- /dev/null +++ b/backend/internal/repository/http_upstream_keepalive.go @@ -0,0 +1,23 @@ +package repository + +import "time" + +// TCP keep-alive of upstream connections (newUpstreamDialer). A connection +// whose peer stops answering is aborted upstreamTCPUserTimeout after its last +// received packet: idle 15 s, then 3 probes 5 s apart. With the previous +// KeepAlive of 30 s and Go's default interval 15 s and count 9, the same case +// took 165 s. +// +// TCP_USER_TIMEOUT (Linux only, see upstreamDialControl) is set to +// idle + interval * count, as Cloudflare's "When TCP sockets refuse to die" +// (2019) recommends when both are used: once it is set the kernel aborts on it +// rather than on the probe count, so a larger value would add probes and a +// smaller one would cut them. It also bounds request data the peer never +// acknowledges, where keep-alive does not run. gRPC proposal A18 likewise sets +// it only on Linux. +const ( + upstreamKeepAliveIdle = 15 * time.Second + upstreamKeepAliveInterval = 5 * time.Second + upstreamKeepAliveCount = 3 + upstreamTCPUserTimeout = upstreamKeepAliveIdle + upstreamKeepAliveInterval*upstreamKeepAliveCount +) diff --git a/backend/internal/repository/http_upstream_keepalive_linux.go b/backend/internal/repository/http_upstream_keepalive_linux.go new file mode 100644 index 0000000000..68d7cd757e --- /dev/null +++ b/backend/internal/repository/http_upstream_keepalive_linux.go @@ -0,0 +1,28 @@ +//go:build linux + +package repository + +import ( + "log/slog" + "syscall" +) + +// tcpUserTimeout is TCP_USER_TIMEOUT from Linux include/uapi/linux/tcp.h; the +// standard library's syscall package does not define it on linux/amd64. +const tcpUserTimeout = 0x12 + +// upstreamDialControl sets TCP_USER_TIMEOUT on each upstream socket +// before it connects. A failure is logged and the dial goes on without the +// option, like the standard library does for the keep-alive options. +func upstreamDialControl(network, _ string, raw syscall.RawConn) error { + var sockErr error + if err := raw.Control(func(fd uintptr) { + sockErr = syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, tcpUserTimeout, int(upstreamTCPUserTimeout.Milliseconds())) + }); err != nil { + sockErr = err + } + if sockErr != nil { + slog.Warn("upstream_tcp_user_timeout_not_set", "network", network, "error", sockErr) + } + return nil +} diff --git a/backend/internal/repository/http_upstream_keepalive_linux_test.go b/backend/internal/repository/http_upstream_keepalive_linux_test.go new file mode 100644 index 0000000000..c25e7458fc --- /dev/null +++ b/backend/internal/repository/http_upstream_keepalive_linux_test.go @@ -0,0 +1,85 @@ +//go:build linux + +package repository + +import ( + "context" + "net" + "syscall" + "testing" + + "github.com/stretchr/testify/require" +) + +// TCP_USER_TIMEOUT in Linux include/uapi/linux/tcp.h. +const testTCPUserTimeoutOpt = 0x12 + +// A socket dialed by the upstream dialer carries the keep-alive configuration +// and TCP_USER_TIMEOUT, read back from the kernel. +func TestUpstreamDialerSetsKeepAliveAndUserTimeoutOnTheSocket(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + t.Cleanup(func() { _ = listener.Close() }) + accepted := make(chan net.Conn, 1) + go func() { + server, err := listener.Accept() + if err != nil { + close(accepted) + return + } + accepted <- server + }() + + conn, err := newUpstreamDialer().DialContext(context.Background(), "tcp", listener.Addr().String()) + require.NoError(t, err) + t.Cleanup(func() { _ = conn.Close() }) + if server, ok := <-accepted; ok { + t.Cleanup(func() { _ = server.Close() }) + } + tcpConn, ok := conn.(*net.TCPConn) + require.True(t, ok, "%T", conn) + raw, err := tcpConn.SyscallConn() + require.NoError(t, err) + + got := map[string]int{} + var readErr error + require.NoError(t, raw.Control(func(fd uintptr) { + for _, opt := range []struct { + name string + level, which int + }{ + {"SO_KEEPALIVE", syscall.SOL_SOCKET, syscall.SO_KEEPALIVE}, + {"TCP_KEEPIDLE", syscall.IPPROTO_TCP, syscall.TCP_KEEPIDLE}, + {"TCP_KEEPINTVL", syscall.IPPROTO_TCP, syscall.TCP_KEEPINTVL}, + {"TCP_KEEPCNT", syscall.IPPROTO_TCP, syscall.TCP_KEEPCNT}, + {"TCP_USER_TIMEOUT", syscall.IPPROTO_TCP, testTCPUserTimeoutOpt}, + } { + value, err := syscall.GetsockoptInt(int(fd), opt.level, opt.which) + if err != nil { + readErr = err + return + } + got[opt.name] = value + } + })) + require.NoError(t, readErr) + require.Equal(t, map[string]int{ + "SO_KEEPALIVE": 1, + "TCP_KEEPIDLE": 15, + "TCP_KEEPINTVL": 5, + "TCP_KEEPCNT": 3, + "TCP_USER_TIMEOUT": 30000, + }, got) +} + +// A socket option the kernel refuses must not fail the dial: TCP_USER_TIMEOUT +// does not apply to a UDP socket, so setting it there returns an error. +func TestUpstreamDialerIgnoresUserTimeoutFailure(t *testing.T) { + packetConn, err := net.ListenPacket("udp", "127.0.0.1:0") + require.NoError(t, err) + t.Cleanup(func() { _ = packetConn.Close() }) + + conn, err := newUpstreamDialer().DialContext(context.Background(), "udp", packetConn.LocalAddr().String()) + require.NoError(t, err) + require.NoError(t, conn.Close()) +} diff --git a/backend/internal/repository/http_upstream_keepalive_other.go b/backend/internal/repository/http_upstream_keepalive_other.go new file mode 100644 index 0000000000..f7f61b2036 --- /dev/null +++ b/backend/internal/repository/http_upstream_keepalive_other.go @@ -0,0 +1,9 @@ +//go:build !linux + +package repository + +import "syscall" + +// upstreamDialControl is nil off Linux: TCP_USER_TIMEOUT is a Linux socket +// option, and the keep-alive configuration alone bounds idle connections. +var upstreamDialControl func(network, address string, c syscall.RawConn) error diff --git a/backend/internal/repository/integration_harness_test.go b/backend/internal/repository/integration_harness_test.go index 46f18598f2..d33b229449 100644 --- a/backend/internal/repository/integration_harness_test.go +++ b/backend/internal/repository/integration_harness_test.go @@ -36,6 +36,7 @@ const ( var ( integrationDB *sql.DB + integrationDSN string integrationEntClient *dbent.Client integrationRedis *redisclient.Client @@ -91,6 +92,7 @@ func TestMain(m *testing.M) { os.Exit(1) } + integrationDSN = dsn integrationDB, err = openSQLWithRetry(ctx, dsn, 30*time.Second) if err != nil { log.Printf("failed to open sql db: %v", err) diff --git a/backend/internal/repository/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go index 63cc5e58d6..1d1a8ae5af 100644 --- a/backend/internal/repository/scheduler_cache.go +++ b/backend/internal/repository/scheduler_cache.go @@ -1483,6 +1483,11 @@ func filterSchedulerCredentials(credentials map[string]any) map[string]any { // Candidate-list admission evaluates the account override before hydrating // the full account. Dropping it silently falls back to the platform threshold. keys := []string{"model_mapping", "compact_model_mapping", "api_key", "project_id", "oauth_type", "plan_type", "account_scheduling_threshold", + // OpenAI 端点能力集必须进投影:候选过滤按 SupportsOpenAIEndpointCapability 判 + // capability_mismatch,而 Seedance 分支直接读该键、不走「未配置即放行」。 + // 裁掉后 Seedance 账号在选号阶段必然被剔除,表现为 /v1/models 能列出模型、 + // 建任务恒定 503 seedance_no_eligible_account。 + "openai_capabilities", // Gemini 显式缓存的候选过滤(GeminiExplicitCacheExclusions)读本投影判定账号是否支持显式缓存: // 官方地址、Vertex 认证方式与上游网关的显式缓存声明。缺这几个键时只能按类型粗筛, // 不支持的账号要逐个选中后才被剔除。 diff --git a/backend/internal/repository/scheduler_metadata_capabilities_unit_test.go b/backend/internal/repository/scheduler_metadata_capabilities_unit_test.go new file mode 100644 index 0000000000..9d2580e23e --- /dev/null +++ b/backend/internal/repository/scheduler_metadata_capabilities_unit_test.go @@ -0,0 +1,53 @@ +//go:build unit + +package repository + +import ( + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +// buildSchedulerMetadataAccount 是调度候选的唯一投影出口,openAIAccountSkipReason +// 按 SupportsOpenAIEndpointCapability 判 capability_mismatch。Seedance 分支直接读 +// credentials.openai_capabilities 且不走「未配置即放行」,所以该键一旦被裁掉, +// Seedance 账号在选号阶段必然被剔除,而 /v1/models 走 DB 全量仍会列出模型。 +func TestSchedulerMetadataKeepsOpenAICapabilities(t *testing.T) { + account := service.Account{ + ID: 1, + Platform: service.PlatformOpenAI, + Type: service.AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "sk-test", + "base_url": "https://relay.example.com/api/v3", + "openai_capabilities": []string{"seedance"}, + }, + } + + projected := buildSchedulerMetadataAccount(account) + + require.Equal(t, []string{"seedance"}, projected.Credentials["openai_capabilities"]) + require.Equal(t, "https://relay.example.com/api/v3", projected.Credentials["base_url"]) + require.True(t, projected.SupportsOpenAIEndpointCapability(service.OpenAIEndpointCapabilitySeedance)) +} + +func TestSchedulerMetadataDropsUnlistedCredentials(t *testing.T) { + account := service.Account{ + ID: 2, + Platform: service.PlatformOpenAI, + Type: service.AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "sk-test", + "base_url": "https://relay.example.com/api/v3", + "openai_capabilities": []string{"seedance"}, + "model_mapping": map[string]string{"seedance-2-5": "doubao-seedance-2-5-260628"}, + "unlisted_secret": "drop-me", + }, + } + + projected := buildSchedulerMetadataAccount(account) + + require.Equal(t, map[string]string{"seedance-2-5": "doubao-seedance-2-5-260628"}, projected.Credentials["model_mapping"]) + require.NotContains(t, projected.Credentials, "unlisted_secret") +} diff --git a/backend/internal/repository/scheduler_snapshot_membership_integration_test.go b/backend/internal/repository/scheduler_snapshot_membership_integration_test.go new file mode 100644 index 0000000000..457fcce5a7 --- /dev/null +++ b/backend/internal/repository/scheduler_snapshot_membership_integration_test.go @@ -0,0 +1,125 @@ +//go:build integration + +package repository + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestSchedulerSnapshotConfiguredMembership(t *testing.T) { + for _, platform := range []string{service.PlatformOpenAI, service.PlatformAnthropic, service.PlatformGemini} { + t.Run(platform, func(t *testing.T) { + ctx := context.Background() + tx := testEntTx(t) + client := tx.Client() + repo := newAccountRepositoryWithSQL(client, tx, nil) + group := mustCreateGroup(t, client, &service.Group{Name: "snapshot-pool", Platform: platform}) + other := mustCreateGroup(t, client, &service.Group{Name: "snapshot-other", Platform: platform}) + future, past := time.Now().Add(time.Hour), time.Now().Add(-time.Hour) + ids := make(map[int64]map[string]int64) + for _, gid := range []int64{0, group.ID, other.ID} { + ids[gid] = make(map[string]int64) + for _, kind := range []string{"ready", "cooling", "expired", "manual", "disabled", "deleted", "other_platform", "mixed_on", "mixed_off"} { + accountPlatform := platform + if kind == "mixed_on" || kind == "mixed_off" { + accountPlatform = service.PlatformAntigravity + } + if kind == "other_platform" { + accountPlatform = service.PlatformGrok + if platform == accountPlatform { + accountPlatform = service.PlatformOpenAI + } + } + create := client.Account.Create().SetName(fmt.Sprintf("%s-%d", kind, gid)). + SetPlatform(accountPlatform).SetType(service.AccountTypeAPIKey). + SetCredentials(map[string]any{}).SetExtra(map[string]any{"mixed_scheduling": kind == "mixed_on"}). + SetStatus(service.StatusActive).SetSchedulable(kind != "manual") + switch kind { + case "cooling": + create.SetRateLimitResetAt(future).SetOverloadUntil(future).SetTempUnschedulableUntil(future) + case "expired": + create.SetExpiresAt(past).SetAutoPauseOnExpired(true) + case "disabled": + create.SetStatus(service.StatusDisabled) + case "deleted": + create.SetDeletedAt(past) + } + account, err := create.Save(ctx) + require.NoError(t, err) + ids[gid][kind] = account.ID + if gid > 0 { + _, err = client.AccountGroup.Create().SetAccountID(account.ID).SetGroupID(gid).Save(ctx) + require.NoError(t, err) + } + } + } + + for _, scope := range []string{"simple", "group", "ungrouped"} { + for _, forced := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/forced=%t", scope, forced), func(t *testing.T) { + cfg := &config.Config{RunMode: config.RunModeStandard} + cfg.Gateway.Scheduling.DbFallbackEnabled = true + var groupID *int64 + groups := []int64{0} + if scope == "group" { + groupID, groups = &group.ID, []int64{group.ID} + } + if scope == "simple" { + cfg.RunMode = config.RunModeSimple + groupID, groups = &group.ID, []int64{0, group.ID, other.ID} + } + mixed := platform != service.PlatformOpenAI && !forced + var wantReady, wantMembers []int64 + for _, gid := range groups { + wantReady = append(wantReady, ids[gid]["ready"]) + wantMembers = append(wantMembers, ids[gid]["ready"], ids[gid]["cooling"], ids[gid]["expired"]) + if mixed { + wantReady = append(wantReady, ids[gid]["mixed_on"]) + wantMembers = append(wantMembers, ids[gid]["mixed_on"]) + } + } + cache := NewSchedulerCache(testRedis(t)) + svc := service.NewSchedulerSnapshotService(cache, nil, repo, nil, cfg) + accountIDs := func(accounts []service.Account) []int64 { + out := make([]int64, len(accounts)) + for i := range accounts { + out[i] = accounts[i].ID + } + return out + } + for range 2 { + accounts, useMixed, err := svc.ListSchedulableAccounts(ctx, groupID, platform, forced) + require.NoError(t, err) + require.Equal(t, mixed, useMixed) + require.ElementsMatch(t, wantReady, accountIDs(accounts), "both DB fallback and cache hit enforce current eligibility") + } + bucket := service.SchedulerBucket{Platform: platform, Mode: service.SchedulerModeSingle} + if scope == "group" { + bucket.GroupID = group.ID + } + if forced { + bucket.Mode = service.SchedulerModeForced + } else if mixed { + bucket.Mode = service.SchedulerModeMixed + } + members, hit, err := cache.GetSnapshot(ctx, bucket) + require.NoError(t, err) + require.True(t, hit) + memberIDs := make([]int64, len(members)) + for i := range members { + memberIDs[i] = members[i].ID + } + require.ElementsMatch(t, wantMembers, memberIDs, "the stored pool retains timed blocks without widening platform/group or manual eligibility") + }) + } + } + }) + } +} diff --git a/backend/internal/repository/usage_cleanup_repo.go b/backend/internal/repository/usage_cleanup_repo.go index f8aa67477f..a9b184a18e 100644 --- a/backend/internal/repository/usage_cleanup_repo.go +++ b/backend/internal/repository/usage_cleanup_repo.go @@ -291,9 +291,7 @@ func (r *usageCleanupRepository) DeleteUsageLogsBatch(ctx context.Context, filte return 0, fmt.Errorf("cleanup filters missing time range") } args = append(args, limit) - if db, ok := r.sql.(*sql.DB); ok { - return r.deleteUsageLogsBatchWithRollupInvalidation(ctx, db, whereClause, args) - } + // usage_logs 的行级触发器按被删记录的日期使分组日桶失效。 query := fmt.Sprintf(` WITH target AS ( SELECT id @@ -323,68 +321,6 @@ func (r *usageCleanupRepository) DeleteUsageLogsBatch(ctx context.Context, filte return deleted, nil } -func (r *usageCleanupRepository) deleteUsageLogsBatchWithRollupInvalidation(ctx context.Context, db *sql.DB, whereClause string, args []any) (int64, error) { - tx, err := db.BeginTx(ctx, nil) - if err != nil { - return 0, err - } - rollback := func(err error) (int64, error) { - _ = tx.Rollback() - return 0, err - } - - if err := lockGroupUsageRollupState(ctx, tx); err != nil { - return rollback(err) - } - query := fmt.Sprintf(` - WITH target AS ( - SELECT id - FROM usage_logs - WHERE %s - ORDER BY created_at ASC, id ASC - LIMIT $%d - ) - DELETE FROM usage_logs - WHERE id IN (SELECT id FROM target) - RETURNING created_at - `, whereClause, len(args)) - rows, err := tx.QueryContext(ctx, query, args...) - if err != nil { - return rollback(err) - } - - var deleted int64 - var earliestDeletedAt time.Time - for rows.Next() { - var deletedAt time.Time - if err := rows.Scan(&deletedAt); err != nil { - _ = rows.Close() - return rollback(err) - } - deleted++ - if earliestDeletedAt.IsZero() || deletedAt.Before(earliestDeletedAt) { - earliestDeletedAt = deletedAt - } - } - if err := rows.Err(); err != nil { - _ = rows.Close() - return rollback(err) - } - if err := rows.Close(); err != nil { - return rollback(err) - } - - if deleted > 0 { - if err := invalidateGroupUsageRollupsAt(ctx, tx, earliestDeletedAt); err != nil { - return rollback(err) - } - } - if err := tx.Commit(); err != nil { - return 0, err - } - return deleted, nil -} - func buildUsageCleanupWhere(filters service.UsageCleanupFilters) (string, []any) { conditions := make([]string, 0, 8) args := make([]any, 0, 8) diff --git a/backend/internal/repository/usage_cleanup_repo_test.go b/backend/internal/repository/usage_cleanup_repo_test.go index b147d03a4f..4b0034ca0d 100644 --- a/backend/internal/repository/usage_cleanup_repo_test.go +++ b/backend/internal/repository/usage_cleanup_repo_test.go @@ -418,16 +418,9 @@ func TestUsageCleanupRepositoryDeleteUsageLogsBatch(t *testing.T) { Model: &model, } - mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) mock.ExpectQuery("DELETE FROM usage_logs"). WithArgs(start, end, userID, "gpt-4", 2). WillReturnRows(sqlmock.NewRows([]string{"created_at"}).AddRow(start.Add(time.Hour)).AddRow(start.Add(2 * time.Hour))) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs(start.Add(time.Hour), "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectCommit() deleted, err := repo.DeleteUsageLogsBatch(context.Background(), filters, 2) require.NoError(t, err) @@ -435,29 +428,22 @@ func TestUsageCleanupRepositoryDeleteUsageLogsBatch(t *testing.T) { require.NoError(t, mock.ExpectationsWereMet()) } -func TestUsageCleanupRepositoryDeleteUsageLogsBatchAtomicallyInvalidatesGroupRollups(t *testing.T) { +// 分组日桶失效由 usage_logs 的行级触发器完成,删除批次不显式锁定汇总状态行, +// 因而不与 usage_logs 写入串行。 +func TestUsageCleanupRepositoryDeleteUsageLogsBatchDoesNotLockGroupRollupState(t *testing.T) { setUsageCleanupRollupTestTimezone(t) db, mock := newSQLMock(t) repo := &usageCleanupRepository{sql: db} start := time.Date(2026, 8, 1, 0, 0, 0, 0, time.UTC) end := start.Add(24 * time.Hour) - firstDeletedAt := time.Date(2026, 8, 1, 3, 0, 0, 0, time.UTC) - secondDeletedAt := firstDeletedAt.Add(time.Hour) filters := service.UsageCleanupFilters{StartTime: start, EndTime: end} - mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) - mock.ExpectQuery(`(?s)DELETE FROM usage_logs.*RETURNING created_at`). + mock.ExpectQuery(`(?s)WITH target AS.*DELETE FROM usage_logs.*RETURNING created_at`). WithArgs(start, end, 2). WillReturnRows(sqlmock.NewRows([]string{"created_at"}). - AddRow(firstDeletedAt). - AddRow(secondDeletedAt)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs(firstDeletedAt, "Asia/Shanghai"). - WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectCommit() + AddRow(start.Add(3 * time.Hour)). + AddRow(start.Add(4 * time.Hour))) deleted, err := repo.DeleteUsageLogsBatch(context.Background(), filters, 2) require.NoError(t, err) @@ -465,32 +451,6 @@ func TestUsageCleanupRepositoryDeleteUsageLogsBatchAtomicallyInvalidatesGroupRol require.NoError(t, mock.ExpectationsWereMet()) } -func TestUsageCleanupRepositoryDeleteUsageLogsBatchRollsBackWhenInvalidationFails(t *testing.T) { - setUsageCleanupRollupTestTimezone(t) - db, mock := newSQLMock(t) - repo := &usageCleanupRepository{sql: db} - - start := time.Date(2026, 8, 1, 0, 0, 0, 0, time.UTC) - end := start.Add(24 * time.Hour) - deletedAt := time.Date(2026, 8, 1, 3, 0, 0, 0, time.UTC) - filters := service.UsageCleanupFilters{StartTime: start, EndTime: end} - - mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) - mock.ExpectQuery(`(?s)DELETE FROM usage_logs.*RETURNING created_at`). - WithArgs(start, end, 1). - WillReturnRows(sqlmock.NewRows([]string{"created_at"}).AddRow(deletedAt)) - mock.ExpectExec(`UPDATE usage_group_rollup_state`). - WithArgs(deletedAt, "Asia/Shanghai"). - WillReturnError(sql.ErrConnDone) - mock.ExpectRollback() - - _, err := repo.DeleteUsageLogsBatch(context.Background(), filters, 1) - require.ErrorIs(t, err, sql.ErrConnDone) - require.NoError(t, mock.ExpectationsWereMet()) -} - func TestUsageCleanupRepositoryDeleteUsageLogsBatchQueryError(t *testing.T) { db, mock := newSQLMock(t) repo := &usageCleanupRepository{sql: db} @@ -499,13 +459,9 @@ func TestUsageCleanupRepositoryDeleteUsageLogsBatchQueryError(t *testing.T) { end := start.Add(24 * time.Hour) filters := service.UsageCleanupFilters{StartTime: start, EndTime: end} - mock.ExpectBegin() - mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`). - WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) mock.ExpectQuery("DELETE FROM usage_logs"). WithArgs(start, end, 5). WillReturnError(sql.ErrConnDone) - mock.ExpectRollback() _, err := repo.DeleteUsageLogsBatch(context.Background(), filters, 5) require.Error(t, err) diff --git a/backend/internal/repository/usage_log_repo_group_summary_test.go b/backend/internal/repository/usage_log_repo_group_summary_test.go index 676a252ab8..986616736e 100644 --- a/backend/internal/repository/usage_log_repo_group_summary_test.go +++ b/backend/internal/repository/usage_log_repo_group_summary_test.go @@ -20,8 +20,8 @@ func TestUsageLogRepositoryGetAllGroupUsageSummaryUsesRollupTail(t *testing.T) { // 水位有效:closed_before = 2026-03-07(≤ today),时区与配置一致。 mock.ExpectQuery(`(?s)COUNT\(\*\).*usage_group_rollup_state.*WHERE id = 1`). - WillReturnRows(sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name"}). - AddRow(1, "2026-03-07", time.Date(2026, 2, 1, 5, 0, 0, 0, time.UTC), "America/New_York")) + WillReturnRows(sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}). + AddRow(1, "2026-03-07", time.Date(2026, 2, 1, 5, 0, 0, 0, time.UTC), "America/New_York", time.Unix(0, 0).UTC())) // 尾段起点必须以参数形式进 WHERE —— 这正是把 usage_logs 全表扫换回 // idx_usage_logs_created_at 索引扫的那一步。 @@ -61,18 +61,18 @@ func TestUsageLogRepositoryGetAllGroupUsageSummaryFallsBackWhenWatermarkInvalid( }{ { name: "水位行缺失", - rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name"}). - AddRow(0, nil, nil, nil), + rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}). + AddRow(0, nil, nil, nil, nil), }, { name: "时区与当前配置不一致", - rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name"}). - AddRow(1, "2026-03-07", time.Date(2026, 2, 1, 5, 0, 0, 0, time.UTC), "Asia/Shanghai"), + rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}). + AddRow(1, "2026-03-07", time.Date(2026, 2, 1, 5, 0, 0, 0, time.UTC), "Asia/Shanghai", time.Unix(0, 0).UTC()), }, { name: "水位位于未来", - rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name"}). - AddRow(1, "2026-03-10", time.Date(2026, 2, 1, 5, 0, 0, 0, time.UTC), "America/New_York"), + rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}). + AddRow(1, "2026-03-10", time.Date(2026, 2, 1, 5, 0, 0, 0, time.UTC), "America/New_York", time.Unix(0, 0).UTC()), }, } @@ -94,3 +94,66 @@ func TestUsageLogRepositoryGetAllGroupUsageSummaryFallsBackWhenWatermarkInvalid( }) } } + +// 尾段不早于保留下界:水位落后于保留下界时(例如清理已推进下界而重建尚未完成), +// 尚未删除的过期记录也不计入。 +func TestUsageLogRepositoryGetAllGroupUsageSummaryTailStartsAtExpiredBefore(t *testing.T) { + todayStart := time.Date(2026, 3, 9, 4, 0, 0, 0, time.UTC) + yesterdayStart := time.Date(2026, 3, 8, 5, 0, 0, 0, time.UTC) + expiredBefore := time.Date(2026, 2, 10, 5, 0, 0, 0, time.UTC) + + cases := []struct { + name string + rows *sqlmock.Rows + valid bool + retained string + closed string + tailStart time.Time + }{ + { + name: "水位有效但早于保留下界", + rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}). + AddRow(1, "2026-02-01", expiredBefore, "America/New_York", expiredBefore), + valid: true, + retained: "2026-02-10", + closed: "2026-02-01", + tailStart: expiredBefore, + }, + { + name: "retained_from 早于保留下界", + rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}). + AddRow(1, "2026-03-07", time.Date(2026, 1, 20, 5, 0, 0, 0, time.UTC), "America/New_York", expiredBefore), + valid: true, + retained: "2026-02-10", + closed: "2026-03-07", + tailStart: time.Date(2026, 3, 7, 5, 0, 0, 0, time.UTC), + }, + { + name: "水位无效", + rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}). + AddRow(1, "2026-03-07", expiredBefore, "Asia/Shanghai", expiredBefore), + valid: false, + retained: "1970-01-01", + closed: "1970-01-01", + tailStart: expiredBefore, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + db, mock := newSQLMock(t) + repo := newUsageLogRepositoryWithSQL(nil, db) + useGroupUsageRepositoryTestTimezone(t, "America/New_York") + + mock.ExpectQuery(`(?s)COUNT\(\*\).*MAX\(expired_before\).*usage_group_rollup_state.*WHERE id = 1`). + WillReturnRows(tc.rows) + mock.ExpectQuery(`(?s)usage_group_daily_rollups.*FROM usage_logs ul\s+WHERE ul\.created_at >= \$7`). + WithArgs(todayStart, yesterdayStart, "2026-03-08", tc.valid, tc.retained, tc.closed, tc.tailStart). + WillReturnRows(sqlmock.NewRows([]string{"group_id", "total_cost", "today_cost", "yesterday_cost"})) + + _, err := repo.GetAllGroupUsageSummary(context.Background(), todayStart) + require.NoError(t, err) + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} diff --git a/backend/internal/repository/usage_log_repo_integration_test.go b/backend/internal/repository/usage_log_repo_integration_test.go index 1ba7609fa4..e0798b2fb7 100644 --- a/backend/internal/repository/usage_log_repo_integration_test.go +++ b/backend/internal/repository/usage_log_repo_integration_test.go @@ -1308,6 +1308,34 @@ func (s *UsageLogRepoSuite) TestGetAccountWindowStats() { s.Require().Equal(int64(70), stats.Tokens) // (10+20) + (15+25) } +func (s *UsageLogRepoSuite) TestActiveFiveHourResetExcludesPreviousWindowCost() { + user := mustCreateUser(s.T(), s.client, &service.User{Email: "window-reset@test.com"}) + apiKey := mustCreateApiKey(s.T(), s.client, &service.APIKey{UserID: user.ID, Key: "sk-window-reset", Name: "k"}) + start := time.Now().UTC().Truncate(time.Second).Add(-30 * time.Minute) + oldStart := start.Add(-5 * time.Hour) + end := start.Add(5 * time.Hour) + account := mustCreateAccount(s.T(), s.client, &service.Account{ + Name: "window-reset", Platform: service.PlatformAnthropic, Type: service.AccountTypeOAuth, + SessionWindowStart: &oldStart, SessionWindowEnd: &start, SessionWindowStatus: "allowed", + Extra: map[string]any{"window_cost_limit": 10.0, "window_cost_sticky_reserve": 1.0}, + }) + s.createUsageLog(user, apiKey, account, 10, 20, 20, start.Add(-time.Minute)) + s.createUsageLog(user, apiKey, account, 10, 20, 2, start.Add(time.Minute)) + accounts := newAccountRepositoryWithSQL(s.client, s.tx, nil) + + // Active quota reads persist this reset before another model response can + // supply session-window headers. Reload as the next scheduler/UI read does. + s.Require().NoError(accounts.UpdateSessionWindowEnd(s.ctx, account.ID, end)) + reloaded, err := accounts.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + stats, err := s.repo.GetAccountWindowStats(s.ctx, account.ID, reloaded.GetCurrentWindowStartTime()) + s.Require().NoError(err) + s.Require().Equal(int64(1), stats.Requests, "the previous window's request must not count in the new window") + s.Require().InDelta(2, stats.StandardCost, 0.000001) + s.Require().Equal(service.WindowCostSchedulable, reloaded.CheckWindowCostSchedulability(stats.StandardCost)) + s.Require().Equal("allowed", reloaded.SessionWindowStatus) +} + // --- GetUserUsageTrendByUserID --- func (s *UsageLogRepoSuite) TestGetUserUsageTrendByUserID() { @@ -1449,16 +1477,18 @@ func (s *UsageLogRepoSuite) TestGetModelStatsWithFilters() { base := time.Date(2025, 1, 15, 12, 0, 0, 0, time.UTC) + accountRate := 0.4 log1 := &service.UsageLog{ - UserID: user.ID, - APIKeyID: apiKey.ID, - AccountID: account.ID, - Model: "claude-3-opus", - InputTokens: 100, - OutputTokens: 200, - TotalCost: 0.5, - ActualCost: 0.5, - CreatedAt: base, + UserID: user.ID, + APIKeyID: apiKey.ID, + AccountID: account.ID, + Model: "claude-3-opus", + InputTokens: 100, + OutputTokens: 200, + TotalCost: 0.5, + ActualCost: 1.0, + AccountRateMultiplier: &accountRate, + CreatedAt: base, } _, err := s.repo.Create(s.ctx, log1) s.Require().NoError(err) @@ -1494,6 +1524,12 @@ func (s *UsageLogRepoSuite) TestGetModelStatsWithFilters() { stats, err = s.repo.GetModelStatsWithFilters(s.ctx, startTime, endTime, 0, 0, account.ID, 0, nil, nil, nil) s.Require().NoError(err, "GetModelStatsWithFilters account filter") s.Require().Len(stats, 2) + for _, stat := range stats { + if stat.Model == "claude-3-opus" { + s.Require().InEpsilon(1.0, stat.ActualCost, 0.0001) + s.Require().InEpsilon(0.2, stat.AccountCost, 0.0001) + } + } } // --- GetAccountUsageStats --- diff --git a/backend/internal/repository/usage_log_repo_request_type_test.go b/backend/internal/repository/usage_log_repo_request_type_test.go index c8fb2f62ad..b37a316857 100644 --- a/backend/internal/repository/usage_log_repo_request_type_test.go +++ b/backend/internal/repository/usage_log_repo_request_type_test.go @@ -1187,3 +1187,48 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) { }) } + +func TestUsageLogRepositoryGetModelStatsAccountFilterKeepsActualCost(t *testing.T) { + db, mock := newSQLMock(t) + repo := &usageLogRepository{sql: db} + + start := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC) + end := start.Add(24 * time.Hour) + accountID := int64(42) + + mock.ExpectQuery("COALESCE\\(SUM\\(actual_cost\\), 0\\) as actual_cost,\\s+COALESCE\\(SUM\\(COALESCE\\(account_stats_cost, total_cost\\) \\* COALESCE\\(account_rate_multiplier, 1\\)\\), 0\\) as account_cost"). + WithArgs(start, end, accountID). + WillReturnRows(sqlmock.NewRows([]string{ + "model", "requests", "input_tokens", "output_tokens", + "cache_creation_tokens", "cache_read_tokens", "total_tokens", + "cost", "actual_cost", "account_cost", + }).AddRow("gemini-4-argon", int64(3), int64(10), int64(20), int64(0), int64(0), int64(30), 6.0, 2.4, 0.9)) + + results, err := repo.GetModelStatsWithUsageFiltersBySource(context.Background(), start, end, usagestats.UsageLogFilters{AccountID: accountID}, usagestats.ModelSourceRequested) + require.NoError(t, err) + require.Len(t, results, 1) + require.Equal(t, 2.4, results[0].ActualCost) + require.Equal(t, 0.9, results[0].AccountCost) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestUsageLogRepositoryGetEndpointStatsAccountFilterKeepsActualCost(t *testing.T) { + db, mock := newSQLMock(t) + repo := &usageLogRepository{sql: db} + + start := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC) + end := start.Add(24 * time.Hour) + accountID := int64(42) + + mock.ExpectQuery("COALESCE\\(SUM\\(actual_cost\\), 0\\) as actual_cost,\\s+COALESCE\\(SUM\\(COALESCE\\(account_stats_cost, total_cost\\) \\* COALESCE\\(account_rate_multiplier, 1\\)\\), 0\\) as account_cost"). + WithArgs(start, end, accountID). + WillReturnRows(sqlmock.NewRows([]string{"endpoint", "requests", "total_tokens", "cost", "actual_cost", "account_cost"}). + AddRow("/v1beta/models", int64(3), int64(30), 6.0, 2.4, 0.9)) + + results, err := repo.GetEndpointStatsWithFilters(context.Background(), start, end, 0, 0, accountID, 0, "", nil, nil, nil) + require.NoError(t, err) + require.Len(t, results, 1) + require.Equal(t, 2.4, results[0].ActualCost) + require.Equal(t, 0.9, results[0].AccountCost) + require.NoError(t, mock.ExpectationsWereMet()) +} diff --git a/backend/internal/repository/usage_log_repo_stats.go b/backend/internal/repository/usage_log_repo_stats.go index 91e0eaf77b..5dfb74646f 100644 --- a/backend/internal/repository/usage_log_repo_stats.go +++ b/backend/internal/repository/usage_log_repo_stats.go @@ -402,8 +402,8 @@ func (r *usageLogRepository) GetGeminiUsageTotalsBatch(ctx context.Context, acco COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN 0 ELSE 1 END), 0) AS pro_requests, COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN (input_tokens + output_tokens + cache_creation_tokens + cache_read_tokens) ELSE 0 END), 0) AS flash_tokens, COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN 0 ELSE (input_tokens + output_tokens + cache_creation_tokens + cache_read_tokens) END), 0) AS pro_tokens, - COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN actual_cost ELSE 0 END), 0) AS flash_cost, - COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN 0 ELSE actual_cost END), 0) AS pro_cost + COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1) ELSE 0 END), 0) AS flash_cost, + COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN 0 ELSE COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1) END), 0) AS pro_cost FROM usage_logs WHERE account_id = ANY($1) AND created_at >= $2 AND created_at < $3 GROUP BY account_id @@ -736,7 +736,6 @@ func (r *usageLogRepository) GetStatsWithFilters(ctx context.Context, filters Us stats := &UsageStats{} var totalAccountCost float64 - useAccountCostForEndpoint := filters.AccountID > 0 && filters.UserID == 0 && filters.APIKeyID == 0 rows, err := r.sql.QueryContext(ctx, query, args...) if err != nil { return nil, err @@ -769,10 +768,6 @@ func (r *usageLogRepository) GetStatsWithFilters(ctx context.Context, filters Us } totalTokens := inputTokens + outputTokens + cacheCreationTokens + cacheReads - endpointActualCost := actualCost - if useAccountCostForEndpoint { - endpointActualCost = accountCost - } switch { case inboundGrouped == 1 && upstreamGrouped == 1: @@ -789,17 +784,17 @@ func (r *usageLogRepository) GetStatsWithFilters(ctx context.Context, filters Us case inboundGrouped == 0 && upstreamGrouped == 1: stats.Endpoints = append(stats.Endpoints, EndpointStat{ Endpoint: inboundEndpoint.String, Requests: requests, TotalTokens: totalTokens, - Cost: cost, ActualCost: endpointActualCost, + Cost: cost, ActualCost: actualCost, AccountCost: accountCost, }) case inboundGrouped == 1 && upstreamGrouped == 0: stats.UpstreamEndpoints = append(stats.UpstreamEndpoints, EndpointStat{ Endpoint: upstreamEndpoint.String, Requests: requests, TotalTokens: totalTokens, - Cost: cost, ActualCost: endpointActualCost, + Cost: cost, ActualCost: actualCost, AccountCost: accountCost, }) case inboundGrouped == 0 && upstreamGrouped == 0: stats.EndpointPaths = append(stats.EndpointPaths, EndpointStat{ Endpoint: inboundEndpoint.String + " -> " + upstreamEndpoint.String, - Requests: requests, TotalTokens: totalTokens, Cost: cost, ActualCost: endpointActualCost, + Requests: requests, TotalTokens: totalTokens, Cost: cost, ActualCost: actualCost, AccountCost: accountCost, }) } } @@ -838,21 +833,17 @@ type AccountUsageStatsResponse = usagestats.AccountUsageStatsResponse type EndpointStat = usagestats.EndpointStat func (r *usageLogRepository) getEndpointStatsByColumnWithFilters(ctx context.Context, endpointColumn string, startTime, endTime time.Time, userID, apiKeyID, accountID, groupID int64, model string, modelSource string, requestType *int16, stream *bool, billingType *int8, billingMode string) (results []EndpointStat, err error) { - actualCostExpr := "COALESCE(SUM(actual_cost), 0) as actual_cost" - if accountID > 0 && userID == 0 && apiKeyID == 0 { - actualCostExpr = "COALESCE(SUM(COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1)), 0) as actual_cost" - } - query := fmt.Sprintf(` SELECT COALESCE(NULLIF(TRIM(%s), ''), 'unknown') AS endpoint, COUNT(*) AS requests, COALESCE(SUM(input_tokens + output_tokens + cache_creation_tokens + cache_read_tokens), 0) AS total_tokens, COALESCE(SUM(total_cost), 0) as cost, - %s + COALESCE(SUM(actual_cost), 0) as actual_cost, + COALESCE(SUM(COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1)), 0) as account_cost FROM usage_logs WHERE created_at >= $1 AND created_at < $2 - `, endpointColumn, actualCostExpr) + `, endpointColumn) args := []any{startTime, endTime} if userID > 0 { @@ -894,7 +885,7 @@ func (r *usageLogRepository) getEndpointStatsByColumnWithFilters(ctx context.Con results = make([]EndpointStat, 0) for rows.Next() { var row EndpointStat - if err := rows.Scan(&row.Endpoint, &row.Requests, &row.TotalTokens, &row.Cost, &row.ActualCost); err != nil { + if err := rows.Scan(&row.Endpoint, &row.Requests, &row.TotalTokens, &row.Cost, &row.ActualCost, &row.AccountCost); err != nil { return nil, err } results = append(results, row) diff --git a/backend/internal/repository/usage_log_repo_trend.go b/backend/internal/repository/usage_log_repo_trend.go index cc7a46ffbf..dcc706115e 100644 --- a/backend/internal/repository/usage_log_repo_trend.go +++ b/backend/internal/repository/usage_log_repo_trend.go @@ -449,12 +449,6 @@ func (r *usageLogRepository) GetModelStatsWithUsageFiltersBySource(ctx context.C } func (r *usageLogRepository) getModelStatsWithFiltersBySource(ctx context.Context, startTime, endTime time.Time, userID, apiKeyID, accountID, groupID int64, model string, requestType *int16, stream *bool, billingType *int8, source string, billingMode string, upstreamModelMismatch *bool, nativeCompactionV2 *bool) (results []ModelStat, err error) { - actualCostExpr := "COALESCE(SUM(actual_cost), 0) as actual_cost" - // 当仅按 account_id 聚合时,实际费用使用账号倍率(total_cost * account_rate_multiplier)。 - if accountID > 0 && userID == 0 && apiKeyID == 0 { - actualCostExpr = "COALESCE(SUM(COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1)), 0) as actual_cost" - } - accountCostExpr := "COALESCE(SUM(COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1)), 0) as account_cost" modelExpr := resolveModelDimensionExpression(source) query := fmt.Sprintf(` @@ -467,11 +461,11 @@ func (r *usageLogRepository) getModelStatsWithFiltersBySource(ctx context.Contex COALESCE(SUM(cache_read_tokens), 0) as cache_read_tokens, COALESCE(SUM(input_tokens + output_tokens + cache_creation_tokens + cache_read_tokens), 0) as total_tokens, COALESCE(SUM(total_cost), 0) as cost, - %s, - %s + COALESCE(SUM(actual_cost), 0) as actual_cost, + COALESCE(SUM(COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1)), 0) as account_cost FROM usage_logs WHERE created_at >= $1 AND created_at < $2 - `, modelExpr, actualCostExpr, accountCostExpr) + `, modelExpr) args := []any{startTime, endTime} if userID > 0 { diff --git a/backend/internal/repository/user_group_rate_repo.go b/backend/internal/repository/user_group_rate_repo.go index 74d25cb0b6..81b17654e0 100644 --- a/backend/internal/repository/user_group_rate_repo.go +++ b/backend/internal/repository/user_group_rate_repo.go @@ -3,6 +3,7 @@ package repository import ( "context" "database/sql" + "fmt" "time" "github.com/Wei-Shaw/sub2api/internal/service" @@ -11,11 +12,55 @@ import ( type userGroupRateRepository struct { sql sqlExecutor + db *sql.DB } // NewUserGroupRateRepository 创建用户专属分组倍率/RPM 仓储 func NewUserGroupRateRepository(sqlDB *sql.DB) service.UserGroupRateRepository { - return &userGroupRateRepository{sql: sqlDB} + return &userGroupRateRepository{sql: sqlDB, db: sqlDB} +} + +func (r *userGroupRateRepository) beginTx(ctx context.Context) (*sql.Tx, error) { + if r == nil || r.db == nil { + return nil, fmt.Errorf("user group rate repository: database handle is not configured") + } + return r.db.BeginTx(ctx, nil) +} + +// dedupeGroupRateMultiplierEntries 按 user_id 去重,保留最后一次出现的值。 +// ON CONFLICT DO UPDATE 对同一行出现两次会直接报错,去重后才能安全写入。 +func dedupeGroupRateMultiplierEntries(entries []service.GroupRateMultiplierInput) []service.GroupRateMultiplierInput { + if len(entries) < 2 { + return entries + } + index := make(map[int64]int, len(entries)) + out := make([]service.GroupRateMultiplierInput, 0, len(entries)) + for _, entry := range entries { + if pos, ok := index[entry.UserID]; ok { + out[pos] = entry + continue + } + index[entry.UserID] = len(out) + out = append(out, entry) + } + return out +} + +func dedupeGroupRPMOverrideEntries(entries []service.GroupRPMOverrideInput) []service.GroupRPMOverrideInput { + if len(entries) < 2 { + return entries + } + index := make(map[int64]int, len(entries)) + out := make([]service.GroupRPMOverrideInput, 0, len(entries)) + for _, entry := range entries { + if pos, ok := index[entry.UserID]; ok { + out[pos] = entry + continue + } + index[entry.UserID] = len(out) + out = append(out, entry) + } + return out } // GetByUserID 获取用户所有专属分组 rate_multiplier(仅返回非 NULL 的条目) @@ -244,14 +289,22 @@ func (r *userGroupRateRepository) SyncUserGroupRates(ctx context.Context, userID // - 未出现在 entries 中的用户行:rate_multiplier 归 NULL;若 rpm_override 也为 NULL 则整行删除。 // - 出现的用户行:upsert rate_multiplier。 func (r *userGroupRateRepository) SyncGroupRateMultipliers(ctx context.Context, groupID int64, entries []service.GroupRateMultiplierInput) error { + entries = dedupeGroupRateMultiplierEntries(entries) + keepUserIDs := make([]int64, 0, len(entries)) for _, e := range entries { keepUserIDs = append(keepUserIDs, e.UserID) } + tx, err := r.beginTx(ctx) + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + // 未在 entries 列表中的行:清空 rate_multiplier。 if len(keepUserIDs) == 0 { - if _, err := r.sql.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, ` UPDATE user_group_rate_multipliers SET rate_multiplier = NULL, updated_at = NOW() WHERE group_id = $1 @@ -259,7 +312,7 @@ func (r *userGroupRateRepository) SyncGroupRateMultipliers(ctx context.Context, return err } } else { - if _, err := r.sql.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, ` UPDATE user_group_rate_multipliers SET rate_multiplier = NULL, updated_at = NOW() WHERE group_id = $1 AND user_id <> ALL($2) @@ -269,32 +322,33 @@ func (r *userGroupRateRepository) SyncGroupRateMultipliers(ctx context.Context, } // 清空后若整行 NULL 则删除。 - if _, err := r.sql.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, ` DELETE FROM user_group_rate_multipliers WHERE group_id = $1 AND rate_multiplier IS NULL AND rpm_override IS NULL `, groupID); err != nil { return err } - if len(entries) == 0 { - return nil + if len(entries) > 0 { + userIDs := make([]int64, len(entries)) + rates := make([]float64, len(entries)) + for i, e := range entries { + userIDs[i] = e.UserID + rates[i] = e.RateMultiplier + } + now := time.Now() + if _, err := tx.ExecContext(ctx, ` + INSERT INTO user_group_rate_multipliers (user_id, group_id, rate_multiplier, created_at, updated_at) + SELECT data.user_id, $1::bigint, data.rate_multiplier, $2::timestamptz, $2::timestamptz + FROM unnest($3::bigint[], $4::double precision[]) AS data(user_id, rate_multiplier) + ON CONFLICT (user_id, group_id) + DO UPDATE SET rate_multiplier = EXCLUDED.rate_multiplier, updated_at = EXCLUDED.updated_at + `, groupID, now, pq.Array(userIDs), pq.Array(rates)); err != nil { + return err + } } - userIDs := make([]int64, len(entries)) - rates := make([]float64, len(entries)) - for i, e := range entries { - userIDs[i] = e.UserID - rates[i] = e.RateMultiplier - } - now := time.Now() - _, err := r.sql.ExecContext(ctx, ` - INSERT INTO user_group_rate_multipliers (user_id, group_id, rate_multiplier, created_at, updated_at) - SELECT data.user_id, $1::bigint, data.rate_multiplier, $2::timestamptz, $2::timestamptz - FROM unnest($3::bigint[], $4::double precision[]) AS data(user_id, rate_multiplier) - ON CONFLICT (user_id, group_id) - DO UPDATE SET rate_multiplier = EXCLUDED.rate_multiplier, updated_at = EXCLUDED.updated_at - `, groupID, now, pq.Array(userIDs), pq.Array(rates)) - return err + return tx.Commit() } // SyncGroupRPMOverrides 同步分组的 rpm_override 部分(不触动 rate_multiplier)。 @@ -302,6 +356,8 @@ func (r *userGroupRateRepository) SyncGroupRateMultipliers(ctx context.Context, // - 未出现的用户行:rpm_override 归 NULL;若 rate_multiplier 也为 NULL 则整行删除。 // - 出现的用户行:若 RPMOverride 为 nil 则清空;非 nil 则 upsert。 func (r *userGroupRateRepository) SyncGroupRPMOverrides(ctx context.Context, groupID int64, entries []service.GroupRPMOverrideInput) error { + entries = dedupeGroupRPMOverrideEntries(entries) + keepUserIDs := make([]int64, 0, len(entries)) var clearUserIDs []int64 upsertUserIDs := make([]int64, 0, len(entries)) @@ -316,9 +372,15 @@ func (r *userGroupRateRepository) SyncGroupRPMOverrides(ctx context.Context, gro } } + tx, err := r.beginTx(ctx) + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + // 未在 entries 列表中的行:清空 rpm_override。 if len(keepUserIDs) == 0 { - if _, err := r.sql.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, ` UPDATE user_group_rate_multipliers SET rpm_override = NULL, updated_at = NOW() WHERE group_id = $1 @@ -326,7 +388,7 @@ func (r *userGroupRateRepository) SyncGroupRPMOverrides(ctx context.Context, gro return err } } else { - if _, err := r.sql.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, ` UPDATE user_group_rate_multipliers SET rpm_override = NULL, updated_at = NOW() WHERE group_id = $1 AND user_id <> ALL($2) @@ -337,7 +399,7 @@ func (r *userGroupRateRepository) SyncGroupRPMOverrides(ctx context.Context, gro // 显式 clear 的行。 if len(clearUserIDs) > 0 { - if _, err := r.sql.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, ` UPDATE user_group_rate_multipliers SET rpm_override = NULL, updated_at = NOW() WHERE group_id = $1 AND user_id = ANY($2) @@ -347,7 +409,7 @@ func (r *userGroupRateRepository) SyncGroupRPMOverrides(ctx context.Context, gro } // 清空后若整行 NULL 则删除。 - if _, err := r.sql.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, ` DELETE FROM user_group_rate_multipliers WHERE group_id = $1 AND rate_multiplier IS NULL AND rpm_override IS NULL `, groupID); err != nil { @@ -356,19 +418,18 @@ func (r *userGroupRateRepository) SyncGroupRPMOverrides(ctx context.Context, gro if len(upsertUserIDs) > 0 { now := time.Now() - _, err := r.sql.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, ` INSERT INTO user_group_rate_multipliers (user_id, group_id, rpm_override, created_at, updated_at) SELECT data.user_id, $1::bigint, data.rpm_override, $2::timestamptz, $2::timestamptz FROM unnest($3::bigint[], $4::integer[]) AS data(user_id, rpm_override) ON CONFLICT (user_id, group_id) DO UPDATE SET rpm_override = EXCLUDED.rpm_override, updated_at = EXCLUDED.updated_at - `, groupID, now, pq.Array(upsertUserIDs), pq.Array(upsertValues)) - if err != nil { + `, groupID, now, pq.Array(upsertUserIDs), pq.Array(upsertValues)); err != nil { return err } } - return nil + return tx.Commit() } // ClearGroupRPMOverrides 清空指定分组所有行的 rpm_override。 diff --git a/backend/internal/repository/user_group_rate_repo_sync_test.go b/backend/internal/repository/user_group_rate_repo_sync_test.go new file mode 100644 index 0000000000..cd6d6282d4 --- /dev/null +++ b/backend/internal/repository/user_group_rate_repo_sync_test.go @@ -0,0 +1,138 @@ +package repository + +import ( + "context" + "errors" + "testing" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestSyncGroupRateMultipliersCommitsInOneTransaction(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + repo := NewUserGroupRateRepository(db) + + mock.ExpectBegin() + mock.ExpectExec("UPDATE user_group_rate_multipliers"). + WithArgs(int64(10), sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec("DELETE FROM user_group_rate_multipliers"). + WithArgs(int64(10)). + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec("INSERT INTO user_group_rate_multipliers"). + WithArgs(int64(10), sqlmock.AnyArg(), sqlmock.AnyArg(), sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectCommit() + + err = repo.SyncGroupRateMultipliers(context.Background(), 10, []service.GroupRateMultiplierInput{ + {UserID: 1, RateMultiplier: 1.5}, + }) + require.NoError(t, err) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestSyncGroupRateMultipliersRollsBackOnInsertFailure(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + repo := NewUserGroupRateRepository(db) + + mock.ExpectBegin() + mock.ExpectExec("UPDATE user_group_rate_multipliers"). + WithArgs(int64(10), sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(0, 2)) + mock.ExpectExec("DELETE FROM user_group_rate_multipliers"). + WithArgs(int64(10)). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec("INSERT INTO user_group_rate_multipliers"). + WithArgs(int64(10), sqlmock.AnyArg(), sqlmock.AnyArg(), sqlmock.AnyArg()). + WillReturnError(errors.New("insert failed")) + mock.ExpectRollback() + + err = repo.SyncGroupRateMultipliers(context.Background(), 10, []service.GroupRateMultiplierInput{ + {UserID: 1, RateMultiplier: 1.5}, + }) + require.ErrorContains(t, err, "insert failed") + require.NoError(t, mock.ExpectationsWereMet(), "the destructive UPDATE/DELETE must be rolled back") +} + +func TestSyncGroupRPMOverridesCommitsInOneTransaction(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + repo := NewUserGroupRateRepository(db) + + override := 5 + mock.ExpectBegin() + mock.ExpectExec("UPDATE user_group_rate_multipliers"). + WithArgs(int64(10), sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec("DELETE FROM user_group_rate_multipliers"). + WithArgs(int64(10)). + WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec("INSERT INTO user_group_rate_multipliers"). + WithArgs(int64(10), sqlmock.AnyArg(), sqlmock.AnyArg(), sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectCommit() + + err = repo.SyncGroupRPMOverrides(context.Background(), 10, []service.GroupRPMOverrideInput{ + {UserID: 1, RPMOverride: &override}, + }) + require.NoError(t, err) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestSyncGroupRPMOverridesRollsBackOnInsertFailure(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + repo := NewUserGroupRateRepository(db) + + override := 5 + mock.ExpectBegin() + mock.ExpectExec("UPDATE user_group_rate_multipliers"). + WithArgs(int64(10), sqlmock.AnyArg()). + WillReturnResult(sqlmock.NewResult(0, 2)) + mock.ExpectExec("DELETE FROM user_group_rate_multipliers"). + WithArgs(int64(10)). + WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec("INSERT INTO user_group_rate_multipliers"). + WithArgs(int64(10), sqlmock.AnyArg(), sqlmock.AnyArg(), sqlmock.AnyArg()). + WillReturnError(errors.New("insert failed")) + mock.ExpectRollback() + + err = repo.SyncGroupRPMOverrides(context.Background(), 10, []service.GroupRPMOverrideInput{ + {UserID: 1, RPMOverride: &override}, + }) + require.ErrorContains(t, err, "insert failed") + require.NoError(t, mock.ExpectationsWereMet(), "the destructive UPDATE/DELETE must be rolled back") +} + +func TestDedupeGroupRateMultiplierEntriesKeepsLastValue(t *testing.T) { + got := dedupeGroupRateMultiplierEntries([]service.GroupRateMultiplierInput{ + {UserID: 1, RateMultiplier: 1}, + {UserID: 2, RateMultiplier: 2}, + {UserID: 1, RateMultiplier: 3}, + }) + require.Equal(t, []service.GroupRateMultiplierInput{ + {UserID: 1, RateMultiplier: 3}, + {UserID: 2, RateMultiplier: 2}, + }, got) +} + +func TestDedupeGroupRPMOverrideEntriesKeepsLastValue(t *testing.T) { + five := 5 + got := dedupeGroupRPMOverrideEntries([]service.GroupRPMOverrideInput{ + {UserID: 1}, + {UserID: 2, RPMOverride: &five}, + {UserID: 1, RPMOverride: &five}, + }) + require.Len(t, got, 2) + require.Equal(t, int64(1), got[0].UserID) + require.Equal(t, &five, got[0].RPMOverride) + require.Equal(t, int64(2), got[1].UserID) +} diff --git a/backend/internal/server/api_contract_test.go b/backend/internal/server/api_contract_test.go index 81d3d91854..df8bf1dd80 100644 --- a/backend/internal/server/api_contract_test.go +++ b/backend/internal/server/api_contract_test.go @@ -2047,6 +2047,10 @@ func (s *stubAccountRepo) ClearModelRateLimits(ctx context.Context, id int64) er return errors.New("not implemented") } +func (s *stubAccountRepo) ClearModelRateLimit(ctx context.Context, id int64, scope string) error { + return errors.New("not implemented") +} + func (s *stubAccountRepo) UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error { return errors.New("not implemented") } diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 63fd809baf..2fe64d9ee7 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -2415,10 +2415,8 @@ const ( // 三态:default(跟随渠道)/ enabled(强制开启)/ disabled(强制关闭)。 // 兼容旧 bool 值:true→enabled, false→default(并记录 debug 日志)。 func (a *Account) GetWebSearchEmulationMode() string { - // OpenAI API Key accounts reach this via /v1/messages; their upstreams - // (DeepSeek etc. over Chat Completions) have no web_search tool. if a == nil || a.Type != AccountTypeAPIKey || a.Extra == nil || - (a.Platform != PlatformAnthropic && a.Platform != PlatformOpenAI) { + !webSearchEmulationPlatformEnabled(a.Platform) { return WebSearchModeDefault } raw := a.Extra[featureKeyWebSearchEmulation] @@ -2442,6 +2440,17 @@ func (a *Account) GetWebSearchEmulationMode() string { } } +// webSearchEmulationPlatformEnabled reports whether API key accounts of the +// platform can set the account-level web search emulation mode. Keep it in sync +// with WEB_SEARCH_EMULATION_PLATFORMS in frontend/src/views/admin/ChannelsView.vue. +func webSearchEmulationPlatformEnabled(platform string) bool { + switch platform { + case PlatformAnthropic, PlatformOpenAI, PlatformZhipu, PlatformCommandCode, PlatformOpenCodeGo, PlatformMiniMax: + return true + } + return false +} + // IsCodexCLIOnlyEnabled 返回 OpenAI OAuth 账号是否启用"仅允许 Codex 官方客户端"。 // 字段:accounts.extra.codex_cli_only。 // 字段缺失或类型不正确时,按 false(关闭)处理。 diff --git a/backend/internal/service/account_scheduling_threshold_eval.go b/backend/internal/service/account_scheduling_threshold_eval.go index 951629658e..24c45d9a99 100644 --- a/backend/internal/service/account_scheduling_threshold_eval.go +++ b/backend/internal/service/account_scheduling_threshold_eval.go @@ -375,9 +375,15 @@ func cnProviderThresholdCandidates(account *Account, provider string) []*account return candidates } -// cnQuotaHasMonthlyWindow 报告供应商的额度快照是否含月度窗口(OpenCode Go、Command Code)。 +// cnQuotaHasMonthlyWindow 报告供应商的额度快照是否含月度窗口(OpenCode Go、 +// Command Code 与 Kimi 新套餐)。 func cnQuotaHasMonthlyWindow(provider string) bool { - return provider == PlatformOpenCodeGo || provider == PlatformCommandCode + switch provider { + case PlatformOpenCodeGo, PlatformCommandCode, PlatformKimi: + return true + default: + return false + } } func cnThresholdCandidate(extra map[string]any, provider, window string) *accountSchedulingThresholdCandidate { diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go index 7980a5c447..541d6abd77 100644 --- a/backend/internal/service/account_service.go +++ b/backend/internal/service/account_service.go @@ -94,8 +94,8 @@ type AccountRepository interface { ListSchedulableUngroupedByPlatforms(ctx context.Context, platforms []string) ([]Account, error) // ListModelAvailabilityCandidates returns accounts that are enabled by // persistent configuration (active + schedulable) for model-support - // diagnosis. It deliberately does not filter transient runtime state such - // as rate-limit, overload, temporary-unschedulable, or expiry windows. + // diagnosis and scheduler snapshot membership. It deliberately does not + // filter rate-limit, overload, temporary-unschedulable, or expiry windows. // When groupID is nil, includeGrouped controls whether the query scans all // matching accounts or only accounts without a group binding. ListModelAvailabilityCandidates(ctx context.Context, groupID *int64, platforms []string, includeGrouped bool) ([]Account, error) @@ -108,6 +108,9 @@ type AccountRepository interface { ClearRateLimit(ctx context.Context, id int64) error ClearAntigravityQuotaScopes(ctx context.Context, id int64) error ClearModelRateLimits(ctx context.Context, id int64) error + // ClearModelRateLimit 只清除指定 scope 的模型级限流,用于单个模型窗口恢复后 + // 定向解封,不影响其他模型与并发生效的限流。 + ClearModelRateLimit(ctx context.Context, id int64, scope string) error UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error // UpdateSessionWindowEnd 仅更新 5h 窗口的结束时间,不动 start / status。 // 用于 active poll 拿到新 ResetsAt 后回写,避免覆盖请求路径上记录的 status。 diff --git a/backend/internal/service/account_service_delete_test.go b/backend/internal/service/account_service_delete_test.go index ed65c25c1b..80c4ff6e6d 100644 --- a/backend/internal/service/account_service_delete_test.go +++ b/backend/internal/service/account_service_delete_test.go @@ -195,6 +195,10 @@ func (s *accountRepoStub) ClearModelRateLimits(ctx context.Context, id int64) er panic("unexpected ClearModelRateLimits call") } +func (s *accountRepoStub) ClearModelRateLimit(ctx context.Context, id int64, scope string) error { + panic("unexpected ClearModelRateLimit call") +} + func (s *accountRepoStub) UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error { panic("unexpected UpdateSessionWindow call") } diff --git a/backend/internal/service/account_usage_service.go b/backend/internal/service/account_usage_service.go index f9a8904e6c..9e30d64eed 100644 --- a/backend/internal/service/account_usage_service.go +++ b/backend/internal/service/account_usage_service.go @@ -287,8 +287,20 @@ type ClaudeUsageResponse struct { } `json:"seven_day_sonnet"` // Fable 专属 7d 窗口(对应响应头 7d_oi,claim 名为 seven_day_overage_included, // 见 anthropic-ratelimit-unified-representative-claim 头)。上游 usage API - // 若不下发该字段,GetUsage 会用被动采样数据回填。 + // 若不下发该字段,先读取 limits[],仍缺失时 GetUsage 用被动采样回填。 SevenDayOverageIncluded ClaudeUsageWindow `json:"seven_day_overage_included"` + Limits []struct { + Kind string `json:"kind"` + Group string `json:"group"` + Percent *float64 `json:"percent"` + ResetsAt string `json:"resets_at"` + Scope struct { + Model struct { + DisplayName string `json:"display_name"` + } `json:"model"` + Surface json.RawMessage `json:"surface"` + } `json:"scope"` + } `json:"limits"` } // ClaudeUsageFetchOptions 包含获取 Claude 用量数据所需的所有选项 @@ -483,8 +495,9 @@ func (s *AccountUsageService) getUsageForAccount(ctx context.Context, account *A // 4. 添加窗口统计(有独立缓存,1 分钟) s.addWindowStats(ctx, account, usage) - // 5. 将主动查询结果同步到被动缓存,下次 passive 加载即为最新值 - s.syncActiveToPassive(ctx, account.ID, usage) + // 5. 将主动查询结果同步到被动缓存,下次 passive 加载即为最新值; + // 其中还会在上游明确给出已回落的 7d_oi 用量时撤销窗口耗尽写入的模型级限流。 + s.syncActiveToPassive(ctx, account, usage) // 6. 上游 usage API 目前不一定下发 Fable 7d 窗口;缺失时回填被动采样 // (7d_oi 响应头)的数据,避免主动查询后 7d F 进度条丢失。 @@ -715,7 +728,15 @@ func buildPassiveUsageWindow(extra map[string]any, utilKey, resetKey string) *Us // syncActiveToPassive 将主动查询的最新数据回写到 Extra 被动缓存, // 这样下次被动加载时能看到最新值。 -func (s *AccountUsageService) syncActiveToPassive(ctx context.Context, accountID int64, usage *UsageInfo) { +// +// 主动查询是“重置卡生效后额度已恢复”最直接的观测点:这里在拿到 API 明确回报的 +// 7d_oi 用量后,顺手撤销窗口耗尽写入的模型级限流。回填被动采样发生在调用方, +// 因此本函数的 usage.SevenDayFable 一定是上游返回值,不会把旧采样当成恢复依据。 +func (s *AccountUsageService) syncActiveToPassive(ctx context.Context, account *Account, usage *UsageInfo) { + if account == nil { + return + } + accountID := account.ID extraUpdates := make(map[string]any, 4) if usage.FiveHour != nil { @@ -748,6 +769,10 @@ func (s *AccountUsageService) syncActiveToPassive(ctx context.Context, accountID slog.Warn("sync_active_to_passive_session_window_end_failed", "account_id", accountID, "error", err) } } + + if usage.SevenDayFable != nil { + recoverAnthropicFableWindowLimit(ctx, s.accountRepo, account, usage.SevenDayFable.Utilization/100) + } } func (s *AccountUsageService) getOpenAIUsage(ctx context.Context, account *Account, force bool) (*UsageInfo, error) { @@ -1773,7 +1798,26 @@ func (s *AccountUsageService) buildUsageInfo(resp *ClaudeUsageResponse, updatedA } // 7天Fable窗口(响应头 7d_oi 对应的窗口) - if fable := resp.SevenDayOverageIncluded; fable.ResetsAt != "" { + fable := resp.SevenDayOverageIncluded + if fable.ResetsAt == "" { + // 新版 usage 将模型周窗口放在 limits[]。仅投影无 surface 限定的 + // Fable 周额度;percent 已是百分比,显式 0 也必须覆盖旧被动采样。 + for _, limit := range resp.Limits { + if limit.Kind != "weekly_scoped" || limit.Group != "weekly" || + limit.Scope.Model.DisplayName != "Fable" || limit.Percent == nil || *limit.Percent < 0 { + continue + } + if surface := bytes.TrimSpace(limit.Scope.Surface); len(surface) > 0 && !bytes.Equal(surface, []byte("null")) { + continue + } + if _, err := parseTime(limit.ResetsAt); err != nil { + continue + } + fable = ClaudeUsageWindow{Utilization: *limit.Percent, ResetsAt: limit.ResetsAt} + break + } + } + if fable.ResetsAt != "" { if fableReset, err := parseTime(fable.ResetsAt); err == nil { info.SevenDayFable = &UsageProgress{ Utilization: fable.Utilization, diff --git a/backend/internal/service/account_usage_service_fable_test.go b/backend/internal/service/account_usage_service_fable_test.go index 60f2e9c79f..71b8a003a2 100644 --- a/backend/internal/service/account_usage_service_fable_test.go +++ b/backend/internal/service/account_usage_service_fable_test.go @@ -2,6 +2,8 @@ package service import ( "encoding/json" + "fmt" + "strings" "testing" "time" @@ -56,6 +58,61 @@ func TestBuildUsageInfo_SevenDayFable(t *testing.T) { require.Nil(t, info.SevenDayFable) } +func TestBuildUsageInfo_ScopedFableLimits(t *testing.T) { + resetAt := time.Now().Add(72 * time.Hour).In(time.FixedZone("UTC+8", 8*60*60)).Truncate(time.Microsecond) + entry := fmt.Sprintf(`{"kind":"weekly_scoped","group":"weekly","percent":5.25,"resets_at":%q,"scope":{"model":{"display_name":"Fable"},"surface":null},"is_active":false}`, resetAt.Format(time.RFC3339Nano)) + for _, tc := range []struct { + name string + limits string + legacy string + wantWindow bool + wantUsage float64 + }{ + {name: "inactive scoped window", limits: entry, wantWindow: true, wantUsage: 5.25}, + {name: "active scoped window", limits: strings.Replace(entry, `"is_active":false`, `"is_active":true`, 1), wantWindow: true, wantUsage: 5.25}, + {name: "omitted surface", limits: strings.Replace(entry, `,"surface":null`, ``, 1), wantWindow: true, wantUsage: 5.25}, + {name: "zero percent", limits: strings.Replace(entry, `"percent":5.25`, `"percent":0`, 1), wantWindow: true}, + {name: "over quota percent", limits: strings.Replace(entry, `"percent":5.25`, `"percent":105.25`, 1), wantWindow: true, wantUsage: 105.25}, + {name: "legacy takes precedence", limits: entry, legacy: fmt.Sprintf(`{"utilization":56,"resets_at":%q}`, resetAt.Format(time.RFC3339Nano)), wantWindow: true, wantUsage: 56}, + {name: "null legacy", limits: entry, legacy: "null", wantWindow: true, wantUsage: 5.25}, + {name: "other model", limits: strings.Replace(entry, `"Fable"`, `"Sonnet"`, 1)}, + {name: "unscoped weekly", limits: strings.Replace(entry, `"weekly_scoped"`, `"weekly"`, 1)}, + {name: "other group", limits: strings.Replace(entry, `"group":"weekly"`, `"group":"daily"`, 1)}, + {name: "missing model", limits: strings.Replace(entry, `{"display_name":"Fable"}`, `null`, 1)}, + {name: "surface restricted", limits: strings.Replace(entry, `"surface":null`, `"surface":{"display_name":"Claude Code"}`, 1)}, + {name: "missing percent", limits: strings.Replace(entry, `"percent":5.25,`, ``, 1)}, + {name: "null percent", limits: strings.Replace(entry, `"percent":5.25`, `"percent":null`, 1)}, + {name: "negative percent", limits: strings.Replace(entry, `"percent":5.25`, `"percent":-1`, 1)}, + {name: "missing reset", limits: strings.Replace(entry, resetAt.Format(time.RFC3339Nano), "", 1)}, + {name: "invalid reset", limits: strings.Replace(entry, resetAt.Format(time.RFC3339Nano), "not-a-time", 1)}, + {name: "invalid entry before valid", limits: strings.Replace(entry, resetAt.Format(time.RFC3339Nano), "not-a-time", 1) + "," + entry, wantWindow: true, wantUsage: 5.25}, + {name: "unknown entry before valid", limits: `null,{"kind":"future_limit"},` + entry, wantWindow: true, wantUsage: 5.25}, + } { + t.Run(tc.name, func(t *testing.T) { + legacy := tc.legacy + if legacy == "" { + legacy = "null" + } + raw := fmt.Sprintf(`{"five_hour":{"utilization":12},"seven_day":{"utilization":34,"resets_at":%q},"seven_day_overage_included":%s,"limits":[%s]}`, resetAt.Format(time.RFC3339Nano), legacy, tc.limits) + var resp ClaudeUsageResponse + require.NoError(t, json.Unmarshal([]byte(raw), &resp)) + now := time.Now() + info := (&AccountUsageService{}).buildUsageInfo(&resp, &now) + require.Equal(t, 12.0, info.FiveHour.Utilization) + require.Equal(t, 34.0, info.SevenDay.Utilization) + if !tc.wantWindow { + require.Nil(t, info.SevenDayFable) + return + } + require.NotNil(t, info.SevenDayFable) + require.Equal(t, tc.wantUsage, info.SevenDayFable.Utilization) + require.NotNil(t, info.SevenDayFable.ResetsAt) + require.True(t, resetAt.Equal(*info.SevenDayFable.ResetsAt)) + require.Positive(t, info.SevenDayFable.RemainingSeconds) + }) + } +} + func TestBuildPassiveUsageWindow(t *testing.T) { future := time.Now().Add(48 * time.Hour).Unix() @@ -106,7 +163,7 @@ func TestSyncActiveToPassive_WritesFableExtras(t *testing.T) { }, } - svc.syncActiveToPassive(t.Context(), 1, usage) + svc.syncActiveToPassive(t.Context(), &Account{ID: 1}, usage) select { case updates := <-repo.updateExtraCh: diff --git a/backend/internal/service/account_usage_session_window_test.go b/backend/internal/service/account_usage_session_window_test.go index 779a5974fd..bca6a456d4 100644 --- a/backend/internal/service/account_usage_session_window_test.go +++ b/backend/internal/service/account_usage_session_window_test.go @@ -97,7 +97,7 @@ func TestSyncActiveToPassive_WritesFiveHourSessionWindowEnd(t *testing.T) { repo := &sessionWindowSyncRepo{} svc := &AccountUsageService{accountRepo: repo} resetsAt := time.Now().Add(3 * time.Hour).UTC().Truncate(time.Second) - svc.syncActiveToPassive(context.Background(), 42, &UsageInfo{ + svc.syncActiveToPassive(context.Background(), &Account{ID: 42}, &UsageInfo{ FiveHour: &UsageProgress{ Utilization: 53, ResetsAt: &resetsAt, @@ -123,7 +123,7 @@ func TestSyncActiveToPassive_SkipsSessionWindowEndWhenResetMissing(t *testing.T) repo := &sessionWindowSyncRepo{} svc := &AccountUsageService{accountRepo: repo} - svc.syncActiveToPassive(context.Background(), 99, &UsageInfo{ + svc.syncActiveToPassive(context.Background(), &Account{ID: 99}, &UsageInfo{ FiveHour: &UsageProgress{Utilization: 10}, }) diff --git a/backend/internal/service/admin_service_clear_error_test.go b/backend/internal/service/admin_service_clear_error_test.go index 41418c4f9a..d4ae092e29 100644 --- a/backend/internal/service/admin_service_clear_error_test.go +++ b/backend/internal/service/admin_service_clear_error_test.go @@ -48,6 +48,10 @@ func (r *accountRepoStubForClearAccountError) ClearModelRateLimits(ctx context.C return nil } +func (r *accountRepoStubForClearAccountError) ClearModelRateLimit(ctx context.Context, id int64, scope string) error { + return nil +} + func (r *accountRepoStubForClearAccountError) ClearTempUnschedulable(ctx context.Context, id int64) error { r.clearTempUnschedCalls++ r.account.TempUnschedulableUntil = nil diff --git a/backend/internal/service/antigravity_compat_committed_no_content.go b/backend/internal/service/antigravity_compat_committed_no_content.go new file mode 100644 index 0000000000..ed91c53db1 --- /dev/null +++ b/backend/internal/service/antigravity_compat_committed_no_content.go @@ -0,0 +1,50 @@ +package service + +import ( + "context" + "errors" + "log/slog" +) + +// antigravityCompatCommittedNoContentError reports a compat stream that +// committed HTTP 200 (pre-content keepalive) and then ended or timed out +// without any content. The response can no longer fail over, so the client +// retries; the handler releases the session's sticky account so that retry is +// scheduled afresh instead of returning to the account that just failed. +type antigravityCompatCommittedNoContentError struct { + msg string +} + +func newAntigravityCompatCommittedNoContentError(msg string) error { + return &antigravityCompatCommittedNoContentError{msg: msg} +} + +func (e *antigravityCompatCommittedNoContentError) Error() string { return e.msg } + +// IsAntigravityCompatCommittedNoContent reports whether err is a compat stream +// that committed its response and then produced no content. +func IsAntigravityCompatCommittedNoContent(err error) bool { + var target *antigravityCompatCommittedNoContentError + return errors.As(err, &target) +} + +// ReleaseStickySessionAfterCommittedNoContent removes the session's sticky +// binding when err is a committed no-content compat stream and the session is +// still bound to accountID. Only this session is affected: the account is not +// cooled or excluded for anyone else. Returns true when a binding was removed. +func (s *GatewayService) ReleaseStickySessionAfterCommittedNoContent(ctx context.Context, groupID *int64, sessionHash string, accountID int64, err error) bool { + if sessionHash == "" || accountID <= 0 || s.cache == nil || !IsAntigravityCompatCommittedNoContent(err) { + return false + } + gid := derefGroupID(groupID) + bound, getErr := s.cache.GetSessionAccountID(ctx, gid, sessionHash) + if getErr != nil || bound != accountID { + return false + } + if delErr := s.cache.DeleteSessionAccountID(ctx, gid, sessionHash); delErr != nil { + slog.Warn("antigravity_compat_sticky_release_failed", "group_id", gid, "account_id", accountID, "error", delErr) + return false + } + slog.Info("antigravity_compat_sticky_released", "group_id", gid, "account_id", accountID, "reason", err.Error()) + return true +} diff --git a/backend/internal/service/antigravity_compat_committed_no_content_test.go b/backend/internal/service/antigravity_compat_committed_no_content_test.go new file mode 100644 index 0000000000..c7887840a1 --- /dev/null +++ b/backend/internal/service/antigravity_compat_committed_no_content_test.go @@ -0,0 +1,98 @@ +package service + +import ( + "context" + "errors" + "io" + "net/http" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +// runCompatStreamToEnd drives the compat stream handler with an upstream that +// sends nothing and closes after closeAfter. +func runCompatStreamToEnd(t *testing.T, keepaliveInterval, maxWait, closeAfter time.Duration) error { + t.Helper() + svc := newAntigravityCompatService(config.GatewayConfig{ + MaxLineSize: defaultMaxLineSize, StreamDataIntervalTimeout: 30, StreamKeepaliveInterval: 0, + }, nil) + c, _ := newAntigravityCompatContext(http.MethodPost, "/v1/responses", nil) + reader, pipeWriter := io.Pipe() + defer func() { _ = reader.Close() }() + resp := &http.Response{StatusCode: http.StatusOK, Body: reader} + done := make(chan error, 1) + go func() { + _, err := svc.handleAntigravityCompatStreamWithKeepaliveInterval( + c, resp, time.Now(), "gemini-4-hydrogen-high", + newAntigravityResponsesStreamAdapter("gemini-4-hydrogen-high"), "test", keepaliveInterval, maxWait, + ) + done <- err + }() + time.Sleep(closeAfter) + _ = pipeWriter.Close() + select { + case err := <-done: + return err + case <-time.After(2 * time.Second): + t.Fatal("compat stream handler did not return") + return nil + } +} + +func TestAntigravityCompatEmptyStreamAfterKeepaliveIsCommittedNoContent(t *testing.T) { + err := runCompatStreamToEnd(t, 10*time.Millisecond, time.Second, 50*time.Millisecond) + require.Error(t, err) + require.True(t, IsAntigravityCompatCommittedNoContent(err), "got %v", err) +} + +func TestAntigravityCompatPreContentTimeoutAfterKeepaliveIsCommittedNoContent(t *testing.T) { + err := runCompatStreamToEnd(t, 10*time.Millisecond, 40*time.Millisecond, 200*time.Millisecond) + require.Error(t, err) + require.ErrorContains(t, err, "pre-content stream timeout") + require.True(t, IsAntigravityCompatCommittedNoContent(err), "got %v", err) +} + +func TestAntigravityCompatEmptyStreamBeforeKeepaliveStaysFailover(t *testing.T) { + err := runCompatStreamToEnd(t, time.Second, 2*time.Second, 10*time.Millisecond) + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "got %v", err) + require.False(t, IsAntigravityCompatCommittedNoContent(err)) +} + +func TestReleaseStickySessionAfterCommittedNoContent(t *testing.T) { + ctx := context.Background() + groupID := int64(10) + committed := &antigravityCompatCommittedNoContentError{msg: "empty Antigravity compatibility stream after keepalive"} + + t.Run("unbinds the session from the account that failed", func(t *testing.T) { + cache := &stubGatewayCache{sessionBindings: map[string]int64{"sess": 5}} + svc := &GatewayService{cache: cache} + require.True(t, svc.ReleaseStickySessionAfterCommittedNoContent(ctx, &groupID, "sess", 5, committed)) + _, bound := cache.sessionBindings["sess"] + require.False(t, bound) + }) + + t.Run("keeps a binding that already moved to another account", func(t *testing.T) { + cache := &stubGatewayCache{sessionBindings: map[string]int64{"sess": 6}} + svc := &GatewayService{cache: cache} + require.False(t, svc.ReleaseStickySessionAfterCommittedNoContent(ctx, &groupID, "sess", 5, committed)) + require.Equal(t, int64(6), cache.sessionBindings["sess"]) + }) + + t.Run("ignores other errors", func(t *testing.T) { + cache := &stubGatewayCache{sessionBindings: map[string]int64{"sess": 5}} + svc := &GatewayService{cache: cache} + require.False(t, svc.ReleaseStickySessionAfterCommittedNoContent(ctx, &groupID, "sess", 5, errors.New("stream data interval timeout"))) + require.Equal(t, int64(5), cache.sessionBindings["sess"]) + }) + + t.Run("no session hash is a no-op", func(t *testing.T) { + cache := &stubGatewayCache{sessionBindings: map[string]int64{"sess": 5}} + svc := &GatewayService{cache: cache} + require.False(t, svc.ReleaseStickySessionAfterCommittedNoContent(ctx, &groupID, "", 5, committed)) + require.Equal(t, int64(5), cache.sessionBindings["sess"]) + }) +} diff --git a/backend/internal/service/antigravity_gateway_compat.go b/backend/internal/service/antigravity_gateway_compat.go index f1ebe19666..e27a11ce6d 100644 --- a/backend/internal/service/antigravity_gateway_compat.go +++ b/backend/internal/service/antigravity_gateway_compat.go @@ -259,7 +259,7 @@ func (s *AntigravityGatewayService) prepareAntigravityCompatCall( mappedModel := s.getMappedModelForThinkingLevel( account, request.originalModel, - geminiThinkingLevelFromClaudeThinking(claudeRequest.Thinking), + geminiThinkingLevelFromClaudeBody(request.claudeBody, claudeRequest.Thinking), ) if mappedModel == "" { MarkOpsClientBusinessLimited(c, OpsClientBusinessLimitedReasonLocalFeatureGate) @@ -322,6 +322,7 @@ func (s *AntigravityGatewayService) buildAntigravityCompatGeminiBody( return nil, err } body = ensureGeminiFunctionCallThoughtSignatures(body) + body = applyGeminiCompatThinkingConfig(body, claudeBody, mappedModel, claudeRequest != nil && claudeRequest.Stream) body, err = injectIdentityPatchToGeminiRequest(body) if err != nil { return nil, err diff --git a/backend/internal/service/antigravity_gateway_compat_stream.go b/backend/internal/service/antigravity_gateway_compat_stream.go index 4dea4c453c..2a0fbaf53a 100644 --- a/backend/internal/service/antigravity_gateway_compat_stream.go +++ b/backend/internal/service/antigravity_gateway_compat_stream.go @@ -154,9 +154,9 @@ func (s *antigravityCompatStreamSession) hasMeaningfulData() bool { } func (s *antigravityCompatStreamSession) writePreContentKeepalive(now time.Time) { - // Intentional tradeoff: this commits HTTP 200 after 15s, so later upstream + // Intentional tradeoff: this commits HTTP 200 after the keepalive interval, so later upstream // failures cannot fail over; report them as SSE errors to the client instead. - if s.hasMeaningfulData() || s.writer.Disconnected() || now.Sub(s.startTime) < s.preContentKeepaliveInterval { + if s.hasMeaningfulData() || s.writer.Disconnected() || (!s.preContentKeepaliveSent && now.Sub(s.startTime) < s.preContentKeepaliveInterval) { return } if s.writer.Write([]byte(": ping\n\n")) { @@ -171,7 +171,7 @@ func (s *antigravityCompatStreamSession) finish() (*antigravityStreamResult, err if !s.hasMeaningfulData() && !s.writer.Disconnected() { if s.preContentKeepaliveSent { s.adapter.WriteError(s.writer, "empty_stream") - return s.result(false), errors.New("empty Antigravity compatibility stream after keepalive") + return s.result(false), newAntigravityCompatCommittedNoContentError("empty Antigravity compatibility stream after keepalive") } return nil, antigravityCompatEmptyStreamError() } @@ -282,12 +282,52 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStream( adapter antigravityCompatStreamAdapter, prefix string, ) (*antigravityStreamResult, error) { - return s.handleAntigravityCompatStreamWithKeepaliveInterval(c, resp, startTime, originalModel, adapter, prefix, antigravityCompatPreContentKeepaliveInterval, antigravityCompatPreContentMaxWait) + return s.handleAntigravityCompatStreamWithKeepaliveInterval( + c, + resp, + startTime, + originalModel, + adapter, + prefix, + antigravityCompatPreContentKeepaliveInterval, + s.antigravityCompatPreContentMaxWait(), + ) +} + +// handleAntigravityCompatStreamAfterHeaders starts reading an upstream HTTP 200 SSE +// stream while keeping startTime for TTFT measurement and anchoring the pre-content +// deadline at response-header arrival rather than request start. +func (s *AntigravityGatewayService) handleAntigravityCompatStreamAfterHeaders( + c *gin.Context, + resp *http.Response, + startTime time.Time, + originalModel string, + adapter antigravityCompatStreamAdapter, + prefix string, +) (*antigravityStreamResult, error) { + return s.handleAntigravityCompatStreamWithTiming( + c, + resp, + startTime, + time.Now(), + originalModel, + adapter, + prefix, + s.antigravityCompatPreContentKeepaliveInterval(), + s.antigravityCompatPreContentMaxWait(), + ) } func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveInterval( c *gin.Context, resp *http.Response, startTime time.Time, originalModel string, adapter antigravityCompatStreamAdapter, prefix string, interval, maxPreContentWait time.Duration, +) (*antigravityStreamResult, error) { + return s.handleAntigravityCompatStreamWithTiming(c, resp, startTime, startTime, originalModel, adapter, prefix, interval, maxPreContentWait) +} + +func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithTiming( + c *gin.Context, resp *http.Response, startTime, streamStart time.Time, originalModel string, + adapter antigravityCompatStreamAdapter, prefix string, interval, maxPreContentWait time.Duration, ) (*antigravityStreamResult, error) { flusher, ok := c.Writer.(http.Flusher) if !ok { @@ -303,6 +343,7 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveIn c.Status(http.StatusOK) } session := newAntigravityCompatStreamSession(originalModel, startTime, adapter, writer) + session.preContentKeepaliveSent = IsResponseCommitted(c) && c.Writer.Written() session.preContentKeepaliveInterval = interval events, stopScanner, maxLineSize, queueBudget := s.startAntigravityCompatScanner(resp.Body) defer stopScanner() @@ -316,13 +357,17 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveIn if keepaliveTicker != nil { defer keepaliveTicker.Stop() } - preContentDelay := time.Until(startTime.Add(interval)) + keepaliveStart := startTime + if session.preContentKeepaliveSent { + keepaliveStart = streamStart + } + preContentDelay := time.Until(keepaliveStart.Add(interval)) if preContentDelay < 0 { preContentDelay = 0 } preContentTimer := time.NewTimer(preContentDelay) defer preContentTimer.Stop() - preContentDeadline := startTime.Add(maxPreContentWait) + preContentDeadline := streamStart.Add(maxPreContentWait) deadlineDelay := time.Until(preContentDeadline) if deadlineDelay < 0 { deadlineDelay = 0 @@ -332,7 +377,7 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveIn preContentTimeout := func() (*antigravityStreamResult, error) { if session.preContentKeepaliveSent { writeAntigravityCompatStreamError(c, adapter, writer, "stream_timeout") - return session.collectResult(false), fmt.Errorf("pre-content stream timeout") + return session.collectResult(false), newAntigravityCompatCommittedNoContentError("pre-content stream timeout") } return nil, antigravityCompatEmptyStreamError() } @@ -393,7 +438,7 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveIn func handleAntigravityCompatEmptyStream(c *gin.Context, session *antigravityCompatStreamSession) (*antigravityStreamResult, error) { if session.preContentKeepaliveSent { writeAntigravityCompatStreamError(c, session.adapter, session.writer, "empty_stream") - return session.collectResult(false), errors.New("empty Antigravity compatibility stream after keepalive") + return session.collectResult(false), newAntigravityCompatCommittedNoContentError("empty Antigravity compatibility stream after keepalive") } return nil, antigravityCompatEmptyStreamError() } @@ -447,6 +492,24 @@ func (s *AntigravityGatewayService) antigravityCompatStreamTimeout() time.Durati return time.Duration(s.settingService.cfg.Gateway.StreamDataIntervalTimeout) * time.Second } +func (s *AntigravityGatewayService) antigravityCompatPreContentKeepaliveInterval() time.Duration { + interval := antigravityCompatPreContentKeepaliveInterval + if s.settingService != nil && s.settingService.cfg != nil { + configured := time.Duration(s.settingService.cfg.Gateway.StreamKeepaliveInterval) * time.Second + if configured > 0 && configured < interval { + interval = configured + } + } + return interval +} + +func (s *AntigravityGatewayService) antigravityCompatPreContentMaxWait() time.Duration { + if timeout := s.antigravityCompatStreamTimeout(); timeout > antigravityCompatPreContentMaxWait { + return timeout + } + return antigravityCompatPreContentMaxWait +} + func (s *AntigravityGatewayService) newAntigravityCompatKeepaliveTicker() (*time.Ticker, <-chan time.Time) { if s.settingService == nil || s.settingService.cfg == nil { return nil, nil @@ -532,7 +595,7 @@ func (s *AntigravityGatewayService) handleChatCompletionsStreamingFromAntigravit originalModel string, includeUsage bool, ) (*antigravityStreamResult, error) { - return s.handleAntigravityCompatStream( + return s.handleAntigravityCompatStreamAfterHeaders( c, resp, startTime, @@ -548,7 +611,7 @@ func (s *AntigravityGatewayService) handleResponsesStreamingFromAntigravity( startTime time.Time, originalModel string, ) (*antigravityStreamResult, error) { - return s.handleAntigravityCompatStream( + return s.handleAntigravityCompatStreamAfterHeaders( c, resp, startTime, diff --git a/backend/internal/service/antigravity_gateway_compat_test.go b/backend/internal/service/antigravity_gateway_compat_test.go index bccbe2472f..f830286d94 100644 --- a/backend/internal/service/antigravity_gateway_compat_test.go +++ b/backend/internal/service/antigravity_gateway_compat_test.go @@ -132,6 +132,74 @@ func antigravityCompatSuccessResponse() *http.Response { } } +func TestAntigravityCompatToolSchemaItemsMatchSelectedType(t *testing.T) { + gin.SetMode(gin.TestMode) + const schema = `{"type":"object","properties":{ + "uri":{"type":["string","array"],"items":{"type":"string"}}, + "paths":{"type":["array","string"],"items":{"type":"integer"}}, + "nested":{"type":"array","items":{"type":"object","properties":{ + "uri":{"type":["string","array"],"items":{"type":"string"}} + }}}, + "fallback":{"type":"array","items":17}, + "inferred":{"items":{"type":"integer"}}, + "items":{"type":"string"} + }}` + const expected = `{"type":"object","properties":{ + "uri":{"type":"string"}, + "paths":{"type":"array","items":{"type":"integer"}}, + "nested":{"type":"array","items":{"type":"object","properties":{ + "uri":{"type":"string"} + }}}, + "fallback":{"type":"array","items":{"type":"string"}}, + "inferred":{"type":"array","items":{"type":"integer"}}, + "items":{"type":"string"} + }}` + for _, protocol := range []string{"chat", "responses", "messages"} { + t.Run(protocol, func(t *testing.T) { + var parameters map[string]any + require.NoError(t, json.Unmarshal([]byte(schema), ¶meters)) + tool := map[string]any{"name": "inspect", "parameters": parameters} + request := map[string]any{"model": "gemini-3.1-pro-high", "max_tokens": 128} + switch protocol { + case "chat": + request["messages"] = []map[string]any{{"role": "user", "content": "inspect URI"}} + request["tools"] = []any{map[string]any{"type": "function", "function": tool}} + case "responses": + request["input"] = "inspect URI" + tool["type"] = "function" + request["tools"] = []any{tool} + case "messages": + request["messages"] = []map[string]any{{"role": "user", "content": "inspect URI"}} + request["tools"] = []any{map[string]any{"name": "inspect", "input_schema": parameters}} + } + body, err := json.Marshal(request) + require.NoError(t, err) + var forwarded []byte + upstream := &queuedHTTPUpstreamStub{ + responses: []*http.Response{antigravityCompatSuccessResponse()}, + onCall: func(req *http.Request, _ *queuedHTTPUpstreamStub) { + forwarded, err = io.ReadAll(req.Body) + require.NoError(t, err) + }, + } + svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream) + account := newAntigravityCompatAccount(AccountTypeOAuth) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/"+protocol, body) + switch protocol { + case "chat": + _, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, nil) + case "responses": + _, err = svc.ForwardAsResponses(context.Background(), c, account, body, nil) + case "messages": + _, err = svc.Forward(context.Background(), c, account, body, false) + } + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.JSONEq(t, expected, gjson.GetBytes(forwarded, "request.tools.0.functionDeclarations.0.parameters").Raw) + }) + } +} + func TestAntigravitySystemIdentityAcrossProtocols(t *testing.T) { gin.SetMode(gin.TestMode) const task = "\nKeep GPT-5.6, gpt-6 and Claude model ids unchanged." @@ -1256,3 +1324,209 @@ func TestAntigravityCompatEmptyAfterKeepaliveReportsStreamError(t *testing.T) { }) } } + +func TestAntigravityCompatGeminiThinkingConfig(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("streaming responses tier suffix enables includeThoughts without thinkingLevel", func(t *testing.T) { + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{antigravityCompatSuccessResponse()}} + svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream) + account := newAntigravityCompatAccount(AccountTypeOAuth) + mapping, ok := account.Credentials["model_mapping"].(map[string]any) + require.True(t, ok) + mapping["gemini-4-argon-high"] = "gemini-4-argon-high" + + body := []byte(`{"model":"gemini-4-argon-high","stream":true,"input":"inspect repository"}`) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/responses", body) + + _, err := svc.ForwardAsResponses(context.Background(), c, account, body, nil) + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.requestBodies, 1) + + cfg := gjson.GetBytes(upstream.requestBodies[0], "request.generationConfig.thinkingConfig") + require.True(t, cfg.Get("includeThoughts").Bool(), "thinkingConfig=%s", cfg.Raw) + require.False(t, cfg.Get("thinkingLevel").Exists(), "tier-suffixed model must not set thinkingLevel: %s", cfg.Raw) + require.False(t, cfg.Get("thinkingBudget").Exists(), "tier-suffixed model must not set thinkingBudget: %s", cfg.Raw) + }) + + t.Run("streaming chat completions tier suffix enables includeThoughts without thinkingLevel", func(t *testing.T) { + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{antigravityCompatSuccessResponse()}} + svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream) + account := newAntigravityCompatAccount(AccountTypeOAuth) + mapping, ok := account.Credentials["model_mapping"].(map[string]any) + require.True(t, ok) + mapping["gemini-4-argon-high"] = "gemini-4-argon-high" + + body := []byte(`{"model":"gemini-4-argon-high","stream":true,"messages":[{"role":"user","content":"inspect repository"}]}`) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/chat/completions", body) + + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, nil) + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.requestBodies, 1) + + cfg := gjson.GetBytes(upstream.requestBodies[0], "request.generationConfig.thinkingConfig") + require.True(t, cfg.Get("includeThoughts").Bool(), "thinkingConfig=%s", cfg.Raw) + require.False(t, cfg.Get("thinkingLevel").Exists(), "thinkingConfig=%s", cfg.Raw) + }) + + t.Run("streaming responses bare model with low effort selects low variant and enables includeThoughts", func(t *testing.T) { + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{antigravityCompatSuccessResponse()}} + svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream) + account := newAntigravityCompatAccount(AccountTypeOAuth) + mapping, ok := account.Credentials["model_mapping"].(map[string]any) + require.True(t, ok) + mapping["gemini-4-argon-low"] = "gemini-4-argon-low" + mapping["gemini-4-argon-high"] = "gemini-4-argon-high" + + body := []byte(`{"model":"gemini-4-argon","stream":true,"reasoning":{"effort":"low"},"input":"quick check"}`) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/responses", body) + + result, err := svc.ForwardAsResponses(context.Background(), c, account, body, nil) + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.requestBodies, 1) + require.Equal(t, "gemini-4-argon-low", gjson.GetBytes(upstream.requestBodies[0], "model").String()) + require.Equal(t, "gemini-4-argon-low", result.UpstreamModel) + + cfg := gjson.GetBytes(upstream.requestBodies[0], "request.generationConfig.thinkingConfig") + require.True(t, cfg.Get("includeThoughts").Bool(), "thinkingConfig=%s", cfg.Raw) + require.False(t, cfg.Get("thinkingLevel").Exists(), "thinkingConfig=%s", cfg.Raw) + }) + + t.Run("streaming responses explicit bare model sets thinkingLevel and includeThoughts", func(t *testing.T) { + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{antigravityCompatSuccessResponse()}} + svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream) + account := newAntigravityCompatAccount(AccountTypeOAuth) + mapping, ok := account.Credentials["model_mapping"].(map[string]any) + require.True(t, ok) + mapping["gemini-3.5-flash"] = "gemini-3.5-flash" + + body := []byte(`{"model":"gemini-3.5-flash","stream":true,"reasoning":{"effort":"medium"},"input":"check"}`) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/responses", body) + + _, err := svc.ForwardAsResponses(context.Background(), c, account, body, nil) + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.requestBodies, 1) + + cfg := gjson.GetBytes(upstream.requestBodies[0], "request.generationConfig.thinkingConfig") + require.Equal(t, "medium", cfg.Get("thinkingLevel").String(), "thinkingConfig=%s", cfg.Raw) + require.True(t, cfg.Get("includeThoughts").Bool(), "thinkingConfig=%s", cfg.Raw) + }) + + t.Run("non-streaming responses do not force includeThoughts", func(t *testing.T) { + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{antigravityCompatSuccessResponse()}} + svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream) + account := newAntigravityCompatAccount(AccountTypeOAuth) + mapping, ok := account.Credentials["model_mapping"].(map[string]any) + require.True(t, ok) + mapping["gemini-4-argon-high"] = "gemini-4-argon-high" + + nonStreamBody := []byte(`{"model":"gemini-4-argon-high","stream":false,"input":"inspect"}`) + c, rec := newAntigravityCompatContext(http.MethodPost, "/v1/responses", nonStreamBody) + _, err := svc.ForwardAsResponses(context.Background(), c, account, nonStreamBody, nil) + require.NoError(t, err) + require.Equal(t, http.StatusOK, rec.Code) + require.Len(t, upstream.requestBodies, 1) + require.False(t, gjson.GetBytes(upstream.requestBodies[0], "request.generationConfig.thinkingConfig.includeThoughts").Bool()) + }) +} + +func TestAntigravityCompatHeaderWaitExceedingPreContentLimitDoesNotAbortStream(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, protocol := range []antigravityCompatProtocol{antigravityCompatResponses, antigravityCompatChatCompletions} { + name := "responses" + path := "/v1/responses" + wantDone := "event: response.completed" + if protocol == antigravityCompatChatCompletions { + name = "chat_completions" + path = "/v1/chat/completions" + wantDone = "data: [DONE]" + } + for _, committedKeepalive := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/keepalive=%t", name, committedKeepalive), func(t *testing.T) { + svc := newAntigravityCompatService(config.GatewayConfig{ + MaxLineSize: defaultMaxLineSize, + StreamDataIntervalTimeout: 180, + StreamKeepaliveInterval: 10, + }, nil) + c, recorder := newAntigravityCompatContext(http.MethodPost, path, nil) + if committedKeepalive { + c.Header("Content-Type", "text/event-stream") + c.Status(http.StatusOK) + MarkResponseCommitted(c) + _, err := c.Writer.Write([]byte(": ping\n\n")) + require.NoError(t, err) + c.Writer.Flush() + } + + requestStart := time.Now().Add(-3 * time.Minute) + call := &antigravityCompatUpstreamCall{ + request: antigravityCompatRequest{ + protocol: protocol, + originalModel: "gemini-4-argon-high", + clientStream: true, + startTime: requestStart, + }, + billingModel: "gemini-4-argon-high", + prefix: "test-long-header-wait", + } + + result, err := svc.consumeAntigravityCompatResponse( + c.Request.Context(), + c, + newAntigravityCompatAccount(AccountTypeOAuth), + call, + antigravityCompatSuccessResponse(), + ) + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, result.FirstTokenMs) + require.GreaterOrEqual(t, *result.FirstTokenMs, int((3*time.Minute - time.Second).Milliseconds())) + require.Contains(t, recorder.Body.String(), wantDone) + require.NotContains(t, recorder.Body.String(), "stream_timeout") + }) + } + } +} + +func TestAntigravityCompatInterleavedThoughtChunksResetIdleTimeout(t *testing.T) { + gin.SetMode(gin.TestMode) + svc := newAntigravityCompatService(config.GatewayConfig{ + MaxLineSize: defaultMaxLineSize, + StreamDataIntervalTimeout: 1, + }, nil) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/responses", nil) + reader, writer := io.Pipe() + defer func() { _ = reader.Close() }() + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: reader, + } + + done := make(chan error, 1) + go func() { + _, err := svc.handleResponsesStreamingFromAntigravity(c, resp, time.Now(), "gemini-4-argon-high") + done <- err + }() + + _, err := io.WriteString(writer, `data: {"response":{"responseId":"resp_44276","candidates":[{"content":{"role":"model","parts":[{"text":"Checking files..."}]}}]}}`+"\n\n") + require.NoError(t, err) + for i := 0; i < 4; i++ { + time.Sleep(350 * time.Millisecond) + _, err = io.WriteString(writer, fmt.Sprintf(`data: {"response":{"responseId":"resp_44276","candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":"step %d "}]}}]}}`+"\n\n", i+1)) + require.NoError(t, err) + } + _, err = io.WriteString(writer, `data: {"response":{"responseId":"resp_44276","candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"sig_done","functionCall":{"name":"exec_command","args":{"cmd":"ls"},"id":"call_1"}}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":20,"thoughtsTokenCount":50}}}`+"\n\n") + require.NoError(t, err) + require.NoError(t, writer.Close()) + + require.NoError(t, <-done) + out := recorder.Body.String() + require.Contains(t, out, "event: response.reasoning_summary_text.delta") + require.Contains(t, out, "event: response.completed") + require.NotContains(t, out, "stream_timeout") +} diff --git a/backend/internal/service/antigravity_gemini_thinking_variant.go b/backend/internal/service/antigravity_gemini_thinking_variant.go index e0ebc5c470..63201ba1e2 100644 --- a/backend/internal/service/antigravity_gemini_thinking_variant.go +++ b/backend/internal/service/antigravity_gemini_thinking_variant.go @@ -85,6 +85,22 @@ func geminiThinkingLevelFromBody(body []byte) string { } } +// geminiThinkingLevelFromClaudeBody 结合兼容层转换后的 output_config.effort 与 thinking 配置推导档位。 +// OpenAI Responses / Chat Completions 在 effort=low/minimal/none 时可能只写 output_config.effort 而不写 thinking, +// 优先读取显式 effort 可避免裸 Gemini 模型被默认归入 high 变体。 +func geminiThinkingLevelFromClaudeBody(claudeBody []byte, thinking *antigravity.ThinkingConfig) string { + switch parseClaudeThinkingIntent(claudeBody).tier { + case "minimal", "low": + return "low" + case "medium": + return "medium" + case "high": + return "high" + default: + return geminiThinkingLevelFromClaudeThinking(thinking) + } +} + // geminiThinkingLevelFromClaudeThinking 用 Claude Messages 协议的 thinking 配置推导档位, // 阈值与 geminiThinkingLevelFromBody 保持一致,使同一请求无论走 Gemini 原生还是 // Chat Completions / Messages 兼容层都落到同一个上游变体。 diff --git a/backend/internal/service/auth_service.go b/backend/internal/service/auth_service.go index 5dbe3bca29..90ba5b3455 100644 --- a/backend/internal/service/auth_service.go +++ b/backend/internal/service/auth_service.go @@ -1057,6 +1057,9 @@ func (s *AuthService) shouldApplyEmailFirstBindDefaults( identity *dbent.AuthIdentity, created bool, ) bool { + if identity == nil { + return false + } source := emailAuthIdentitySource(identity.Metadata) if source == "auth_service_login_backfill" { return false @@ -1064,7 +1067,7 @@ func (s *AuthService) shouldApplyEmailFirstBindDefaults( if created { return true } - if s == nil || s.entClient == nil || userID <= 0 || identity == nil || identity.UserID != userID { + if s == nil || s.entClient == nil || userID <= 0 || identity.UserID != userID { return false } if source != "auth_service_dual_write" { diff --git a/backend/internal/service/auth_service_identity_sync_test.go b/backend/internal/service/auth_service_identity_sync_test.go index 59ed8e52b8..ba596718b9 100644 --- a/backend/internal/service/auth_service_identity_sync_test.go +++ b/backend/internal/service/auth_service_identity_sync_test.go @@ -259,6 +259,53 @@ func TestAuthServiceRecordSuccessfulLoginBackfillsEmailIdentity(t *testing.T) { require.Equal(t, user.ID, identity.UserID) } +func TestAuthServiceRecordSuccessfulLogin_EmailIdentityOwnedByAnotherUser(t *testing.T) { + assigner := &authIdentityDefaultSubAssignerStub{} + svc, _, client := newAuthServiceWithEnt(t, map[string]string{ + service.SettingKeyRegistrationEnabled: "true", + service.SettingKeyAuthSourceDefaultEmailBalance: "8.5", + service.SettingKeyAuthSourceDefaultEmailGrantOnFirstBind: "true", + }, assigner) + ctx := context.Background() + + // users.email 唯一索引区分大小写,email 身份按小写邮箱唯一:只差大小写的两个账号共用一条身份。 + owner, err := client.User.Create(). + SetEmail("Shared@Example.com"). + SetPasswordHash("hash"). + SetBalance(1). + SetConcurrency(1). + SetRole(service.RoleUser). + SetStatus(service.StatusActive). + Save(ctx) + require.NoError(t, err) + user, err := client.User.Create(). + SetEmail("shared@example.com"). + SetPasswordHash("hash"). + SetBalance(1). + SetConcurrency(1). + SetRole(service.RoleUser). + SetStatus(service.StatusActive). + Save(ctx) + require.NoError(t, err) + require.NoError(t, client.AuthIdentity.Create(). + SetUserID(owner.ID). + SetProviderType("email"). + SetProviderKey("email"). + SetProviderSubject("shared@example.com"). + SetVerifiedAt(time.Now().UTC()). + SetMetadata(map[string]any{"source": "auth_service_dual_write"}). + Exec(ctx)) + + require.NotPanics(t, func() { svc.RecordSuccessfulLogin(ctx, user.ID) }) + + storedUser, err := client.User.Get(ctx, user.ID) + require.NoError(t, err) + require.NotNil(t, storedUser.LastLoginAt) + require.Equal(t, 1.0, storedUser.Balance) + require.Empty(t, assigner.calls) + require.Equal(t, 0, countProviderGrantRecords(t, client, user.ID, "email", "first_bind")) +} + func TestAuthServiceLogin_DoesNotApplyEmailFirstBindDefaultsWhenBackfillingLegacyEmailIdentity(t *testing.T) { assigner := &authIdentityDefaultSubAssignerStub{} svc, _, client := newAuthServiceWithEnt(t, map[string]string{ diff --git a/backend/internal/service/billing_cache_service.go b/backend/internal/service/billing_cache_service.go index 39435f90bd..f899130de9 100644 --- a/backend/internal/service/billing_cache_service.go +++ b/backend/internal/service/billing_cache_service.go @@ -940,7 +940,7 @@ func (s *BillingCacheService) checkRPM(ctx context.Context, user *User, group *G if group != nil { // 解析 override:优先从 auth cache snapshot;snapshot 未确认该分组时回退 DB。 var override *int - if user.UserGroupRPMOverride != nil || user.UserGroupRPMOverrideGroupID == group.ID { + if user.UserGroupRPMOverrideGroupID == group.ID { override = user.UserGroupRPMOverride } else if s.userGroupRateRepo != nil { dbOverride, err := s.userGroupRateRepo.GetRPMOverrideByUserAndGroup(ctx, user.ID, group.ID) diff --git a/backend/internal/service/billing_inflight_reservation_test.go b/backend/internal/service/billing_inflight_reservation_test.go index fa9281823b..5018652610 100644 --- a/backend/internal/service/billing_inflight_reservation_test.go +++ b/backend/internal/service/billing_inflight_reservation_test.go @@ -359,8 +359,8 @@ func TestInflightEstimate_AccountLevelMappingFallsBackLikeBilling(t *testing.T) groupID := int64(31) svc := newInflightEstimateGateway(t, nil) snap := &inflightSnapshotCacheStub{byBucket: map[string][]Account{inflightBucketKey(groupID, PlatformAnthropic): { - {ID: 1, Platform: PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"acct-alias-31": "claude-sonnet-4-5"}}}, - {ID: 2, Platform: PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"acct-alias-31": "claude-opus-4-1"}}}, + {ID: 1, Platform: PlatformAnthropic, Status: StatusActive, Schedulable: true, Credentials: map[string]any{"model_mapping": map[string]any{"acct-alias-31": "claude-sonnet-4-5"}}}, + {ID: 2, Platform: PlatformAnthropic, Status: StatusActive, Schedulable: true, Credentials: map[string]any{"model_mapping": map[string]any{"acct-alias-31": "claude-opus-4-1"}}}, }}} attachInflightSnapshot(svc, snap) apiKey := &APIKey{User: &User{ID: 1}, GroupID: &groupID, Group: &Group{ID: groupID, Platform: PlatformAnthropic, RateMultiplier: 1}} @@ -468,7 +468,7 @@ func TestInflightEstimate_AccountMappingNoDBAndBoundedMemory(t *testing.T) { func TestInflightEstimate_NoGroupKeyUsesUngroupedAccountMapping(t *testing.T) { svc := newInflightEstimateGateway(t, nil) snap := &inflightSnapshotCacheStub{byBucket: map[string][]Account{inflightBucketKey(0, PlatformAnthropic): { - {ID: 1, Platform: PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"acct-alias-nog": "claude-opus-4-1"}}}, + {ID: 1, Platform: PlatformAnthropic, Status: StatusActive, Schedulable: true, Credentials: map[string]any{"model_mapping": map[string]any{"acct-alias-nog": "claude-opus-4-1"}}}, }}} attachInflightSnapshot(svc, snap) apiKey := &APIKey{User: &User{ID: 1}} @@ -493,7 +493,7 @@ func TestInflightEstimate_AccountMappingNoNegativeCaching(t *testing.T) { _, priced := svc.EstimateInflightReservation(ctx, apiKey, req) require.False(t, priced) - snap.set(groupID, PlatformAnthropic, []Account{{ID: 9, Platform: PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"acct-*": "claude-sonnet-4-5"}}}}) + snap.set(groupID, PlatformAnthropic, []Account{{ID: 9, Platform: PlatformAnthropic, Status: StatusActive, Schedulable: true, Credentials: map[string]any{"model_mapping": map[string]any{"acct-*": "claude-sonnet-4-5"}}}}) est, priced := svc.EstimateInflightReservation(ctx, apiKey, req) require.True(t, priced, "new mapping (incl. wildcard) visible on next request") require.Greater(t, est, 0.0) diff --git a/backend/internal/service/billing_service.go b/backend/internal/service/billing_service.go index ca526bd8b6..37340fe652 100644 --- a/backend/internal/service/billing_service.go +++ b/backend/internal/service/billing_service.go @@ -98,15 +98,16 @@ type BillingCache interface { type ModelPricing struct { // UltrafastMultiplier is model-owned and independent of operator Fast pricing. UltrafastMultiplier float64 - InputPricePerToken float64 // 每token输入价格 (USD) - InputPricePerTokenPriority float64 // priority service tier 下每token输入价格 (USD) - ImageInputPricePerToken float64 // 图片输入 token 价格 (USD),用于多模态 embedding 等图文不同价场景;为 0 时回退到 InputPricePerToken - ImageCacheReadPricePerToken float64 // 图片缓存输入价格;无独立价格时沿用缓存读取价 - OutputPricePerToken float64 // 每token输出价格 (USD) - OutputPricePerTokenPriority float64 // priority service tier 下每token输出价格 (USD) - CacheCreationPricePerToken float64 // 缓存创建每token价格 (USD) - CacheCreationPricePerTokenPriority float64 // priority service tier 下缓存创建每token价格 (USD) - CacheCreationPriceExplicit bool // 是否由渠道/区间定价显式设定(为 true 时即使 == 0 也不回退) + InputPricePerToken float64 // 每token输入价格 (USD) + InputPricePerTokenPriority float64 // priority service tier 下每token输入价格 (USD) + ImageInputPricePerToken float64 // 图片输入 token 价格 (USD),用于多模态 embedding 等图文不同价场景;为 0 时回退到 InputPricePerToken + ImageCacheReadPricePerToken float64 // 图片缓存输入价格;无独立价格时沿用缓存读取价 + OutputPricePerToken float64 // 每token输出价格 (USD) + OutputPricePerTokenPriority float64 // priority service tier 下每token输出价格 (USD) + CacheCreationPricePerToken float64 // 缓存创建每token价格 (USD) + CacheCreationPricePerTokenPriority float64 // priority service tier 下缓存创建每token价格 (USD) + CacheCreationPriceExplicit bool // 是否由渠道/区间定价显式设定(为 true 时即使 == 0 也不回退) + priceOverrides tokenPriceOverrides CacheReadPricePerToken float64 // 缓存读取每token价格 (USD) CacheReadPricePerTokenPriority float64 // priority service tier 下缓存读取每token价格 (USD) FastMultiplier *float64 // 渠道显式 Fast/priority 倍率;nil 时沿用模型目录行为 @@ -1454,6 +1455,7 @@ func (s *BillingService) getModelPricingAt(model string, pricingAt time.Time) (* price1h := litellmPricing.CacheCreationInputTokenCostAbove1hr enableBreakdown := price1h > 0 && price1h > price5m return s.applyModelSpecificPricingPolicyEx(model, &ModelPricing{ + priceOverrides: litellmPricing.priceOverrides, InputPricePerToken: litellmPricing.InputCostPerToken, InputPricePerTokenPriority: litellmPricing.InputCostPerTokenPriority, OutputPricePerToken: litellmPricing.OutputCostPerToken, @@ -1676,13 +1678,19 @@ func (s *BillingService) calculateTokenCost(resolved *ResolvedPricing, input Cos // DeepSeek 模型默认价卡按官方峰谷口径调整:高峰时段(01:00–04:00 与 // 06:00–10:00 UTC,仅工作日;北京时间周末全天低谷)按 2× 低谷价计费。 // 仅作用于默认价卡(Source=LiteLLM,无分组/渠道自定义定价)——分组/渠道 - // 自定义定价保持运营者语义,不叠加。先克隆再乘,避免污染共享 fallbackPrices 指针。 + // 自定义定价及 override_file 显式覆盖的字段不叠加。先克隆再乘,避免污染共享价卡。 if resolved.Source == PricingSourceLiteLLM && isDeepSeekModel(input.Model) { if mult := deepseekPeakMultiplierAt(pricingAt); mult > 1 { cloned := *pricing - cloned.InputPricePerToken *= mult - cloned.OutputPricePerToken *= mult - cloned.CacheReadPricePerToken *= mult + if !cloned.priceOverrides.input { + cloned.InputPricePerToken *= mult + } + if !cloned.priceOverrides.output { + cloned.OutputPricePerToken *= mult + } + if !cloned.priceOverrides.cacheRead { + cloned.CacheReadPricePerToken *= mult + } pricing = &cloned } } @@ -1986,7 +1994,7 @@ func (s *BillingService) applyModelSpecificPricingPolicyEx(model string, pricing if pricing == nil { return nil } - // DeepSeek 模型:无论 JSON/远端价格表给什么价,一律强制官方低谷价 + // DeepSeek 模型:目录/回退数据使用官方低谷价;override_file 显式覆盖的字段保留。 // (Flash 三档为 2026-09-10 官方降价后口径)。这是覆盖远端旧价的关键——远端 // 仓库不可改,生产会先拉到旧价,必须在此兜底修正;克隆后再覆盖,避免污染 // 共享 fallbackPrices 指针。 @@ -1997,16 +2005,18 @@ func (s *BillingService) applyModelSpecificPricingPolicyEx(model string, pricing // 对默认价卡另行叠加(分组/渠道自定义定价不叠加)。 if forceDeepSeekRates && isDeepSeekModel(model) { cloned := *pricing + inputPrice, outputPrice, cacheReadPrice := deepseekFlashOffPeakInputPrice, deepseekFlashOffPeakOutputPrice, deepseekFlashOffPeakCacheRead if isDeepSeekProModel(model) { - cloned.InputPricePerToken = deepseekProOffPeakInputPrice - cloned.OutputPricePerToken = deepseekProOffPeakOutputPrice - cloned.CacheReadPricePerToken = deepseekProOffPeakCacheRead - } else { - // deepseek-flash(= V4.1-Flash)、deepseek-v4-flash / - // deepseek-v4-flash-vision-exp 与其余 deepseek-* 共用 flash 价。 - cloned.InputPricePerToken = deepseekFlashOffPeakInputPrice - cloned.OutputPricePerToken = deepseekFlashOffPeakOutputPrice - cloned.CacheReadPricePerToken = deepseekFlashOffPeakCacheRead + inputPrice, outputPrice, cacheReadPrice = deepseekProOffPeakInputPrice, deepseekProOffPeakOutputPrice, deepseekProOffPeakCacheRead + } + if !cloned.priceOverrides.input { + cloned.InputPricePerToken = inputPrice + } + if !cloned.priceOverrides.output { + cloned.OutputPricePerToken = outputPrice + } + if !cloned.priceOverrides.cacheRead { + cloned.CacheReadPricePerToken = cacheReadPrice } return &cloned } diff --git a/backend/internal/service/chat_completions_metadata.go b/backend/internal/service/chat_completions_metadata.go new file mode 100644 index 0000000000..0eb94bfb23 --- /dev/null +++ b/backend/internal/service/chat_completions_metadata.go @@ -0,0 +1,32 @@ +package service + +import ( + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// withChatCompletionsMetadataUserID carries the client's top-level +// metadata.user_id of a Chat Completions request into the Anthropic body +// converted from it. ChatCompletionsRequest and ResponsesRequest have no +// metadata field, so the conversion never sets AnthropicRequest.Metadata and +// without this the Anthropic request never sees the id the client sent. +// +// Only a string user_id that ParseMetadataUserID accepts (JSON form with +// non-empty device_id and session_id, or the legacy form) is carried, as the +// raw JSON string token of the original body, so its bytes do not change. +// Every other metadata key is dropped. In every other case anthropicBody is +// returned as it is. +func withChatCompletionsMetadataUserID(chatBody, anthropicBody []byte) []byte { + userID := gjson.GetBytes(chatBody, "metadata.user_id") + if userID.Type != gjson.String { + return anthropicBody + } + if parsed := ParseMetadataUserID(userID.String()); parsed == nil || parsed.SessionID == "" { + return anthropicBody + } + out, err := sjson.SetRawBytes(anthropicBody, "metadata", []byte(`{"user_id":`+userID.Raw+`}`)) + if err != nil { + return anthropicBody + } + return out +} diff --git a/backend/internal/service/chat_completions_metadata_test.go b/backend/internal/service/chat_completions_metadata_test.go new file mode 100644 index 0000000000..2ad68da361 --- /dev/null +++ b/backend/internal/service/chat_completions_metadata_test.go @@ -0,0 +1,192 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +const ( + chatMetaSessionID = "3f0c9a52-7b1e-4d6a-9c38-5e2f0a1b7c44" + chatMetaJSONUserID = `{"device_id":"device-1","session_id":"` + chatMetaSessionID + `"}` + chatMetaLegacyUser = "user_a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2_account__session_" + chatMetaSessionID + chatMetaConverted = `{"model":"claude-sonnet-4-5","max_tokens":64,"messages":[{"role":"user","content":"hi"}],"stream":true}` + chatMetaChatPrefix = `{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hi"}],` + chatMetaNoMetaChat = `{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hi"}]}` + chatMetaOnlyUserKey = `{"user_id":` +) + +func chatMetaQuote(t *testing.T, s string) string { + t.Helper() + b, err := json.Marshal(s) + require.NoError(t, err) + return string(b) +} + +func TestWithChatCompletionsMetadataUserID_Carries(t *testing.T) { + for name, userID := range map[string]string{"json": chatMetaJSONUserID, "legacy": chatMetaLegacyUser} { + t.Run(name, func(t *testing.T) { + quoted := chatMetaQuote(t, userID) + chat := []byte(chatMetaChatPrefix + `"metadata":{"user_id":` + quoted + `}}`) + out := withChatCompletionsMetadataUserID(chat, []byte(chatMetaConverted)) + + require.Equal(t, chatMetaOnlyUserKey+quoted+`}`, gjson.GetBytes(out, "metadata").Raw) + require.Equal(t, userID, gjson.GetBytes(out, "metadata.user_id").String()) + rest, err := sjson.DeleteBytes(out, "metadata") + require.NoError(t, err) + require.Equal(t, chatMetaConverted, string(rest), "everything but metadata is unchanged") + }) + } +} + +func TestWithChatCompletionsMetadataUserID_KeepsEscapesAndOtherKeysOut(t *testing.T) { + // The id is carried as the client's own string token, escapes included. + userID := `{"device_id":"dév","session_id":"` + chatMetaSessionID + `"}` + chat := []byte(chatMetaChatPrefix + `"metadata":{"trace":"x","user_id":"{\"device_id\":\"dév\",\"session_id\":\"` + chatMetaSessionID + `\"}","other":{"a":1}}}`) + out := withChatCompletionsMetadataUserID(chat, []byte(chatMetaConverted)) + require.Equal(t, `{"user_id":"{\"device_id\":\"dév\",\"session_id\":\"`+chatMetaSessionID+`\"}"}`, gjson.GetBytes(out, "metadata").Raw) + require.Equal(t, userID, gjson.GetBytes(out, "metadata.user_id").String()) + require.False(t, gjson.GetBytes(out, "metadata.trace").Exists()) + require.False(t, gjson.GetBytes(out, "metadata.other").Exists()) +} + +func TestWithChatCompletionsMetadataUserID_LeavesBodyAlone(t *testing.T) { + cases := map[string]string{ + "no metadata": chatMetaNoMetaChat, + "metadata string": chatMetaChatPrefix + `"metadata":"x"}`, + "metadata array": chatMetaChatPrefix + `"metadata":[{"user_id":` + chatMetaQuote(t, chatMetaJSONUserID) + `}]}`, + "metadata null": chatMetaChatPrefix + `"metadata":null}`, + "metadata without id": chatMetaChatPrefix + `"metadata":{"trace":"x"}}`, + "user_id number": chatMetaChatPrefix + `"metadata":{"user_id":12345}}`, + "user_id object": chatMetaChatPrefix + `"metadata":{"user_id":` + chatMetaJSONUserID + `}}`, + "user_id array": chatMetaChatPrefix + `"metadata":{"user_id":[` + chatMetaQuote(t, chatMetaJSONUserID) + `]}}`, + "user_id null": chatMetaChatPrefix + `"metadata":{"user_id":null}}`, + "user_id empty": chatMetaChatPrefix + `"metadata":{"user_id":""}}`, + "user_id bare uuid": chatMetaChatPrefix + `"metadata":{"user_id":"` + chatMetaSessionID + `"}}`, + "user_id free text": chatMetaChatPrefix + `"metadata":{"user_id":"alice"}}`, + "json without device_id": chatMetaChatPrefix + `"metadata":{"user_id":` + chatMetaQuote(t, `{"session_id":"`+chatMetaSessionID+`"}`) + `}}`, + "json empty device_id": chatMetaChatPrefix + `"metadata":{"user_id":` + chatMetaQuote(t, `{"device_id":"","session_id":"`+chatMetaSessionID+`"}`) + `}}`, + "json without session_id": chatMetaChatPrefix + `"metadata":{"user_id":` + chatMetaQuote(t, `{"device_id":"device-1"}`) + `}}`, + "json empty session_id": chatMetaChatPrefix + `"metadata":{"user_id":` + chatMetaQuote(t, `{"device_id":"device-1","session_id":""}`) + `}}`, + "json malformed": chatMetaChatPrefix + `"metadata":{"user_id":"{\"device_id\":"}}`, + "legacy short session": chatMetaChatPrefix + `"metadata":{"user_id":"user_a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2_account__session_123"}}`, + "top-level user only": chatMetaChatPrefix + `"user":` + chatMetaQuote(t, chatMetaJSONUserID) + `}`, + } + for name, chat := range cases { + t.Run(name, func(t *testing.T) { + out := withChatCompletionsMetadataUserID([]byte(chat), []byte(chatMetaConverted)) + require.Equal(t, chatMetaConverted, string(out)) + require.False(t, gjson.GetBytes(out, "metadata").Exists()) + }) + } +} + +func chatMetaStreamUpstream() *httpUpstreamRecorder { + return &httpUpstreamRecorder{resp: nativeAnthropicStreamResponse()} +} + +func chatMetaRequestBody(userID string) []byte { + return []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hi"}],"stream":true,` + + `"metadata":{"trace":"x","user_id":` + userID + `}}`) +} + +func chatMetaContext(body []byte) *gin.Context { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(string(body))) + c.Request.Header.Set("Content-Type", "application/json") + return c +} + +// The Anthropic-platform path (GatewayService.ForwardAsChatCompletions). +func TestForwardAsChatCompletions_CarriesMetadataUserID(t *testing.T) { + for name, tc := range map[string]struct { + userID string + want bool + }{ + "json": {chatMetaQuote(t, chatMetaJSONUserID), true}, + "legacy": {chatMetaQuote(t, chatMetaLegacyUser), true}, + "bare id": {chatMetaQuote(t, chatMetaSessionID), false}, + "number": {`12345`, false}, + } { + t.Run(name, func(t *testing.T) { + body := chatMetaRequestBody(tc.userID) + upstream := chatMetaStreamUpstream() + svc := &GatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := &Account{ID: 1, Platform: PlatformAnthropic, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "sk-test"}} + _, err := svc.ForwardAsChatCompletions(context.Background(), chatMetaContext(body), account, body, nil) + require.NoError(t, err) + require.NotEmpty(t, upstream.lastBody) + if !tc.want { + require.False(t, gjson.GetBytes(upstream.lastBody, "metadata").Exists(), string(upstream.lastBody)) + return + } + require.Equal(t, `{"user_id":`+tc.userID+`}`, gjson.GetBytes(upstream.lastBody, "metadata").Raw, string(upstream.lastBody)) + }) + } +} + +// OAuth accounts keep the id the mimicry synthesizes: the client's id is not carried. +func TestForwardAsChatCompletions_OAuthAccountKeepsSynthesizedMetadataUserID(t *testing.T) { + forward := func(t *testing.T, body []byte) []byte { + t.Helper() + upstream := chatMetaStreamUpstream() + svc := &GatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: upstream, + identityService: NewIdentityService(&stubIdentityCache{fingerprint: &Fingerprint{ + UserAgent: "claude-cli/2.9.0 (external, cli)", ClientID: "test-client", UpdatedAt: time.Now().Unix(), + }}), + } + account := &Account{ID: 1, Platform: PlatformAnthropic, Type: AccountTypeOAuth, Credentials: map[string]any{"access_token": "tok"}} + _, err := svc.ForwardAsChatCompletions(context.Background(), chatMetaContext(body), account, body, nil) + require.NoError(t, err) + require.NotEmpty(t, upstream.lastBody) + return upstream.lastBody + } + + withID := forward(t, chatMetaRequestBody(chatMetaQuote(t, chatMetaJSONUserID))) + withoutID := forward(t, []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hi"}],"stream":true,"metadata":{"trace":"x"}}`)) + + require.NotEmpty(t, gjson.GetBytes(withoutID, "metadata.user_id").String(), string(withoutID)) + require.Equal(t, gjson.GetBytes(withoutID, "metadata").Raw, gjson.GetBytes(withID, "metadata").Raw, string(withID)) + require.NotContains(t, string(withID), "device-1") +} + +// The native Anthropic endpoint path (OpenAIGatewayService.forwardChatCompletionsViaNativeAnthropic). +func TestForwardChatCompletionsViaNativeAnthropic_CarriesMetadataUserID(t *testing.T) { + for name, tc := range map[string]struct { + userID string + want bool + }{ + "json": {chatMetaQuote(t, chatMetaJSONUserID), true}, + "legacy": {chatMetaQuote(t, chatMetaLegacyUser), true}, + "bare id": {chatMetaQuote(t, chatMetaSessionID), false}, + "number": {`12345`, false}, + } { + t.Run(name, func(t *testing.T) { + body := chatMetaRequestBody(tc.userID) + upstream := chatMetaStreamUpstream() + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + _, err := svc.forwardChatCompletionsViaNativeAnthropic(context.Background(), chatMetaContext(body), nativeAnthropicTestAccount(), body, "") + require.NoError(t, err) + require.NotEmpty(t, upstream.lastBody) + if !tc.want { + require.False(t, gjson.GetBytes(upstream.lastBody, "metadata").Exists(), string(upstream.lastBody)) + return + } + require.Equal(t, `{"user_id":`+tc.userID+`}`, gjson.GetBytes(upstream.lastBody, "metadata").Raw, string(upstream.lastBody)) + }) + } +} diff --git a/backend/internal/service/cn_provider_quota_service.go b/backend/internal/service/cn_provider_quota_service.go index 6bbeddec52..1257cf40e3 100644 --- a/backend/internal/service/cn_provider_quota_service.go +++ b/backend/internal/service/cn_provider_quota_service.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "log/slog" + "math" "net/http" "sort" "strconv" @@ -268,10 +269,27 @@ func (s *CNProviderQuotaService) queryUsageForAccount(ctx context.Context, accou result.PlanLevel = strings.TrimSpace(gjson.GetBytes(bodyBytes, "current_subscribe_title").String()) } result.Tiers = tiers + // 2xx 但一个可用窗口都解析不出来,通常意味着上游报文改版/字段改名,而不是 + // 「额度无限」。必须按失败处理:保留旧快照、不写成功时间;否则下面的缺席 + // 清理会把 5h/weekly/monthly 全写 nil,调度层看到「没有窗口」就会解除预停调, + // 让仍处于耗尽的账号回池撞 429。 + if len(tiers) == 0 { + result.Error = fmt.Sprintf( + "quota response for %s contains no recognized usage window (upstream schema may have changed); keeping the previous snapshot", + provider) + slog.Warn("cn_quota_no_recognized_window", + "account_id", account.ID, "provider", provider, "http_status", resp.StatusCode) + return result, nil + } result.Success = true result.CredentialValid = true updates := cnQuotaExtraUpdates(provider, tiers, now) + // 只对 5h/weekly/monthly 三档通吃的供应商清理缺席窗口;Command Code 与 + // Cline 走各自的取舍(抓取失败时保留月度),不在这里处理。 + if provider == PlatformKimi || provider == PlatformZhipu || provider == PlatformMiniMax || provider == PlatformOpenCodeGo { + clearAbsentCNQuotaWindows(provider, tiers, updates) + } if err := s.accountRepo.UpdateExtra(ctx, account.ID, updates); err != nil { slog.Warn("cn_quota_persist_failed", "account_id", account.ID, "provider", provider, "error", err) } else { @@ -379,59 +397,119 @@ func zhipuQuotaHost(baseURL string) string { // parseKimiUsageTiers 解析 Kimi For Coding 的 /usages 响应。 // -// - limits[].detail.{limit,remaining,resetTime} → 5h 窗口(取首个 detail) -// - usage.{limit,remaining,resetTime} → 周窗口 +// Kimi 目前并存两种套餐形态: // -// utilization = (limit-remaining)/limit*100。 +// - 老套餐(5h + 7d):limits[].detail.{limit,remaining,resetTime} → 5h +// (取首个 detail),顶层 usage.{limit,remaining,resetTime} → 周窗口, +// utilization = (limit-remaining)/limit*100。 +// - 新套餐(5h + 月度):不再有顶层 usage,改由 usages.limit_5h / +// usages.limit_7d / usages.limit_month_total / usages.limit_month_code +// 以 used_ratio(0-1)+ reset_time 上报。月度 total 与 code 任一耗尽都会 +// 限流,因此 monthly 取两者较大用量、较早重置时间。 +// +// 两者同时出现时 used_ratio 优先(比 counts 更贴近官方口径),顶层 usage 仅兜底; +// usages.limit_5h 只在 limits[] 没有 detail 时补位,避免重复产出 5h 档。 func parseKimiUsageTiers(body []byte) []CNQuotaTier { var tiers []CNQuotaTier + hasFiveHour := false if limits := gjson.GetBytes(body, "limits"); limits.IsArray() { limits.ForEach(func(_, item gjson.Result) bool { detail := item.Get("detail") if !detail.Exists() { return true } - limit, _ := cnParseF64(detail.Get("limit").Value()) - remaining, _ := cnParseF64(detail.Get("remaining").Value()) - used := limit - remaining - if used < 0 { - used = 0 - } - var util float64 - if limit > 0 { - util = used / limit * 100 + // 字段节点存在不等于数值可信:limit/remaining 必须可解析、limit>0、 + // remaining 落在 [0, limit],否则跳过该条(`{"detail":{}}` 或 limit=0 + // 不能产出一个「已用 0%」的伪窗口,那会掩盖真实的额度耗尽状态)。 + limit, okLimit := cnParseF64(detail.Get("limit").Value()) + remaining, okRemaining := cnParseF64(detail.Get("remaining").Value()) + if !okLimit || !okRemaining || limit <= 0 || remaining < 0 || remaining > limit { + return true } + util := (limit - remaining) / limit * 100 tiers = append(tiers, CNQuotaTier{ Window: "5h", UsedPercent: util, ResetAt: cnNormalizeResetTime(detail.Get("resetTime").Value()), }) - return false // 取首个 detail 作为 5h 窗口 + hasFiveHour = true + return false // 取首个有效 detail 作为 5h 窗口 }) } + if !hasFiveHour { + if tier, ok := kimiUsedRatioTier(body, "limit_5h", "5h"); ok { + tiers = append(tiers, tier) + hasFiveHour = true + } + } - if usage := gjson.GetBytes(body, "usage"); usage.Exists() { - limit, _ := cnParseF64(usage.Get("limit").Value()) - remaining, _ := cnParseF64(usage.Get("remaining").Value()) - used := limit - remaining - if used < 0 { - used = 0 + // 周窗口:usages.limit_7d 优先,顶层 usage(老套餐单数)兜底。 + if tier, ok := kimiUsedRatioTier(body, "limit_7d", "weekly"); ok { + tiers = append(tiers, tier) + } else if usage := gjson.GetBytes(body, "usage"); usage.Exists() { + limit, okLimit := cnParseF64(usage.Get("limit").Value()) + remaining, okRemaining := cnParseF64(usage.Get("remaining").Value()) + if okLimit && okRemaining && limit > 0 && remaining >= 0 && remaining <= limit { + tiers = append(tiers, CNQuotaTier{ + Window: "weekly", + UsedPercent: (limit - remaining) / limit * 100, + ResetAt: cnNormalizeResetTime(usage.Get("resetTime").Value()), + }) } - var util float64 - if limit > 0 { - util = used / limit * 100 + } + + // 月度限额(新套餐):total 与 code 是两个**独立**的限流窗口,任一耗尽都会限流。 + // 用量取两者较大值;重置时间取**较晚**者——取较早会在另一个窗口仍耗尽时提前 + // 解除预停调(例如 total 到 11-26 才恢复、code 到 11-20 恢复)。宁可晚回池, + // 不可提前撞 429。 + total, hasTotal := kimiUsedRatioTier(body, "limit_month_total", "monthly") + code, hasCode := kimiUsedRatioTier(body, "limit_month_code", "monthly") + if hasTotal || hasCode { + monthly := total + if !hasTotal { + monthly = code + } else if hasCode { + if code.UsedPercent > monthly.UsedPercent { + monthly.UsedPercent = code.UsedPercent + } + if code.ResetAt != "" && (monthly.ResetAt == "" || code.ResetAt > monthly.ResetAt) { + monthly.ResetAt = code.ResetAt + } } - tiers = append(tiers, CNQuotaTier{ - Window: "weekly", - UsedPercent: util, - ResetAt: cnNormalizeResetTime(usage.Get("resetTime").Value()), - }) + tiers = append(tiers, monthly) } return tiers } +// kimiUsedRatioTier 解析 usages..{used_ratio,reset_time} 为窗口档位。 +// used_ratio 是 0-1 比例,输出换算为百分比;键缺失、不可解析或越界返回 false。 +func kimiUsedRatioTier(body []byte, key, window string) (CNQuotaTier, bool) { + node := gjson.GetBytes(body, "usages."+key) + if !node.Exists() { + return CNQuotaTier{}, false + } + ratioNode := node.Get("used_ratio") + if !ratioNode.Exists() { + return CNQuotaTier{}, false + } + ratio, ok := cnParseF64(ratioNode.Value()) + if !ok { + return CNQuotaTier{}, false + } + // 必须落在上游声明区间 [0,1]:越界值(例如把百分数 65 直接塞进 used_ratio) + // 会算出 6500%,NaN/Inf 同理不可信。 + if ratio < 0 || ratio > 1 { + return CNQuotaTier{}, false + } + return CNQuotaTier{ + Window: window, + UsedPercent: ratio * 100, + ResetAt: cnNormalizeResetTime(node.Get("reset_time").Value()), + }, true +} + // parseMiniMaxUsageTiers 解析 MiniMax Token Plan / Coding Plan remains 响应。 // // 只取 model_name == "general"(编程套餐),跳过 video。字段是剩余百分比, @@ -574,9 +652,11 @@ func parseZhipuTokenTiers(data gjson.Result) []CNQuotaTier { if limitType != "TOKENS_LIMIT" && limitType != "CREDIT_LIMIT" { return true } - percentage := 0.0 - if p, ok := cnParseF64(item.Get("percentage").Value()); ok { - percentage = p + // percentage 缺失/非数字/NaN/越界时不能默认 0:那会产出一个「已用 0%」的 + // 合法窗口,既掩盖真实耗尽状态,也会被缺席清理当成有效快照落库。 + percentage, okPercentage := cnParseF64(item.Get("percentage").Value()) + if !okPercentage || percentage < 0 || percentage > 100 { + return true } var ( resetMs int64 @@ -671,6 +751,35 @@ func cnQuotaExtraUpdates(provider string, tiers []CNQuotaTier, now time.Time) ma return updates } +// clearAbsentCNQuotaWindows 把本次探测缺席的窗口显式写 nil(JSONB 合并语义下等于 +// 移除按键):账号 extra 的更新走 `extra || $1`,只"不写"会保留旧值。上游改套餐 +// (Kimi 老套餐 7d → 新套餐月度)后旧窗口不再上报,不清理就会把切换前的用量永久 +// 冻结在快照里(生产实测冻结 13 天,列表一直显示过期的 7D 用量)。 +// +// 仅供 5h/weekly/monthly 三档通吃的供应商调用;Command Code / Cline 有自己的 +// 取舍(周期端点抓取失败时保留月度值),不在此列。 +func clearAbsentCNQuotaWindows(provider string, tiers []CNQuotaTier, updates map[string]any) { + present := make(map[string]CNQuotaTier, len(tiers)) + for _, tier := range tiers { + present[tier.Window] = tier + } + for _, window := range []struct{ name, used, reset string }{ + {"5h", cnExtraSuffix5hUsed, cnExtraSuffix5hReset}, + {"weekly", cnExtraSuffixWeeklyUsed, cnExtraSuffixWeeklyReset}, + {"monthly", cnExtraSuffixMonthlyUsed, cnExtraSuffixMonthlyReset}, + } { + tier, ok := present[window.name] + if !ok { + updates[cnExtraKey(provider, window.used)] = nil + updates[cnExtraKey(provider, window.reset)] = nil + continue + } + if tier.ResetAt == "" { + updates[cnExtraKey(provider, window.reset)] = nil + } + } +} + // parseOpenCodeGoUsageTiers 解析 OpenCode Go GET /usage 响应。 // // 结构对齐 cc-switch extractor: @@ -718,24 +827,37 @@ func parseOpenCodeGoUsageTiers(body []byte) []CNQuotaTier { // cnParseF64 把 JSON 数值或字符串解析为 float64(兼容 "100" 与 100)。 func cnParseF64(raw any) (float64, bool) { + var value float64 switch v := raw.(type) { case float64: - return v, true + value = v case float32: - return float64(v), true + value = float64(v) case int: - return float64(v), true + value = float64(v) case int64: - return float64(v), true + value = float64(v) case json.Number: f, err := v.Float64() - return f, err == nil + if err != nil { + return 0, false + } + value = f case string: f, err := strconv.ParseFloat(strings.TrimSpace(v), 64) - return f, err == nil + if err != nil { + return 0, false + } + value = f default: return 0, false } + // strconv.ParseFloat 接受 "NaN"/"Inf",JSON 的 1e999 也会得到 +Inf; + // 这类值参与百分比与阈值比较会让停调判定失效,一律视为不可解析。 + if math.IsNaN(value) || math.IsInf(value, 0) { + return 0, false + } + return value, true } // cnNormalizeResetTime 把上游重置时间(ISO8601 字符串 / 秒级 / 毫秒级数字)归一化为 diff --git a/backend/internal/service/cn_providers_test.go b/backend/internal/service/cn_providers_test.go index 61fea87a5a..fefd4d062c 100644 --- a/backend/internal/service/cn_providers_test.go +++ b/backend/internal/service/cn_providers_test.go @@ -103,8 +103,84 @@ func TestParseKimiUsageTiers_LimitZero(t *testing.T) { t.Parallel() body := []byte(`{"limits":[{"detail":{"limit":0,"remaining":0,"resetTime":"2026-08-14T15:00:00Z"}}]}`) tiers := parseKimiUsageTiers(body) + // limit=0 无法计算利用率:不能产出「已用 0%」的伪窗口(那会把额度耗尽 + // 显示成完全没用),该条目应被跳过。 + require.Len(t, tiers, 0) +} + +// TestParseKimiUsageTiers_MonthlyPlan 新套餐形态(5h + 月度限额):不再有顶层 +// usage,改由 usages.limit_5h / limit_month_total / limit_month_code 以 +// used_ratio(0-1)+ reset_time 上报。monthly 取两条月度键的较大用量 + 较早重置。 +func TestParseKimiUsageTiers_MonthlyPlan(t *testing.T) { + t.Parallel() + body := []byte(`{ + "limits": [{ + "window": {"duration": 300, "timeUnit": "TIME_UNIT_MINUTE"}, + "detail": {"limit": "100", "used": "10", "remaining": "90", "resetTime": "2026-11-13T16:10:29.523075Z"} + }], + "usages": { + "limit_5h": {"used_ratio": 0.0982, "reset_time": "2026-11-13T16:10:28Z"}, + "limit_month_total": {"used_ratio": 0.6564, "reset_time": "2026-11-26T00:00:00Z"}, + "limit_month_code": {"used_ratio": 0.6252, "reset_time": "2026-11-26T00:00:00Z"} + } + }`) + tiers := parseKimiUsageTiers(body) + require.Len(t, tiers, 2, "新套餐应为 5h + monthly,且不得产出已废弃的 weekly") + + require.Equal(t, "5h", tiers[0].Window) + require.InDelta(t, 10.0, tiers[0].UsedPercent, 1e-9, "5h 用 limits[].detail 的绝对计数") + require.Equal(t, "2026-11-13T16:10:29Z", tiers[0].ResetAt) + + require.Equal(t, "monthly", tiers[1].Window) + require.InDelta(t, 65.64, tiers[1].UsedPercent, 1e-9, "used_ratio 0-1 换算为百分比") + require.Equal(t, "2026-11-26T00:00:00Z", tiers[1].ResetAt) +} + +// TestParseKimiUsageTiers_MonthlyPicksMaxUsage total/code 任一耗尽都会限流: +// monthly 取较大用量;重置时间取较早者(先恢复额度,避免过度停调)。 +func TestParseKimiUsageTiers_MonthlyPicksMaxUsage(t *testing.T) { + t.Parallel() + body := []byte(`{"usages":{ + "limit_month_total":{"used_ratio":0.4,"reset_time":"2026-11-26T00:00:00Z"}, + "limit_month_code":{"used_ratio":0.9,"reset_time":"2026-11-20T00:00:00Z"}}}`) + tiers := parseKimiUsageTiers(body) require.Len(t, tiers, 1) - require.InDelta(t, 0.0, tiers[0].UsedPercent, 1e-9) + require.Equal(t, "monthly", tiers[0].Window) + require.InDelta(t, 90.0, tiers[0].UsedPercent, 1e-9) + // total 与 code 是两个独立限流窗口:reset 必须取较晚者,否则 code 先到期的 + // 11-20 会让仍处于 40% 的 total 窗口提前放行。 + require.Equal(t, "2026-11-26T00:00:00Z", tiers[0].ResetAt) + + // 两窗口同为 100% 时也不得取更早的 reset。 + bothFull := parseKimiUsageTiers([]byte(`{"usages":{ + "limit_month_total":{"used_ratio":1,"reset_time":"2026-11-26T00:00:00Z"}, + "limit_month_code":{"used_ratio":1,"reset_time":"2026-11-20T00:00:00Z"}}}`)) + require.Len(t, bothFull, 1) + require.Equal(t, "2026-11-26T00:00:00Z", bothFull[0].ResetAt) + + onlyCode := parseKimiUsageTiers([]byte(`{"usages":{"limit_month_code":{"used_ratio":0.5,"reset_time":"2026-11-20T00:00:00Z"}}}`)) + require.Len(t, onlyCode, 1) + require.Equal(t, "monthly", onlyCode[0].Window) + require.InDelta(t, 50.0, onlyCode[0].UsedPercent, 1e-9) +} + +// TestParseKimiUsageTiers_LegacyWithUsedRatio 老套餐(顶层 usage)同时携带 +// usages.limit_7d 时,weekly 以 used_ratio 为准、不重复产出 weekly 档。 +func TestParseKimiUsageTiers_LegacyWithUsedRatio(t *testing.T) { + t.Parallel() + body := []byte(`{ + "usage": {"limit": "100", "remaining": "80", "resetTime": "2026-10-07T05:04:39.713183Z"}, + "usages": { + "limit_5h": {"used_ratio": 0, "reset_time": "2026-10-04T11:04:38Z"}, + "limit_7d": {"used_ratio": 0.203912, "reset_time": "2026-10-07T05:04:38Z"} + } + }`) + tiers := parseKimiUsageTiers(body) + require.Len(t, tiers, 2) + require.Equal(t, "5h", tiers[0].Window) + require.Equal(t, "weekly", tiers[1].Window) + require.InDelta(t, 20.3912, tiers[1].UsedPercent, 1e-9) + require.Equal(t, "2026-10-07T05:04:38Z", tiers[1].ResetAt) } // TestParseZhipuTokenTiers_UnitClassification 显式 unit(3=5h / 6=weekly)优先分类, @@ -231,6 +307,107 @@ func TestCNQuotaExtraUpdates(t *testing.T) { require.Equal(t, now.Format(time.RFC3339), updates["kimi_usage_updated_at"]) } +// 缺席窗口必须显式写 nil:extra 走 JSONB 合并(`extra || $1`),只"不写"会保留 +// 旧值。Kimi 老套餐 → 新套餐(月度)切换后 weekly 不再上报,不清理就会把切换前 +// 的用量永久冻结在快照里(生产实测冻结 13 天)。 +func TestCNQuotaExtraUpdatesClearsAbsentWindows(t *testing.T) { + t.Parallel() + now := time.Date(2026, 11, 13, 0, 0, 0, 0, time.UTC) + tiers := []CNQuotaTier{ + {Window: "5h", UsedPercent: 10, ResetAt: "2026-11-13T16:10:29Z"}, + {Window: "monthly", UsedPercent: 65.64, ResetAt: "2026-11-26T00:00:00Z"}, + } + updates := cnQuotaExtraUpdates(PlatformKimi, tiers, now) + clearAbsentCNQuotaWindows(PlatformKimi, tiers, updates) + + value, present := updates["kimi_weekly_used_percent"] + require.True(t, present, "缺席的 weekly 必须显式出现在更新里") + require.Nil(t, value) + _, resetPresent := updates["kimi_weekly_reset_at"] + require.True(t, resetPresent) + + require.Equal(t, 10.0, updates["kimi_5h_used_percent"]) + require.Equal(t, 65.64, updates["kimi_monthly_used_percent"]) + require.Equal(t, "2026-11-26T00:00:00Z", updates["kimi_monthly_reset_at"]) +} + +// TestParseKimiUsageTiers_RejectsMalformedWindows 受损/改版结构不得产出伪窗口。 +// 这类窗口一旦被当成有效快照落库,缺席清理会把其他窗口写成 nil, +// 调度层看到「没有窗口」就会解除预停调。 +func TestParseKimiUsageTiers_RejectsMalformedWindows(t *testing.T) { + t.Parallel() + cases := map[string]struct { + body []byte + }{ + "empty object": {[]byte(`{}`)}, + "empty detail": {[]byte(`{"limits":[{"detail":{}}]}`)}, + "limit zero": {[]byte(`{"limits":[{"detail":{"limit":0,"remaining":0}}]}`)}, + "remaining exceeds": {[]byte(`{"limits":[{"detail":{"limit":100,"remaining":200}}]}`)}, + "limit not a number": {[]byte(`{"limits":[{"detail":{"limit":"abc","remaining":"1"}}]}`)}, + "empty usage": {[]byte(`{"usage":{}}`)}, + "ratio out of range": {[]byte(`{"usages":{"limit_5h":{"used_ratio":65}}}`)}, + "ratio NaN": {[]byte(`{"usages":{"limit_5h":{"used_ratio":"NaN"}}}`)}, + "ratio negative": {[]byte(`{"usages":{"limit_5h":{"used_ratio":-0.2}}}`)}, + "renamed top level key": {[]byte(`{"limits_v2":[{"detail":{"limit":100,"remaining":50}}]}`)}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + tiers := parseKimiUsageTiers(tc.body) + require.Empty(t, tiers, "受损结构不得产出窗口:%s", string(tc.body)) + }) + } +} + +// TestParseKimiUsageTiers_KeepsLegalEdgeValues 合法边界(0%、满额、单窗口、整数)不得被误伤。 +func TestParseKimiUsageTiers_KeepsLegalEdgeValues(t *testing.T) { + t.Parallel() + // remaining == limit → 合法的 0%。 + tiers := parseKimiUsageTiers([]byte(`{"limits":[{"detail":{"limit":100,"remaining":100}}]}`)) + require.Len(t, tiers, 1) + require.InDelta(t, 0.0, tiers[0].UsedPercent, 1e-9) + + // remaining == 0 → 100%。 + tiers = parseKimiUsageTiers([]byte(`{"limits":[{"detail":{"limit":100,"remaining":0}}]}`)) + require.Len(t, tiers, 1) + require.InDelta(t, 100.0, tiers[0].UsedPercent, 1e-9) + + // used_ratio == 0 / 1 同样合法。 + tiers = parseKimiUsageTiers([]byte(`{"usages":{"limit_5h":{"used_ratio":0}}}`)) + require.Len(t, tiers, 1) + require.InDelta(t, 0.0, tiers[0].UsedPercent, 1e-9) + + tiers = parseKimiUsageTiers([]byte(`{"usages":{"limit_5h":{"used_ratio":1}}}`)) + require.Len(t, tiers, 1) + require.InDelta(t, 100.0, tiers[0].UsedPercent, 1e-9) + + // 首个 detail 坏、后续合法 → 采用首个有效条目。 + tiers = parseKimiUsageTiers([]byte(`{"limits":[{"detail":{}},{"detail":{"limit":100,"remaining":60}}]}`)) + require.Len(t, tiers, 1) + require.InDelta(t, 40.0, tiers[0].UsedPercent, 1e-9) +} + +// TestParseZhipuTokenTiers_SkipsMissingPercentage percentage 缺失/非法不得伪造 0% 窗口。 +func TestParseZhipuTokenTiers_SkipsMissingPercentage(t *testing.T) { + t.Parallel() + cases := map[string]struct { + body string + wantTiers int + }{ + "missing percentage": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3}]}`, 0}, + "non numeric": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":"abc"}]}`, 0}, + "negative": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":-5}]}`, 0}, + "over 100": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":120}]}`, 0}, + "legal zero": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":0}]}`, 1}, + "legal five hour": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":42}]}`, 1}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + tiers := parseZhipuTokenTiers(gjson.Parse(tc.body)) + require.Len(t, tiers, tc.wantTiers, "输入:%s", tc.body) + }) + } +} + func TestParseOpenCodeGoUsageTiers(t *testing.T) { t.Parallel() body := []byte(`{ diff --git a/backend/internal/service/composite_platform.go b/backend/internal/service/composite_platform.go index b7fcfd3451..ddaf2d83ad 100644 --- a/backend/internal/service/composite_platform.go +++ b/backend/internal/service/composite_platform.go @@ -6,6 +6,8 @@ import ( "github.com/Wei-Shaw/sub2api/internal/domain" "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" ) // WithResolvedTargetPlatform stores the concrete provider chosen for a request @@ -73,6 +75,33 @@ func RequestedPublicModelFromContext(ctx context.Context) (string, bool) { return model, true } +// compositeClientModel returns the public model the client asked for when a +// composite route sent a different model upstream, and fallback otherwise. The +// response reports that public name whatever model the upstream says served it. +func compositeClientModel(ctx context.Context, fallback string) string { + publicModel, ok := RequestedPublicModelFromContext(ctx) + if !ok { + return fallback + } + if upstreamModel, ok := ResolvedUpstreamModelFromContext(ctx); !ok || upstreamModel == publicModel { + return fallback + } + return publicModel +} + +// restoreCompositeClientModel reports the client's public model in an Anthropic +// response body when a composite route rewrote the model. +func restoreCompositeClientModel(ctx context.Context, body []byte) []byte { + clientModel := compositeClientModel(ctx, "") + if clientModel == "" || !gjson.GetBytes(body, "model").Exists() { + return body + } + if rewritten, err := sjson.SetBytes(body, "model", clientModel); err == nil { + return rewritten + } + return body +} + func CompositeRouteSourceFromContext(ctx context.Context) (string, bool) { if ctx == nil { return "", false diff --git a/backend/internal/service/composite_route_client_model_test.go b/backend/internal/service/composite_route_client_model_test.go new file mode 100644 index 0000000000..48444e2c19 --- /dev/null +++ b/backend/internal/service/composite_route_client_model_test.go @@ -0,0 +1,299 @@ +//go:build unit + +package service + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// publicModelRoute serves requests for public-model with claude-opus-5-5. +func publicModelRoute() CompositeModelRoute { + return CompositeModelRoute{ + ID: 1, + GroupID: 11, + PublicModel: "public-model", + MatchType: CompositeRouteMatchExact, + TargetPlatform: PlatformAnthropic, + UpstreamModel: "claude-opus-5-5", + Endpoint: CompositeRouteEndpointAny, + Priority: 100, + Enabled: true, + } +} + +// routeCompositeBody resolves body's model against route and rewrites the +// model the way the composite middleware does before any handler runs. +func routeCompositeBody(t *testing.T, route CompositeModelRoute, endpoint string, body []byte) (context.Context, []byte) { + t.Helper() + resolver := NewCompositeRouteResolver(compositeRouteRepoStub{routes: []CompositeModelRoute{route}}) + decision, err := resolver.Resolve(context.Background(), route.GroupID, gjson.GetBytes(body, "model").String(), endpoint) + require.NoError(t, err) + require.True(t, decision.Matched) + body, err = sjson.SetBytes(body, "model", decision.UpstreamModel) + require.NoError(t, err) + return WithCompositeRouteDecision(context.Background(), decision), body +} + +func anthropicMessageStartModel(t *testing.T, sse string) string { + t.Helper() + for _, line := range strings.Split(sse, "\n") { + data, ok := strings.CutPrefix(line, "data: ") + if ok && gjson.Get(data, "type").String() == "message_start" { + return gjson.Get(data, "message.model").String() + } + } + t.Fatalf("no message_start event in stream:\n%s", sse) + return "" +} + +func TestCompositeRouteRestoresPublicModelOnAnthropicForward(t *testing.T) { + gin.SetMode(gin.TestMode) + accounts := map[string]func() *Account{ + "oauth": newAnthropicOAuthAccountForPartialUsageTest, + "apikey-passthrough": newAnthropicAPIKeyAccountForTest, + } + for accountName, newAccount := range accounts { + for _, stream := range []bool{false, true} { + t.Run(accountName+"/stream="+strconv.FormatBool(stream), func(t *testing.T) { + client := []byte(`{"model":"public-model","max_tokens":16,"stream":` + strconv.FormatBool(stream) + + `,"messages":[{"role":"user","content":"hi"}]}`) + ctx, body := routeCompositeBody(t, publicModelRoute(), CompositeRouteEndpointMessages, client) + + // The upstream reports its own dated id: the client still sees + // the public name it asked for. + upstreamBody := `{"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-5-5-20260901","content":[{"type":"text","text":"hi"}],"usage":{"input_tokens":1,"output_tokens":1}}` + contentType := "application/json" + if stream { + upstreamBody = strings.Join([]string{ + `event: message_start`, + `data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-5-5-20260901","content":[],"usage":{"input_tokens":1}}}`, + "", + `event: message_delta`, + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`, + "", + `event: message_stop`, + `data: {"type":"message_stop"}`, + "", + "", + }, "\n") + contentType = "text/event-stream" + } + upstream := &anthropicHTTPUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{contentType}}, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + }} + svc := newForwardPartialUsageServiceForTest(upstream) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil).WithContext(ctx) + parsed, err := ParseGatewayRequest(NewRequestBodyRef(body), PlatformAnthropic) + require.NoError(t, err) + + _, err = svc.Forward(ctx, c, newAccount(), parsed) + require.NoError(t, err) + + require.Equal(t, "claude-opus-5-5", gjson.GetBytes(upstream.lastBody, "model").String()) + if stream { + require.Equal(t, "public-model", anthropicMessageStartModel(t, rec.Body.String())) + } else { + require.Equal(t, "public-model", gjson.GetBytes(rec.Body.Bytes(), "model").String()) + require.Equal(t, "hi", gjson.GetBytes(rec.Body.Bytes(), "content.0.text").String()) + } + }) + } + } +} + +func TestCompositeRouteRestoresPublicModelOnResponsesBridge(t *testing.T) { + gin.SetMode(gin.TestMode) + route := publicModelRoute() + route.TargetPlatform = PlatformOpenAI + route.UpstreamModel = "gpt-5.6-sol" + for _, stream := range []bool{false, true} { + t.Run("stream="+strconv.FormatBool(stream), func(t *testing.T) { + client := []byte(`{"model":"public-model","max_tokens":16,"stream":` + strconv.FormatBool(stream) + + `,"messages":[{"role":"user","content":"hello"}]}`) + ctx, body := routeCompositeBody(t, route, CompositeRouteEndpointMessages, client) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(string(body))).WithContext(ctx) + c.Request.Header.Set("Content-Type", "application/json") + upstream := &httpUpstreamRecorder{resp: openAICompatSSECompletedResponse("resp_route", route.UpstreamModel)} + upstream.resp.Body = io.NopCloser(io.MultiReader( + strings.NewReader(`data: {"type":"response.created","response":{"id":"resp_route","model":"`+route.UpstreamModel+`"}}`+"\n\n"), + upstream.resp.Body, + )) + svc := &OpenAIGatewayService{httpUpstream: upstream, cfg: rawChatCompletionsTestConfig()} + + _, err := svc.ForwardAsAnthropic(ctx, c, rawGPT56ResponsesOAuthAccount(route.UpstreamModel, route.UpstreamModel), body, "", "") + require.NoError(t, err) + + require.Equal(t, route.UpstreamModel, gjson.GetBytes(upstream.lastBody, "model").String()) + if stream { + require.Equal(t, "public-model", anthropicMessageStartModel(t, rec.Body.String())) + } else { + require.Equal(t, "public-model", gjson.GetBytes(rec.Body.Bytes(), "model").String()) + } + }) + } +} + +func TestCompositeRouteRestoresPublicModelOnChatCompletionsBridge(t *testing.T) { + gin.SetMode(gin.TestMode) + route := publicModelRoute() + route.TargetPlatform = PlatformOpenAI + route.UpstreamModel = "gpt-5.6-luna" + for _, stream := range []bool{false, true} { + t.Run("stream="+strconv.FormatBool(stream), func(t *testing.T) { + client := []byte(`{"model":"public-model","max_tokens":16,"messages":[{"role":"user","content":"hello"}],"stream":` + strconv.FormatBool(stream) + `}`) + ctx, body := routeCompositeBody(t, route, CompositeRouteEndpointMessages, client) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(string(body))).WithContext(ctx) + c.Request.Header.Set("Content-Type", "application/json") + upstreamBody := `{"id":"chatcmpl_route","object":"chat.completion","model":"gpt-5.6-luna","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}` + contentType := "application/json" + if stream { + upstreamBody = strings.Join([]string{ + `data: {"id":"chatcmpl_route","object":"chat.completion.chunk","model":"gpt-5.6-luna","choices":[{"index":0,"delta":{"role":"assistant","content":"ok"},"finish_reason":null}]}`, + "", + `data: {"id":"chatcmpl_route","object":"chat.completion.chunk","model":"gpt-5.6-luna","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}`, + "", + "data: [DONE]", + "", + }, "\n") + contentType = "text/event-stream" + } + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{contentType}}, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + }} + account := forceChatMessagesFallbackAccount() + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + + _, err := svc.ForwardAsAnthropic(ctx, c, account, body, "", "") + require.NoError(t, err) + require.Equal(t, "gpt-5.6-luna", gjson.GetBytes(upstream.lastBody, "model").String()) + if stream { + require.Equal(t, "public-model", anthropicMessageStartModel(t, rec.Body.String())) + } else { + require.Equal(t, "public-model", gjson.GetBytes(rec.Body.Bytes(), "model").String()) + } + }) + } +} + +func TestRestoreCompositeClientModelOnlyWhenRouteRewroteModel(t *testing.T) { + body := []byte(`{"id":"msg_1","type":"message","model":"claude-opus-5-5-20260901"}`) + route := publicModelRoute() + + renamedCtx, _ := routeCompositeBody(t, route, CompositeRouteEndpointMessages, []byte(`{"model":"public-model"}`)) + require.Equal(t, "public-model", gjson.GetBytes(restoreCompositeClientModel(renamedCtx, body), "model").String()) + require.Equal(t, "public-model", compositeClientModel(renamedCtx, "claude-opus-5-5")) + + route.PublicModel = route.UpstreamModel + sameCtx, _ := routeCompositeBody(t, route, CompositeRouteEndpointMessages, []byte(`{"model":"claude-opus-5-5"}`)) + require.Equal(t, string(body), string(restoreCompositeClientModel(sameCtx, body))) + require.Equal(t, "claude-opus-5-5", compositeClientModel(sameCtx, "claude-opus-5-5")) + + require.Equal(t, string(body), string(restoreCompositeClientModel(context.Background(), body))) + require.Equal(t, "claude-opus-5-5", compositeClientModel(context.Background(), "claude-opus-5-5")) + + noModel := []byte(`{"type":"error"}`) + require.Equal(t, string(noModel), string(restoreCompositeClientModel(renamedCtx, noModel))) +} + +func forwardCompositeAnthropicStream(t *testing.T, newAccount func() *Account, upstreamSSE string) string { + t.Helper() + gin.SetMode(gin.TestMode) + client := []byte(`{"model":"public-model","max_tokens":16,"stream":true,"messages":[{"role":"user","content":"hi"}]}`) + ctx, body := routeCompositeBody(t, publicModelRoute(), CompositeRouteEndpointMessages, client) + upstream := &anthropicHTTPUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(upstreamSSE)), + }} + svc := newForwardPartialUsageServiceForTest(upstream) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil).WithContext(ctx) + parsed, err := ParseGatewayRequest(NewRequestBodyRef(body), PlatformAnthropic) + require.NoError(t, err) + + _, err = svc.Forward(ctx, c, newAccount(), parsed) + require.NoError(t, err) + return rec.Body.String() +} + +func anthropicStreamEventData(t *testing.T, sse, eventType string) string { + t.Helper() + for _, line := range strings.Split(sse, "\n") { + data, ok := strings.CutPrefix(line, "data:") + data = strings.TrimSpace(data) + if ok && gjson.Get(data, "type").String() == eventType { + return data + } + } + t.Fatalf("no %s event in stream:\n%s", eventType, sse) + return "" +} + +func TestCompositeRouteStreamRewritesOnlyMessageStartModel(t *testing.T) { + accounts := map[string]func() *Account{ + "oauth": newAnthropicOAuthAccountForPartialUsageTest, + "apikey-passthrough": newAnthropicAPIKeyAccountForTest, + } + for accountName, newAccount := range accounts { + t.Run(accountName, func(t *testing.T) { + sse := forwardCompositeAnthropicStream(t, newAccount, strings.Join([]string{ + `event: message_start`, + `data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-5-5-20260901","content":[],"usage":{"input_tokens":1}}}`, + "", + `event: ping`, + `data: {"type":"ping","message":{"model":"other-model"}}`, + "", + `event: message_delta`, + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`, + "", + `event: message_stop`, + `data: {"type":"message_stop"}`, + "", + "", + }, "\n")) + + require.Equal(t, "public-model", gjson.Get(anthropicStreamEventData(t, sse, "message_start"), "message.model").String()) + require.Equal(t, "other-model", gjson.Get(anthropicStreamEventData(t, sse, "ping"), "message.model").String()) + }) + } +} + +func TestCompositeRoutePassthroughStreamKeepsMessageStartWithoutModel(t *testing.T) { + sse := forwardCompositeAnthropicStream(t, newAnthropicAPIKeyAccountForTest, strings.Join([]string{ + `event: message_start`, + `data:{"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"usage":{"input_tokens":1}}}`, + "", + `event: message_stop`, + `data: {"type":"message_stop"}`, + "", + "", + }, "\n")) + + require.False(t, gjson.Get(anthropicStreamEventData(t, sse, "message_start"), "message.model").Exists()) +} diff --git a/backend/internal/service/custom_group_usage_rollup.go b/backend/internal/service/custom_group_usage_rollup.go index d14dc9bfd9..79123c8be0 100644 --- a/backend/internal/service/custom_group_usage_rollup.go +++ b/backend/internal/service/custom_group_usage_rollup.go @@ -21,12 +21,14 @@ func GroupUsageTimezoneName() string { // GroupUsageTodayStart 返回指定时刻在服务端配置时区内的自然日 UTC 起点。 func GroupUsageTodayStart(at time.Time) time.Time { - return appTimezone.StartOfDay(at).UTC() + year, month, day := at.In(appTimezone.Location()).Date() + return groupUsageDayStart(year, month, day).UTC() } // GroupUsageYesterdayStart 返回指定时刻前一个本地日历日的 UTC 起点。 func GroupUsageYesterdayStart(at time.Time) time.Time { - return appTimezone.StartOfDay(at).AddDate(0, 0, -1).UTC() + // 任一本地日至少 22 小时,当日起点前 12 小时必落在前一个日历日内。 + return GroupUsageTodayStart(GroupUsageTodayStart(at).Add(-12 * time.Hour)) } // GroupUsageDate 返回指定时刻在服务端配置时区内的日期。 @@ -34,7 +36,44 @@ func GroupUsageDate(at time.Time) string { return at.In(appTimezone.Location()).Format(groupUsageDateFormat) } -// ParseGroupUsageDate 解析服务端配置时区内的日期并返回其零点。 +// ParseGroupUsageDate 解析服务端配置时区内的日期并返回该日期的起点。 func ParseGroupUsageDate(value string) (time.Time, error) { - return appTimezone.ParseInLocation(groupUsageDateFormat, value) + date, err := time.Parse(groupUsageDateFormat, value) + if err != nil { + return time.Time{}, err + } + year, month, day := date.Date() + return groupUsageDayStart(year, month, day), nil +} + +// groupUsageDayStart 返回本地日期 year-month-day 的第一个时刻(服务端配置时区)。 +// 夏令时在零点跳变的日期,00:00 可能不存在或出现两次,此时返回该日期实际开始的时刻。 +func groupUsageDayStart(year int, month time.Month, day int) time.Time { + loc := appTimezone.Location() + target := groupUsageDateOrdinal(year, month, day) + start := time.Date(year, month, day, 0, 0, 0, 0, loc) + if localGroupUsageDateOrdinal(start) == target && localGroupUsageDateOrdinal(start.Add(-time.Nanosecond)) < target { + return start + } + // 在 [前一日正午, 当日正午] 内二分出本地日期首次到达目标日期的时刻。 + low := time.Date(year, month, day-1, 12, 0, 0, 0, loc) + high := time.Date(year, month, day, 12, 0, 0, 0, loc) + for high.Sub(low) > time.Nanosecond { + mid := low.Add(high.Sub(low) / 2) + if localGroupUsageDateOrdinal(mid) >= target { + high = mid + } else { + low = mid + } + } + return high +} + +func localGroupUsageDateOrdinal(at time.Time) int { + year, month, day := at.In(appTimezone.Location()).Date() + return groupUsageDateOrdinal(year, month, day) +} + +func groupUsageDateOrdinal(year int, month time.Month, day int) int { + return year*10000 + int(month)*100 + day } diff --git a/backend/internal/service/dashboard_aggregation_service.go b/backend/internal/service/dashboard_aggregation_service.go index c85dec07a3..82b0a94889 100644 --- a/backend/internal/service/dashboard_aggregation_service.go +++ b/backend/internal/service/dashboard_aggregation_service.go @@ -373,13 +373,18 @@ func (s *DashboardAggregationService) maybeCleanupRetention(ctx context.Context, } hourlyCutoff := now.AddDate(0, 0, -s.cfg.Retention.HourlyDays) dailyCutoff := now.AddDate(0, 0, -s.cfg.Retention.DailyDays) - usageCutoff := now.AddDate(0, 0, -usageDays) + // usage_logs 按服务端配置时区整日保留,与分组日桶的日界对齐。 + usageCutoff := GroupUsageTodayStart(now.AddDate(0, 0, -usageDays)) dedupDays := s.cfg.Retention.UsageBillingDedupDays if dedupDays <= 0 { dedupDays = 365 } dedupDays = max(dedupDays, usageDays) + // 计费去重记录的保留不短于 usage_logs。 dedupCutoff := now.AddDate(0, 0, -dedupDays) + if usageDays > 0 && dedupCutoff.After(usageCutoff) { + dedupCutoff = usageCutoff + } var aggErr, usageErr, dedupErr error if s.cfg.Enabled { diff --git a/backend/internal/service/deepseek_pricing_test.go b/backend/internal/service/deepseek_pricing_test.go index 4f7f8b6f49..e11c6265d0 100644 --- a/backend/internal/service/deepseek_pricing_test.go +++ b/backend/internal/service/deepseek_pricing_test.go @@ -442,3 +442,115 @@ func TestCalculateCostUnified_DeepseekProRetainsRatesAfterSeptember14(t *testing require.InDelta(t, proTotal, versioned.TotalCost, 1e-10, "versioned pro names must retain Pro rates on September 14") } + +// Explicit override-file token prices are final operator rates, including zero. +// Fields absent from that patch still use the official default and peak policy. +func TestDeepseekOverrideFileTokenPrices(t *testing.T) { + type prices struct{ input, output, cacheRead float64 } + official := prices{1.5e-7, 6e-7, 3e-9} + officialPeak := prices{3e-7, 1.2e-6, 6e-9} + custom := prices{2e-6, 3e-6, 4e-7} + fullPatch := `{"input_cost_per_token":0.000002,"output_cost_per_token":0.000003,"cache_read_input_token_cost":0.0000004}` + cases := []struct { + name, model, layer, patch string + offPeak, peak prices + }{ + {"flash full", "deepseek-flash", "catalog", fullPatch, custom, custom}, + {"pro full", "deepseek-v4-pro", "catalog", fullPatch, custom, custom}, + {"versioned pro full", "deepseek-v4-pro-0813", "catalog", fullPatch, custom, custom}, + {"fallback full", "deepseek-flash", "fallback", fullPatch, custom, custom}, + {"custom model override only", "deepseek-custom", "override", fullPatch, custom, custom}, + {"override only", "deepseek-flash", "override", fullPatch, custom, custom}, + {"input only", "deepseek-flash", "catalog", `{"input_cost_per_token":0.000002}`, prices{2e-6, 6e-7, 3e-9}, prices{2e-6, 1.2e-6, 6e-9}}, + {"zero input", "deepseek-flash", "catalog", `{"input_cost_per_token":0}`, prices{0, 6e-7, 3e-9}, prices{0, 1.2e-6, 6e-9}}, + {"zero output", "deepseek-flash", "catalog", `{"output_cost_per_token":0}`, prices{1.5e-7, 0, 3e-9}, prices{3e-7, 0, 6e-9}}, + {"zero cache read", "deepseek-flash", "catalog", `{"cache_read_input_token_cost":0}`, prices{1.5e-7, 6e-7, 0}, prices{3e-7, 1.2e-6, 0}}, + {"metadata only", "deepseek-flash", "catalog", `{"supports_prompt_caching":true}`, official, officialPeak}, + {"null input", "deepseek-flash", "catalog", `{"input_cost_per_token":null}`, official, officialPeak}, + {"negative input", "deepseek-flash", "catalog", `{"input_cost_per_token":-0.000002}`, official, officialPeak}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + cfg := &config.Config{} + cfg.Pricing.DataDir = dir + cfg.Pricing.OverrideFile = filepath.Join(dir, "overrides.json") + require.NoError(t, os.WriteFile(cfg.Pricing.OverrideFile, []byte(`{"`+tc.model+`":`+tc.patch+`}`), 0644)) + // Deliberately stale catalog rates must still be corrected for every + // field that the operator did not explicitly override. + catalog := []byte(`{"` + tc.model + `":{"input_cost_per_token":0.00001,"output_cost_per_token":0.00002,"cache_read_input_token_cost":0.000001}}`) + if tc.layer == "fallback" { + cfg.Pricing.FallbackFile = filepath.Join(dir, "fallback.json") + require.NoError(t, os.WriteFile(cfg.Pricing.FallbackFile, catalog, 0644)) + } + if tc.layer != "catalog" { + catalog = []byte(`{"other-model":{"input_cost_per_token":0.000001}}`) + } + svc := &PricingService{cfg: cfg} + require.NoError(t, os.WriteFile(svc.getPricingFilePath(), catalog, 0644)) + require.NoError(t, svc.loadPricingData(svc.getPricingFilePath())) + billing := NewBillingService(cfg, svc) + resolver := NewModelPricingResolver(nil, billing) + tokens := UsageTokens{InputTokens: 1000, OutputTokens: 500, CacheReadTokens: 2000} + for _, slot := range []struct { + name string + at time.Time + want prices + }{ + {"off peak", time.Date(2026, 8, 24, 12, 0, 0, 0, time.UTC), tc.offPeak}, + {"peak", time.Date(2026, 8, 24, 2, 0, 0, 0, time.UTC), tc.peak}, + } { + t.Run(slot.name, func(t *testing.T) { + cost, err := billing.CalculateCostUnified(CostInput{ + Ctx: context.Background(), Model: tc.model, Tokens: tokens, RateMultiplier: 1.25, + Resolver: resolver, PricingAt: slot.at, + }) + require.NoError(t, err) + require.InDelta(t, 1000*slot.want.input, cost.InputCost, 1e-12) + require.InDelta(t, 500*slot.want.output, cost.OutputCost, 1e-12) + require.InDelta(t, 2000*slot.want.cacheRead, cost.CacheReadCost, 1e-12) + want := 1000*slot.want.input + 500*slot.want.output + 2000*slot.want.cacheRead + require.InDelta(t, want, cost.TotalCost, 1e-12) + require.InDelta(t, want*1.25, cost.ActualCost, 1e-12) + stats := tryModelFilePricing(billing, tc.model, tokens, "", slot.at, false) + require.NotNil(t, stats) + require.InDelta(t, want, *stats, 1e-12, "account statistics use the same override rates") + }) + } + // Catalog lookup and legacy estimates also retain the override. + pricing, err := billing.GetModelPricing(tc.model) + require.NoError(t, err) + require.InDelta(t, tc.offPeak.input, pricing.InputPricePerToken, 1e-15) + require.InDelta(t, tc.offPeak.output, pricing.OutputPricePerToken, 1e-15) + require.InDelta(t, tc.offPeak.cacheRead, pricing.CacheReadPricePerToken, 1e-15) + estimate, err := billing.CalculateCost(tc.model, tokens, 1) + require.NoError(t, err) + want := 1000*tc.offPeak.input + 500*tc.offPeak.output + 2000*tc.offPeak.cacheRead + require.InDelta(t, want, estimate.TotalCost, 1e-12) + }) + } +} + +func TestDeepseekOverrideFileReloadRestoresOfficialPolicy(t *testing.T) { + svc := newHotReloadPricingService(t, `{"deepseek-flash":{"input_cost_per_token":0.00001,"output_cost_per_token":0.00002}}`, + `{"deepseek-flash":{"input_cost_per_token":0.000002,"output_cost_per_token":0.000003,"cache_read_input_token_cost":0}}`) + billing := NewBillingService(svc.cfg, svc) + resolver := NewModelPricingResolver(nil, billing) + check := func(wantInput, wantOutput, wantCacheRead float64) { + t.Helper() + cost, err := billing.CalculateCostUnified(CostInput{Ctx: context.Background(), Model: "deepseek-flash", + Tokens: UsageTokens{InputTokens: 1000, OutputTokens: 500, CacheReadTokens: 2000}, RateMultiplier: 1, + Resolver: resolver, PricingAt: time.Date(2026, 8, 24, 2, 0, 0, 0, time.UTC)}) + require.NoError(t, err) + require.InDelta(t, wantInput, cost.InputCost, 1e-12) + require.InDelta(t, wantOutput, cost.OutputCost, 1e-12) + require.InDelta(t, wantCacheRead, cost.CacheReadCost, 1e-12) + } + check(0.002, 0.0015, 0) + require.NoError(t, os.WriteFile(svc.cfg.Pricing.OverrideFile, []byte(`{"deepseek-flash":{"output_cost_per_token":0}}`), 0644)) + svc.reloadIfCustomFilesChanged() + check(0.0003, 0, 0.000012) + require.NoError(t, os.Remove(svc.cfg.Pricing.OverrideFile)) + svc.reloadIfCustomFilesChanged() + check(0.0003, 0.0006, 0.000012) +} diff --git a/backend/internal/service/gateway_anthropic_compat_observation_test.go b/backend/internal/service/gateway_anthropic_compat_observation_test.go new file mode 100644 index 0000000000..115c77d665 --- /dev/null +++ b/backend/internal/service/gateway_anthropic_compat_observation_test.go @@ -0,0 +1,73 @@ +//go:build unit + +package service + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestAnthropicCompatUpstreamObservation(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, protocol := range []string{"chat", "responses"} { + for _, streaming := range []bool{false, true} { + for _, scenario := range []string{"normal", "missing", "conflict", "partial-error"} { + t.Run(fmt.Sprintf("%s/stream=%t/%s", protocol, streaming, scenario), func(t *testing.T) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/", nil) + beginUpstreamResponseModelObservation(c).Observe("stale-model", false) + body := "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"actual-model\",\"usage\":{\"input_tokens\":3,\"speed\":\"fast\"}}}\n\nevent: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":1}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + + expectedModel, expectedTier := "actual-model", "fast" + switch scenario { + case "missing": + body = strings.ReplaceAll(body, `,"model":"actual-model"`, "") + body = strings.ReplaceAll(body, `,"speed":"fast"`, "") + expectedModel, expectedTier = "", "" + case "conflict": + body = strings.Replace(body, `"type":"message_delta","delta"`, `"type":"message_delta","model":"other-model","delta"`, 1) + case "partial-error": + body = body[:strings.Index(body, "event: message_delta")] + } + resp := &http.Response{Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)} + svc := &GatewayService{} + var result *ForwardResult + var err error + if protocol == "chat" { + if streaming { + result, err = svc.handleCCStreamingFromAnthropic(resp, c, "public-model", "sent-model", nil, time.Now()) + } else { + result, err = svc.handleCCBufferedFromAnthropic(resp, c, "public-model", "sent-model", nil, time.Now()) + } + } else { + if streaming { + result, err = svc.handleResponsesStreamingResponse(resp, c, "public-model", "sent-model", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + } else { + result, err = svc.handleResponsesBufferedStreamingResponse(resp, c, "public-model", "sent-model", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + } + } + if scenario == "partial-error" { + require.Error(t, err) + } else { + require.NoError(t, err) + } + require.NotNil(t, result) + require.Equal(t, expectedModel, result.UpstreamResponseModel) + require.Equal(t, expectedTier, result.UpstreamResponseServiceTier) + require.Equal(t, scenario == "conflict", result.UpstreamResponseModelConflict) + require.Equal(t, "sent-model", result.UpstreamModel) + require.Equal(t, "public-model", result.Model) + }) + } + } + } +} diff --git a/backend/internal/service/gateway_anthropic_passthrough.go b/backend/internal/service/gateway_anthropic_passthrough.go index e7c99cb076..a781b69913 100644 --- a/backend/internal/service/gateway_anthropic_passthrough.go +++ b/backend/internal/service/gateway_anthropic_passthrough.go @@ -501,6 +501,7 @@ func (s *GatewayService) handleStreamingResponseAnthropicAPIKeyPassthrough( keepaliveTimer.Reset(keepaliveInterval) } inPartialEvent := false + clientModel := compositeClientModel(ctx, "") for { select { @@ -560,8 +561,14 @@ func (s *GatewayService) handleStreamingResponseAnthropicAPIKeyPassthrough( } } + if data, ok := extractAnthropicSSEDataLine(line); ok && clientModel != "" && gjson.Get(data, "type").String() == "message_start" && gjson.Get(data, "message.model").Exists() { + if rewritten, err := sjson.Set(data, "message.model", clientModel); err == nil { + line = "data: " + rewritten + } + } + if !clientDisconnected { - restored := string(reverseToolNamesIfPresent(c, []byte(line))) + restored := reverseToolNamesIfPresentString(c, line) if _, err := io.WriteString(w, restored); err != nil { clientDisconnected = true logger.LegacyPrintf("service.gateway", "[Anthropic passthrough] Client disconnected during streaming, continue draining upstream for usage: account=%d", account.ID) @@ -894,6 +901,7 @@ func (s *GatewayService) handleNonStreamingResponseAnthropicAPIKeyPassthrough( if contentType == "" { contentType = "application/json" } + body = restoreCompositeClientModel(ctx, body) body = reverseToolNamesIfPresent(c, body) c.Data(resp.StatusCode, contentType, body) return usage, nil diff --git a/backend/internal/service/gateway_bedrock.go b/backend/internal/service/gateway_bedrock.go index 60d6937fbb..196d977579 100644 --- a/backend/internal/service/gateway_bedrock.go +++ b/backend/internal/service/gateway_bedrock.go @@ -130,9 +130,7 @@ func (s *GatewayService) forwardBedrock( // 错误/failover 处理 if resp.StatusCode >= 400 { - // 账号状态按模型隔离时用调度器的模型键(账号映射后的模型名),不是发往上游的 Bedrock 模型 ID; - // 两者不一致会让模型级冷却写到调度器不会读取的键上。 - return s.handleBedrockUpstreamErrors(ctx, resp, c, account, account.GetMappedModel(reqModel)) + return s.handleBedrockUpstreamErrors(ctx, resp, c, account, bedrockSchedulingModelKey(ctx, account, reqModel)) } // Bedrock 分支绕过通用 Forward 成功路径,这里保持上游接受回调语义一致。 @@ -147,6 +145,10 @@ func (s *GatewayService) forwardBedrock( if reqStream { streamResult, err := s.handleBedrockStreamingResponse(ctx, resp, c, account, startTime, reqModel) if err != nil { + // 流中断时保留已观测到的 usage 与错误一起返回,handler 照常提交 usage 记录。 + if partial := partialStreamUsageResult(c, resp, streamResult, reqModel, mappedModel, startTime, err); partial != nil { + return partial, err + } return nil, err } usage = streamResult.usage @@ -274,6 +276,16 @@ func (s *GatewayService) handleBedrockUpstreamErrors( account *Account, modelKey string, ) (*ForwardResult, error) { + // 内容过滤由请求内容决定,换号结果相同:不换号,按普通错误返回客户端。 + if resp.StatusCode >= http.StatusInternalServerError { + respBody, _ := s.readUpstreamErrorBody(resp) + _ = resp.Body.Close() + resp.Body = io.NopCloser(bytes.NewReader(respBody)) + if isBedrockContentFilterError(resp.StatusCode, respBody) { + return s.handleErrorResponse(ctx, resp, c, account, modelKey) + } + } + // retry exhausted + failover if s.shouldRetryUpstreamError(account, resp.StatusCode) { if s.shouldFailoverUpstreamError(resp.StatusCode) { diff --git a/backend/internal/service/gateway_billing_header.go b/backend/internal/service/gateway_billing_header.go index a794af0d20..fff59baccd 100644 --- a/backend/internal/service/gateway_billing_header.go +++ b/backend/internal/service/gateway_billing_header.go @@ -44,12 +44,17 @@ func syncBillingHeaderVersion(body []byte, userAgent string) []byte { } replacement := "cc_version=" + version + // The fingerprint depends only on the original messages and version, so it + // is the same for every billing block. Compute it lazily, at most once. + fingerprintedReplacement := "" idx := 0 systemResult.ForEach(func(_, item gjson.Result) bool { text := item.Get("text") if text.Exists() && text.Type == gjson.String && strings.HasPrefix(text.String(), "x-anthropic-billing-header") { - fingerprintedReplacement := replacement + "." + computeClaudeCodeFingerprint(body, version) + if fingerprintedReplacement == "" { + fingerprintedReplacement = replacement + "." + computeClaudeCodeFingerprint(body, version) + } newText := ccVersionWithFingerprintInBillingRe.ReplaceAllString(text.String(), fingerprintedReplacement) newText = ccVersionInBillingRe.ReplaceAllString(newText, replacement) if newText != text.String() { diff --git a/backend/internal/service/gateway_claude_oauth_body.go b/backend/internal/service/gateway_claude_oauth_body.go index 44e9aaaac1..eb4faac461 100644 --- a/backend/internal/service/gateway_claude_oauth_body.go +++ b/backend/internal/service/gateway_claude_oauth_body.go @@ -307,7 +307,8 @@ func normalizeClaudeOAuthRequestBody(body []byte, modelID string, opts claudeOAu // applyToolNameRewriteToBody 同步映射为假名 // - 其他形态(auto/any/none)原样透传 // 如果 body 里完全没有 tools(空数组),tool_choice 没意义时才删除 - if !gjson.GetBytes(out, "tools").IsArray() || len(gjson.GetBytes(out, "tools").Array()) == 0 { + toolsResult := gjson.GetBytes(out, "tools") + if !toolsResult.IsArray() || !toolsResult.Get("0").Exists() { if !isClaude55SignedThinkingModel(modelID) && gjson.GetBytes(out, "tool_choice").Exists() { if next, ok := deleteJSONPathBytes(out, "tool_choice"); ok { out = next @@ -1059,9 +1060,37 @@ func collectCacheControlPaths(body []byte) (invalidThinking []cacheControlPath, return invalidThinking, messagePaths, toolPaths, systemPaths } +var ( + cacheControlKeyBytes = []byte(`"cache_control"`) + thinkingBlockTypeBytes = []byte(`"thinking"`) + cacheTTL1hJSONBytes = []byte(`"1h"`) + jsonUnicodeEscapeBytes = []byte(`\u`) +) + // enforceCacheControlLimit 让出站 cache_control 满足上游约束: // 先执行块数量限制,再修正 TTL 顺序。 +// +// 大多数请求的 cache_control 块不超过 4 个、没有 thinking 块、也没有 1h TTL, +// 此时两步都是 no-op。用字节级预检查跳过两次 collectCacheControlPaths 遍历。 +// 预检查只会多算(把请求送回原路径),不会漏判;含 \u 转义的 body 可能把 +// 键名或值写成转义形式,字节匹配看不到,因此直接走原路径。 func enforceCacheControlLimit(body []byte) []byte { + if len(body) == 0 { + return body + } + if bytes.Contains(body, jsonUnicodeEscapeBytes) { + return normalizeCacheControlTTLOrder(enforceCacheControlBlockLimit(body)) + } + if !bytes.Contains(body, cacheControlKeyBytes) { + return body + } + if bytes.Count(body, cacheControlKeyBytes) <= maxCacheControlBlocks && + !bytes.Contains(body, thinkingBlockTypeBytes) { + if !bytes.Contains(body, cacheTTL1hJSONBytes) { + return body + } + return normalizeCacheControlTTLOrder(body) + } return normalizeCacheControlTTLOrder(enforceCacheControlBlockLimit(body)) } diff --git a/backend/internal/service/gateway_count_tokens.go b/backend/internal/service/gateway_count_tokens.go index a6a493e25e..4e1c843a92 100644 --- a/backend/internal/service/gateway_count_tokens.go +++ b/backend/internal/service/gateway_count_tokens.go @@ -448,11 +448,11 @@ func (s *GatewayService) buildCountTokensRequestAnthropicAPIKeyPassthrough( // targetURL 的 base 取值),其余保持 extra/default 行为。 setAnthropicAPIKeyAuthHeader(req.Header, account, token, baseURL) - if req.Header.Get("content-type") == "" { - req.Header.Set("content-type", "application/json") + if getHeaderRaw(req.Header, "content-type") == "" { + setHeaderRaw(req.Header, "content-type", "application/json") } - if req.Header.Get("anthropic-version") == "" { - req.Header.Set("anthropic-version", "2023-06-01") + if getHeaderRaw(req.Header, "anthropic-version") == "" { + setHeaderRaw(req.Header, "anthropic-version", "2023-06-01") } // 账号级请求头覆写(最终生效,覆盖上面所有来源的同名头) @@ -614,7 +614,7 @@ func (s *GatewayService) buildCountTokensRequest(ctx context.Context, c *gin.Con filterSonnet55ToolsetBetaHeader(req.Header, body, modelID) if c != nil && tokenType == "oauth" { - c.Set(claudeMimicDebugInfoKey, buildClaudeMimicDebugLine(req, body, account, tokenType, mimicClaudeCode)) + c.Set(claudeMimicDebugInfoKey, newClaudeMimicDebugLine(req, body, account, tokenType, mimicClaudeCode)) } if s.debugClaudeMimicEnabled() { logClaudeMimicDebug(req, body, account, tokenType, mimicClaudeCode) diff --git a/backend/internal/service/gateway_count_tokens_raw_headers_test.go b/backend/internal/service/gateway_count_tokens_raw_headers_test.go new file mode 100644 index 0000000000..04849c25a8 --- /dev/null +++ b/backend/internal/service/gateway_count_tokens_raw_headers_test.go @@ -0,0 +1,87 @@ +//go:build unit + +package service + +import ( + "context" + "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 headerKeysFold(h http.Header, name string) []string { + var keys []string + for k := range h { + if strings.EqualFold(k, name) { + keys = append(keys, k) + } + } + return keys +} + +// The count_tokens passthrough builder copies client headers under their wire casing +// (lowercase content-type / anthropic-version). It must look those up under the same +// key before filling in defaults, so the upstream request carries exactly one of each. +func TestCountTokensPassthroughSendsOneContentTypeAndVersion(t *testing.T) { + tests := []struct { + name string + clientSends bool + wantType string + wantVersion string + }{ + {"client sent both", true, "application/json; charset=utf-8", "2024-01-01"}, + {"client sent neither", false, "application/json", "2023-06-01"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", nil) + if tt.clientSends { + c.Request.Header.Set("Anthropic-Version", tt.wantVersion) + c.Request.Header.Set("Content-Type", tt.wantType) + } + account := &Account{ + ID: 1, + Platform: PlatformAnthropic, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "test-key"}, + Status: StatusActive, + Schedulable: true, + } + svc := &GatewayService{cfg: &config.Config{}} + body := []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hi"}]}`) + + req, err := svc.buildCountTokensRequestAnthropicAPIKeyPassthrough(context.Background(), c, account, body, "test-key") + require.NoError(t, err) + + require.Equal(t, []string{"content-type"}, headerKeysFold(req.Header, "content-type")) + require.Equal(t, []string{tt.wantType}, req.Header["content-type"]) + require.Equal(t, []string{"anthropic-version"}, headerKeysFold(req.Header, "anthropic-version")) + require.Equal(t, []string{tt.wantVersion}, req.Header["anthropic-version"]) + }) + } +} + +// The Claude mimic debug line must report headers stored under their wire casing. +func TestBuildClaudeMimicDebugLineReadsRawCasedHeaders(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, "https://upstream.example/v1/messages", nil) + setHeaderRaw(req.Header, "anthropic-version", "2023-06-01") + setHeaderRaw(req.Header, "anthropic-beta", "beta-a") + setHeaderRaw(req.Header, "content-type", "application/json") + setHeaderRaw(req.Header, "x-app", "cli") + setHeaderRaw(req.Header, "X-Stainless-OS", "Linux") + + line := buildClaudeMimicDebugLine(req, []byte(`{}`), nil, "oauth", true) + + require.Contains(t, line, `anthropic-version="2023-06-01"`) + require.Contains(t, line, `anthropic-beta="beta-a"`) + require.Contains(t, line, `content-type="application/json"`) + require.Contains(t, line, `x-app="cli"`) + require.Contains(t, line, `x-stainless-os="Linux"`) +} diff --git a/backend/internal/service/gateway_forward.go b/backend/internal/service/gateway_forward.go index c74472ce1b..17ce62faa3 100644 --- a/backend/internal/service/gateway_forward.go +++ b/backend/internal/service/gateway_forward.go @@ -53,6 +53,37 @@ func (s *GatewayService) shouldFailoverUpstreamError(statusCode int) bool { } } +// rotatedClaudeAccessToken recovers a token rotated while this request was in +// flight. Compare against the token actually sent, which may have come from the +// cache rather than the account snapshot. Never refresh or persist credentials +// here: an unchanged token must retain the normal 401 policy. +func (s *GatewayService) rotatedClaudeAccessToken(ctx context.Context, account *Account, rejectedToken string) string { + if account == nil || account.Platform != PlatformAnthropic || account.Type != AccountTypeOAuth || + s.accountRepo == nil || rejectedToken == "" || ctx.Err() != nil { + return "" + } + latest, err := s.accountRepo.GetByID(ctx, account.ID) + if err != nil { + slog.Warn("claude_oauth_401_reload_failed", "account_id", account.ID, "error", err) + return "" + } + if latest == nil || latest.Platform != PlatformAnthropic || latest.Type != AccountTypeOAuth || + latest.Status != StatusActive || !latest.Schedulable { + return "" + } + token := strings.TrimSpace(latest.GetCredential("access_token")) + if token == "" || token == rejectedToken { + return "" + } + if p := s.claudeTokenProvider; p != nil && p.tokenCache != nil { + if err := p.tokenCache.DeleteAccessToken(ctx, ClaudeTokenCacheKey(latest)); err != nil { + slog.Warn("claude_oauth_401_invalidate_cache_failed", "account_id", account.ID, "error", err) + } + } + slog.Info("claude_oauth_rotated_token_retry", "account_id", account.ID) + return token +} + func retryBackoffDelay(attempt int) time.Duration { // attempt 从 1 开始,表示第 attempt 次请求刚失败,需要等待后进行第 attempt+1 次请求。 if attempt <= 0 { @@ -387,6 +418,7 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *A var resp *http.Response lastWireBody := body retryStart := time.Now() + retriedRotatedToken := false for attempt := 1; attempt <= maxRetryAttempts; attempt++ { // 构建上游请求(每次重试需要重新构建,因为请求体需要重新读取) upstreamCtx, releaseUpstreamCtx := detachStreamUpstreamContext(ctx, reqStream) @@ -409,6 +441,16 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *A }) } + if resp.StatusCode == http.StatusUnauthorized && !retriedRotatedToken && + attempt < maxRetryAttempts && time.Since(retryStart) < maxRetryElapsed { + if rotatedToken := s.rotatedClaudeAccessToken(ctx, account, token); rotatedToken != "" { + _ = resp.Body.Close() + token = rotatedToken + retriedRotatedToken = true + continue + } + } + // 优先检测thinking block签名错误(400)并重试一次 if resp.StatusCode == 400 { respBody, readErr := s.readUpstreamErrorBody(resp) diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index a1f9786719..565ec4a069 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -94,6 +94,10 @@ func (s *GatewayService) ForwardAsChatCompletions( if err != nil { return nil, fmt.Errorf("marshal anthropic request: %w", err) } + if !account.IsOAuth() { + // OAuth accounts get their id from the mimicry below. + anthropicBody = withChatCompletionsMetadataUserID(body, anthropicBody) + } // 6. Apply Claude Code mimicry for OAuth accounts. // Chat Completions 协议进来的请求永远不是 Claude Code 客户端,所以对 OAuth 账号 @@ -122,30 +126,43 @@ func (s *GatewayService) ForwardAsChatCompletions( proxyURL = account.Proxy.URL() } - // 10. Build upstream request - upstreamCtx, releaseUpstreamCtx := detachStreamUpstreamContext(ctx, reqStream) - upstreamReq, forwardedBody, err := s.buildUpstreamRequest(upstreamCtx, c, account, anthropicBody, token, tokenType, mappedModel, reqStream, shouldMimicClaudeCode) - releaseUpstreamCtx() - if err != nil { - return nil, fmt.Errorf("build upstream request: %w", err) + // 10. Build and send the request, recovering a concurrent token rotation once. + var upstreamReq *http.Request + var forwardedBody []byte + var resp *http.Response + for retriedRotatedToken := false; ; { + upstreamCtx, releaseUpstreamCtx := detachStreamUpstreamContext(ctx, reqStream) + upstreamReq, forwardedBody, err = s.buildUpstreamRequest(upstreamCtx, c, account, anthropicBody, token, tokenType, mappedModel, reqStream, shouldMimicClaudeCode) + releaseUpstreamCtx() + if err != nil { + return nil, fmt.Errorf("build upstream request: %w", err) + } + resp, err = s.httpUpstream.DoWithTLS(upstreamReq, proxyURL, account.ID, account.Concurrency, s.tlsFPProfileService.ResolveTLSProfile(account)) + if err != nil { + if resp != nil && resp.Body != nil { + _ = resp.Body.Close() + } + return nil, s.handleUpstreamTransportError(ctx, c, account, err, OpsUpstreamErrorEvent{ + UpstreamURL: safeUpstreamURL(upstreamReq.URL.String()), + }) + } + if resp.StatusCode == http.StatusUnauthorized && !retriedRotatedToken { + if rotatedToken := s.rotatedClaudeAccessToken(ctx, account, token); rotatedToken != "" { + _ = resp.Body.Close() + token = rotatedToken + retriedRotatedToken = true + continue + } + } + break } + defer func() { _ = resp.Body.Close() }() + // Bill the final Anthropic effort after conversion and account normalization. // For example, OpenAI xhigh is forwarded as output_config.effort=max. reasoningEffort := NormalizeClaudeOutputEffort(gjson.GetBytes(forwardedBody, "output_config.effort").String()) reasoningEffort = ApplyThinkingEnabledFallback(reasoningEffort, forwardedBody, mappedModel) - // 11. Send request - resp, err := s.httpUpstream.DoWithTLS(upstreamReq, proxyURL, account.ID, account.Concurrency, s.tlsFPProfileService.ResolveTLSProfile(account)) - if err != nil { - if resp != nil && resp.Body != nil { - _ = resp.Body.Close() - } - return nil, s.handleUpstreamTransportError(ctx, c, account, err, OpsUpstreamErrorEvent{ - UpstreamURL: safeUpstreamURL(upstreamReq.URL.String()), - }) - } - defer func() { _ = resp.Body.Close() }() - // 12. Handle error response with failover if resp.StatusCode >= 400 { respBody, _ := s.readUpstreamErrorBody(resp) @@ -236,6 +253,7 @@ func (s *GatewayService) handleCCBufferedFromAnthropic( reasoningEffort *string, startTime time.Time, ) (*ForwardResult, error) { + observer := beginUpstreamResponseModelObservation(c) requestID := resp.Header.Get("x-request-id") scanner := bufio.NewScanner(resp.Body) @@ -271,6 +289,7 @@ func (s *GatewayService) handleCCBufferedFromAnthropic( continue } + observer.ObserveAnthropic([]byte(payload)) streamStatus.observe(&event, payload) if streamStatus.upstreamErrType != "" { break @@ -323,7 +342,10 @@ func (s *GatewayService) handleCCBufferedFromAnthropic( _ = resp.Body.Close() writeGatewayCCError(c, http.StatusBadGateway, "server_error", failure.message) return &ForwardResult{ - RequestID: requestID, UpstreamHeaders: resp.Header, Usage: usage, + UpstreamResponseModel: observer.Model(), + UpstreamResponseModelConflict: observer.Conflict(), + UpstreamResponseServiceTier: observer.ServiceTier(), + RequestID: requestID, UpstreamHeaders: resp.Header, Usage: usage, Model: originalModel, UpstreamModel: mappedModel, ReasoningEffort: reasoningEffort, Duration: time.Since(startTime), }, failure.err @@ -367,14 +389,17 @@ func (s *GatewayService) handleCCBufferedFromAnthropic( } return &ForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: usage, - Model: originalModel, - UpstreamModel: mappedModel, - ReasoningEffort: reasoningEffort, - Stream: false, - Duration: time.Since(startTime), + UpstreamResponseModel: observer.Model(), + UpstreamResponseModelConflict: observer.Conflict(), + UpstreamResponseServiceTier: observer.ServiceTier(), + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: usage, + Model: originalModel, + UpstreamModel: mappedModel, + ReasoningEffort: reasoningEffort, + Stream: false, + Duration: time.Since(startTime), }, nil } @@ -388,6 +413,7 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( reasoningEffort *string, startTime time.Time, ) (*ForwardResult, error) { + observer := beginUpstreamResponseModelObservation(c) requestID := resp.Header.Get("x-request-id") if s.responseHeaderFilter != nil { @@ -415,16 +441,19 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( resultWithUsage := func() *ForwardResult { return &ForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: usage, - Model: originalModel, - UpstreamModel: mappedModel, - ReasoningEffort: reasoningEffort, - Stream: true, - Duration: time.Since(startTime), - FirstTokenMs: firstTokenMs, - ClientDisconnect: stream.clientDisconnected, + UpstreamResponseModel: observer.Model(), + UpstreamResponseModelConflict: observer.Conflict(), + UpstreamResponseServiceTier: observer.ServiceTier(), + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: usage, + Model: originalModel, + UpstreamModel: mappedModel, + ReasoningEffort: reasoningEffort, + Stream: true, + Duration: time.Since(startTime), + FirstTokenMs: firstTokenMs, + ClientDisconnect: stream.clientDisconnected, } } @@ -435,7 +464,7 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( } // Reverse tool name mapping: fake → real, per-chunk bytes.Replace. // c 可能持有请求侧注入的 ToolNameRewrite;无则仅做静态前缀还原。 - out := string(reverseToolNamesIfPresent(c, []byte(sse))) + out := reverseToolNamesIfPresentString(c, sse) if _, err := fmt.Fprint(c.Writer, out); err != nil { return true // client disconnected } @@ -522,6 +551,7 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( // The intermediate Responses converter synthesizes usage even when absent. ccState.IncludeUsage = ccState.IncludeUsage || anthropicChatStreamHasUsage(&event, payload) + observer.ObserveAnthropic([]byte(payload)) stream.observe(&event, payload) if stream.upstreamErrType != "" { break diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index db10be2568..93c3f62239 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -133,30 +133,43 @@ func (s *GatewayService) ForwardAsResponses( proxyURL = account.Proxy.URL() } - // 10. Build upstream request - upstreamCtx, releaseUpstreamCtx := detachStreamUpstreamContext(ctx, reqStream) - upstreamReq, forwardedBody, err := s.buildUpstreamRequest(upstreamCtx, c, account, anthropicBody, token, tokenType, mappedModel, reqStream, shouldMimicClaudeCode) - releaseUpstreamCtx() - if err != nil { - return nil, fmt.Errorf("build upstream request: %w", err) + // 10. Build and send the request, recovering a concurrent token rotation once. + var upstreamReq *http.Request + var forwardedBody []byte + var resp *http.Response + for retriedRotatedToken := false; ; { + upstreamCtx, releaseUpstreamCtx := detachStreamUpstreamContext(ctx, reqStream) + upstreamReq, forwardedBody, err = s.buildUpstreamRequest(upstreamCtx, c, account, anthropicBody, token, tokenType, mappedModel, reqStream, shouldMimicClaudeCode) + releaseUpstreamCtx() + if err != nil { + return nil, fmt.Errorf("build upstream request: %w", err) + } + resp, err = s.httpUpstream.DoWithTLS(upstreamReq, proxyURL, account.ID, account.Concurrency, s.tlsFPProfileService.ResolveTLSProfile(account)) + if err != nil { + if resp != nil && resp.Body != nil { + _ = resp.Body.Close() + } + return nil, s.handleUpstreamTransportError(ctx, c, account, err, OpsUpstreamErrorEvent{ + UpstreamURL: safeUpstreamURL(upstreamReq.URL.String()), + }) + } + if resp.StatusCode == http.StatusUnauthorized && !retriedRotatedToken { + if rotatedToken := s.rotatedClaudeAccessToken(ctx, account, token); rotatedToken != "" { + _ = resp.Body.Close() + token = rotatedToken + retriedRotatedToken = true + continue + } + } + break } + defer func() { _ = resp.Body.Close() }() + // Bill the final Anthropic effort after conversion and account normalization. // For example, OpenAI xhigh is forwarded as output_config.effort=max. reasoningEffort := NormalizeClaudeOutputEffort(gjson.GetBytes(forwardedBody, "output_config.effort").String()) reasoningEffort = ApplyThinkingEnabledFallback(reasoningEffort, forwardedBody, mappedModel) - // 11. Send request - resp, err := s.httpUpstream.DoWithTLS(upstreamReq, proxyURL, account.ID, account.Concurrency, s.tlsFPProfileService.ResolveTLSProfile(account)) - if err != nil { - if resp != nil && resp.Body != nil { - _ = resp.Body.Close() - } - return nil, s.handleUpstreamTransportError(ctx, c, account, err, OpsUpstreamErrorEvent{ - UpstreamURL: safeUpstreamURL(upstreamReq.URL.String()), - }) - } - defer func() { _ = resp.Body.Close() }() - // 12. Handle error response with failover if resp.StatusCode >= 400 { respBody, _ := s.readUpstreamErrorBody(resp) @@ -385,6 +398,7 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse( startTime time.Time, clientToolMapping apicompat.ResponsesClientToolMapping, ) (*ForwardResult, error) { + observer := beginUpstreamResponseModelObservation(c) requestID := resp.Header.Get("x-request-id") scanner := bufio.NewScanner(resp.Body) @@ -427,6 +441,7 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse( continue } + observer.ObserveAnthropic([]byte(payload)) streamStatus.observe(&event, payload) if streamStatus.upstreamErrType != "" { break @@ -483,7 +498,10 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse( _ = resp.Body.Close() writeResponsesError(c, http.StatusBadGateway, "server_error", failure.message) return &ForwardResult{ - RequestID: requestID, UpstreamHeaders: resp.Header, Usage: usage, + UpstreamResponseModel: observer.Model(), + UpstreamResponseModelConflict: observer.Conflict(), + UpstreamResponseServiceTier: observer.ServiceTier(), + RequestID: requestID, UpstreamHeaders: resp.Header, Usage: usage, Model: originalModel, UpstreamModel: mappedModel, ReasoningEffort: reasoningEffort, Duration: time.Since(startTime), }, failure.err @@ -532,14 +550,17 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse( } return &ForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: usage, - Model: originalModel, - UpstreamModel: mappedModel, - ReasoningEffort: reasoningEffort, - Stream: false, - Duration: time.Since(startTime), + UpstreamResponseModel: observer.Model(), + UpstreamResponseModelConflict: observer.Conflict(), + UpstreamResponseServiceTier: observer.ServiceTier(), + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: usage, + Model: originalModel, + UpstreamModel: mappedModel, + ReasoningEffort: reasoningEffort, + Stream: false, + Duration: time.Since(startTime), }, nil } @@ -554,6 +575,7 @@ func (s *GatewayService) handleResponsesStreamingResponse( startTime time.Time, clientToolMapping apicompat.ResponsesClientToolMapping, ) (*ForwardResult, error) { + observer := beginUpstreamResponseModelObservation(c) requestID := resp.Header.Get("x-request-id") if s.responseHeaderFilter != nil { @@ -579,16 +601,19 @@ func (s *GatewayService) handleResponsesStreamingResponse( resultWithUsage := func() *ForwardResult { return &ForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: usage, - Model: originalModel, - UpstreamModel: mappedModel, - ReasoningEffort: reasoningEffort, - Stream: true, - Duration: time.Since(startTime), - FirstTokenMs: firstTokenMs, - ClientDisconnect: stream.clientDisconnected, + UpstreamResponseModel: observer.Model(), + UpstreamResponseModelConflict: observer.Conflict(), + UpstreamResponseServiceTier: observer.ServiceTier(), + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: usage, + Model: originalModel, + UpstreamModel: mappedModel, + ReasoningEffort: reasoningEffort, + Stream: true, + Duration: time.Since(startTime), + FirstTokenMs: firstTokenMs, + ClientDisconnect: stream.clientDisconnected, } } @@ -666,7 +691,7 @@ func (s *GatewayService) handleResponsesStreamingResponse( if err != nil { continue } - out := string(reverseToolNamesIfPresent(c, []byte(sse))) + out := reverseToolNamesIfPresentString(c, sse) fmt.Fprint(c.Writer, out) //nolint:errcheck } c.Writer.Flush() @@ -705,6 +730,7 @@ func (s *GatewayService) handleResponsesStreamingResponse( continue } + observer.ObserveAnthropic([]byte(payload)) stream.observe(&event, payload) if stream.upstreamErrType != "" { break diff --git a/backend/internal/service/gateway_mid_conversation_output_config_test.go b/backend/internal/service/gateway_mid_conversation_output_config_test.go index d551fae785..2c563c1778 100644 --- a/backend/internal/service/gateway_mid_conversation_output_config_test.go +++ b/backend/internal/service/gateway_mid_conversation_output_config_test.go @@ -5,8 +5,10 @@ package service import ( "bytes" "context" + "io" "net/http" "net/http/httptest" + "strings" "testing" "github.com/Wei-Shaw/sub2api/internal/config" @@ -17,7 +19,7 @@ import ( ) // ============================================================================ -// message-level output_config ↔ mid-conversation-output-config beta +// message-level output_config ↔ mid-conversation-output-config / per-turn-control beta // ============================================================================ // // 背景:pi-ai(Harness 使用的 Anthropic provider)会为 opus5 生成形如 @@ -32,11 +34,11 @@ import ( // "output_config: Extra inputs are not permitted" // // 修复策略(剥字段,不注入 beta): -// - header 缺该 token:仅为携带 message-level output_config 的消息剥此字段; +// - header 缺这两种 token:仅为携带 message-level output_config 的消息剥此字段; // role=system 且 content 无正文(缺失 / null / 空 string / 空 array / 仅空 // text 块)时整条删除;system 有正文保留正文与其余字段;user/assistant 只剥 // 字段,绝不整条删除。 -// - header 含该 token:完全保留。 +// - header 含任一 token:完全保留。 // - 无任何 message-level output_config:字节 no-op。 // - 顶层 output_config / effort 不受该 beta 约束,本增量不触碰。 // @@ -154,10 +156,120 @@ func TestSanitizeAnthropicBodyForBetaTokens_MidConversationOutputConfig_SystemWi // header 含该 beta → 完全保留,字节 no-op(即使是空控制 system 消息)。 func TestSanitizeAnthropicBodyForBetaTokens_MidConversationOutputConfig_ByteNoopWhenBetaPresent(t *testing.T) { body := []byte(`{"model":"claude-opus-5","output_config":{"effort":"high"},"messages":[{"role":"system","content":[],"output_config":{"effort":"high"}},{"role":"user","content":"hi"}]}`) - out, changed := sanitizeAnthropicBodyForBetaTokens(body, - "claude-code-20250219,oauth-2025-04-20,"+claude.BetaMidConversationOutputConfig) - require.False(t, changed, "header 含 mid-conversation-output-config beta → 完全保留") - require.True(t, bytes.Equal(body, out), "含 beta 时必须字节 no-op") + for _, beta := range []string{ + claude.BetaMidConversationOutputConfig, + "per-turn-control-2026-07-01", + "per-turn-control-2026-07-01," + claude.BetaMidConversationOutputConfig, + } { + t.Run(beta, func(t *testing.T) { + out, changed := sanitizeAnthropicBodyForBetaTokens(body, "claude-code-20250219, "+beta+" ") + require.False(t, changed, "a supported beta must preserve message-level output_config") + require.True(t, bytes.Equal(body, out), "含 beta 时必须字节 no-op") + }) + } +} + +func TestForward_PerTurnControlMessageOutputConfig(t *testing.T) { + gin.SetMode(gin.TestMode) + const perTurnBeta = "per-turn-control-2026-07-01" + const body = `{"model":"claude-opus-5","max_tokens":256,"output_config":{"effort":"high"},` + + `"metadata":{"user_id":"user_a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2_account_550e8400-e29b-41d4-a716-446655440000_session_123e4567-e89b-12d3-a456-426614174000"},` + + `"messages":[{"role":"user","content":"Hello"},{"role":"assistant","content":"Hi"},` + + `{"role":"system","content":[],"output_config":{"effort":"low"}},` + + `{"role":"user","content":"Summarize that in one sentence."}]}` + for _, mode := range []string{"oauth_claude_code", "oauth_mimic", "apikey", "apikey_passthrough"} { + for _, withBeta := range []bool{true, false} { + name := "without_beta" + if withBeta { + name = "with_beta" + } + t.Run(mode+"/"+name, func(t *testing.T) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body)) + c.Request.Header.Set("User-Agent", "claude-cli/2.1.321") + if mode == "oauth_mimic" { + c.Request.Header.Set("User-Agent", "third-party-client/1.0") + } + if withBeta { + c.Request.Header.Set("Anthropic-Beta", "claude-code-20250219,"+perTurnBeta) + } + account := newAnthropicAPIKeyAccountForTest() + account.Extra["anthropic_passthrough"] = mode == "apikey_passthrough" + if strings.HasPrefix(mode, "oauth") { + account = newAnthropicOAuthAccountForPartialUsageTest() + } + upstream := &anthropicHTTPUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"id":"msg_test","type":"message","role":"assistant",` + + `"model":"claude-opus-5","content":[{"type":"text","text":"OK"}],"stop_reason":"end_turn",` + + `"usage":{"input_tokens":10,"output_tokens":1}}`)), + }} + parsed, err := ParseGatewayRequest(NewRequestBodyRef([]byte(body)), PlatformAnthropic) + require.NoError(t, err) + svc := newForwardPartialUsageServiceForTest(upstream) + _, err = svc.Forward(context.Background(), c, account, parsed) + require.NoError(t, err) + require.NotNil(t, upstream.lastReq) + + beta := getHeaderRaw(upstream.lastReq.Header, "anthropic-beta") + require.Equal(t, withBeta && mode != "oauth_mimic", anthropicBetaTokensContains(beta, perTurnBeta)) + wantControl := withBeta || mode == "oauth_mimic" + messages := gjson.GetBytes(upstream.lastBody, "messages").Array() + if wantControl { + require.Len(t, messages, 4) + require.Equal(t, "system", messages[2].Get("role").String()) + require.Equal(t, "[]", messages[2].Get("content").Raw) + require.Equal(t, "low", messages[2].Get("output_config.effort").String()) + } else { + require.Len(t, messages, 3) + } + require.Equal(t, "Hello", messages[0].Get("content").String()) + require.Equal(t, "Hi", messages[1].Get("content").String()) + require.Equal(t, "Summarize that in one sentence.", messages[len(messages)-1].Get("content").String()) + require.Equal(t, "high", gjson.GetBytes(upstream.lastBody, "output_config.effort").String()) + }) + } + } +} + +func TestBuildUpstreamRequest_PerTurnControlPolicyFilter(t *testing.T) { + gin.SetMode(gin.TestMode) + const perTurnBeta = "per-turn-control-2026-07-01" + const midConversationBeta = "mid-conversation-output-config-2026-07-01" + body := []byte(`{"model":"claude-opus-5","messages":[{"role":"user","content":"Hello"},` + + `{"role":"system","content":[],"output_config":{"effort":"low"}}]}`) + for _, tc := range []struct { + name string + drop []string + keep bool + }{ + {"drop_per_turn_only", []string{perTurnBeta}, true}, + {"drop_mid_conversation_only", []string{midConversationBeta}, true}, + {"drop_both", []string{perTurnBeta, midConversationBeta}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + c.Request.Header.Set("Anthropic-Beta", "claude-code-20250219,"+perTurnBeta+","+midConversationBeta) + c.Set(betaPolicyFilterSetKey, buildBetaTokenSet(tc.drop)) + svc := &GatewayService{cfg: &config.Config{}} + req, _, err := svc.buildUpstreamRequest(context.Background(), c, + newAnthropicOAuthAccountForPartialUsageTest(), body, + "oauth-token", "oauth", "claude-opus-5", false, false) + require.NoError(t, err) + for _, token := range tc.drop { + require.False(t, anthropicBetaTokensContains(getHeaderRaw(req.Header, "anthropic-beta"), token)) + } + out := readUpstreamBodyForTest(t, req) + require.Equal(t, tc.keep, gjson.GetBytes(out, "messages.1.output_config").Exists()) + if tc.keep { + require.Equal(t, "low", gjson.GetBytes(out, "messages.1.output_config.effort").String()) + } else { + require.Len(t, gjson.GetBytes(out, "messages").Array(), 1) + } + }) + } } // 无 message-level output_config(仅有顶层 output_config,或完全没有)→ 字节 no-op。 diff --git a/backend/internal/service/gateway_multiplatform_test.go b/backend/internal/service/gateway_multiplatform_test.go index badb2427cf..de8fc0c7fa 100644 --- a/backend/internal/service/gateway_multiplatform_test.go +++ b/backend/internal/service/gateway_multiplatform_test.go @@ -156,7 +156,10 @@ func (m *mockAccountRepoForPlatform) ListSchedulableUngroupedByPlatform(ctx cont func (m *mockAccountRepoForPlatform) ListSchedulableUngroupedByPlatforms(ctx context.Context, platforms []string) ([]Account, error) { return m.ListSchedulableByPlatforms(ctx, platforms) } -func (m *mockAccountRepoForPlatform) ListModelAvailabilityCandidates(_ context.Context, groupID *int64, platforms []string, includeGrouped bool) ([]Account, error) { +func (m *mockAccountRepoForPlatform) ListModelAvailabilityCandidates(ctx context.Context, groupID *int64, platforms []string, includeGrouped bool) ([]Account, error) { + if m.listPlatformFunc != nil { + return m.listPlatformFunc(ctx, firstPlatform(platforms)) + } platformSet := make(map[string]struct{}, len(platforms)) for _, platform := range platforms { platformSet[platform] = struct{}{} @@ -208,6 +211,10 @@ func (m *mockAccountRepoForPlatform) ClearAntigravityQuotaScopes(ctx context.Con func (m *mockAccountRepoForPlatform) ClearModelRateLimits(ctx context.Context, id int64) error { return nil } + +func (m *mockAccountRepoForPlatform) ClearModelRateLimit(ctx context.Context, id int64, scope string) error { + return nil +} func (m *mockAccountRepoForPlatform) UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error { return nil } diff --git a/backend/internal/service/gateway_record_usage_test.go b/backend/internal/service/gateway_record_usage_test.go index 9dfa556298..d97aad6af8 100644 --- a/backend/internal/service/gateway_record_usage_test.go +++ b/backend/internal/service/gateway_record_usage_test.go @@ -362,6 +362,8 @@ func TestGatewayServiceRecordUsage_PeakRateAffectsTokenModeImageOutputTokens(t * }, User: &User{ID: 602}, Account: &Account{ID: 702}, + // The peak window excludes 23:59, so do not depend on the wall clock. + PricingAt: time.Date(2026, time.January, 15, 12, 0, 0, 0, time.UTC), }) require.NoError(t, err) diff --git a/backend/internal/service/gateway_request.go b/backend/internal/service/gateway_request.go index 95dfb069a3..2abbe5e1a8 100644 --- a/backend/internal/service/gateway_request.go +++ b/backend/internal/service/gateway_request.go @@ -1085,8 +1085,9 @@ const anthropicBetaContextManagementToken = "context-management-2025-06-27" // - pi-ai(Harness 使用的 Anthropic provider)会为 opus5 生成形如 // `{"role":"system","content":[],"output_config":{"effort":"high"}}` 的控制消息, // 并请求 `mid-conversation-output-config-2026-07-01` beta -// - 该 output_config 是 **message 级**字段,只有该 beta 保护;顶层 output_config/effort -// 不受它约束 +// - Claude Code 也会以 `per-turn-control-2026-07-01` 请求该能力 +// - 该 output_config 是 **message 级**字段,由上述任一 beta 保护;顶层 output_config/effort +// 不受它们约束 // - OAuth mimic 用 FullClaudeCodeMimicryBetas 覆盖客户端 beta;固定列表漏该 beta 时 // body 字段与 header 不对称 → 上游报 "output_config: Extra inputs are not permitted" // - 缺 token 时净化消息级 output_config(详见 stripAnthropicMessageOutputConfigUnlessBeta) @@ -1137,7 +1138,7 @@ func sanitizeAnthropicBodyForBetaTokens(body []byte, anthropicBetaHeader string) body, changed = b, true } - // messages[].output_config:mid-conversation-output-config beta 专属字段。 + // messages[].output_config:需要 mid-conversation-output-config 或 per-turn-control beta。 // 顶层 output_config / effort 不受该 beta 约束,本分支只净化消息内字段。 if b, deleted := stripAnthropicMessageOutputConfigUnlessBeta(body, anthropicBetaHeader); deleted { body, changed = b, true @@ -1186,17 +1187,18 @@ func anthropicBetaTokensContains(header, token string) bool { } // stripAnthropicMessageOutputConfigUnlessBeta 在 anthropic-beta header 缺 -// mid-conversation-output-config beta 时,净化 **messages[].output_config**: +// mid-conversation-output-config 和 per-turn-control 两种 beta 时,净化 **messages[].output_config**: // - 仅为携带 message-level output_config 的消息剥该字段; // - 若该消息 role=system 且 content 无正文(缺失 / null / 空 string / 空 array / // 仅空 text 块),整条删除(pi-ai 为 opus5 生成的空 system 控制消息即此形态); // - system 有正文则保留正文与其余字段;user/assistant 只剥字段,绝不整条删除; // - 无任何消息携带该字段时返回原 body(字节 no-op)。 // -// header 含该 beta 时完全保留。顶层 output_config / effort 不属于该 beta 保护范围, +// header 含任一 beta 时完全保留。顶层 output_config / effort 不属于这些 beta 保护范围, // 本函数不做任何处理。多条删除用「稳健重建」实现,保留其余字段与消息先后顺序。 func stripAnthropicMessageOutputConfigUnlessBeta(body []byte, anthropicBetaHeader string) ([]byte, bool) { - if anthropicBetaTokensContains(anthropicBetaHeader, claude.BetaMidConversationOutputConfig) { + if anthropicBetaTokensContains(anthropicBetaHeader, claude.BetaMidConversationOutputConfig) || + anthropicBetaTokensContains(anthropicBetaHeader, claude.BetaPerTurnControl) { return body, false } // 快速路径:body 中不含 output_config 字面量时无需解析。 diff --git a/backend/internal/service/gateway_request_json_bench_test.go b/backend/internal/service/gateway_request_json_bench_test.go new file mode 100644 index 0000000000..d56064a09c --- /dev/null +++ b/backend/internal/service/gateway_request_json_bench_test.go @@ -0,0 +1,133 @@ +package service + +import ( + "fmt" + "net/http" + "strings" + "testing" +) + +// claudeCodeLikeBody builds a ~32KB request shaped like a Claude Code turn: +// 20 tools, a system prompt, and 40 messages with 4 content blocks each. +func claudeCodeLikeBody(cacheControls int, with1h bool) []byte { + var b strings.Builder + _, _ = b.WriteString(`{"model":"claude-sonnet-5-5","max_tokens":32000,"stream":true,"tools":[`) + for i := 0; i < 20; i++ { + if i > 0 { + _ = b.WriteByte(',') + } + fmt.Fprintf(&b, `{"name":"tool_%d","description":"%s","input_schema":{"type":"object","properties":{"path":{"type":"string"}}}`, i, strings.Repeat("d", 40)) + if i == 19 && cacheControls > 0 { + _, _ = b.WriteString(`,"cache_control":{"type":"ephemeral"}`) + cacheControls-- + } + _ = b.WriteByte('}') + } + _, _ = b.WriteString(`],"system":[{"type":"text","text":"You are Claude Code, Anthropic's official CLI for Claude."`) + if cacheControls > 0 { + _, _ = b.WriteString(`,"cache_control":{"type":"ephemeral"}`) + cacheControls-- + } + _, _ = b.WriteString(`}],"messages":[`) + for m := 0; m < 40; m++ { + if m > 0 { + _ = b.WriteByte(',') + } + role := "user" + if m%2 == 1 { + role = "assistant" + } + fmt.Fprintf(&b, `{"role":%q,"content":[`, role) + for c := 0; c < 4; c++ { + if c > 0 { + _ = b.WriteByte(',') + } + fmt.Fprintf(&b, `{"type":"text","text":"%s"`, strings.Repeat("x", 120)) + if m >= 38 && c == 3 && cacheControls > 0 { + ttl := "" + if with1h && m == 39 { + ttl = `,"ttl":"1h"` + } + fmt.Fprintf(&b, `,"cache_control":{"type":"ephemeral"%s}`, ttl) + cacheControls-- + } + _ = b.WriteByte('}') + } + _, _ = b.WriteString(`]}`) + } + _, _ = b.WriteString(`]}`) + return []byte(b.String()) +} + +func BenchmarkEnforceCacheControlLimit(b *testing.B) { + cases := []struct { + name string + body []byte + }{ + {"common_4cc_no1h", claudeCodeLikeBody(4, false)}, + {"with_1h", claudeCodeLikeBody(4, true)}, + } + for _, tc := range cases { + b.Run(tc.name+"/legacy", func(b *testing.B) { + b.SetBytes(int64(len(tc.body))) + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _ = legacyEnforceCacheControlLimit(tc.body) + } + }) + b.Run(tc.name+"/optimized", func(b *testing.B) { + b.SetBytes(int64(len(tc.body))) + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _ = enforceCacheControlLimit(tc.body) + } + }) + } +} + +func BenchmarkRequestToolHelpers(b *testing.B) { + body := claudeCodeLikeBody(4, false) + b.Run("legacy", func(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _ = legacyRequestNeedsBetaFeatures(body) + _ = legacyFilterSonnet55ToolsetBeta("fine-grained-tool-streaming-2025-05-14", body, "claude-sonnet-5-5") + _ = legacyIsOnlyWebSearchToolInBody(body) + _ = legacyBuildToolNameRewriteFromBody(body) + _ = legacyApplyToolsLastCacheBreakpoint(body) + _ = legacyExtractSystemPreviewFromBody(body) + } + }) + b.Run("optimized", func(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _ = requestNeedsBetaFeatures(body) + _ = filterSonnet55ToolsetBeta("fine-grained-tool-streaming-2025-05-14", body, "claude-sonnet-5-5") + _ = isOnlyWebSearchToolInBody(body) + _ = buildToolNameRewriteFromBody(body) + _ = applyToolsLastCacheBreakpoint(body) + _ = extractSystemPreviewFromBody(body) + } + }) +} + +func BenchmarkClaudeMimicDebugLine(b *testing.B) { + req, _ := http.NewRequest(http.MethodPost, "https://api.anthropic.com/v1/messages?beta=true", nil) + for _, h := range []string{"User-Agent", "X-App", "Anthropic-Version", "Anthropic-Beta", "X-Stainless-Lang", "X-Stainless-Os", "Authorization", "Content-Type", "Accept"} { + req.Header.Set(h, "value-"+h) + } + body := claudeCodeLikeBody(4, false) + account := &Account{ID: 1, Name: "acc"} + b.Run("eager", func(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _ = buildClaudeMimicDebugLine(req, body, account, "oauth", true) + } + }) + b.Run("lazy_unused", func(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _ = newClaudeMimicDebugLine(req, body, account, "oauth", true) + } + }) +} diff --git a/backend/internal/service/gateway_request_json_equivalence_test.go b/backend/internal/service/gateway_request_json_equivalence_test.go new file mode 100644 index 0000000000..e8fc31be32 --- /dev/null +++ b/backend/internal/service/gateway_request_json_equivalence_test.go @@ -0,0 +1,424 @@ +package service + +import ( + "bytes" + "fmt" + "math/rand" + "net/http" + "strings" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// legacyEnforceCacheControlLimit / legacyNormalizeCacheControlTTLOrder / +// legacyForceEphemeralCacheControlTTL are verbatim copies of the +// implementations before the fast path was introduced. The tests below compare +// the optimized code against them byte for byte. +func legacyEnforceCacheControlLimit(body []byte) []byte { + return legacyNormalizeCacheControlTTLOrder(enforceCacheControlBlockLimit(body)) +} + +func legacyNormalizeCacheControlTTLOrder(body []byte) []byte { + _, messagePaths, toolPaths, systemPaths := collectCacheControlPaths(body) + paths := make([]string, 0, len(toolPaths)+len(systemPaths)+len(messagePaths)+1) + paths = append(paths, toolPaths...) + paths = append(paths, systemPaths...) + paths = append(paths, messagePaths...) + if gjson.GetBytes(body, "cache_control").Exists() { + paths = append(paths, "cache_control") + } + last1h := -1 + for i, path := range paths { + if gjson.GetBytes(body, path+".ttl").String() == cacheTTLTarget1h { + last1h = i + } + } + out := body + for _, path := range paths[:last1h+1] { + cc := gjson.GetBytes(out, path) + if cc.Get("type").String() != "ephemeral" || cc.Get("ttl").String() == cacheTTLTarget1h { + continue + } + if next, err := sjson.SetBytes(out, path+".ttl", cacheTTLTarget1h); err == nil { + out = next + } + } + return out +} + +func cacheControlEquivalenceCases() map[string]string { + return map[string]string{ + "empty": ``, + "no_cc": `{"model":"claude","messages":[{"role":"user","content":"hi"}]}`, + "one_cc": `{"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":"hi"}]}`, + "four_cc": `{"tools":[{"name":"a","cache_control":{"type":"ephemeral"}}],"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral"}},{"type":"text","text":"b","cache_control":{"type":"ephemeral"}}]}]}`, + "five_cc": `{"tools":[{"name":"a","cache_control":{"type":"ephemeral"}},{"name":"b","cache_control":{"type":"ephemeral"}}],"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral"}},{"type":"text","text":"b","cache_control":{"type":"ephemeral"}}]}]}`, + "thinking_cc": `{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"x","cache_control":{"type":"ephemeral"}}]}]}`, + "thinking_text": `{"messages":[{"role":"user","content":[{"type":"text","text":"thinking about it","cache_control":{"type":"ephemeral"}}]}]}`, + "ttl_order": `{"tools":[{"name":"a","cache_control":{"type":"ephemeral","ttl":"5m"}}],"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`, + "ttl_all_1h": `{"tools":[{"name":"a","cache_control":{"type":"ephemeral","ttl":"1h"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`, + "top_level_1h": `{"cache_control":{"type":"ephemeral","ttl":"1h"},"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":"hi"}]}`, + "1h_in_text": `{"system":[{"type":"text","text":"\"1h\"","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":"1h"}]}`, + "escaped_key": `{"messages":[{"role":"user","content":[{"type":"text","text":"a","cache\u005fcontrol":{"type":"ephemeral","ttl":"1h"}}]}],"tools":[{"name":"t","cache_control":{"type":"ephemeral"}}]}`, + "escaped_ttl": `{"tools":[{"name":"t","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral","ttl":"\u0031h"}}]}]}`, + "escaped_think": `{"messages":[{"role":"assistant","content":[{"type":"\u0074hinking","thinking":"x","cache_control":{"type":"ephemeral"}}]}]}`, + "non_ephemeral": `{"tools":[{"name":"a","cache_control":{"type":"persistent"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`, + "cc_in_string": `{"messages":[{"role":"user","content":"please explain \"cache_control\" and \"thinking\""}]}`, + "duplicate_key": `{"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral"},"cache_control":{"type":"ephemeral","ttl":"1h"}}]}],"tools":[{"name":"t","cache_control":{"type":"ephemeral"}}]}`, + "invalid_json": `{"messages":[`, + } +} + +func TestEnforceCacheControlLimitMatchesLegacy(t *testing.T) { + for name, raw := range cacheControlEquivalenceCases() { + t.Run(name, func(t *testing.T) { + body := []byte(raw) + want := legacyEnforceCacheControlLimit(append([]byte(nil), body...)) + got := enforceCacheControlLimit(append([]byte(nil), body...)) + require.Equal(t, string(want), string(got)) + }) + } +} + +func TestEnforceCacheControlLimitMatchesLegacyRandomized(t *testing.T) { + rng := rand.New(rand.NewSource(20261111)) + for i := 0; i < 3000; i++ { + body := randomCacheControlBody(rng) + want := legacyEnforceCacheControlLimit(append([]byte(nil), body...)) + got := enforceCacheControlLimit(append([]byte(nil), body...)) + require.Equal(t, string(want), string(got), "case %d body=%s", i, body) + } +} + +func TestEnforceCacheControlLimitDoesNotMutateInput(t *testing.T) { + for name, raw := range cacheControlEquivalenceCases() { + t.Run(name, func(t *testing.T) { + body := []byte(raw) + before := append([]byte(nil), body...) + _ = enforceCacheControlLimit(body) + require.Equal(t, string(before), string(body)) + }) + } +} + +func TestNormalizeCacheControlTTLOrderMatchesLegacy(t *testing.T) { + rng := rand.New(rand.NewSource(7)) + cases := cacheControlEquivalenceCases() + for i := 0; i < 2000; i++ { + cases[fmt.Sprintf("random_%d", i)] = string(randomCacheControlBody(rng)) + } + for name, raw := range cases { + body := []byte(raw) + before := append([]byte(nil), body...) + want := legacyNormalizeCacheControlTTLOrder(append([]byte(nil), body...)) + got := normalizeCacheControlTTLOrder(body) + require.Equal(t, string(want), string(got), name) + require.Equal(t, string(before), string(body), "%s: input must not be mutated", name) + } +} + +func TestForceEphemeralCacheControlTTLDoesNotMutateInput(t *testing.T) { + body := []byte(`{"cache_control":{"type":"ephemeral"},"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral","ttl":"5m"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral"}}]}],"tools":[{"name":"t","cache_control":{"type":"ephemeral"}}]}`) + before := append([]byte(nil), body...) + got := forceEphemeralCacheControlTTL(body, cacheTTLTarget1h) + require.Equal(t, string(before), string(body)) + require.Equal(t, 4, strings.Count(string(got), `"ttl":"1h"`)) + require.True(t, gjson.ValidBytes(got)) +} + +func randomCacheControlBody(rng *rand.Rand) []byte { + cc := func() string { + switch rng.Intn(7) { + case 0: + return `,"cache_control":{"type":"ephemeral"}` + case 1: + return `,"cache_control":{"type":"ephemeral","ttl":"5m"}` + case 2: + return `,"cache_control":{"type":"ephemeral","ttl":"1h"}` + case 3: + return `,"cache_control":{"type":"persistent","ttl":"1h"}` + default: + return "" + } + } + var b bytes.Buffer + _, _ = b.WriteString(`{"model":"claude-sonnet"`) + if rng.Intn(5) == 0 { + _, _ = b.WriteString(`,"cache_control":{"type":"ephemeral","ttl":"1h"}`) + } + if rng.Intn(2) == 0 { + _, _ = b.WriteString(`,"tools":[`) + n := rng.Intn(4) + for i := 0; i < n; i++ { + if i > 0 { + _ = b.WriteByte(',') + } + fmt.Fprintf(&b, `{"name":"tool_%d"%s}`, i, cc()) + } + _ = b.WriteByte(']') + } + if rng.Intn(2) == 0 { + _, _ = b.WriteString(`,"system":[`) + n := rng.Intn(3) + for i := 0; i < n; i++ { + if i > 0 { + _ = b.WriteByte(',') + } + fmt.Fprintf(&b, `{"type":"text","text":"sys %d"%s}`, i, cc()) + } + _ = b.WriteByte(']') + } + _, _ = b.WriteString(`,"messages":[`) + m := rng.Intn(4) + for i := 0; i < m; i++ { + if i > 0 { + _ = b.WriteByte(',') + } + _, _ = b.WriteString(`{"role":"user","content":[`) + c := rng.Intn(3) + 1 + for j := 0; j < c; j++ { + if j > 0 { + _ = b.WriteByte(',') + } + blockType := "text" + if rng.Intn(6) == 0 { + blockType = "thinking" + } + fmt.Fprintf(&b, `{"type":%q,"text":"m%d-%d"%s}`, blockType, i, j, cc()) + } + _, _ = b.WriteString(`]}`) + } + _, _ = b.WriteString(`]}`) + return b.Bytes() +} + +// ---- legacy copies of the array-materializing helpers ---- + +func legacyIsOnlyWebSearchToolInBody(body []byte) bool { + tools := gjson.GetBytes(body, "tools") + if !tools.IsArray() { + return false + } + arr := tools.Array() + if len(arr) != 1 { + return false + } + return isWebSearchToolJSON(arr[0]) +} + +func legacyExtractSearchQueryFromBody(body []byte) string { + messages := gjson.GetBytes(body, "messages") + if !messages.IsArray() { + return "" + } + arr := messages.Array() + if len(arr) == 0 { + return "" + } + lastMsg := arr[len(arr)-1] + if lastMsg.Get("role").String() != "user" { + return "" + } + content := lastMsg.Get("content") + if content.Type == gjson.String { + return content.String() + } + if content.IsArray() { + for _, block := range content.Array() { + if block.Get("type").String() == "text" { + if text := block.Get("text").String(); text != "" { + return text + } + } + } + } + return "" +} + +func legacyExtractSystemPreviewFromBody(body []byte) string { + if len(body) == 0 { + return "" + } + sys := gjson.GetBytes(body, "system") + if !sys.Exists() { + return "" + } + switch { + case sys.IsArray(): + for _, item := range sys.Array() { + if !item.IsObject() { + continue + } + if strings.EqualFold(item.Get("type").String(), "text") { + if t := item.Get("text").String(); strings.TrimSpace(t) != "" { + return t + } + } + } + return "" + case sys.Type == gjson.String: + return sys.String() + default: + return "" + } +} + +func legacyRequestNeedsBetaFeatures(body []byte) bool { + tools := gjson.GetBytes(body, "tools") + if tools.Exists() && tools.IsArray() && len(tools.Array()) > 0 { + return true + } + thinkingType := gjson.GetBytes(body, "thinking.type").String() + return strings.EqualFold(thinkingType, "enabled") || strings.EqualFold(thinkingType, "adaptive") +} + +func requestHelperEquivalenceBodies() []string { + return []string{ + ``, + `{}`, + `{"tools":[]}`, + `{"tools":{}}`, + `{"tools":null}`, + `{"tools":[null]}`, + `{"tools":[{"type":"web_search_20250305","name":"web_search"}]}`, + `{"tools":[{"name":"web_search"}]}`, + `{"tools":[{"name":"google_search"}]}`, + `{"tools":[{"type":"web_search_20250305"},{"name":"bash"}]}`, + `{"tools":[{"name":"bash"}]}`, + `{"tools":[{"type":"computer_toolset_20260801"},{"type":"x"}]}`, + `{"tools":[{"type":"x"},{"type":"browser_toolset_20260801"}]}`, + `{"thinking":{"type":"adaptive"}}`, + `{"messages":[]}`, + `{"messages":[{"role":"assistant","content":"x"}]}`, + `{"messages":[{"role":"user","content":"hello"}]}`, + `{"messages":[{"role":"user","content":[{"type":"image"},{"type":"text","text":""},{"type":"text","text":"q"}]}]}`, + `{"messages":[{"role":"user","content":"a"},{"role":"user","content":[{"type":"text","text":"last"}]}]}`, + `{"messages":[{"role":"user","content":"a"},null]}`, + `{"system":"plain system"}`, + `{"system":[]}`, + `{"system":[1,"x",{"type":"TEXT","text":" "},{"type":"text","text":"first"},{"type":"text","text":"second"}]}`, + `{"system":{"type":"text"}}`, + `{"messages":[`, + } +} + +func TestRequestJSONHelpersMatchLegacy(t *testing.T) { + for _, raw := range requestHelperEquivalenceBodies() { + body := []byte(raw) + require.Equal(t, legacyIsOnlyWebSearchToolInBody(body), isOnlyWebSearchToolInBody(body), "isOnlyWebSearchToolInBody %s", raw) + require.Equal(t, legacyExtractSearchQueryFromBody(body), extractSearchQueryFromBody(body), "extractSearchQueryFromBody %s", raw) + require.Equal(t, legacyExtractSystemPreviewFromBody(body), extractSystemPreviewFromBody(body), "extractSystemPreviewFromBody %s", raw) + require.Equal(t, legacyRequestNeedsBetaFeatures(body), requestNeedsBetaFeatures(body), "requestNeedsBetaFeatures %s", raw) + } +} + +func TestClaudeMimicDebugLineIsLazyAndMatchesEager(t *testing.T) { + req, err := http.NewRequest(http.MethodPost, "https://api.anthropic.com/v1/messages", nil) + require.NoError(t, err) + req.Header.Set("User-Agent", "claude-cli/2.1.200") + req.Header.Set("Authorization", "Bearer secret-token") + body := []byte(`{"metadata":{"user_id":"user_1"},"system":[{"type":"text","text":"You are Claude Code"}]}`) + account := &Account{ID: 7, Name: "acc"} + + want := buildClaudeMimicDebugLine(req, body, account, "oauth", true) + lazy := newClaudeMimicDebugLine(req, body, account, "oauth", true) + require.Empty(t, lazy.line, "line must not be built eagerly") + require.Equal(t, want, lazy.String()) + require.Equal(t, want, lazy.String(), "second call returns cached line") + require.Nil(t, lazy.req, "request reference is released after building") + require.Nil(t, lazy.body, "body reference is released after building") + + c := &ginContextStub{values: map[string]any{claudeMimicDebugInfoKey: newClaudeMimicDebugLine(req, body, account, "oauth", true)}} + require.Equal(t, want, claudeMimicDebugLineFromContext(c)) + c.values[claudeMimicDebugInfoKey] = "legacy string" + require.Equal(t, "legacy string", claudeMimicDebugLineFromContext(c)) + delete(c.values, claudeMimicDebugInfoKey) + require.Empty(t, claudeMimicDebugLineFromContext(c)) + require.Empty(t, claudeMimicDebugLineFromContext(nil)) +} + +type ginContextStub struct { + values map[string]any +} + +func (c *ginContextStub) Get(key string) (any, bool) { + v, ok := c.values[key] + return v, ok +} + +func toolBodiesForEquivalence() []string { + return []string{ + `{}`, + `{"tools":[]}`, + `{"tools":{}}`, + `{"tools":[{"name":"bash"}]}`, + `{"tools":[{"name":"sessions_list"},{"name":"session_get","type":"custom"},{"name":"web_search","type":"web_search_20250305"}]}`, + `{"tools":[{"name":"a"},{"name":"b"},{"name":"c"},{"name":"d"},{"name":"e"},{"name":"f"},{"name":"g"}],"tool_choice":{"type":"tool","name":"c"}}`, + `{"tools":[{"name":"a","defer_loading":true,"cache_control":{"type":"ephemeral"}},{"name":"b"}]}`, + `{"tools":[{"name":"a"},{"name":"b","custom":{"defer_loading":true},"cache_control":{"type":"ephemeral"}}]}`, + `{"tools":[{"name":"a","defer_loading":true},{"name":"b","defer_loading":true}]}`, + `{"tools":[{"name":"a","cache_control":{"type":"ephemeral","ttl":"1h"}}]}`, + `{"tools":[{"name":"a","cache_control":{"type":"ephemeral"}}]}`, + `{"tools":[{"name":"a","defer_loading":"true","cache_control":{"type":"ephemeral"}}]}`, + `{"tools":[{"type":"computer_toolset_20260801"}]}`, + `{"tools":[{"type":"browser_toolset_20260801"},{"type":"computer_toolset_20260801"}]}`, + } +} + +func TestToolHelpersMatchLegacy(t *testing.T) { + headers := []string{"", "fine-grained-tool-streaming-2025-05-14", "a,fine-grained-tool-streaming-2025-05-14,b"} + models := []string{"claude-sonnet-5-5", "claude-haiku-5-5@20260101", "claude-opus-5-5"} + for _, raw := range toolBodiesForEquivalence() { + body := []byte(raw) + + requireEquivalentToolNameRewrite(t, legacyBuildToolNameRewriteFromBody(body), buildToolNameRewriteFromBody(body), raw) + require.Equal(t, + string(legacyApplyToolsLastCacheBreakpoint(append([]byte(nil), body...))), + string(applyToolsLastCacheBreakpoint(append([]byte(nil), body...))), raw) + require.Equal(t, + string(legacyStripDeferredToolCacheControl(append([]byte(nil), body...))), + string(stripDeferredToolCacheControl(append([]byte(nil), body...))), raw) + for _, h := range headers { + for _, m := range models { + require.Equal(t, legacyFilterSonnet55ToolsetBeta(h, body, m), filterSonnet55ToolsetBeta(h, body, m), "%s %s %s", raw, h, m) + } + } + } +} + +func TestSyncBillingHeaderVersionMatchesLegacy(t *testing.T) { + bodies := []string{ + `{"system":"plain"}`, + `{"system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.0.0.abc; cc_entrypoint=cli"}],"messages":[{"role":"user","content":"hello world from a long prompt"}]}`, + `{"system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.0.0; cc_entrypoint=cli"},{"type":"text","text":"x-anthropic-billing-header: cc_version=1.0.0.xyz"}],"messages":[{"role":"user","content":[{"type":"text","text":"你好世界🙂"}]}]}`, + `{"system":[{"type":"text","text":"other"}]}`, + } + for _, raw := range bodies { + for _, ua := range []string{"", "claude-cli/2.1.200 (external, cli)", "curl/8"} { + want := legacySyncBillingHeaderVersion(append([]byte(nil), raw...), ua) + got := syncBillingHeaderVersion(append([]byte(nil), raw...), ua) + require.Equal(t, string(want), string(got), "%s ua=%s", raw, ua) + } + } +} + +// ReverseOrdered is built from map iteration, so entries with equal fake-name +// length come out in random order (both before and after this change). Equal +// length distinct names cannot be substrings of each other, so that order does +// not affect replacement; compare the set and the length ordering instead. +func requireEquivalentToolNameRewrite(t *testing.T, want, got *ToolNameRewrite, msg string) { + t.Helper() + if want == nil || got == nil { + require.Equal(t, want, got, msg) + return + } + require.Equal(t, want.Forward, got.Forward, msg) + require.Equal(t, want.Reverse, got.Reverse, msg) + require.ElementsMatch(t, want.ReverseOrdered, got.ReverseOrdered, msg) + for i := 1; i < len(got.ReverseOrdered); i++ { + require.GreaterOrEqual(t, len(got.ReverseOrdered[i-1][0]), len(got.ReverseOrdered[i][0]), msg) + } +} diff --git a/backend/internal/service/gateway_request_json_legacy_test.go b/backend/internal/service/gateway_request_json_legacy_test.go new file mode 100644 index 0000000000..a57dc75bd8 --- /dev/null +++ b/backend/internal/service/gateway_request_json_legacy_test.go @@ -0,0 +1,170 @@ +package service + +import ( + "fmt" + "sort" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/pkg/claude" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// Verbatim legacy copies used only by equivalence tests. + +func legacyBuildToolNameRewriteFromBody(body []byte) *ToolNameRewrite { + tools := gjson.GetBytes(body, "tools") + if !tools.IsArray() { + return nil + } + + mimicableNames := make([]string, 0) + toolsArr := tools.Array() + for _, t := range toolsArr { + if !shouldMimicToolName(t.Get("type").String()) { + continue + } + name := t.Get("name").String() + if name == "" { + continue + } + mimicableNames = append(mimicableNames, name) + } + + dynamic := buildDynamicToolMap(mimicableNames) + + rw := &ToolNameRewrite{ + Forward: make(map[string]string), + Reverse: make(map[string]string), + } + for _, name := range mimicableNames { + fake := sanitizeToolName(name, dynamic) + if fake == name { + continue + } + rw.Forward[name] = fake + rw.Reverse[fake] = name + } + if len(rw.Forward) == 0 { + return nil + } + + rw.ReverseOrdered = make([][2]string, 0, len(rw.Reverse)) + for fake, real := range rw.Reverse { + rw.ReverseOrdered = append(rw.ReverseOrdered, [2]string{fake, real}) + } + sort.SliceStable(rw.ReverseOrdered, func(i, j int) bool { + return len(rw.ReverseOrdered[i][0]) > len(rw.ReverseOrdered[j][0]) + }) + + return rw +} + +func legacyApplyToolsLastCacheBreakpoint(body []byte) []byte { + body = legacyStripDeferredToolCacheControl(body) + tools := gjson.GetBytes(body, "tools") + if !tools.IsArray() { + return body + } + arr := tools.Array() + if len(arr) == 0 { + return body + } + lastIdx := -1 + for idx, tool := range arr { + if isDeferredLoadingTool(tool) { + continue + } + lastIdx = idx + } + if lastIdx == -1 { + return body + } + + existingCC := arr[lastIdx].Get("cache_control") + + if existingCC.Exists() && existingCC.Get("ttl").String() != "" { + return body + } + + if existingCC.Exists() { + if next, err := sjson.SetBytes(body, fmt.Sprintf("tools.%d.cache_control.ttl", lastIdx), claude.DefaultCacheControlTTL); err == nil { + body = next + } + return body + } + + raw := fmt.Sprintf(`{"type":"ephemeral","ttl":%q}`, claude.DefaultCacheControlTTL) + if next, err := sjson.SetRawBytes(body, fmt.Sprintf("tools.%d.cache_control", lastIdx), []byte(raw)); err == nil { + body = next + } + return body +} + +func legacyStripDeferredToolCacheControl(body []byte) []byte { + tools := gjson.GetBytes(body, "tools") + if !tools.IsArray() { + return body + } + for idx, tool := range tools.Array() { + if !isDeferredLoadingTool(tool) || !tool.Get("cache_control").Exists() { + continue + } + if next, err := sjson.DeleteBytes(body, fmt.Sprintf("tools.%d.cache_control", idx)); err == nil { + body = next + } + } + return body +} + +func legacyFilterSonnet55ToolsetBeta(header string, body []byte, modelID string) string { + if at := strings.IndexByte(modelID, '@'); at >= 0 { + modelID = modelID[:at] // Vertex's dated model ID + } + if !claude.IsSonnet55(modelID) && !claude.IsHaiku55(modelID) { + return header + } + for _, tool := range gjson.GetBytes(body, "tools").Array() { + switch tool.Get("type").String() { + case "computer_toolset_20260801", "browser_toolset_20260801": + if !containsBetaToken(header, claude.BetaFineGrainedToolStreaming) { + return header + } + return stripBetaTokensWithSet(header, map[string]struct{}{claude.BetaFineGrainedToolStreaming: {}}) + } + } + return header +} + +func legacySyncBillingHeaderVersion(body []byte, userAgent string) []byte { + version := ExtractCLIVersion(userAgent) + if version == "" { + return body + } + + systemResult := gjson.GetBytes(body, "system") + if !systemResult.Exists() || !systemResult.IsArray() { + return body + } + + replacement := "cc_version=" + version + idx := 0 + systemResult.ForEach(func(_, item gjson.Result) bool { + text := item.Get("text") + if text.Exists() && text.Type == gjson.String && + strings.HasPrefix(text.String(), "x-anthropic-billing-header") { + fingerprintedReplacement := replacement + "." + computeClaudeCodeFingerprint(body, version) + newText := ccVersionWithFingerprintInBillingRe.ReplaceAllString(text.String(), fingerprintedReplacement) + newText = ccVersionInBillingRe.ReplaceAllString(newText, replacement) + if newText != text.String() { + if updated, err := sjson.SetBytes(body, fmt.Sprintf("system.%d.text", idx), newText); err == nil { + body = updated + } + } + } + idx++ + return true + }) + + return body +} diff --git a/backend/internal/service/gateway_rotated_token_test.go b/backend/internal/service/gateway_rotated_token_test.go new file mode 100644 index 0000000000..41a799d44f --- /dev/null +++ b/backend/internal/service/gateway_rotated_token_test.go @@ -0,0 +1,214 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "fmt" + "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" +) + +type rotatedClaudeTokenRepo struct { + AccountRepository + account *Account + err error + reads int + cooldownCalls int + errorCalls int +} + +func (r *rotatedClaudeTokenRepo) GetByID(_ context.Context, id int64) (*Account, error) { + r.reads++ + return r.account, r.err +} + +func (r *rotatedClaudeTokenRepo) SetTempUnschedulable(context.Context, int64, time.Time, string) error { + r.cooldownCalls++ + return nil +} + +func (r *rotatedClaudeTokenRepo) SetError(context.Context, int64, string) error { + r.errorCalls++ + return nil +} + +type rotatedClaudeTokenBody struct { + io.Reader + closed bool +} + +func (b *rotatedClaudeTokenBody) Close() error { + b.closed = true + return nil +} + +func TestGatewayService_RotatedClaudeToken(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, path := range []string{"messages", "chat/completions", "responses"} { + for _, stream := range []bool{false, true} { + for _, tc := range []struct { + name string + snapshotToken string + storedToken string + lookupErr error + accountType string + inactive bool + unschedulable bool + cacheDeleteErr error + rejectRetry bool + wantCalls int + wantCooldown int + wantError int + }{ + {name: "rotated", storedToken: "new-token", wantCalls: 2}, + {name: "cached_token_differs_from_snapshot", snapshotToken: "new-token", storedToken: "new-token", wantCalls: 2}, + {name: "unchanged", storedToken: "old-token", wantCalls: 1, wantCooldown: 1}, + {name: "missing", wantCalls: 1, wantCooldown: 1}, + {name: "lookup_failed", lookupErr: errors.New("database unavailable"), wantCalls: 1, wantCooldown: 1}, + {name: "retry_rejected", storedToken: "new-token", rejectRetry: true, wantCalls: 2, wantCooldown: 1}, + {name: "disabled_account", storedToken: "new-token", inactive: true, wantCalls: 1, wantCooldown: 1}, + {name: "unschedulable_account", storedToken: "new-token", unschedulable: true, wantCalls: 1, wantCooldown: 1}, + {name: "cache_delete_failed", storedToken: "new-token", cacheDeleteErr: errors.New("cache unavailable"), wantCalls: 2}, + {name: "setup_token", accountType: AccountTypeSetupToken, storedToken: "new-token", wantCalls: 1, wantError: 1}, + {name: "api_key", accountType: AccountTypeAPIKey, storedToken: "new-token", wantCalls: 1, wantError: 1}, + } { + t.Run(fmt.Sprintf("%s/stream=%t/%s", path, stream, tc.name), func(t *testing.T) { + snapshotToken := tc.snapshotToken + if snapshotToken == "" { + snapshotToken = "old-token" + } + account := &Account{ + ID: 71, Platform: PlatformAnthropic, Type: AccountTypeOAuth, + Status: StatusActive, Schedulable: true, Concurrency: 1, + Credentials: map[string]any{"access_token": snapshotToken, "refresh_token": "refresh-token", "api_key": "old-token"}, + } + if tc.accountType != "" { + account.Type = tc.accountType + } + latest := *account + latest.Credentials = map[string]any{"access_token": tc.storedToken, "refresh_token": "new-refresh-token"} + if tc.inactive { + latest.Status = StatusError + } + if tc.unschedulable { + latest.Schedulable = false + } + repo := &rotatedClaudeTokenRepo{account: account} + cache := newClaudeTokenCacheStub() + cache.deleteErr = tc.cacheDeleteErr + require.NoError(t, cache.SetAccessToken(context.Background(), ClaudeTokenCacheKey(account), "old-token", time.Hour)) + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}} + calls := 0 + var firstWireBody []byte + var rejectedBodies []*rotatedClaudeTokenBody + upstream := &systemOneHTTPUpstream{do: func(req *http.Request) (*http.Response, error) { + calls++ + wireBody, err := io.ReadAll(req.Body) + require.NoError(t, err) + _ = req.Body.Close() + if calls == 1 { + if account.Type == AccountTypeAPIKey { + require.Equal(t, "old-token", getHeaderRaw(req.Header, "x-api-key")) + } else { + require.Equal(t, "Bearer old-token", getHeaderRaw(req.Header, "authorization")) + } + firstWireBody = wireBody + // The refresh completes only after the rejected request was sent. + repo.account, repo.err = &latest, tc.lookupErr + } else { + require.Equal(t, 2, calls, "recover at most once, even if the token rotates again") + require.Equal(t, "Bearer new-token", getHeaderRaw(req.Header, "authorization")) + require.Equal(t, firstWireBody, wireBody, "replay the complete request") + require.True(t, rejectedBodies[0].closed) + latest.Credentials["access_token"] = "third-token" + } + if calls == 1 || tc.rejectRetry { + body := &rotatedClaudeTokenBody{Reader: strings.NewReader(`{"type":"error","error":{"type":"authentication_error","message":"OAuth access token has been revoked"}}`)} + rejectedBodies = append(rejectedBodies, body) + return &http.Response{StatusCode: http.StatusUnauthorized, Header: make(http.Header), Body: body}, nil + } + payload := strings.Join([]string{ + "event: message_start", + `data: {"type":"message_start","message":{"id":"msg_rotated","type":"message","role":"assistant","model":"claude-sonnet-4-6","content":[],"usage":{"input_tokens":11}}}`, + "", "event: content_block_start", + `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + "", "event: content_block_delta", + `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hello"}}`, + "", "event: content_block_stop", + `data: {"type":"content_block_stop","index":0}`, + "", "event: message_delta", + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":7}}`, + "", "event: message_stop", `data: {"type":"message_stop"}`, "", "", + }, "\n") + contentType := "text/event-stream" + if path == "messages" && !stream { + payload = `{"id":"msg_rotated","type":"message","role":"assistant","model":"claude-sonnet-4-6","content":[{"type":"text","text":"hello"}],"stop_reason":"end_turn","usage":{"input_tokens":11,"output_tokens":7}}` + contentType = "application/json" + } + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{contentType}}, Body: io.NopCloser(strings.NewReader(payload))}, nil + }} + svc := &GatewayService{ + cfg: cfg, accountRepo: repo, httpUpstream: upstream, + claudeTokenProvider: NewClaudeTokenProvider(repo, cache, nil), + rateLimitService: &RateLimitService{cfg: cfg, accountRepo: repo}, + deferredService: &DeferredService{}, + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/"+path, nil) + body := []byte(fmt.Sprintf(`{"model":"claude-sonnet-4-6","stream":%t,"max_tokens":32,"messages":[{"role":"user","content":"hello"}]}`, stream)) + var result *ForwardResult + var err error + switch path { + case "messages": + var parsed *ParsedRequest + parsed, err = ParseGatewayRequest(NewRequestBodyRef(body), PlatformAnthropic) + require.NoError(t, err) + result, err = svc.Forward(context.Background(), c, account, parsed) + case "chat/completions": + result, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, nil) + case "responses": + body = []byte(fmt.Sprintf(`{"model":"claude-sonnet-4-6","stream":%t,"input":"hello"}`, stream)) + result, err = svc.ForwardAsResponses(context.Background(), c, account, body, nil) + } + if tc.wantCooldown == 0 && tc.wantError == 0 { + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, 11, result.Usage.InputTokens) + require.Equal(t, 7, result.Usage.OutputTokens) + require.Contains(t, rec.Body.String(), "hello") + require.NotContains(t, rec.Body.String(), "revoked") + cached, cacheErr := cache.GetAccessToken(context.Background(), ClaudeTokenCacheKey(account)) + require.NoError(t, cacheErr) + if tc.cacheDeleteErr == nil { + require.NotEqual(t, "old-token", cached) + } + } else { + var failover *UpstreamFailoverError + require.ErrorAs(t, err, &failover) + require.Equal(t, http.StatusUnauthorized, failover.StatusCode) + require.False(t, c.Writer.Written(), "leave the response available for account failover") + } + require.Equal(t, tc.wantCalls, calls) + require.Equal(t, tc.wantCooldown, repo.cooldownCalls) + require.Equal(t, tc.wantError, repo.errorCalls) + require.Equal(t, snapshotToken, account.GetCredential("access_token"), "do not mutate the shared account snapshot") + require.Equal(t, "new-refresh-token", latest.GetCredential("refresh_token"), "do not overwrite rotated credentials") + for _, body := range rejectedBodies { + require.True(t, body.closed) + } + }) + } + } + } +} diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index e6e8131009..63858570eb 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -15,6 +15,7 @@ import ( "sort" "strconv" "strings" + "sync" "sync/atomic" "time" "unsafe" @@ -303,17 +304,20 @@ func extractSystemPreviewFromBody(body []byte) string { switch { case sys.IsArray(): - for _, item := range sys.Array() { + var preview string + sys.ForEach(func(_, item gjson.Result) bool { if !item.IsObject() { - continue + return true } if strings.EqualFold(item.Get("type").String(), "text") { if t := item.Get("text").String(); strings.TrimSpace(t) != "" { - return t + preview = t + return false } } - } - return "" + return true + }) + return preview case sys.Type == gjson.String: return sys.String() default: @@ -350,7 +354,7 @@ func buildClaudeMimicDebugLine(req *http.Request, body []byte, account *Account, h := make([]string, 0, len(interesting)) for _, k := range interesting { - if v := req.Header.Get(k); v != "" { + if v := getHeaderRaw(req.Header, k); v != "" { h = append(h, fmt.Sprintf("%s=%q", k, safeHeaderValueForLog(k, v))) } } @@ -385,6 +389,64 @@ func buildClaudeMimicDebugLine(req *http.Request, body []byte, account *Account, ) } +// claudeMimicDebugLine defers building the diagnostics line until an error +// path actually needs it. The line is read only on Claude Code credential-scope +// errors, so building it eagerly cost every OAuth request a header walk, a +// system-prompt scan and several fmt.Sprintf calls for nothing. +type claudeMimicDebugLine struct { + once sync.Once + req *http.Request + body []byte + account *Account + tokenType string + mimicClaudeCode bool + line string +} + +func newClaudeMimicDebugLine(req *http.Request, body []byte, account *Account, tokenType string, mimicClaudeCode bool) *claudeMimicDebugLine { + return &claudeMimicDebugLine{ + req: req, + body: body, + account: account, + tokenType: tokenType, + mimicClaudeCode: mimicClaudeCode, + } +} + +func (l *claudeMimicDebugLine) String() string { + if l == nil { + return "" + } + l.once.Do(func() { + l.line = buildClaudeMimicDebugLine(l.req, l.body, l.account, l.tokenType, l.mimicClaudeCode) + // Drop references so the request/body are not retained after use. + l.req, l.body, l.account = nil, nil, nil + }) + return l.line +} + +// claudeMimicDebugLineFromContext returns the stored diagnostics line, building +// it on first use. It also accepts a plain string for compatibility. +func claudeMimicDebugLineFromContext(c interface { + Get(string) (any, bool) +}) string { + if c == nil { + return "" + } + v, ok := c.Get(claudeMimicDebugInfoKey) + if !ok { + return "" + } + switch line := v.(type) { + case *claudeMimicDebugLine: + return line.String() + case string: + return line + default: + return "" + } +} + func logClaudeMimicDebug(req *http.Request, body []byte, account *Account, tokenType string, mimicClaudeCode bool) { line := buildClaudeMimicDebugLine(req, body, account, tokenType, mimicClaudeCode) if line == "" { @@ -402,10 +464,7 @@ func isClaudeCodeCredentialScopeError(msg string) bool { strings.Contains(m, "cannot be used for other api requests") } -// sseDataRe matches SSE data lines with optional whitespace after colon. -// Some upstream APIs return non-standard "data:" without space (should be "data: "). var ( - sseDataRe = regexp.MustCompile(`^data:\s*`) claudeCliUserAgentRe = regexp.MustCompile(`(?i)^claude-cli/\d+\.\d+\.\d+`) // claudeCodePromptPrefixes 用于检测 Claude Code 系统提示词的前缀列表 @@ -712,6 +771,7 @@ type UpstreamFailoverError struct { NextAccountAction NextAccountAction ClientStatusCode int ClientMessage string + StreamFailedFrame *OpenAIStreamFailedFrame // 触发本次 failover 的流内 failed/error 帧;耗尽时用于错误透传规则匹配 } func (e *UpstreamFailoverError) Error() string { diff --git a/backend/internal/service/gateway_streaming_test.go b/backend/internal/service/gateway_streaming_test.go index cf0adfaa24..e5a2ccab47 100644 --- a/backend/internal/service/gateway_streaming_test.go +++ b/backend/internal/service/gateway_streaming_test.go @@ -532,3 +532,104 @@ func TestHandleStreamingResponse_SSEErrorEvent_NonJSONDataLine(t *testing.T) { }) require.Equal(t, "", ExtractUpstreamErrorMessage([]byte(sseErr.RawData))) } + +func TestSSEEventNeedsJSONParse(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + eventName string + data string + keepalive bool + modelReplace bool + want bool + }{ + { + name: "content_block_delta is forwarded verbatim", + eventName: "content_block_delta", + data: `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hello"}}`, + want: false, + }, + { + name: "ping is forwarded verbatim", + eventName: "ping", + data: `{"type":"ping"}`, + want: false, + }, + { + name: "message_start needs usage parsing", + eventName: "message_start", + data: `{"type":"message_start","message":{"usage":{"input_tokens":1}}}`, + want: true, + }, + { + name: "message_delta needs usage parsing", + eventName: "message_delta", + data: `{"type":"message_delta","usage":{"output_tokens":1}}`, + want: true, + }, + { + name: "missing event name falls back to parsing", + eventName: "", + data: `{"type":"content_block_delta"}`, + want: true, + }, + { + name: "keepalive needs block fields", + eventName: "content_block_delta", + data: `{"type":"content_block_delta","index":0}`, + keepalive: true, + want: true, + }, + { + name: "model replace needs message parsing", + eventName: "content_block_start", + data: `{"type":"content_block_start","message":{"model":"x"}}`, + modelReplace: true, + want: true, + }, + { + name: "unknown event with usage must be parsed", + eventName: "custom_event", + data: `{"usage":{"input_tokens":1}}`, + want: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + require.Equal(t, tt.want, sseEventNeedsJSONParse(tt.eventName, []byte(tt.data), tt.keepalive, tt.modelReplace)) + }) + } +} + +// 快路径必须原样转发 content_block_delta,不能重新序列化改变 key 顺序/空格/转义; +// message_stop 在没有 keepalive 的情况下也要能被识别为终态。 +func TestHandleStreamingResponse_FastPathForwardsDeltaBytesVerbatim(t *testing.T) { + gin.SetMode(gin.TestMode) + svc := newMinimalGatewayService() + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + + pr, pw := io.Pipe() + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: pr} + + delta := `{"delta":{"text":"你好","type":"text_delta"},"type":"content_block_delta","index":0,"extra":"a b"}` + go func() { + defer func() { _ = pw.Close() }() + _, _ = pw.Write([]byte("event: content_block_delta\ndata: " + delta + "\n\n")) + _, _ = pw.Write([]byte("event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n")) + }() + + result, err := svc.handleStreamingResponse(context.Background(), resp, c, &Account{ID: 1}, time.Now(), "model", "model", false) + _ = pr.Close() + require.NoError(t, err) + require.NotNil(t, result) + + body := rec.Body.String() + require.Contains(t, body, "event: content_block_delta\ndata: "+delta+"\n\n", + "网关必须逐字节转发不需要改写的 delta") + require.Contains(t, body, "event: message_stop") +} diff --git a/backend/internal/service/gateway_tool_rewrite.go b/backend/internal/service/gateway_tool_rewrite.go index c3e1d8da7f..0a114ec6a2 100644 --- a/backend/internal/service/gateway_tool_rewrite.go +++ b/backend/internal/service/gateway_tool_rewrite.go @@ -128,17 +128,15 @@ func buildToolNameRewriteFromBody(body []byte) *ToolNameRewrite { } mimicableNames := make([]string, 0) - toolsArr := tools.Array() - for _, t := range toolsArr { + tools.ForEach(func(_, t gjson.Result) bool { if !shouldMimicToolName(t.Get("type").String()) { - continue + return true } - name := t.Get("name").String() - if name == "" { - continue + if name := t.Get("name").String(); name != "" { + mimicableNames = append(mimicableNames, name) } - mimicableNames = append(mimicableNames, name) - } + return true + }) dynamic := buildDynamicToolMap(mimicableNames) @@ -269,22 +267,22 @@ func applyToolsLastCacheBreakpoint(body []byte) []byte { if !tools.IsArray() { return body } - arr := tools.Array() - if len(arr) == 0 { - return body - } + idx := 0 lastIdx := -1 - for idx, tool := range arr { - if isDeferredLoadingTool(tool) { - continue + lastTool := gjson.Result{} + tools.ForEach(func(_, tool gjson.Result) bool { + if !isDeferredLoadingTool(tool) { + lastIdx = idx + lastTool = tool } - lastIdx = idx - } + idx++ + return true + }) if lastIdx == -1 { return body } - existingCC := arr[lastIdx].Get("cache_control") + existingCC := lastTool.Get("cache_control") if existingCC.Exists() && existingCC.Get("ttl").String() != "" { return body @@ -316,14 +314,16 @@ func stripDeferredToolCacheControl(body []byte) []byte { if !tools.IsArray() { return body } - for idx, tool := range tools.Array() { - if !isDeferredLoadingTool(tool) || !tool.Get("cache_control").Exists() { - continue + idx := 0 + tools.ForEach(func(_, tool gjson.Result) bool { + if isDeferredLoadingTool(tool) && tool.Get("cache_control").Exists() { + if next, err := sjson.DeleteBytes(body, fmt.Sprintf("tools.%d.cache_control", idx)); err == nil { + body = next + } } - if next, err := sjson.DeleteBytes(body, fmt.Sprintf("tools.%d.cache_control", idx)); err == nil { - body = next - } - } + idx++ + return true + }) return body } @@ -351,10 +351,14 @@ func restoreToolNamesInBytes(data []byte, rw *ToolNameRewrite) []byte { // replaceAllBytes 是 bytes.ReplaceAll 的便捷封装,避免每个调用点各自做 []byte 转换。 func replaceAllBytes(data []byte, from, to string) []byte { - if len(data) == 0 || from == to || !strings.Contains(string(data), from) { + if len(data) == 0 || from == to { return data } - return []byte(strings.ReplaceAll(string(data), from, to)) + fromBytes := []byte(from) + if !bytes.Contains(data, fromBytes) { + return data + } + return bytes.ReplaceAll(data, fromBytes, []byte(to)) } // toolNameRewriteFromContext 从 gin.Context 取出请求阶段保存的工具名映射。 @@ -384,3 +388,30 @@ func reverseToolNamesIfPresent(c interface { } return restoreToolNamesInBytes(chunk, rw) } + +// reverseToolNamesIfPresentString is the string-typed variant for streaming +// writers. The common case (no tool names in the chunk) returns the original +// string without any []byte/string copy. +func reverseToolNamesIfPresentString(c interface { + Get(string) (any, bool) +}, chunk string) string { + rw := toolNameRewriteFromContext(c) + if rw == nil && len(staticToolNameRewrites) == 0 { + return chunk + } + if rw != nil { + for _, pair := range rw.ReverseOrdered { + fake, real := pair[0], pair[1] + if fake == "" || fake == real || !strings.Contains(chunk, fake) { + continue + } + chunk = strings.ReplaceAll(chunk, fake, real) + } + } + for prefix, replacement := range staticToolNameRewrites { + if strings.Contains(chunk, replacement) { + chunk = strings.ReplaceAll(chunk, replacement, prefix) + } + } + return chunk +} diff --git a/backend/internal/service/gateway_tool_rewrite_test.go b/backend/internal/service/gateway_tool_rewrite_test.go index 04f405b129..d34fd0e546 100644 --- a/backend/internal/service/gateway_tool_rewrite_test.go +++ b/backend/internal/service/gateway_tool_rewrite_test.go @@ -358,3 +358,43 @@ func BenchmarkApplyToolNameRewriteToBody_LongHistory(b *testing.B) { _ = applyToolNameRewriteToBody(body, rw) } } + +type toolRewriteCtxStub struct { + rw *ToolNameRewrite +} + +func (c toolRewriteCtxStub) Get(key string) (any, bool) { + if key == toolNameRewriteKey && c.rw != nil { + return c.rw, true + } + return nil, false +} + +// 字符串版本和 bytes 版本的还原结果必须完全一致,流式路径才能安全替换。 +func TestReverseToolNamesStringMatchesBytes(t *testing.T) { + rw := &ToolNameRewrite{ + ReverseOrdered: [][2]string{ + {"sessions_abc", "session_abc"}, + {"sessions_x", "sessions_x"}, + }, + } + cases := []string{ + "plain chunk", + `{"name":"sessions_x"}`, + `{"name":"sessions_abc"}`, + `{"name":"sessions_abc","x":"session_y"}`, + `{"name":"sessions_x","y":"sessions_abc","z":"session_y"}`, + } + for _, in := range cases { + got := reverseToolNamesIfPresentString(toolRewriteCtxStub{rw: rw}, in) + want := string(reverseToolNamesIfPresent(toolRewriteCtxStub{rw: rw}, []byte(in))) + require.Equal(t, want, got, "input=%q", in) + } + + // mapping 为 nil 时仍要做静态前缀还原。 + for _, in := range []string{`sessions_a`, `session_b`, `plain`} { + got := reverseToolNamesIfPresentString(toolRewriteCtxStub{}, in) + want := string(reverseToolNamesIfPresent(toolRewriteCtxStub{}, []byte(in))) + require.Equal(t, want, got, "input=%q", in) + } +} diff --git a/backend/internal/service/gateway_upstream_request.go b/backend/internal/service/gateway_upstream_request.go index beb6fc47e7..a159c867bd 100644 --- a/backend/internal/service/gateway_upstream_request.go +++ b/backend/internal/service/gateway_upstream_request.go @@ -248,7 +248,7 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex // Always capture a compact fingerprint line for later error diagnostics. // We only print it when needed (or when the explicit debug flag is enabled). if c != nil && tokenType == "oauth" { - c.Set(claudeMimicDebugInfoKey, buildClaudeMimicDebugLine(req, body, account, tokenType, mimicClaudeCode)) + c.Set(claudeMimicDebugInfoKey, newClaudeMimicDebugLine(req, body, account, tokenType, mimicClaudeCode)) } if s.debugClaudeMimicEnabled() { logClaudeMimicDebug(req, body, account, tokenType, mimicClaudeCode) @@ -441,7 +441,7 @@ func (s *GatewayService) getBetaHeader(modelID string, clientBetaHeader string) func requestNeedsBetaFeatures(body []byte) bool { tools := gjson.GetBytes(body, "tools") - if tools.Exists() && tools.IsArray() && len(tools.Array()) > 0 { + if tools.Exists() && tools.IsArray() && tools.Get("0").Exists() { return true } thinkingType := gjson.GetBytes(body, "thinking.type").String() @@ -470,9 +470,18 @@ func filterSonnet55ToolsetBeta(header string, body []byte, modelID string) strin if !claude.IsSonnet55(modelID) && !claude.IsHaiku55(modelID) { return header } - for _, tool := range gjson.GetBytes(body, "tools").Array() { - switch tool.Get("type").String() { - case "computer_toolset_20260801", "browser_toolset_20260801": + tools := gjson.GetBytes(body, "tools") + if tools.IsArray() { + matched := false + tools.ForEach(func(_, tool gjson.Result) bool { + switch tool.Get("type").String() { + case "computer_toolset_20260801", "browser_toolset_20260801": + matched = true + return false + } + return true + }) + if matched { if !containsBetaToken(header, claude.BetaFineGrainedToolStreaming) { return header } diff --git a/backend/internal/service/gateway_upstream_response.go b/backend/internal/service/gateway_upstream_response.go index 85b415e5cf..45059d8776 100644 --- a/backend/internal/service/gateway_upstream_response.go +++ b/backend/internal/service/gateway_upstream_response.go @@ -383,14 +383,12 @@ func (s *GatewayService) handleErrorResponse(ctx context.Context, resp *http.Res // Print a compact upstream request fingerprint when we hit the Claude Code OAuth // credential scope error. This avoids requiring env-var tweaks in a fixed deploy. if isClaudeCodeCredentialScopeError(upstreamMsg) && c != nil { - if v, ok := c.Get(claudeMimicDebugInfoKey); ok { - if line, ok := v.(string); ok && strings.TrimSpace(line) != "" { - logger.LegacyPrintf("service.gateway", "[ClaudeMimicDebugOnError] status=%d request_id=%s %s", - resp.StatusCode, - resp.Header.Get("x-request-id"), - line, - ) - } + if line := claudeMimicDebugLineFromContext(c); strings.TrimSpace(line) != "" { + logger.LegacyPrintf("service.gateway", "[ClaudeMimicDebugOnError] status=%d request_id=%s %s", + resp.StatusCode, + resp.Header.Get("x-request-id"), + line, + ) } } @@ -503,6 +501,13 @@ func (s *GatewayService) handleErrorResponse(ctx context.Context, resp *http.Res errType = "overloaded_error" errMsg = "Upstream service overloaded, please retry later" case 500, 502, 503, 504: + // Bedrock 内容过滤是请求级的确定性结果,按请求错误返回,客户端不应原样重试。 + if account.IsBedrock() && isBedrockContentFilterError(resp.StatusCode, body) && upstreamMsg != "" { + statusCode = http.StatusBadRequest + errType = "invalid_request_error" + errMsg = upstreamMsg + break + } statusCode = http.StatusBadGateway errType = "upstream_error" errMsg = "Upstream service temporarily unavailable" @@ -572,14 +577,12 @@ func (s *GatewayService) handleRetryExhaustedError(ctx context.Context, resp *ht upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg) if isClaudeCodeCredentialScopeError(upstreamMsg) && c != nil { - if v, ok := c.Get(claudeMimicDebugInfoKey); ok { - if line, ok := v.(string); ok && strings.TrimSpace(line) != "" { - logger.LegacyPrintf("service.gateway", "[ClaudeMimicDebugOnError] status=%d request_id=%s %s", - resp.StatusCode, - resp.Header.Get("x-request-id"), - line, - ) - } + if line := claudeMimicDebugLineFromContext(c); strings.TrimSpace(line) != "" { + logger.LegacyPrintf("service.gateway", "[ClaudeMimicDebugOnError] status=%d request_id=%s %s", + resp.StatusCode, + resp.Header.Get("x-request-id"), + line, + ) } } @@ -706,6 +709,36 @@ func partialStreamUsageResult(c *gin.Context, resp *http.Response, streamResult } } +// SSE fast-path predicates. Package-level byte slices keep the per-event +// checks allocation-free. +var ( + sseUsageFieldBytes = []byte(`"usage"`) + sseMessageFieldBytes = []byte(`"message"`) + sseModelFieldBytes = []byte(`"model"`) + sseMessageStopValueBytes = []byte(`"message_stop"`) +) + +// sseEventNeedsJSONParse reports whether an Anthropic SSE data line must be +// decoded into map[string]any. Most stream events (content_block_delta, ping, +// etc.) are forwarded verbatim; decoding them only adds allocations and GC +// pressure on the hot path. +func sseEventNeedsJSONParse(eventName string, data []byte, useNoopDeltaKeepalive, needModelReplace bool) bool { + eventName = strings.ToLower(strings.TrimSpace(eventName)) + if eventName == "" || eventName == "message_start" || eventName == "message_delta" { + return true + } + if useNoopDeltaKeepalive { + switch eventName { + case "content_block_start", "content_block_delta", "content_block_stop", "message_stop": + return true + } + } + if needModelReplace && bytes.Contains(data, sseMessageFieldBytes) { + return true + } + return bytes.Contains(data, sseUsageFieldBytes) +} + func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http.Response, c *gin.Context, account *Account, startTime time.Time, originalModel, mappedModel string, mimicClaudeCode bool) (*streamingResult, error) { observer := upstreamResponseModelObserverFromContext(c) if observer == nil { @@ -856,6 +889,7 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http } needModelReplace := originalModel != mappedModel + clientModel := compositeClientModel(ctx, "") clientDisconnected := false // 客户端断开标志,断开后继续读取上游以获取完整usage sawTerminalEvent := false useNoopDeltaKeepalive := c != nil && c.Request != nil && shouldUseClaudeCodeNoopDeltaKeepalive(c.GetHeader("User-Agent")) @@ -877,8 +911,8 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http eventName = strings.TrimSpace(strings.TrimPrefix(trimmed, "event:")) continue } - if dataLine == "" && sseDataRe.MatchString(trimmed) { - dataLine = sseDataRe.ReplaceAllString(trimmed, "") + if dataLine == "" && strings.HasPrefix(trimmed, "data:") { + dataLine = strings.TrimLeft(strings.TrimPrefix(trimmed, "data:"), " \t\n\f\r") } } @@ -900,8 +934,28 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http return []string{block}, dataLine, nil, nil } + dataLineBytes := []byte(dataLine) + if !sseEventNeedsJSONParse(eventName, dataLineBytes, useNoopDeltaKeepalive, needModelReplace) { + // Fast path: the event is forwarded verbatim. Skip the map decode and + // only do the cheap observations that still need the raw payload. + if bytes.Contains(dataLineBytes, sseModelFieldBytes) { + observer.ObserveAnthropic(dataLineBytes) + } + if strings.EqualFold(eventName, "message_stop") || bytes.Contains(dataLineBytes, sseMessageStopValueBytes) { + if anthropicStreamEventIsTerminal(eventName, dataLine) { + sawTerminalEvent = true + } + } + block := "" + if eventName != "" { + block = "event: " + eventName + "\n" + } + block += "data: " + dataLine + "\n\n" + return []string{block}, dataLine, nil, nil + } + var event map[string]any - if err := json.Unmarshal([]byte(dataLine), &event); err != nil { + if err := json.Unmarshal(dataLineBytes, &event); err != nil { // JSON 解析失败,直接透传原始数据 block := "" if eventName != "" { @@ -992,6 +1046,14 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http } } } + if clientModel != "" && eventType == "message_start" { + if msg, ok := event["message"].(map[string]any); ok { + if _, ok := msg["model"].(string); ok { + msg["model"] = clientModel + eventChanged = true + } + } + } usagePatch := s.extractSSEUsagePatch(event) if anthropicStreamEventIsTerminal(eventName, dataLine) { @@ -1101,8 +1163,8 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http for _, block := range outputBlocks { if !clientDisconnected { - restored := reverseToolNamesIfPresent(c, []byte(block)) - if _, werr := fmt.Fprint(w, string(restored)); werr != nil { + restored := reverseToolNamesIfPresentString(c, block) + if _, werr := io.WriteString(w, restored); werr != nil { clientDisconnected = true logger.LegacyPrintf("service.gateway", "Client disconnected during streaming, continuing to drain upstream for billing") // 不 break:客户端断开后仍需继续合并本事件及后续事件的 usage, @@ -1466,6 +1528,7 @@ func (s *GatewayService) handleNonStreamingResponse(ctx context.Context, resp *h if originalModel != mappedModel { body = s.replaceModelInResponseBody(body, mappedModel, originalModel) } + body = restoreCompositeClientModel(ctx, body) responseheaders.WriteFilteredHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter) diff --git a/backend/internal/service/gateway_websearch_emulation.go b/backend/internal/service/gateway_websearch_emulation.go index 8425109018..c359433d2d 100644 --- a/backend/internal/service/gateway_websearch_emulation.go +++ b/backend/internal/service/gateway_websearch_emulation.go @@ -100,11 +100,10 @@ func isOnlyWebSearchToolInBody(body []byte) bool { if !tools.IsArray() { return false } - arr := tools.Array() - if len(arr) != 1 { + if !tools.Get("0").Exists() || tools.Get("1").Exists() { return false } - return isWebSearchToolJSON(arr[0]) + return isWebSearchToolJSON(tools.Get("0")) } func isWebSearchToolJSON(tool gjson.Result) bool { @@ -125,12 +124,14 @@ func extractSearchQueryFromBody(body []byte) string { if !messages.IsArray() { return "" } - arr := messages.Array() - if len(arr) == 0 { - return "" - } - lastMsg := arr[len(arr)-1] - if lastMsg.Get("role").String() != "user" { + var lastMsg gjson.Result + found := false + messages.ForEach(func(_, msg gjson.Result) bool { + lastMsg = msg + found = true + return true + }) + if !found || lastMsg.Get("role").String() != "user" { return "" } return extractWebSearchTextFromContent(lastMsg.Get("content")) @@ -141,13 +142,17 @@ func extractWebSearchTextFromContent(content gjson.Result) string { return content.String() } if content.IsArray() { - for _, block := range content.Array() { + var result string + content.ForEach(func(_, block gjson.Result) bool { if block.Get("type").String() == "text" { if text := block.Get("text").String(); text != "" { - return text + result = text + return false } } - } + return true + }) + return result } return "" } diff --git a/backend/internal/service/gateway_websearch_emulation_test.go b/backend/internal/service/gateway_websearch_emulation_test.go index 0c05563f66..2577e38dcc 100644 --- a/backend/internal/service/gateway_websearch_emulation_test.go +++ b/backend/internal/service/gateway_websearch_emulation_test.go @@ -418,7 +418,10 @@ func TestShouldEmulateWebSearchFor_AccountChannelModes(t *testing.T) { settingSvc := newSettingServiceForWebSearchTest(true) groupID := int64(42) - for _, platform := range []string{PlatformOpenAI, PlatformAnthropic} { + platforms := []string{ + PlatformOpenAI, PlatformAnthropic, PlatformZhipu, PlatformCommandCode, PlatformOpenCodeGo, PlatformMiniMax, + } + for _, platform := range platforms { for _, accountType := range []string{AccountTypeAPIKey, AccountTypeOAuth, AccountTypeSetupToken} { for _, mode := range []string{WebSearchModeDefault, WebSearchModeEnabled, WebSearchModeDisabled} { for _, channelEnabled := range []bool{false, true} { diff --git a/backend/internal/service/gemini_chat_completions_compat_service.go b/backend/internal/service/gemini_chat_completions_compat_service.go index f0716e003c..4b236dcd0d 100644 --- a/backend/internal/service/gemini_chat_completions_compat_service.go +++ b/backend/internal/service/gemini_chat_completions_compat_service.go @@ -16,6 +16,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/Wei-Shaw/sub2api/internal/util/responseheaders" "github.com/gin-gonic/gin" + "github.com/tidwall/sjson" ) // ForwardAsChatCompletions serves OpenAI Chat Completions clients through @@ -66,7 +67,7 @@ func (s *GeminiMessagesCompatService) ForwardAsChatCompletions( return nil, fmt.Errorf("marshal chat completions compat request: %w", err) } - return s.forwardClaudeBodyAsChatCompletions(ctx, c, account, claudeBody, originalModel, clientStream, includeUsage, startTime) + return s.forwardClaudeBodyAsChatCompletions(ctx, c, account, claudeBody, ccReq.ResponseFormat, originalModel, clientStream, includeUsage, startTime) } func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( @@ -74,6 +75,7 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( c *gin.Context, account *Account, claudeBody []byte, + responseFormat json.RawMessage, originalModel string, clientStream bool, includeUsage bool, @@ -104,6 +106,7 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( } geminiReq = ensureGeminiFunctionCallThoughtSignatures(geminiReq) geminiReq = applyGeminiCompatThinkingConfig(geminiReq, claudeBody, mappedModel, clientStream) + geminiReq = applyGeminiChatResponseFormat(geminiReq, responseFormat, mappedModel) proxyURL := "" if account.ProxyID != nil && account.Proxy != nil { @@ -383,15 +386,21 @@ func (s *GeminiMessagesCompatService) buildGeminiChatCompletionsUpstreamRequestF fullURL += "?alt=sse" } - var inner any - if err := json.Unmarshal(geminiReq, &inner); err != nil { - return nil, "", fmt.Errorf("failed to parse gemini request: %w", err) + // request 按原字节嵌入,保留 responseJsonSchema 等 schema 的属性顺序与数值字面量。 + if !json.Valid(geminiReq) { + return nil, "", errors.New("failed to parse gemini request: invalid JSON") } - wrappedBytes, _ := json.Marshal(map[string]any{ + wrapperBytes, err := json.Marshal(map[string]any{ "model": mappedModel, "project": projectID, - "request": inner, }) + if err != nil { + return nil, "", err + } + wrappedBytes, err := sjson.SetRawBytes(wrapperBytes, "request", geminiReq) + if err != nil { + return nil, "", err + } upstreamReq, err := http.NewRequestWithContext(ctx, http.MethodPost, fullURL, bytes.NewReader(wrappedBytes)) if err != nil { @@ -600,6 +609,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom var seenThought geminiTextDelta openToolIndex := -1 openToolName := "" + var toolBoundary geminiToolCallBoundary var seenToolJSON geminiTextDelta closeOpenBlock := func() bool { @@ -619,6 +629,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom openToolIndex = -1 openToolName = "" seenToolJSON.reset() + toolBoundary = geminiToolCallBoundary{} return disconnected } @@ -735,7 +746,8 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom if closeOpenBlock() { return streamResult(), nil } - if openToolIndex >= 0 && openToolName != name { + argsJSONText := geminiToolCallArgsJSON(fc["args"]) + if openToolIndex >= 0 && toolBoundary.startsNewBlock(openToolName, seenToolJSON.seen.String(), argsJSONText, fc) { if closeOpenTool() { return streamResult(), nil } @@ -760,19 +772,8 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom } } - argsJSONText := "{}" - switch v := fc["args"].(type) { - case nil: - case string: - if strings.TrimSpace(v) != "" { - argsJSONText = v - } - default: - if b, err := json.Marshal(v); err == nil && len(b) > 0 { - argsJSONText = string(b) - } - } delta := seenToolJSON.next(argsJSONText) + toolBoundary.observe(fc) if delta != "" { if emitAnthropicEvent(&apicompat.AnthropicStreamEvent{ Type: "content_block_delta", diff --git a/backend/internal/service/gemini_compat_response_format.go b/backend/internal/service/gemini_compat_response_format.go new file mode 100644 index 0000000000..457067d878 --- /dev/null +++ b/backend/internal/service/gemini_compat_response_format.go @@ -0,0 +1,50 @@ +package service + +import ( + "encoding/json" + + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// applyGeminiChatResponseFormat 把 Chat Completions 的 response_format 写入 Gemini generationConfig: +// json_object 写 responseMimeType=application/json;json_schema 另把 json_schema.schema 原样写入 +// responseJsonSchema(JSON Schema 形态,不转换为 OpenAPI 子集的 responseSchema)。 +// text、缺省或无法解析的 response_format 不改请求。 +// 以下情况不写:请求带 tools(Gemini 2.x 不接受工具与 JSON responseMimeType 同用); +// upstreamModel 为图片输出模型(输出含图片,与 JSON responseMimeType 冲突)。 +func applyGeminiChatResponseFormat(geminiReq []byte, responseFormat json.RawMessage, upstreamModel string) []byte { + if len(responseFormat) == 0 || !gjson.ValidBytes(responseFormat) || isGeminiImageOutputModel(upstreamModel) { + return geminiReq + } + format := gjson.ParseBytes(responseFormat) + if !format.IsObject() { + return geminiReq + } + + var schema gjson.Result + switch format.Get("type").String() { + case "json_object": + case "json_schema": + schema = format.Get("json_schema.schema") + default: + return geminiReq + } + + if tools := gjson.GetBytes(geminiReq, "tools"); tools.IsArray() && len(tools.Array()) > 0 { + return geminiReq + } + + out, err := sjson.SetBytes(geminiReq, "generationConfig.responseMimeType", "application/json") + if err != nil { + return geminiReq + } + if schema.IsObject() { + withSchema, err := sjson.SetRawBytes(out, "generationConfig.responseJsonSchema", []byte(schema.Raw)) + if err != nil { + return geminiReq + } + out = withSchema + } + return out +} diff --git a/backend/internal/service/gemini_compat_response_format_test.go b/backend/internal/service/gemini_compat_response_format_test.go new file mode 100644 index 0000000000..9d554a3fb9 --- /dev/null +++ b/backend/internal/service/gemini_compat_response_format_test.go @@ -0,0 +1,168 @@ +package service + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strconv" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const geminiResponseFormatTestSchema = `{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"score":{"type":"integer","minimum":1,"maximum":10},"note":{"anyOf":[{"type":"string","maxLength":600},{"type":"null"}]}},"required":["score","note"],"additionalProperties":false}` + +func TestApplyGeminiChatResponseFormat(t *testing.T) { + base := []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"generationConfig":{"maxOutputTokens":32000,"thinkingConfig":{"thinkingLevel":"high"}}}`) + withTools := []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"tools":[{"functionDeclarations":[{"name":"lookup"}]}],"generationConfig":{"maxOutputTokens":100}}`) + noConfig := []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`) + + tests := []struct { + name string + req []byte + format string + model string + wantMime bool + wantSchema string + }{ + {name: "json_schema writes mime and schema", req: base, format: `{"type":"json_schema","json_schema":{"name":"grade","strict":true,"schema":` + geminiResponseFormatTestSchema + `}}`, wantMime: true, wantSchema: geminiResponseFormatTestSchema}, + {name: "json_schema without schema writes mime only", req: base, format: `{"type":"json_schema","json_schema":{"name":"grade"}}`, wantMime: true}, + {name: "json_object writes mime only", req: base, format: `{"type":"json_object"}`, wantMime: true}, + {name: "json_object creates generationConfig", req: noConfig, format: `{"type":"json_object"}`, wantMime: true}, + {name: "text leaves request unchanged", req: base, format: `{"type":"text"}`}, + {name: "null leaves request unchanged", req: base, format: `null`}, + {name: "empty leaves request unchanged", req: base, format: ``}, + {name: "invalid json leaves request unchanged", req: base, format: `{"type":"json_object"`}, + {name: "non-object leaves request unchanged", req: base, format: `"json_object"`}, + {name: "image model leaves request unchanged", req: base, format: `{"type":"json_object"}`, model: "gemini-2.5-flash-image"}, + {name: "unlisted image model leaves request unchanged", req: base, format: `{"type":"json_object"}`, model: "models/gemini-3.5-flash-image-preview"}, + {name: "text model writes mime", req: base, format: `{"type":"json_object"}`, model: "gemini-4-argon", wantMime: true}, + {name: "tools present leaves request unchanged", req: withTools, format: `{"type":"json_schema","json_schema":{"name":"grade","schema":` + geminiResponseFormatTestSchema + `}}`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := applyGeminiChatResponseFormat(tt.req, json.RawMessage(tt.format), tt.model) + require.True(t, json.Valid(got), string(got)) + if !tt.wantMime { + require.Equal(t, string(tt.req), string(got)) + return + } + require.Equal(t, "application/json", gjson.GetBytes(got, "generationConfig.responseMimeType").String()) + schema := gjson.GetBytes(got, "generationConfig.responseJsonSchema") + if tt.wantSchema == "" { + require.False(t, schema.Exists(), string(got)) + } else { + require.JSONEq(t, tt.wantSchema, schema.Raw) + } + require.False(t, gjson.GetBytes(got, "generationConfig.responseSchema").Exists(), string(got)) + require.Equal(t, gjson.GetBytes(tt.req, "contents").Raw, gjson.GetBytes(got, "contents").Raw) + for _, path := range []string{"generationConfig.maxOutputTokens", "generationConfig.thinkingConfig"} { + require.Equal(t, gjson.GetBytes(tt.req, path).Raw, gjson.GetBytes(got, path).Raw, path) + } + }) + } +} + +func TestGeminiForwardAsChatCompletions_ForwardsResponseFormat(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + stream bool + format string + wantSchema string + }{ + {name: "non-stream json_schema", format: `{"type":"json_schema","json_schema":{"name":"grade","strict":true,"schema":` + geminiResponseFormatTestSchema + `}}`, wantSchema: geminiResponseFormatTestSchema}, + {name: "stream json_object", stream: true, format: `{"type":"json_object"}`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + resp := &http.Response{StatusCode: http.StatusOK} + if tt.stream { + resp.Header = http.Header{"Content-Type": []string{"text/event-stream"}} + resp.Body = io.NopCloser(strings.NewReader(`data: {"candidates":[{"content":{"role":"model","parts":[{"text":"{\"score\":7,\"note\":null}"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":5}}` + "\n\n")) + } else { + resp.Header = http.Header{"Content-Type": []string{"application/json"}} + resp.Body = io.NopCloser(strings.NewReader(`{"candidates":[{"content":{"parts":[{"text":"{\"score\":7,\"note\":null}"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":5}}`)) + } + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{resp}} + svc := &GeminiMessagesCompatService{httpUpstream: upstream, cfg: &config.Config{}} + body := []byte(`{"model":"gemini-4-argon","stream":` + strconv.FormatBool(tt.stream) + `,"reasoning_effort":"high","max_tokens":32000,"response_format":` + tt.format + `,"messages":[{"role":"user","content":"grade this"}]}`) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/chat/completions", body) + + _, err := svc.ForwardAsChatCompletions(context.Background(), c, geminiCompatThinkingTestAccount(), body) + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.requestBodies, 1) + sent := upstream.requestBodies[0] + require.Equal(t, "application/json", gjson.GetBytes(sent, "generationConfig.responseMimeType").String(), string(sent)) + schema := gjson.GetBytes(sent, "generationConfig.responseJsonSchema") + if tt.wantSchema == "" { + require.False(t, schema.Exists(), string(sent)) + } else { + require.JSONEq(t, tt.wantSchema, schema.Raw) + } + require.Equal(t, "high", gjson.GetBytes(sent, "generationConfig.thinkingConfig.thinkingLevel").String()) + require.Equal(t, int64(32000), gjson.GetBytes(sent, "generationConfig.maxOutputTokens").Int()) + if !tt.stream { + require.Equal(t, `{"score":7,"note":null}`, gjson.Get(recorder.Body.String(), "choices.0.message.content").String()) + } + }) + } +} + +func TestGeminiForwardAsChatCompletions_ResponseFormatSkippedWithTools(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":1}}`)), + }}} + svc := &GeminiMessagesCompatService{httpUpstream: upstream, cfg: &config.Config{}} + body := []byte(`{"model":"gemini-4-argon","response_format":{"type":"json_object"},"tools":[{"type":"function","function":{"name":"lookup","parameters":{"type":"object","properties":{"q":{"type":"string"}}}}}],"messages":[{"role":"user","content":"hi"}]}`) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/chat/completions", body) + + _, err := svc.ForwardAsChatCompletions(context.Background(), c, geminiCompatThinkingTestAccount(), body) + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.requestBodies, 1) + sent := upstream.requestBodies[0] + require.True(t, gjson.GetBytes(sent, "tools").IsArray(), string(sent)) + require.False(t, gjson.GetBytes(sent, "generationConfig.responseMimeType").Exists(), string(sent)) + require.False(t, gjson.GetBytes(sent, "generationConfig.responseJsonSchema").Exists(), string(sent)) +} + +func TestGeminiForwardAsChatCompletions_CodeAssistKeepsResponseSchemaBytes(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(`data: {"response":{"candidates":[{"content":{"parts":[{"text":"{\"reasoning\":\"r\",\"answer\":\"a\"}"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":5}}}` + "\n\n")), + }}} + svc := &GeminiMessagesCompatService{tokenProvider: &GeminiTokenProvider{}, httpUpstream: upstream, cfg: &config.Config{}} + account := &Account{ + ID: 612, + Platform: PlatformGemini, + Type: AccountTypeOAuth, + Credentials: map[string]any{"access_token": "ya29.test-token", "project_id": "project-1"}, + Concurrency: 1, + } + schema := `{"type":"object","properties":{"reasoning":{"type":"string"},"answer":{"type":"string"},"big":{"type":"integer","maximum":9007199254740993}},"required":["reasoning","answer"]}` + body := []byte(`{"model":"gemini-4-argon","response_format":{"type":"json_schema","json_schema":{"name":"r","schema":` + schema + `}},"messages":[{"role":"user","content":"hi"}]}`) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/chat/completions", body) + + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body) + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.requestBodies, 1) + sent := upstream.requestBodies[0] + require.Equal(t, "gemini-4-argon", gjson.GetBytes(sent, "model").String()) + require.Equal(t, "project-1", gjson.GetBytes(sent, "project").String()) + require.Equal(t, "application/json", gjson.GetBytes(sent, "request.generationConfig.responseMimeType").String(), string(sent)) + require.Equal(t, schema, gjson.GetBytes(sent, "request.generationConfig.responseJsonSchema").Raw) + require.Equal(t, `{"reasoning":"r","answer":"a"}`, gjson.Get(recorder.Body.String(), "choices.0.message.content").String()) +} diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index 9d2ad1ae45..4aee3e384d 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -2215,6 +2215,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re openToolIndex := -1 openToolID := "" openToolName := "" + var toolBoundary geminiToolCallBoundary var seenToolJSON geminiTextDelta reader := newBoundedSSELineReader(resp.Body, s.cfg) @@ -2282,6 +2283,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re openToolIndex = -1 openToolName = "" seenToolJSON.reset() + toolBoundary = geminiToolCallBoundary{} } if openBlockType != "thinking" { if openBlockIndex >= 0 { @@ -2333,6 +2335,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re openToolIndex = -1 openToolName = "" seenToolJSON.reset() + toolBoundary = geminiToolCallBoundary{} } delta := seenText.next(text) @@ -2378,7 +2381,6 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re if fc, ok := part["functionCall"].(map[string]any); ok && fc != nil { name, _ := fc["name"].(string) - args := fc["args"] if strings.TrimSpace(name) == "" { name = "tool" } @@ -2394,7 +2396,8 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re } // If we receive streamed tool args in pieces, keep a single tool block open and emit deltas. - if openToolIndex >= 0 && openToolName != name { + argsJSONText := geminiToolCallArgsJSON(fc["args"]) + if openToolIndex >= 0 && toolBoundary.startsNewBlock(openToolName, seenToolJSON.seen.String(), argsJSONText, fc) { writeSSE(c.Writer, "content_block_stop", map[string]any{ "type": "content_block_stop", "index": openToolIndex, @@ -2402,6 +2405,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re openToolIndex = -1 openToolName = "" seenToolJSON.reset() + toolBoundary = geminiToolCallBoundary{} } if openToolIndex < 0 { @@ -2423,21 +2427,8 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re }) } - argsJSONText := "{}" - switch v := args.(type) { - case nil: - // keep default "{}" - case string: - if strings.TrimSpace(v) != "" { - argsJSONText = v - } - default: - if b, err := json.Marshal(args); err == nil && len(b) > 0 { - argsJSONText = string(b) - } - } - delta := seenToolJSON.next(argsJSONText) + toolBoundary.observe(fc) if delta != "" { writeSSE(c.Writer, "content_block_delta", map[string]any{ "type": "content_block_delta", diff --git a/backend/internal/service/gemini_multiplatform_test.go b/backend/internal/service/gemini_multiplatform_test.go index 3c26f8f2ca..63ac4a6f51 100644 --- a/backend/internal/service/gemini_multiplatform_test.go +++ b/backend/internal/service/gemini_multiplatform_test.go @@ -172,6 +172,10 @@ func (m *mockAccountRepoForGemini) ClearAntigravityQuotaScopes(ctx context.Conte func (m *mockAccountRepoForGemini) ClearModelRateLimits(ctx context.Context, id int64) error { return nil } + +func (m *mockAccountRepoForGemini) ClearModelRateLimit(ctx context.Context, id int64, scope string) error { + return nil +} func (m *mockAccountRepoForGemini) UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error { return nil } diff --git a/backend/internal/service/gemini_parallel_tools_test.go b/backend/internal/service/gemini_parallel_tools_test.go new file mode 100644 index 0000000000..30145de0d3 --- /dev/null +++ b/backend/internal/service/gemini_parallel_tools_test.go @@ -0,0 +1,186 @@ +package service + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestGeminiParallelToolStreams(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + frames [][]string + want []string + }{ + {"same_name_distinct_ids_one_event", [][]string{{`{"id":"a","name":"read_file","args":{"path":"a"}}`, `{"id":"b","name":"read_file","args":{"path":"b"}}`}}, []string{`{"path":"a"}`, `{"path":"b"}`}}, + {"same_name_distinct_ids_separate_events", [][]string{{`{"id":"a","name":"read_file","args":{"path":"a"}}`}, {`{"id":"b","name":"read_file","args":{"path":"b"}}`}}, []string{`{"path":"a"}`, `{"path":"b"}`}}, + {"same_name_identical_arguments_distinct_ids", [][]string{{`{"id":"a","name":"read_file","args":{}}`, `{"id":"b","name":"read_file","args":{}}`}}, []string{`{}`, `{}`}}, + {"same_name_no_ids_one_event", [][]string{{`{"name":"read_file","args":{"path":"a"}}`, `{"name":"read_file","args":{"path":"b"}}`}}, []string{`{"path":"a"}`, `{"path":"b"}`}}, + {"same_name_no_ids_identical_separate_events", [][]string{{`{"name":"read_file","args":{}}`}, {`{"name":"read_file","args":{}}`}}, []string{`{}`, `{}`}}, + {"same_id_incremental_strings", [][]string{{`{"id":"a","name":"read_file","args":"{\"path\":"}`}, {`{"id":"a","name":"read_file","args":"\"a\"}"}`}}, []string{`{"path":"a"}`}}, + {"no_id_incremental_strings", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}"}`}}, []string{`{"path":"a"}`}}, + {"same_id_cumulative_and_duplicate", [][]string{{`{"id":"a","name":"read_file","args":"{\"path\":"}`}, {`{"id":"a","name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"id":"a","name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"anonymous_incremental_then_final_snapshot", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"id_first_chunk_only_then_final_snapshot", [][]string{{`{"id":"a","name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"id_learned_on_second_chunk_then_duplicate", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"id":"a","name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"id":"a","name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"same_name_no_ids_identical_one_event", [][]string{{`{"name":"read_file","args":{"path":"a"}}`, `{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, + {"anonymous_fragments_snapshot_then_identical_call", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, + {"anonymous_fragments_then_distinct_complete_call", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}"}`}, {`{"name":"read_file","args":{"path":"b"}}`}}, []string{`{"path":"a"}`, `{"path":"b"}`}}, + {"late_id_then_distinct_same_arguments_call", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"\"a\"}","id":"a"}`}, {`{"name":"read_file","args":{"path":"a"},"id":"b"}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, + {"anonymous_cumulative_final_string_then_snapshot", [][]string{{`{"name":"read_file","args":"{\"path\":"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"explicit_id_change_overrides_fragment_snapshot", [][]string{{`{"name":"read_file","args":"{\"path\":","id":"a"}`}, {`{"name":"read_file","args":"\"a\"}","id":"a"}`}, {`{"name":"read_file","args":{"path":"a"},"id":"b"}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, + {"complete_string_duplicate_no_ids", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}"}`}}, []string{`{"path":"a"}`}}, + {"complete_string_duplicate_first_id_only", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}","id":"a"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}"}`}}, []string{`{"path":"a"}`}}, + {"complete_string_duplicate_final_object_same_id", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}","id":"a"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"},"id":"a"}`}}, []string{`{"path":"a"}`}}, + {"complete_string_final_object_no_ids", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`}}, + {"complete_strings_stable_id", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}","id":"a"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}","id":"a"}`}, {`{"name":"read_file","args":{"path":"a"},"id":"a"}`}}, []string{`{"path":"a"}`}}, + {"complete_strings_distinct_ids", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}","id":"a"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}","id":"b"}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, + {"complete_string_snapshot_then_identical_native_call", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":{"path":"a"}}`}, {`{"name":"read_file","args":{"path":"a"}}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, + {"complete_string_late_id_then_new_id", [][]string{{`{"name":"read_file","args":"{\"path\":\"a\"}"}`}, {`{"name":"read_file","args":"{\"path\":\"a\"}","id":"a"}`}, {`{"name":"read_file","args":{"path":"a"},"id":"b"}`}}, []string{`{"path":"a"}`, `{"path":"a"}`}}, + {"different_names", [][]string{{`{"name":"read_file","args":{}}`, `{"name":"read_other","args":{}}`}}, []string{`{}`, `{}`}}, + } + for _, tt := range tests { + for _, protocol := range []string{"chat", "messages"} { + t.Run(tt.name+"/"+protocol, func(t *testing.T) { + var upstream strings.Builder + for _, frame := range tt.frames { + parts := []any{} + for _, fc := range frame { + var call map[string]any + require.NoError(t, json.Unmarshal([]byte(fc), &call)) + parts = append(parts, map[string]any{"functionCall": call}) + } + b, err := json.Marshal(map[string]any{"candidates": []any{map[string]any{"content": map[string]any{"parts": parts}}}}) + require.NoError(t, err) + _, _ = upstream.WriteString("data: " + string(b) + "\n\n") + } + _, _ = upstream.WriteString(`data: {"candidates":[{"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":7,"cachedContentTokenCount":3}}` + "\n\ndata: [DONE]\n\n") + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + svc := &GeminiMessagesCompatService{} + resp := &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(upstream.String()))} + var result *geminiStreamResult + var err error + if protocol == "chat" { + result, err = svc.handleChatCompletionsStreamingResponseFromGemini(c, resp, time.Now(), "gemini-test", false, true) + } else { + result, err = svc.handleStreamingResponse(c, resp, time.Now(), "gemini-test") + } + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, 3, result.usage.CacheReadInputTokens) + calls, terminal, open := collectParallelToolCalls(t, rec.Body.String(), protocol) + require.True(t, terminal) + require.Equal(t, -1, open) + require.Len(t, calls, len(tt.want)) + ids := map[string]bool{} + for i, want := range tt.want { + a := calls[i] + require.NotNil(t, a) + require.NotEmpty(t, a.id) + require.NotEmpty(t, a.name) + require.False(t, ids[a.id]) + ids[a.id] = true + require.JSONEq(t, want, a.args) + } + }) + } + } +} + +// collectParallelToolCalls checks the public SSE representation, including +// per-call metadata and the Anthropic content block lifecycle. +func collectParallelToolCalls(t *testing.T, body, protocol string) (map[int]*parallelToolCall, bool, int) { + t.Helper() + calls := map[int]*parallelToolCall{} + terminal, open := false, -1 + for _, line := range strings.Split(body, "\n") { + if !strings.HasPrefix(line, "data:") { + continue + } + raw := strings.TrimSpace(strings.TrimPrefix(line, "data:")) + if raw == "[DONE]" { + continue + } + var e struct { + Type string `json:"type"` + Index int `json:"index"` + ContentBlock struct { + Type string `json:"type"` + ID string `json:"id"` + Name string `json:"name"` + } `json:"content_block"` + Delta struct { + Type string `json:"type"` + PartialJSON string `json:"partial_json"` + StopReason string `json:"stop_reason"` + } `json:"delta"` + Choices []struct { + FinishReason string `json:"finish_reason"` + Delta struct { + ToolCalls []struct { + Index *int `json:"index"` + ID string `json:"id"` + Function struct { + Name string `json:"name"` + Arguments string `json:"arguments"` + } `json:"function"` + } `json:"tool_calls"` + } `json:"delta"` + } `json:"choices"` + } + require.NoError(t, json.Unmarshal([]byte(raw), &e)) + if protocol == "chat" { + for _, choice := range e.Choices { + if choice.FinishReason == "tool_calls" { + terminal = true + } + for _, tc := range choice.Delta.ToolCalls { + require.NotNil(t, tc.Index) + idx := *tc.Index + a := calls[idx] + if a == nil { + require.NotEmpty(t, tc.ID, "first delta must identify its call") + require.NotEmpty(t, tc.Function.Name, "first delta must name its function") + a = ¶llelToolCall{} + calls[idx] = a + } + a.id += tc.ID + a.name += tc.Function.Name + a.args += tc.Function.Arguments + } + } + continue + } + switch e.Type { + case "content_block_start": + require.Equal(t, -1, open, "previous block must close before the next starts") + require.Equal(t, "tool_use", e.ContentBlock.Type) + open = e.Index + _, exists := calls[e.Index] + require.False(t, exists, "tool block indexes must be unique") + calls[e.Index] = ¶llelToolCall{id: e.ContentBlock.ID, name: e.ContentBlock.Name} + case "content_block_delta": + require.Equal(t, open, e.Index) + require.Equal(t, "input_json_delta", e.Delta.Type) + require.NotNil(t, calls[e.Index]) + calls[e.Index].args += e.Delta.PartialJSON + case "content_block_stop": + require.Equal(t, open, e.Index) + open = -1 + case "message_delta": + terminal = e.Delta.StopReason == "tool_use" + } + } + return calls, terminal, open +} + +type parallelToolCall struct{ id, name, args string } diff --git a/backend/internal/service/gemini_quota.go b/backend/internal/service/gemini_quota.go index be927754cf..afe486998d 100644 --- a/backend/internal/service/gemini_quota.go +++ b/backend/internal/service/gemini_quota.go @@ -416,11 +416,11 @@ func geminiAggregateUsage(stats []usagestats.ModelStat) GeminiUsageTotals { case geminiModelFlash: totals.FlashRequests += stat.Requests totals.FlashTokens += stat.TotalTokens - totals.FlashCost += stat.ActualCost + totals.FlashCost += stat.AccountCost default: totals.ProRequests += stat.Requests totals.ProTokens += stat.TotalTokens - totals.ProCost += stat.ActualCost + totals.ProCost += stat.AccountCost } } return totals diff --git a/backend/internal/service/gemini_quota_test.go b/backend/internal/service/gemini_quota_test.go index 36e60f291e..69df88ea12 100644 --- a/backend/internal/service/gemini_quota_test.go +++ b/backend/internal/service/gemini_quota_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/usagestats" "github.com/stretchr/testify/require" ) @@ -78,3 +79,14 @@ func geminiQuotaAPIKeyAccount(baseURL string) *Account { } return &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: credentials} } + +func TestGeminiAggregateUsageUsesAccountCost(t *testing.T) { + totals := geminiAggregateUsage([]usagestats.ModelStat{ + {Model: "gemini-3.7-flash", Requests: 2, TotalTokens: 20, ActualCost: 5, AccountCost: 1.5}, + {Model: "gemini-4-argon", Requests: 1, TotalTokens: 10, ActualCost: 8, AccountCost: 3}, + }) + require.Equal(t, int64(2), totals.FlashRequests) + require.Equal(t, 1.5, totals.FlashCost) + require.Equal(t, int64(1), totals.ProRequests) + require.Equal(t, 3.0, totals.ProCost) +} diff --git a/backend/internal/service/gemini_tool_call_boundary.go b/backend/internal/service/gemini_tool_call_boundary.go new file mode 100644 index 0000000000..5388e27e09 --- /dev/null +++ b/backend/internal/service/gemini_tool_call_boundary.go @@ -0,0 +1,65 @@ +package service + +import ( + "encoding/json" + "strings" +) + +// geminiToolCallBoundary tracks identity separately from the function name. +// Native object-valued args without IDs represent independent calls, including +// identical calls. String-valued arguments use stream mode even when the first +// chunk is already complete JSON; retain duplicate strings and the terminal +// object snapshot in that call. Without IDs, a terminal snapshot and a new +// identical call after strings are indistinguishable; prefer the snapshot. +type geminiToolCallBoundary struct { + upstreamID string + stringArgs bool +} + +func (b *geminiToolCallBoundary) startsNewBlock(openName, seenJSON, argsJSON string, fc map[string]any) bool { + name, _ := fc["name"].(string) + if strings.TrimSpace(name) == "" { + name = "tool" + } + if name != openName { + return true + } + id, _ := fc["id"].(string) + if id != "" && b.upstreamID != "" { + return id != b.upstreamID + } + if !json.Valid([]byte(seenJSON)) { + return false + } + // Keep the existing delta accumulator's duplicate/rewind behavior for a + // string-argument call. Do not deduplicate separate complete native calls. + if b.stringArgs && strings.HasPrefix(seenJSON, strings.TrimSuffix(argsJSON, "\u0000")) { + return false + } + return true +} + +func (b *geminiToolCallBoundary) observe(fc map[string]any) { + if b.upstreamID == "" { + b.upstreamID, _ = fc["id"].(string) + } + // The representation determines the mode, not whether the first string + // happens to contain complete JSON. An object consumes the final snapshot, + // allowing the next anonymous native object to be an independent call. + _, b.stringArgs = fc["args"].(string) +} + +func geminiToolCallArgsJSON(args any) string { + switch v := args.(type) { + case nil: + case string: + if strings.TrimSpace(v) != "" { + return v + } + default: + if b, err := json.Marshal(args); err == nil && len(b) > 0 { + return string(b) + } + } + return "{}" +} diff --git a/backend/internal/service/model_rate_limit.go b/backend/internal/service/model_rate_limit.go index fc181de078..1081f4846f 100644 --- a/backend/internal/service/model_rate_limit.go +++ b/backend/internal/service/model_rate_limit.go @@ -244,3 +244,27 @@ func setAccountModelRateLimitSnapshot(account *Account, scope string, resetAt ti extra[modelRateLimitsKey] = limits account.Extra = extra } + +// clearAccountModelRateLimitSnapshot 从本账号对象的 Extra 快照中删除指定 scope, +// 让当前实例立刻停止跳过该模型,而不必等下一次快照重建。 +// 与 setAccountModelRateLimitSnapshot 一样写时复制,不修改可能共享的旧 map。 +func clearAccountModelRateLimitSnapshot(account *Account, scope string) { + if account == nil || strings.TrimSpace(scope) == "" { + return + } + oldLimits, ok := account.Extra[modelRateLimitsKey].(map[string]any) + if !ok { + return + } + if _, exists := oldLimits[scope]; !exists { + return + } + limits := make(map[string]any, len(oldLimits)) + maps.Copy(limits, oldLimits) + delete(limits, scope) + + extra := make(map[string]any, len(account.Extra)) + maps.Copy(extra, account.Extra) + extra[modelRateLimitsKey] = limits + account.Extra = extra +} diff --git a/backend/internal/service/openai_capacity_shed_test.go b/backend/internal/service/openai_capacity_shed_test.go index 6737e42cbd..ae060c02dd 100644 --- a/backend/internal/service/openai_capacity_shed_test.go +++ b/backend/internal/service/openai_capacity_shed_test.go @@ -241,6 +241,13 @@ func TestOpenAIStreamMetadataAndKeepaliveBeforeOverloadFailOver(t *testing.T) { require.True(t, failoverErr.RequestScopedTransient) require.Equal(t, http.StatusServiceUnavailable, failoverErr.ClientStatusCode) require.Contains(t, failoverErr.ClientMessage, "servers are currently overloaded") + if tt.name == "native" { + // Only the upstream keepalive events reach the client before first output. + require.Equal(t, "event: keepalive\ndata: {\"type\":\"keepalive\"}\n\ndata: {\"type\":\"keepalive\"}\n\n", rec.Body.String()) + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c)) + require.Empty(t, rec.Header().Get("X-Request-Id")) + return + } require.False(t, c.Writer.Written()) require.Empty(t, rec.Body.String()) }) @@ -354,6 +361,12 @@ func TestOpenAIStreamKeepaliveOnlyFailureDoesNotRecordFirstToken(t *testing.T) { require.ErrorAs(t, err, &failoverErr) require.True(t, failoverErr.RetryableOnSameAccount) require.True(t, failoverErr.RequestScopedTransient) + if !passthrough { + // Only the upstream keepalive event reaches the client before first output. + require.Equal(t, "data: {\"type\":\"keepalive\"}\n\n", rec.Body.String()) + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c)) + return + } require.Empty(t, rec.Body.String()) }) } diff --git a/backend/internal/service/openai_codex_account_identity.go b/backend/internal/service/openai_codex_account_identity.go index a7ce166165..39921cd530 100644 --- a/backend/internal/service/openai_codex_account_identity.go +++ b/backend/internal/service/openai_codex_account_identity.go @@ -46,6 +46,15 @@ func codexAccountIdentitySource(c *gin.Context, fallback *Account) *Account { return fallback } +// codexClientSessionID returns the client's own session header, before any +// outbound rewrite. +func codexClientSessionID(c *gin.Context) string { + if c == nil || c.Request == nil { + return "" + } + return extractClientSessionID(c.Request.Header) +} + // codexAccountIdentityNamespace returns a stable, credential-scoped namespace. // Multiple local rows that use the same ChatGPT account intentionally share the // same namespace. Setup tokens use an irreversible bearer fingerprint because @@ -162,7 +171,21 @@ func applyCodexAccountIdentityEmbeddedMetadata(values map[string]any, account *A return true } -func applyCodexAccountIdentityClientMetadataMap(requestBody map[string]any, account *Account, apiKeyID int64) bool { +// codexPromptCacheKeyKind scopes a prompt_cache_key that names the client's +// session in the session namespace, so it stays equal to the scoped session. +// Codex derives the key from its session-id header, which matches +// client_metadata.session_id except on an ephemeral fork such as thread/sample: +// the fork names itself in the metadata but keeps its parent's header and key. +func codexPromptCacheKeyKind(promptCacheKey, bodySessionID, clientSessionID string) string { + for _, sessionID := range []string{bodySessionID, clientSessionID} { + if strings.TrimSpace(sessionID) != "" && promptCacheKey == sessionID { + return "session" + } + } + return "prompt-cache" +} + +func applyCodexAccountIdentityClientMetadataMap(requestBody map[string]any, account *Account, apiKeyID int64, clientSessionID string) bool { if requestBody == nil || codexAccountIdentityNamespace(account) == "" { return false } @@ -179,10 +202,7 @@ func applyCodexAccountIdentityClientMetadataMap(requestBody map[string]any, acco } } if raw, ok := requestBody["prompt_cache_key"].(string); ok && strings.TrimSpace(raw) != "" { - kind := "prompt-cache" - if strings.TrimSpace(originalBodySessionID) != "" && raw == originalBodySessionID { - kind = "session" - } + kind := codexPromptCacheKeyKind(raw, originalBodySessionID, clientSessionID) next := scopeCodexAccountIdentityValue(account, apiKeyID, kind, raw) if next != raw { requestBody["prompt_cache_key"] = next @@ -195,7 +215,7 @@ func applyCodexAccountIdentityClientMetadataMap(requestBody map[string]any, acco // applyCodexAccountIdentityClientMetadataRaw scopes only the small identity // subobjects with gjson/sjson. The passthrough hot path never unmarshals the // potentially multi-megabyte request body. -func applyCodexAccountIdentityClientMetadataRaw(body []byte, account *Account, apiKeyID int64) ([]byte, bool, error) { +func applyCodexAccountIdentityClientMetadataRaw(body []byte, account *Account, apiKeyID int64, clientSessionID string) ([]byte, bool, error) { if len(body) == 0 || codexAccountIdentityNamespace(account) == "" { return body, false, nil } @@ -232,10 +252,7 @@ func applyCodexAccountIdentityClientMetadataRaw(body []byte, account *Account, a } if promptCacheKey := gjson.GetBytes(body, "prompt_cache_key"); promptCacheKey.Type == gjson.String && strings.TrimSpace(promptCacheKey.String()) != "" { raw := promptCacheKey.String() - kind := "prompt-cache" - if strings.TrimSpace(originalBodySessionID) != "" && raw == originalBodySessionID { - kind = "session" - } + kind := codexPromptCacheKeyKind(raw, originalBodySessionID, clientSessionID) scoped := scopeCodexAccountIdentityValue(account, apiKeyID, kind, raw) if scoped != raw { rewritten, err := sjson.SetBytes(next, "prompt_cache_key", scoped) diff --git a/backend/internal/service/openai_codex_account_identity_test.go b/backend/internal/service/openai_codex_account_identity_test.go index ffceba2d39..e0e864beb7 100644 --- a/backend/internal/service/openai_codex_account_identity_test.go +++ b/backend/internal/service/openai_codex_account_identity_test.go @@ -4,13 +4,17 @@ import ( "bytes" "context" "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" "github.com/tidwall/gjson" + "github.com/tidwall/sjson" ) type codexAccountIdentityRepoStub struct { @@ -27,13 +31,13 @@ func TestCodexRequestBodyIdentityNamespaceIsStablePerOAuthAccount(t *testing.T) account11 := &Account{ID: 11, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"chatgpt_account_id": "chatgpt-account-11"}} account19 := &Account{ID: 19, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"chatgpt_account_id": "chatgpt-account-19"}} - first, changed, err := applyCodexAccountIdentityClientMetadataRaw(body, account11, 77) + first, changed, err := applyCodexAccountIdentityClientMetadataRaw(body, account11, 77, "") require.NoError(t, err) require.True(t, changed) - firstAgain, changed, err := applyCodexAccountIdentityClientMetadataRaw(body, account11, 77) + firstAgain, changed, err := applyCodexAccountIdentityClientMetadataRaw(body, account11, 77, "") require.NoError(t, err) require.True(t, changed) - second, changed, err := applyCodexAccountIdentityClientMetadataRaw(body, account19, 77) + second, changed, err := applyCodexAccountIdentityClientMetadataRaw(body, account19, 77, "") require.NoError(t, err) require.True(t, changed) require.JSONEq(t, string(first), string(firstAgain)) @@ -228,3 +232,67 @@ func TestBuildUpstreamRequestNamespacesCodexIdentityByOAuthAccount(t *testing.T) } require.GreaterOrEqual(t, checked, 5, "test must exercise the real outbound identity surface") } + +// An ephemeral Codex fork, such as thread/sample, names itself in +// client_metadata.session_id but keeps its parent's session-id header and +// prompt_cache_key. Upstream, the fork must keep the parent's cache key. +func TestCodexForkKeepsParentPromptCacheKeyUpstream(t *testing.T) { + for _, passthrough := range []bool{false, true} { + t.Run(map[bool]string{false: "transformed", true: "passthrough"}[passthrough], func(t *testing.T) { + gin.SetMode(gin.TestMode) + forward := func(promptCacheKey, bodySessionID string) (http.Header, []byte) { + t.Helper() + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil)) + c.Request.Header.Set("User-Agent", "codex_cli_rs/0.167.0") + c.Request.Header.Set("originator", "codex_cli_rs") + c.Request.Header.Set("session-id", "parent-session") + body := []byte(`{"model":"gpt-5.6-sol","stream":false,"input":[{"type":"message","role":"user","content":"hi"}]}`) + body, err := sjson.SetBytes(body, "prompt_cache_key", promptCacheKey) + require.NoError(t, err) + body, err = sjson.SetBytes(body, "client_metadata.session_id", bodySessionID) + require.NoError(t, err) + + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid"}}, + Body: io.NopCloser(strings.NewReader("data: [DONE]\n\n")), + }} + svc := &OpenAIGatewayService{ + cfg: &config.Config{}, + httpUpstream: upstream, + toolCorrector: NewCodexToolCorrector(), + } + account := newTestOAuthAccount(4501, map[string]any{"openai_oauth_passthrough": passthrough}) + account.Status = StatusActive + account.Schedulable = true + account.Concurrency = 1 + account.Credentials = map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"} + + _, err = svc.Forward(context.Background(), c, account, body) + require.NoError(t, err) + require.NotNil(t, upstream.lastReq) + return upstream.lastReq.Header, upstream.lastBody + } + + parentHeader, parentBody := forward("parent-session", "parent-session") + parentKey := gjson.GetBytes(parentBody, "prompt_cache_key").String() + require.NotEqual(t, "parent-session", parentKey, "the key is account-scoped") + require.Equal(t, gjson.GetBytes(parentBody, "client_metadata.session_id").String(), parentKey) + + forkHeader, forkBody := forward("parent-session", "fork-session") + require.Equal(t, parentKey, gjson.GetBytes(forkBody, "prompt_cache_key").String(), + "a fork keeps its parent's upstream cache key") + require.Equal(t, parentHeader.Get("session_id"), forkHeader.Get("session_id")) + require.NotEqual(t, + gjson.GetBytes(parentBody, "client_metadata.session_id").String(), + gjson.GetBytes(forkBody, "client_metadata.session_id").String(), + "the fork keeps its own session identity", + ) + + _, customBody := forward("caller-cache-key", "parent-session") + require.NotEqual(t, parentKey, gjson.GetBytes(customBody, "prompt_cache_key").String(), + "a caller-chosen key keeps its own namespace") + }) + } +} diff --git a/backend/internal/service/openai_codex_additional_tools_test.go b/backend/internal/service/openai_codex_additional_tools_test.go new file mode 100644 index 0000000000..d11fe49480 --- /dev/null +++ b/backend/internal/service/openai_codex_additional_tools_test.go @@ -0,0 +1,217 @@ +package service + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "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 TestFilterCodexInput_AdditionalToolsDeclarationID(t *testing.T) { + for _, preserveReferences := range []bool{false, true} { + t.Run(fmt.Sprintf("references=%t", preserveReferences), func(t *testing.T) { + input := []any{ + map[string]any{ + "type": "additional_tools", "id": "at_discovery", "role": "developer", + "tools": []any{map[string]any{"type": "tool_search", "execution": "client"}}, + }, + map[string]any{"type": "message", "id": "msg_history", "role": "user", "content": "find a tool"}, + map[string]any{"type": "reasoning", "id": "rs_history", "encrypted_content": "sealed", "summary": []any{}}, + map[string]any{"type": "item_reference", "id": "msg_reference"}, + } + original, err := json.Marshal(input) + require.NoError(t, err) + + filtered := filterCodexInput(input, preserveReferences) + encoded, err := json.Marshal(filtered) + require.NoError(t, err) + require.Equal(t, "at_discovery", gjson.GetBytes(encoded, "0.id").String()) + require.Equal(t, "tool_search", gjson.GetBytes(encoded, "0.tools.0.type").String()) + require.Equal(t, preserveReferences, gjson.GetBytes(encoded, "1.id").Exists()) + require.False(t, gjson.GetBytes(encoded, "2.id").Exists()) + require.Equal(t, "sealed", gjson.GetBytes(encoded, "2.encrypted_content").String()) + require.Equal(t, preserveReferences, gjson.GetBytes(encoded, "3.id").Exists()) + after, err := json.Marshal(input) + require.NoError(t, err) + require.JSONEq(t, string(original), string(after), "filtering must not mutate the caller's input") + }) + } +} + +func TestFilterCodexInput_AdditionalToolsUUID(t *testing.T) { + const uuidID = "at_00112233-4455-4677-8899-aabbccddeeff" + const compactID = "at_00112233445546778899aabbccddeeff" + for _, tc := range []struct { + name string + id any + want any + }{ + {"hyphenated", uuidID, compactID}, + {"uppercase", "at_00112233-4455-4677-8899-AABBCCDDEEFF", "at_00112233445546778899AABBCCDDEEFF"}, + {"compact", compactID, compactID}, + {"opaque", "at_discovery", "at_discovery"}, + {"wrong_prefix", "xx_00112233-4455-4677-8899-aabbccddeeff", "xx_00112233-4455-4677-8899-aabbccddeeff"}, + {"non_hex", "at_z0112233-4455-4677-8899-aabbccddeeff", "at_z0112233-4455-4677-8899-aabbccddeeff"}, + {"misplaced_hyphen", "at_0011223-34455-4677-8899-aabbccddeeff", "at_0011223-34455-4677-8899-aabbccddeeff"}, + {"extra_hyphens", "at_0011223--4455-4677-8899-aabbccddeef-", "at_0011223--4455-4677-8899-aabbccddeef-"}, + {"short", "at_00112233-4455-4677-8899-aabbccddee", "at_00112233-4455-4677-8899-aabbccddee"}, + {"whitespace", " " + uuidID, " " + uuidID}, + {"numeric", 42, 42}, + {"null", nil, nil}, + } { + for _, preserveReferences := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/references=%t", tc.name, preserveReferences), func(t *testing.T) { + declaration := map[string]any{ + "type": "additional_tools", "id": tc.id, "role": "developer", + "tools": []any{map[string]any{"type": "tool_search", "execution": "client"}}, + } + reference := map[string]any{"type": "item_reference", "id": tc.id} + input := []any{declaration, reference} + filtered := filterCodexInput(input, preserveReferences) + want := map[string]any{ + "type": "additional_tools", "id": tc.want, "role": "developer", "tools": declaration["tools"], + } + require.Equal(t, want, filtered[0]) + if preserveReferences { + require.Equal(t, map[string]any{"type": "item_reference", "id": tc.want}, filtered[1]) + } else { + require.Len(t, filtered, 1) + } + require.Equal(t, tc.id, declaration["id"], "normalization must not mutate the declaration") + require.Equal(t, tc.id, reference["id"], "normalization must not mutate references") + require.Equal(t, filtered, filterCodexInput(filtered, preserveReferences), "normalization must be idempotent") + }) + } + } + + t.Run("only_declared_tools", func(t *testing.T) { + input := []any{ + map[string]any{"type": "additional_tools", "tools": []any{}}, + map[string]any{"type": "message", "id": "msg_00112233-4455-4677-8899-aabbccddeeff", "role": "user", "content": "hello"}, + map[string]any{"type": "item_reference", "id": uuidID}, + map[string]any{"type": "item_reference", "id": "at_11112233-4455-4677-8899-aabbccddeeff"}, + } + require.Equal(t, input, filterCodexInput(input, true), "do not invent IDs or rewrite unrelated history/references") + }) +} + +func TestOpenAIResponsesCompatibility_AdditionalToolsUUID(t *testing.T) { + const uuidID = "at_00112233-4455-4677-8899-aabbccddeeff" + const compactID = "at_00112233445546778899aabbccddeeff" + for _, accountType := range []string{AccountTypeOAuth, AccountTypeAPIKey} { + t.Run(accountType, func(t *testing.T) { + body := []byte(`{"model":"gpt-6.1-sol","marker":"\u0061","number":9007199254740993,"input":[` + + `{"type":"item_reference","id":"` + uuidID + `"},` + + `{"type":"additional_tools","id":"` + uuidID + `","role":"developer","tools":[{"type":"tool_search","execution":"client"}]},` + + `{"type":"future_item","id":"` + uuidID + `"},` + + `{"type":"additional_tools","id":"at_discovery","tools":[]},` + + `{"type":"additional_tools","id":"at_z0112233-4455-4677-8899-aabbccddeeff","tools":[]},` + + `{"type":"message","id":"msg_test","role":"user","content":"` + uuidID + `"}]}`) + original := bytes.Clone(body) + account := &Account{Platform: PlatformOpenAI, Type: accountType} + normalized, changed, err := normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, account, openAIResponsesCompatibilityOptions{}) + require.NoError(t, err) + require.Equal(t, accountType == AccountTypeOAuth, changed) + wantID := uuidID + if accountType == AccountTypeOAuth { + wantID = compactID + } + require.Equal(t, wantID, gjson.GetBytes(normalized, "input.0.id").String(), "references can precede declarations") + require.Equal(t, wantID, gjson.GetBytes(normalized, "input.1.id").String()) + for _, index := range []int{2, 3, 4, 5} { + path := fmt.Sprintf("input.%d", index) + require.Equal(t, gjson.GetBytes(body, path).Raw, gjson.GetBytes(normalized, path).Raw) + } + require.Equal(t, `"\u0061"`, gjson.GetBytes(normalized, "marker").Raw) + require.Equal(t, "9007199254740993", gjson.GetBytes(normalized, "number").Raw) + require.Equal(t, original, body) + again, changed, err := normalizeOpenAIResponsesCompatibilityBodyWithOptions(normalized, account, openAIResponsesCompatibilityOptions{}) + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, normalized, again) + }) + } + t.Run("undeclared_reference", func(t *testing.T) { + body := []byte(`{"model":"gpt-6.1-sol","input":[{"type":"item_reference","id":"` + uuidID + `"}]}`) + normalized, changed, err := normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth}, openAIResponsesCompatibilityOptions{}) + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, body, normalized) + }) +} + +func TestOpenAIGatewayService_OAuthAdditionalToolsDeclarationID(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, passthrough := range []bool{false, true} { + for _, lite := range []bool{false, true} { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("passthrough=%t/lite=%t/stream=%t", passthrough, lite, stream), func(t *testing.T) { + body := []byte(fmt.Sprintf(`{ + "model":"gpt-6.1-sol","stream":%t,"store":false,"instructions":"test instructions", + "input":[ + {"type":"additional_tools","id":"at_00112233-4455-4677-8899-aabbccddeeff","role":"developer","tools":[ + {"type":"tool_search","execution":"client"}, + {"type":"namespace","name":"multi_agent_v1","tools":[{"type":"function","name":"spawn_agent","parameters":{"type":"object"},"defer_loading":true}]} + ]}, + {"type":"message","id":"msg_history","role":"user","content":[{"type":"input_text","text":"find spawn_agent"}]}, + {"type":"reasoning","id":"rs_history","encrypted_content":"sealed","summary":[]} + ] + }`, stream)) + upstreamSSE := strings.Join([]string{ + `data: {"type":"response.output_item.added","output_index":0,"item":{"type":"tool_search_call","id":"tsc_discovery","call_id":"tsc_discovery","execution":"client","arguments":"{\"query\":\"spawn_agent\"}"}}`, + "", + `data: {"type":"response.output_item.done","output_index":0,"item":{"type":"tool_search_call","id":"tsc_discovery","call_id":"tsc_discovery","execution":"client","arguments":"{\"query\":\"spawn_agent\"}"}}`, + "", + `data: {"type":"response.completed","response":{"id":"resp_discovery","status":"completed","model":"gpt-6.1-sol","output":[{"type":"tool_search_call","id":"tsc_discovery","call_id":"tsc_discovery","execution":"client","arguments":"{\"query\":\"spawn_agent\"}"}],"usage":{"input_tokens":2,"output_tokens":1,"total_tokens":3}}}`, + "", "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(upstreamSSE)), + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := &Account{ + ID: 8752, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "test-token", "chatgpt_account_id": "test-account"}, + Extra: map[string]any{"openai_passthrough": passthrough}, + Status: StatusActive, Schedulable: true, + } + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + c.Request.Header.Set("User-Agent", "codex_cli_rs/0.167.0") + if lite { + c.Request.Header.Set(responsesLiteHeader, "true") + } + + result, err := svc.Forward(context.Background(), c, account, body) + + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, "https://chatgpt.com/backend-api/codex/responses", upstream.lastReq.URL.String()) + wantID := "at_00112233445546778899aabbccddeeff" + require.Equal(t, wantID, gjson.GetBytes(upstream.lastBody, "input.0.id").String()) + require.Equal(t, "at_00112233-4455-4677-8899-aabbccddeeff", gjson.GetBytes(body, "input.0.id").String()) + require.JSONEq(t, gjson.GetBytes(body, "input.0.tools").Raw, gjson.GetBytes(upstream.lastBody, "input.0.tools").Raw) + require.Equal(t, passthrough, gjson.GetBytes(upstream.lastBody, "input.1.id").Exists()) + require.Equal(t, passthrough, gjson.GetBytes(upstream.lastBody, "input.2.id").Exists()) + require.Equal(t, "sealed", gjson.GetBytes(upstream.lastBody, "input.2.encrypted_content").String()) + require.Contains(t, recorder.Body.String(), `"type":"tool_search_call"`) + require.Contains(t, recorder.Body.String(), `"call_id":"tsc_discovery"`) + require.NotContains(t, recorder.Body.String(), `"type":"function_call"`) + }) + } + } + } +} diff --git a/backend/internal/service/openai_codex_transform.go b/backend/internal/service/openai_codex_transform.go index f4b33dbab3..1d369c3f23 100644 --- a/backend/internal/service/openai_codex_transform.go +++ b/backend/internal/service/openai_codex_transform.go @@ -8,6 +8,8 @@ import ( "strings" "github.com/Wei-Shaw/sub2api/internal/pkg/openai" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" ) var codexModelMap = map[string]string{ @@ -1607,9 +1609,84 @@ func codexInputCallIDs(input []any) map[string]struct{} { return callIDs } +// Only compact UUID-shaped declaration IDs; other provider IDs are opaque. +func normalizeCodexAdditionalToolsID(id string) string { + if len(id) != 39 || !strings.HasPrefix(id, "at_") || + id[11] != '-' || id[16] != '-' || id[21] != '-' || id[26] != '-' { + return id + } + compactUUID := strings.ReplaceAll(id[3:], "-", "") + if len(compactUUID) != 32 { + return id + } + if _, err := hex.DecodeString(compactUUID); err != nil { + return id + } + return "at_" + compactUUID +} + +func codexAdditionalToolsIDMappings(input []any) map[string]string { + mappings := make(map[string]string) + for _, rawItem := range input { + item, ok := rawItem.(map[string]any) + if !ok || item["type"] != "additional_tools" { + continue + } + if id, ok := item["id"].(string); ok { + if normalizedID := normalizeCodexAdditionalToolsID(id); normalizedID != id { + mappings[id] = normalizedID + } + } + } + return mappings +} + +// The passthrough/WebSocket compatibility path must not decode and re-encode +// whole requests. Patch only declaration IDs and references to those declarations. +func normalizeCodexAdditionalToolsIDsBody(body []byte) ([]byte, bool, error) { + input := parseRawJSONView(body).Get("input") + if !input.IsArray() { + return body, false, nil + } + mappings := make(map[string]string) + input.ForEach(func(_, item gjson.Result) bool { + if id := item.Get("id"); item.Get("type").String() == "additional_tools" && id.Type == gjson.String { + if normalizedID := normalizeCodexAdditionalToolsID(id.Str); normalizedID != id.Str { + mappings[id.Str] = normalizedID + } + } + return true + }) + if len(mappings) == 0 { + return body, false, nil + } + items := make([]string, 0) + var patchErr error + input.ForEach(func(_, item gjson.Result) bool { + raw := item.Raw + if typ := item.Get("type").String(); typ == "additional_tools" || typ == "item_reference" { + if id := item.Get("id"); id.Type == gjson.String { + if normalizedID, mapped := mappings[id.Str]; mapped { + raw, patchErr = sjson.Set(raw, "id", normalizedID) + if patchErr != nil { + return false + } + } + } + } + items = append(items, raw) + return true + }) + if patchErr != nil { + return body, false, fmt.Errorf("normalize additional_tools ID: %w", patchErr) + } + return replaceOpenAIRawInput(body, input, items), true, nil +} + func filterCodexInputWithOptions(input []any, opts codexInputFilterOptions) []any { filtered := make([]any, 0, len(input)) referenceIDMappings := codexItemReferenceIDMappings(input, opts.PreserveCallIDs) + additionalToolsIDMappings := codexAdditionalToolsIDMappings(input) inputItemIDs := codexInputItemIDs(input) inputCallIDs := codexInputCallIDs(input) for _, item := range input { @@ -1672,6 +1749,11 @@ func filterCodexInputWithOptions(input []any, opts codexInputFilterOptions) []an for key, value := range m { newItem[key] = value } + if id, ok := newItem["id"].(string); ok { + if normalizedID, mapped := additionalToolsIDMappings[id]; mapped { + newItem["id"] = normalizedID + } + } if id, ok := newItem["id"].(string); ok && strings.HasPrefix(strings.TrimSpace(id), "call_") { trimmedID := strings.TrimSpace(id) _, referencesExistingItem := inputItemIDs[trimmedID] @@ -1743,7 +1825,17 @@ func filterCodexInputWithOptions(input []any, opts codexInputFilterOptions) []an } } - if !opts.PreserveReferences { + // additional_tools IDs identify declarations carried in this request, + // not stored history. Removing them can change native tool discovery + // into ordinary function calls even with store=false. + if typ == "additional_tools" { + if id, ok := m["id"].(string); ok { + if normalizedID, mapped := additionalToolsIDMappings[id]; mapped { + ensureCopy() + newItem["id"] = normalizedID + } + } + } else if !opts.PreserveReferences { ensureCopy() delete(newItem, "id") } else if id, ok := m["id"].(string); ok && shouldStripOpenAIResponsesInputItemID(typ, id) { diff --git a/backend/internal/service/openai_codex_turn_metadata_test.go b/backend/internal/service/openai_codex_turn_metadata_test.go index a3a5b4773b..94d132f571 100644 --- a/backend/internal/service/openai_codex_turn_metadata_test.go +++ b/backend/internal/service/openai_codex_turn_metadata_test.go @@ -24,7 +24,7 @@ func TestCodexTurnMetadataRewritePreservesHeaderSafeJSON(t *testing.T) { }, "account_body_map": func(t *testing.T, raw string) string { cm := map[string]any{openAIWSTurnMetadataHeader: raw} - require.True(t, applyCodexAccountIdentityClientMetadataMap(map[string]any{"client_metadata": cm}, account, 77)) + require.True(t, applyCodexAccountIdentityClientMetadataMap(map[string]any{"client_metadata": cm}, account, 77, "")) value, ok := cm[openAIWSTurnMetadataHeader].(string) require.True(t, ok) return value @@ -32,7 +32,7 @@ func TestCodexTurnMetadataRewritePreservesHeaderSafeJSON(t *testing.T) { "account_body_raw": func(t *testing.T, raw string) string { body, err := json.Marshal(map[string]any{"client_metadata": map[string]any{openAIWSTurnMetadataHeader: raw}}) require.NoError(t, err) - updated, changed, err := applyCodexAccountIdentityClientMetadataRaw(body, account, 77) + updated, changed, err := applyCodexAccountIdentityClientMetadataRaw(body, account, 77, "") require.NoError(t, err) require.True(t, changed) return gjson.GetBytes(updated, "client_metadata."+openAIWSTurnMetadataHeader).String() diff --git a/backend/internal/service/openai_compat_model_test.go b/backend/internal/service/openai_compat_model_test.go index 7bd000b4b8..97d1c5fd26 100644 --- a/backend/internal/service/openai_compat_model_test.go +++ b/backend/internal/service/openai_compat_model_test.go @@ -2159,7 +2159,10 @@ func TestForwardAsAnthropic_MissingTerminalAfterClientDisconnectSkipsOpsAndFailo c, _ := gin.CreateTestContext(rec) c.Writer = &openAICompatFailingWriter{ResponseWriter: c.Writer, failAfter: 0} body := []byte(`{"model":"gpt-5.4","max_tokens":16,"messages":[{"role":"user","content":"hello"}],"stream":true}`) - c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + // A real disconnect also cancels the request context. + reqCtx, cancel := context.WithCancel(context.Background()) + cancel() + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)).WithContext(reqCtx) c.Request.Header.Set("Content-Type", "application/json") upstreamBody := strings.Join([]string{ diff --git a/backend/internal/service/openai_first_output_timeout.go b/backend/internal/service/openai_first_output_timeout.go index 3b47fdd7d4..438ec17f4d 100644 --- a/backend/internal/service/openai_first_output_timeout.go +++ b/backend/internal/service/openai_first_output_timeout.go @@ -145,7 +145,10 @@ func (s *openAIFirstOutputStage) prepareWrite(incoming int) error { } file, err := s.createTemp() if err != nil { - return fmt.Errorf("create first-output spool: %w", err) + // Unavailable temporary storage must not fail an otherwise valid stream. + // Keep buffering in memory under the same stage limit. + s.memoryOnly = true + return nil } path := file.Name() // Unlink before writing any request data. Unix keeps the file descriptor diff --git a/backend/internal/service/openai_first_output_timeout_test.go b/backend/internal/service/openai_first_output_timeout_test.go index ebab68c019..b1d392ad73 100644 --- a/backend/internal/service/openai_first_output_timeout_test.go +++ b/backend/internal/service/openai_first_output_timeout_test.go @@ -9,6 +9,7 @@ import ( "net/http" "net/http/httptest" "os" + "path/filepath" "runtime" "strings" "sync" @@ -284,6 +285,84 @@ func TestOpenAIFirstOutputStageCommitCopiesSpoolAndRemovesTemp(t *testing.T) { require.NoError(t, stage.Close()) } +func TestOpenAIFirstOutputStageCreateFailurePreservesBoundedBuffer(t *testing.T) { + for _, useWriteString := range []bool{false, true} { + t.Run(fmt.Sprintf("write_string_%t", useWriteString), func(t *testing.T) { + stage := newOpenAIFirstOutputStage(70 * 1024) + stage.memoryOnly = false + t.Cleanup(func() { require.NoError(t, stage.Close()) }) + createCalls := 0 + stage.createTemp = func() (*os.File, error) { + createCalls++ + return nil, &os.PathError{Op: "open", Path: "unwritable/spool", Err: os.ErrPermission} + } + stage.removeFile = func(string) error { + t.Fatal("failed creation must not leave a spool to remove") + return nil + } + write := func(value string) (int, error) { + if useWriteString { + return stage.WriteString(value) + } + return stage.Write([]byte(value)) + } + + payload := "" + for _, chunk := range []string{strings.Repeat("a", 32*1024), strings.Repeat("b", 36*1024), strings.Repeat("c", 2*1024)} { + n, err := write(chunk) + require.NoError(t, err) + require.Equal(t, len(chunk), n) + payload += chunk + } + require.Equal(t, 1, createCalls, "fallback must not retry CreateTemp on later writes") + require.EqualValues(t, len(payload), stage.Buffered()) + + n, err := write("overflow") + require.Zero(t, n) + require.ErrorIs(t, err, errOpenAIFirstOutputStageLimit) + require.EqualValues(t, len(payload), stage.Buffered()) + var downstream bytes.Buffer + require.NoError(t, stage.CommitTo(&downstream)) + require.Equal(t, payload, downstream.String()) + require.Zero(t, stage.Buffered()) + }) + } +} + +func TestOpenAINativeFirstOutputWithUnavailableTempDir(t *testing.T) { + missingDir := filepath.Join(t.TempDir(), "missing") + for _, name := range []string{"TMPDIR", "TMP", "TEMP"} { + t.Setenv(name, missingDir) + } + cfg := &config.Config{Gateway: config.GatewayConfig{ + OpenAIFirstOutputTimeoutSeconds: 30, + MaxLineSize: defaultMaxLineSize, + }} + svc := &OpenAIGatewayService{cfg: cfg, responseHeaderFilter: compileResponseHeaderFilter(cfg)} + // Cross the disk-spill threshold before any semantic output is available. + preamble := `data: {"type":"response.created","response":{"id":"resp_no_temp","created_at":1700000000,"padding":"` + strings.Repeat("x", 68*1024) + `"}}` + "\n\n" + delta := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"hello\"}\n\n" + payload := preamble + delta + + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_no_temp\",\"usage\":{\"input_tokens\":3,\"output_tokens\":2}}}\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-no-temp"}, + }, 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.True(t, strings.HasPrefix(rec.Body.String(), preamble+delta), "buffered preamble and first output must be forwarded intact") + require.Contains(t, rec.Body.String(), `"type":"response.completed"`) + require.Equal(t, 3, result.usage.InputTokens) + require.Equal(t, 2, result.usage.OutputTokens) + require.Equal(t, "request-no-temp", rec.Header().Get("X-Request-Id")) +} + func TestOpenAIFirstOutputStageUnlinkFailurePermanentlyFallsBackToMemoryAndRetriesCleanup(t *testing.T) { stage := newDefaultOpenAIFirstOutputStage() stage.memoryOnly = false diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index c340de7c49..befaa75d7b 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -285,7 +285,7 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions( } else if promptCacheKey != "" { reqBody["prompt_cache_key"] = promptCacheKey } - applyCodexAccountIdentityClientMetadataMap(reqBody, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c)) + applyCodexAccountIdentityClientMetadataMap(reqBody, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c), codexClientSessionID(c)) responsesBody, err = json.Marshal(reqBody) if err != nil { return nil, fmt.Errorf("remarshal after codex transform: %w", err) @@ -974,6 +974,7 @@ func (s *OpenAIGatewayService) handleChatStreamingResponse( streamFailoverErr = s.newOpenAIStreamFailoverErrorWithModel(c, account, false, requestID, payloadBytes, message, upstreamModel, resp.Header) return true } + s.handleOpenAIStreamTerminalAccountSideEffects(c, account, payloadBytes, message, resp.Header, upstreamModel) message = s.recordOpenAIStreamUpstreamError(c, account, false, requestID, "http_error", payloadBytes, message) defaultStatus, defaultErrType, defaultMsg := http.StatusBadGateway, "upstream_error", message // 统一走语义状态推断 + body 归一化(与 /v1/responses 路径一致), diff --git a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go index 5c2d86b87d..7c06556352 100644 --- a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go +++ b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go @@ -42,6 +42,7 @@ func (s *OpenAIGatewayService) forwardChatCompletionsViaNativeAnthropic( defaultMappedModel string, ) (*OpenAIForwardResult, error) { startTime := time.Now() + SetActualOpenAIUpstreamEndpoint(c, "/v1/messages") // 1. Parse Chat Completions request var ccReq apicompat.ChatCompletionsRequest @@ -93,6 +94,7 @@ func (s *OpenAIGatewayService) forwardChatCompletionsViaNativeAnthropic( if err != nil { return nil, fmt.Errorf("marshal anthropic request: %w", err) } + anthropicBody = withChatCompletionsMetadataUserID(body, anthropicBody) // 与 /v1/messages 直通路径相同的 pre-filter。 anthropicBody = StripEmptyTextBlocks(anthropicBody) @@ -410,7 +412,7 @@ func (s *OpenAIGatewayService) handleCCStreamingFromNativeAnthropic( if err != nil { return false } - out := string(reverseToolNamesIfPresent(c, []byte(sse))) + out := reverseToolNamesIfPresentString(c, sse) if _, err := fmt.Fprint(c.Writer, out); err != nil { clientDisconnected = true return false diff --git a/backend/internal/service/openai_gateway_chat_fallback_observation_test.go b/backend/internal/service/openai_gateway_chat_fallback_observation_test.go new file mode 100644 index 0000000000..6aa69b3a56 --- /dev/null +++ b/backend/internal/service/openai_gateway_chat_fallback_observation_test.go @@ -0,0 +1,162 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func chatObservationResponse(t *testing.T, stream bool, model string, conflict, readError, invalidTool bool) *http.Response { + t.Helper() + encode := func(v any) string { + b, err := json.Marshal(v) + require.NoError(t, err) + return string(b) + } + usage := map[string]int{"prompt_tokens": 20, "completion_tokens": 10, "total_tokens": 30} + payload := map[string]any{"id": "chatcmpl_observed", "service_tier": "default", "usage": usage} + if model != "" { + payload["model"] = model + } + payload["choices"] = []any{map[string]any{ + "index": 0, "message": map[string]string{"role": "assistant", "content": "observed response"}, "finish_reason": "stop", + }} + wire := encode(payload) + contentType := "application/json" + if stream { + contentType = "text/event-stream" + payload["choices"] = []any{map[string]any{ + "index": 0, "delta": map[string]string{"role": "assistant", "content": "observed response"}, "finish_reason": nil, + }} + if invalidTool { + payload["choices"] = []any{map[string]any{"index": 0, "delta": map[string]any{ + "tool_calls": []any{map[string]any{"index": 0, "id": "call_bad", "type": "function", + "function": map[string]string{"name": "lookup", "arguments": "{"}}}, + }, "finish_reason": nil}} + } + wire = "data: " + encode(payload) + "\n\n" + if conflict { + payload["model"] = "conflicting-model" + wire += "data: " + encode(payload) + "\n\n" + } + if !readError { + wire += "data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":20,\"completion_tokens\":10,\"total_tokens\":30}}\n\n" + + "data: [DONE]\n\n" + } + } + var body io.ReadCloser = io.NopCloser(strings.NewReader(wire)) + if readError { + body = &errTailReader{data: []byte(wire), err: io.ErrUnexpectedEOF} + } + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{ + "Content-Type": []string{contentType}, "X-Request-Id": []string{"chat-observed"}, + }, Body: body} +} + +func TestChatFallbackResponseObservationReachesUsage(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, endpoint := range []string{"messages", "responses"} { + for _, tt := range []struct { + name string + stream bool + model string + conflict bool + readError bool + disconnect bool + invalidTool bool + }{ + {name: "buffered matching", model: "gpt-5.4"}, + {name: "buffered mismatch", model: "reported-model"}, + {name: "buffered undeclared"}, + {name: "stream matching", stream: true, model: "gpt-5.4"}, + {name: "stream mismatch", stream: true, model: "reported-model"}, + {name: "stream undeclared", stream: true}, + {name: "stream conflicting", stream: true, model: "reported-model", conflict: true}, + {name: "stream read error", stream: true, model: "reported-model", readError: true}, + {name: "client disconnected", stream: true, model: "reported-model", disconnect: true}, + {name: "invalid tool arguments", stream: true, model: "reported-model", invalidTool: true}, + } { + if tt.invalidTool && endpoint != "responses" { + continue + } + t.Run(endpoint+"/"+tt.name, func(t *testing.T) { + request := map[string]any{"model": "gpt-5.4", "stream": tt.stream} + if endpoint == "messages" { + request["max_tokens"] = 32 + request["messages"] = []map[string]string{{"role": "user", "content": "hi"}} + } else { + request["input"] = "hi" + } + body, err := json.Marshal(request) + require.NoError(t, err) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/"+endpoint, strings.NewReader(string(body))) + c.Request.Header.Set("Content-Type", "application/json") + if tt.disconnect { + c.Writer = &failWriteResponseWriter{ResponseWriter: c.Writer} + } + upstream := &httpUpstreamRecorder{resp: chatObservationResponse(t, tt.stream, tt.model, tt.conflict, tt.readError, tt.invalidTool)} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := forceChatMessagesFallbackAccount() + var result *OpenAIForwardResult + if endpoint == "messages" { + result, err = svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + } else { + account = forceChatResponsesFallbackAccount() + result, err = svc.Forward(context.Background(), c, account, body) + } + if tt.readError || tt.invalidTool { + require.Error(t, err) + } else { + require.NoError(t, err) + } + require.NotNil(t, result) + require.Equal(t, "/v1/chat/completions", upstream.lastReq.URL.Path) + require.Equal(t, "gpt-5.4", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, "gpt-5.4", result.Model) + require.Equal(t, "gpt-5.4", result.UpstreamModel) + require.Equal(t, 20, result.Usage.InputTokens) + require.Equal(t, 10, result.Usage.OutputTokens) + if !tt.disconnect && !tt.invalidTool { + require.Contains(t, rec.Body.String(), "observed response") + } + require.Equal(t, tt.model, observedUpstreamResponseModel(c), "the shared pipeline already saw the upstream model") + wantTier := "default" + if tt.model == "" { + wantTier = "" + } + require.Equal(t, wantTier, result.UpstreamResponseServiceTier) + + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + usageSvc := newOpenAIRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) + require.NoError(t, usageSvc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: result, APIKey: &APIKey{ID: 10}, User: &User{ID: 20}, Account: account, + })) + require.NotNil(t, usageRepo.lastLog) + log := usageRepo.lastLog + if tt.model == "" { + require.Nil(t, log.UpstreamResponseModel) + require.Nil(t, log.UpstreamModelMismatch) + } else { + require.NotNil(t, log.UpstreamResponseModel) + require.Equal(t, tt.model, *log.UpstreamResponseModel) + require.NotNil(t, log.UpstreamModelMismatch) + require.Equal(t, tt.model != "gpt-5.4", *log.UpstreamModelMismatch) + } + require.Equal(t, tt.model, result.UpstreamResponseModel) + require.Equal(t, tt.conflict, result.UpstreamResponseModelConflict) + }) + } + } +} diff --git a/backend/internal/service/openai_gateway_compat_stream_account_side_effects_test.go b/backend/internal/service/openai_gateway_compat_stream_account_side_effects_test.go new file mode 100644 index 0000000000..a6f47ec8d4 --- /dev/null +++ b/backend/internal/service/openai_gateway_compat_stream_account_side_effects_test.go @@ -0,0 +1,145 @@ +package service + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// compatStreamSideEffectsRepo records the account-health writes made by the rate limit service. +type compatStreamSideEffectsRepo struct { + stubOpenAIAccountRepo + rateLimitCalls []time.Time + errorCalls []string +} + +func (r *compatStreamSideEffectsRepo) SetRateLimited(_ context.Context, _ int64, resetAt time.Time) error { + r.rateLimitCalls = append(r.rateLimitCalls, resetAt) + return nil +} + +func (r *compatStreamSideEffectsRepo) SetError(_ context.Context, _ int64, msg string) error { + r.errorCalls = append(r.errorCalls, msg) + return nil +} + +func compatStreamSideEffectsAccount() Account { + return Account{ + ID: 601, + Name: "openai-apikey-compat-stream", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test"}, + } +} + +// compatStreamSideEffectsSSE builds an upstream responses stream that fails with errorEvent. +// With outputFirst the error follows response.created and a text delta, so client output has +// started (in practice response.created alone already starts it on both compat paths); without, +// the error is the first event and the request can still fail over. +func compatStreamSideEffectsSSE(outputFirst bool, errorEvent string) string { + var lines []string + if outputFirst { + lines = append(lines, + `data: {"type":"response.created","response":{"id":"resp_side","model":"gpt-5.5","status":"in_progress","output":[]}}`, + "", + `data: {"type":"response.output_text.delta","item_id":"msg_1","output_index":0,"content_index":0,"delta":"partial"}`, + "", + ) + } + lines = append(lines, `event: error`, `data: `+errorEvent, "") + return strings.Join(lines, "\n") +} + +const compatStreamAuthErrorEvent = `{"type":"error","status":401,"error":{"code":"invalid_api_key","type":"invalid_request_error","message":"Incorrect API key provided"}}` + +func newCompatStreamSideEffectsService(sse string) (*OpenAIGatewayService, *compatStreamSideEffectsRepo, *Account) { + account := compatStreamSideEffectsAccount() + repo := &compatStreamSideEffectsRepo{stubOpenAIAccountRepo: stubOpenAIAccountRepo{accounts: []Account{account}}} + svc := &OpenAIGatewayService{ + accountRepo: repo, + rateLimitService: &RateLimitService{accountRepo: repo}, + httpUpstream: &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid_side"}}, + Body: io.NopCloser(strings.NewReader(sse)), + }}, + } + return svc, repo, &account +} + +func newCompatStreamContext(path string, body []byte) (*gin.Context, *httptest.ResponseRecorder) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + return c, rec +} + +// A terminal stream error that arrives after client output started can no longer fail over, but the +// account health still has to be updated — otherwise the account stays schedulable and every new +// request routed to it fails the same way. +func TestForwardAsChatCompletions_StreamErrorAfterOutputAppliesAccountSideEffects(t *testing.T) { + svc, repo, account := newCompatStreamSideEffectsService(compatStreamSideEffectsSSE(true, compatStreamAuthErrorEvent)) + body := []byte(`{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}],"stream":true}`) + c, rec := newCompatStreamContext("/v1/chat/completions", body) + + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "gpt-5.5") + require.Error(t, err) + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr), "output already started: must not fail over") + require.Contains(t, rec.Body.String(), "partial", "client output must have started before the error") + require.Len(t, repo.errorCalls, 1, "auth failure after output must mark the account exactly once") + require.Empty(t, repo.rateLimitCalls) +} + +func TestForwardAsAnthropic_StreamErrorAfterOutputAppliesAccountSideEffects(t *testing.T) { + svc, repo, account := newCompatStreamSideEffectsService(compatStreamSideEffectsSSE(true, compatStreamAuthErrorEvent)) + body := []byte(`{"model":"gpt-5.5","max_tokens":1024,"messages":[{"role":"user","content":"hi"}],"stream":true}`) + c, rec := newCompatStreamContext("/v1/messages", body) + + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "gpt-5.5") + require.Error(t, err) + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr), "output already started: must not fail over") + require.Contains(t, rec.Body.String(), "partial", "client output must have started before the error") + require.Len(t, repo.errorCalls, 1, "auth failure after output must mark the account exactly once") + require.Empty(t, repo.rateLimitCalls) +} + +// Before client output the error fails over; the failover constructor already applies the side +// effects, so the account is marked once — not once per path. +func TestForwardAsChatCompletions_StreamErrorBeforeOutputCountsOnce(t *testing.T) { + svc, repo, account := newCompatStreamSideEffectsService(compatStreamSideEffectsSSE(false, compatStreamAuthErrorEvent)) + body := []byte(`{"model":"gpt-5.5","messages":[{"role":"user","content":"hi"}],"stream":true}`) + c, _ := newCompatStreamContext("/v1/chat/completions", body) + + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "gpt-5.5") + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "no output yet: must fail over, got %v", err) + require.Len(t, repo.errorCalls, 1, "failover path must not double count") +} + +func TestForwardAsAnthropic_StreamErrorBeforeOutputCountsOnce(t *testing.T) { + svc, repo, account := newCompatStreamSideEffectsService(compatStreamSideEffectsSSE(false, compatStreamAuthErrorEvent)) + body := []byte(`{"model":"gpt-5.5","max_tokens":1024,"messages":[{"role":"user","content":"hi"}],"stream":true}`) + c, _ := newCompatStreamContext("/v1/messages", body) + + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "gpt-5.5") + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "no output yet: must fail over, got %v", err) + require.Len(t, repo.errorCalls, 1, "failover path must not double count") +} diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index ba7c1beaec..d74ac5c775 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -569,7 +569,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco // Account namespace is orthogonal to fingerprint convergence: preserve // each client's identity cardinality, but never reuse it across OAuth // credentials after scheduler failover. - if !isCompactRequest && applyCodexAccountIdentityClientMetadataMap(decoded, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c)) { + if !isCompactRequest && applyCodexAccountIdentityClientMetadataMap(decoded, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c), codexClientSessionID(c)) { markDecodedModified() } stageCodexFingerprintIDs(c, nil) diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 4756d83383..7f0c07ddf4 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -266,7 +266,7 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( if codexResult.PromptCacheKey != "" { promptCacheKey = codexResult.PromptCacheKey } - applyCodexAccountIdentityClientMetadataMap(reqBody, codexAccountIdentitySource(c, account), apiKeyID) + applyCodexAccountIdentityClientMetadataMap(reqBody, codexAccountIdentitySource(c, account), apiKeyID, codexClientSessionID(c)) delete(reqBody, "prompt_cache_key") if shouldAutoInjectPromptCacheKeyForCompat(upstreamModel) { compatTurnState = s.getOpenAICompatSessionTurnState(ctx, c, account, promptCacheKey) @@ -679,7 +679,7 @@ func (s *OpenAIGatewayService) handleAnthropicBufferedStreamingResponse( // accumulated delta events so the client receives the full content. acc.SupplementResponseOutput(finalResponse) - anthropicResp := apicompat.ResponsesToAnthropic(finalResponse, originalModel) + anthropicResp := apicompat.ResponsesToAnthropic(finalResponse, compositeClientModel(c.Request.Context(), originalModel)) if s.responseHeaderFilter != nil { responseheaders.WriteFilteredHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter) @@ -1019,7 +1019,7 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( writeStreamHeaders := s.newStreamHeaderWriter(c, resp.Header) state := apicompat.NewResponsesEventToAnthropicState() - state.Model = originalModel + state.Model = compositeClientModel(c.Request.Context(), originalModel) var usage OpenAIUsage responseID := "" var firstTokenMs *int @@ -1077,6 +1077,34 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( return out } + // Until the first content_block_delta the translated prelude is held, so a + // failure before any content reaches the client still fails over and the + // next attempt starts a fresh message. + var held strings.Builder + emit := func(sse string, release bool) error { + if !clientOutputStarted && !release { + _, _ = held.WriteString(sse) + return nil + } + writeStreamHeaders() + if held.Len() > 0 { + sse = held.String() + sse + held.Reset() + } + if _, err := fmt.Fprint(c.Writer, sse); err != nil { + return err + } + clientOutputStarted = true + return nil + } + // A failure that does not fail over still shows the client the prelude it + // would have seen without holding. + releaseHeld := func() { + if held.Len() > 0 && !clientDisconnected && emit("", true) == nil { + c.Writer.Flush() + } + } + // processDataLine handles a single "data: ..." SSE line from upstream. processDataLine := func(payload string) bool { payload = string(restoreCodexToolNamesFromContext(c, []byte(payload))) @@ -1130,12 +1158,11 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( UpstreamOutTok: usage.OutputTokens, }) if !clientDisconnected { - writeStreamHeaders() clientMsg := msg if clientMsg == "" { clientMsg = "Request blocked by upstream cyber-security policy" } - if _, err := fmt.Fprint(c.Writer, buildAnthropicStreamErrorSSE("invalid_request_error", clientMsg)); err == nil { + if emit(buildAnthropicStreamErrorSSE("invalid_request_error", clientMsg), true) == nil { c.Writer.Flush() } clientDisconnected = true @@ -1154,6 +1181,7 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( streamFailoverErr = s.newOpenAIStreamFailoverErrorWithModel(c, account, false, requestID, payloadBytes, message, upstreamModel, resp.Header) return true } + s.handleOpenAIStreamTerminalAccountSideEffects(c, account, payloadBytes, message, resp.Header, upstreamModel) message = s.recordOpenAIStreamUpstreamError(c, account, false, requestID, "http_error", payloadBytes, message) errStatus, errType, errMsg := http.StatusBadGateway, "api_error", message // 统一走语义状态推断 + body 归一化(与 /v1/responses 路径一致), @@ -1168,14 +1196,11 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( MarkResponseCommitted(c) } if !clientDisconnected { - if !clientOutputStarted { + if !clientOutputStarted && held.Len() == 0 { writeAnthropicError(c, errStatus, errType, errMsg) clientOutputStarted = true - } else { - writeStreamHeaders() - if _, err := fmt.Fprint(c.Writer, buildAnthropicStreamErrorSSE(errType, errMsg)); err == nil { - c.Writer.Flush() - } + } else if emit(buildAnthropicStreamErrorSSE(errType, errMsg), true) == nil { + c.Writer.Flush() } } streamNonFailoverErr = fmt.Errorf("upstream response failed: %s", errMsg) @@ -1195,18 +1220,18 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( ) continue } - writeStreamHeaders() - if _, err := fmt.Fprint(c.Writer, sse); err != nil { + if err := emit(sse, isTerminalEvent || evt.Type == "content_block_delta"); err != nil { clientDisconnected = true logger.L().Info("openai messages stream: client disconnected, continuing to drain upstream for billing", zap.String("request_id", requestID), ) break } - clientOutputStarted = true } } - if len(events) > 0 && !clientDisconnected { + // gin's Flush commits the 200 header first; flushing while the prelude + // is held would make the attempt ineligible for failover. + if clientOutputStarted && len(events) > 0 && !clientDisconnected { c.Writer.Flush() } return isTerminalEvent @@ -1226,15 +1251,13 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( if err != nil { continue } - writeStreamHeaders() - if _, err := fmt.Fprint(c.Writer, sse); err != nil { + if err := emit(sse, true); err != nil { clientDisconnected = true logger.L().Info("openai messages stream: client disconnected during final flush", zap.String("request_id", requestID), ) break } - clientOutputStarted = true } if !clientDisconnected { c.Writer.Flush() @@ -1254,6 +1277,9 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( } } missingTerminalErr := func() (*OpenAIForwardResult, error) { + if !clientOutputStarted && c.Request.Context().Err() != nil { + clientDisconnected = true + } result := resultWithUsage() if clientDisconnected { return result, fmt.Errorf("stream usage incomplete: missing terminal event") @@ -1294,6 +1320,7 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( } if err := scanner.Err(); err != nil { handleScanErr(err) + releaseHeld() return resultWithUsage(), fmt.Errorf("stream usage incomplete: %w", err) } if frame, ok := parser.Finish(); ok { @@ -1375,6 +1402,7 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( } if ev.err != nil { handleScanErr(ev.err) + releaseHeld() return resultWithUsage(), fmt.Errorf("stream usage incomplete: %w", ev.err) } lastDataAt = time.Now() @@ -1403,18 +1431,26 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( zap.String("model", originalModel), zap.Duration("interval", streamInterval), ) + releaseHeld() return resultWithUsage(), fmt.Errorf("stream data interval timeout") case <-keepaliveCh: if clientDisconnected { continue } - if time.Since(lastDataAt) < keepaliveInterval { + // While the prelude is held nothing else reaches the client, so every + // tick pings. Account headers stay private and the bytes count as + // keepalive: the attempt that finally answers may be another one. + if clientOutputStarted && time.Since(lastDataAt) < keepaliveInterval { continue } - // Send Anthropic-format ping event - writeStreamHeaders() - if _, err := fmt.Fprint(c.Writer, "event: ping\ndata: {\"type\":\"ping\"}\n\n"); err != nil { + if clientOutputStarted { + writeStreamHeaders() + } else { + setSSEHeaders(c) + } + n, err := fmt.Fprint(c.Writer, "event: ping\ndata: {\"type\":\"ping\"}\n\n") + if err != nil { // Client disconnected logger.L().Info("openai messages stream: client disconnected during keepalive", zap.String("request_id", requestID), @@ -1422,14 +1458,25 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( clientDisconnected = true continue } - clientOutputStarted = true + if !clientOutputStarted { + recordOpenAIStreamKeepaliveBytes(c, n) + } c.Writer.Flush() } } } // writeAnthropicError writes an error response in Anthropic Messages API format. +// Once the response is committed as SSE (keepalive pings went out), a bare JSON +// body would be unreadable to the client's SSE parser, so the error is written +// as an SSE error event instead. func writeAnthropicError(c *gin.Context, statusCode int, errType, message string) { + if c.Writer.Written() && strings.HasPrefix(c.Writer.Header().Get("Content-Type"), "text/event-stream") { + if _, err := fmt.Fprint(c.Writer, buildAnthropicStreamErrorSSE(errType, message)); err == nil { + c.Writer.Flush() + } + return + } c.JSON(statusCode, gin.H{ "type": "error", "error": gin.H{ diff --git a/backend/internal/service/openai_gateway_messages_anthropic_native.go b/backend/internal/service/openai_gateway_messages_anthropic_native.go index 3156aa8546..0570abcbda 100644 --- a/backend/internal/service/openai_gateway_messages_anthropic_native.go +++ b/backend/internal/service/openai_gateway_messages_anthropic_native.go @@ -40,6 +40,7 @@ func (s *OpenAIGatewayService) forwardAnthropicViaNativeAnthropicEndpoint( defaultMappedModel string, ) (*OpenAIForwardResult, error) { startTime := time.Now() + SetActualOpenAIUpstreamEndpoint(c, "/v1/messages") originalModel := strings.TrimSpace(gjson.GetBytes(body, "model").String()) if originalModel == "" { @@ -276,16 +277,19 @@ func (s *OpenAIGatewayService) handleNativeAnthropicBufferedResponse( c.Data(resp.StatusCode, contentType, body) return &OpenAIForwardResult{ - RequestID: resp.Header.Get("x-request-id"), - UpstreamHeaders: resp.Header, - Usage: claudeUsageToOpenAIUsage(usage), - Model: originalModel, - BillingModel: billingModel, - UpstreamModel: upstreamModel, - UpstreamEndpoint: "/v1/messages", - Stream: false, - ReasoningEffort: reasoningEffort, - Duration: time.Since(startTime), + RequestID: resp.Header.Get("x-request-id"), + UpstreamHeaders: resp.Header, + Usage: claudeUsageToOpenAIUsage(usage), + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + UpstreamEndpoint: "/v1/messages", + Stream: false, + ReasoningEffort: reasoningEffort, + Duration: time.Since(startTime), }, nil } @@ -483,7 +487,7 @@ func (s *OpenAIGatewayService) handleNativeAnthropicStreamingResponse( } if !clientDisconnected { - restored := string(reverseToolNamesIfPresent(c, []byte(line))) + restored := reverseToolNamesIfPresentString(c, line) if _, err := io.WriteString(w, restored); err != nil { clientDisconnected = true logger.LegacyPrintf("service.gateway", "[CN Anthropic 直通] Client disconnected during streaming, continue draining upstream for usage: account=%d", account.ID) @@ -559,18 +563,21 @@ func (s *OpenAIGatewayService) nativeAnthropicStreamResult( usage = &ClaudeUsage{} } return &OpenAIForwardResult{ - RequestID: resp.Header.Get("x-request-id"), - UpstreamHeaders: resp.Header, - Usage: claudeUsageToOpenAIUsage(usage), - Model: originalModel, - BillingModel: billingModel, - UpstreamModel: upstreamModel, - UpstreamEndpoint: "/v1/messages", - Stream: true, - ReasoningEffort: reasoningEffort, - Duration: time.Since(startTime), - FirstTokenMs: firstTokenMs, - ClientDisconnect: clientDisconnect, + RequestID: resp.Header.Get("x-request-id"), + UpstreamHeaders: resp.Header, + Usage: claudeUsageToOpenAIUsage(usage), + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + UpstreamEndpoint: "/v1/messages", + Stream: true, + ReasoningEffort: reasoningEffort, + Duration: time.Since(startTime), + FirstTokenMs: firstTokenMs, + ClientDisconnect: clientDisconnect, } } diff --git a/backend/internal/service/openai_gateway_messages_chat_fallback.go b/backend/internal/service/openai_gateway_messages_chat_fallback.go index 0a92e5963a..9a04d3fd72 100644 --- a/backend/internal/service/openai_gateway_messages_chat_fallback.go +++ b/backend/internal/service/openai_gateway_messages_chat_fallback.go @@ -170,7 +170,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsAnthropic( if err != nil { return nil, err } - anthropicResp := apicompat.ChatCompletionsResponseToAnthropic(ccResp, originalModel) + anthropicResp := apicompat.ChatCompletionsResponseToAnthropic(ccResp, compositeClientModel(c.Request.Context(), originalModel)) if s.responseHeaderFilter != nil { responseheaders.WriteFilteredHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter) @@ -178,17 +178,19 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsAnthropic( c.JSON(http.StatusOK, anthropicResp) return &OpenAIForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: usage, - Model: originalModel, - BillingModel: billingModel, - UpstreamModel: upstreamModel, - ReasoningEffort: reasoningEffort, - UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), - ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), - Stream: false, - Duration: time.Since(startTime), + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: usage, + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + ReasoningEffort: reasoningEffort, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), + Stream: false, + Duration: time.Since(startTime), }, nil } @@ -205,7 +207,7 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic( requestID := resp.Header.Get("x-request-id") writeStreamHeaders := s.newStreamHeaderWriter(c, resp.Header) - anthropicState := apicompat.NewChatCompletionsToAnthropicStreamState(originalModel) + anthropicState := apicompat.NewChatCompletionsToAnthropicStreamState(compositeClientModel(c.Request.Context(), originalModel)) clientDisconnected := false // 与 responses 兄弟不同:客户端断开后仍继续做事件转换(喂 anthropicState), @@ -240,19 +242,21 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic( // masks the truncation, and surface the error to flag usage incomplete // (mirrors forwardResponsesViaRawChatCompletions). return &OpenAIForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: usage, - Model: originalModel, - BillingModel: billingModel, - UpstreamModel: upstreamModel, - ReasoningEffort: reasoningEffort, - UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), - ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), - Stream: true, - Duration: time.Since(startTime), - FirstTokenMs: scan.FirstTokenMs, - ClientDisconnect: clientDisconnected, + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: usage, + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + ReasoningEffort: reasoningEffort, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), + Stream: true, + Duration: time.Since(startTime), + FirstTokenMs: scan.FirstTokenMs, + ClientDisconnect: clientDisconnected, }, fmt.Errorf("stream usage incomplete: %w", scan.Err) } @@ -277,18 +281,20 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic( } return &OpenAIForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: usage, - Model: originalModel, - BillingModel: billingModel, - UpstreamModel: upstreamModel, - ReasoningEffort: reasoningEffort, - UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), - ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), - Stream: true, - Duration: time.Since(startTime), - FirstTokenMs: scan.FirstTokenMs, - ClientDisconnect: clientDisconnected, + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: usage, + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + ReasoningEffort: reasoningEffort, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), + Stream: true, + Duration: time.Since(startTime), + FirstTokenMs: scan.FirstTokenMs, + ClientDisconnect: clientDisconnected, }, nil } diff --git a/backend/internal/service/openai_gateway_messages_pre_content_test.go b/backend/internal/service/openai_gateway_messages_pre_content_test.go new file mode 100644 index 0000000000..5c911ee68b --- /dev/null +++ b/backend/internal/service/openai_gateway_messages_pre_content_test.go @@ -0,0 +1,188 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "errors" + "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" +) + +const ( + preContentCreatedFrame = `data: {"type":"response.created","response":{"id":"resp_pre","object":"response","model":"gpt-5.4","status":"in_progress","output":[]}}` + "\n\n" + preContentFailoverFailed = `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"server_error","message":"An error occurred while processing your request."}}}` + "\n\n" +) + +func newPreContentContext() (*httptest.ResponseRecorder, *gin.Context, []byte) { + 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") + return rec, c, body +} + +func forwardPreContent(t *testing.T, cfg *config.Config, header http.Header, upstreamBody io.ReadCloser) (*httptest.ResponseRecorder, *gin.Context, error) { + t.Helper() + rec, c, body := newPreContentContext() + if header == nil { + header = http.Header{} + } + header.Set("Content-Type", "text/event-stream") + upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusOK, Header: header, Body: upstreamBody}} + svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream, responseHeaderFilter: compileResponseHeaderFilter(cfg)} + _, err := svc.ForwardAsAnthropic(context.Background(), c, rawChatCompletionsTestAccount(), body, "", "") + return rec, c, err +} + +func TestForwardAsAnthropic_PreContentFailedFailsOver(t *testing.T) { + stream := preContentCreatedFrame + + `data: {"type":"response.in_progress","response":{"id":"resp_pre","object":"response","model":"gpt-5.4","status":"in_progress","output":[]}}` + "\n\n" + + `data: {"type":"response.output_item.added","output_index":0,"item":{"id":"rs_1","type":"reasoning","summary":[]}}` + "\n\n" + + preContentFailoverFailed + rec, c, err := forwardPreContent(t, rawChatCompletionsTestConfig(), nil, io.NopCloser(strings.NewReader(stream))) + + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "failure before content must fail over: %T: %v", err, err) + require.Empty(t, rec.Body.String()) + require.False(t, c.Writer.Written()) +} + +func TestForwardAsAnthropic_PreContentMissingTerminalFailsOver(t *testing.T) { + rec, c, err := forwardPreContent(t, rawChatCompletionsTestConfig(), nil, io.NopCloser(strings.NewReader(preContentCreatedFrame))) + + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "EOF without a terminal event before content must fail over: %T: %v", err, err) + require.Empty(t, rec.Body.String()) + require.False(t, c.Writer.Written()) +} + +func TestForwardAsAnthropic_PreContentReadErrorDoesNotFailOver(t *testing.T) { + reader := &errAfterReader{data: strings.NewReader(preContentCreatedFrame), err: io.ErrUnexpectedEOF} + rec, _, err := forwardPreContent(t, rawChatCompletionsTestConfig(), nil, io.NopCloser(reader)) + + require.ErrorIs(t, err, io.ErrUnexpectedEOF) + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr), "a read error never fails over: %v", err) + require.Contains(t, rec.Body.String(), "message_start") +} + +func TestForwardAsAnthropic_PreContentPingKeepsFailover(t *testing.T) { + cfg := rawChatCompletionsTestConfig() + cfg.Gateway.StreamKeepaliveInterval = 1 + pr, pw := io.Pipe() + go func() { + _, _ = io.WriteString(pw, preContentCreatedFrame) + time.Sleep(1300 * time.Millisecond) + _, _ = io.WriteString(pw, preContentFailoverFailed) + _ = pw.Close() + }() + rec, c, err := forwardPreContent(t, cfg, http.Header{"X-Request-Id": []string{"attempt-1"}}, pr) + + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "ping-only output must keep failover: %T: %v", err, err) + body := rec.Body.String() + require.GreaterOrEqual(t, strings.Count(body, "event: ping"), 1) + require.NotContains(t, body, "message_start") + require.Equal(t, "text/event-stream", rec.Header().Get("Content-Type")) + require.Empty(t, rec.Header().Get("X-Request-Id"), "account headers must stay private while the prelude is held") + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c)) +} + +func TestForwardAsAnthropic_ContentReleasedNeverFailsOver(t *testing.T) { + stream := preContentCreatedFrame + + `data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"partial"}` + "\n\n" + + preContentFailoverFailed + rec, _, err := forwardPreContent(t, rawChatCompletionsTestConfig(), nil, io.NopCloser(strings.NewReader(stream))) + + require.Error(t, err) + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr), "released content must not fail over: %v", err) + body := rec.Body.String() + start := strings.Index(body, "event: message_start") + text := strings.Index(body, `"text":"partial"`) + errEvt := strings.Index(body, "event: error") + require.True(t, start >= 0 && text > start && errEvt > text, "body order: %q", body) +} + +func TestForwardAsAnthropic_TerminalBeforeContentReleasesPrelude(t *testing.T) { + stream := preContentCreatedFrame + + `data: {"type":"response.completed","response":{"id":"resp_pre","object":"response","model":"gpt-5.4","status":"completed","output":[],"usage":{"input_tokens":3,"output_tokens":0,"total_tokens":3}}}` + "\n\n" + rec, _, err := forwardPreContent(t, rawChatCompletionsTestConfig(), nil, io.NopCloser(strings.NewReader(stream))) + + require.NoError(t, err) + body := rec.Body.String() + start := strings.Index(body, "event: message_start") + delta := strings.Index(body, "event: message_delta") + stop := strings.Index(body, "event: message_stop") + require.True(t, start >= 0 && delta > start && stop > delta, "body order: %q", body) +} + +func TestForwardAsAnthropic_IntervalTimeoutReleasesPrelude(t *testing.T) { + cfg := rawChatCompletionsTestConfig() + cfg.Gateway.StreamDataIntervalTimeout = 1 + pr, pw := io.Pipe() + defer func() { _ = pw.Close() }() + go func() { + _, _ = io.WriteString(pw, preContentCreatedFrame) + }() + rec, _, err := forwardPreContent(t, cfg, nil, pr) + + require.Error(t, err) + require.Contains(t, err.Error(), "stream data interval timeout") + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr)) + require.Contains(t, rec.Body.String(), "message_start") +} + +func TestWriteAnthropicErrorAfterCommittedSSE(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + setSSEHeaders(c) + _, err := io.WriteString(c.Writer, "event: ping\ndata: {\"type\":\"ping\"}\n\n") + require.NoError(t, err) + + writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", "prompt is too long") + + body := rec.Body.String() + require.True(t, strings.HasSuffix(body, "event: error\ndata: {\"error\":{\"message\":\"prompt is too long\",\"type\":\"invalid_request_error\"},\"type\":\"error\"}\n\n"), "body: %q", body) + for _, line := range strings.Split(body, "\n") { + require.False(t, strings.HasPrefix(line, "{"), "bare JSON line in SSE body: %q", line) + } +} + +func TestForwardAsAnthropic_OpenCodeUnsupportedModelAfterCommittedSSEIsSSEError(t *testing.T) { + rec, c, body := newPreContentContext() + body = []byte(`{"model":"gemini-3-pro","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":true}`) + setSSEHeaders(c) + _, err := io.WriteString(c.Writer, "event: ping\ndata: {\"type\":\"ping\"}\n\n") + require.NoError(t, err) + account := &Account{ + ID: 1, Platform: PlatformOpenCodeGo, Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-test", "base_url": "http://upstream.example"}, + } + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig()} + + _, err = svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + + require.Error(t, err) + out := rec.Body.String() + lastEvent := out[strings.LastIndex(strings.TrimRight(out, "\n"), "\n\n")+2:] + require.True(t, strings.HasPrefix(lastEvent, "event: error\ndata: {"), "last event: %q", lastEvent) + for _, line := range strings.Split(out, "\n") { + require.False(t, strings.HasPrefix(line, "{"), "bare JSON line in SSE body: %q", line) + } +} diff --git a/backend/internal/service/openai_gateway_native_anthropic_observation_test.go b/backend/internal/service/openai_gateway_native_anthropic_observation_test.go new file mode 100644 index 0000000000..3decfa9f64 --- /dev/null +++ b/backend/internal/service/openai_gateway_native_anthropic_observation_test.go @@ -0,0 +1,195 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func nativeObservationResponse(t *testing.T, stream bool, model, speed string, conflict, partial, readError bool) (*http.Response, string) { + t.Helper() + usage := map[string]any{"input_tokens": 20, "output_tokens": 10} + if speed != "" { + usage["speed"] = speed + } + message := map[string]any{ + "id": "msg_observed", "type": "message", "role": "assistant", + "content": []map[string]string{{"type": "text", "text": "observed response"}}, "usage": usage, + } + if model != "" { + message["model"] = model + } + encode := func(v any) string { + b, err := json.Marshal(v) + require.NoError(t, err) + return string(b) + } + wire := encode(message) + contentType := "application/json" + if stream { + contentType = "text/event-stream" + usage["output_tokens"] = 1 + message["content"] = []any{} + wire = "event: message_start\ndata: " + encode(map[string]any{"type": "message_start", "message": message}) + "\n\n" + if conflict { + message["model"] = "conflicting-model" + usage["speed"] = "standard" + wire += "event: message_start\ndata: " + encode(map[string]any{"type": "message_start", "message": message}) + "\n\n" + } + wire += "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n" + + "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"observed response\"}}\n\n" + if !partial { + wire += "event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n" + + "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":10}}\n\n" + + "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + } + } + var body io.ReadCloser = io.NopCloser(strings.NewReader(wire)) + if readError { + body = &streamReadCloser{payload: []byte(wire), err: io.ErrUnexpectedEOF} + } + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{ + "Content-Type": []string{contentType}, "X-Request-Id": []string{"native-observed"}, + }, Body: body}, wire +} + +func TestNativeAnthropicResponseObservationReachesUsage(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tt := range []struct { + name string + stream bool + model string + speed string + conflict bool + partial bool + readError bool + disconnect bool + wantModel string + wantSpeed string + }{ + {name: "buffered matching", model: " k3 ", speed: "standard", wantModel: "k3", wantSpeed: "standard"}, + {name: "buffered mismatch", model: "reported-k3", speed: "fast", wantModel: "reported-k3", wantSpeed: "fast"}, + {name: "buffered undeclared", speed: "fast"}, + {name: "stream matching", stream: true, model: "k3", speed: "standard", wantModel: "k3", wantSpeed: "standard"}, + {name: "stream mismatch", stream: true, model: "reported-k3", speed: "fast", wantModel: "reported-k3", wantSpeed: "fast"}, + {name: "stream undeclared", stream: true, speed: "fast"}, + {name: "stream conflicting declarations", stream: true, model: "reported-k3", speed: "fast", conflict: true, wantModel: "reported-k3"}, + {name: "stream truncated", stream: true, model: "reported-k3", speed: "standard", partial: true, wantModel: "reported-k3", wantSpeed: "standard"}, + {name: "stream read error", stream: true, model: "reported-k3", speed: "standard", partial: true, readError: true, wantModel: "reported-k3", wantSpeed: "standard"}, + {name: "client disconnected", stream: true, model: "reported-k3", speed: "fast", disconnect: true, wantModel: "reported-k3", wantSpeed: "fast"}, + } { + t.Run(tt.name, func(t *testing.T) { + resp, wire := nativeObservationResponse(t, tt.stream, tt.model, tt.speed, tt.conflict, tt.partial, tt.readError) + upstream := &httpUpstreamRecorder{resp: resp} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + body, err := json.Marshal(map[string]any{ + "model": "client-model", "max_tokens": 32, "stream": tt.stream, + "messages": []map[string]string{{"role": "user", "content": "hi"}}, + }) + require.NoError(t, err) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(string(body))) + if tt.disconnect { + c.Writer = &failWriteResponseWriter{ResponseWriter: c.Writer} + } + // A previous attempt must not leak its declaration into an undeclared response. + beginUpstreamResponseModelObservation(c).Observe("stale-model", false) + account := nativeAnthropicTestAccount() + result, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "k3") + if tt.partial { + require.Error(t, err) + } else { + require.NoError(t, err) + } + require.NotNil(t, result) + require.Equal(t, "k3", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, "client-model", result.Model) + require.Equal(t, "k3", result.BillingModel) + require.Equal(t, "k3", result.UpstreamModel) + require.Equal(t, 20, result.Usage.InputTokens) + wantOutput := 10 + if tt.partial { + wantOutput = 0 + } + require.Equal(t, wantOutput, result.Usage.OutputTokens) + require.Equal(t, tt.disconnect, result.ClientDisconnect) + if !tt.disconnect { + require.Equal(t, wire, rec.Body.String(), "observation must preserve the upstream response bytes") + } + require.Equal(t, tt.wantModel, observedUpstreamResponseModel(c), "the observer already saw the declaration") + + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + usageSvc := newOpenAIRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) + require.NoError(t, usageSvc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: result, APIKey: &APIKey{ID: 10}, User: &User{ID: 20}, Account: account, + })) + require.NotNil(t, usageRepo.lastLog) + log := usageRepo.lastLog + require.Equal(t, "k3", *log.UpstreamModel) + if tt.wantModel == "" { + require.Nil(t, log.UpstreamResponseModel) + require.Nil(t, log.UpstreamModelMismatch) + } else { + require.NotNil(t, log.UpstreamResponseModel) + require.Equal(t, tt.wantModel, *log.UpstreamResponseModel) + require.NotNil(t, log.UpstreamModelMismatch) + require.Equal(t, tt.wantModel != "k3", *log.UpstreamModelMismatch) + } + require.Equal(t, tt.wantModel, result.UpstreamResponseModel) + require.Equal(t, tt.conflict, result.UpstreamResponseModelConflict) + require.Equal(t, tt.wantSpeed, result.UpstreamResponseServiceTier) + }) + } +} + +func TestNativeAnthropicResponseObservationRespectsBillingSource(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, stream := range []bool{false, true} { + for _, source := range []string{BillingModelSourceChannelMapped, BillingModelSourceResponse} { + name := "buffered/" + source + if stream { + name = "stream/" + source + } + t.Run(name, func(t *testing.T) { + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + userRepo := &openAIRecordUsageUserRepoStub{} + usageSvc := newOpenAIRecordUsageServiceForTest(usageRepo, userRepo, &openAIRecordUsageSubRepoStub{}, nil) + cheaper, pricier, cheapCost, baselineCost := orderedResponseBillingModels(t, usageSvc.billingService, + UsageTokens{InputTokens: 20, OutputTokens: 10}, openAICheapFixtureModel, openAIPriceyFixtureModel) + resp, _ := nativeObservationResponse(t, stream, cheaper, "standard", false, false, false) + upstream := &httpUpstreamRecorder{resp: resp} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + body, err := json.Marshal(map[string]any{ + "model": pricier, "max_tokens": 32, "stream": stream, + "messages": []map[string]string{{"role": "user", "content": "hi"}}, + }) + require.NoError(t, err) + account := nativeAnthropicTestAccount() + result, err := svc.ForwardAsAnthropic(context.Background(), adaptiveProtocolTestContext("/v1/messages", body), account, body, "", "") + require.NoError(t, err) + require.NoError(t, usageSvc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: result, APIKey: &APIKey{ID: 10}, User: &User{ID: 20}, Account: account, + ChannelUsageFields: ChannelUsageFields{ChannelID: 9, OriginalModel: pricier, ChannelMappedModel: pricier, BillingModelSource: source}, + })) + wantCost := baselineCost + if source == BillingModelSourceResponse { + wantCost = cheapCost + } + require.NotNil(t, usageRepo.lastLog) + require.InDelta(t, wantCost.ActualCost, usageRepo.lastLog.ActualCost, 1e-12) + require.InDelta(t, wantCost.ActualCost, userRepo.lastAmount, 1e-12) + }) + } + } +} diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index bf3debe638..bf3993d1ca 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -173,7 +173,7 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( reqStream = false } - accountScopedBody, accountScoped, scopeErr := applyCodexAccountIdentityClientMetadataRaw(body, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c)) + accountScopedBody, accountScoped, scopeErr := applyCodexAccountIdentityClientMetadataRaw(body, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c), codexClientSessionID(c)) if scopeErr != nil { return nil, scopeErr } @@ -1557,6 +1557,33 @@ func applyOpenAIStreamFailedErrorPassthroughRule( ) } +// OpenAIStreamFailedFrame is the in-stream failed or error frame behind a +// failover, kept so an exhausted failover can still apply the error +// passthrough rules that would have matched the frame. +type OpenAIStreamFailedFrame struct { + Platform string + Payload []byte + Message string +} + +// ApplyOpenAIStreamFailedFrameRule applies the error passthrough rules to the +// frame that triggered an exhausted failover, matching it the way +// applyOpenAIStreamFailedErrorPassthroughRule does for an in-band frame. +func ApplyOpenAIStreamFailedFrameRule(c *gin.Context, failoverErr *UpstreamFailoverError) (status int, errType string, errMsg string, matched bool) { + if failoverErr == nil || failoverErr.StreamFailedFrame == nil { + return 0, "", "", false + } + frame := failoverErr.StreamFailedFrame + status, errType, errMsg, matched = applyOpenAIStreamFailedErrorPassthroughRule(c, frame.Platform, frame.Payload, frame.Message) + if !matched { + return 0, "", "", false + } + if errMsg == "" { + errMsg = frame.Message + } + return status, errType, errMsg, true +} + func openAIStreamFailedEventShouldFailover(payload []byte, message string) bool { if hit, _, _ := detectOpenAICyberPolicy(payload); hit { return false @@ -1792,6 +1819,9 @@ func (s *OpenAIGatewayService) newOpenAIStreamFailoverErrorWithModel( classificationHeaders = nil } failoverErr := s.newOpenAIAccountFailoverErrorWithClassificationHeaders(account, statusCode, headers, classificationHeaders, payload, message, shouldDisable, retryableOnSameAccount) + if len(payload) > 0 && account != nil { + failoverErr.StreamFailedFrame = &OpenAIStreamFailedFrame{Platform: account.Platform, Payload: payload, Message: message} + } if failoverErr.IsCredentialFailure() || failoverErr.RequestScopedTransient { return failoverErr } diff --git a/backend/internal/service/openai_gateway_record_usage_test.go b/backend/internal/service/openai_gateway_record_usage_test.go index be4cf1850c..b1e2bde2f4 100644 --- a/backend/internal/service/openai_gateway_record_usage_test.go +++ b/backend/internal/service/openai_gateway_record_usage_test.go @@ -476,6 +476,8 @@ func TestOpenAIGatewayServiceRecordUsage_PeakRateAffectsTokenModeImageOutputToke }, User: &User{ID: 2004}, Account: &Account{ID: 3004}, + // The peak window excludes 23:59, so do not depend on the wall clock. + PricingAt: time.Date(2026, time.January, 15, 12, 0, 0, 0, time.UTC), }) require.NoError(t, err) diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index b7e4514405..8465c54ed1 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -1452,9 +1452,9 @@ func normalizeOpenAIOAuthResponsesCompatibilityBody(body []byte) ([]byte, bool, } normalized := body changed := false - prompt := gjson.GetBytes(normalized, "prompt") + prompt := parseRawJSONView(normalized).Get("prompt") if prompt.Exists() { - input := gjson.GetBytes(normalized, "input") + input := parseRawJSONView(normalized).Get("input") if prompt.Type != gjson.Null && (!input.Exists() || input.Type == gjson.Null) { next, err := sjson.SetRawBytes(normalized, "input", []byte(prompt.Raw)) if err != nil { @@ -1469,7 +1469,7 @@ func normalizeOpenAIOAuthResponsesCompatibilityBody(body []byte) ([]byte, bool, normalized = next changed = true } - if gjson.GetBytes(normalized, "commands").Exists() { + if parseRawJSONView(normalized).Get("commands").Exists() { next, err := sjson.DeleteBytes(normalized, "commands") if err != nil { return body, false, fmt.Errorf("normalize oauth responses delete commands: %w", err) @@ -1478,22 +1478,39 @@ func normalizeOpenAIOAuthResponsesCompatibilityBody(body []byte) ([]byte, bool, changed = true } // Only remove the input-item field, never same-named user content. - input := gjson.GetBytes(normalized, "input") + input := parseRawJSONView(normalized).Get("input") if !input.IsArray() { return normalized, changed, nil } - for i, item := range input.Array() { - if !item.IsObject() || !item.Get("internal_chat_message_metadata_passthrough").Exists() { - continue - } - next, err := sjson.DeleteBytes(normalized, fmt.Sprintf("input.%d.internal_chat_message_metadata_passthrough", i)) - if err != nil { - return body, false, fmt.Errorf("normalize oauth input metadata: %w", err) - } - normalized = next - changed = true + const field = "internal_chat_message_metadata_passthrough" + hasMetadata := false + input.ForEach(func(_, item gjson.Result) bool { + hasMetadata = item.IsObject() && item.Get(field).Exists() + return !hasMetadata + }) + if !hasMetadata { + return normalized, changed, nil } - return normalized, changed, nil + + // Clean each item locally, then rebuild the request once. Deleting by + // input.N on the full body copies the entire history for every message. + var items []string + var normalizeErr error + input.ForEach(func(_, item gjson.Result) bool { + raw := item.Raw + if item.IsObject() && item.Get(field).Exists() { + raw, normalizeErr = sjson.Delete(raw, field) + if normalizeErr != nil { + return false + } + } + items = append(items, raw) + return true + }) + if normalizeErr != nil { + return body, false, fmt.Errorf("normalize oauth input metadata: %w", normalizeErr) + } + return replaceOpenAIRawInput(normalized, input, items), true, nil } func normalizeGPT6ResponsesSampling(body []byte, model string) ([]byte, bool, error) { @@ -1622,6 +1639,12 @@ func normalizeOpenAIResponsesCompatibilityBodyWithOptions(body []byte, account * if err != nil { return body, false, err } + if next, idsChanged, err := normalizeCodexAdditionalToolsIDsBody(normalized); err != nil { + return body, false, err + } else if idsChanged { + normalized = next + changed = true + } } if next, normalizedReasoningContent, err := normalizeOpenAIResponsesReasoningContentReplay(normalized); err != nil { return body, false, err diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index ae528e4fea..3d1d67af84 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -484,6 +484,25 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. sendErrorEvent(code, message) return resultWithUsage(), fmt.Errorf("stream read error: %w", scanErr), true } + // Upstream keepalive events bypass the first-output stage the same way the + // comment keepalive does: Codex resets its stream idle timer only on parsed + // SSE events, while the attempt's lifecycle events and account headers stay + // private until semantic output. The bytes do not count as client output. + keepaliveEventDirect := false + forwardsKeepaliveDirect := func(eventType string) bool { + return eventType == "keepalive" && stageFirstOutput && !firstOutputStage.closed && !failureDelivered && !suppressCurrentEvent + } + writeKeepaliveDirect := func(value string) { + if clientDisconnected { + return + } + n, err := w.Write([]byte(value)) + recordOpenAIStreamKeepaliveBytes(c, n) + if err != nil { + clientDisconnected = true + logger.LegacyPrintf("service.openai_gateway", "Client disconnected during streaming, continuing to drain upstream for billing") + } + } processSSELine := func(line string, queueDrained bool) { if streamEarlyErr != nil { return @@ -492,11 +511,23 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. pendingSSEEventType = eventType eventType = strings.TrimSpace(eventType) suppressCurrentEvent = codexFailureTerminal && (eventType == "error" || (sawBareError && !sawResponseFailed && eventType != "response.failed")) + if forwardsKeepaliveDirect(eventType) { + keepaliveEventDirect = true + eventInProgress = true + writeKeepaliveDirect(line + "\n") + return + } } // Extract data from SSE line (supports both "data: " and "data:" formats) if data, ok := extractOpenAISSEDataLine(line); ok { dataBytes := []byte(data) eventType := effectiveOpenAISSEEventType(dataBytes, pendingSSEEventType) + if keepaliveEventDirect || forwardsKeepaliveDirect(eventType) { + keepaliveEventDirect = true + eventInProgress = true + writeKeepaliveDirect(line + "\n") + return + } if codexFailureTerminal && sawBareError && !sawResponseFailed && (eventType == "response.completed" || eventType == "response.done") { // A later successful terminal is authoritative over a pending bare @@ -748,6 +779,16 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. // A blank line dispatches a guarded event from the attempt-local stage. if stageFirstOutput && line == "" { pendingSSEEventType = "" + if keepaliveEventDirect { + keepaliveEventDirect = false + eventInProgress = false + writeKeepaliveDirect("\n") + if !clientDisconnected { + flusher.Flush() + lastDownstreamWriteAt = time.Now() + } + return + } if suppressCurrentEvent { suppressCurrentEvent = false terminalFailurePending = false diff --git a/backend/internal/service/openai_gateway_responses_anthropic_native.go b/backend/internal/service/openai_gateway_responses_anthropic_native.go index d4ed554a71..3f36d0d30b 100644 --- a/backend/internal/service/openai_gateway_responses_anthropic_native.go +++ b/backend/internal/service/openai_gateway_responses_anthropic_native.go @@ -42,6 +42,7 @@ func (s *OpenAIGatewayService) forwardResponsesViaNativeAnthropic( defaultMappedModel string, ) (*OpenAIForwardResult, error) { startTime := time.Now() + SetActualOpenAIUpstreamEndpoint(c, "/v1/messages") // 1. Lower Codex client-side tools to function tools understood by Anthropic. adaptedBody, clientToolMapping, err := adaptResponsesClientToolsForAnthropic(body) diff --git a/backend/internal/service/openai_gateway_responses_chat_fallback.go b/backend/internal/service/openai_gateway_responses_chat_fallback.go index 154a0b18e1..3b82eae8f5 100644 --- a/backend/internal/service/openai_gateway_responses_chat_fallback.go +++ b/backend/internal/service/openai_gateway_responses_chat_fallback.go @@ -169,17 +169,19 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsResponses( c.JSON(http.StatusOK, responsesResp) return &OpenAIForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: usage, - Model: originalModel, - BillingModel: billingModel, - UpstreamModel: upstreamModel, - ReasoningEffort: reasoningEffort, - UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), - ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), - Stream: false, - Duration: time.Since(startTime), + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: usage, + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + ReasoningEffort: reasoningEffort, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), + Stream: false, + Duration: time.Since(startTime), }, nil } @@ -241,34 +243,38 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsResponses( if scan.Err != nil { return &OpenAIForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: scan.Usage, - Model: originalModel, - BillingModel: billingModel, - UpstreamModel: upstreamModel, - ReasoningEffort: reasoningEffort, - UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), - ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), - Stream: true, - Duration: time.Since(startTime), - FirstTokenMs: scan.FirstTokenMs, + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: scan.Usage, + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + ReasoningEffort: reasoningEffort, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), + Stream: true, + Duration: time.Since(startTime), + FirstTokenMs: scan.FirstTokenMs, }, fmt.Errorf("stream usage incomplete: %w", scan.Err) } if err := state.ValidateToolCallArguments(); err != nil { return &OpenAIForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: scan.Usage, - Model: originalModel, - BillingModel: billingModel, - UpstreamModel: upstreamModel, - ReasoningEffort: reasoningEffort, - UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), - ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), - Stream: true, - Duration: time.Since(startTime), - FirstTokenMs: scan.FirstTokenMs, + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: scan.Usage, + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + ReasoningEffort: reasoningEffort, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), + Stream: true, + Duration: time.Since(startTime), + FirstTokenMs: scan.FirstTokenMs, }, fmt.Errorf("invalid tool call arguments from upstream: %w", err) } @@ -289,18 +295,20 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsResponses( } return &OpenAIForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: scan.Usage, - Model: originalModel, - BillingModel: billingModel, - UpstreamModel: upstreamModel, - ReasoningEffort: reasoningEffort, - UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), - ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), - Stream: true, - Duration: time.Since(startTime), - FirstTokenMs: scan.FirstTokenMs, + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: scan.Usage, + Model: originalModel, + BillingModel: billingModel, + UpstreamModel: upstreamModel, + ReasoningEffort: reasoningEffort, + UpstreamResponseModel: observedUpstreamResponseModel(c), + UpstreamResponseModelConflict: observedUpstreamResponseModelConflict(c), + UpstreamResponseServiceTier: observedUpstreamResponseServiceTier(c), + ServiceTier: resolvedOpenAIUpstreamServiceTier(c, serviceTier), + Stream: true, + Duration: time.Since(startTime), + FirstTokenMs: scan.FirstTokenMs, }, nil } diff --git a/backend/internal/service/openai_gateway_stream_keepalive_forward_test.go b/backend/internal/service/openai_gateway_stream_keepalive_forward_test.go new file mode 100644 index 0000000000..d83e2a3d41 --- /dev/null +++ b/backend/internal/service/openai_gateway_stream_keepalive_forward_test.go @@ -0,0 +1,215 @@ +package service + +import ( + "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" +) + +// keepaliveForwardBody holds the upstream stream open until the gateway closes it. +type keepaliveForwardBody struct { + io.ReadCloser + closed chan struct{} + once sync.Once +} + +func (b *keepaliveForwardBody) Close() error { + b.once.Do(func() { close(b.closed) }) + return b.ReadCloser.Close() +} + +// stalledKeepaliveResponse returns an upstream response that sends the preamble and the given +// keepalive frames, then produces no semantic output until it is closed. +func stalledKeepaliveResponse(frames ...string) *http.Response { + pr, pw := io.Pipe() + body := &keepaliveForwardBody{ReadCloser: pr, closed: make(chan struct{})} + 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")) + for _, frame := range frames { + _, _ = pw.Write([]byte(frame)) + } + select { + case <-body.closed: + case <-time.After(5 * time.Second): + } + }() + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{ + "Content-Type": []string{"text/event-stream"}, + "X-Request-Id": []string{"request-stalled"}, + "X-Ratelimit-Remaining-Requests": []string{"1"}, + }, + Body: body, + } +} + +func newKeepaliveForwardService(firstOutputTimeoutSeconds int) *OpenAIGatewayService { + cfg := &config.Config{Gateway: config.GatewayConfig{ + OpenAIFirstOutputTimeoutSeconds: firstOutputTimeoutSeconds, + MaxLineSize: defaultMaxLineSize, + }} + return &OpenAIGatewayService{cfg: cfg, responseHeaderFilter: compileResponseHeaderFilter(cfg)} +} + +func newKeepaliveForwardContext() (*gin.Context, *httptest.ResponseRecorder) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + return c, rec +} + +const ( + upstreamKeepaliveData = `data: {"type":"keepalive","sequence_number":3}` + upstreamKeepaliveEvent = "event: keepalive\n" + upstreamKeepaliveData + "\n\n" +) + +// Codex resets its stream idle timer only on parsed SSE events, so the upstream keepalive event +// must reach the client before the first semantic output, while the attempt's preamble and +// account headers stay private and the bytes still do not count as client output. +func TestOpenAINativeStreamForwardsUpstreamKeepaliveBeforeFirstOutput(t *testing.T) { + for _, tc := range []struct { + name string + frame string + }{ + {"event_and_data", upstreamKeepaliveEvent}, + {"data_only", upstreamKeepaliveData + "\n\n"}, + } { + t.Run(tc.name, func(t *testing.T) { + svc := newKeepaliveForwardService(1) + c, rec := newKeepaliveForwardContext() + + _, err := svc.handleStreamingResponse(c.Request.Context(), stalledKeepaliveResponse(tc.frame), c, + &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr, "no semantic output: the first-output timeout must fail over") + require.Equal(t, tc.frame, rec.Body.String(), "only the upstream keepalive event reaches the client, verbatim") + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c), "keepalive bytes are not client output") + require.Empty(t, rec.Result().Header.Values("X-Request-Id"), "account headers stay private before output") + require.Empty(t, rec.Result().Header.Values("X-Ratelimit-Remaining-Requests")) + }) + } +} + +// After a pre-output failover the next account's stream continues the same response: the client +// sees the first account's keepalive, then the second account's complete stream from its start. +func TestOpenAINativeStreamKeepaliveThenFailoverContinuesWithNextAccount(t *testing.T) { + svc := newKeepaliveForwardService(1) + c, rec := newKeepaliveForwardContext() + + _, firstErr := svc.handleStreamingResponse(c.Request.Context(), stalledKeepaliveResponse(upstreamKeepaliveEvent), c, + &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, firstErr, &failoverErr) + + secondResp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "X-Request-Id": []string{"request-second"}}, + Body: io.NopCloser(strings.NewReader(strings.Join([]string{ + `data: {"type":"response.created","response":{"id":"resp_second"}}`, + "", + `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) + + body := rec.Body.String() + require.True(t, strings.HasPrefix(body, upstreamKeepaliveEvent), "first account's keepalive comes first, got %q", body) + require.NotContains(t, body, "resp_stalled", "the failed attempt's preamble never reaches the client") + created := strings.Index(body, `"id":"resp_second"`) + require.Greater(t, created, len(upstreamKeepaliveEvent)-1) + require.Less(t, created, strings.Index(body, `"delta":"hello"`)) + require.Empty(t, rec.Result().Header.Values("X-Request-Id"), "headers were committed by the keepalive, not the second account") +} + +// Keepalive events after output started keep their place in the stream: not dropped, not repeated. +func TestOpenAINativeStreamKeepaliveAfterOutputStaysInOrder(t *testing.T) { + svc := newKeepaliveForwardService(0) + c, rec := newKeepaliveForwardContext() + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(strings.Join([]string{ + `data: {"type":"response.created","response":{"id":"resp_order"}}`, + "", + `data: {"type":"response.output_text.delta","delta":"a"}`, + "", + "event: keepalive", + upstreamKeepaliveData, + "", + `data: {"type":"response.output_text.delta","delta":"b"}`, + "", + `data: {"type":"response.completed","response":{"id":"resp_order","usage":{"input_tokens":1,"output_tokens":2}}}`, + "", + }, "\n"))), + } + + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + require.NoError(t, err) + + body := rec.Body.String() + require.Equal(t, 1, strings.Count(body, `"type":"keepalive"`)) + a, ka, b := strings.Index(body, `"delta":"a"`), strings.Index(body, upstreamKeepaliveEvent), strings.Index(body, `"delta":"b"`) + require.True(t, a < ka && ka < b, "keepalive must stay between the deltas, got %q", body) +} + +// Forwarded keepalive events are not output: they must not postpone the first-output timeout, +// so an attempt whose upstream only keeps the stream alive still fails over on time. +func TestOpenAINativeStreamKeepaliveDoesNotResetFirstOutputTimeout(t *testing.T) { + pr, pw := io.Pipe() + body := &keepaliveForwardBody{ReadCloser: pr, closed: make(chan struct{})} + go func() { + defer func() { _ = pw.Close() }() + _, _ = pw.Write([]byte("data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_paced\"}}\n\n")) + ticker := time.NewTicker(200 * time.Millisecond) + defer ticker.Stop() + deadline := time.After(4 * time.Second) + for { + select { + case <-body.closed: + return + case <-deadline: + return + case <-ticker.C: + if _, err := pw.Write([]byte(upstreamKeepaliveEvent)); err != nil { + return + } + } + } + }() + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: body, + } + svc := newKeepaliveForwardService(1) + c, rec := newKeepaliveForwardContext() + + started := time.Now() + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, started, "model", "model") + elapsed := time.Since(started) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Less(t, elapsed, 2500*time.Millisecond, "keepalive events must not reset the first-output timer") + require.GreaterOrEqual(t, strings.Count(rec.Body.String(), upstreamKeepaliveEvent), 2, "keepalives reached the client before the timeout") + require.NotContains(t, rec.Body.String(), "resp_paced") + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c)) +} diff --git a/backend/internal/service/openai_oauth_input_metadata_test.go b/backend/internal/service/openai_oauth_input_metadata_test.go index 0279ee6112..d234831684 100644 --- a/backend/internal/service/openai_oauth_input_metadata_test.go +++ b/backend/internal/service/openai_oauth_input_metadata_test.go @@ -1,13 +1,113 @@ package service import ( + "bytes" "encoding/json" + "runtime" + "strings" "testing" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" ) +func oauthInputMetadataHistory(items, textBytes, metadataEvery int) []byte { + var body strings.Builder + _, _ = body.WriteString(`{"model":"gpt-5.5","opaque":9007199254740993,"input":[`) + text := strings.Repeat("x", textBytes) + for i := 0; i < items; i++ { + if i > 0 { + _ = body.WriteByte(',') + } + _, _ = body.WriteString(`{"role":"user","content":"`) + _, _ = body.WriteString(text) + _ = body.WriteByte('"') + if metadataEvery > 0 && i%metadataEvery == 0 { + _, _ = body.WriteString(`,"internal_chat_message_metadata_passthrough":{"content_item_kinds":["text"]}`) + } + _ = body.WriteByte('}') + } + _, _ = body.WriteString(`],"tail":{"keep":true}}`) + return []byte(body.String()) +} + +func TestOAuthInputInternalMetadataLargeHistory(t *testing.T) { + for _, fixture := range []struct { + name string + metadataEvery int + }{ + {name: "all", metadataEvery: 1}, + {name: "sparse", metadataEvery: 32}, + } { + t.Run(fixture.name, func(t *testing.T) { + body := oauthInputMetadataHistory(128, 16<<10, fixture.metadataEvery) + original := bytes.Clone(body) + out, changed, err := normalizeOpenAIOAuthResponsesCompatibilityBody(body) + require.NoError(t, err) + require.True(t, changed) + require.Equal(t, original, body, "normalization must not mutate caller-owned history") + require.True(t, gjson.ValidBytes(out)) + require.Equal(t, int64(128), gjson.GetBytes(out, "input.#").Int()) + require.NotContains(t, string(out), "internal_chat_message_metadata_passthrough") + require.Equal(t, "9007199254740993", gjson.GetBytes(out, "opaque").Raw) + require.True(t, gjson.GetBytes(out, "tail.keep").Bool()) + text := strings.Repeat("x", 16<<10) + for _, item := range gjson.GetBytes(out, "input").Array() { + require.Equal(t, "user", item.Get("role").String()) + require.Equal(t, text, item.Get("content").String()) + } + }) + } +} + +func TestOAuthInputInternalMetadataPreservesRawContent(t *testing.T) { + const body = ` {"opaque":9007199254740993,"inpu\u0074":[null,42,"keep",{"type":"function_call_output","call_id":"call_keep","output":[{"type":"input_image","image_url":"https://example.com/image.png","internal_chat_message_metadata_passthrough":{"keep":true}}],"internal_chat_message_metadata_passthrou\u0067h":null},{"role":"user","content":"internal_chat_message_metadata_passthrough"}],"tail" : "unchanged" } ` + out, changed, err := normalizeOpenAIOAuthResponsesCompatibilityBody([]byte(body)) + require.NoError(t, err) + require.True(t, changed) + require.True(t, bytes.HasPrefix(out, []byte(` {"opaque":9007199254740993,"inpu\u0074":`))) + require.True(t, bytes.HasSuffix(out, []byte(`,"tail" : "unchanged" } `))) + require.Equal(t, `[null,42,"keep",{"type":"function_call_output","call_id":"call_keep","output":[{"type":"input_image","image_url":"https://example.com/image.png","internal_chat_message_metadata_passthrough":{"keep":true}}]},{"role":"user","content":"internal_chat_message_metadata_passthrough"}]`, gjson.GetBytes(out, "input").Raw) +} + +func TestOAuthInputInternalMetadataUnchangedHistory(t *testing.T) { + body := oauthInputMetadataHistory(128, 16<<10, 0) + original := bytes.Clone(body) + out, changed, err := normalizeOpenAIOAuthResponsesCompatibilityBody(body) + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, original, out) + require.Same(t, &body[0], &out[0], "unchanged history should retain the caller's buffer") +} + +func BenchmarkOAuthInputInternalMetadataHistory(b *testing.B) { + for _, fixture := range []struct { + name string + items int + metadataEvery int + }{ + {name: "1_item", items: 1, metadataEvery: 1}, + {name: "32_items", items: 32, metadataEvery: 1}, + {name: "128_items", items: 128, metadataEvery: 1}, + {name: "128_items_sparse", items: 128, metadataEvery: 32}, + {name: "128_items_unchanged", items: 128}, + } { + b.Run(fixture.name, func(b *testing.B) { + body := oauthInputMetadataHistory(fixture.items, 16<<10, fixture.metadataEvery) + b.ReportAllocs() + b.SetBytes(int64(len(body))) + b.ResetTimer() + for i := 0; i < b.N; i++ { + out, changed, err := normalizeOpenAIOAuthResponsesCompatibilityBody(body) + if err != nil || changed != (fixture.metadataEvery > 0) { + b.Fatalf("changed=%v err=%v", changed, err) + } + runtime.KeepAlive(out) + } + }) + } +} + func TestOAuthInputInternalMetadata(t *testing.T) { const field = "internal_chat_message_metadata_passthrough" // The identically named field in user content must not be recursively stripped. diff --git a/backend/internal/service/openai_responses_sealed_call_test.go b/backend/internal/service/openai_responses_sealed_call_test.go index 31d1406c2d..2235990873 100644 --- a/backend/internal/service/openai_responses_sealed_call_test.go +++ b/backend/internal/service/openai_responses_sealed_call_test.go @@ -8,6 +8,7 @@ import ( "net/http/httptest" "strings" "testing" + "time" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" @@ -18,21 +19,26 @@ func TestOpenAIResponsesSealedFunctionCallRoundTrip(t *testing.T) { gin.SetMode(gin.TestMode) const arguments = `{"message":"synthetic-sealed-message"}` for _, marker := range []struct { - name string - raw string + name string + raw string + encryptedContent string }{ - {name: "encrypted", raw: `["message"]`}, + {name: "encrypted", raw: `["message"]`, encryptedContent: "synthetic-call-ciphertext"}, {name: "plaintext", raw: `[]`}, {name: "null", raw: `null`}, - {name: "absent"}, + {name: "absent", encryptedContent: "synthetic-call-ciphertext"}, } { for _, shape := range []string{"terminal_output", "item_done", "delta_fallback"} { - for _, passthrough := range []bool{false, true} { - mode := "normal" - if passthrough { - mode = "passthrough" - } - t.Run(marker.name+"/"+shape+"/"+mode, func(t *testing.T) { + for _, mode := range []struct { + name string + passthrough bool + streaming bool + }{ + {name: "normal"}, + {name: "passthrough", passthrough: true}, + {name: "streaming", streaming: true}, + } { + t.Run(marker.name+"/"+shape+"/"+mode.name, func(t *testing.T) { item := map[string]any{ "type": "function_call", "call_id": "call_sealed", "name": "send_message", "namespace": "collaboration", "arguments": arguments, @@ -40,6 +46,9 @@ func TestOpenAIResponsesSealedFunctionCallRoundTrip(t *testing.T) { if marker.raw != "" { item["encrypted_function_args"] = json.RawMessage(marker.raw) } + if marker.encryptedContent != "" { + item["encrypted_content"] = marker.encryptedContent + } output := []any{} var frames []string addFrame := func(event map[string]any) { @@ -75,7 +84,11 @@ func TestOpenAIResponsesSealedFunctionCallRoundTrip(t *testing.T) { } account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth} svc := newCompactBridgeTestService() - if passthrough { + if mode.streaming { + result, err := svc.handleStreamingResponse(context.Background(), resp, c, account, time.Now(), "test-model", "test-model") + require.NoError(t, err) + require.Equal(t, 7, result.usage.InputTokens) + } else if mode.passthrough { result, err := svc.handleNonStreamingResponsePassthrough(context.Background(), resp, c, account, "test-model", "test-model") require.NoError(t, err) require.Equal(t, 7, result.usage.InputTokens) @@ -85,8 +98,15 @@ func TestOpenAIResponsesSealedFunctionCallRoundTrip(t *testing.T) { require.Equal(t, 7, result.usage.InputTokens) } require.Equal(t, http.StatusOK, rec.Code) - require.Contains(t, rec.Header().Get("Content-Type"), "application/json") body := rec.Body.Bytes() + if mode.streaming { + require.Contains(t, rec.Header().Get("Content-Type"), "text/event-stream") + _, terminal, ok := extractOpenAISSETerminalEvent(string(body)) + require.True(t, ok) + body = []byte(gjson.GetBytes(terminal, "response").Raw) + } else { + require.Contains(t, rec.Header().Get("Content-Type"), "application/json") + } require.Len(t, gjson.GetBytes(body, "output").Array(), 1) call := gjson.GetBytes(body, "output.0") require.Equal(t, "function_call", call.Get("type").String()) @@ -98,6 +118,11 @@ func TestOpenAIResponsesSealedFunctionCallRoundTrip(t *testing.T) { } else { require.Equal(t, marker.raw, call.Get("encrypted_function_args").Raw) } + if marker.encryptedContent == "" { + require.False(t, call.Get("encrypted_content").Exists()) + } else { + require.Equal(t, marker.encryptedContent, call.Get("encrypted_content").String()) + } require.Equal(t, "collaboration", call.Get("namespace").String()) }) } diff --git a/backend/internal/service/openai_visible_ttft_test.go b/backend/internal/service/openai_visible_ttft_test.go index 24a60e21e2..87497f39f0 100644 --- a/backend/internal/service/openai_visible_ttft_test.go +++ b/backend/internal/service/openai_visible_ttft_test.go @@ -98,7 +98,9 @@ func TestOpenAINativeMetadataAndKeepaliveDoNotDisarmFirstOutputTimeout(t *testin var failoverErr *UpstreamFailoverError require.ErrorAs(t, err, &failoverErr) require.True(t, failoverErr.SafeToFailoverAfterWrite) - require.Empty(t, recorder.Body.String()) + // Only the upstream keepalive event reaches the client; it is not output. + require.Equal(t, "data: {\"type\":\"keepalive\"}\n\n", recorder.Body.String()) + require.Equal(t, -1, OpenAICompactKeepaliveAdjustedWrittenSize(c)) select { case <-writerDone: case <-time.After(time.Second): diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 5d8fffa62f..c3994e3540 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -320,7 +320,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( normalized = next } accountIdentitySourceRaw := append([]byte(nil), normalized...) - accountScopedPayload, accountScoped, scopeErr := applyCodexAccountIdentityClientMetadataRaw(normalized, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c)) + accountScopedPayload, accountScoped, scopeErr := applyCodexAccountIdentityClientMetadataRaw(normalized, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c), codexClientSessionID(c)) if scopeErr != nil { return openAIWSClientPayload{}, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket identity metadata", scopeErr) } diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index 71804511eb..22d74f58db 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -761,7 +761,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( firstClientMessage = aliasedBody } } - accountScopedFirst, accountScoped, scopeErr := applyCodexAccountIdentityClientMetadataRaw(firstClientMessage, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c)) + accountScopedFirst, accountScoped, scopeErr := applyCodexAccountIdentityClientMetadataRaw(firstClientMessage, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c), codexClientSessionID(c)) if scopeErr != nil { return NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket identity metadata", scopeErr) } @@ -1015,7 +1015,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( } } if isResponseCreate || eventType == "session.update" { - accountScopedPayload, accountScoped, scopeErr := applyCodexAccountIdentityClientMetadataRaw(payload, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c)) + accountScopedPayload, accountScoped, scopeErr := applyCodexAccountIdentityClientMetadataRaw(payload, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c), codexClientSessionID(c)) if scopeErr != nil { return payload, nil, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket identity metadata", scopeErr) } diff --git a/backend/internal/service/opencode_go.go b/backend/internal/service/opencode_go.go index 248ced9589..7709cb55e3 100644 --- a/backend/internal/service/opencode_go.go +++ b/backend/internal/service/opencode_go.go @@ -82,13 +82,7 @@ func writeOpenCodeUnsupportedModelError(c *gin.Context, isAnthropic bool, model msg := fmt.Sprintf("Model '%s' is not supported on OpenCode standard gateway (gemini models require Google SDK endpoint, jev models require System One endpoint)", model) if c != nil { if isAnthropic { - c.JSON(http.StatusBadRequest, gin.H{ - "type": "error", - "error": gin.H{ - "type": "invalid_request_error", - "message": msg, - }, - }) + writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", msg) } else { c.JSON(http.StatusBadRequest, gin.H{ "error": gin.H{ diff --git a/backend/internal/service/pricing_service.go b/backend/internal/service/pricing_service.go index f973b5abef..3f362a4964 100644 --- a/backend/internal/service/pricing_service.go +++ b/backend/internal/service/pricing_service.go @@ -232,10 +232,17 @@ var ( } ) +// tokenPriceOverrides tracks explicit nonnegative rates from pricing.override_file. +// Keep this provenance with the parsed card so billing never rereads the file. +type tokenPriceOverrides struct { + input, output, cacheRead bool +} + // LiteLLMModelPricing LiteLLM价格数据结构 // 只保留我们需要的字段,使用指针来处理可能缺失的值 type LiteLLMModelPricing struct { - CacheCreationInputTokenCostExplicit bool `json:"-"` + CacheCreationInputTokenCostExplicit bool `json:"-"` + priceOverrides tokenPriceOverrides InputCostPerToken float64 `json:"input_cost_per_token"` InputCostPerTokenPriority float64 `json:"input_cost_per_token_priority"` OutputCostPerToken float64 `json:"output_cost_per_token"` @@ -343,7 +350,10 @@ func (s *PricingService) Initialize() error { // 启动定时更新 s.startUpdateScheduler() - logger.LegacyPrintf("service.pricing", "[Pricing] Service initialized with %d models", len(s.pricingData)) + s.mu.RLock() + modelCount := len(s.pricingData) + s.mu.RUnlock() + logger.LegacyPrintf("service.pricing", "[Pricing] Service initialized with %d models", modelCount) return nil } @@ -416,25 +426,10 @@ func (s *PricingService) checkAndUpdatePricing() error { return s.downloadPricingData() } - // 如果配置了哈希URL,通过远程哈希检查是否有更新 + // 如果配置了哈希URL,通过远程哈希检查是否有更新。本地文件已加载,服务已可用, + // 校验放到后台做:远端慢或不通时不挡启动与监听(fetchRemoteHash 请求挂住时会一直等到客户端超时)。 if s.cfg.Pricing.HashURL != "" { - remoteHash, err := s.fetchRemoteHash() - if err != nil { - logger.LegacyPrintf("service.pricing", "[Pricing] Failed to fetch remote hash on startup: %v", err) - return nil // 已加载本地文件,哈希获取失败不影响启动 - } - - s.mu.RLock() - localHash := s.localHash - s.mu.RUnlock() - - if localHash == "" || remoteHash != localHash { - logger.LegacyPrintf("service.pricing", "[Pricing] Remote hash differs on startup (local=%s remote=%s), downloading...", - localHash[:min(8, len(localHash))], remoteHash[:min(8, len(remoteHash))]) - if err := s.downloadPricingData(); err != nil { - logger.LegacyPrintf("service.pricing", "[Pricing] Download failed, using existing file: %v", err) - } - } + go s.checkRemoteHashOnStartup() return nil } @@ -457,6 +452,27 @@ func (s *PricingService) checkAndUpdatePricing() error { return nil } +// checkRemoteHashOnStartup 启动后在后台比对远程哈希,不同则下载;失败只记日志,沿用已加载的本地文件。 +func (s *PricingService) checkRemoteHashOnStartup() { + remoteHash, err := s.fetchRemoteHash() + if err != nil { + logger.LegacyPrintf("service.pricing", "[Pricing] Failed to fetch remote hash on startup: %v", err) + return + } + + s.mu.RLock() + localHash := s.localHash + s.mu.RUnlock() + + if localHash == "" || remoteHash != localHash { + logger.LegacyPrintf("service.pricing", "[Pricing] Remote hash differs on startup (local=%s remote=%s), downloading...", + localHash[:min(8, len(localHash))], remoteHash[:min(8, len(remoteHash))]) + if err := s.downloadPricingData(); err != nil { + logger.LegacyPrintf("service.pricing", "[Pricing] Download failed, using existing file: %v", err) + } + } +} + // syncWithRemote 与远程同步(基于哈希校验) func (s *PricingService) syncWithRemote() error { // 如果配置了哈希URL,从远程获取哈希进行比对 @@ -686,7 +702,7 @@ func (s *PricingService) parsePricingData(body []byte) (map[string]*LiteLLMModel if err := json.Unmarshal(body, &rawData); err != nil { return nil, fmt.Errorf("parse raw JSON: %w", err) } - rawData = s.applyPricingOverrides(rawData) + rawData, priceOverrides := s.applyPricingOverrides(rawData) result := make(map[string]*LiteLLMModelPricing) skipped := 0 @@ -711,6 +727,7 @@ func (s *PricingService) parsePricingData(body []byte) (map[string]*LiteLLMModel } pricing := &LiteLLMModelPricing{ + priceOverrides: priceOverrides[modelName], LiteLLMProvider: entry.LiteLLMProvider, Mode: entry.Mode, SupportsPromptCaching: entry.SupportsPromptCaching, @@ -951,11 +968,12 @@ func warnOrphanCacheTierFields(entries []string) { // 文件的解析都经过 parsePricingData,因此 override 是最高优先级的数据源。这里只修补 // 已存在的条目:目录/回退里都没有的模型由 mergeOverrideOnlyModels 在两层数据合并后 // 统一并入——若在此处抢先建条目,纯 override 条目会挡住回退文件中同名完整条目的合并。 -func (s *PricingService) applyPricingOverrides(rawData map[string]json.RawMessage) map[string]json.RawMessage { +func (s *PricingService) applyPricingOverrides(rawData map[string]json.RawMessage) (map[string]json.RawMessage, map[string]tokenPriceOverrides) { overrides := s.loadPricingOverrideEntries() if len(overrides) == 0 { - return rawData + return rawData, nil } + priceOverrides := make(map[string]tokenPriceOverrides, len(overrides)) for name, patch := range overrides { base, ok := rawData[name] if !ok { @@ -967,8 +985,25 @@ func (s *PricingService) applyPricingOverrides(rawData map[string]json.RawMessag continue } rawData[name] = merged + priceOverrides[name] = tokenPriceOverridesFromPatch(patch) + } + return rawData, priceOverrides +} + +func tokenPriceOverridesFromPatch(patch json.RawMessage) tokenPriceOverrides { + var fields map[string]json.RawMessage + if json.Unmarshal(patch, &fields) != nil { + return tokenPriceOverrides{} + } + explicitRate := func(field string) bool { + var rate *float64 + return json.Unmarshal(fields[field], &rate) == nil && rate != nil && *rate >= 0 + } + return tokenPriceOverrides{ + input: explicitRate("input_cost_per_token"), + output: explicitRate("output_cost_per_token"), + cacheRead: explicitRate("cache_read_input_token_cost"), } - return rawData } // loadPricingOverrideEntries 读取 override 文件的原始条目。未配置返回 nil; diff --git a/backend/internal/service/pricing_service_startup_test.go b/backend/internal/service/pricing_service_startup_test.go new file mode 100644 index 0000000000..bf0b1d14da --- /dev/null +++ b/backend/internal/service/pricing_service_startup_test.go @@ -0,0 +1,134 @@ +package service + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "os" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +// blockingHashRemoteClient 的 FetchHashText 一直阻塞到 release 关闭,模拟远端不可达时等满超时。 +type blockingHashRemoteClient struct { + started chan struct{} + release chan struct{} + once sync.Once +} + +func (c *blockingHashRemoteClient) FetchPricingJSON(context.Context, string) ([]byte, error) { + return nil, context.DeadlineExceeded +} + +func (c *blockingHashRemoteClient) FetchHashText(context.Context, string) (string, error) { + c.once.Do(func() { close(c.started) }) + <-c.release + return "", context.DeadlineExceeded +} + +// failingHashRemoteClient 的哈希请求立即失败,下载请求只计数。 +type failingHashRemoteClient struct { + mu sync.Mutex + hashCalls int + downloads int +} + +func (c *failingHashRemoteClient) FetchPricingJSON(context.Context, string) ([]byte, error) { + c.mu.Lock() + defer c.mu.Unlock() + c.downloads++ + return nil, errors.New("unexpected download") +} + +func (c *failingHashRemoteClient) FetchHashText(context.Context, string) (string, error) { + c.mu.Lock() + defer c.mu.Unlock() + c.hashCalls++ + return "", errors.New("hash endpoint unreachable") +} + +func (c *failingHashRemoteClient) counts() (hashCalls, downloads int) { + c.mu.Lock() + defer c.mu.Unlock() + return c.hashCalls, c.downloads +} + +func newStartupPricingService(t *testing.T, remote PricingRemoteClient) *PricingService { + t.Helper() + svc := NewPricingService(&config.Config{Pricing: config.PricingConfig{ + DataDir: t.TempDir(), + RemoteURL: "https://example.com/pricing.json", + HashURL: "https://example.com/pricing.sha256", + }}, remote) + require.NoError(t, os.WriteFile(svc.getPricingFilePath(), []byte(hotReloadCatalogJSON), 0644)) + return svc +} + +// 本地价格文件已在时,启动检查不得等远端哈希:远端不可达也要立即返回,价格表已可用。 +func TestPricingStartupDoesNotWaitForRemoteHash(t *testing.T) { + remote := &blockingHashRemoteClient{started: make(chan struct{}), release: make(chan struct{})} + t.Cleanup(func() { close(remote.release) }) + svc := newStartupPricingService(t, remote) + + done := make(chan error, 1) + go func() { done <- svc.checkAndUpdatePricing() }() + + select { + case err := <-done: + require.NoError(t, err) + case <-time.After(2 * time.Second): + t.Fatal("startup must not block on the remote hash fetch") + } + require.NotNil(t, svc.GetModelPricing("remote-model"), "本地价格表启动即可用") + select { + case <-remote.started: + case <-time.After(2 * time.Second): + t.Fatal("remote hash check must still run in the background") + } +} + +// 后台哈希校验发现远端哈希不同时,仍要下载并替换价格表。 +func TestPricingStartupBackgroundCheckDownloadsWhenHashDiffers(t *testing.T) { + newBody := `{` + hotReloadModelJSON("remote-model", 3e-6, 6e-6) + `}` + newHash := fmt.Sprintf("%x", sha256.Sum256([]byte(newBody))) + remote := &stubPricingRemoteClient{body: newBody, hash: newHash} + svc := newStartupPricingService(t, remote) + + require.NoError(t, svc.checkAndUpdatePricing()) + + require.Eventually(t, func() bool { + p := svc.GetModelPricing("remote-model") + return p != nil && p.InputCostPerToken == 3e-6 + }, 2*time.Second, 10*time.Millisecond, "后台校验应下载并替换价格表") + svc.mu.RLock() + require.Equal(t, newHash, svc.localHash) + svc.mu.RUnlock() + saved, err := os.ReadFile(svc.getPricingFilePath()) + require.NoError(t, err) + require.Equal(t, newBody, string(saved)) +} + +// 后台哈希获取失败时沿用已加载的本地价格表,只记日志,不触发下载。 +func TestPricingStartupBackgroundCheckKeepsLocalDataWhenHashFetchFails(t *testing.T) { + logs, restore := captureStructuredLog(t) + defer restore() + remote := &failingHashRemoteClient{} + svc := newStartupPricingService(t, remote) + + require.NoError(t, svc.checkAndUpdatePricing()) + + require.Eventually(t, func() bool { + return logs.ContainsMessage("Failed to fetch remote hash on startup: hash endpoint unreachable") + }, 2*time.Second, 10*time.Millisecond, "哈希获取失败应记日志") + hashCalls, downloads := remote.counts() + require.Equal(t, 1, hashCalls) + require.Zero(t, downloads) + p := svc.GetModelPricing("remote-model") + require.NotNil(t, p) + require.InDelta(t, 1e-6, p.InputCostPerToken, 1e-12) +} diff --git a/backend/internal/service/ratelimit_bedrock.go b/backend/internal/service/ratelimit_bedrock.go new file mode 100644 index 0000000000..a3f29a14e5 --- /dev/null +++ b/backend/internal/service/ratelimit_bedrock.go @@ -0,0 +1,110 @@ +package service + +import ( + "context" + "log/slog" + "net/http" + "strings" + "time" +) + +// Bedrock 错误文案(小写,与 extractUpstreamErrorMessage 的结果比对)。 +// 400 ValidationException 会把请求里的非法字段名回显进消息,账号级判定只认整句或固定开头, +// 不按子串匹配,避免请求内容触发停号。 +const ( + // 400 ValidationException:AWS 封禁账号后所有调用返回的完整消息。 + bedrockAccountBlockedMessage = "operation not allowed" + // 404 ResourceNotFoundException:账号未提交 Anthropic 模型用例表单时消息的开头。 + bedrockUseCaseMissingPrefix = "model use case details have not been submitted" + // 5xx:Bedrock 内容过滤拦截了请求或输出。 + bedrockContentFilterMarker = "blocked by content filtering policy" + + bedrockThrottlingReason = "bedrock_throttling" +) + +type gatewaySchedulingModelContextKey struct{} + +// WithGatewaySchedulingModel 记录选号时使用的客户端模型。请求经渠道模型映射改写模型后转发时, +// Bedrock 账号的模型级状态按该模型推导调度器读取的键。 +func WithGatewaySchedulingModel(ctx context.Context, model string) context.Context { + if ctx == nil { + ctx = context.Background() + } + return context.WithValue(ctx, gatewaySchedulingModelContextKey{}, strings.TrimSpace(model)) +} + +// bedrockSchedulingModelKey 返回调度器按模型隔离账号状态时读取的键:账号映射后的选号模型; +// 上下文未记录选号模型时用本次转发的模型。键不是发往上游的 Bedrock 模型 ID。 +func bedrockSchedulingModelKey(ctx context.Context, account *Account, forwardModel string) string { + model := forwardModel + if ctx != nil { + if scheduling, _ := ctx.Value(gatewaySchedulingModelContextKey{}).(string); scheduling != "" { + model = scheduling + } + } + return account.GetMappedModel(model) +} + +// handleBedrockUpstreamError 处理 Bedrock 账号特有的错误语义,handled=false 时交回通用逻辑。 +// +// Bedrock 的限流额度按(AWS 账号、源区域、推理配置、模型)计算,而一个 Bedrock 账号固定了 +// AWS 凭证、区域与推理配置,所以 429 只冷却本次请求的模型;模型未知时交回通用的账号级兜底。 +func (s *RateLimitService) handleBedrockUpstreamError(ctx context.Context, account *Account, statusCode int, upstreamMsg string, modelKey string) (handled bool, shouldDisable bool) { + switch statusCode { + case http.StatusBadRequest: + if isBedrockAccountBlockedMessage(upstreamMsg) { + s.handleAuthError(ctx, account, "Bedrock account blocked (400): "+upstreamMsg) + return true, true + } + // 其余 400 都是请求错误,不影响账号状态。 + return true, false + case http.StatusNotFound: + if strings.HasPrefix(normalizeBedrockErrorMessage(upstreamMsg), bedrockUseCaseMissingPrefix) { + s.handleAuthError(ctx, account, "Bedrock model use case not submitted (404): "+upstreamMsg) + return true, true + } + case http.StatusTooManyRequests: + modelKey = strings.TrimSpace(modelKey) + if modelKey == "" { + return false, false + } + s.applyBedrockModelThrottle(ctx, account, modelKey) + return true, false + } + return false, false +} + +// applyBedrockModelThrottle 按 429 默认回避配置冷却 (账号, 模型);回避关闭时不写任何状态。 +func (s *RateLimitService) applyBedrockModelThrottle(ctx context.Context, account *Account, modelKey string) { + cooldown, enabled := s.get429FallbackCooldown(ctx, account) + if !enabled { + slog.Info("bedrock_throttling_cooldown_ignored", "account_id", account.ID, "model", modelKey) + return + } + resetAt := time.Now().Add(cooldown) + if err := s.accountRepo.SetModelRateLimit(ctx, account.ID, modelKey, resetAt, bedrockThrottlingReason); err != nil { + slog.Warn("bedrock_throttling_set_model_rate_limit_failed", "account_id", account.ID, "model", modelKey, "error", err) + return + } + slog.Info("bedrock_throttling_model_rate_limited", "account_id", account.ID, "model", modelKey, "reset_at", resetAt) +} + +func normalizeBedrockErrorMessage(msg string) string { + return strings.ToLower(strings.TrimSpace(msg)) +} + +// isBedrockAccountBlockedMessage 按整句比对封号消息(忽略大小写与句末句点)。 +func isBedrockAccountBlockedMessage(msg string) bool { + return strings.TrimSuffix(normalizeBedrockErrorMessage(msg), ".") == bedrockAccountBlockedMessage +} + +// isBedrockContentFilterError 判断上游错误是否为 Bedrock 内容过滤拦截;状态码集合与 +// handleErrorResponse 把 5xx 改写为客户端响应的 case 一致(500/502/503/504)。 +func isBedrockContentFilterError(statusCode int, body []byte) bool { + switch statusCode { + case http.StatusInternalServerError, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout: + default: + return false + } + return strings.Contains(normalizeBedrockErrorMessage(extractUpstreamErrorMessage(body)), bedrockContentFilterMarker) +} diff --git a/backend/internal/service/ratelimit_bedrock_test.go b/backend/internal/service/ratelimit_bedrock_test.go new file mode 100644 index 0000000000..297ab023b2 --- /dev/null +++ b/backend/internal/service/ratelimit_bedrock_test.go @@ -0,0 +1,451 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/binary" + "errors" + "hash/crc32" + "io" + "net/http" + "net/http/httptest" + "strings" + "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" + "github.com/tidwall/gjson" +) + +type bedrockErrorRepoStub struct { + tempUnschedScopeRepoStub + errorMessages []string + rateLimitedAt []time.Time +} + +func (r *bedrockErrorRepoStub) SetError(_ context.Context, _ int64, msg string) error { + r.errorCalls++ + r.errorMessages = append(r.errorMessages, msg) + return nil +} + +func (r *bedrockErrorRepoStub) SetRateLimited(_ context.Context, _ int64, resetAt time.Time) error { + r.rateLimitedAt = append(r.rateLimitedAt, resetAt) + return nil +} + +type bedrockErrorUpstreamStub struct { + status int + header http.Header + body []byte + calls int + lastURL string +} + +func (u *bedrockErrorUpstreamStub) Do(req *http.Request, proxyURL string, accountID int64, accountConcurrency int) (*http.Response, error) { + return u.DoWithTLS(req, proxyURL, accountID, accountConcurrency, nil) +} + +func (u *bedrockErrorUpstreamStub) DoWithTLS(req *http.Request, _ string, _ int64, _ int, _ *tlsfingerprint.Profile) (*http.Response, error) { + u.calls++ + u.lastURL = req.URL.String() + header := http.Header{"Content-Type": []string{"application/json"}, "X-Amzn-Requestid": []string{"aws-req-1"}} + for k, v := range u.header { + header[k] = v + } + return &http.Response{StatusCode: u.status, Header: header, Body: io.NopCloser(bytes.NewReader(u.body))}, nil +} + +func newBedrockErrorTestAccount(rules ...map[string]any) *Account { + account := &Account{ + ID: 77, + Name: "bedrock-error-test", + Platform: PlatformAnthropic, + Type: AccountTypeBedrock, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{ + "auth_mode": "apikey", + "api_key": "bedrock-key", + "aws_region": "us-east-1", + }, + } + if len(rules) > 0 { + raw := make([]any, 0, len(rules)) + for _, rule := range rules { + raw = append(raw, rule) + } + account.Credentials["temp_unschedulable_enabled"] = true + account.Credentials["temp_unschedulable_rules"] = raw + } + return account +} + +type bedrockForwardOutcome struct { + result *ForwardResult + err error + failover *UpstreamFailoverError + recorder *httptest.ResponseRecorder + upstream *bedrockErrorUpstreamStub +} + +type bedrockForwardOptions struct { + ctx context.Context + model string + stream bool + rateLimiter *RateLimitService +} + +func runBedrockForward(t *testing.T, repo *bedrockErrorRepoStub, account *Account, upstream *bedrockErrorUpstreamStub, stream bool) bedrockForwardOutcome { + t.Helper() + return runBedrockForwardWith(t, repo, account, upstream, bedrockForwardOptions{stream: stream}) +} + +func runBedrockForwardWith(t *testing.T, repo *bedrockErrorRepoStub, account *Account, upstream *bedrockErrorUpstreamStub, opts bedrockForwardOptions) bedrockForwardOutcome { + t.Helper() + gin.SetMode(gin.TestMode) + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}} + rateLimiter := opts.rateLimiter + if rateLimiter == nil { + rateLimiter = &RateLimitService{accountRepo: repo, cfg: cfg} + } + ctx := opts.ctx + if ctx == nil { + ctx = context.Background() + } + model := opts.model + if model == "" { + model = "claude-sonnet-4-5" + } + svc := &GatewayService{cfg: cfg, httpUpstream: upstream, rateLimitService: rateLimiter} + body := []byte(`{"model":"` + model + `","messages":[{"role":"user","content":"hi"}]}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + parsed := &ParsedRequest{Body: NewRequestBodyRef(body), Model: model, Stream: opts.stream} + + result, err := svc.forwardBedrock(ctx, c, account, parsed, time.Now()) + out := bedrockForwardOutcome{result: result, err: err, recorder: rec, upstream: upstream} + var failover *UpstreamFailoverError + if errors.As(err, &failover) { + out.failover = failover + } + return out +} + +func bedrockErrorRule(statusCode int, keyword string, minutes int, scope string) map[string]any { + return map[string]any{ + "error_code": float64(statusCode), + "keywords": []any{keyword}, + "duration_minutes": float64(minutes), + "scope": scope, + } +} + +func TestBedrockUpstreamErrors_AccountBlockedDisablesAndFailsOver(t *testing.T) { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusBadRequest, body: []byte(`{"message":"Operation not allowed"}`)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.NotNil(t, out.failover, "封号必须换号,不能把 400 回给客户端") + require.Equal(t, http.StatusBadRequest, out.failover.StatusCode) + require.Equal(t, 1, repo.errorCalls) + require.Contains(t, repo.errorMessages[0], "Operation not allowed") + require.Zero(t, out.recorder.Body.Len()) +} + +func TestBedrockUpstreamErrors_UseCaseMissingDisablesAndFailsOver(t *testing.T) { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusNotFound, body: []byte(`{"message":"Model use case details have not been submitted for this account. Fill out the Anthropic use case details form before using the model. If you have already filled out the form, try again in 15 minutes."}`)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.NotNil(t, out.failover) + require.Equal(t, http.StatusNotFound, out.failover.StatusCode) + require.Equal(t, 1, repo.errorCalls) + require.Empty(t, repo.modelRateLimitCalls, "用例未提交是账号级问题,不按模型不存在冷却") + require.Zero(t, out.recorder.Body.Len()) +} + +func TestBedrockUpstreamErrors_TempUnschedRuleOverridesAccountLevelDefaults(t *testing.T) { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusNotFound, body: []byte(`{"message":"Model use case details have not been submitted for this account."}`)} + account := newBedrockErrorTestAccount(bedrockErrorRule(http.StatusNotFound, "use case details", 30, TempUnschedScopeAccount)) + + out := runBedrockForward(t, repo, account, upstream, false) + + require.NotNil(t, out.failover) + require.Zero(t, repo.errorCalls) + require.Equal(t, 1, repo.tempCalls) +} + +func TestBedrockUpstreamErrors_ThrottlingCoolsOnlyRequestedModel(t *testing.T) { + for _, msg := range []string{ + "Too many requests, please wait before trying again.", + "Too many tokens per day, please wait before trying again.", + } { + t.Run(msg, func(t *testing.T) { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusTooManyRequests, body: []byte(`{"message":"` + msg + `"}`)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.NotNil(t, out.failover) + require.Equal(t, http.StatusTooManyRequests, out.failover.StatusCode) + require.Equal(t, 1, upstream.calls, "Bedrock 429 不在同一个桶上重试") + require.Empty(t, repo.rateLimitedAt, "429 不冷却整个账号") + require.Len(t, repo.modelRateLimitCalls, 1) + call := repo.modelRateLimitCalls[0] + require.Equal(t, "claude-sonnet-4-5", call.scope, "冷却键与调度器读取的模型键一致") + require.Equal(t, bedrockThrottlingReason, call.reason) + require.WithinDuration(t, time.Now().Add(defaultRateLimit429CooldownSeconds*time.Second), call.resetAt, 2*time.Second) + }) + } +} + +func TestBedrockUpstreamErrors_DailyTokenRuleTakesPrecedenceOverThrottlingCooldown(t *testing.T) { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusTooManyRequests, body: []byte(`{"message":"Too many tokens per day, please wait before trying again."}`)} + account := newBedrockErrorTestAccount(bedrockErrorRule(http.StatusTooManyRequests, "tokens per day", 240, TempUnschedScopeModel)) + + out := runBedrockForward(t, repo, account, upstream, false) + + require.NotNil(t, out.failover) + require.Empty(t, repo.rateLimitedAt) + require.Zero(t, repo.tempCalls) + require.Len(t, repo.modelRateLimitCalls, 1) + require.Equal(t, "claude-sonnet-4-5", repo.modelRateLimitCalls[0].scope) + require.WithinDuration(t, time.Now().Add(240*time.Minute), repo.modelRateLimitCalls[0].resetAt, 2*time.Second) +} + +func TestBedrockThrottlingWithoutModelFallsBackToAccountCooldown(t *testing.T) { + repo := &bedrockErrorRepoStub{} + svc := &RateLimitService{accountRepo: repo} + + shouldDisable := svc.HandleUpstreamError(context.Background(), newBedrockErrorTestAccount(), http.StatusTooManyRequests, http.Header{}, []byte(`{"message":"Too many requests, please wait before trying again."}`)) + + require.False(t, shouldDisable) + require.Empty(t, repo.modelRateLimitCalls) + require.Len(t, repo.rateLimitedAt, 1) +} + +func TestBedrockUpstreamErrors_ContentFilterReturnsRequestErrorWithoutFailover(t *testing.T) { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusInternalServerError, body: []byte(`{"message":"Output blocked by content filtering policy"}`)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.Error(t, out.err) + require.Nil(t, out.failover, "内容过滤换号结果相同,不换号") + require.Equal(t, http.StatusBadRequest, out.recorder.Code) + require.Equal(t, "invalid_request_error", gjson.Get(out.recorder.Body.String(), "error.type").String()) + require.Equal(t, "Output blocked by content filtering policy", gjson.Get(out.recorder.Body.String(), "error.message").String()) + require.Zero(t, repo.errorCalls) + require.Zero(t, repo.tempCalls) + require.Empty(t, repo.modelRateLimitCalls) + require.Empty(t, repo.rateLimitedAt) +} + +func TestBedrockUpstreamErrors_ServerErrorsStillFailOverWithoutPenalty(t *testing.T) { + for _, tc := range []struct { + status int + body string + }{ + {http.StatusInternalServerError, `{"message":"Internal server error"}`}, + {http.StatusServiceUnavailable, `{"message":"Bedrock is unable to process your request."}`}, + } { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: tc.status, body: []byte(tc.body)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.NotNil(t, out.failover, "status %d", tc.status) + require.Equal(t, tc.status, out.failover.StatusCode) + require.Zero(t, repo.errorCalls) + require.Zero(t, repo.tempCalls) + require.Empty(t, repo.modelRateLimitCalls) + require.Empty(t, repo.rateLimitedAt) + } +} + +func TestBedrockUpstreamErrors_OtherValidationErrorsReturnToClient(t *testing.T) { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusBadRequest, body: []byte(`{"message":"messages.0.content.0.image.source.base64: image exceeds 5 MB maximum"}`)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.Error(t, out.err) + require.Nil(t, out.failover) + require.Equal(t, http.StatusBadRequest, out.recorder.Code) + require.Zero(t, repo.errorCalls) +} + +func buildBedrockEventStreamFrame(headers map[string]string, payload []byte) []byte { + var headersBuf bytes.Buffer + for _, name := range []string{":event-type", ":exception-type", ":message-type"} { + value, ok := headers[name] + if !ok { + continue + } + _ = headersBuf.WriteByte(byte(len(name))) + _, _ = headersBuf.WriteString(name) + _ = headersBuf.WriteByte(7) + _ = binary.Write(&headersBuf, binary.BigEndian, uint16(len(value))) + _, _ = headersBuf.WriteString(value) + } + headerBytes := headersBuf.Bytes() + total := uint32(12 + len(headerBytes) + len(payload) + 4) + + var prelude bytes.Buffer + _ = binary.Write(&prelude, binary.BigEndian, total) + _ = binary.Write(&prelude, binary.BigEndian, uint32(len(headerBytes))) + + var frame bytes.Buffer + _, _ = frame.Write(prelude.Bytes()) + _ = binary.Write(&frame, binary.BigEndian, crc32.ChecksumIEEE(prelude.Bytes())) + _, _ = frame.Write(headerBytes) + _, _ = frame.Write(payload) + _ = binary.Write(&frame, binary.BigEndian, crc32.ChecksumIEEE(frame.Bytes())) + return frame.Bytes() +} + +func bedrockChunkFrame(event string) []byte { + payload := []byte(`{"bytes":"` + base64.StdEncoding.EncodeToString([]byte(event)) + `"}`) + return buildBedrockEventStreamFrame(map[string]string{":event-type": "chunk", ":message-type": "event"}, payload) +} + +func TestForwardBedrockStreamInterruptionKeepsObservedUsage(t *testing.T) { + var stream bytes.Buffer + _, _ = stream.Write(bedrockChunkFrame(`{"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","usage":{"input_tokens":120,"cache_read_input_tokens":30,"output_tokens":1}}}`)) + _, _ = stream.Write(bedrockChunkFrame(`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hel"}}`)) + _, _ = stream.Write(buildBedrockEventStreamFrame(map[string]string{ + ":exception-type": "internalServerException", + ":message-type": "exception", + }, []byte(`{"message":"Overloaded"}`))) + + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{ + status: http.StatusOK, + header: http.Header{"Content-Type": []string{"application/vnd.amazon.eventstream"}}, + body: stream.Bytes(), + } + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, true) + + require.Error(t, out.err) + require.Nil(t, out.failover, "已向客户端输出内容后不换号") + require.Contains(t, out.err.Error(), "internalServerException") + require.NotNil(t, out.result, "流中断时返回已观测到的 usage 供计费") + require.Equal(t, 120, out.result.Usage.InputTokens) + require.Equal(t, 30, out.result.Usage.CacheReadInputTokens) + require.Equal(t, "claude-sonnet-4-5", out.result.Model) + require.True(t, strings.HasPrefix(out.result.UpstreamModel, "us.anthropic.claude-sonnet-4-5"), out.result.UpstreamModel) + require.Equal(t, "aws-req-1", out.result.RequestID) + require.True(t, out.result.Stream) + require.Contains(t, out.recorder.Body.String(), "message_start") +} + +func TestBedrockUpstreamErrors_AccountBlockedMatchesWholeMessageOnly(t *testing.T) { + for _, msg := range []string{"Operation not allowed", "operation not allowed.", " OPERATION NOT ALLOWED "} { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusBadRequest, body: []byte(`{"message":"` + msg + `"}`)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.NotNil(t, out.failover, msg) + require.Equal(t, 1, repo.errorCalls, msg) + } +} + +func TestBedrockUpstreamErrors_EchoedRequestContentDoesNotDisableAccount(t *testing.T) { + for _, echoed := range []string{"Operation not allowed", "credit balance", "organization has been disabled", "identity verification is required"} { + t.Run(echoed, func(t *testing.T) { + repo := &bedrockErrorRepoStub{} + body := `{"message":"Malformed input request: #: extraneous key [` + echoed + `] is not permitted, please reformat your input and try again."}` + upstream := &bedrockErrorUpstreamStub{status: http.StatusBadRequest, body: []byte(body)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.Nil(t, out.failover, "请求错误不换号") + require.Equal(t, http.StatusBadRequest, out.recorder.Code) + require.Zero(t, repo.errorCalls, "回显进错误消息的请求内容不能触发停号") + require.Zero(t, repo.tempCalls) + require.Empty(t, repo.modelRateLimitCalls) + }) + } +} + +func TestBedrockUpstreamErrors_ChannelMappedModelCoolsSchedulingKey(t *testing.T) { + ctx := WithGatewaySchedulingModel(context.Background(), "claude-sonnet-4-5") + + t.Run("throttling", func(t *testing.T) { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusTooManyRequests, body: []byte(`{"message":"Too many requests, please wait before trying again."}`)} + account := newBedrockErrorTestAccount() + + out := runBedrockForwardWith(t, repo, account, upstream, bedrockForwardOptions{ctx: ctx, model: "claude-sonnet-4-6"}) + + require.NotNil(t, out.failover) + require.Contains(t, upstream.lastURL, "claude-sonnet-4-6", "上游按渠道映射后的模型请求") + require.Len(t, repo.modelRateLimitCalls, 1) + scope := repo.modelRateLimitCalls[0].scope + require.Equal(t, "claude-sonnet-4-5", scope, "冷却写在调度器按客户端模型读取的键上") + setAccountModelRateLimitSnapshot(account, scope, time.Now().Add(time.Minute), bedrockThrottlingReason, time.Now()) + require.False(t, account.IsSchedulableForModelWithContext(context.Background(), "claude-sonnet-4-5")) + }) + + t.Run("model scoped rule", func(t *testing.T) { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: http.StatusTooManyRequests, body: []byte(`{"message":"Too many tokens per day, please wait before trying again."}`)} + account := newBedrockErrorTestAccount(bedrockErrorRule(http.StatusTooManyRequests, "tokens per day", 240, TempUnschedScopeModel)) + + out := runBedrockForwardWith(t, repo, account, upstream, bedrockForwardOptions{ctx: ctx, model: "claude-sonnet-4-6"}) + + require.NotNil(t, out.failover) + require.Len(t, repo.modelRateLimitCalls, 1) + require.Equal(t, "claude-sonnet-4-5", repo.modelRateLimitCalls[0].scope) + }) +} + +func TestBedrockUpstreamErrors_ThrottlingCooldownDisabledWritesNothing(t *testing.T) { + repo := &bedrockErrorRepoStub{} + settingRepo := newMockSettingRepo() + settingRepo.data[SettingKeyRateLimit429CooldownSettings] = `{"enabled":false,"cooldown_seconds":12}` + rateLimiter := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + rateLimiter.SetSettingService(NewSettingService(settingRepo, &config.Config{})) + upstream := &bedrockErrorUpstreamStub{status: http.StatusTooManyRequests, body: []byte(`{"message":"Too many requests, please wait before trying again."}`)} + + out := runBedrockForwardWith(t, repo, newBedrockErrorTestAccount(), upstream, bedrockForwardOptions{rateLimiter: rateLimiter}) + + require.NotNil(t, out.failover) + require.Empty(t, repo.modelRateLimitCalls) + require.Empty(t, repo.rateLimitedAt) +} + +func TestBedrockUpstreamErrors_ContentFilterOnlyForRewrittenServerErrors(t *testing.T) { + for _, status := range []int{501, 529} { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: status, body: []byte(`{"message":"Output blocked by content filtering policy"}`)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.NotNil(t, out.failover, "status %d 按原有 5xx 语义换号", status) + require.Equal(t, status, out.failover.StatusCode) + } + for _, status := range []int{500, 502, 503, 504} { + repo := &bedrockErrorRepoStub{} + upstream := &bedrockErrorUpstreamStub{status: status, body: []byte(`{"message":"Input blocked by content filtering policy"}`)} + + out := runBedrockForward(t, repo, newBedrockErrorTestAccount(), upstream, false) + + require.Nil(t, out.failover, "status %d", status) + require.Equal(t, http.StatusBadRequest, out.recorder.Code, "status %d", status) + } +} diff --git a/backend/internal/service/ratelimit_fable_recovery_test.go b/backend/internal/service/ratelimit_fable_recovery_test.go new file mode 100644 index 0000000000..dab59c9222 --- /dev/null +++ b/backend/internal/service/ratelimit_fable_recovery_test.go @@ -0,0 +1,195 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "net/http" + "strconv" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// 上游 7d_oi 窗口耗尽会给账号写入 model_rate_limits["claude-fable-5"],冷却到窗口重置时间。 +// 如果期间用户用重置卡让上游额度提前归零,本地原本没有任何撤销路径:请求一直在本地 +// 被判为 model_rate_limited,直到旧的 rate_limit_reset_at 到期为止。 +// +// 下面锁定恢复规则:只有上游**明确**回报 7d_oi 用量回落到耗尽线以下、且已有记录来自 +// 窗口耗尽时,才按单 key 撤销;缺失数据、积分不足、窗口仍被拒、以及其它模型都不受影响。 + +type fableRecoveryRepo struct { + sessionWindowMockRepo + clearedScopes []string + clearErr error +} + +func (r *fableRecoveryRepo) ClearModelRateLimit(_ context.Context, _ int64, scope string) error { + r.clearedScopes = append(r.clearedScopes, scope) + return r.clearErr +} + +func newFableRecoveryAccount(reason string, extraLimits map[string]any) *Account { + limits := map[string]any{ + anthropicFableRateLimitKey: map[string]any{ + "rate_limited_at": time.Now().Add(-2 * time.Hour).UTC().Format(time.RFC3339), + "rate_limit_reset_at": time.Now().Add(3 * 24 * time.Hour).UTC().Format(time.RFC3339), + "reason": reason, + }, + } + for scope, payload := range extraLimits { + limits[scope] = payload + } + return &Account{ + ID: 42, + Platform: PlatformAnthropic, + Type: AccountTypeOAuth, + Extra: map[string]any{modelRateLimitsKey: limits}, + } +} + +func fableUsageHeaders(utilization string, rejected bool) http.Header { + headers := http.Header{} + headers.Set("anthropic-ratelimit-unified-5h-status", "allowed") + if rejected { + headers.Set("anthropic-ratelimit-unified-7d_oi-status", "rejected") + } + if utilization != "" { + headers.Set("anthropic-ratelimit-unified-7d_oi-utilization", utilization) + } + headers.Set("anthropic-ratelimit-unified-7d_oi-reset", strconv.FormatInt(time.Now().Add(7*24*time.Hour).Unix(), 10)) + return headers +} + +func TestPassiveUsageClearsExhaustedFableLimitAfterQuotaReset(t *testing.T) { + ctx := context.Background() + repo := &fableRecoveryRepo{} + svc := &RateLimitService{accountRepo: repo} + account := newFableRecoveryAccount(anthropicFableWindowReason, nil) + + require.True(t, account.isModelRateLimitedWithContext(ctx, "claude-fable-5-2"), + "前提:窗口耗尽后 Fable 请求被本地拦截") + + // 重置卡生效:上游回报该窗口 0%。 + svc.samplePassiveUsageFromHeaders(ctx, account, fableUsageHeaders("0", false)) + + require.Equal(t, []string{anthropicFableRateLimitKey}, repo.clearedScopes, + "必须只按 claude-fable-5 这一个 scope 撤销") + require.False(t, account.isModelRateLimitedWithContext(ctx, "claude-fable-5-2"), + "本实例的账号快照要同步解除,否则当前实例仍会继续跳过该账号") +} + +func TestPassiveUsageKeepsFableLimitWhenUtilizationMissing(t *testing.T) { + ctx := context.Background() + repo := &fableRecoveryRepo{} + svc := &RateLimitService{accountRepo: repo} + account := newFableRecoveryAccount(anthropicFableWindowReason, nil) + + // 缺失不等于 0:上游没给 7d_oi 用量时不得撤销。 + svc.samplePassiveUsageFromHeaders(ctx, account, fableUsageHeaders("", false)) + + require.Empty(t, repo.clearedScopes) + require.True(t, account.isModelRateLimitedWithContext(ctx, "claude-fable-5-2")) +} + +func TestPassiveUsageKeepsFableLimitWhileWindowStillRejected(t *testing.T) { + ctx := context.Background() + repo := &fableRecoveryRepo{} + svc := &RateLimitService{accountRepo: repo} + account := newFableRecoveryAccount(anthropicFableWindowReason, nil) + + // 窗口仍是 rejected 时,即使 utilization 因为口径差异低于 1.0 也不能撤销。 + svc.samplePassiveUsageFromHeaders(ctx, account, fableUsageHeaders("0.5", true)) + + require.Empty(t, repo.clearedScopes) + require.True(t, account.isModelRateLimitedWithContext(ctx, "claude-fable-5-2")) +} + +func TestPassiveUsageKeepsFableLimitWhenUtilizationStillHigh(t *testing.T) { + ctx := context.Background() + repo := &fableRecoveryRepo{} + svc := &RateLimitService{accountRepo: repo} + account := newFableRecoveryAccount(anthropicFableWindowReason, nil) + + svc.samplePassiveUsageFromHeaders(ctx, account, fableUsageHeaders("0.98", false)) + + require.Empty(t, repo.clearedScopes, "利用率仍接近耗尽线时不撤销") +} + +func TestPassiveUsageKeepsCreditsRequiredLimit(t *testing.T) { + ctx := context.Background() + repo := &fableRecoveryRepo{} + svc := &RateLimitService{accountRepo: repo} + account := newFableRecoveryAccount(anthropicFableCreditsRequiredReason, nil) + + // 积分不足(credits required)与窗口耗尽语义不同,不能被窗口用量顺手清掉。 + svc.samplePassiveUsageFromHeaders(ctx, account, fableUsageHeaders("0", false)) + + require.Empty(t, repo.clearedScopes) + require.True(t, account.isModelRateLimitedWithContext(ctx, "claude-fable-5-2")) +} + +func TestPassiveUsageKeepsOtherModelLimitsWhenRecoveringFable(t *testing.T) { + ctx := context.Background() + repo := &fableRecoveryRepo{} + svc := &RateLimitService{accountRepo: repo} + otherLimit := map[string]any{ + "rate_limited_at": time.Now().Add(-time.Hour).UTC().Format(time.RFC3339), + "rate_limit_reset_at": time.Now().Add(6 * time.Hour).UTC().Format(time.RFC3339), + "reason": anthropicFableWindowReason, + } + account := newFableRecoveryAccount(anthropicFableWindowReason, map[string]any{ + "claude-opus-4-1": otherLimit, + }) + + svc.samplePassiveUsageFromHeaders(ctx, account, fableUsageHeaders("0", false)) + + require.Equal(t, []string{anthropicFableRateLimitKey}, repo.clearedScopes) + require.False(t, account.isRateLimitActiveForKey(anthropicFableRateLimitKey)) + require.True(t, account.isRateLimitActiveForKey("claude-opus-4-1"), + "其它模型的限流必须原样保留") +} + +func TestPassiveUsageKeepsLimitWhenClearFails(t *testing.T) { + ctx := context.Background() + repo := &fableRecoveryRepo{clearErr: errors.New("db unavailable")} + svc := &RateLimitService{accountRepo: repo} + account := newFableRecoveryAccount(anthropicFableWindowReason, nil) + + svc.samplePassiveUsageFromHeaders(ctx, account, fableUsageHeaders("0", false)) + + require.Equal(t, []string{anthropicFableRateLimitKey}, repo.clearedScopes) + require.True(t, account.isModelRateLimitedWithContext(ctx, "claude-fable-5-2"), + "写库失败时不能只改内存快照,否则本实例放行而调度快照仍拦截") +} + +// 主动用量刷新(管理端「刷新额度」)是另一个观测点:上游 usage API 明确给出 +// 已回落的 7d_oi 用量时同样要撤销;API 没给这个窗口时保持原状。 +func TestSyncActiveToPassiveClearsExhaustedFableLimit(t *testing.T) { + ctx := context.Background() + repo := &fableRecoveryRepo{} + svc := &AccountUsageService{accountRepo: repo} + + t.Run("api reports recovery", func(t *testing.T) { + account := newFableRecoveryAccount(anthropicFableWindowReason, nil) + usage := &UsageInfo{SevenDayFable: &UsageProgress{Utilization: 3}} + + svc.syncActiveToPassive(ctx, account, usage) + + require.Equal(t, []string{anthropicFableRateLimitKey}, repo.clearedScopes) + require.False(t, account.isRateLimitActiveForKey(anthropicFableRateLimitKey)) + }) + + t.Run("api omits the fable window", func(t *testing.T) { + repo.clearedScopes = nil + account := newFableRecoveryAccount(anthropicFableWindowReason, nil) + usage := &UsageInfo{SevenDayFable: nil} + + svc.syncActiveToPassive(ctx, account, usage) + + require.Empty(t, repo.clearedScopes, "上游未下发该窗口时不能当成 0") + require.True(t, account.isRateLimitActiveForKey(anthropicFableRateLimitKey)) + }) +} diff --git a/backend/internal/service/ratelimit_rollover_weekly_usage_test.go b/backend/internal/service/ratelimit_rollover_weekly_usage_test.go new file mode 100644 index 0000000000..86bb9fa802 --- /dev/null +++ b/backend/internal/service/ratelimit_rollover_weekly_usage_test.go @@ -0,0 +1,123 @@ +package service + +import ( + "context" + "encoding/json" + "maps" + "net/http" + "strconv" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// applyExtraCalls applies UpdateExtra calls the way the JSONB merge does: +// a nil value is stored as JSON null. +func applyExtraCalls(extra map[string]any, calls []ueCall) map[string]any { + merged := maps.Clone(extra) + for _, call := range calls { + maps.Copy(merged, call.Updates) + } + return merged +} + +// A Fable-exhausted account stops receiving Fable requests, so its non-Fable +// responses carry 5h and 7d headers but no 7d_oi. A 5h rollover must keep the +// still-current 7d F reading instead of erasing it until the weekly reset. +func TestUpdateSessionWindow_RolloverKeepsCurrentWeeklyReadings(t *testing.T) { + now := time.Now() + weeklyReset := now.Add(72 * time.Hour).Unix() + expiredEnd := now.Add(-time.Minute) + extra := map[string]any{ + "session_window_utilization": 1.0, + "passive_usage_7d_utilization": 0.7, + "passive_usage_7d_reset": float64(weeklyReset), // as decoded from JSONB + "passive_usage_7d_oi_utilization": 1.0, + "passive_usage_7d_oi_reset": json.Number(strconv.FormatInt(weeklyReset, 10)), + "passive_usage_sampled_at": now.Add(-time.Hour).UTC().Format(time.RFC3339), + } + account := &Account{ID: 7, Platform: PlatformAnthropic, Type: AccountTypeSetupToken, SessionWindowEnd: &expiredEnd, Extra: extra} + + headers := http.Header{} + headers.Set("anthropic-ratelimit-unified-5h-status", "allowed") + headers.Set("anthropic-ratelimit-unified-5h-reset", strconv.FormatInt(now.Add(5*time.Hour).Unix(), 10)) + headers.Set("anthropic-ratelimit-unified-5h-utilization", "0.05") + headers.Set("anthropic-ratelimit-unified-7d-utilization", "0.71") + headers.Set("anthropic-ratelimit-unified-7d-reset", strconv.FormatInt(weeklyReset, 10)) + + repo := &sessionWindowMockRepo{} + newRateLimitServiceForTest(repo).UpdateSessionWindow(context.Background(), account, headers) + + require.Len(t, repo.updateExtraCalls, 2, "rollover clear, then the new sample") + require.Equal(t, map[string]any{"session_window_utilization": nil}, repo.updateExtraCalls[0].Updates) + + merged := applyExtraCalls(extra, repo.updateExtraCalls) + require.Equal(t, 0.05, merged["session_window_utilization"]) + require.Equal(t, 0.71, merged["passive_usage_7d_utilization"]) + require.Equal(t, 1.0, merged["passive_usage_7d_oi_utilization"], "7d F reading must survive a non-Fable rollover") + require.Equal(t, json.Number(strconv.FormatInt(weeklyReset, 10)), merged["passive_usage_7d_oi_reset"]) + require.NotNil(t, merged["passive_usage_sampled_at"]) + + fable := buildPassiveUsageWindow(merged, "passive_usage_7d_oi_utilization", "passive_usage_7d_oi_reset") + require.NotNil(t, fable) + require.Equal(t, 100.0, fable.Utilization) +} + +func TestRolloverPassiveUsageClears(t *testing.T) { + now := time.Now() + future := now.Add(24 * time.Hour).Unix() + past := now.Add(-time.Hour).Unix() + weekly := []string{"passive_usage_7d_utilization", "passive_usage_7d_reset"} + fable := []string{"passive_usage_7d_oi_utilization", "passive_usage_7d_oi_reset"} + + for _, tc := range []struct { + name string + extra map[string]any + cleared []string + kept []string + clearSample bool + }{ + { + name: "both current", + extra: map[string]any{"passive_usage_7d_reset": future, "passive_usage_7d_oi_reset": float64(future)}, + kept: append(weekly, fable...), + }, + { + name: "weekly expired, fable current", + extra: map[string]any{"passive_usage_7d_reset": past, "passive_usage_7d_oi_reset": strconv.FormatInt(future, 10)}, + cleared: weekly, + kept: fable, + }, + { + name: "reading without reset is stale", + extra: map[string]any{"passive_usage_7d_utilization": 0.4, "passive_usage_7d_oi_reset": nil}, + cleared: append(weekly, fable...), + clearSample: true, + }, + { + name: "no extra", + cleared: append(weekly, fable...), + clearSample: true, + }, + } { + t.Run(tc.name, func(t *testing.T) { + updates := rolloverPassiveUsageClears(tc.extra, now) + require.Contains(t, updates, "session_window_utilization") + require.Nil(t, updates["session_window_utilization"]) + for _, key := range tc.cleared { + value, present := updates[key] + require.True(t, present, key) + require.Nil(t, value, key) + } + for _, key := range tc.kept { + require.NotContains(t, updates, key) + } + if tc.clearSample { + require.Contains(t, updates, "passive_usage_sampled_at") + } else { + require.NotContains(t, updates, "passive_usage_sampled_at") + } + }) + } +} diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index 61c065ec0d..c3cacf7603 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -424,6 +424,11 @@ func (s *RateLimitService) HandleUpstreamError(ctx context.Context, account *Acc return false } } + if account.IsBedrock() { + if handled, disable := s.handleBedrockUpstreamError(ctx, account, statusCode, upstreamMsg, firstRequestedModel(requestedModel)); handled { + return disable + } + } switch statusCode { case 400: @@ -1598,8 +1603,49 @@ func (s *RateLimitService) persistAnthropicExhaustedWindowLimit(ctx context.Cont const ( anthropicFableWindowReason = "anthropic_7d_oi_window_exhausted" anthropicFableCreditsRequiredReason = "anthropic_fable_credits_required" + + // anthropicFableWindowRecoveredUtilization 是判定 7d_oi 窗口已恢复的用量上限。 + // 上游明确回报利用率低于该值(重置卡生效、窗口滚动)时撤销窗口耗尽写入的限流; + // 留出余量避免贴着 1.0 的采样来回抖动。 + anthropicFableWindowRecoveredUtilization = 0.95 ) +// recoverAnthropicFableWindowLimit 在上游明确回报 7d_oi 用量已回落到耗尽线以下时, +// 撤销此前由窗口耗尽写入的 claude-fable-5 模型级限流。 +// +// 三条约束: +// 1. 只有明确拿到利用率才判断;缺失一律不动,缺失不等于 0; +// 2. 只撤销 anthropicFableWindowReason 来源的限流——积分不足(credits required) +// 与管理端阈值来源的语义不同,不能被窗口用量顺手清掉; +// 3. 只清 claude-fable-5 这一个 scope,不影响其他模型与并发新写入的限流。 +func recoverAnthropicFableWindowLimit(ctx context.Context, repo AccountRepository, account *Account, utilization float64) bool { + if repo == nil || account == nil || account.ID <= 0 { + return false + } + if utilization < 0 || utilization >= anthropicFableWindowRecoveredUtilization { + return false + } + if !account.isRateLimitActiveForKey(anthropicFableRateLimitKey) { + return false + } + if account.modelRateLimitReason(anthropicFableRateLimitKey) != anthropicFableWindowReason { + return false + } + if err := repo.ClearModelRateLimit(ctx, account.ID, anthropicFableRateLimitKey); err != nil { + slog.Warn("anthropic_fable_window_recovery_clear_failed", + "account_id", account.ID, + "utilization", utilization, + "error", err) + return false + } + clearAccountModelRateLimitSnapshot(account, anthropicFableRateLimitKey) + slog.Info("anthropic_fable_window_recovered", + "account_id", account.ID, + "scope", anthropicFableRateLimitKey, + "utilization", utilization) + return true +} + // persistAnthropicFableCreditsRequired handles Anthropic's credits_required // response for Fable. Although the upstream status is 429, this response only // says that the organization cannot use Fable; marking the whole account rate @@ -2104,16 +2150,10 @@ func (s *RateLimitService) UpdateSessionWindow(ctx context.Context, account *Acc slog.Info("account_session_window_initialized", "account_id", account.ID, "window_start", start, "window_end", end, "status", status) } - // 窗口重置时清除旧的 utilization 和被动采样数据,避免残留上个窗口的数据 + // 5h 窗口重置时清除上个 5h 窗口的 utilization。周窗口有自己的重置时间, + // 只清除已经过期的周读数(见 rolloverPassiveUsageClears)。 if windowEnd != nil && needInitWindow { - _ = s.accountRepo.UpdateExtra(ctx, account.ID, map[string]any{ - "session_window_utilization": nil, - "passive_usage_7d_utilization": nil, - "passive_usage_7d_reset": nil, - "passive_usage_7d_oi_utilization": nil, - "passive_usage_7d_oi_reset": nil, - "passive_usage_sampled_at": nil, - }) + _ = s.accountRepo.UpdateExtra(ctx, account.ID, rolloverPassiveUsageClears(account.Extra, time.Now())) } if err := s.accountRepo.UpdateSessionWindow(ctx, account.ID, windowStart, windowEnd, status); err != nil { @@ -2131,6 +2171,36 @@ func (s *RateLimitService) UpdateSessionWindow(ctx context.Context, account *Acc } } +// passiveWeeklyUsageWindows lists the sampled weekly windows as utilization/reset Extra keys. +var passiveWeeklyUsageWindows = [...][2]string{ + {"passive_usage_7d_utilization", "passive_usage_7d_reset"}, + {"passive_usage_7d_oi_utilization", "passive_usage_7d_oi_reset"}, +} + +// rolloverPassiveUsageClears returns the Extra updates for a 5h window rollover. +// The 5h utilization always belongs to the previous window. A weekly reading +// is kept while its own reset is still ahead: only Fable responses carry 7d_oi, +// so a Fable-exhausted account that no longer receives Fable traffic would +// otherwise lose its 7d F reading at every rollover until the weekly reset. +// Readings with no reset, or a reset that has passed, are stale and cleared. +func rolloverPassiveUsageClears(extra map[string]any, now time.Time) map[string]any { + updates := map[string]any{"session_window_utilization": nil} + kept := false + for _, keys := range passiveWeeklyUsageWindows { + if reset := parseExtraFloat64(extra[keys[1]]); reset > 0 && time.Unix(int64(reset), 0).After(now) { + kept = true + continue + } + updates[keys[0]] = nil + updates[keys[1]] = nil + } + // The sample time still describes any weekly reading that was kept. + if !kept { + updates["passive_usage_sampled_at"] = nil + } + return updates +} + // samplePassiveUsageFromHeaders 从 Anthropic 响应头收集 5h/7d/7d_oi 的 // utilization 与 reset 被动采样数据,合并为一次 Extra 写入。无数据时不写。 func (s *RateLimitService) samplePassiveUsageFromHeaders(ctx context.Context, account *Account, headers http.Header) { @@ -2157,9 +2227,11 @@ func (s *RateLimitService) samplePassiveUsageFromHeaders(ctx context.Context, ac } } // 7d_oi (Fable 专属 7d 窗口) utilization(0-1 小数) + var fableUtil *float64 if utilStr := headers.Get("anthropic-ratelimit-unified-7d_oi-utilization"); utilStr != "" { if util, err := strconv.ParseFloat(utilStr, 64); err == nil { extraUpdates["passive_usage_7d_oi_utilization"] = util + fableUtil = &util } } // 7d_oi reset timestamp @@ -2177,6 +2249,13 @@ func (s *RateLimitService) samplePassiveUsageFromHeaders(ctx context.Context, ac slog.Warn("passive_usage_update_failed", "account_id", account.ID, "error", err) } } + + // 上游已明确回报 7d_oi 用量回落到耗尽线以下(额度重置或窗口滚动)时, + // 撤销此前窗口耗尽写入的模型级限流,避免重置卡生效后仍被本地拦到原 + // rate_limit_reset_at 才解封。窗口仍处于 rejected/exceeded 时不撤销。 + if fableUtil != nil && !isAnthropicWindowRejected(headers, "7d_oi") && !isAnthropicWindowExceeded(headers, "7d_oi") { + recoverAnthropicFableWindowLimit(ctx, s.accountRepo, account, *fableUtil) + } } // ClearRateLimit 清除账号的限流状态 diff --git a/backend/internal/service/ratelimit_service_clear_test.go b/backend/internal/service/ratelimit_service_clear_test.go index e8d312f9b9..c3f4538cbb 100644 --- a/backend/internal/service/ratelimit_service_clear_test.go +++ b/backend/internal/service/ratelimit_service_clear_test.go @@ -57,6 +57,10 @@ func (r *rateLimitClearRepoStub) ClearModelRateLimits(ctx context.Context, id in return r.clearModelRateLimitErr } +func (r *rateLimitClearRepoStub) ClearModelRateLimit(ctx context.Context, id int64, scope string) error { + return nil +} + func (r *rateLimitClearRepoStub) ClearTempUnschedulable(ctx context.Context, id int64) error { r.clearTempUnschedCalls++ return r.clearTempUnschedulableErr diff --git a/backend/internal/service/ratelimit_session_window_test.go b/backend/internal/service/ratelimit_session_window_test.go index bf7cc2bf0a..d3de55622b 100644 --- a/backend/internal/service/ratelimit_session_window_test.go +++ b/backend/internal/service/ratelimit_session_window_test.go @@ -54,6 +54,10 @@ func (m *sessionWindowMockRepo) ClearAntigravityQuotaScopes(_ context.Context, _ func (m *sessionWindowMockRepo) ClearModelRateLimits(_ context.Context, _ int64) error { return nil } + +func (m *sessionWindowMockRepo) ClearModelRateLimit(_ context.Context, _ int64, _ string) error { + return nil +} func (m *sessionWindowMockRepo) ClearTempUnschedulable(_ context.Context, _ int64) error { return nil } diff --git a/backend/internal/service/request_log_retention_test.go b/backend/internal/service/request_log_retention_test.go index 4cc8955f79..a41c5bd2c5 100644 --- a/backend/internal/service/request_log_retention_test.go +++ b/backend/internal/service/request_log_retention_test.go @@ -9,6 +9,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" + "github.com/Wei-Shaw/sub2api/internal/pkg/timezone" "github.com/stretchr/testify/require" ) @@ -40,8 +41,13 @@ func TestRequestLogRetention_RuntimePolicy(t *testing.T) { svc.maybeCleanupRetention(context.Background(), now) if tt.wantCleanup { require.Equal(t, 1, repo.cleanupUsageCalls) - require.Equal(t, now.AddDate(0, 0, -tt.wantDays), repo.cleanupUsageCutoff) - require.Equal(t, now.AddDate(0, 0, -max(365, tt.wantDays)), repo.cleanupDedupCutoff) + wantUsageCutoff := GroupUsageTodayStart(now.AddDate(0, 0, -tt.wantDays)) + wantDedupCutoff := now.AddDate(0, 0, -max(365, tt.wantDays)) + if wantDedupCutoff.After(wantUsageCutoff) { + wantDedupCutoff = wantUsageCutoff + } + require.Equal(t, wantUsageCutoff, repo.cleanupUsageCutoff) + require.Equal(t, wantDedupCutoff, repo.cleanupDedupCutoff) } else { require.Zero(t, repo.cleanupUsageCalls) require.Zero(t, repo.cleanupDedupCalls) @@ -53,7 +59,7 @@ func TestRequestLogRetention_RuntimePolicy(t *testing.T) { settings.values[SettingKeyOpsRuntimeLogConfig] = `{"request_retention_days":180}` next := now.Add(dashboardAggregationRetentionInterval) svc.maybeCleanupRetention(context.Background(), next) - require.Equal(t, next.AddDate(0, 0, -180), repo.cleanupUsageCutoff) + require.Equal(t, GroupUsageTodayStart(next.AddDate(0, 0, -180)), repo.cleanupUsageCutoff) }) } } @@ -107,3 +113,70 @@ func TestRuntimeLogConfig_RequestRetentionCompatibility(t *testing.T) { require.NoError(t, err) require.Equal(t, 90, *reset.RequestRetentionDays) } + +func TestRequestLogRetention_CutoffAlignsToConfiguredDayStart(t *testing.T) { + previous := timezone.Name() + require.NoError(t, timezone.Init("Asia/Shanghai")) + t.Cleanup(func() { require.NoError(t, timezone.Init(previous)) }) + + for _, tt := range []struct { + name string + dedupDays int + wantDedup time.Time + }{ + // 2026-09-15 20:00 +08 往前 90 天是 2026-06-17 20:00 +08,对齐到 2026-06-17 00:00 +08。 + {"dedup longer than usage", 365, time.Date(2025, 9, 15, 12, 0, 0, 0, time.UTC)}, + {"dedup equal to usage keeps whole days", 90, time.Date(2026, 6, 16, 16, 0, 0, 0, time.UTC)}, + } { + t.Run(tt.name, func(t *testing.T) { + repo := &dashboardAggregationRepoTestStub{} + svc := NewDashboardAggregationService(repo, nil, &config.Config{DashboardAgg: config.DashboardAggregationConfig{ + Enabled: true, + Retention: config.DashboardAggregationRetentionConfig{UsageLogsDays: 90, UsageBillingDedupDays: tt.dedupDays, HourlyDays: 180, DailyDays: 730}, + }}) + now := time.Date(2026, 9, 15, 12, 0, 0, 0, time.UTC) + svc.maybeCleanupRetention(context.Background(), now) + + require.Equal(t, time.Date(2026, 6, 16, 16, 0, 0, 0, time.UTC), repo.cleanupUsageCutoff) + require.Equal(t, tt.wantDedup, repo.cleanupDedupCutoff) + }) + } +} + +// 夏令时在零点跳变的日期没有 00:00:日界取该日期实际开始的时刻,而不是前一天的 23:00。 +func TestGroupUsageDayBoundariesSkipMidnightDSTGap(t *testing.T) { + previous := timezone.Name() + require.NoError(t, timezone.Init("America/Santiago")) + t.Cleanup(func() { require.NoError(t, timezone.Init(previous)) }) + loc := timezone.Location() + + noon := time.Date(2026, 9, 6, 12, 0, 0, 0, loc) + start := GroupUsageTodayStart(noon) + require.Equal(t, "2026-09-06", GroupUsageDate(start)) + require.Equal(t, "2026-09-05", GroupUsageDate(start.Add(-time.Nanosecond))) + + parsed, err := ParseGroupUsageDate("2026-09-06") + require.NoError(t, err) + require.True(t, parsed.Equal(start), "parsed=%s start=%s", parsed, start) + + nextNoon := time.Date(2026, 9, 7, 12, 0, 0, 0, loc) + require.True(t, GroupUsageYesterdayStart(nextNoon).Equal(start)) + + // 普通日期仍是本地零点。 + regular, err := ParseGroupUsageDate("2026-09-08") + require.NoError(t, err) + require.True(t, regular.Equal(time.Date(2026, 9, 8, 0, 0, 0, 0, loc))) +} + +// 零点出现两次的日期(Asia/Gaza 2020-10-24 在 01:00 回拨到 00:00):日界取第一次出现的 00:00。 +func TestGroupUsageDayBoundariesUseFirstOfRepeatedMidnight(t *testing.T) { + previous := timezone.Name() + require.NoError(t, timezone.Init("Asia/Gaza")) + t.Cleanup(func() { require.NoError(t, timezone.Init(previous)) }) + + start, err := ParseGroupUsageDate("2020-10-24") + require.NoError(t, err) + require.Equal(t, "2020-10-24", GroupUsageDate(start)) + require.Equal(t, "2020-10-23", GroupUsageDate(start.Add(-time.Nanosecond))) + require.True(t, GroupUsageTodayStart(start.Add(90*time.Minute)).Equal(start)) +} diff --git a/backend/internal/service/rpm_override_group_repro_test.go b/backend/internal/service/rpm_override_group_repro_test.go new file mode 100644 index 0000000000..42e805250a --- /dev/null +++ b/backend/internal/service/rpm_override_group_repro_test.go @@ -0,0 +1,58 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/require" +) + +// 复现:snapshot 里的 override 属于分组 10,但请求跑到分组 11 时, +// 当前实现仍然使用分组 10 的 override,导致分组 11 的 rpm_limit 失效。 +func TestBillingCacheService_CheckRPM_OverrideFromAnotherGroupMustNotApply(t *testing.T) { + zero := 0 // 分组 10 的 override:0 = 免检 + cache := &userRPMCacheStub{ + userGroupCounts: []int{1, 2, 3, 4, 5, 6}, // 分组 11 的 RPM 计数 + } + repo := &rpmOverrideRepoStub{} // 分组 11 没有 override + svc := newBillingServiceForRPM(t, cache, repo) + + user := &User{ + ID: 1, + UserGroupRPMOverride: &zero, + UserGroupRPMOverrideGroupID: 10, + } + group := &Group{ID: 11, RPMLimit: 5} + + for i := 0; i < 5; i++ { + require.NoError(t, svc.checkRPM(context.Background(), user, group)) + } + require.ErrorIs(t, svc.checkRPM(context.Background(), user, group), ErrGroupRPMExceeded, + "分组 11 的 rpm_limit 应生效,不能使用分组 10 的 override") + require.EqualValues(t, 6, atomic.LoadInt32(&repo.calls), + "snapshot 只确认了分组 10,分组 11 应回源查询") +} + +// override 属于当前分组时必须直接生效,且不应回源查询(保留 snapshot 缓存优化)。 +func TestBillingCacheService_CheckRPM_SnapshotOverrideAppliesForItsOwnGroup(t *testing.T) { + override := 2 + cache := &userRPMCacheStub{userGroupCounts: []int{1, 2, 3}} + repo := &rpmOverrideRepoStub{err: errors.New("must not be queried")} + svc := newBillingServiceForRPM(t, cache, repo) + + user := &User{ + ID: 1, + UserGroupRPMOverride: &override, + UserGroupRPMOverrideGroupID: 10, + } + group := &Group{ID: 10, RPMLimit: 100} + + require.NoError(t, svc.checkRPM(context.Background(), user, group)) + require.NoError(t, svc.checkRPM(context.Background(), user, group)) + require.ErrorIs(t, svc.checkRPM(context.Background(), user, group), ErrGroupRPMExceeded) + require.Zero(t, atomic.LoadInt32(&repo.calls), "分组 10 的 override 已确认,不应回源") +} diff --git a/backend/internal/service/scheduler_snapshot_batch_query_test.go b/backend/internal/service/scheduler_snapshot_batch_query_test.go index b957891d36..f40384db19 100644 --- a/backend/internal/service/scheduler_snapshot_batch_query_test.go +++ b/backend/internal/service/scheduler_snapshot_batch_query_test.go @@ -56,8 +56,12 @@ func (r *batchAccountQueryRepo) ListSchedulableUngroupedByPlatforms(_ context.Co return r.run(batchAccountQueryKey{platform: platforms[0], mixed: true}) } -func (r *batchAccountQueryRepo) ListModelAvailabilityCandidates(context.Context, *int64, []string, bool) ([]Account, error) { - panic("unexpected ListModelAvailabilityCandidates call") +func (r *batchAccountQueryRepo) ListModelAvailabilityCandidates(_ context.Context, groupID *int64, platforms []string, _ bool) ([]Account, error) { + key := batchAccountQueryKey{platform: platforms[0], mixed: len(platforms) > 1} + if groupID != nil { + key.groupID = *groupID + } + return r.run(key) } func (r *batchAccountQueryRepo) ListSchedulableByPlatform(_ context.Context, platform string) ([]Account, error) { @@ -725,7 +729,7 @@ type batchQueryBenchmarkRepo struct { accounts []Account } -func (r *batchQueryBenchmarkRepo) ListSchedulableByGroupIDAndPlatform(context.Context, int64, string) ([]Account, error) { +func (r *batchQueryBenchmarkRepo) ListModelAvailabilityCandidates(context.Context, *int64, []string, bool) ([]Account, error) { return r.accounts, nil } diff --git a/backend/internal/service/scheduler_snapshot_cancellation_test.go b/backend/internal/service/scheduler_snapshot_cancellation_test.go index 3f46cb14aa..7205624e1b 100644 --- a/backend/internal/service/scheduler_snapshot_cancellation_test.go +++ b/backend/internal/service/scheduler_snapshot_cancellation_test.go @@ -36,7 +36,7 @@ type schedulerCancellationAccountRepo struct { getByIDCalls int } -func (r *schedulerCancellationAccountRepo) ListSchedulableUngroupedByPlatform(ctx context.Context, _ string) ([]Account, error) { +func (r *schedulerCancellationAccountRepo) ListModelAvailabilityCandidates(ctx context.Context, _ *int64, _ []string, _ bool) ([]Account, error) { r.listCalls++ return nil, ctx.Err() } diff --git a/backend/internal/service/scheduler_snapshot_fallback_coalesce_test.go b/backend/internal/service/scheduler_snapshot_fallback_coalesce_test.go index 8049a93204..b5f5e4825a 100644 --- a/backend/internal/service/scheduler_snapshot_fallback_coalesce_test.go +++ b/backend/internal/service/scheduler_snapshot_fallback_coalesce_test.go @@ -8,6 +8,7 @@ import ( "sync/atomic" "testing" "testing/synctest" + "time" "github.com/Wei-Shaw/sub2api/internal/config" "github.com/stretchr/testify/require" @@ -38,7 +39,7 @@ func (c *fallbackCoalesceCache) SetSnapshot(_ context.Context, _ SchedulerBucket return nil } -// fallbackCoalesceRepo 的分组查询停在 release 关闭之前,并统计调用次数。 +// fallbackCoalesceRepo 的配置池查询停在 release 关闭之前,并统计调用次数。 type fallbackCoalesceRepo struct { AccountRepository release chan struct{} @@ -46,7 +47,7 @@ type fallbackCoalesceRepo struct { accounts []Account } -func (r *fallbackCoalesceRepo) ListSchedulableByGroupIDAndPlatform(ctx context.Context, _ int64, _ string) ([]Account, error) { +func (r *fallbackCoalesceRepo) ListModelAvailabilityCandidates(ctx context.Context, _ *int64, _ []string, _ bool) ([]Account, error) { r.calls.Add(1) select { case <-r.release: @@ -171,7 +172,10 @@ func (c *valuesReaderCache) GetSnapshot(context.Context, SchedulerBucket) ([]*Ac } func TestSchedulerSnapshotListUsesValuesReaderWithoutCopy(t *testing.T) { - cache := &valuesReaderCache{values: []Account{{ID: 7301, Platform: PlatformOpenAI}, {ID: 7302, Platform: PlatformOpenAI}}} + cache := &valuesReaderCache{values: []Account{ + {ID: 7301, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true}, + {ID: 7302, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true}, + }} svc := newFallbackCoalesceService(cache, nil) groupID := int64(73) @@ -182,6 +186,48 @@ func TestSchedulerSnapshotListUsesValuesReaderWithoutCopy(t *testing.T) { require.Zero(t, cache.snapshotCalls.Load()) } +// 快照缓存的是配置池(#8729):值切片路径同样要在读取时排除限时封禁中的账号,到期的账号直接回到候选。 +func TestSchedulerSnapshotValuesReaderFiltersTimeBlockedAccounts(t *testing.T) { + future := time.Now().Add(time.Hour) + past := time.Now().Add(-time.Minute) + cache := &valuesReaderCache{values: []Account{ + {ID: 7311, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true, RateLimitResetAt: &future}, + {ID: 7312, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true, RateLimitResetAt: &past}, + {ID: 7313, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true, TempUnschedulableUntil: &future}, + {ID: 7314, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true, OverloadUntil: &past}, + }} + svc := newFallbackCoalesceService(cache, nil) + groupID := int64(74) + + accounts, _, err := svc.ListSchedulableAccounts(context.Background(), &groupID, PlatformOpenAI, false) + require.NoError(t, err) + require.Equal(t, []int64{7312, 7314}, []int64{accounts[0].ID, accounts[1].ID}) + require.Len(t, accounts, 2) +} + +// 合并回源时回写快照保留完整配置池,各调用方拿到的切片只含当前可调度的账号。 +func TestSchedulerFallbackPublishesPoolAndReturnsSchedulable(t *testing.T) { + future := time.Now().Add(time.Hour) + release := make(chan struct{}) + close(release) + cache := &fallbackCoalesceCache{} + repo := &fallbackCoalesceRepo{ + release: release, + accounts: []Account{ + {ID: 7401, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true}, + {ID: 7402, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true, RateLimitResetAt: &future}, + }, + } + svc := newFallbackCoalesceService(cache, repo) + groupID := int64(75) + + accounts, _, err := svc.ListSchedulableAccounts(context.Background(), &groupID, PlatformOpenAI, false) + require.NoError(t, err) + require.Len(t, accounts, 1) + require.Equal(t, int64(7401), accounts[0].ID) + require.Len(t, cache.snapshot, 2, "the published snapshot keeps the configured pool") +} + func TestFilterAccountsBySchedulingThresholdCompactsInPlace(t *testing.T) { svc := &GatewayService{} accounts := []Account{{ID: 1}, {ID: 2}, {ID: 3}} diff --git a/backend/internal/service/scheduler_snapshot_full_rebuild_lifecycle_test.go b/backend/internal/service/scheduler_snapshot_full_rebuild_lifecycle_test.go index e4489b81c7..229d29d88a 100644 --- a/backend/internal/service/scheduler_snapshot_full_rebuild_lifecycle_test.go +++ b/backend/internal/service/scheduler_snapshot_full_rebuild_lifecycle_test.go @@ -214,8 +214,12 @@ func (r *fullRebuildAccountRepo) ListSchedulableUngroupedByPlatforms(_ context.C return r.record(0, firstPlatform(platforms)) } -func (r *fullRebuildAccountRepo) ListModelAvailabilityCandidates(context.Context, *int64, []string, bool) ([]Account, error) { - panic("unexpected ListModelAvailabilityCandidates call") +func (r *fullRebuildAccountRepo) ListModelAvailabilityCandidates(_ context.Context, groupID *int64, platforms []string, _ bool) ([]Account, error) { + var id int64 + if groupID != nil { + id = *groupID + } + return r.record(id, firstPlatform(platforms)) } func (r *fullRebuildAccountRepo) ListSchedulableByPlatform(_ context.Context, platform string) ([]Account, error) { diff --git a/backend/internal/service/scheduler_snapshot_group_lifecycle_test.go b/backend/internal/service/scheduler_snapshot_group_lifecycle_test.go index 7eda02f737..bba40e41af 100644 --- a/backend/internal/service/scheduler_snapshot_group_lifecycle_test.go +++ b/backend/internal/service/scheduler_snapshot_group_lifecycle_test.go @@ -296,11 +296,7 @@ func (r *groupLifecycleTestAccountRepo) load(ctx context.Context, platform strin 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) { +func (r *groupLifecycleTestAccountRepo) ListModelAvailabilityCandidates(ctx context.Context, _ *int64, platforms []string, _ bool) ([]Account, error) { platform := "mixed" if len(platforms) > 0 { platform = platforms[0] diff --git a/backend/internal/service/scheduler_snapshot_outbox_cleanup_test.go b/backend/internal/service/scheduler_snapshot_outbox_cleanup_test.go index 2a476ff077..e4ae7cbb5f 100644 --- a/backend/internal/service/scheduler_snapshot_outbox_cleanup_test.go +++ b/backend/internal/service/scheduler_snapshot_outbox_cleanup_test.go @@ -108,7 +108,7 @@ type outboxCleanupAccountRepo struct { AccountRepository } -func (r *outboxCleanupAccountRepo) ListSchedulableUngroupedByPlatform(context.Context, string) ([]Account, error) { +func (r *outboxCleanupAccountRepo) ListModelAvailabilityCandidates(context.Context, *int64, []string, bool) ([]Account, error) { return nil, nil } diff --git a/backend/internal/service/scheduler_snapshot_retirement_test.go b/backend/internal/service/scheduler_snapshot_retirement_test.go index 7b5a8368d3..5ccc49d524 100644 --- a/backend/internal/service/scheduler_snapshot_retirement_test.go +++ b/backend/internal/service/scheduler_snapshot_retirement_test.go @@ -243,7 +243,8 @@ func TestSchedulerFallbackReturnsDBAccountsWhenBucketRetired(t *testing.T) { cache := newRetirementRaceCache() require.NoError(t, cache.RetireBucket(context.Background(), bucket)) repo := &mockAccountRepoForPlatform{ - accounts: []Account{{ID: 6301, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true}}, + accounts: []Account{{ID: 6301, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: true, + AccountGroups: []AccountGroup{{GroupID: bucket.GroupID}}}}, } svc := NewSchedulerSnapshotService(cache, nil, repo, nil, &config.Config{ RunMode: config.RunModeStandard, diff --git a/backend/internal/service/scheduler_snapshot_service.go b/backend/internal/service/scheduler_snapshot_service.go index f4173d47c3..9c9538eaae 100644 --- a/backend/internal/service/scheduler_snapshot_service.go +++ b/backend/internal/service/scheduler_snapshot_service.go @@ -245,21 +245,27 @@ func (s *SchedulerSnapshotService) ListSchedulableAccounts(ctx context.Context, return accounts, useMixed, nil } -// readSnapshotAccounts 读取 bucket 快照;缓存实现能直接返回值切片时直接使用该切片。 +// readSnapshotAccounts 读取 bucket 快照,只返回当前可调度的账号;缓存实现能直接返回值切片时直接使用该切片。 +// 快照缓存的是配置的账号池,限流、过载、临时不可调度等限时封禁在每次读取时判定,到期无需写入或 outbox 事件。 func (s *SchedulerSnapshotService) readSnapshotAccounts(ctx context.Context, bucket SchedulerBucket) ([]Account, bool, error) { if reader, ok := s.cache.(schedulerSnapshotValuesReader); ok { - return reader.GetSnapshotValues(ctx, bucket) + accounts, hit, err := reader.GetSnapshotValues(ctx, bucket) + if err != nil || !hit { + return nil, false, err + } + // GetSnapshotValues 返回的切片由本次调用独占,可以原地压缩。 + return compactSchedulableAccounts(accounts), true, nil } cached, hit, err := s.cache.GetSnapshot(ctx, bucket) if err != nil || !hit { return nil, false, err } - return derefAccounts(cached), true, nil + return derefSchedulableAccounts(cached), true, nil } // loadFallbackAccounts 回源数据库读取 bucket 的账号,取得发布令牌时尽力回写快照。 // 同一 bucket 的并发回源合并为一次:合并回源与回写不随单个调用方取消,各调用方按自身 ctx 等待结果, -// 并各自得到一份独占的切片;账号的 map、切片底层数组与指针指向的值在调用方之间共享,不得原地修改。 +// 并各自得到一份只含当前可调度账号的独占切片;账号的 map、切片底层数组与指针指向的值在调用方之间共享,不得原地修改。 func (s *SchedulerSnapshotService) loadFallbackAccounts(ctx context.Context, bucket SchedulerBucket, useMixed bool) ([]Account, error) { loadCtx := context.WithoutCancel(ctx) results := s.fallbackLoads.DoChan(bucket.String(), func() (result any, err error) { @@ -280,8 +286,12 @@ func (s *SchedulerSnapshotService) loadFallbackAccounts(ctx context.Context, buc if shared == nil { return nil, nil } - accounts := make([]Account, len(shared)) - copy(accounts, shared) + accounts := make([]Account, 0, len(shared)) + for i := range shared { + if shared[i].IsSchedulable() { + accounts = append(accounts, shared[i]) + } + } return accounts, nil case <-ctx.Done(): return nil, ctx.Err() @@ -329,6 +339,7 @@ func (s *SchedulerSnapshotService) loadAndPublishFallback(ctx context.Context, b } } + // 回写与共享结果保留完整的配置池;限时封禁在各调用方读取时按 IsSchedulable 判定(见 loadFallbackAccounts)。 return accounts, nil } @@ -1532,42 +1543,28 @@ func (s *SchedulerSnapshotService) loadAccountsFromDB(ctx context.Context, bucke if s.accountRepo == nil { return nil, ErrSchedulerCacheNotReady } - groupID := bucket.GroupID - if s.isRunModeSimple() { - groupID = 0 + var groupID *int64 + if !s.isRunModeSimple() && bucket.GroupID > 0 { + groupID = &bucket.GroupID } - + platforms := []string{bucket.Platform} if useMixed { - platforms := []string{bucket.Platform, PlatformAntigravity} - var accounts []Account - var err error - if groupID > 0 { - accounts, err = s.accountRepo.ListSchedulableByGroupIDAndPlatforms(ctx, groupID, platforms) - } else if s.isRunModeSimple() { - accounts, err = s.accountRepo.ListSchedulableByPlatforms(ctx, platforms) - } else { - accounts, err = s.accountRepo.ListSchedulableUngroupedByPlatforms(ctx, platforms) - } - if err != nil { - return nil, err - } - filtered := make([]Account, 0, len(accounts)) - for _, acc := range accounts { - if acc.Platform == PlatformAntigravity && !acc.IsMixedSchedulingEnabled() { - continue - } - filtered = append(filtered, acc) - } - return filtered, nil + platforms = append(platforms, PlatformAntigravity) } - - if groupID > 0 { - return s.accountRepo.ListSchedulableByGroupIDAndPlatform(ctx, groupID, bucket.Platform) + // Cache the configured pool, as model availability does. Time-based blocks + // must be checked on each read so expiry needs no write or outbox event. + accounts, err := s.accountRepo.ListModelAvailabilityCandidates(ctx, groupID, platforms, s.isRunModeSimple()) + if err != nil || !useMixed { + return accounts, err } - if s.isRunModeSimple() { - return s.accountRepo.ListSchedulableByPlatform(ctx, bucket.Platform) + filtered := make([]Account, 0, len(accounts)) + for _, acc := range accounts { + if acc.Platform == PlatformAntigravity && !acc.IsMixedSchedulingEnabled() { + continue + } + filtered = append(filtered, acc) } - return s.accountRepo.ListSchedulableUngroupedByPlatform(ctx, bucket.Platform) + return filtered, nil } func (s *SchedulerSnapshotService) loadAccountsForRebuild( @@ -1723,13 +1720,25 @@ func dedupeBuckets(in []SchedulerBucket) []SchedulerBucket { return out } -func derefAccounts(accounts []*Account) []Account { +// compactSchedulableAccounts 原地保留当前可调度的账号;accounts 必须由调用方独占。 +func compactSchedulableAccounts(accounts []Account) []Account { + out := accounts[:0] + for i := range accounts { + if accounts[i].IsSchedulable() { + out = append(out, accounts[i]) + } + } + clear(accounts[len(out):]) + return out +} + +func derefSchedulableAccounts(accounts []*Account) []Account { if len(accounts) == 0 { return []Account{} } out := make([]Account, 0, len(accounts)) for _, account := range accounts { - if account == nil { + if account == nil || !account.IsSchedulable() { continue } out = append(out, *account) diff --git a/backend/internal/service/scheduler_snapshot_transient_expiry_test.go b/backend/internal/service/scheduler_snapshot_transient_expiry_test.go new file mode 100644 index 0000000000..888fd013db --- /dev/null +++ b/backend/internal/service/scheduler_snapshot_transient_expiry_test.go @@ -0,0 +1,133 @@ +package service + +import ( + "context" + "testing" + "testing/synctest" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type transientExpirySnapshotCache struct { + SchedulerCache + accounts []*Account + hit bool +} + +func (c *transientExpirySnapshotCache) GetSnapshot(context.Context, SchedulerBucket) ([]*Account, bool, error) { + return c.accounts, c.hit, nil +} + +func (c *transientExpirySnapshotCache) CaptureBucketWriteToken(_ context.Context, bucket SchedulerBucket) (SchedulerBucketWriteToken, error) { + return SchedulerBucketWriteToken{Bucket: bucket, Epoch: 1}, nil +} + +func (c *transientExpirySnapshotCache) SetSnapshot(_ context.Context, _ SchedulerBucket, _ SchedulerBucketWriteToken, accounts []Account) error { + c.accounts = nil + for _, account := range accounts { + copy := account + c.accounts = append(c.accounts, ©) + } + c.hit = true + return nil +} + +type transientExpiryAccountRepo struct { + AccountRepository + accounts []Account + calls int +} + +func (r *transientExpiryAccountRepo) ListModelAvailabilityCandidates(context.Context, *int64, []string, bool) ([]Account, error) { + r.calls++ + var accounts []Account + for _, account := range r.accounts { + if account.IsActive() && account.Schedulable { + accounts = append(accounts, account) + } + } + return accounts, nil +} + +// Match the current repository contract: the source query excludes accounts +// while any transient cooldown is in the future. +func (r *transientExpiryAccountRepo) ListSchedulableByPlatform(context.Context, string) ([]Account, error) { + r.calls++ + var accounts []Account + for _, account := range r.accounts { + if account.IsSchedulable() { + accounts = append(accounts, account) + } + } + return accounts, nil +} + +func TestSchedulerSnapshotRecoversTransientCooldownWithoutIntervalRebuild(t *testing.T) { + for _, field := range []string{"rate_limit_reset_at", "overload_until", "temp_unschedulable_until"} { + t.Run(field, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + until := time.Now().Add(30 * time.Second) + past := time.Now().Add(-time.Second) + ready := Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true} + cooling := ready + cooling.ID = 2 + switch field { + case "rate_limit_reset_at": + cooling.RateLimitResetAt = &until + case "overload_until": + cooling.OverloadUntil = &until + case "temp_unschedulable_until": + cooling.TempUnschedulableUntil = &until + } + disabled := ready + disabled.ID, disabled.Status = 3, StatusDisabled + manual := ready + manual.ID, manual.Schedulable = 4, false + expired := ready + expired.ID, expired.AutoPauseOnExpired, expired.ExpiresAt = 5, true, &past + expiring := ready + expiring.ID, expiring.AutoPauseOnExpired, expiring.ExpiresAt = 6, true, &until + repo := &transientExpiryAccountRepo{accounts: []Account{ready, cooling, disabled, manual, expired, expiring}} + cache := &transientExpirySnapshotCache{} + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Gateway.Scheduling.DbFallbackEnabled = true + svc := NewSchedulerSnapshotService(cache, nil, repo, nil, cfg) + eligible := func(accounts []Account) []int64 { + var ids []int64 + for _, account := range accounts { + if account.IsSchedulable() { + ids = append(ids, account.ID) + } + } + return ids + } + + accounts, _, err := svc.ListSchedulableAccounts(context.Background(), nil, PlatformOpenAI, false) + require.NoError(t, err) + require.Equal(t, []int64{1, 6}, eligible(accounts)) + require.Len(t, accounts, 2, "the DB fallback returns only currently eligible accounts") + require.True(t, cache.hit) + require.Len(t, cache.accounts, 4, "the stored pool retains cooling and expired configured members") + require.Equal(t, 1, repo.calls) + + time.Sleep(31 * time.Second) + require.True(t, cooling.IsSchedulable(), "the account's own cooldown has expired") + accounts, _, err = svc.ListSchedulableAccounts(context.Background(), nil, PlatformOpenAI, false) + require.NoError(t, err) + t.Logf("after expiry: eligible=%v cached_members=%d source_calls=%d", eligible(accounts), len(cache.accounts), repo.calls) + assert.ElementsMatch(t, []int64{1, 2}, eligible(accounts), "an expired cooldown must not wait for the interval rebuild") + require.Len(t, accounts, 2, "the cache hit excludes disabled, manually paused and expired accounts") + require.Equal(t, 1, repo.calls, "expiry must not require a database read") + + // Positive control: a fresh source read immediately restores the account. + cache.hit = false + accounts, _, err = svc.ListSchedulableAccounts(context.Background(), nil, PlatformOpenAI, false) + require.NoError(t, err) + require.ElementsMatch(t, []int64{1, 2}, eligible(accounts)) + }) + }) + } +} diff --git a/backend/internal/web/embed_on.go b/backend/internal/web/embed_on.go index 03e5e5f50e..d401e7fde9 100644 --- a/backend/internal/web/embed_on.go +++ b/backend/internal/web/embed_on.go @@ -149,18 +149,23 @@ func (s *FrontendServer) serveIndexHTML(c *gin.Context) { // Check cache first cached := s.cache.Get() if cached != nil { - // Check If-None-Match for 304 response - if match := c.GetHeader("If-None-Match"); match == cached.ETag { - c.Status(http.StatusNotModified) - c.Abort() - return + // A matching ETag is only enough for 304 when the response has no + // per-request nonce. Otherwise the browser would reuse HTML carrying a + // stale nonce that no longer matches the CSP header of this request. + if nonce == "" { + if match := c.GetHeader("If-None-Match"); match == cached.ETag { + applyHTMLNoCacheHeaders(c.Writer.Header()) + c.Status(http.StatusNotModified) + c.Abort() + return + } } // Replace nonce placeholder with actual nonce before serving content := replaceNoncePlaceholder(cached.Content, nonce) c.Header("ETag", cached.ETag) - c.Header("Cache-Control", "no-cache") // Must revalidate + applyHTMLNoCacheHeaders(c.Writer.Header()) c.Data(http.StatusOK, "text/html; charset=utf-8", content) c.Abort() return @@ -173,6 +178,7 @@ func (s *FrontendServer) serveIndexHTML(c *gin.Context) { settings, err := s.settings.GetPublicSettingsForInjection(ctx) if err != nil { // Fallback: serve without injection + applyHTMLNoCacheHeaders(c.Writer.Header()) c.Data(http.StatusOK, "text/html; charset=utf-8", s.baseHTML) c.Abort() return @@ -181,6 +187,7 @@ func (s *FrontendServer) serveIndexHTML(c *gin.Context) { settingsJSON, err := json.Marshal(settings) if err != nil { // Fallback: serve without injection + applyHTMLNoCacheHeaders(c.Writer.Header()) c.Data(http.StatusOK, "text/html; charset=utf-8", s.baseHTML) c.Abort() return @@ -196,7 +203,7 @@ func (s *FrontendServer) serveIndexHTML(c *gin.Context) { if cached != nil { c.Header("ETag", cached.ETag) } - c.Header("Cache-Control", "no-cache") + applyHTMLNoCacheHeaders(c.Writer.Header()) c.Data(http.StatusOK, "text/html; charset=utf-8", content) c.Abort() } diff --git a/backend/internal/web/embed_test.go b/backend/internal/web/embed_test.go index 75dac764fb..97b9c948d8 100644 --- a/backend/internal/web/embed_test.go +++ b/backend/internal/web/embed_test.go @@ -352,7 +352,7 @@ func TestFrontendServer_ServeIndexHTML(t *testing.T) { assert.True(t, strings.HasSuffix(etag, `"`)) }) - t.Run("returns_304_for_matching_etag", func(t *testing.T) { + t.Run("returns_304_only_when_no_nonce_is_present", func(t *testing.T) { provider := &mockSettingsProvider{ settings: map[string]string{"test": "value"}, } @@ -360,12 +360,8 @@ func TestFrontendServer_ServeIndexHTML(t *testing.T) { server, err := NewFrontendServer(provider) require.NoError(t, err) - // Use a real router for proper 304 handling + // No nonce in context means the cached body has no per-request part. router := gin.New() - router.Use(func(c *gin.Context) { - c.Set(middleware.CSPNonceKey, "test-nonce") - c.Next() - }) router.Use(server.Middleware()) // First request to populate cache and get ETag @@ -383,9 +379,47 @@ func TestFrontendServer_ServeIndexHTML(t *testing.T) { assert.Equal(t, http.StatusNotModified, w2.Code) assert.Empty(t, w2.Body.String()) + assertNoStoreHTMLHeaders(t, w2.Header()) }) - t.Run("sets_cache_control_header", func(t *testing.T) { + t.Run("serves_fresh_html_when_cached_nonce_is_stale", func(t *testing.T) { + provider := &mockSettingsProvider{ + settings: map[string]string{"test": "value"}, + } + + server, err := NewFrontendServer(provider) + require.NoError(t, err) + + router := gin.New() + router.Use(func(c *gin.Context) { + c.Set(middleware.CSPNonceKey, c.GetHeader("X-Test-Nonce")) + c.Next() + }) + router.Use(server.Middleware()) + + w1 := httptest.NewRecorder() + req1 := httptest.NewRequest(http.MethodGet, "/", nil) + req1.Header.Set("X-Test-Nonce", "first-nonce") + router.ServeHTTP(w1, req1) + etag := w1.Header().Get("ETag") + require.NotEmpty(t, etag) + assert.Contains(t, w1.Body.String(), `nonce="first-nonce"`) + + // The document embeds the request nonce, so a matching ETag must not + // turn this into a 304 that reuses the previous nonce. + w2 := httptest.NewRecorder() + req2 := httptest.NewRequest(http.MethodGet, "/", nil) + req2.Header.Set("X-Test-Nonce", "second-nonce") + req2.Header.Set("If-None-Match", etag) + router.ServeHTTP(w2, req2) + + assert.Equal(t, http.StatusOK, w2.Code) + assert.Contains(t, w2.Body.String(), `nonce="second-nonce"`) + assert.NotContains(t, w2.Body.String(), `nonce="first-nonce"`) + assertNoStoreHTMLHeaders(t, w2.Header()) + }) + + t.Run("sets_no_store_cache_headers", func(t *testing.T) { provider := &mockSettingsProvider{ settings: map[string]string{"test": "value"}, } @@ -400,7 +434,7 @@ func TestFrontendServer_ServeIndexHTML(t *testing.T) { server.serveIndexHTML(c) - assert.Equal(t, "no-cache", w.Header().Get("Cache-Control")) + assertNoStoreHTMLHeaders(t, w.Header()) }) t.Run("fallback_on_settings_error", func(t *testing.T) { @@ -427,6 +461,78 @@ func TestFrontendServer_ServeIndexHTML(t *testing.T) { }) } +func assertNoStoreHTMLHeaders(t *testing.T, header http.Header) { + t.Helper() + assert.Equal(t, "no-cache, no-store, must-revalidate", header.Get("Cache-Control")) + assert.Equal(t, "no-cache", header.Get("Pragma")) + assert.Equal(t, "0", header.Get("Expires")) + assert.Equal(t, "no-store", header.Get("CDN-Cache-Control")) + assert.Equal(t, "no-store", header.Get("Surrogate-Control")) +} + +func TestFrontendServer_NoStoreHeadersOnEveryHTMLPath(t *testing.T) { + t.Run("cache_hit", func(t *testing.T) { + provider := &mockSettingsProvider{ + settings: map[string]string{"test": "value"}, + } + + server, err := NewFrontendServer(provider) + require.NoError(t, err) + + w1 := httptest.NewRecorder() + c1, _ := gin.CreateTestContext(w1) + c1.Request = httptest.NewRequest(http.MethodGet, "/", nil) + c1.Set(middleware.CSPNonceKey, "nonce1") + server.serveIndexHTML(c1) + require.Equal(t, http.StatusOK, w1.Code) + + w2 := httptest.NewRecorder() + c2, _ := gin.CreateTestContext(w2) + c2.Request = httptest.NewRequest(http.MethodGet, "/", nil) + c2.Set(middleware.CSPNonceKey, "nonce2") + server.serveIndexHTML(c2) + + assert.Equal(t, http.StatusOK, w2.Code) + assertNoStoreHTMLHeaders(t, w2.Header()) + }) + + t.Run("settings_error_fallback", func(t *testing.T) { + provider := &mockSettingsProvider{ + err: context.DeadlineExceeded, + } + + server, err := NewFrontendServer(provider) + require.NoError(t, err) + + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodGet, "/", nil) + c.Set(middleware.CSPNonceKey, "nonce123") + server.serveIndexHTML(c) + + assert.Equal(t, http.StatusOK, w.Code) + assertNoStoreHTMLHeaders(t, w.Header()) + }) + + t.Run("settings_marshal_error_fallback", func(t *testing.T) { + provider := &mockSettingsProvider{ + settings: make(chan struct{}), + } + + server, err := NewFrontendServer(provider) + require.NoError(t, err) + + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodGet, "/", nil) + c.Set(middleware.CSPNonceKey, "nonce123") + server.serveIndexHTML(c) + + assert.Equal(t, http.StatusOK, w.Code) + assertNoStoreHTMLHeaders(t, w.Header()) + }) +} + func TestFrontendServer_InvalidateCache(t *testing.T) { t.Run("invalidates_cache", func(t *testing.T) { provider := &mockSettingsProvider{ diff --git a/backend/internal/web/html_cache_headers.go b/backend/internal/web/html_cache_headers.go new file mode 100644 index 0000000000..ade6c35987 --- /dev/null +++ b/backend/internal/web/html_cache_headers.go @@ -0,0 +1,18 @@ +//go:build embed || unit + +package web + +import "net/http" + +// applyHTMLNoCacheHeaders marks settings-injected HTML as uncacheable at every +// layer: browser memory/disk cache, back/forward cache (browsers skip bfcache +// for no-store responses) and CDN edge caches. Settings are injected into the +// document, so a stale copy would paint outdated branding until the next +// revalidation. +func applyHTMLNoCacheHeaders(header http.Header) { + header.Set("Cache-Control", "no-cache, no-store, must-revalidate") + header.Set("Pragma", "no-cache") + header.Set("Expires", "0") + header.Set("CDN-Cache-Control", "no-store") + header.Set("Surrogate-Control", "no-store") +} diff --git a/backend/internal/web/html_cache_headers_test.go b/backend/internal/web/html_cache_headers_test.go new file mode 100644 index 0000000000..e762b3ddb9 --- /dev/null +++ b/backend/internal/web/html_cache_headers_test.go @@ -0,0 +1,40 @@ +//go:build unit + +package web + +import ( + "net/http" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestApplyHTMLNoCacheHeaders(t *testing.T) { + header := http.Header{} + + applyHTMLNoCacheHeaders(header) + + assert.Equal(t, "no-cache, no-store, must-revalidate", header.Get("Cache-Control")) + assert.Equal(t, "no-cache", header.Get("Pragma")) + assert.Equal(t, "0", header.Get("Expires")) + assert.Equal(t, "no-store", header.Get("CDN-Cache-Control")) + assert.Equal(t, "no-store", header.Get("Surrogate-Control")) +} + +func TestApplyHTMLNoCacheHeadersReplacesExistingValues(t *testing.T) { + header := http.Header{ + "Cache-Control": {"public, max-age=3600"}, + "Pragma": {"cache"}, + "Expires": {"Thu, 01 Jan 2099 00:00:00 GMT"}, + "CDN-Cache-Control": {"max-age=3600"}, + "Surrogate-Control": {"max-age=3600"}, + } + + applyHTMLNoCacheHeaders(header) + + assert.Equal(t, "no-cache, no-store, must-revalidate", header.Get("Cache-Control")) + assert.Equal(t, "no-cache", header.Get("Pragma")) + assert.Equal(t, "0", header.Get("Expires")) + assert.Equal(t, "no-store", header.Get("CDN-Cache-Control")) + assert.Equal(t, "no-store", header.Get("Surrogate-Control")) +} diff --git a/backend/migrations/251_group_usage_rollup_nonblocking_build.sql b/backend/migrations/251_group_usage_rollup_nonblocking_build.sql new file mode 100644 index 0000000000..279c95b201 --- /dev/null +++ b/backend/migrations/251_group_usage_rollup_nonblocking_build.sql @@ -0,0 +1,159 @@ +-- /admin/groups 分组日汇总的过期下界与重建登记。 +-- expired_before 之前的 usage_logs 已超出保留期,不属于任何可读日桶,其变更不触发失效。 +-- 重建期间登记 building_until;落在该日期之前的源记录变更记入 build_dirty_from, +-- 发布时水位不越过 build_dirty_from,因此重建计算阶段无需排斥 usage_logs 写入。 + +SET LOCAL lock_timeout = '5s'; + +ALTER TABLE usage_group_rollup_state + ADD COLUMN IF NOT EXISTS expired_before TIMESTAMPTZ NOT NULL DEFAULT TIMESTAMPTZ '1970-01-01 00:00:00+00', + ADD COLUMN IF NOT EXISTS building_until DATE, + ADD COLUMN IF NOT EXISTS build_dirty_from DATE; + +COMMENT ON COLUMN usage_group_rollup_state.expired_before IS '早于该时刻的 usage_logs 已超出保留期,不计入分组日汇总,也不触发失效。'; +COMMENT ON COLUMN usage_group_rollup_state.building_until IS '进行中重建的目标日期(排他上界);没有重建时为 NULL。'; +COMMENT ON COLUMN usage_group_rollup_state.build_dirty_from IS '重建期间源记录发生变化的最早日期;发布水位不越过该日期。'; + +-- 按受影响日期后退发布水位,并在重建进行中记录脏日期;水位与脏日期都已不晚于该日期时不写状态行。 +-- 调用方必须已对状态行持有 FOR KEY SHARE 或更强的行锁:重建的登记与发布持有 FOR UPDATE, +-- 由此保证每次源记录变更要么先于登记提交、被重建快照看到,要么看到登记并记入脏日期。 +CREATE OR REPLACE FUNCTION apply_group_usage_rollup_invalidation(affected_date DATE) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +BEGIN + UPDATE usage_group_rollup_state + SET closed_before = LEAST(closed_before, affected_date), + build_dirty_from = CASE + WHEN building_until > affected_date THEN LEAST(build_dirty_from, affected_date) + ELSE build_dirty_from + END, + updated_at = NOW() + WHERE id = 1 + AND ( + closed_before > affected_date + OR ( + building_until > affected_date + AND (build_dirty_from IS NULL OR build_dirty_from > affected_date) + ) + ); +END; +$$; + +-- 供应用侧调用:使 affected_at 在 bucket_timezone 中的日期及之后的日桶失效; +-- 早于 expired_before 的部分不属于任何可读日桶,失效从 expired_before 起算。 +CREATE OR REPLACE FUNCTION invalidate_group_usage_rollups_at(affected_at TIMESTAMPTZ, bucket_timezone TEXT) +RETURNS VOID +LANGUAGE plpgsql +AS $$ +DECLARE + state_expired_before TIMESTAMPTZ; +BEGIN + SELECT expired_before + INTO state_expired_before + FROM usage_group_rollup_state + WHERE id = 1 + FOR KEY SHARE; + + IF NOT FOUND OR affected_at IS NULL THEN + RETURN; + END IF; + + PERFORM apply_group_usage_rollup_invalidation( + (GREATEST(affected_at, state_expired_before) AT TIME ZONE bucket_timezone)::date + ); +END; +$$; + +-- DELETE/UPDATE 行级触发器。FOR KEY SHARE 与 usage_logs 写入及其他失效互相兼容,只与重建的登记、发布串行。 +CREATE OR REPLACE FUNCTION invalidate_group_usage_rollup_state() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + configured_timezone TEXT := current_setting('TimeZone'); + old_date DATE; + new_date DATE; + affected_date DATE; + state_closed_before DATE; + state_building_until DATE; + state_build_dirty_from DATE; + state_expired_before TIMESTAMPTZ; +BEGIN + SELECT closed_before, building_until, build_dirty_from, expired_before + INTO state_closed_before, state_building_until, state_build_dirty_from, state_expired_before + FROM usage_group_rollup_state + WHERE id = 1 + FOR KEY SHARE; + + IF FOUND THEN + IF OLD.group_id IS NOT NULL AND OLD.created_at >= state_expired_before THEN + old_date := (OLD.created_at AT TIME ZONE configured_timezone)::date; + END IF; + IF TG_OP = 'UPDATE' THEN + IF NEW.group_id IS NOT NULL AND NEW.created_at >= state_expired_before THEN + new_date := (NEW.created_at AT TIME ZONE configured_timezone)::date; + END IF; + END IF; + + affected_date := LEAST(old_date, new_date); + IF state_closed_before > affected_date + OR ( + state_building_until > affected_date + AND (state_build_dirty_from IS NULL OR state_build_dirty_from > affected_date) + ) THEN + PERFORM apply_group_usage_rollup_invalidation(affected_date); + END IF; + END IF; + + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; +END; +$$; + +-- INSERT 语句级触发器:每个批量 INSERT 只读一次状态行;当天写入既不后退水位也不记脏。 +CREATE OR REPLACE FUNCTION invalidate_group_usage_rollup_state_after_insert() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + configured_timezone TEXT := current_setting('TimeZone'); + affected_date DATE; + state_closed_before DATE; + state_building_until DATE; + state_build_dirty_from DATE; + state_expired_before TIMESTAMPTZ; +BEGIN + IF NOT EXISTS (SELECT 1 FROM inserted_usage_logs WHERE group_id IS NOT NULL) THEN + RETURN NULL; + END IF; + + SELECT closed_before, building_until, build_dirty_from, expired_before + INTO state_closed_before, state_building_until, state_build_dirty_from, state_expired_before + FROM usage_group_rollup_state + WHERE id = 1 + FOR KEY SHARE; + + IF NOT FOUND THEN + RETURN NULL; + END IF; + + SELECT MIN((created_at AT TIME ZONE configured_timezone)::date) + INTO affected_date + FROM inserted_usage_logs + WHERE group_id IS NOT NULL + AND created_at >= state_expired_before; + + IF state_closed_before > affected_date + OR ( + state_building_until > affected_date + AND (state_build_dirty_from IS NULL OR state_build_dirty_from > affected_date) + ) THEN + PERFORM apply_group_usage_rollup_invalidation(affected_date); + END IF; + + RETURN NULL; +END; +$$; diff --git a/backend/migrations/group_usage_rollup_migration_test.go b/backend/migrations/group_usage_rollup_migration_test.go index f2e9a5d0ad..006a0b35c3 100644 --- a/backend/migrations/group_usage_rollup_migration_test.go +++ b/backend/migrations/group_usage_rollup_migration_test.go @@ -50,3 +50,22 @@ func TestMigration223TracksConfiguredTimezone(t *testing.T) { require.Contains(t, sql, "CREATE OR REPLACE FUNCTION invalidate_group_usage_rollup_state") require.Contains(t, sql, "CREATE OR REPLACE FUNCTION invalidate_group_usage_rollup_state_after_insert") } + +func TestMigration251AddsExpiredFloorAndNonBlockingBuildMarks(t *testing.T) { + content, err := FS.ReadFile("251_group_usage_rollup_nonblocking_build.sql") + require.NoError(t, err) + + sql := string(content) + require.Contains(t, sql, "SET LOCAL lock_timeout") + require.Contains(t, sql, "ADD COLUMN IF NOT EXISTS expired_before TIMESTAMPTZ NOT NULL") + require.Contains(t, sql, "ADD COLUMN IF NOT EXISTS building_until DATE") + require.Contains(t, sql, "ADD COLUMN IF NOT EXISTS build_dirty_from DATE") + require.Contains(t, sql, "CREATE OR REPLACE FUNCTION apply_group_usage_rollup_invalidation") + require.Contains(t, sql, "CREATE OR REPLACE FUNCTION invalidate_group_usage_rollups_at") + require.Contains(t, sql, "CREATE OR REPLACE FUNCTION invalidate_group_usage_rollup_state()") + require.Contains(t, sql, "CREATE OR REPLACE FUNCTION invalidate_group_usage_rollup_state_after_insert()") + require.Contains(t, sql, "created_at >= state_expired_before") + // 源记录变更只对状态行持 KEY SHARE,与 usage_logs 写入互不阻塞。 + require.Contains(t, sql, "FOR KEY SHARE") + require.NotContains(t, sql, "FOR UPDATE;") +} diff --git a/deploy/Dockerfile b/deploy/Dockerfile index d5c580b466..e0e8fbf030 100644 --- a/deploy/Dockerfile +++ b/deploy/Dockerfile @@ -7,7 +7,7 @@ # ============================================================================= ARG NODE_IMAGE=node:24-alpine -ARG GOLANG_IMAGE=golang:1.27.2-alpine +ARG GOLANG_IMAGE=golang:1.27.4-alpine ARG ALPINE_IMAGE=alpine:3.20 ARG GOPROXY=https://goproxy.cn,direct ARG GOSUMDB=sum.golang.google.cn diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index 2c6859ec0d..257dbc751f 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -882,8 +882,8 @@ idempotency: # 并发等待配置 # ============================================================================= concurrency: - # SSE ping interval during concurrency wait (seconds) - # 并发等待期间的 SSE ping 间隔(秒) + # SSE ping interval during concurrency wait (seconds); 0 disables pings to avoid committing HTTP status early + # 并发等待期间的 SSE ping 间隔(秒);0 禁用 ping,避免提前写入 HTTP 状态码 ping_interval: 10 # ============================================================================= @@ -1155,6 +1155,11 @@ pricing: # Gemini 显式缓存存储单价(每 token 每小时,USD)优先取这里的 cache_storage_cost_per_token_per_hour 字段, # 未配置时使用内置官方价(先按已发布型号,再按 Pro / Flash 系列兜底);两者都没有的模型拒绝创建缓存。 # 目录中不存在的模型条目还须同时提供 input_cost_per_token / output_cost_per_token。 + # Explicit nonnegative DeepSeek input/output/cache-read token prices here, + # including zero, are final rates and do not receive the official peak multiplier. + # Omitted or null fields still use the official defaults and peak/off-peak rules. + # DeepSeek 的输入/输出/缓存读单价若在此显式设为非负值(含 0),按该价计费, + # 不叠加官方高峰倍率;省略或 null 的字段仍按官方默认价与峰谷规则计费。 # override_file: "./data/model_pricing_overrides.json" # Update interval in hours # 更新间隔(小时) diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue index f6a7533838..8ccc433706 100644 --- a/frontend/src/components/account/AccountUsageCell.vue +++ b/frontend/src/components/account/AccountUsageCell.vue @@ -625,7 +625,7 @@ color="purple" /> -
+
diff --git a/frontend/src/components/account/CNProviderQuotaCell.vue b/frontend/src/components/account/CNProviderQuotaCell.vue index d814173abb..9cddb9f088 100644 --- a/frontend/src/components/account/CNProviderQuotaCell.vue +++ b/frontend/src/components/account/CNProviderQuotaCell.vue @@ -4,7 +4,7 @@ data-test="cn-provider-quota" class="min-w-[220px] space-y-1" > -
cnQuotaCellVisible(props.account)) const loading = ref(false) const error = ref(null) -const data = ref(null) +const probeData = ref(null) +let probeGeneration = 0 // 后端周期任务/手动探测写入的 extra 快照键(_ 前缀,与后端 // cnQuotaExtraUpdates 对齐)。页面加载即有数据,无需等待探测。 @@ -118,6 +119,18 @@ const snapshotData = computed(() => { return { success: true, tiers } as CNProviderQuotaProbeResult }) +const data = computed(() => probeData.value ?? snapshotData.value) + +// A list refresh replaces account.extra even when its quota snapshot is +// unchanged. Keep a manual probe until the quota values or snapshot version +// actually change, rather than reverting it on unrelated account updates. +watch( + [snapshotData, () => readExtraString(`${props.account.platform}_usage_updated_at`)], + (next, previous) => { + if (JSON.stringify(next) !== JSON.stringify(previous)) probeData.value = null + } +) + // 快照是否过期(无更新时间或超过 staleness 窗口)→ 挂载时需要自动探测。 const snapshotIsStale = computed(() => { const updatedAt = readExtraString(`${props.account.platform}_usage_updated_at`) @@ -130,7 +143,6 @@ const snapshotIsStale = computed(() => { // 避免静默失败导致单元格空白无提示)。 onMounted(() => { if (!visible.value) return - data.value = snapshotData.value if (!snapshotIsStale.value) return // 模块级去抖:列表页每行一个实例,翻页/筛选/刷新会重复挂载;同一账号 // 短时间内已自动探测过则跳过,避免对上游形成探测风暴。 @@ -168,27 +180,31 @@ const windowLabel = (window: string) => { const handleProbe = async () => { if (loading.value) return + const generation = ++probeGeneration + const accountID = props.account.id loading.value = true error.value = null try { - const result = await adminAPI.cnProviders.queryQuota(props.account.id) + const result = await adminAPI.cnProviders.queryQuota(accountID) + if (generation !== probeGeneration) return // 失败时保留已渲染的快照条形图(仅显示错误行),成功才覆盖。 if (result.success) { - data.value = result + probeData.value = result } else { error.value = result.error || t('common.error') } } catch (e) { - error.value = extractErrorMessage(e) + if (generation === probeGeneration) error.value = extractErrorMessage(e) } finally { - loading.value = false + if (generation === probeGeneration) loading.value = false } } watch( - () => props.account.id, + [() => props.account.id, () => props.account.platform], () => { - data.value = null + probeGeneration++ + probeData.value = null error.value = null loading.value = false } diff --git a/frontend/src/components/account/ModelWhitelistSelector.vue b/frontend/src/components/account/ModelWhitelistSelector.vue index b1645a49fa..16788af018 100644 --- a/frontend/src/components/account/ModelWhitelistSelector.vue +++ b/frontend/src/components/account/ModelWhitelistSelector.vue @@ -278,6 +278,10 @@ const copyModelId = async (model: string) => { const addCustom = () => { const model = customModel.value.trim() if (!model) return + if (model.includes('*')) { + appStore.showInfo(t('admin.accounts.modelWildcardNotSupported')) + return + } if (props.modelValue.includes(model)) { appStore.showInfo(t('admin.accounts.modelExists')) return diff --git a/frontend/src/components/account/__tests__/CNProviderQuotaCell.spec.ts b/frontend/src/components/account/__tests__/CNProviderQuotaCell.spec.ts index e0384fe72c..55c250dbd1 100644 --- a/frontend/src/components/account/__tests__/CNProviderQuotaCell.spec.ts +++ b/frontend/src/components/account/__tests__/CNProviderQuotaCell.spec.ts @@ -1,5 +1,6 @@ import { flushPromises, mount } from '@vue/test-utils' import { beforeEach, describe, expect, it, vi } from 'vitest' +import { reactive } from 'vue' import CNProviderQuotaCell from '../CNProviderQuotaCell.vue' import UsageProgressBar from '../UsageProgressBar.vue' import type { Account } from '@/types' @@ -102,4 +103,85 @@ describe('CNProviderQuotaCell', () => { await flushPromises() expect(queryQuota).toHaveBeenCalledWith(account.id) }) + + it('renders replacement quota values and windows for the same account without probing', async () => { + const wrapper = mount(CNProviderQuotaCell, { props: { account } }) + await wrapper.setProps({ account: { + ...account, + extra: { + ...account.extra, + zhipu_5h_used_percent: 52, + zhipu_weekly_used_percent: null, + zhipu_monthly_used_percent: 81, + zhipu_monthly_reset_at: '2026-12-01T00:00:00Z' + } + } }) + const bars = wrapper.findAllComponents(UsageProgressBar) + expect(bars.map(bar => bar.props('utilization'))).toEqual([52, 81]) + expect(bars[1].props('label')).toBe('admin.accounts.cnProviders.windowMonthly') + expect(bars[1].props('resetsAt')).toBe('2026-12-01T00:00:00Z') + expect(queryQuota).not.toHaveBeenCalled() + }) + + it('reacts to quota changes inside the existing extra object', async () => { + const row = reactive({ ...account, extra: { ...account.extra } }) + const wrapper = mount(CNProviderQuotaCell, { props: { account: row } }) + row.extra.zhipu_5h_used_percent = 63 + await flushPromises() + expect(wrapper.findAllComponents(UsageProgressBar)[0].props('utilization')).toBe(63) + expect(queryQuota).not.toHaveBeenCalled() + }) + + it('removes bars when a refreshed snapshot clears all quota windows', async () => { + const wrapper = mount(CNProviderQuotaCell, { props: { account } }) + await wrapper.setProps({ account: { + ...account, + extra: { ...account.extra, zhipu_5h_used_percent: null, zhipu_weekly_used_percent: null } + } }) + expect(wrapper.findAllComponents(UsageProgressBar)).toHaveLength(0) + expect(queryQuota).not.toHaveBeenCalled() + }) + + it('keeps a manual result through unrelated refreshes, then adopts a changed snapshot', async () => { + queryQuota.mockResolvedValue({ success: true, tiers: [{ window: '5h', used_percent: 44 }] }) + const wrapper = mount(CNProviderQuotaCell, { props: { account } }) + await wrapper.get('[data-test="cn-provider-quota-probe"]').trigger('click') + await flushPromises() + await wrapper.setProps({ account: { + ...account, extra: { ...account.extra, unrelated_field: true } + } }) + expect(wrapper.findAllComponents(UsageProgressBar).map(bar => bar.props('utilization'))).toEqual([44]) + await wrapper.setProps({ account: { + ...account, extra: { ...account.extra, zhipu_5h_used_percent: 66 } + } }) + expect(wrapper.findAllComponents(UsageProgressBar).map(bar => bar.props('utilization'))).toEqual([66, 27]) + expect(queryQuota).toHaveBeenCalledTimes(1) + }) + + it('adopts a new snapshot version even if its quota values equal the old snapshot', async () => { + queryQuota.mockResolvedValue({ success: true, tiers: [{ window: '5h', used_percent: 44 }] }) + const wrapper = mount(CNProviderQuotaCell, { props: { account } }) + await wrapper.get('[data-test="cn-provider-quota-probe"]').trigger('click') + await flushPromises() + await wrapper.setProps({ account: { + ...account, + extra: { ...account.extra, zhipu_usage_updated_at: new Date(Date.now() + 1000).toISOString() } + } }) + expect(wrapper.findAllComponents(UsageProgressBar).map(bar => bar.props('utilization'))).toEqual([0, 27]) + }) + + it('keeps the new account snapshot when the previous account probe finishes late', async () => { + let resolveProbe!: (value: unknown) => void + queryQuota.mockReturnValue(new Promise(resolve => { resolveProbe = resolve })) + const wrapper = mount(CNProviderQuotaCell, { props: { account } }) + await wrapper.get('[data-test="cn-provider-quota-probe"]').trigger('click') + await wrapper.setProps({ account: { + ...account, id: 8, extra: { ...account.extra, zhipu_5h_used_percent: 91 } + } }) + expect(wrapper.findAllComponents(UsageProgressBar)[0].props('utilization')).toBe(91) + resolveProbe({ success: true, tiers: [{ window: '5h', used_percent: 44 }] }) + await flushPromises() + expect(wrapper.findAllComponents(UsageProgressBar)[0].props('utilization')).toBe(91) + expect(wrapper.get('[data-test="cn-provider-quota-probe"]').attributes('disabled')).toBeUndefined() + }) }) diff --git a/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts b/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts index 83f843df73..277fdd4780 100644 --- a/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts +++ b/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts @@ -165,6 +165,33 @@ describe('ModelWhitelistSelector', () => { wrapper.unmount() }) + it.each(['claude-*', '*', 'gpt-*-mini'])( + 'rejects wildcard whitelist entry %s without clearing the input', async (model) => { + const wrapper = mountSelector({ modelValue: ['gpt-5'] }) + const input = wrapper.get('input[placeholder="admin.accounts.enterCustomModelName"]') + await input.setValue(model) + await wrapper.findAll('button').find(button => button.text() === 'admin.accounts.addModel')!.trigger('click') + + expect(wrapper.emitted('update:modelValue')).toBeUndefined() + expect(showInfo).toHaveBeenCalledWith('admin.accounts.modelWildcardNotSupported') + expect((input.element as HTMLInputElement).value).toBe(model) + } + ) + + it('rejects wildcard entries submitted with Enter and accepts a corrected exact model', async () => { + const wrapper = mountSelector() + const input = wrapper.get('input[placeholder="admin.accounts.enterCustomModelName"]') + await input.setValue(' claude-* ') + await input.trigger('keydown.enter') + expect(wrapper.emitted('update:modelValue')).toBeUndefined() + expect(showInfo).toHaveBeenCalledWith('admin.accounts.modelWildcardNotSupported') + + await input.setValue(' claude-sonnet-4-5 ') + await input.trigger('keydown.enter') + expect(wrapper.emitted('update:modelValue')).toEqual([[['claude-sonnet-4-5']]]) + expect((input.element as HTMLInputElement).value).toBe('') + }) + it('rejects a custom whitelist model that is already mapped to a different target', async () => { const wrapper = mountSelector({ modelMappings: [{ from: 'gpt-latest', to: 'deepseek-chat' }] }) await wrapper.get('input[placeholder="admin.accounts.enterCustomModelName"]').setValue(' gpt-latest ') diff --git a/frontend/src/components/charts/EndpointDistributionChart.vue b/frontend/src/components/charts/EndpointDistributionChart.vue index a813df19b5..2cfc7f3110 100644 --- a/frontend/src/components/charts/EndpointDistributionChart.vue +++ b/frontend/src/components/charts/EndpointDistributionChart.vue @@ -83,6 +83,7 @@ {{ t('admin.dashboard.requests') }} {{ t('admin.dashboard.tokens') }} {{ t('admin.dashboard.actual') }} + {{ t('admin.dashboard.accountCost') }} {{ t('admin.dashboard.standard') }} @@ -109,15 +110,19 @@ ${{ formatCost(item.actual_cost) }} + + ${{ formatCost(item.account_cost ?? 0) }} + ${{ formatCost(item.cost) }} - + @@ -161,6 +166,7 @@ const props = withDefaults( showMetricToggle?: boolean showSourceToggle?: boolean enableBreakdown?: boolean + showAccountCost?: boolean startDate?: string endDate?: string filters?: Record @@ -174,7 +180,8 @@ const props = withDefaults( source: 'inbound', showMetricToggle: false, showSourceToggle: false, - enableBreakdown: true + enableBreakdown: true, + showAccountCost: true } ) diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts index 78f7c550dd..e851568a40 100644 --- a/frontend/src/i18n/locales/en/admin/accounts.ts +++ b/frontend/src/i18n/locales/en/admin/accounts.ts @@ -857,6 +857,7 @@ export default { enterCustomModelName: 'Enter custom model name', addModel: 'Add', modelExists: 'Model already exists', + modelWildcardNotSupported: 'Wildcards are not supported in the model whitelist. Enter an exact model name.', modelMappingConflict: 'A mapping already exists for {from} → {to}. Modify or remove it under Model Mapping before adding this whitelist model', modelCount: '{count} models', poolMode: 'Pool Mode', diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts index e55b725e96..4c93b07972 100644 --- a/frontend/src/i18n/locales/zh/admin/accounts.ts +++ b/frontend/src/i18n/locales/zh/admin/accounts.ts @@ -968,6 +968,7 @@ export default { enterCustomModelName: '输入自定义模型名称', addModel: '填入', modelExists: '该模型已存在', + modelWildcardNotSupported: '模型白名单不支持通配符,请输入完整的模型名称。', modelMappingConflict: '该模型已配置映射 {from} → {to},请在模型映射中修改或删除后再添加白名单模型', modelCount: '{count} 个模型', poolMode: '池模式', diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 1d3fd163d4..f98a4b83a8 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -2089,8 +2089,9 @@ export interface EndpointStat { endpoint: string requests: number total_tokens: number - cost: number - actual_cost: number + cost: number // 标准计费 + actual_cost: number // 实际扣除 + account_cost?: number // 账号成本(仅管理员接口返回) } export interface GroupStat { diff --git a/frontend/src/views/admin/ChannelsView.vue b/frontend/src/views/admin/ChannelsView.vue index 5ee185131e..3633f27267 100644 --- a/frontend/src/views/admin/ChannelsView.vue +++ b/frontend/src/views/admin/ChannelsView.vue @@ -1196,18 +1196,10 @@ function formToAPI(): { group_ids: number[], model_pricing: ChannelModelPricing[ delete featuresConfig.codex_image_generation_bridge } - const bedrockCCCompat: Record = {} - for (const section of form.platforms) { - if (!section.enabled) continue - if (section.platform === 'anthropic') { - bedrockCCCompat[section.platform] = !!section.bedrock_cc_compat - } - } - if (Object.keys(bedrockCCCompat).length > 0) { - featuresConfig.bedrock_cc_compat = bedrockCCCompat - } else { - delete featuresConfig.bedrock_cc_compat - } + // The backend reads a channel-level boolean; send false explicitly to clear it on update. + featuresConfig.bedrock_cc_compat = form.platforms.some( + section => section.enabled && section.platform === 'anthropic' && section.bedrock_cc_compat + ) return { group_ids: uniqueGroupIds, model_pricing, model_mapping, features_config: featuresConfig } } diff --git a/frontend/src/views/admin/__tests__/ChannelsView.bedrockCompat.spec.ts b/frontend/src/views/admin/__tests__/ChannelsView.bedrockCompat.spec.ts new file mode 100644 index 0000000000..1291095480 --- /dev/null +++ b/frontend/src/views/admin/__tests__/ChannelsView.bedrockCompat.spec.ts @@ -0,0 +1,177 @@ +import { defineComponent } from 'vue' +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { Channel, CreateChannelRequest, UpdateChannelRequest } from '@/api/admin/channels' +import ChannelsView from '@/views/admin/ChannelsView.vue' + +const { listChannels, createChannel, updateChannel, getGroups, showSuccess, showError } = vi.hoisted(() => ({ + listChannels: vi.fn(), + createChannel: vi.fn(), + updateChannel: vi.fn(), + getGroups: vi.fn(), + showSuccess: vi.fn(), + showError: vi.fn() +})) + +vi.mock('@/api/admin', () => ({ + adminAPI: { + channels: { list: listChannels, create: createChannel, update: updateChannel }, + groups: { getAll: getGroups }, + settings: { getWebSearchEmulationConfig: vi.fn().mockResolvedValue({ enabled: false }) } + } +})) + +vi.mock('@/stores/app', () => ({ useAppStore: () => ({ showSuccess, showError }) })) + +vi.mock('vue-i18n', async () => ({ + ...await vi.importActual('vue-i18n'), + useI18n: () => ({ t: (key: string) => key }) +})) + +function mountView() { + return mount(ChannelsView, { + global: { + stubs: { + AppLayout: defineComponent({ template: '
' }), + TablePageLayout: defineComponent({ + template: '
' + }), + BaseDialog: defineComponent({ + props: ['show'], + template: '
' + }), + DataTable: defineComponent({ + props: ['data'], + template: '
' + }), + Pagination: true, + ConfirmDialog: true, + EmptyState: true, + Select: true, + Icon: true, + PlatformIcon: true, + PricingEntryCard: true + } + } + }) +} + +type View = ReturnType + +async function clickButton(wrapper: View, text: string) { + const button = wrapper.findAll('button').find(button => button.text() === text) + expect(button).toBeDefined() + await button!.trigger('click') + await flushPromises() +} + +function platformCheckbox(wrapper: View, platform: string) { + return wrapper.findAll('label') + .find(label => label.text() === `admin.groups.platforms.${platform}`)! + .get('input[type="checkbox"]') +} + +function bedrockToggle(wrapper: View) { + return wrapper.findAll('[role="switch"]') + .find(toggle => toggle.element.parentElement?.textContent?.includes('admin.channels.form.bedrockCCCompat'))! +} + +function makeChannel(features: Record): Channel { + return { + id: 1, name: 'Bedrock relay', description: '', status: 'active', + billing_model_source: 'channel_mapped', restrict_models: false, + features_config: features, group_ids: [11, 22], model_pricing: [], model_mapping: {}, + apply_pricing_to_account_stats: false, account_stats_pricing_rules: [], + created_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z' + } +} + +describe('ChannelsView Bedrock compatibility', () => { + let stored: Channel[] + + beforeEach(() => { + vi.clearAllMocks() + localStorage.clear() + stored = [] + listChannels.mockImplementation(async () => ({ items: stored, total: stored.length })) + getGroups.mockResolvedValue([ + { id: 11, name: 'Anthropic group', platform: 'anthropic', rate_multiplier: 1 }, + { id: 22, name: 'OpenAI group', platform: 'openai', rate_multiplier: 1 } + ]) + createChannel.mockImplementation(async (request: CreateChannelRequest) => { + const channel = makeChannel(request.features_config || {}) + channel.group_ids = request.group_ids || [] + stored = [channel] + return channel + }) + updateChannel.mockImplementation(async (_id: number, request: UpdateChannelRequest) => { + stored = [{ ...stored[0], ...request } as Channel] + return stored[0] + }) + }) + + it.each([true, false])('creates and reopens a channel with compatibility %s', async enabled => { + const wrapper = mountView() + await flushPromises() + await clickButton(wrapper, 'admin.channels.createChannel') + await wrapper.get('input[required]').setValue('Bedrock relay') + await platformCheckbox(wrapper, 'anthropic').setValue(true) + await clickButton(wrapper, 'admin.groups.platforms.anthropic') + await wrapper.findAll('label').find(label => label.text().includes('Anthropic group'))! + .get('input[type="checkbox"]').setValue(true) + if (enabled) await bedrockToggle(wrapper).trigger('click') + + await wrapper.get('#channel-form').trigger('submit') + await flushPromises() + expect(showError).not.toHaveBeenCalled() + expect(createChannel).toHaveBeenCalledOnce() + expect(createChannel.mock.calls[0][0].features_config.bedrock_cc_compat).toBe(enabled) + + await clickButton(wrapper, 'common.edit') + await clickButton(wrapper, 'admin.groups.platforms.anthropic') + expect(bedrockToggle(wrapper).attributes('aria-checked')).toBe(String(enabled)) + wrapper.unmount() + }) + + it.each([true, false])('updates compatibility to %s while preserving other features', async enabled => { + stored = [makeChannel({ bedrock_cc_compat: true, future_feature: { enabled: true } })] + const wrapper = mountView() + await flushPromises() + await clickButton(wrapper, 'common.edit') + await clickButton(wrapper, 'admin.groups.platforms.anthropic') + expect(bedrockToggle(wrapper).attributes('aria-checked')).toBe('true') + if (!enabled) await bedrockToggle(wrapper).trigger('click') + + await wrapper.get('#channel-form').trigger('submit') + await flushPromises() + expect(showError).not.toHaveBeenCalled() + expect(updateChannel).toHaveBeenCalledOnce() + expect(updateChannel.mock.calls[0][1].features_config).toMatchObject({ + bedrock_cc_compat: enabled, + future_feature: { enabled: true } + }) + + await clickButton(wrapper, 'common.edit') + await clickButton(wrapper, 'admin.groups.platforms.anthropic') + expect(bedrockToggle(wrapper).attributes('aria-checked')).toBe(String(enabled)) + wrapper.unmount() + }) + + it('explicitly disables compatibility when the Anthropic section is removed', async () => { + stored = [makeChannel({ bedrock_cc_compat: true, future_feature: { enabled: true } })] + const wrapper = mountView() + await flushPromises() + await clickButton(wrapper, 'common.edit') + await platformCheckbox(wrapper, 'anthropic').setValue(false) + + await wrapper.get('#channel-form').trigger('submit') + await flushPromises() + expect(showError).not.toHaveBeenCalled() + expect(updateChannel).toHaveBeenCalledOnce() + expect(updateChannel.mock.calls[0][1]).toMatchObject({ + group_ids: [22], + features_config: { bedrock_cc_compat: false, future_feature: { enabled: true } } + }) + wrapper.unmount() + }) +}) diff --git a/frontend/src/views/user/UsageView.vue b/frontend/src/views/user/UsageView.vue index 8ced361457..688bc19817 100644 --- a/frontend/src/views/user/UsageView.vue +++ b/frontend/src/views/user/UsageView.vue @@ -58,6 +58,7 @@ :show-source-toggle="false" :show-metric-toggle="true" :enable-breakdown="false" + :show-account-cost="false" :title="t('usage.endpointDistribution')" :start-date="startDate" :end-date="endDate"