diff --git a/README.md b/README.md index ca3eda9b..a6c9136b 100644 --- a/README.md +++ b/README.md @@ -427,6 +427,7 @@ Important optional settings: - `audit.ledgerMode`: `observe` reports ledger faults; `enforce` can pause new inference to protect billing integrity. - `routing.accountIsolatedConnections`: partitions outbound TCP/HTTP pools by account for external L4 or connection-hash load balancers. It is off by default because it increases connections, TLS handshakes, memory, and file-descriptor usage. - `routing.segmentedSelectorEnabled`: enabled by default for pools with at least 3,000 eligible accounts; bounds dynamic concurrency reads while retaining quota/tier priorities, sticky sessions, full-planner fallback, and atomic guards. +- `routing.autoAssignMaxNodeShare` / `routing.autoAssignMaxMigrationShare`: optional large-pool guards. `0` (default) keeps the historical unbounded first-pass evacuation and the existing 200-move ceiling for capacity/rebalance repair. Set `0.05`–`1` only when a quarantined node would otherwise dump thousands of auto accounts onto the last healthy exits. `GROK2API_AUTO_ASSIGN_MAX_NODE_SHARE` and `GROK2API_AUTO_ASSIGN_MAX_MIGRATION_SHARE` override the YAML when set. - Build response-header timeout and exact-match 403 invalidation rules are hot-reloadable. - **Sync latest version** applies the validated Grok Build client version and User-Agent. diff --git a/README.zh-CN.md b/README.zh-CN.md index 7b81395b..713e66e0 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -418,6 +418,7 @@ GROK2API_DATABASE_URL='postgresql://user:password@host:5432/grok2api?sslmode=req - `audit.ledgerMode`:`observe` 仅报告账本故障;`enforce` 可暂停新推理以保护计费准确性。 - `routing.accountIsolatedConnections`:为外部 L4 或按连接哈希的负载均衡器按账号拆分出站 TCP/HTTP 连接池。默认关闭,因为会增加连接数、TLS 握手、内存和文件描述符占用。 - `routing.segmentedSelectorEnabled`:默认对至少 3000 个可用账号的大号池启用,限制动态并发读取规模,同时保留额度/等级优先级、会话粘性、完整选号回退与原子门禁。 +- `routing.autoAssignMaxNodeShare` / `routing.autoAssignMaxMigrationShare`:可选的大号池保护。`0`(默认)保持历史行为:不健康节点上的 auto 账号会一次性迁走,容量/再均衡仍最多 200 次。仅在隔离一个节点会把大量账号压到最后几个健康出口时,才设为 `0.05`–`1`。环境变量 `GROK2API_AUTO_ASSIGN_MAX_NODE_SHARE` 与 `GROK2API_AUTO_ASSIGN_MAX_MIGRATION_SHARE` 可覆盖 YAML。 - Build 响应头超时和精确匹配的 403 失效规则支持热加载。 - “同步最新版本”可应用已验证的 Grok Build 客户端版本和 User-Agent。 diff --git a/backend/internal/app/application.go b/backend/internal/app/application.go index 9d49bcdd..e170426b 100644 --- a/backend/internal/app/application.go +++ b/backend/internal/app/application.go @@ -309,6 +309,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat accountSyncService.SetBulkPool(importPool) accountSyncService.UpdateConcurrency(cfg.Batch.ImportConcurrency) egressService := egressapp.NewService(egressRepo, cipher, infraegress.DefaultUserAgent, accountRepo) + egressService.ConfigureAutoAssignBounds(cfg.Routing.AutoAssignMaxNodeShare, cfg.Routing.AutoAssignMaxMigrationShare) egressService.SetClearanceManager(egressManager) egressService.SetNodeProber(egressManager) egressService.SetOperationsConfigInvalidator(egressManager) @@ -351,6 +352,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat modelRepo.SetInvalidationObserver(invalidationService.Notify) clientKeyRepo.SetInvalidationObserver(invalidationService.Notify) gatewayService := gateway.NewService(modelService, auditService, accountService, clientKeyService, providers, selector, responseRepo, cfg.Routing.MaxAttempts) + gatewayService.UpdateQualityRetry(qualityRetryRuntime(cfg.QualityGuard.RequestRetry)) gatewayService.UpdateVideoMaxAttempts(cfg.Routing.VideoMaxAttempts) gatewayService.UpdateMarkBuildChatDeniedAsReauth(cfg.Routing.MarkBuildChatDeniedAsReauth) gatewayService.SetLogger(logger) @@ -401,11 +403,13 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat selector.UpdateConfig(next.Routing.StickyTTL.Value(), next.Routing.CooldownBase.Value(), next.Routing.CooldownMax.Value(), next.Routing.CapacityWait.Value()) selector.UpdatePreferFreeBuild(next.Routing.PreferFreeBuild) selector.UpdateSegmentedSelector(next.Routing.SegmentedSelectorEnabled, next.Routing.SegmentedMinCandidates, next.Routing.SegmentedWindowSize) + egressService.ConfigureAutoAssignBounds(next.Routing.AutoAssignMaxNodeShare, next.Routing.AutoAssignMaxMigrationShare) selector.UpdateExcludeBuildBotFlaggedFromScheduling(next.Accounts.ExcludeBuildBotFlaggedFromScheduling) accountService.UpdateExcludeBuildBotFlaggedFromScheduling(next.Accounts.ExcludeBuildBotFlaggedFromScheduling) egressManager.UpdateAccountIsolatedConnections(next.Routing.AccountIsolatedConnections) reasoningReplay.UpdateConfig(reasoningreplay.Config{Enabled: next.Routing.ReasoningReplayEnabled, TTL: next.Routing.ReasoningReplayTTL.Value()}) gatewayService.UpdateMaxAttempts(next.Routing.MaxAttempts) + gatewayService.UpdateQualityRetry(qualityRetryRuntime(next.QualityGuard.RequestRetry)) gatewayService.UpdateVideoMaxAttempts(next.Routing.VideoMaxAttempts) gatewayService.UpdateMarkBuildChatDeniedAsReauth(next.Routing.MarkBuildChatDeniedAsReauth) gatewayService.UpdateBuildForbiddenReauthPolicy(next.Accounts.MarkBuildForbiddenReauth, next.Accounts.BuildForbiddenReauthCodes) @@ -485,6 +489,16 @@ func accountAutoCleanConfig(value config.AccountsConfig) accountapp.AutoCleanCon } } +func qualityRetryRuntime(value config.QualityGuardRequestRetryConfig) gateway.QualityRetryRuntime { + return gateway.QualityRetryRuntime{ + Enabled: value.Enabled, + MaxAttempts: value.MaxAttempts, + HoldTimeout: value.HoldTimeout.Value(), + MinOutputTokens: int64(value.MinOutputTokens), + OnExhausted: value.OnExhausted, + } +} + func auditLedgerConfig(value config.AuditConfig) auditapp.LedgerConfig { return auditapp.LedgerConfig{ Mode: auditapp.LedgerMode(value.LedgerMode), diff --git a/backend/internal/application/egress/assignment.go b/backend/internal/application/egress/assignment.go index 0abb1e0e..d11c5c3f 100644 --- a/backend/internal/application/egress/assignment.go +++ b/backend/internal/application/egress/assignment.go @@ -3,7 +3,11 @@ package egress import ( "context" "errors" + "math" + "os" "sort" + "strconv" + "strings" "time" accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" @@ -67,6 +71,10 @@ func (s *Service) rebalanceProvider(ctx context.Context, provider accountdomain. if len(nodes) == 0 { return RebalanceResult{Unplaced: countAutoAssignable(accounts, autoAssign, autoBalance)}, nil } + nodeShare, migrationShare := s.autoAssignBounds() + nodes = capAutomaticAssignmentShare(nodes, accounts, nodeShare) + migrationLimit := autoAssignmentMigrationLimit(accounts, migrationShare) + migrations := 0 loads := make(map[uint64]int, len(nodes)) byID := make(map[uint64]domain.Node, len(nodes)) for _, node := range nodes { @@ -95,6 +103,11 @@ func (s *Service) rebalanceProvider(ctx context.Context, provider accountdomain. if credential.EgressNodeID == 0 && !autoAssign { continue } + if credential.EgressNodeID != 0 && migrationLimit >= 0 && migrations >= migrationLimit { + // Keep the remaining accounts bound until the next cycle instead of + // evacuating an entire unhealthy node in one burst. + continue + } target, found := leastLoadedNode(nodes, loads) if !found { result.Unplaced++ @@ -106,6 +119,7 @@ func (s *Service) rebalanceProvider(ctx context.Context, provider accountdomain. if credential.EgressNodeID == 0 { result.Assigned++ } else { + migrations++ result.Rebalanced++ } } @@ -114,8 +128,12 @@ func (s *Service) rebalanceProvider(ctx context.Context, provider accountdomain. // Repair automatic assignments that became over capacity even when ordinary // load balancing is disabled. Manual assignments remain immovable. moves := 0 + capacityMoveLimit := maxAutomaticReassignments + if migrationLimit >= 0 { + capacityMoveLimit = min(maxAutomaticReassignments, max(0, migrationLimit-migrations)) + } blockedCapacitySources := make(map[uint64]bool) - for moves < maxAutomaticReassignments { + for moves < capacityMoveLimit { source, destination, found := overCapacityPair(nodes, loads, blockedCapacitySources) if !found { break @@ -135,7 +153,7 @@ func (s *Service) rebalanceProvider(ctx context.Context, provider accountdomain. if autoBalance { blocked := make(map[uint64]bool) - for moves < maxAutomaticReassignments { + for moves < capacityMoveLimit { source, destination, found := rebalancePair(nodes, loads, blocked) if !found { break @@ -170,6 +188,107 @@ func (s *Service) rebalanceProvider(ctx context.Context, provider accountdomain. return result, nil } +// capAutomaticAssignmentShare optionally prevents a cascading node quarantine +// from concentrating the whole active provider pool on the last healthy node. +// Zero or invalid shares leave configured node capacities unchanged. +func capAutomaticAssignmentShare(nodes []domain.Node, accounts []accountdomain.Credential, share float64) []domain.Node { + if !validAutoAssignShare(share) || share == 0 { + return nodes + } + active := activeAccountCount(accounts) + if active == 0 { + return nodes + } + maxPerNode := max(1, int(math.Ceil(float64(active)*share))) + activeLoads := make(map[uint64]int, len(nodes)) + for _, credential := range accounts { + if credential.Enabled && credential.AuthStatus == accountdomain.AuthStatusActive && credential.EgressNodeID != 0 { + activeLoads[credential.EgressNodeID]++ + } + } + for index := range nodes { + configured := nodes[index].AccountCapacity + // AssignedAccountCount is global across providers and includes inactive + // and manual bindings. Preserve those reserved slots while limiting only + // this provider's active share on the node. + reservedByOthers := max(0, nodes[index].AssignedAccountCount-activeLoads[nodes[index].ID]) + shareCapacity := reservedByOthers + maxPerNode + if configured <= 0 || configured > shareCapacity { + nodes[index].AccountCapacity = shareCapacity + } + } + return nodes +} + +// autoAssignmentMigrationLimit returns the per-cycle move budget when share is +// enabled. A negative result means the first-pass evacuation stays unbounded +// and later capacity/rebalance loops keep the existing 200-move ceiling. +func autoAssignmentMigrationLimit(accounts []accountdomain.Credential, share float64) int { + if !validAutoAssignShare(share) || share == 0 { + return -1 + } + return max(1, int(math.Ceil(float64(activeAccountCount(accounts))*share))) +} + +func activeAccountCount(accounts []accountdomain.Credential) int { + active := 0 + for _, credential := range accounts { + if credential.Enabled && credential.AuthStatus == accountdomain.AuthStatusActive { + active++ + } + } + return active +} + +func (s *Service) ConfigureAutoAssignBounds(maxNodeShare, maxMigrationShare float64) { + if s == nil { + return + } + s.mu.Lock() + defer s.mu.Unlock() + s.autoAssignMaxNodeShare = normalizeAutoAssignShare(maxNodeShare) + s.autoAssignMaxMigrationShare = normalizeAutoAssignShare(maxMigrationShare) +} + +func (s *Service) autoAssignBounds() (nodeShare, migrationShare float64) { + if s == nil { + return 0, 0 + } + s.mu.RLock() + configuredNode, configuredMigration := s.autoAssignMaxNodeShare, s.autoAssignMaxMigrationShare + s.mu.RUnlock() + return resolveAutoAssignShare("GROK2API_AUTO_ASSIGN_MAX_NODE_SHARE", configuredNode), + resolveAutoAssignShare("GROK2API_AUTO_ASSIGN_MAX_MIGRATION_SHARE", configuredMigration) +} + +func resolveAutoAssignShare(envName string, configured float64) float64 { + if raw, ok := os.LookupEnv(envName); ok { + if parsed, valid := parseAutoAssignShare(raw); valid { + return parsed + } + } + return normalizeAutoAssignShare(configured) +} + +func parseAutoAssignShare(raw string) (float64, bool) { + value, err := strconv.ParseFloat(strings.TrimSpace(raw), 64) + if err != nil || !validAutoAssignShare(value) { + return 0, false + } + return value, true +} + +func normalizeAutoAssignShare(value float64) float64 { + if !validAutoAssignShare(value) { + return 0 + } + return value +} + +func validAutoAssignShare(value float64) bool { + return !math.IsNaN(value) && !math.IsInf(value, 0) && (value == 0 || (value >= 0.05 && value <= 1)) +} + func (s *Service) eligibleNodesForProvider(values []domain.Node, provider accountdomain.Provider, probeInterval time.Duration, now time.Time) []domain.Node { values = append([]domain.Node(nil), values...) result := make([]domain.Node, 0, len(values)) diff --git a/backend/internal/application/egress/assignment_bounds_test.go b/backend/internal/application/egress/assignment_bounds_test.go new file mode 100644 index 00000000..44fe1916 --- /dev/null +++ b/backend/internal/application/egress/assignment_bounds_test.go @@ -0,0 +1,101 @@ +package egress + +import ( + "math" + "testing" + + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" + domain "github.com/chenyme/grok2api/backend/internal/domain/egress" +) + +func TestNormalizeAndParseAutoAssignShare(t *testing.T) { + if got := normalizeAutoAssignShare(0); got != 0 { + t.Fatalf("zero must stay off: %v", got) + } + if got := normalizeAutoAssignShare(0.03); got != 0 { + t.Fatalf("below 0.05 must stay off: %v", got) + } + if got := normalizeAutoAssignShare(1.2); got != 0 { + t.Fatalf("above 1 must stay off: %v", got) + } + if got := normalizeAutoAssignShare(0.3); got != 0.3 { + t.Fatalf("valid share = %v", got) + } + for _, value := range []float64{math.NaN(), math.Inf(1), math.Inf(-1)} { + if got := normalizeAutoAssignShare(value); got != 0 { + t.Fatalf("special float %v must stay off: %v", value, got) + } + } + if _, ok := parseAutoAssignShare("0"); !ok { + t.Fatal("explicit 0 is a valid env override") + } + if _, ok := parseAutoAssignShare("0.03"); ok { + t.Fatal("0.03 must be rejected so YAML/default remains") + } + if value, ok := parseAutoAssignShare("0.10"); !ok || value != 0.10 { + t.Fatalf("0.10 = %v %v", value, ok) + } + for _, raw := range []string{"NaN", "Inf", "-Inf"} { + if _, ok := parseAutoAssignShare(raw); ok { + t.Fatalf("%q must be rejected so YAML/default remains", raw) + } + } +} + +func TestCapAutomaticAssignmentShareDisabledByDefault(t *testing.T) { + nodes := []domain.Node{{ID: 1, AccountCapacity: 0}, {ID: 2, AccountCapacity: 40}} + accounts := makeActiveAccounts(20) + got := capAutomaticAssignmentShare(nodes, accounts, 0) + if got[0].AccountCapacity != 0 || got[1].AccountCapacity != 40 { + t.Fatalf("disabled share must not rewrite capacities: %#v", got) + } +} + +func TestCapAutomaticAssignmentShareAppliesFraction(t *testing.T) { + nodes := []domain.Node{{ID: 1, AccountCapacity: 0}, {ID: 2, AccountCapacity: 40}} + accounts := makeActiveAccounts(100) + got := capAutomaticAssignmentShare(nodes, accounts, 0.30) + if got[0].AccountCapacity != 30 { + t.Fatalf("uncapped node should absorb at most 30: %#v", got[0]) + } + if got[1].AccountCapacity != 30 { + t.Fatalf("configured 40 should be lowered to 30: %#v", got[1]) + } +} + +func TestCapAutomaticAssignmentSharePreservesOtherProviderLoad(t *testing.T) { + nodes := []domain.Node{{ID: 1, AccountCapacity: 0, AssignedAccountCount: 30}} + accounts := makeActiveAccounts(100) + got := capAutomaticAssignmentShare(nodes, accounts, 0.30) + if got[0].AccountCapacity != 60 { + t.Fatalf("30 reserved slots plus 30 active provider slots = %#v", got[0]) + } +} + +func TestAutoAssignmentMigrationLimitPreservesHistoricalCeilingWhenOff(t *testing.T) { + if got := autoAssignmentMigrationLimit(makeActiveAccounts(5000), 0); got != -1 { + t.Fatalf("disabled share must leave first-pass unbounded: %d", got) + } + if got := autoAssignmentMigrationLimit(makeActiveAccounts(100), 0.10); got != 10 { + t.Fatalf("10%% of 100 active accounts = %d", got) + } +} + +func TestResolveAutoAssignSharePrefersValidEnv(t *testing.T) { + t.Setenv("GROK2API_AUTO_ASSIGN_MAX_NODE_SHARE", "0.25") + if got := resolveAutoAssignShare("GROK2API_AUTO_ASSIGN_MAX_NODE_SHARE", 0); got != 0.25 { + t.Fatalf("env should override disabled YAML: %v", got) + } + t.Setenv("GROK2API_AUTO_ASSIGN_MAX_NODE_SHARE", "nope") + if got := resolveAutoAssignShare("GROK2API_AUTO_ASSIGN_MAX_NODE_SHARE", 0.4); got != 0.4 { + t.Fatalf("invalid env should fall back to YAML: %v", got) + } +} + +func makeActiveAccounts(n int) []accountdomain.Credential { + accounts := make([]accountdomain.Credential, n) + for i := range accounts { + accounts[i] = accountdomain.Credential{Enabled: true, AuthStatus: accountdomain.AuthStatusActive} + } + return accounts +} diff --git a/backend/internal/application/egress/service.go b/backend/internal/application/egress/service.go index 308f024b..830a65ea 100644 --- a/backend/internal/application/egress/service.go +++ b/backend/internal/application/egress/service.go @@ -104,19 +104,21 @@ type ServiceRepository interface { } type Service struct { - repository ServiceRepository - accounts AccountBindingRepository - operations OperationsRepository - cipher *security.Cipher - mu sync.RWMutex - browserUA string - clearance ClearanceManager - prober NodeProber - operationsCache OperationsConfigInvalidator - qualityProber QualityProber - assignmentMu sync.Mutex - lastAssignmentRun time.Time - assignmentRunning bool + repository ServiceRepository + accounts AccountBindingRepository + operations OperationsRepository + cipher *security.Cipher + mu sync.RWMutex + browserUA string + clearance ClearanceManager + prober NodeProber + operationsCache OperationsConfigInvalidator + qualityProber QualityProber + assignmentMu sync.Mutex + lastAssignmentRun time.Time + assignmentRunning bool + autoAssignMaxNodeShare float64 + autoAssignMaxMigrationShare float64 } func (s *Service) SetQualityProber(value QualityProber) { diff --git a/backend/internal/application/gateway/attempt.go b/backend/internal/application/gateway/attempt.go index 0843bf8e..972d198e 100644 --- a/backend/internal/application/gateway/attempt.go +++ b/backend/internal/application/gateway/attempt.go @@ -171,6 +171,23 @@ func (r *failureAttemptRecorder) captureStreamFailure(credential accountdomain.C }) } +func (r *failureAttemptRecorder) captureQualityDegraded(credential accountdomain.Credential, startedAt time.Time) { + status := http.StatusOK + r.append(audit.Attempt{ + Source: audit.AttemptSourceUpstreamHTTP, + Stage: "quality_hold", + AccountID: auditAccountID(credential.ID), + AccountName: credential.Name, + Method: r.method, + RequestPath: r.path, + StartedAt: startedAt.UTC(), + DurationMS: time.Since(startedAt).Milliseconds(), + UpstreamStatusCode: &status, + UpstreamStatus: "200 OK", + TransportError: ErrorQualityDegraded, + }) +} + func (r *failureAttemptRecorder) append(attempt audit.Attempt) { attempt.Number = len(r.attempts) + 1 r.attempts = append(r.attempts, attempt) diff --git a/backend/internal/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go new file mode 100644 index 00000000..df99047a --- /dev/null +++ b/backend/internal/application/gateway/quality_retry.go @@ -0,0 +1,293 @@ +package gateway + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "strings" + "time" + + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/domain/audit" + inferencedomain "github.com/chenyme/grok2api/backend/internal/domain/inference" + modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" + infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" +) + +const ( + ErrorQualityDegraded = "quality_degraded" + qualityRetryFailOpen = "fail_open" + qualityRetryFailClosed = "fail_closed" + defaultQualityMaxAttempts = 6 + defaultQualityHoldTimeout = 3 * time.Second + defaultQualityMinOutput = int64(32) +) + +var errQualityDegraded = errors.New("上游响应缺少推理") + +// QualityRetryRuntime is the isolated request-path withhold/retry policy. +// Zero Enabled leaves production behavior unchanged. +type QualityRetryRuntime struct { + Enabled bool + MaxAttempts int + HoldTimeout time.Duration + MinOutputTokens int64 + OnExhausted string +} + +// QualityStreamSignals is the hold classifier input. Tests drive this +// directly and via ObserveQualityChunk on SSE fixtures. +type QualityStreamSignals struct { + HasThinking bool + VisibleTokens int64 + ReasoningTokens int64 + OutputTokens int64 + Terminal bool + HoldExpired bool +} + +// QualityVerdict is the hold decision for one upstream stream. +type QualityVerdict string + +const ( + QualityWait QualityVerdict = "wait" + QualityDeliver QualityVerdict = "deliver" + QualityWithhold QualityVerdict = "withhold" +) + +// QualityRetryAction is what the attempt loop does with a withhold verdict. +type QualityRetryAction string + +const ( + QualityActionDeliver QualityRetryAction = "deliver" + QualityActionDeliverLast QualityRetryAction = "deliver_last" + QualityActionRetry QualityRetryAction = "retry" + QualityActionReject QualityRetryAction = "reject" +) + +func normalizeQualityRetry(cfg QualityRetryRuntime) QualityRetryRuntime { + if cfg.MaxAttempts <= 0 { + cfg.MaxAttempts = defaultQualityMaxAttempts + } + if cfg.HoldTimeout <= 0 { + cfg.HoldTimeout = defaultQualityHoldTimeout + } + if cfg.MinOutputTokens <= 0 { + cfg.MinOutputTokens = defaultQualityMinOutput + } + cfg.OnExhausted = normalizeQualityExhaustionPolicy(cfg.OnExhausted) + return cfg +} + +func (s *Service) UpdateQualityRetry(cfg QualityRetryRuntime) { + normalized := normalizeQualityRetry(cfg) + s.qualityRetry.Store(&normalized) +} + +func (s *Service) qualityRetryConfig() QualityRetryRuntime { + if s == nil { + return normalizeQualityRetry(QualityRetryRuntime{}) + } + if value := s.qualityRetry.Load(); value != nil { + return *value + } + return normalizeQualityRetry(QualityRetryRuntime{}) +} + +// ClassifyQualityHold decides whether a held stream may be forwarded. +// Thinking (or reasoning tokens) always delivers. A finished or expired +// sample with enough visible output and no reasoning is 降智 and withheld. +// Short replies below minOutput are delivered so "ok"/"yes" is not retried. +func ClassifyQualityHold(sig QualityStreamSignals, minOutput int64) QualityVerdict { + if minOutput <= 0 { + minOutput = defaultQualityMinOutput + } + if sig.HasThinking || sig.ReasoningTokens > 0 { + return QualityDeliver + } + output := sig.OutputTokens + if output < sig.VisibleTokens { + output = sig.VisibleTokens + } + enough := output >= minOutput + if sig.Terminal { + if enough { + return QualityWithhold + } + return QualityDeliver + } + if enough { + return QualityWithhold + } + if sig.HoldExpired { + return QualityDeliver + } + return QualityWait +} + +// DecideQualityRetry caps withhold recovery at maxAttempts (default 6: +// original + five extra accounts). The last withhold +// (attemptIndex == maxAttempts-1) is fail-open unless OnExhausted is fail_closed. +func DecideQualityRetry(verdict QualityVerdict, attemptIndex, maxAttempts int, onExhausted string) QualityRetryAction { + if verdict != QualityWithhold { + return QualityActionDeliver + } + if maxAttempts <= 0 { + maxAttempts = defaultQualityMaxAttempts + } + if attemptIndex < 0 { + attemptIndex = 0 + } + if attemptIndex < maxAttempts-1 { + return QualityActionRetry + } + // attemptIndex == maxAttempts-1 (or past it): do not retry again. + if normalizeQualityExhaustionPolicy(onExhausted) == qualityRetryFailClosed { + return QualityActionReject + } + return QualityActionDeliverLast +} + +// BoundQualityRetry turns a Retry into DeliverLast/Reject when the routing +// loop has no remaining account slot, so the already-held body is not dropped +// on continue-into-exhausted-loop. +func BoundQualityRetry(action QualityRetryAction, hasNextRoutingAttempt bool, onExhausted string) QualityRetryAction { + if action != QualityActionRetry || hasNextRoutingAttempt { + return action + } + if normalizeQualityExhaustionPolicy(onExhausted) == qualityRetryFailClosed { + return QualityActionReject + } + return QualityActionDeliverLast +} + +func normalizeQualityExhaustionPolicy(value string) string { + if strings.EqualFold(strings.TrimSpace(value), qualityRetryFailOpen) { + return qualityRetryFailOpen + } + return qualityRetryFailClosed +} + +// QualityCommit is the single attempt-loop decision for a held stream. +type QualityCommit struct { + Action QualityRetryAction + Audit bool + KeepBody bool +} + +// CommitQualityHold is the shipped withhold/retry/commit unit. The attempt +// loop must not re-derive this from Decide+Bound+switch. +func CommitQualityHold(verdict QualityVerdict, qualityAttempt, maxAttempts int, hasNextRouting bool, onExhausted string) QualityCommit { + action := BoundQualityRetry( + DecideQualityRetry(verdict, qualityAttempt, maxAttempts, onExhausted), + hasNextRouting, + onExhausted, + ) + switch action { + case QualityActionRetry, QualityActionReject: + return QualityCommit{Action: action, Audit: true, KeepBody: false} + case QualityActionDeliverLast: + return QualityCommit{Action: action, Audit: false, KeepBody: true} + default: + return QualityCommit{Action: QualityActionDeliver, Audit: false, KeepBody: true} + } +} + +func shouldHoldQualityStream(input Input, ownership *inferencedomain.ResponseOwnership, route modeldomain.Route, operation audit.Operation, cfg QualityRetryRuntime) bool { + if !cfg.Enabled || !input.Streaming || input.ForcedEgressNodeID != 0 || ownership != nil { + return false + } + switch operation { + case audit.OperationChat, audit.OperationResponses, audit.OperationMessages, "": + default: + return false + } + if route.Provider != accountdomain.ProviderBuild && route.Provider != accountdomain.ProviderConsole { + return false + } + // Retrying a tool-capable request can repeat external side effects. Tool + // requests remain outside this feature until they have their own replay + // safety contract. + if qualityRequestUsesTools(input.Body) { + return false + } + // Aliases are rewritten before this gate, so inspect the effective request + // body instead of only the reasoning-capable base model. In particular, + // grok-4.3-none becomes grok-4.3 plus an explicit disabled setting. + if qualityRequestDisablesReasoning(input.Body) { + return false + } + if modeldomain.SupportsReasoningForProvider(route.Provider, input.PublicModel) { + return true + } + return modeldomain.SupportsReasoningForProvider(route.Provider, route.UpstreamModel) +} + +func qualityRequestUsesTools(body []byte) bool { + var payload map[string]json.RawMessage + if json.Unmarshal(body, &payload) != nil { + return false + } + return nonEmptyJSONCollection(payload["tools"]) || nonEmptyJSONCollection(payload["functions"]) +} + +func qualityRequestDisablesReasoning(body []byte) bool { + var payload map[string]json.RawMessage + if json.Unmarshal(body, &payload) != nil { + return false + } + if jsonStringEquals(payload["reasoning_effort"], modeldomain.ReasoningEffortNone) { + return true + } + for _, key := range []string{"reasoning", "output_config", "thinking"} { + var nested map[string]json.RawMessage + if json.Unmarshal(payload[key], &nested) != nil { + continue + } + if jsonStringEquals(nested["effort"], modeldomain.ReasoningEffortNone) || jsonStringEquals(nested["type"], "disabled") { + return true + } + var budget int64 + if raw, ok := nested["budget_tokens"]; ok && json.Unmarshal(raw, &budget) == nil && budget == 0 { + return true + } + } + return jsonStringEquals(payload["thinking"], "disabled") +} + +func nonEmptyJSONCollection(raw json.RawMessage) bool { + trimmed := strings.TrimSpace(string(raw)) + if trimmed == "" || trimmed == "null" || trimmed == "[]" || trimmed == "{}" { + return false + } + return strings.HasPrefix(trimmed, "[") || strings.HasPrefix(trimmed, "{") +} + +func jsonStringEquals(raw json.RawMessage, want string) bool { + var value string + return json.Unmarshal(raw, &value) == nil && strings.EqualFold(strings.TrimSpace(value), want) +} + +func (s *Service) recordQualityDegraded(ctx context.Context, base audit.Record, credential accountdomain.Credential, usage Usage, startedAt time.Time, trace *infraegress.Trace, provider accountdomain.Provider) { + record := base + record.EventID = newAuditEventID() + accountID := credential.ID + record.AccountID = &accountID + record.AccountName = credential.Name + record.StatusCode = http.StatusOK + record.ErrorCode = ErrorQualityDegraded + record.OutputTokens = usage.OutputTokens + record.ReasoningTokens = usage.ReasoningTokens + record.TotalTokens = usage.TotalTokens + record.InputTokens = usage.InputTokens + if usage.Reported { + record.UsageSource = audit.UsageSourceUpstream + } + record.DurationMS = time.Since(startedAt).Milliseconds() + record.CreatedAt = time.Now().UTC() + applyAuditEgress(&record, trace, provider) + if err := s.audits.Create(ctx, record); err != nil { + s.logger.Error("quality_degraded_audit_failed", "event_id", record.EventID, "request_id", record.RequestID, "error", err) + } +} diff --git a/backend/internal/application/gateway/quality_retry_scan.go b/backend/internal/application/gateway/quality_retry_scan.go new file mode 100644 index 00000000..c70a4493 --- /dev/null +++ b/backend/internal/application/gateway/quality_retry_scan.go @@ -0,0 +1,420 @@ +package gateway + +import ( + "bytes" + "context" + "encoding/json" + "io" + "sync" + "time" + "unicode/utf8" + + "github.com/chenyme/grok2api/backend/internal/domain/audit" +) + +const ( + qualityProtocolChat = "chat" + qualityProtocolResponses = "responses" + qualityProtocolAnthropic = "anthropic" + qualityReasoningSSEComment = ": grok2api-reasoning-start" + qualityHoldMaxBufferBytes = 4 << 20 +) + +type qualityScanState struct { + protocol string + pending []byte + hasThinking bool + visibleRunes int + reasoningTokens int64 + outputTokens int64 + usage Usage + responseID string + terminal bool +} + +type qualityReadResult struct { + data []byte + err error +} + +// qualityReadPump is the sole reader of the upstream body. It lets the hold +// timer win while an upstream Read is blocked, then remains the continuation +// reader for the response body after the held prefix is replayed. +type qualityReadPump struct { + source io.ReadCloser + results chan qualityReadResult + done chan struct{} + closeOnce sync.Once + pending []byte + finalErr error +} + +func newQualityReadPump(source io.ReadCloser) *qualityReadPump { + pump := &qualityReadPump{ + source: source, + results: make(chan qualityReadResult), + done: make(chan struct{}), + } + go pump.run() + return pump +} + +func (p *qualityReadPump) run() { + defer close(p.results) + buf := make([]byte, 4096) + for { + n, err := p.source.Read(buf) + if n == 0 && err == nil { + continue + } + result := qualityReadResult{err: err} + if n > 0 { + result.data = append([]byte(nil), buf[:n]...) + } + select { + case p.results <- result: + case <-p.done: + return + } + if err != nil { + return + } + } +} + +func (p *qualityReadPump) Read(dst []byte) (int, error) { + for len(p.pending) == 0 { + if p.finalErr != nil { + return 0, p.finalErr + } + result, ok := <-p.results + if !ok { + p.finalErr = io.EOF + return 0, io.EOF + } + p.pending = result.data + p.finalErr = result.err + if len(p.pending) == 0 && p.finalErr != nil { + return 0, p.finalErr + } + } + n := copy(dst, p.pending) + p.pending = p.pending[n:] + return n, nil +} + +func (p *qualityReadPump) Close() error { + var err error + p.closeOnce.Do(func() { + close(p.done) + err = p.source.Close() + }) + return err +} + +func qualityProtocolForOperation(operation audit.Operation) string { + switch operation { + case audit.OperationChat: + return qualityProtocolChat + case audit.OperationMessages: + return qualityProtocolAnthropic + default: + return qualityProtocolResponses + } +} + +func (s *qualityScanState) signals() QualityStreamSignals { + visible := int64((s.visibleRunes + 3) / 4) + if s.usage.Reported { + fromUsage := s.usage.OutputTokens - s.usage.ReasoningTokens + if fromUsage > visible { + visible = fromUsage + } + } + output := s.outputTokens + if s.usage.Reported && s.usage.OutputTokens > output { + output = s.usage.OutputTokens + } + return QualityStreamSignals{ + HasThinking: s.hasThinking || s.reasoningTokens > 0 || s.usage.ReasoningTokens > 0, + VisibleTokens: visible, + ReasoningTokens: max(s.reasoningTokens, s.usage.ReasoningTokens), + OutputTokens: output, + Terminal: s.terminal, + } +} + +// ObserveQualityChunk feeds one SSE chunk into the hold classifier state. +// This is the shipped scanner used by peekQualityStream. +func ObserveQualityChunk(state *qualityScanState, chunk []byte) { + if state == nil || len(chunk) == 0 { + return + } + state.pending = append(state.pending, chunk...) + for { + index := bytes.IndexByte(state.pending, '\n') + if index < 0 { + if len(state.pending) > 1<<20 { + state.pending = nil + } + return + } + line := bytes.TrimSpace(state.pending[:index]) + state.pending = state.pending[index+1:] + if len(line) == 0 { + continue + } + if bytes.Equal(line, []byte(qualityReasoningSSEComment)) { + state.hasThinking = true + continue + } + if !bytes.HasPrefix(line, []byte("data:")) { + continue + } + payload := bytes.TrimSpace(bytes.TrimPrefix(line, []byte("data:"))) + if bytes.Equal(payload, []byte("[DONE]")) { + state.terminal = true + continue + } + observeQualityPayload(state, payload) + } +} + +func observeQualityPayload(state *qualityScanState, payload []byte) { + switch state.protocol { + case qualityProtocolChat: + observeQualityChat(state, payload) + case qualityProtocolAnthropic: + observeQualityAnthropic(state, payload) + default: + observeQualityResponses(state, payload) + } +} + +func observeQualityChat(state *qualityScanState, payload []byte) { + var event struct { + ID string `json:"id"` + Model string `json:"model"` + Choices []struct { + Delta struct { + Content string `json:"content"` + Reasoning string `json:"reasoning"` + ReasoningContent string `json:"reasoning_content"` + ThinkingContent string `json:"thinking_content"` + } `json:"delta"` + FinishReason string `json:"finish_reason"` + } `json:"choices"` + Usage *struct { + PromptTokens int64 `json:"prompt_tokens"` + CompletionTokens int64 `json:"completion_tokens"` + TotalTokens int64 `json:"total_tokens"` + CompletionTokensDetails struct { + ReasoningTokens int64 `json:"reasoning_tokens"` + } `json:"completion_tokens_details"` + } `json:"usage"` + } + if json.Unmarshal(payload, &event) != nil { + return + } + if state.responseID == "" { + state.responseID = event.ID + } + if event.Usage != nil { + state.usage.Reported = true + state.usage.InputTokens = event.Usage.PromptTokens + state.usage.OutputTokens = event.Usage.CompletionTokens + state.usage.ReasoningTokens = event.Usage.CompletionTokensDetails.ReasoningTokens + state.usage.TotalTokens = event.Usage.TotalTokens + state.usage.ResponseModel = event.Model + state.outputTokens = event.Usage.CompletionTokens + state.reasoningTokens = event.Usage.CompletionTokensDetails.ReasoningTokens + if state.reasoningTokens > 0 { + state.hasThinking = true + } + } + for _, choice := range event.Choices { + delta := choice.Delta + if delta.Reasoning != "" || delta.ReasoningContent != "" || delta.ThinkingContent != "" { + state.hasThinking = true + } + if delta.Content != "" { + noteVisibleContent(state, delta.Content) + } + if choice.FinishReason != "" { + state.terminal = true + } + } +} + +func observeQualityResponses(state *qualityScanState, payload []byte) { + var event struct { + Type string `json:"type"` + Delta string `json:"delta"` + Item struct { + ID string `json:"id"` + Type string `json:"type"` + } `json:"item"` + Response *struct { + ID string `json:"id"` + Model string `json:"model"` + Usage *struct { + OutputTokens int64 `json:"output_tokens"` + InputTokens int64 `json:"input_tokens"` + TotalTokens int64 `json:"total_tokens"` + OutputTokensDetails struct { + ReasoningTokens int64 `json:"reasoning_tokens"` + } `json:"output_tokens_details"` + } `json:"usage"` + } `json:"response"` + } + if json.Unmarshal(payload, &event) != nil { + return + } + switch event.Type { + case "response.completed", "response.incomplete", "response.failed": + state.terminal = true + case "response.reasoning_text.delta", "response.reasoning_summary_text.delta": + if event.Delta != "" { + state.hasThinking = true + } + case "response.output_item.added": + if event.Item.Type == "reasoning" && event.Item.ID != "" { + state.hasThinking = true + } + case "response.output_text.delta": + if event.Delta != "" { + noteVisibleContent(state, event.Delta) + } + } + if event.Response != nil { + if state.responseID == "" { + state.responseID = event.Response.ID + } + if event.Response.Usage != nil { + state.usage.Reported = true + state.usage.InputTokens = event.Response.Usage.InputTokens + state.usage.OutputTokens = event.Response.Usage.OutputTokens + state.usage.ReasoningTokens = event.Response.Usage.OutputTokensDetails.ReasoningTokens + state.usage.TotalTokens = event.Response.Usage.TotalTokens + state.usage.ResponseModel = event.Response.Model + state.outputTokens = event.Response.Usage.OutputTokens + state.reasoningTokens = event.Response.Usage.OutputTokensDetails.ReasoningTokens + if state.reasoningTokens > 0 { + state.hasThinking = true + } + } + } +} + +func observeQualityAnthropic(state *qualityScanState, payload []byte) { + var event struct { + Type string `json:"type"` + ContentBlock struct { + Type string `json:"type"` + } `json:"content_block"` + Delta struct { + Type string `json:"type"` + Text string `json:"text"` + Thinking string `json:"thinking"` + } `json:"delta"` + Usage *struct { + OutputTokens int64 `json:"output_tokens"` + OutputTokensDetails struct { + ThinkingTokens int64 `json:"thinking_tokens"` + } `json:"output_tokens_details"` + } `json:"usage"` + } + if json.Unmarshal(payload, &event) != nil { + return + } + switch event.Type { + case "message_stop": + state.terminal = true + case "content_block_start": + if event.ContentBlock.Type == "thinking" { + state.hasThinking = true + } + case "content_block_delta": + if event.Delta.Type == "thinking_delta" && event.Delta.Thinking != "" { + state.hasThinking = true + } + if event.Delta.Type == "text_delta" && event.Delta.Text != "" { + noteVisibleContent(state, event.Delta.Text) + } + } + if event.Usage != nil { + state.usage.Reported = true + state.usage.OutputTokens = event.Usage.OutputTokens + state.usage.ReasoningTokens = event.Usage.OutputTokensDetails.ThinkingTokens + state.outputTokens = event.Usage.OutputTokens + state.reasoningTokens = event.Usage.OutputTokensDetails.ThinkingTokens + if state.reasoningTokens > 0 { + state.hasThinking = true + } + } +} + +func noteVisibleContent(state *qualityScanState, text string) { + if text == "" { + return + } + state.visibleRunes += utf8.RuneCountInString(text) +} + +func peekQualityStream(ctx context.Context, body io.ReadCloser, protocol string, cfg QualityRetryRuntime) (io.ReadCloser, QualityVerdict, Usage, string, error) { + cfg = normalizeQualityRetry(cfg) + if body == nil { + return io.NopCloser(bytes.NewReader(nil)), QualityDeliver, Usage{}, "", nil + } + pump := newQualityReadPump(body) + state := qualityScanState{protocol: protocol} + var held bytes.Buffer + holdTimer := time.NewTimer(cfg.HoldTimeout) + defer holdTimer.Stop() + for { + sig := state.signals() + if verdict := ClassifyQualityHold(sig, cfg.MinOutputTokens); verdict != QualityWait { + return newPrefixReplay(&held, pump), verdict, state.usage, state.responseID, nil + } + + select { + case <-ctx.Done(): + _ = pump.Close() + return io.NopCloser(bytes.NewReader(held.Bytes())), QualityDeliver, state.usage, state.responseID, ctx.Err() + case <-holdTimer.C: + sig.HoldExpired = true + return newPrefixReplay(&held, pump), ClassifyQualityHold(sig, cfg.MinOutputTokens), state.usage, state.responseID, nil + case result, ok := <-pump.results: + if !ok { + state.terminal = true + return newPrefixReplay(&held, pump), ClassifyQualityHold(state.signals(), cfg.MinOutputTokens), state.usage, state.responseID, nil + } + if len(result.data) > 0 { + if held.Len()+len(result.data) > qualityHoldMaxBufferBytes { + _, _ = held.Write(result.data) + return newPrefixReplay(&held, pump), QualityDeliver, state.usage, state.responseID, nil + } + _, _ = held.Write(result.data) + ObserveQualityChunk(&state, result.data) + } + if result.err == io.EOF { + state.terminal = true + return newPrefixReplay(&held, pump), ClassifyQualityHold(state.signals(), cfg.MinOutputTokens), state.usage, state.responseID, nil + } + if result.err != nil { + _ = pump.Close() + return io.NopCloser(bytes.NewReader(held.Bytes())), QualityDeliver, state.usage, state.responseID, result.err + } + } + } +} + +func newPrefixReplay(held *bytes.Buffer, rest io.ReadCloser) io.ReadCloser { + if rest == nil { + rest = io.NopCloser(bytes.NewReader(nil)) + } + if held == nil || held.Len() == 0 { + return rest + } + return &replayReadCloser{Reader: io.MultiReader(bytes.NewReader(held.Bytes()), rest), source: rest} +} diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go new file mode 100644 index 00000000..409569d7 --- /dev/null +++ b/backend/internal/application/gateway/quality_retry_test.go @@ -0,0 +1,815 @@ +package gateway + +import ( + "context" + "fmt" + "io" + "net/http" + "path/filepath" + "strings" + "testing" + "time" + + accountapp "github.com/chenyme/grok2api/backend/internal/application/account" + clientkeyapp "github.com/chenyme/grok2api/backend/internal/application/clientkey" + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/domain/audit" + "github.com/chenyme/grok2api/backend/internal/domain/clientkey" + inferencedomain "github.com/chenyme/grok2api/backend/internal/domain/inference" + modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" + "github.com/chenyme/grok2api/backend/internal/infra/persistence/relational" + "github.com/chenyme/grok2api/backend/internal/infra/provider" + "github.com/chenyme/grok2api/backend/internal/infra/runtime/memory" +) + +func TestClassifyQualityHold(t *testing.T) { + t.Parallel() + tests := []struct { + name string + sig QualityStreamSignals + want QualityVerdict + }{ + {name: "thinking delivers", sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 10}, want: QualityDeliver}, + {name: "reasoning tokens deliver", sig: QualityStreamSignals{ReasoningTokens: 40, VisibleTokens: 80, Terminal: true}, want: QualityDeliver}, + {name: "visible 32 no think withhold", sig: QualityStreamSignals{VisibleTokens: 32, Terminal: true}, want: QualityWithhold}, + {name: "output 40 no think withhold", sig: QualityStreamSignals{OutputTokens: 40, Terminal: true}, want: QualityWithhold}, + {name: "short no think delivers", sig: QualityStreamSignals{VisibleTokens: 10, Terminal: true}, want: QualityDeliver}, + {name: "midstream enough content withhold", sig: QualityStreamSignals{VisibleTokens: 64}, want: QualityWithhold}, + {name: "wait for more", sig: QualityStreamSignals{VisibleTokens: 8}, want: QualityWait}, + {name: "hold expired short delivers", sig: QualityStreamSignals{VisibleTokens: 8, HoldExpired: true}, want: QualityDeliver}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + if got := ClassifyQualityHold(test.sig, 32); got != test.want { + t.Fatalf("ClassifyQualityHold() = %s, want %s", got, test.want) + } + }) + } +} + +func TestDecideQualityRetry(t *testing.T) { + t.Parallel() + if got := DecideQualityRetry(QualityDeliver, 0, 2, qualityRetryFailOpen); got != QualityActionDeliver { + t.Fatalf("deliver verdict: %s", got) + } + if got := DecideQualityRetry(QualityWithhold, 0, 2, qualityRetryFailOpen); got != QualityActionRetry { + t.Fatalf("first withhold: %s", got) + } + if got := DecideQualityRetry(QualityWithhold, 1, 2, qualityRetryFailOpen); got != QualityActionDeliverLast { + t.Fatalf("last fail-open: %s", got) + } + if got := DecideQualityRetry(QualityWithhold, 1, 2, qualityRetryFailClosed); got != QualityActionReject { + t.Fatalf("last fail-closed: %s", got) + } + if got := DecideQualityRetry(QualityWithhold, 0, 1, qualityRetryFailOpen); got != QualityActionDeliverLast { + t.Fatalf("max 1 fail-open: %s", got) + } + if got := DecideQualityRetry(QualityWithhold, 5, 0, ""); got != QualityActionReject { + t.Fatalf("zero-value policy must use fail-closed default: %s", got) + } +} + +func TestDecideQualityRetryLastWithholdIsMaxAttemptsMinusOne(t *testing.T) { + t.Parallel() + for _, maxAttempts := range []int{1, 2, 3, 6} { + last := maxAttempts - 1 + if got := DecideQualityRetry(QualityWithhold, last, maxAttempts, qualityRetryFailOpen); got != QualityActionDeliverLast { + t.Fatalf("fail-open last withhold max=%d index=%d got %s", maxAttempts, last, got) + } + if got := DecideQualityRetry(QualityWithhold, last, maxAttempts, qualityRetryFailClosed); got != QualityActionReject { + t.Fatalf("fail-closed last withhold max=%d index=%d got %s", maxAttempts, last, got) + } + if last > 0 { + if got := DecideQualityRetry(QualityWithhold, last-1, maxAttempts, qualityRetryFailOpen); got != QualityActionRetry { + t.Fatalf("pre-last should retry max=%d index=%d got %s", maxAttempts, last-1, got) + } + } + } +} + +func TestCommitQualityHold(t *testing.T) { + t.Parallel() + tests := []struct { + name string + verdict QualityVerdict + qualityAttempt int + maxAttempts int + hasNext bool + onExhausted string + wantAction QualityRetryAction + wantAudit bool + wantKeep bool + }{ + { + name: "first withhold + hasNext → Retry+Audit", + verdict: QualityWithhold, qualityAttempt: 0, maxAttempts: 2, hasNext: true, onExhausted: qualityRetryFailOpen, + wantAction: QualityActionRetry, wantAudit: true, wantKeep: false, + }, + { + name: "last withhold fail-open → DeliverLast+KeepBody", + verdict: QualityWithhold, qualityAttempt: 1, maxAttempts: 2, hasNext: true, onExhausted: qualityRetryFailOpen, + wantAction: QualityActionDeliverLast, wantAudit: false, wantKeep: true, + }, + { + name: "last withhold fail-closed → Reject+Audit", + verdict: QualityWithhold, qualityAttempt: 1, maxAttempts: 2, hasNext: true, onExhausted: qualityRetryFailClosed, + wantAction: QualityActionReject, wantAudit: true, wantKeep: false, + }, + { + name: "routing exhausted even at qualityAttempt=0 → not Retry", + verdict: QualityWithhold, qualityAttempt: 0, maxAttempts: 2, hasNext: false, onExhausted: qualityRetryFailOpen, + wantAction: QualityActionDeliverLast, wantAudit: false, wantKeep: true, + }, + { + name: "thinking delivers keep body", + verdict: QualityDeliver, qualityAttempt: 0, maxAttempts: 2, hasNext: true, onExhausted: qualityRetryFailOpen, + wantAction: QualityActionDeliver, wantAudit: false, wantKeep: true, + }, + { + name: "switch 5 times: attempt 4 of 6 still retries", + verdict: QualityWithhold, qualityAttempt: 4, maxAttempts: 6, hasNext: true, onExhausted: qualityRetryFailClosed, + wantAction: QualityActionRetry, wantAudit: true, wantKeep: false, + }, + { + name: "switch 5 times: attempt 5 of 6 fail-closed rejects no body", + verdict: QualityWithhold, qualityAttempt: 5, maxAttempts: 6, hasNext: true, onExhausted: qualityRetryFailClosed, + wantAction: QualityActionReject, wantAudit: true, wantKeep: false, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + got := CommitQualityHold(test.verdict, test.qualityAttempt, test.maxAttempts, test.hasNext, test.onExhausted) + if got.Action != test.wantAction || got.Audit != test.wantAudit || got.KeepBody != test.wantKeep { + t.Fatalf("CommitQualityHold() = %+v, want action=%s audit=%t keep=%t", got, test.wantAction, test.wantAudit, test.wantKeep) + } + if got.Action == QualityActionRetry && !test.hasNext { + t.Fatal("routing exhausted must not Retry") + } + }) + } +} + +func TestBoundQualityRetryWhenRoutingExhausted(t *testing.T) { + t.Parallel() + if got := BoundQualityRetry(QualityActionRetry, true, qualityRetryFailOpen); got != QualityActionRetry { + t.Fatalf("has next: %s", got) + } + if got := BoundQualityRetry(QualityActionRetry, false, qualityRetryFailOpen); got != QualityActionDeliverLast { + t.Fatalf("no next fail-open: %s", got) + } + if got := BoundQualityRetry(QualityActionRetry, false, qualityRetryFailClosed); got != QualityActionReject { + t.Fatalf("no next fail-closed: %s", got) + } + if got := BoundQualityRetry(QualityActionDeliverLast, false, qualityRetryFailOpen); got != QualityActionDeliverLast { + t.Fatalf("already last: %s", got) + } +} + +func TestSelectionSessionHasAvailableCandidate(t *testing.T) { + t.Parallel() + session := &selectionSession{ + values: []accountdomain.RoutingCandidate{ + {Credential: accountdomain.Credential{ID: 1}}, + {Credential: accountdomain.Credential{ID: 2}}, + {Credential: accountdomain.Credential{ID: 3}}, + }, + normalCandidates: []int{0, 1}, + probeCandidates: []int{2}, + staleCandidates: make(map[uint64]bool), + } + if !session.hasAvailableCandidate(map[uint64]bool{1: true}, false) { + t.Fatal("second normal account should be available") + } + if session.hasAvailableCandidate(map[uint64]bool{1: true, 2: true}, false) { + t.Fatal("routing attempt budget must not invent another normal account") + } + if !session.hasAvailableCandidate(map[uint64]bool{1: true, 2: true}, true) { + t.Fatal("quota probe should be available when allowed") + } + if session.hasAvailableCandidate(map[uint64]bool{1: true, 2: true, 3: true}, true) { + t.Fatal("fully excluded session should be exhausted") + } +} + +func sse(frames ...string) string { + var b strings.Builder + for _, frame := range frames { + b.WriteString(frame) + if !strings.HasSuffix(frame, "\n") { + b.WriteByte('\n') + } + if !strings.HasSuffix(frame, "\n\n") { + b.WriteByte('\n') + } + } + return b.String() +} + +func TestObserveQualityChunkThinkingChat(t *testing.T) { + t.Parallel() + state := qualityScanState{protocol: qualityProtocolChat} + ObserveQualityChunk(&state, []byte(sse( + ": grok2api-reasoning-start", + `data: {"choices":[{"delta":{"thinking_content":"plan the game"}}]}`, + `data: {"choices":[{"delta":{"content":"here is a game"}}]}`, + `data: {"usage":{"completion_tokens":80,"completion_tokens_details":{"reasoning_tokens":40}}}`, + "data: [DONE]", + ))) + sig := state.signals() + if !sig.HasThinking || !sig.Terminal || sig.ReasoningTokens != 40 { + t.Fatalf("thinking fixture signals = %#v", sig) + } + if ClassifyQualityHold(sig, 32) != QualityDeliver { + t.Fatalf("thinking fixture withheld") + } +} + +func TestObserveQualityChunkNoThinkEnoughChat(t *testing.T) { + t.Parallel() + state := qualityScanState{protocol: qualityProtocolChat} + content := strings.Repeat("word ", 40) // 200 runes → 50 tokens + ObserveQualityChunk(&state, []byte(sse( + `data: {"choices":[{"delta":{"content":"`+content+`"}}]}`, + `data: {"choices":[{"delta":{},"finish_reason":"stop"}]}`, + `data: {"usage":{"completion_tokens":50,"completion_tokens_details":{"reasoning_tokens":0}}}`, + "data: [DONE]", + ))) + sig := state.signals() + if sig.HasThinking || !sig.Terminal || sig.VisibleTokens < 32 { + t.Fatalf("no-think fixture signals = %#v", sig) + } + if ClassifyQualityHold(sig, 32) != QualityWithhold { + t.Fatalf("no-think enough should withhold, got %s (%#v)", ClassifyQualityHold(sig, 32), sig) + } +} + +func TestObserveQualityChunkShortNoThink(t *testing.T) { + t.Parallel() + state := qualityScanState{protocol: qualityProtocolChat} + ObserveQualityChunk(&state, []byte(sse( + `data: {"choices":[{"delta":{"content":"ok"}}]}`, + "data: [DONE]", + ))) + sig := state.signals() + if ClassifyQualityHold(sig, 32) != QualityDeliver { + t.Fatalf("short no-think should deliver, got %s (%#v)", ClassifyQualityHold(sig, 32), sig) + } +} + +func TestObserveQualityChunkResponsesReasoningItem(t *testing.T) { + t.Parallel() + state := qualityScanState{protocol: qualityProtocolResponses} + ObserveQualityChunk(&state, []byte(sse( + `data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`, + `data: {"type":"response.output_text.delta","delta":"hello"}`, + `data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`, + ))) + if ClassifyQualityHold(state.signals(), 32) != QualityDeliver { + t.Fatalf("responses reasoning item should deliver: %#v", state.signals()) + } +} + +func TestPeekQualityStreamThinkingDeliversRemainder(t *testing.T) { + t.Parallel() + body := io.NopCloser(strings.NewReader(sse( + `data: {"choices":[{"delta":{"thinking_content":"think"}}]}`, + `data: {"choices":[{"delta":{"content":"answer after think"}}]}`, + "data: [DONE]", + ))) + replay, verdict, _, _, err := peekQualityStream(context.Background(), body, qualityProtocolChat, QualityRetryRuntime{MinOutputTokens: 32, HoldTimeout: time.Second}) + if err != nil { + t.Fatal(err) + } + defer replay.Close() + if verdict != QualityDeliver { + t.Fatalf("verdict=%s", verdict) + } + got, _ := io.ReadAll(replay) + if !strings.Contains(string(got), "answer after think") || !strings.Contains(string(got), "thinking_content") { + t.Fatalf("replay lost frames: %s", got) + } +} + +func TestPeekQualityStreamWithholdsNoThinkEnough(t *testing.T) { + t.Parallel() + content := strings.Repeat("abcd", 16) // 64 runes → 16 tokens... need 32 tokens = 128 runes + content = strings.Repeat("abcd", 40) // 160 runes → 40 tokens + body := io.NopCloser(strings.NewReader(sse( + `data: {"choices":[{"delta":{"content":"`+content+`"}}]}`, + `data: {"usage":{"completion_tokens":40,"completion_tokens_details":{"reasoning_tokens":0}}}`, + "data: [DONE]", + ))) + replay, verdict, usage, _, err := peekQualityStream(context.Background(), body, qualityProtocolChat, QualityRetryRuntime{MinOutputTokens: 32, HoldTimeout: time.Second}) + if err != nil { + t.Fatal(err) + } + defer replay.Close() + if verdict != QualityWithhold { + t.Fatalf("verdict=%s usage=%#v", verdict, usage) + } + if usage.ReasoningTokens != 0 || usage.OutputTokens < 32 { + t.Fatalf("usage=%#v", usage) + } +} + +func TestPeekThenDecideQualityRetryBounded(t *testing.T) { + t.Parallel() + content := strings.Repeat("abcd", 40) + fixture := sse( + `data: {"choices":[{"delta":{"content":"`+content+`"}}]}`, + `data: {"usage":{"completion_tokens":40,"completion_tokens_details":{"reasoning_tokens":0}}}`, + "data: [DONE]", + ) + cfg := QualityRetryRuntime{MinOutputTokens: 32, MaxAttempts: 2, OnExhausted: qualityRetryFailOpen, HoldTimeout: time.Second} + + replay, verdict, usage, _, err := peekQualityStream(context.Background(), io.NopCloser(strings.NewReader(fixture)), qualityProtocolChat, cfg) + if err != nil { + t.Fatal(err) + } + defer replay.Close() + if verdict != QualityWithhold { + t.Fatalf("first peek verdict=%s usage=%#v", verdict, usage) + } + if got := DecideQualityRetry(verdict, 0, cfg.MaxAttempts, cfg.OnExhausted); got != QualityActionRetry { + t.Fatalf("first withhold action=%s", got) + } + + replay2, verdict2, _, _, err := peekQualityStream(context.Background(), io.NopCloser(strings.NewReader(fixture)), qualityProtocolChat, cfg) + if err != nil { + t.Fatal(err) + } + defer replay2.Close() + if verdict2 != QualityWithhold { + t.Fatalf("second peek verdict=%s", verdict2) + } + action2 := DecideQualityRetry(verdict2, 1, cfg.MaxAttempts, cfg.OnExhausted) + action2 = BoundQualityRetry(action2, false, cfg.OnExhausted) + if action2 != QualityActionDeliverLast { + t.Fatalf("second withhold fail-open action=%s", action2) + } + got, _ := io.ReadAll(replay2) + if !strings.Contains(string(got), content) { + t.Fatalf("fail-open must still deliver the last body, got %q", got) + } +} + +func TestPeekQualityStreamShortDelivers(t *testing.T) { + t.Parallel() + body := io.NopCloser(strings.NewReader(sse( + `data: {"choices":[{"delta":{"content":"hi"}}]}`, + "data: [DONE]", + ))) + replay, verdict, _, _, err := peekQualityStream(context.Background(), body, qualityProtocolChat, QualityRetryRuntime{MinOutputTokens: 32}) + if err != nil { + t.Fatal(err) + } + defer replay.Close() + if verdict != QualityDeliver { + t.Fatalf("short verdict=%s", verdict) + } +} + +func TestPeekQualityStreamHoldTimeoutInterruptsBlockedReadAndPreservesRemainder(t *testing.T) { + t.Parallel() + reader, writer := io.Pipe() + first := sse(`data: {"choices":[{"delta":{"content":"hi"}}]}`) + second := sse(`data: {"choices":[{"delta":{"content":" after timeout"}}]}`, "data: [DONE]") + writeErr := make(chan error, 1) + continueWrite := make(chan struct{}) + go func() { + if _, err := io.WriteString(writer, first); err != nil { + writeErr <- err + return + } + select { + case <-continueWrite: + case <-time.After(500 * time.Millisecond): + } + if _, err := io.WriteString(writer, second); err != nil { + writeErr <- err + return + } + writeErr <- writer.Close() + }() + + started := time.Now() + replay, verdict, _, _, err := peekQualityStream(context.Background(), reader, qualityProtocolChat, QualityRetryRuntime{ + MinOutputTokens: 32, + HoldTimeout: 30 * time.Millisecond, + }) + if err != nil { + t.Fatal(err) + } + defer replay.Close() + close(continueWrite) + if elapsed := time.Since(started); elapsed < 20*time.Millisecond || elapsed > 200*time.Millisecond { + t.Fatalf("peek returned after %s, want the 30ms hold timeout", elapsed) + } + if verdict != QualityDeliver { + t.Fatalf("short timed-out response verdict = %s", verdict) + } + body, err := io.ReadAll(replay) + if err != nil { + t.Fatal(err) + } + if err := <-writeErr; err != nil { + t.Fatal(err) + } + if got := string(body); !strings.Contains(got, "hi") || !strings.Contains(got, "after timeout") { + t.Fatalf("replay lost streamed bytes: %q", got) + } +} + +func TestPeekQualityStreamHoldTimeoutCoversBlockedFirstByte(t *testing.T) { + t.Parallel() + reader, writer := io.Pipe() + continueWrite := make(chan struct{}) + writeErr := make(chan error, 1) + go func() { + select { + case <-continueWrite: + case <-time.After(500 * time.Millisecond): + } + _, err := io.WriteString(writer, sse( + `data: {"choices":[{"delta":{"content":"late first byte"}}]}`, + "data: [DONE]", + )) + if closeErr := writer.Close(); err == nil { + err = closeErr + } + writeErr <- err + }() + + started := time.Now() + replay, verdict, _, _, err := peekQualityStream(context.Background(), reader, qualityProtocolChat, QualityRetryRuntime{ + MinOutputTokens: 32, + HoldTimeout: 30 * time.Millisecond, + }) + if err != nil { + t.Fatal(err) + } + defer replay.Close() + close(continueWrite) + if elapsed := time.Since(started); elapsed < 20*time.Millisecond || elapsed > 200*time.Millisecond { + t.Fatalf("first-byte hold returned after %s, want the 30ms timeout", elapsed) + } + if verdict != QualityDeliver { + t.Fatalf("empty timed-out prefix verdict = %s", verdict) + } + body, err := io.ReadAll(replay) + if err != nil { + t.Fatal(err) + } + if err := <-writeErr; err != nil { + t.Fatal(err) + } + if !strings.Contains(string(body), "late first byte") { + t.Fatalf("replay lost post-timeout first byte: %q", body) + } +} + +func TestShouldHoldQualityStreamGates(t *testing.T) { + t.Parallel() + cfg := QualityRetryRuntime{Enabled: true, MaxAttempts: 2, MinOutputTokens: 32} + route := modeldomain.Route{Provider: accountdomain.ProviderBuild, UpstreamModel: "grok-4.6", PublicID: "grok-4.6"} + input := Input{Streaming: true, PublicModel: "grok-4.6"} + if !shouldHoldQualityStream(input, nil, route, audit.OperationChat, cfg) { + t.Fatal("expected hold on thinking build chat") + } + off := cfg + off.Enabled = false + if shouldHoldQualityStream(input, nil, route, audit.OperationChat, off) { + t.Fatal("disabled must not hold") + } + forced := input + forced.ForcedEgressNodeID = 9 + if shouldHoldQualityStream(forced, nil, route, audit.OperationChat, cfg) { + t.Fatal("forced egress must not hold") + } + owned := inferencedomain.ResponseOwnership{ResponseID: "r1", AccountID: 1} + if shouldHoldQualityStream(input, &owned, route, audit.OperationChat, cfg) { + t.Fatal("pinned response must not hold") + } + if shouldHoldQualityStream(input, nil, route, audit.OperationImage, cfg) { + t.Fatal("image must not hold") + } + for _, test := range []struct { + name string + body string + }{ + {name: "chat reasoning none", body: `{"reasoning_effort":"none"}`}, + {name: "responses reasoning none", body: `{"reasoning":{"effort":"none"}}`}, + {name: "messages thinking disabled", body: `{"thinking":{"type":"disabled"}}`}, + {name: "messages zero thinking budget", body: `{"thinking":{"type":"enabled","budget_tokens":0}}`}, + {name: "client tools", body: `{"tools":[{"type":"function","function":{"name":"charge"}}]}`}, + {name: "legacy functions", body: `{"functions":[{"name":"charge"}]}`}, + } { + t.Run(test.name, func(t *testing.T) { + request := input + request.Body = []byte(test.body) + if shouldHoldQualityStream(request, nil, route, audit.OperationChat, cfg) { + t.Fatal("explicitly disabled reasoning and tool requests must not be held") + } + }) + } + toolCache := input + toolCache.Body = []byte(`{"messages":[{"role":"user","content":"hello"}]}`) + toolCache.AllowClientToolCacheRoute = true + if !shouldHoldQualityStream(toolCache, nil, route, audit.OperationChat, cfg) { + t.Fatal("client identity/cache compatibility alone must not disable the hold") + } +} + +func TestAttemptLoopQualityHold(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "quality-hold-loop.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accountRepo := relational.NewAccountRepository(database) + modelRepo := relational.NewModelRepository(database) + auditRepo := relational.NewAuditRepository(database) + responseRepo := relational.NewResponseRepository(database) + keyRepo := relational.NewClientKeyRepository(database) + + credentials := make([]accountdomain.Credential, 0, 2) + for index, name := range []string{"quality-a", "quality-b"} { + credential, _, createErr := accountRepo.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderBuild, Name: name, SourceKey: name, EncryptedAccessToken: name, + EncryptedRefreshToken: "refresh-" + name, ExpiresAt: time.Now().Add(time.Hour), + Enabled: true, AuthStatus: accountdomain.AuthStatusActive, Priority: 200 - index, MaxConcurrent: 1, + }) + if createErr != nil { + t.Fatal(createErr) + } + credentials = append(credentials, credential) + } + if err := modelRepo.UpsertDiscovered(ctx, accountdomain.ProviderBuild, []string{"grok-4.6"}); err != nil { + t.Fatal(err) + } + for _, credential := range credentials { + if err := modelRepo.ReplaceAccountCapabilities(ctx, credential.ID, []string{"grok-4.6"}, time.Now().UTC()); err != nil { + t.Fatal(err) + } + } + clientKey, err := keyRepo.Create(ctx, clientkey.Key{ + Name: "quality-loop-key", Prefix: "qhold", SecretHash: strings.Repeat("f", 64), EncryptedSecret: "encrypted", + Enabled: true, RPMLimit: 120, MaxConcurrent: 8, + }) + if err != nil { + t.Fatal(err) + } + + noThink := sse( + `data: {"choices":[{"delta":{"content":"`+strings.Repeat("abcd", 40)+`"}}]}`, + `data: {"usage":{"completion_tokens":40,"completion_tokens_details":{"reasoning_tokens":0}}}`, + "data: [DONE]", + ) + thinking := sse( + `data: {"choices":[{"delta":{"thinking_content":"plan the game"}}]}`, + `data: {"choices":[{"delta":{"content":"good game after retry"}}]}`, + `data: {"usage":{"completion_tokens":80,"completion_tokens_details":{"reasoning_tokens":40}}}`, + "data: [DONE]", + ) + adapter := &scriptedBuildAdapter{responses: map[uint64][]scriptedBuildResponse{ + credentials[0].ID: {{status: http.StatusOK, body: noThink}}, + credentials[1].ID: {{status: http.StatusOK, body: thinking}}, + }} + registry := provider.NewRegistry(adapter) + sticky := memory.NewStickyStore() + accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil) + selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute) + service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(nil, nil, nil, 60, 4, nil), registry, selector, responseRepo, 3) + service.UpdateQualityRetry(QualityRetryRuntime{Enabled: true, MaxAttempts: 2, MinOutputTokens: 32, OnExhausted: qualityRetryFailOpen, HoldTimeout: time.Second}) + + result, err := service.CreateChatCompletion(ctx, Input{ + RequestID: "req-quality-hold", ClientKey: clientKey, PublicModel: "grok-4.6", Streaming: true, + Body: []byte(`{"model":"grok-4.6","messages":[{"role":"user","content":"write a game"}],"stream":true}`), + }) + if err != nil { + t.Fatalf("attempt loop should deliver after withhold retry, err=%v", err) + } + if result.StatusCode != http.StatusOK { + t.Fatalf("status = %d", result.StatusCode) + } + body, _ := io.ReadAll(result.Body) + result.Finalize(Usage{Reported: true, OutputTokens: 80, ReasoningTokens: 40}, "chat-ok", "") + _ = result.Body.Close() + if !strings.Contains(string(body), "good game after retry") || !strings.Contains(string(body), "thinking_content") { + t.Fatalf("client must receive the second attempt body, got %s", body) + } + if strings.Contains(string(body), strings.Repeat("abcd", 40)) { + t.Fatal("first no-think body must not be delivered") + } + attempts := adapter.Attempts() + if len(attempts) != 2 || attempts[0] != credentials[0].ID || attempts[1] != credentials[1].ID { + t.Fatalf("expected account exclude+retry, attempts=%#v want [%d %d]", attempts, credentials[0].ID, credentials[1].ID) + } + logs, total, err := auditRepo.List(ctx, 0, 20) + if err != nil { + t.Fatal(err) + } + var degraded, delivered bool + for _, rec := range logs { + if rec.ErrorCode == ErrorQualityDegraded && rec.AccountID != nil && *rec.AccountID == credentials[0].ID { + degraded = true + } + if rec.RequestID == "req-quality-hold" && rec.ErrorCode == "" && rec.StatusCode == http.StatusOK { + delivered = true + } + } + if !degraded { + t.Fatalf("first withhold must write quality_degraded, audits=%d total=%d", len(logs), total) + } + if !delivered { + t.Fatalf("final delivered attempt missing from audits, total=%d", total) + } +} + +func TestAttemptLoopQualityHoldFailOpenKeepsSingleAccountBody(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "quality-hold-single.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accountRepo := relational.NewAccountRepository(database) + modelRepo := relational.NewModelRepository(database) + auditRepo := relational.NewAuditRepository(database) + responseRepo := relational.NewResponseRepository(database) + keyRepo := relational.NewClientKeyRepository(database) + + credential, _, err := accountRepo.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderBuild, Name: "quality-only", SourceKey: "quality-only", + EncryptedAccessToken: "quality-only", EncryptedRefreshToken: "refresh-quality-only", + ExpiresAt: time.Now().Add(time.Hour), Enabled: true, AuthStatus: accountdomain.AuthStatusActive, + Priority: 200, MaxConcurrent: 1, + }) + if err != nil { + t.Fatal(err) + } + if err := modelRepo.UpsertDiscovered(ctx, accountdomain.ProviderBuild, []string{"grok-4.6"}); err != nil { + t.Fatal(err) + } + if err := modelRepo.ReplaceAccountCapabilities(ctx, credential.ID, []string{"grok-4.6"}, time.Now().UTC()); err != nil { + t.Fatal(err) + } + clientKey, err := keyRepo.Create(ctx, clientkey.Key{ + Name: "quality-single-key", Prefix: "qsingle", SecretHash: strings.Repeat("e", 64), EncryptedSecret: "encrypted", + Enabled: true, RPMLimit: 120, MaxConcurrent: 8, + }) + if err != nil { + t.Fatal(err) + } + + content := strings.Repeat("abcd", 40) + noThink := sse( + `data: {"choices":[{"delta":{"content":"`+content+`"}}]}`, + `data: {"usage":{"completion_tokens":40,"completion_tokens_details":{"reasoning_tokens":0}}}`, + "data: [DONE]", + ) + adapter := &scriptedBuildAdapter{responses: map[uint64][]scriptedBuildResponse{ + credential.ID: {{status: http.StatusOK, body: noThink}}, + }} + registry := provider.NewRegistry(adapter) + sticky := memory.NewStickyStore() + accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil) + selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute) + service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(nil, nil, nil, 60, 4, nil), registry, selector, responseRepo, 999) + service.UpdateQualityRetry(QualityRetryRuntime{ + Enabled: true, MaxAttempts: 6, MinOutputTokens: 32, OnExhausted: qualityRetryFailOpen, HoldTimeout: time.Second, + }) + + result, err := service.CreateChatCompletion(ctx, Input{ + RequestID: "req-quality-single", ClientKey: clientKey, PublicModel: "grok-4.6", Streaming: true, + Body: []byte(`{"model":"grok-4.6","messages":[{"role":"user","content":"write a game"}],"stream":true}`), + }) + if err != nil { + t.Fatalf("fail-open should deliver the only account body, err=%v", err) + } + body, err := io.ReadAll(result.Body) + if err != nil { + t.Fatal(err) + } + result.Finalize(Usage{Reported: true, OutputTokens: 40}, "chat-single", "") + _ = result.Body.Close() + if !strings.Contains(string(body), content) { + t.Fatalf("fail-open lost the held body: %s", body) + } + if attempts := adapter.Attempts(); len(attempts) != 1 || attempts[0] != credential.ID { + t.Fatalf("single-account pool must not enter a fake retry, attempts=%#v", attempts) + } +} + +func TestAttemptLoopQualityFailOpenFallbackAndTotalAttemptCap(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "quality-hold-fallback.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accountRepo := relational.NewAccountRepository(database) + modelRepo := relational.NewModelRepository(database) + auditRepo := relational.NewAuditRepository(database) + responseRepo := relational.NewResponseRepository(database) + keyRepo := relational.NewClientKeyRepository(database) + + credentials := make([]accountdomain.Credential, 0, 7) + for index := 0; index < 7; index++ { + name := fmt.Sprintf("quality-fallback-%d", index) + credential, _, createErr := accountRepo.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderBuild, Name: name, SourceKey: name, + EncryptedAccessToken: name, EncryptedRefreshToken: "refresh-" + name, + ExpiresAt: time.Now().Add(time.Hour), Enabled: true, AuthStatus: accountdomain.AuthStatusActive, + Priority: 300 - index, MaxConcurrent: 1, + }) + if createErr != nil { + t.Fatal(createErr) + } + credentials = append(credentials, credential) + } + if err := modelRepo.UpsertDiscovered(ctx, accountdomain.ProviderBuild, []string{"grok-4.6"}); err != nil { + t.Fatal(err) + } + for _, credential := range credentials { + if err := modelRepo.ReplaceAccountCapabilities(ctx, credential.ID, []string{"grok-4.6"}, time.Now().UTC()); err != nil { + t.Fatal(err) + } + } + clientKey, err := keyRepo.Create(ctx, clientkey.Key{ + Name: "quality-fallback-key", Prefix: "qfallback", SecretHash: strings.Repeat("d", 64), EncryptedSecret: "encrypted", + Enabled: true, RPMLimit: 120, MaxConcurrent: 8, + }) + if err != nil { + t.Fatal(err) + } + + content := strings.Repeat("fallback", 24) + responses := make(map[uint64][]scriptedBuildResponse, len(credentials)) + responses[credentials[0].ID] = []scriptedBuildResponse{{status: http.StatusOK, body: sse( + `data: {"choices":[{"delta":{"content":"`+content+`"}}]}`, + `data: {"usage":{"completion_tokens":48,"completion_tokens_details":{"reasoning_tokens":0}}}`, + "data: [DONE]", + )}} + for _, credential := range credentials[1:] { + responses[credential.ID] = []scriptedBuildResponse{{status: http.StatusInternalServerError, body: `{"error":"temporary"}`}} + } + adapter := &scriptedBuildAdapter{responses: responses} + registry := provider.NewRegistry(adapter) + sticky := memory.NewStickyStore() + accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil) + selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute) + service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(nil, nil, nil, 60, 4, nil), registry, selector, responseRepo, 999) + service.UpdateQualityRetry(QualityRetryRuntime{ + Enabled: true, MaxAttempts: 6, MinOutputTokens: 32, OnExhausted: qualityRetryFailOpen, HoldTimeout: time.Second, + }) + + result, err := service.CreateChatCompletion(ctx, Input{ + RequestID: "req-quality-fallback", ClientKey: clientKey, PublicModel: "grok-4.6", Streaming: true, + Body: []byte(`{"model":"grok-4.6","messages":[{"role":"user","content":"write a game"}],"stream":true}`), + }) + if err != nil { + t.Fatalf("fail-open should return the retained response after later failures: %v", err) + } + body, err := io.ReadAll(result.Body) + if err != nil { + t.Fatal(err) + } + result.Finalize(Usage{Reported: true, OutputTokens: 48}, "chat-fallback", "") + _ = result.Body.Close() + if !strings.Contains(string(body), content) { + t.Fatalf("retained fail-open response was lost: %s", body) + } + if attempts := adapter.Attempts(); len(attempts) != 6 || attempts[0] != credentials[0].ID { + t.Fatalf("requestRetry must cap real account attempts at 6, attempts=%#v", attempts) + } + logs, _, err := auditRepo.List(ctx, 0, 50) + if err != nil { + t.Fatal(err) + } + for _, record := range logs { + if record.ErrorCode == ErrorQualityDegraded && record.AccountID != nil && *record.AccountID == credentials[0].ID { + t.Fatal("the delivered fallback must not be audited as a discarded quality attempt") + } + } +} + +func TestNormalizeQualityRetryDefaults(t *testing.T) { + t.Parallel() + got := normalizeQualityRetry(QualityRetryRuntime{Enabled: true}) + if !got.Enabled || got.MaxAttempts != 6 || got.MinOutputTokens != 32 || got.OnExhausted != qualityRetryFailClosed || got.HoldTimeout != 3*time.Second { + t.Fatalf("defaults = %#v", got) + } +} diff --git a/backend/internal/application/gateway/selector_session.go b/backend/internal/application/gateway/selector_session.go index 3a6181a5..37682d89 100644 --- a/backend/internal/application/gateway/selector_session.go +++ b/backend/internal/application/gateway/selector_session.go @@ -359,6 +359,27 @@ func (session *selectionSession) hasUnexcludedNormal(excluded map[uint64]bool) b return false } +// hasAvailableCandidate reports whether this request-level snapshot still has +// an account the quality retry is allowed to switch to. This is deliberately +// stronger than checking the routing attempt counter: a large attempt budget +// does not imply that another account exists. +func (session *selectionSession) hasAvailableCandidate(excluded map[uint64]bool, allowQuotaProbe bool) bool { + if session == nil { + return false + } + if session.hasUnexcludedNormal(excluded) { + return true + } + if allowQuotaProbe { + for _, index := range session.probeCandidates { + if !session.candidateExcluded(excluded, session.values[index].Credential.ID) { + return true + } + } + } + return false +} + func (session *selectionSession) unexcludedNormalIndexes(excluded map[uint64]bool) []int { if len(excluded) == 0 && len(session.staleCandidates) == 0 { return session.normalCandidates diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index 05e2261f..666bb7bd 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -205,6 +205,7 @@ type Service struct { modelSyncMu sync.Mutex modelSyncing map[uint64]struct{} markBuildChatDeniedAsReauth atomic.Bool + qualityRetry atomic.Pointer[QualityRetryRuntime] } type teamModelRateLimit struct { @@ -994,18 +995,25 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string excluded := make(map[uint64]bool) failureFingerprints := make(map[string]int) authRecoveryAttempted := make(map[uint64]bool) + holdCfg := s.qualityRetryConfig() + qualityHoldEnabled := shouldHoldQualityStream(input, ownership, route, operation, holdCfg) + // Count accounts that actually reached the upstream. Credential-only skips + // do not consume the quality retry budget; refreshes stay on the same account. + qualityAccountAttempts := 0 quotaMode := s.providers.QuotaMode(route.Provider, route.UpstreamModel) quotaProbeAttempted := false selection := preselectedSession var lastErr error var lastFailure *UpstreamFailure failureAttempts := newFailureAttemptRecorder(http.MethodPost, path) + normalizedMetadata := &provider.NormalizedRequestMetadata{} responseStartedAt := startedAt forwardResponse := func(lease *accountLease, credential accountdomain.Credential, billing *accountdomain.Billing) (*provider.Response, error) { started := time.Now() responseStartedAt = started lease.markSelectorUpstreamStarted() - response, err := adapter.ForwardResponse(physicalCallCtx, provider.ResponseResourceRequest{Credential: credential, ForcedEgressNodeID: input.ForcedEgressNodeID, Billing: billing, Method: http.MethodPost, Path: path, Model: route.UpstreamModel, PromptCacheKey: input.PromptCacheKey, ReasoningReplayKey: reasoningReplayKey, AllowClientToolCacheRoute: input.AllowClientToolCacheRoute, GrokTurnIndex: input.GrokTurnIndex, IdempotencyID: idempotencyID, Body: input.Body, Streaming: input.Streaming, NormalizeBody: true, Operation: string(operation)}) + response, err := adapter.ForwardResponse(physicalCallCtx, provider.ResponseResourceRequest{Credential: credential, ForcedEgressNodeID: input.ForcedEgressNodeID, Billing: billing, Method: http.MethodPost, Path: path, Model: route.UpstreamModel, PromptCacheKey: input.PromptCacheKey, ReasoningReplayKey: reasoningReplayKey, AllowClientToolCacheRoute: input.AllowClientToolCacheRoute, GrokTurnIndex: input.GrokTurnIndex, IdempotencyID: idempotencyID, Body: input.Body, Streaming: input.Streaming, NormalizeBody: true, Operation: string(operation), NormalizedMetadata: normalizedMetadata}) + auditBase.ReasoningEffort = normalizedMetadata.ReasoningEffort err = failureAttempts.captureResponse(credential, started, response, err) timing.markUpstream(time.Since(started)) return response, err @@ -1017,8 +1025,151 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string timing.markCredential(time.Since(started)) return result, err } + handoffResponse := func(response *provider.Response, lease *accountLease, credential accountdomain.Credential, upstreamStartedAt time.Time) *Result { + accountID := credential.ID + var once sync.Once + finalize := func(usage Usage, responseID, errorCode string) { + once.Do(func() { + // HTTP 状态码保留线上真实值;流在 2xx 响应头之后失败时由 errorCode + // 决定最终结果,避免把协议状态与业务结果混为一谈。 + successful := auditRequestSucceeded(response.StatusCode, errorCode) + lease.completeSelectorObservation(successful) + budget := newFinalizationBudget(string(operation), string(route.Provider)) + if isUpstreamStreamFailure(errorCode) { + if err := budget.run("account_health", finalizationHealthBudget, func(stageCtx context.Context) error { + return s.selector.MarkFailureAfterSuccess(stageCtx, credential, 0, 0) + }); err != nil { + s.logger.Warn("stream_failure_health_write_failed", "account_id", credential.ID, "provider", credential.Provider, "error", err) + } + } + lease.Release() + now := time.Now().UTC() + record := auditBase + if usage.Reported { + record.UsageSource = usageSource + } + record.AccountID = &accountID + record.AccountName = credential.Name + record.StatusCode = response.StatusCode + record.InputTokens = usage.InputTokens + record.CachedInputTokens = usage.CachedInputTokens + record.OutputTokens = usage.OutputTokens + record.ReasoningTokens = usage.ReasoningTokens + record.TotalTokens = usage.TotalTokens + record.CostInUSDTicks = usage.CostInUSDTicks + imagePricing, imagePriced := audit.EstimateOfficialImageCost(pricingModel, "", "", response.QuotaUnits) + if imagePriced { + record.MediaOutputImages = int64(max(0, response.QuotaUnits)) + } + tokenPricing, tokenPriced := audit.EstimateOfficialCost(pricingModel, usage.InputTokens, usage.CachedInputTokens, usage.OutputTokens, usage.ContextInputTokens) + if successful && imagePriced { + record.EstimatedCostInUSDTicks = imagePricing.CostInUSDTicks + record.PricingModel = imagePricing.Model + record.PricingVersion = audit.OfficialPricingAsOf + } else if tokenPriced { + record.EstimatedCostInUSDTicks = tokenPricing.CostInUSDTicks + record.PricingModel = tokenPricing.Model + record.PricingVersion = audit.OfficialPricingAsOf + } + record.NumSourcesUsed = usage.NumSourcesUsed + record.NumServerSideToolsUsed = usage.NumServerSideToolsUsed + record.ContextInputTokens = usage.ContextInputTokens + record.ContextOutputTokens = usage.ContextOutputTokens + if successful && input.Streaming { + record.FirstTokenMS = firstToken.milliseconds() + } + record.DurationMS = time.Since(startedAt).Milliseconds() + record.ErrorCode = errorCode + attempts := failureAttempts.snapshot() + if !successful || len(attempts) > 0 { + record.Attempts = attempts + } + record.CreatedAt = now + applyAuditEgress(&record, egressTrace, route.Provider) + if supportsStoredResponses && operation == audit.OperationResponses && responseID != "" && successful { + err := budget.run("response_ownership", finalizationOwnershipBudget, func(stageCtx context.Context) error { + return s.responses.Save(stageCtx, inferencedomain.ResponseOwnership{ResponseID: responseID, AccountID: accountID, ClientKeyID: input.ClientKey.ID, ModelRouteID: route.ID, Provider: route.Provider, PromptCacheKey: ownershipPromptCacheKey, ReasoningReplayKey: reasoningReplayKey, ExpiresAt: now.Add(responseOwnershipTTL), CreatedAt: now, UpdatedAt: now}) + }) + if err != nil { + s.logger.Error("response_ownership_save_failed", "response_id", responseID, "client_key_id", input.ClientKey.ID, "account_id", accountID, "provider", route.Provider, "error", err) + } + } + if successful && lease.QuotaMode != "" { + if lease.QuotaMode != "weekly" { + units := max(1, response.QuotaUnits) + var updated bool + err := budget.run("quota_decrement", finalizationQuotaBudget, func(stageCtx context.Context) error { + var decrementErr error + updated, decrementErr = s.accounts.DecrementQuota(stageCtx, accountID, lease.QuotaMode, units) + return decrementErr + }) + if err != nil { + s.logger.Warn("provider_quota_decrement_failed", "provider", credential.Provider, "account_id", accountID, "mode", lease.QuotaMode, "units", units, "error", err) + } else if updated { + s.selector.ConsumeQuota(credential.Provider, accountID, lease.QuotaMode, units) + } + } + } + if err := budget.run("audit", finalizationAuditBudget, func(stageCtx context.Context) error { + return s.audits.Create(stageCtx, record) + }); err != nil { + s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", input.RequestID, "error", err) + } + if usage.ResponseModel != "" { + _ = budget.run("observed_model", finalizationMetadataBudget, func(stageCtx context.Context) error { + return s.accounts.ObserveResponseModel(stageCtx, accountID, usage.ResponseModel) + }) + } + if successful && lease.QuotaMode != "" { + if quotaKind, _ := s.providers.QuotaKind(credential.Provider); quotaKind == provider.QuotaRemoteWindow { + s.accounts.QueueQuotaRefresh(accountID, lease.QuotaMode) + } + } + outcome := "failed" + if successful { + outcome = "success" + } + timing.finish(s.logger, outcome) + }) + } + response.Body = &firstByteReadCloser{ReadCloser: response.Body, mark: timing.markFirstBody} + recordStreamFailure := func(diagnostic StreamFailureDiagnostic) { + failureAttempts.captureStreamFailure(credential, upstreamStartedAt, response, diagnostic) + } + var markFirstToken func() + if firstToken != nil { + markFirstToken = firstToken.mark + } + timingHandedOff = true + return &Result{StatusCode: response.StatusCode, Status: response.Status, Header: response.Header, Body: &finalizingBody{ReadCloser: response.Body, finalize: func() { finalize(Usage{}, "", "stream_closed") }}, MarkFirstToken: markFirstToken, RecordStreamFailure: recordStreamFailure, Finalize: finalize} + } + // fail_open retains at most one successful no-thinking stream. The account + // lease is released immediately; the read pump applies upstream backpressure + // until this response is either delivered or replaced by a better one. + type qualityFallback struct { + response *provider.Response + lease *accountLease + credential accountdomain.Credential + usage Usage + upstreamStartedAt time.Time + } + var fallback *qualityFallback + discardFallback := func(recordDegraded bool) { + if fallback == nil { + return + } + if recordDegraded { + s.recordQualityDegraded(ctx, auditBase, fallback.credential, fallback.usage, startedAt, egressTrace, route.Provider) + failureAttempts.captureQualityDegraded(fallback.credential, fallback.upstreamStartedAt) + } + _ = fallback.response.Body.Close() + fallback = nil + } attemptLoop: for attempt := 0; attemptPolicy.allows(attempt); attempt++ { + if qualityHoldEnabled && qualityAccountAttempts >= holdCfg.MaxAttempts { + break + } var lease *accountLease var err error selectionStarted := time.Now() @@ -1082,6 +1233,9 @@ attemptLoop: lastFailure = newCredentialUpstreamFailure(err, lease.Credential.ID, lease.Credential.Name) continue } + if qualityHoldEnabled { + qualityAccountAttempts++ + } response, err := forwardResponse(lease, credential, lease.Billing) if err != nil { lease.Release() @@ -1337,6 +1491,74 @@ attemptLoop: } if response.StatusCode >= 200 && response.StatusCode < 300 { s.selector.markSuccess(ctx, credential, lease.QuotaProbe) + if qualityHoldEnabled { + replay, verdict, peekUsage, _, peekErr := peekQualityStream(ctx, response.Body, qualityProtocolForOperation(operation), holdCfg) + if peekErr != nil { + if replay != nil { + _ = replay.Close() + } else { + _ = response.Body.Close() + } + lease.Release() + lastErr = peekErr + if ctx.Err() != nil || errors.Is(peekErr, context.Canceled) { + lastFailure = &UpstreamFailure{HTTPStatus: 499, Code: "request_canceled", PublicMessage: "请求已取消", AccountID: credential.ID, AccountName: credential.Name, Cause: firstError(ctx.Err(), peekErr)} + break + } + lastFailure = newTransportUpstreamFailure(peekErr, credential.ID, credential.Name) + continue + } + response.Body = replay + hasNextAccount := attemptPolicy.hasNext(attempt) && selection.hasAvailableCandidate(excluded, !quotaProbeAttempted) + hasNextAccount = hasNextAccount && qualityAccountAttempts < holdCfg.MaxAttempts + commit := CommitQualityHold(verdict, qualityAccountAttempts-1, holdCfg.MaxAttempts, hasNextAccount, holdCfg.OnExhausted) + deferFailOpenAudit := commit.Action == QualityActionRetry && holdCfg.OnExhausted == qualityRetryFailOpen + if commit.Audit && !deferFailOpenAudit { + s.recordQualityDegraded(ctx, auditBase, credential, peekUsage, startedAt, egressTrace, route.Provider) + failureAttempts.captureQualityDegraded(credential, responseStartedAt) + } + switch commit.Action { + case QualityActionRetry: + if deferFailOpenAudit { + discardFallback(true) + fallback = &qualityFallback{response: response, lease: lease, credential: credential, usage: peekUsage, upstreamStartedAt: responseStartedAt} + lease.completeSelectorObservation(true) + lease.Release() + } else { + _ = response.Body.Close() + lease.Release() + } + lastErr = errQualityDegraded + lastFailure = &UpstreamFailure{ + HTTPStatus: http.StatusServiceUnavailable, Code: ErrorQualityDegraded, + PublicMessage: "上游响应缺少推理", AccountID: credential.ID, AccountName: credential.Name, + Cause: errQualityDegraded, + } + s.logger.Info("quality_degraded_retry", "request_id", input.RequestID, "account_id", credential.ID, "quality_attempt", qualityAccountAttempts, "output_tokens", peekUsage.OutputTokens) + continue + case QualityActionReject: + _ = response.Body.Close() + lease.Release() + lastErr = errQualityDegraded + lastFailure = &UpstreamFailure{ + HTTPStatus: http.StatusServiceUnavailable, Code: ErrorQualityDegraded, + PublicMessage: "上游响应缺少推理", AccountID: credential.ID, AccountName: credential.Name, + Cause: errQualityDegraded, + } + s.logger.Info("quality_degraded_rejected", "request_id", input.RequestID, "account_id", credential.ID) + break attemptLoop + case QualityActionDeliverLast: + discardFallback(true) + s.logger.Info("quality_degraded_deliver_last", "request_id", input.RequestID, "account_id", credential.ID, "quality_attempt", qualityAccountAttempts, "output_tokens", peekUsage.OutputTokens) + case QualityActionDeliver: + discardFallback(true) + } + if !commit.KeepBody { + _ = response.Body.Close() + lease.Release() + break attemptLoop + } + } if diagnostic := response.RecoveredPrimaryFailure; diagnostic != nil { recoveredFailure := newHTTPUpstreamFailure(diagnostic.StatusCode, diagnostic.Body, credential.ID, credential.Name) if recoveredFailure.AccountBlocked || (credential.Provider == accountdomain.ProviderBuild && s.shouldInvalidateBuildForbidden(recoveredFailure)) { @@ -1347,122 +1569,25 @@ attemptLoop: } } } - accountID := credential.ID - var once sync.Once - finalize := func(usage Usage, responseID, errorCode string) { - once.Do(func() { - // HTTP 状态码保留线上真实值;流在 2xx 响应头之后失败时由 errorCode - // 决定最终结果,避免把协议状态与业务结果混为一谈。 - successful := auditRequestSucceeded(response.StatusCode, errorCode) - lease.completeSelectorObservation(successful) - budget := newFinalizationBudget(string(operation), string(route.Provider)) - if isUpstreamStreamFailure(errorCode) { - if err := budget.run("account_health", finalizationHealthBudget, func(stageCtx context.Context) error { - return s.selector.MarkFailureAfterSuccess(stageCtx, credential, 0, 0) - }); err != nil { - s.logger.Warn("stream_failure_health_write_failed", "account_id", credential.ID, "provider", credential.Provider, "error", err) - } - } - lease.Release() - now := time.Now().UTC() - record := auditBase - if usage.Reported { - record.UsageSource = usageSource - } - record.AccountID = &accountID - record.AccountName = credential.Name - record.StatusCode = response.StatusCode - record.InputTokens = usage.InputTokens - record.CachedInputTokens = usage.CachedInputTokens - record.OutputTokens = usage.OutputTokens - record.ReasoningTokens = usage.ReasoningTokens - record.TotalTokens = usage.TotalTokens - record.CostInUSDTicks = usage.CostInUSDTicks - imagePricing, imagePriced := audit.EstimateOfficialImageCost(pricingModel, "", "", response.QuotaUnits) - if imagePriced { - record.MediaOutputImages = int64(max(0, response.QuotaUnits)) - } - tokenPricing, tokenPriced := audit.EstimateOfficialCost(pricingModel, usage.InputTokens, usage.CachedInputTokens, usage.OutputTokens, usage.ContextInputTokens) - if successful && imagePriced { - record.EstimatedCostInUSDTicks = imagePricing.CostInUSDTicks - record.PricingModel = imagePricing.Model - record.PricingVersion = audit.OfficialPricingAsOf - } else if tokenPriced { - record.EstimatedCostInUSDTicks = tokenPricing.CostInUSDTicks - record.PricingModel = tokenPricing.Model - record.PricingVersion = audit.OfficialPricingAsOf - } - record.NumSourcesUsed = usage.NumSourcesUsed - record.NumServerSideToolsUsed = usage.NumServerSideToolsUsed - record.ContextInputTokens = usage.ContextInputTokens - record.ContextOutputTokens = usage.ContextOutputTokens - if successful && input.Streaming { - record.FirstTokenMS = firstToken.milliseconds() - } - record.DurationMS = time.Since(startedAt).Milliseconds() - record.ErrorCode = errorCode - attempts := failureAttempts.snapshot() - if !successful || len(attempts) > 0 { - record.Attempts = attempts - } - record.CreatedAt = now - applyAuditEgress(&record, egressTrace, route.Provider) - if supportsStoredResponses && operation == audit.OperationResponses && responseID != "" && successful { - err := budget.run("response_ownership", finalizationOwnershipBudget, func(stageCtx context.Context) error { - return s.responses.Save(stageCtx, inferencedomain.ResponseOwnership{ResponseID: responseID, AccountID: accountID, ClientKeyID: input.ClientKey.ID, ModelRouteID: route.ID, Provider: route.Provider, PromptCacheKey: ownershipPromptCacheKey, ReasoningReplayKey: reasoningReplayKey, ExpiresAt: now.Add(responseOwnershipTTL), CreatedAt: now, UpdatedAt: now}) - }) - if err != nil { - s.logger.Error("response_ownership_save_failed", "response_id", responseID, "client_key_id", input.ClientKey.ID, "account_id", accountID, "provider", route.Provider, "error", err) - } - } - if successful && lease.QuotaMode != "" { - if lease.QuotaMode != "weekly" { - units := max(1, response.QuotaUnits) - var updated bool - err := budget.run("quota_decrement", finalizationQuotaBudget, func(stageCtx context.Context) error { - var decrementErr error - updated, decrementErr = s.accounts.DecrementQuota(stageCtx, accountID, lease.QuotaMode, units) - return decrementErr - }) - if err != nil { - s.logger.Warn("provider_quota_decrement_failed", "provider", credential.Provider, "account_id", accountID, "mode", lease.QuotaMode, "units", units, "error", err) - } else if updated { - s.selector.ConsumeQuota(credential.Provider, accountID, lease.QuotaMode, units) - } - } - } - if err := budget.run("audit", finalizationAuditBudget, func(stageCtx context.Context) error { - return s.audits.Create(stageCtx, record) - }); err != nil { - s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", input.RequestID, "error", err) - } - if usage.ResponseModel != "" { - _ = budget.run("observed_model", finalizationMetadataBudget, func(stageCtx context.Context) error { - return s.accounts.ObserveResponseModel(stageCtx, accountID, usage.ResponseModel) - }) - } - if successful && lease.QuotaMode != "" { - if quotaKind, _ := s.providers.QuotaKind(credential.Provider); quotaKind == provider.QuotaRemoteWindow { - s.accounts.QueueQuotaRefresh(accountID, lease.QuotaMode) - } - } - outcome := "failed" - if successful { - outcome = "success" - } - timing.finish(s.logger, outcome) - }) + if fallback != nil && holdCfg.OnExhausted == qualityRetryFailOpen { + _ = response.Body.Close() + lease.completeSelectorObservation(false) + lease.Release() + selected := fallback + fallback = nil + s.logger.Info("quality_degraded_fallback", "request_id", input.RequestID, "account_id", selected.credential.ID, "quality_attempts", qualityAccountAttempts) + return handoffResponse(selected.response, selected.lease, selected.credential, selected.upstreamStartedAt), nil } - response.Body = &firstByteReadCloser{ReadCloser: response.Body, mark: timing.markFirstBody} - recordStreamFailure := func(diagnostic StreamFailureDiagnostic) { - failureAttempts.captureStreamFailure(credential, responseStartedAt, response, diagnostic) + return handoffResponse(response, lease, credential, responseStartedAt), nil + } + if fallback != nil { + if ctx.Err() == nil && holdCfg.OnExhausted == qualityRetryFailOpen { + selected := fallback + fallback = nil + s.logger.Info("quality_degraded_fallback", "request_id", input.RequestID, "account_id", selected.credential.ID, "quality_attempts", qualityAccountAttempts) + return handoffResponse(selected.response, selected.lease, selected.credential, selected.upstreamStartedAt), nil } - var markFirstToken func() - if firstToken != nil { - markFirstToken = firstToken.mark - } - timingHandedOff = true - return &Result{StatusCode: response.StatusCode, Status: response.Status, Header: response.Header, Body: &finalizingBody{ReadCloser: response.Body, finalize: func() { finalize(Usage{}, "", "stream_closed") }}, MarkFirstToken: markFirstToken, RecordStreamFailure: recordStreamFailure, Finalize: finalize}, nil + discardFallback(true) } if lastFailure != nil { record := auditBase diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index 6be8cc6c..f161c727 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -191,8 +191,9 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) { adapter := &failoverAdapter{ firstID: first.ID, failureStatus: http.StatusPaymentRequired, - failureBody: `{"code":"personal-team-blocked:spending-limit","error":"You have run out of credits"}`, - failureHeader: http.Header{"X-Should-Retry": {"false"}}, + failureBody: `{"code":"personal-team-blocked:spending-limit","error":"You have run out of credits"}`, + failureHeader: http.Header{"X-Should-Retry": {"false"}}, + reasoningEffort: "high", } registry := provider.NewRegistry(adapter) cipher := testCipher(t) @@ -202,7 +203,7 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) { clientService := clientkeyapp.NewService(nil, nil, nil, 60, 4, nil) selector := NewSelector(accountRepo, concurrency, sticky, registry, time.Hour, time.Second, time.Minute) service := NewService(modelRepo, auditRepo, accountService, clientService, registry, selector, responseRepo, 3) - result, err := service.CreateResponse(ctx, Input{RequestID: "req-1", ClientKey: clientKey, PublicModel: "grok-test", Body: []byte(`{"model":"grok-test"}`), PromptCacheSeed: "claude-session", GrokTurnIndex: "3"}) + result, err := service.CreateResponse(ctx, Input{RequestID: "req-1", ClientKey: clientKey, PublicModel: "grok-test", Body: []byte(`{"model":"grok-test","reasoning":{"effort":"high"}}`), PromptCacheSeed: "claude-session", GrokTurnIndex: "3"}) if err != nil { t.Fatal(err) } @@ -237,7 +238,7 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) { t.Fatalf("observed account = %#v, err = %v", observedAccount, err) } logs, total, err := auditRepo.List(ctx, 0, 10) - if err != nil || total != 1 || logs[0].AccountID == nil || *logs[0].AccountID != second.ID || logs[0].ClientKeyName != "test-key" || logs[0].ModelPublicID != "grok-test" || logs[0].ModelUpstreamModel != "Build/grok-test" || logs[0].AccountName != "second" || logs[0].CachedInputTokens != 80 || logs[0].UsageSource != audit.UsageSourceUpstream || logs[0].StatusCode != http.StatusOK || logs[0].AttemptCount != 1 { + if err != nil || total != 1 || logs[0].AccountID == nil || *logs[0].AccountID != second.ID || logs[0].ClientKeyName != "test-key" || logs[0].ModelPublicID != "grok-test" || logs[0].ModelUpstreamModel != "Build/grok-test" || logs[0].ReasoningEffort != "high" || logs[0].AccountName != "second" || logs[0].CachedInputTokens != 80 || logs[0].UsageSource != audit.UsageSourceUpstream || logs[0].StatusCode != http.StatusOK || logs[0].AttemptCount != 1 { t.Fatalf("audit = %#v, %d, %v", logs, total, err) } detail, err := auditRepo.Get(ctx, logs[0].ID) @@ -2597,6 +2598,7 @@ type failoverAdapter struct { lastPromptCacheKey string lastReasoningReplayKey string lastGrokTurnIndex string + reasoningEffort string forwardedModels []string resourceStatus int transportErrorIDs map[uint64]error @@ -4147,6 +4149,9 @@ func (a *failoverAdapter) Definition() provider.Definition { } } func (a *failoverAdapter) ForwardResponse(_ context.Context, request provider.ResponseResourceRequest) (*provider.Response, error) { + if request.NormalizedMetadata != nil { + request.NormalizedMetadata.ReasoningEffort = a.reasoningEffort + } a.mu.Lock() a.attempts = append(a.attempts, request.Credential.ID) a.forwardedModels = append(a.forwardedModels, request.Model) diff --git a/backend/internal/domain/audit/audit.go b/backend/internal/domain/audit/audit.go index 1cbb1a54..18882586 100644 --- a/backend/internal/domain/audit/audit.go +++ b/backend/internal/domain/audit/audit.go @@ -82,6 +82,7 @@ type Record struct { Provider string Operation Operation UsageSource UsageSource + ReasoningEffort string AccountID *uint64 AccountName string EgressNodeID *uint64 diff --git a/backend/internal/domain/audit/reasoning_effort.go b/backend/internal/domain/audit/reasoning_effort.go new file mode 100644 index 00000000..7e02ffb2 --- /dev/null +++ b/backend/internal/domain/audit/reasoning_effort.go @@ -0,0 +1,14 @@ +package audit + +import "strings" + +// NormalizeReasoningEffort accepts only bounded, non-sensitive audit values. +// Provider adapters must resolve client aliases before calling this function. +func NormalizeReasoningEffort(value string) string { + switch normalized := strings.ToLower(strings.TrimSpace(value)); normalized { + case "auto", "none", "low", "medium", "high", "xhigh", "fixed": + return normalized + default: + return "" + } +} diff --git a/backend/internal/domain/audit/reasoning_effort_test.go b/backend/internal/domain/audit/reasoning_effort_test.go new file mode 100644 index 00000000..4b8f9f2f --- /dev/null +++ b/backend/internal/domain/audit/reasoning_effort_test.go @@ -0,0 +1,23 @@ +package audit + +import "testing" + +func TestNormalizeReasoningEffort(t *testing.T) { + tests := []struct { + value string + want string + }{ + {value: " XHIGH ", want: "xhigh"}, + {value: "fixed", want: "fixed"}, + {value: "max", want: ""}, + {value: "thinking:32000", want: ""}, + {value: "customer@example.com", want: ""}, + } + for _, test := range tests { + t.Run(test.value, func(t *testing.T) { + if got := NormalizeReasoningEffort(test.value); got != test.want { + t.Fatalf("got %q, want %q", got, test.want) + } + }) + } +} diff --git a/backend/internal/infra/config/config.go b/backend/internal/infra/config/config.go index f7a3c83f..49f611c2 100644 --- a/backend/internal/infra/config/config.go +++ b/backend/internal/infra/config/config.go @@ -227,6 +227,18 @@ type RoutingConfig struct { ReasoningReplayEnabled bool `yaml:"reasoningReplayEnabled"` ReasoningReplayTTL Duration `yaml:"reasoningReplayTTL"` ReasoningReplayMaxEntries int `yaml:"reasoningReplayMaxEntries"` + // AutoAssignMaxNodeShare optionally caps how many active accounts one + // healthy node may absorb during auto assignment. 0 keeps the historical + // unbounded first-pass evacuation. Values in [0.05, 1] are a fraction of + // the active provider pool. GROK2API_AUTO_ASSIGN_MAX_NODE_SHARE overrides + // this field when set to a valid value. + AutoAssignMaxNodeShare float64 `yaml:"autoAssignMaxNodeShare"` + // AutoAssignMaxMigrationShare optionally caps how many already-bound + // accounts may move in one maintenance cycle. 0 keeps the historical + // unbounded first-pass evacuation and the existing 200-move ceiling for + // capacity/rebalance repair. GROK2API_AUTO_ASSIGN_MAX_MIGRATION_SHARE + // overrides this field when set to a valid value. + AutoAssignMaxMigrationShare float64 `yaml:"autoAssignMaxMigrationShare"` } type AuditConfig struct { @@ -267,6 +279,18 @@ type QualityGuardConfig struct { RotationToken string `yaml:"rotationToken"` RotationTimeout Duration `yaml:"rotationTimeout"` RotatableNodeIDs []uint64 `yaml:"rotatableNodeIDs"` + // RequestRetry withholds a thinking-model stream that already has enough + // visible output and no reasoning, then retries on another account. + RequestRetry QualityGuardRequestRetryConfig `yaml:"requestRetry"` +} + +// QualityGuardRequestRetryConfig holds the in-process missing-thinking withhold policy. +type QualityGuardRequestRetryConfig struct { + Enabled bool `yaml:"enabled"` + MaxAttempts int `yaml:"maxAttempts"` + HoldTimeout Duration `yaml:"holdTimeout"` + MinOutputTokens int `yaml:"minOutputTokens"` + OnExhausted string `yaml:"onExhausted"` } type ClientKeyDefaultsConfig struct { @@ -630,6 +654,9 @@ func (c Config) Validate() error { if c.Routing.ReasoningReplayMaxEntries < 100 || c.Routing.ReasoningReplayMaxEntries > 1000000 { return errors.New("routing.reasoningReplayMaxEntries 必须在 100 到 1000000 之间") } + if !validAutoAssignShare(c.Routing.AutoAssignMaxNodeShare) || !validAutoAssignShare(c.Routing.AutoAssignMaxMigrationShare) { + return errors.New("routing.autoAssignMaxNodeShare 与 autoAssignMaxMigrationShare 必须为 0 或 0.05 到 1 之间") + } if c.Audit.BufferSize < 1 || c.Audit.BufferSize > maxAuditBufferSize || c.Audit.BatchSize < 1 || c.Audit.BatchSize > maxAuditBatchSize || c.Audit.BatchSize > c.Audit.BufferSize || c.Audit.FlushInterval.Value() < minAuditFlushInterval || c.Audit.FlushInterval.Value() > maxAuditFlushInterval { return errors.New("audit 队列和批量写入配置无效") } @@ -675,6 +702,9 @@ func (c Config) Validate() error { } func validateQualityGuardConfig(value QualityGuardConfig) error { + if err := validateQualityGuardRequestRetry(value.RequestRetry); err != nil { + return err + } if !value.Enabled { return nil } @@ -726,6 +756,31 @@ func validateQualityGuardConfig(value QualityGuardConfig) error { return nil } +func validateQualityGuardRequestRetry(value QualityGuardRequestRetryConfig) error { + if !value.Enabled { + return nil + } + if value.MaxAttempts != 0 && (value.MaxAttempts < 1 || value.MaxAttempts > 6) { + return errors.New("qualityGuard.requestRetry.maxAttempts 必须在 1 到 6 之间") + } + if d := value.HoldTimeout.Value(); d != 0 && (d < 200*time.Millisecond || d > 30*time.Second) { + return errors.New("qualityGuard.requestRetry.holdTimeout 必须在 200ms 到 30s 之间") + } + if value.MinOutputTokens != 0 && (value.MinOutputTokens < 8 || value.MinOutputTokens > 256) { + return errors.New("qualityGuard.requestRetry.minOutputTokens 必须在 8 到 256 之间") + } + switch strings.TrimSpace(value.OnExhausted) { + case "", "fail_open", "fail_closed": + default: + return errors.New("qualityGuard.requestRetry.onExhausted 必须是 fail_open 或 fail_closed") + } + return nil +} + +func validAutoAssignShare(value float64) bool { + return value == 0 || (value >= 0.05 && value <= 1) +} + func validUniquePositiveIDs(values []uint64) bool { seen := make(map[uint64]struct{}, len(values)) for _, value := range values { @@ -850,6 +905,9 @@ func defaultConfig() Config { QuarantineDuration: Duration(5 * time.Minute), NoAccountBackoff: Duration(5 * time.Minute), MinimumHealthyNodes: 3, MaxOutputTokens: 384, MinimumGenerationWindow: Duration(time.Second), RotationTimeout: Duration(45 * time.Second), + RequestRetry: QualityGuardRequestRetryConfig{ + MaxAttempts: 6, HoldTimeout: Duration(3 * time.Second), MinOutputTokens: 32, OnExhausted: "fail_closed", + }, }, ClientKeyDefaults: ClientKeyDefaultsConfig{RPMLimit: clientkeydomain.DefaultRPMLimit, MaxConcurrent: clientkeydomain.DefaultMaxConcurrent}, Accounts: AccountsConfig{ diff --git a/backend/internal/infra/config/config_test.go b/backend/internal/infra/config/config_test.go index bee1da7f..f06024ce 100644 --- a/backend/internal/infra/config/config_test.go +++ b/backend/internal/infra/config/config_test.go @@ -214,6 +214,18 @@ qualityGuard: if !value.QualityGuard.Enabled || value.QualityGuard.DeprecatedClientKeyID != 999 || value.QualityGuard.ActiveInterval.Value() != 45*time.Minute { t.Fatalf("qualityGuard = %#v", value.QualityGuard) } + retry := value.QualityGuard.RequestRetry + if retry.Enabled || retry.MaxAttempts != 6 || retry.HoldTimeout.Value() != 3*time.Second || retry.MinOutputTokens != 32 || retry.OnExhausted != "fail_closed" { + t.Fatalf("loaded requestRetry defaults = %#v", retry) + } +} + +func TestDefaultQualityGuardRequestRetryContract(t *testing.T) { + t.Parallel() + got := defaultConfig().QualityGuard.RequestRetry + if got.Enabled || got.MaxAttempts != 6 || got.HoldTimeout.Value() != 3*time.Second || got.MinOutputTokens != 32 || got.OnExhausted != "fail_closed" { + t.Fatalf("requestRetry defaults = %#v", got) + } } func TestEnabledQualityGuardUsesManagedIdentity(t *testing.T) { @@ -373,6 +385,22 @@ func TestRoutingMaxAttemptsSupportsLargeCredentialPools(t *testing.T) { } } +func TestValidateRejectsInvalidAutoAssignShareConfig(t *testing.T) { + cfg := defaultConfig() + cfg.Routing.AutoAssignMaxNodeShare = 0.03 + if err := cfg.Validate(); err == nil { + t.Fatal("autoAssignMaxNodeShare 0.03 should be rejected") + } + cfg = defaultConfig() + cfg.Routing.AutoAssignMaxMigrationShare = 1.5 + if err := cfg.Validate(); err == nil { + t.Fatal("autoAssignMaxMigrationShare 1.5 should be rejected") + } + if !validAutoAssignShare(0) || !validAutoAssignShare(0.3) || !validAutoAssignShare(1) { + t.Fatal("0, 0.3, and 1 must remain valid shares") + } +} + func TestValidateRejectsInvalidSegmentedSelectorConfig(t *testing.T) { tests := []func(*RoutingConfig){ func(value *RoutingConfig) { value.SegmentedMinCandidates = 99 }, diff --git a/backend/internal/infra/persistence/relational/audit_repository.go b/backend/internal/infra/persistence/relational/audit_repository.go index b908ce71..8ec8eb54 100644 --- a/backend/internal/infra/persistence/relational/audit_repository.go +++ b/backend/internal/infra/persistence/relational/audit_repository.go @@ -351,7 +351,8 @@ func toAuditModels(value audit.Record) (requestAuditModel, []requestAuditAttempt EventID: truncate(eventID, 64), RequestID: truncate(value.RequestID, 64), ClientKeyID: value.ClientKeyID, ClientKeyName: truncate(value.ClientKeyName, 160), ModelRouteID: value.ModelRouteID, ModelPublicID: truncate(value.ModelPublicID, 255), ModelUpstreamModel: truncate(value.ModelUpstreamModel, 255), Provider: truncate(provider, 32), Operation: string(operation), UsageSource: string(usageSource), - AccountID: value.AccountID, AccountName: truncate(value.AccountName, 160), + ReasoningEffort: audit.NormalizeReasoningEffort(value.ReasoningEffort), + AccountID: value.AccountID, AccountName: truncate(value.AccountName, 160), EgressNodeID: value.EgressNodeID, EgressNodeName: truncate(value.EgressNodeName, 160), EgressScope: truncate(value.EgressScope, 32), EgressMode: string(value.EgressMode), StatusCode: value.StatusCode, Streaming: value.Streaming, MediaInputImages: nonNegative(value.MediaInputImages), MediaOutputImages: nonNegative(value.MediaOutputImages), MediaOutputSeconds: nonNegative(value.MediaOutputSeconds), diff --git a/backend/internal/infra/persistence/relational/audit_repository_test.go b/backend/internal/infra/persistence/relational/audit_repository_test.go index 5525b12b..c144ebe5 100644 --- a/backend/internal/infra/persistence/relational/audit_repository_test.go +++ b/backend/internal/infra/persistence/relational/audit_repository_test.go @@ -61,7 +61,7 @@ func TestAuditRepositoryBatchAndCursor(t *testing.T) { {RequestID: "cursor-old", ClientKeyID: 1, ModelRouteID: 1, StatusCode: 200, CreatedAt: now.Add(-48 * time.Hour)}, {RequestID: "cursor-1", ClientKeyID: 1, ModelRouteID: 1, StatusCode: 200, CreatedAt: now.Add(-3 * time.Minute)}, {RequestID: "cursor-2", ClientKeyID: 1, ModelRouteID: 1, StatusCode: 200, CreatedAt: now.Add(-2 * time.Minute)}, - {RequestID: "cursor-3", ClientKeyID: 1, ClientKeyName: "production", ModelRouteID: 1, ModelPublicID: "grok-test", ModelUpstreamModel: "grok-test-upstream", AccountName: "primary", EgressNodeID: uint64Pointer(42), EgressNodeName: "proxy-shanghai", EgressScope: "grok_web", EgressMode: audit.EgressModeProxy, StatusCode: 200, CreatedAt: now.Add(-time.Minute)}, + {RequestID: "cursor-3", ClientKeyID: 1, ClientKeyName: "production", ModelRouteID: 1, ModelPublicID: "grok-test", ModelUpstreamModel: "grok-test-upstream", ReasoningEffort: "xhigh", AccountName: "primary", EgressNodeID: uint64Pointer(42), EgressNodeName: "proxy-shanghai", EgressScope: "grok_web", EgressMode: audit.EgressModeProxy, StatusCode: 200, CreatedAt: now.Add(-time.Minute)}, } if err := repository.CreateBatch(ctx, values); err != nil { t.Fatal(err) @@ -74,7 +74,7 @@ func TestAuditRepositoryBatchAndCursor(t *testing.T) { if len(first) != 2 || !hasMore || first[0].ID <= first[1].ID { t.Fatalf("first page = %#v, hasMore = %v", first, hasMore) } - if first[0].ClientKeyName != "production" || first[0].ModelPublicID != "grok-test" || first[0].ModelUpstreamModel != "grok-test-upstream" || first[0].AccountName != "primary" || first[0].EgressNodeID == nil || *first[0].EgressNodeID != 42 || first[0].EgressNodeName != "proxy-shanghai" || first[0].EgressMode != audit.EgressModeProxy { + if first[0].ClientKeyName != "production" || first[0].ModelPublicID != "grok-test" || first[0].ModelUpstreamModel != "grok-test-upstream" || first[0].ReasoningEffort != "xhigh" || first[0].AccountName != "primary" || first[0].EgressNodeID == nil || *first[0].EgressNodeID != 42 || first[0].EgressNodeName != "proxy-shanghai" || first[0].EgressMode != audit.EgressModeProxy { t.Fatalf("audit snapshots = %#v", first[0]) } matched, _, err := repository.ListCursor(ctx, repositorypkg.AuditCursorQuery{Limit: 10, Search: "proxy-shanghai", Sort: sort}) @@ -445,14 +445,14 @@ func TestAuditRepositoryNormalizesUntrustedUsage(t *testing.T) { } repository := NewAuditRepository(database) negativeFirstToken := int64(-4) - if err := repository.Create(ctx, audit.Record{RequestID: "normalize", ClientKeyID: 1, ModelRouteID: 1, StatusCode: 200, Streaming: true, MediaInputImages: -1, MediaOutputImages: -2, MediaOutputSeconds: -3, InputTokens: -1, TotalTokens: -2, FirstTokenMS: &negativeFirstToken, DurationMS: -3, CreatedAt: time.Now().UTC()}); err != nil { + if err := repository.Create(ctx, audit.Record{RequestID: "normalize", ClientKeyID: 1, ModelRouteID: 1, StatusCode: 200, Streaming: true, ReasoningEffort: "customer@example.com", MediaInputImages: -1, MediaOutputImages: -2, MediaOutputSeconds: -3, InputTokens: -1, TotalTokens: -2, FirstTokenMS: &negativeFirstToken, DurationMS: -3, CreatedAt: time.Now().UTC()}); err != nil { t.Fatal(err) } values, _, err := repository.List(ctx, 0, 1) if err != nil || len(values) != 1 { t.Fatalf("values = %#v, err = %v", values, err) } - if values[0].MediaInputImages != 0 || values[0].MediaOutputImages != 0 || values[0].MediaOutputSeconds != 0 || values[0].InputTokens != 0 || values[0].TotalTokens != 0 || values[0].FirstTokenMS == nil || *values[0].FirstTokenMS != 0 || values[0].DurationMS != 0 { + if values[0].ReasoningEffort != "" || values[0].MediaInputImages != 0 || values[0].MediaOutputImages != 0 || values[0].MediaOutputSeconds != 0 || values[0].InputTokens != 0 || values[0].TotalTokens != 0 || values[0].FirstTokenMS == nil || *values[0].FirstTokenMS != 0 || values[0].DurationMS != 0 { t.Fatalf("normalized audit = %#v", values[0]) } } diff --git a/backend/internal/infra/persistence/relational/egress_operations_test.go b/backend/internal/infra/persistence/relational/egress_operations_test.go index 3fbdc593..a02b8b86 100644 --- a/backend/internal/infra/persistence/relational/egress_operations_test.go +++ b/backend/internal/infra/persistence/relational/egress_operations_test.go @@ -3,6 +3,7 @@ package relational import ( "context" "errors" + "fmt" "strings" "testing" "time" @@ -217,6 +218,52 @@ func TestEgressOperationsSharesWebNodeCapacityAcrossProviders(t *testing.T) { } } +func TestEgressOperationsAutoAssignShareUsesProviderLoadOnSharedWebNode(t *testing.T) { + ctx := context.Background() + database := openTestDatabase(t) + accounts := NewAccountRepository(database) + nodes := NewEgressRepository(database) + cipher := egressOperationsCipher(t) + node := createHealthyEgressNodeForScope(t, ctx, nodes, cipher, "shared-web-bounded", egress.ScopeWeb, 0) + + consoleIDs := make([]uint64, 0, 3) + for index := 0; index < 3; index++ { + credential := createEgressOperationsProviderAccount(t, ctx, accounts, account.ProviderConsole, fmt.Sprintf("console-%d", index)) + consoleIDs = append(consoleIDs, credential.ID) + } + if _, err := accounts.UpdateEgressBindings(ctx, account.ProviderConsole, consoleIDs, &node.ID, account.EgressAssignmentManual, time.Now().UTC()); err != nil { + t.Fatal(err) + } + + web := make([]account.Credential, 0, 10) + for index := 0; index < 10; index++ { + web = append(web, createEgressOperationsProviderAccount(t, ctx, accounts, account.ProviderWeb, fmt.Sprintf("web-%d", index))) + } + + service := egressapp.NewService(nodes, cipher, "test-browser", accounts) + service.ConfigureAutoAssignBounds(0.30, 0) + result, err := service.RebalanceAccounts(ctx, true, false, 15*time.Minute) + if err != nil { + t.Fatal(err) + } + if result.Assigned != 3 || result.Unplaced != 7 || result.Rebalanced != 0 { + t.Fatalf("rebalance result = %#v", result) + } + assigned := 0 + for _, credential := range web { + stored, getErr := accounts.Get(ctx, credential.ID) + if getErr != nil { + t.Fatal(getErr) + } + if stored.EgressNodeID == node.ID { + assigned++ + } + } + if assigned != 3 { + t.Fatalf("shared Web node received %d Web accounts, want 3", assigned) + } +} + func TestEgressOperationsRejectsIncompatibleNodeScopeChangeWithBindings(t *testing.T) { ctx := context.Background() database := openTestDatabase(t) diff --git a/backend/internal/infra/persistence/relational/mapping.go b/backend/internal/infra/persistence/relational/mapping.go index f37d6931..52db977d 100644 --- a/backend/internal/infra/persistence/relational/mapping.go +++ b/backend/internal/infra/persistence/relational/mapping.go @@ -254,7 +254,8 @@ func toAuditDomain(value requestAuditModel) audit.Record { ID: value.ID, EventID: value.EventID, RequestID: value.RequestID, ClientKeyID: value.ClientKeyID, ClientKeyName: value.ClientKeyName, ModelRouteID: value.ModelRouteID, ModelPublicID: value.ModelPublicID, ModelUpstreamModel: value.ModelUpstreamModel, Provider: value.Provider, Operation: audit.Operation(value.Operation), UsageSource: audit.UsageSource(value.UsageSource), - AccountID: value.AccountID, AccountName: value.AccountName, + ReasoningEffort: value.ReasoningEffort, + AccountID: value.AccountID, AccountName: value.AccountName, EgressNodeID: value.EgressNodeID, EgressNodeName: value.EgressNodeName, EgressScope: value.EgressScope, EgressMode: audit.EgressMode(value.EgressMode), StatusCode: value.StatusCode, Streaming: value.Streaming, MediaInputImages: value.MediaInputImages, MediaOutputImages: value.MediaOutputImages, MediaOutputSeconds: value.MediaOutputSeconds, diff --git a/backend/internal/infra/persistence/relational/models.go b/backend/internal/infra/persistence/relational/models.go index 966fd6e4..676ca6d0 100644 --- a/backend/internal/infra/persistence/relational/models.go +++ b/backend/internal/infra/persistence/relational/models.go @@ -299,6 +299,7 @@ type requestAuditModel struct { Provider string `gorm:"size:32;not null;check:chk_request_audits_provider,provider IN ('grok_build','grok_web','grok_console')"` Operation string `gorm:"size:32;not null;check:chk_request_audits_operation,operation IN ('responses','compaction','chat','messages','image','image_edit','video','tts','stt','realtime','voice')"` UsageSource string `gorm:"size:16;not null;check:chk_request_audits_usage_source,usage_source IN ('upstream','estimated','none')"` + ReasoningEffort string `gorm:"size:32;not null;default:'';check:chk_request_audits_reasoning_effort,length(reasoning_effort) <= 32"` AccountID *uint64 `gorm:"check:chk_request_audits_account_id,account_id IS NULL OR account_id > 0"` AccountName string `gorm:"size:160;check:chk_request_audits_account_name,length(account_name) <= 160"` EgressNodeID *uint64 `gorm:"check:chk_request_audits_egress_node_id,egress_node_id IS NULL OR egress_node_id > 0"` diff --git a/backend/internal/infra/provider/cli/adapter.go b/backend/internal/infra/provider/cli/adapter.go index 4de91bc5..cc628919 100644 --- a/backend/internal/infra/provider/cli/adapter.go +++ b/backend/internal/infra/provider/cli/adapter.go @@ -221,6 +221,9 @@ func (a *Adapter) config() Config { } func (a *Adapter) ForwardResponse(ctx context.Context, request provider.ResponseResourceRequest) (*provider.Response, error) { + if request.NormalizedMetadata != nil { + *request.NormalizedMetadata = provider.NormalizedRequestMetadata{} + } accessToken, err := a.cipher.Decrypt(request.Credential.EncryptedAccessToken) if err != nil { return nil, err @@ -233,18 +236,24 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response if request.NormalizeBody { if request.Operation == conversation.OperationChat || request.Operation == conversation.OperationMessages { body, conversationOptions, err = conversation.ConvertRequestWithOptions(body, request.Model, request.Operation) + if err == nil && conversationOptions.ReasoningEffortSet && request.NormalizedMetadata != nil { + request.NormalizedMetadata.ReasoningEffort = conversationOptions.ReasoningEffort + } } else { - var foreignCompactions int - body, foreignCompactions, err = expandGatewayCompactionHistory(body, a.compaction, request.PromptCacheKey) + var foreignCompactions, driftedCompactions int + body, foreignCompactions, driftedCompactions, err = expandGatewayCompactionHistory(body, a.compaction, request.PromptCacheKey) if err != nil { return invalidResponsesResponse(err), nil } - body, toolCompatibility, err = normalizeResponsesRequest(body, request.Model) + body, toolCompatibility, err = normalizeResponsesRequestWithMetadata(body, request.Model, request.NormalizedMetadata) if toolCompatibility != nil { compactionRequested = toolCompatibility.compactionRequested if foreignCompactions > 0 { toolCompatibility.addWarning("foreign_compaction_omitted") } + if driftedCompactions > 0 { + toolCompatibility.addWarning("compaction_session_drifted") + } } } if err != nil { @@ -253,7 +262,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response } return invalidResponsesResponse(err), nil } - body, err = normalizeBuildRequest(body, request.Model, request.Operation) + body, err = normalizeBuildRequestWithMetadata(body, request.Model, request.Operation, request.NormalizedMetadata) if err != nil { if request.Operation == conversation.OperationChat || request.Operation == conversation.OperationMessages { return invalidConversationResponse(request.Operation, err), nil diff --git a/backend/internal/infra/provider/cli/normalize.go b/backend/internal/infra/provider/cli/normalize.go index 8f5374ef..6658bf37 100644 --- a/backend/internal/infra/provider/cli/normalize.go +++ b/backend/internal/infra/provider/cli/normalize.go @@ -6,18 +6,24 @@ import ( "fmt" "strings" + auditdomain "github.com/chenyme/grok2api/backend/internal/domain/audit" modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" + "github.com/chenyme/grok2api/backend/internal/infra/provider" "github.com/chenyme/grok2api/backend/internal/infra/provider/conversation" ) // normalizeResponsesRequest 改写路由字段和兼容别名,并为上游不支持的新工具协议建立请求级映射。 func normalizeResponsesRequest(body []byte, model string) ([]byte, *responsesToolCompatibility, error) { + return normalizeResponsesRequestWithMetadata(body, model, nil) +} + +func normalizeResponsesRequestWithMetadata(body []byte, model string, metadata *provider.NormalizedRequestMetadata) ([]byte, *responsesToolCompatibility, error) { var payload map[string]json.RawMessage if err := json.Unmarshal(body, &payload); err != nil { return nil, nil, fmt.Errorf("解析 Responses 请求: %w", err) } payload["model"] = mustJSON(model) - if _, err := normalizeBuildRequestPayload(payload, model, conversation.OperationResponses); err != nil { + if _, err := normalizeBuildRequestPayloadWithMetadata(payload, model, conversation.OperationResponses, metadata); err != nil { return nil, nil, err } if responseFormat, exists := payload["response_format"]; exists { @@ -59,11 +65,15 @@ func normalizeResponsesRequest(body []byte, model string) ([]byte, *responsesToo // normalizeBuildRequest applies the stable compatibility boundary shared by Responses, // Chat Completions, and Anthropic Messages before the request reaches Grok Build. func normalizeBuildRequest(body []byte, model, operation string) ([]byte, error) { + return normalizeBuildRequestWithMetadata(body, model, operation, nil) +} + +func normalizeBuildRequestWithMetadata(body []byte, model, operation string, metadata *provider.NormalizedRequestMetadata) ([]byte, error) { var payload map[string]json.RawMessage if err := json.Unmarshal(body, &payload); err != nil { return nil, fmt.Errorf("解析 Build 请求: %w", err) } - changed, err := normalizeBuildRequestPayload(payload, model, operation) + changed, err := normalizeBuildRequestPayloadWithMetadata(payload, model, operation, metadata) if err != nil { return nil, err } @@ -74,6 +84,12 @@ func normalizeBuildRequest(body []byte, model, operation string) ([]byte, error) } func normalizeBuildRequestPayload(payload map[string]json.RawMessage, model, operation string) (bool, error) { + return normalizeBuildRequestPayloadWithMetadata(payload, model, operation, nil) +} + +func normalizeBuildRequestPayloadWithMetadata(payload map[string]json.RawMessage, model, operation string, metadata *provider.NormalizedRequestMetadata) (bool, error) { + requestedEffort := metadata != nil && auditdomain.NormalizeReasoningEffort(metadata.ReasoningEffort) != "" + requestedEffort = requestedEffort || hasRecognizedBuildReasoningEffort(payload) changed := false // client_metadata is a Codex transport envelope and may contain local paths, // repository remotes, and installation/session identifiers. It is consumed by @@ -110,9 +126,57 @@ func normalizeBuildRequestPayload(payload map[string]json.RawMessage, model, ope if err != nil { return false, err } + updateBuildReasoningMetadata(payload, model, requestedEffort, metadata) return changed || defaultsChanged, nil } +func hasRecognizedBuildReasoningEffort(payload map[string]json.RawMessage) bool { + effort, ok := buildReasoningEffort(payload) + if !ok { + return false + } + switch strings.ToLower(strings.TrimSpace(effort)) { + case "auto", "none", "minimal", "low", "medium", "high", "xhigh", "max": + return true + default: + return false + } +} + +func updateBuildReasoningMetadata(payload map[string]json.RawMessage, model string, requested bool, metadata *provider.NormalizedRequestMetadata) { + if metadata == nil { + return + } + previous := auditdomain.NormalizeReasoningEffort(metadata.ReasoningEffort) + metadata.ReasoningEffort = "" + if !requested { + return + } + if modeldomain.IsGrokComposerModel(model) { + metadata.ReasoningEffort = "fixed" + return + } + if effort, ok := buildReasoningEffort(payload); ok { + metadata.ReasoningEffort = auditdomain.NormalizeReasoningEffort(effort) + return + } + metadata.ReasoningEffort = previous +} + +func buildReasoningEffort(payload map[string]json.RawMessage) (string, bool) { + raw := payload["reasoning"] + if isEmptyJSON(raw) { + return "", false + } + var reasoning struct { + Effort string `json:"effort"` + } + if json.Unmarshal(raw, &reasoning) != nil || strings.TrimSpace(reasoning.Effort) == "" { + return "", false + } + return reasoning.Effort, true +} + // applyBuildResponseDefaults mirrors the official Grok Build client boundary. // Explicit store=true remains a caller choice; only an absent/null value is made ZDR-safe. func applyBuildResponseDefaults(payload map[string]json.RawMessage) (bool, error) { @@ -173,6 +237,8 @@ func normalizeBuildReasoningEffortPayload(payload map[string]json.RawMessage, mo } var normalized string switch strings.ToLower(strings.TrimSpace(effort)) { + case "minimal": + normalized = modeldomain.ReasoningEffortLow case "xhigh": if modeldomain.SupportsReasoningEffort(model, modeldomain.ReasoningEffortXHigh) { normalized = modeldomain.ReasoningEffortXHigh diff --git a/backend/internal/infra/provider/cli/normalize_test.go b/backend/internal/infra/provider/cli/normalize_test.go index 47a71ace..8e6fff3c 100644 --- a/backend/internal/infra/provider/cli/normalize_test.go +++ b/backend/internal/infra/provider/cli/normalize_test.go @@ -59,13 +59,15 @@ func TestNormalizeBuildReasoningEffort(t *testing.T) { {name: "prefixed 4.6 uppercase max maps to xhigh", model: "Build/grok-4.6", effort: "MAX", want: "xhigh"}, {name: "unknown xhigh remains guarded", model: "future-model", effort: "xhigh", want: "high"}, {name: "unknown max remains guarded", model: "future-model", effort: "max", want: "high"}, + {name: "minimal maps to low", model: "grok-4.6", effort: "minimal", want: "low"}, {name: "high", model: "grok-4.5", effort: "high", want: "high"}, {name: "medium", model: "grok-4.5", effort: "medium", want: "medium"}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { body := []byte(`{"reasoning":{"effort":"` + test.effort + `"},"input":"hello"}`) - normalized, err := normalizeBuildRequest(body, test.model, conversation.OperationResponses) + metadata := &provider.NormalizedRequestMetadata{} + normalized, err := normalizeBuildRequestWithMetadata(body, test.model, conversation.OperationResponses, metadata) if err != nil { t.Fatal(err) } @@ -77,10 +79,29 @@ func TestNormalizeBuildReasoningEffort(t *testing.T) { if !ok || reasoning["effort"] != test.want { t.Fatalf("reasoning = %#v, want %q", payload["reasoning"], test.want) } + if metadata.ReasoningEffort != test.want { + t.Fatalf("metadata effort = %q, want %q", metadata.ReasoningEffort, test.want) + } }) } } +func TestNormalizeBuildReasoningMetadataRejectsArbitraryValuesAndDefaults(t *testing.T) { + for _, body := range []string{ + `{"input":"hello"}`, + `{"input":"hello","reasoning":{"effort":"customer@example.com"}}`, + `{"input":"hello","reasoning":{"effort":123}}`, + } { + metadata := &provider.NormalizedRequestMetadata{} + if _, err := normalizeBuildRequestWithMetadata([]byte(body), "grok-4.6", conversation.OperationResponses, metadata); err != nil { + t.Fatal(err) + } + if metadata.ReasoningEffort != "" { + t.Fatalf("body %s persisted metadata %q", body, metadata.ReasoningEffort) + } + } +} + func TestNormalizeBuildChatRequestsVisibleReasoningSummary(t *testing.T) { tests := []struct { name string @@ -203,7 +224,8 @@ func TestNormalizeBuildComposerStripsReasoningEffort(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - normalized, err := normalizeBuildRequest(test.body, modeldomain.GrokComposer25Fast, test.operation) + metadata := &provider.NormalizedRequestMetadata{} + normalized, err := normalizeBuildRequestWithMetadata(test.body, modeldomain.GrokComposer25Fast, test.operation, metadata) if err != nil { t.Fatal(err) } @@ -216,6 +238,9 @@ func TestNormalizeBuildComposerStripsReasoningEffort(t *testing.T) { t.Fatalf("Composer reasoning effort leaked upstream: %#v", payload) } } + if metadata.ReasoningEffort != "fixed" { + t.Fatalf("Composer metadata effort = %q, want fixed", metadata.ReasoningEffort) + } }) } diff --git a/backend/internal/infra/provider/cli/responses_compaction.go b/backend/internal/infra/provider/cli/responses_compaction.go index 51f7277b..ed9adbcb 100644 --- a/backend/internal/infra/provider/cli/responses_compaction.go +++ b/backend/internal/infra/provider/cli/responses_compaction.go @@ -61,40 +61,45 @@ func (c *gatewayCompactionCodec) encode(session, summary string) (string, error) return gatewayCompactionPrefix + encrypted, nil } -func (c *gatewayCompactionCodec) decode(session, blob string) (string, bool, error) { +func (c *gatewayCompactionCodec) decode(session, blob string) (summary string, owned bool, sessionDrifted bool, err error) { if !strings.HasPrefix(blob, gatewayCompactionPrefix) { - return "", false, nil + return "", false, false, nil } if c == nil || c.cipher == nil { - return "", true, fmt.Errorf("compaction codec unavailable") + return "", true, false, fmt.Errorf("compaction codec unavailable") } plain, err := c.cipher.Decrypt(strings.TrimPrefix(blob, gatewayCompactionPrefix)) if err != nil { - return "", true, fmt.Errorf("decode gateway compaction blob: %w", err) + return "", true, false, fmt.Errorf("decode gateway compaction blob: %w", err) } var envelope gatewayCompactionEnvelope if err := json.Unmarshal([]byte(plain), &envelope); err != nil { - return "", true, fmt.Errorf("decode gateway compaction payload: %w", err) + return "", true, false, fmt.Errorf("decode gateway compaction payload: %w", err) } - if envelope.Version != gatewayCompactionVersion || envelope.Session != session || envelope.Summary == "" || len(envelope.Summary) > maxGatewayCompactionSummary { - return "", true, fmt.Errorf("gateway compaction payload does not match this session") + if envelope.Version != gatewayCompactionVersion || envelope.Summary == "" || len(envelope.Summary) > maxGatewayCompactionSummary { + return "", true, false, fmt.Errorf("gateway compaction payload is invalid") } - return envelope.Summary, true, nil + // Session / PromptCacheKey is advisory. A still-decryptable summary from + // this gateway instance is kept when the client key drifts after a model + // switch, degrade, or TUI session change. Foreign provider blobs stay + // rejected because they never carry this prefix or this cipher. + return envelope.Summary, true, envelope.Session != session, nil } // expandGatewayCompactionHistory restores gateway-owned remote-v2 state to a // portable developer message. Foreign OpenAI/Claude/Gemini blobs are never // forwarded to Grok Build: its decoder cannot decrypt those provider states. -func expandGatewayCompactionHistory(body []byte, codec *gatewayCompactionCodec, session string) ([]byte, int, error) { +func expandGatewayCompactionHistory(body []byte, codec *gatewayCompactionCodec, session string) ([]byte, int, int, error) { var payload map[string]any if err := json.Unmarshal(body, &payload); err != nil { - return body, 0, nil // normalizeResponsesRequest owns the public JSON error. + return body, 0, 0, nil // normalizeResponsesRequest owns the public JSON error. } items, ok := payload["input"].([]any) if !ok { - return body, 0, nil + return body, 0, 0, nil } foreign := 0 + drifted := 0 changed := false for index, raw := range items { item, ok := raw.(map[string]any) @@ -102,7 +107,7 @@ func expandGatewayCompactionHistory(body []byte, codec *gatewayCompactionCodec, continue } blob, _ := item["encrypted_content"].(string) - summary, owned, err := codec.decode(session, blob) + summary, owned, sessionDrifted, err := codec.decode(session, blob) if err != nil { foreign++ items[index] = compatibilityBoundaryMessage("A prior compacted context could not be decoded by this gateway instance. Continue from the retained conversation messages.") @@ -111,6 +116,9 @@ func expandGatewayCompactionHistory(body []byte, codec *gatewayCompactionCodec, } if owned { items[index] = gatewayCompactionSummaryMessage(summary) + if sessionDrifted { + drifted++ + } } else { foreign++ items[index] = compatibilityBoundaryMessage("A compacted context created by another provider cannot be decoded by Grok Build. Continue from the retained conversation messages.") @@ -118,11 +126,11 @@ func expandGatewayCompactionHistory(body []byte, codec *gatewayCompactionCodec, changed = true } if !changed { - return body, 0, nil + return body, 0, 0, nil } payload["input"] = items encoded, err := json.Marshal(payload) - return encoded, foreign, err + return encoded, foreign, drifted, err } // prepareGatewayCompactionSample mirrors Grok Build full-replace diff --git a/backend/internal/infra/provider/cli/responses_compaction_test.go b/backend/internal/infra/provider/cli/responses_compaction_test.go index c7af848e..4933802a 100644 --- a/backend/internal/infra/provider/cli/responses_compaction_test.go +++ b/backend/internal/infra/provider/cli/responses_compaction_test.go @@ -51,16 +51,61 @@ func TestGatewayCompactionLifecycle(t *testing.T) { t.Fatalf("content type = %q", contentType) } blob = compactionBlobFromSSE(t, stream) - expanded, foreign, err := expandGatewayCompactionHistory([]byte(`{"input":[{"type":"compaction","encrypted_content":`+mustJSONString(blob)+`}]} `), codec, "session-1") + expanded, foreign, drifted, err := expandGatewayCompactionHistory([]byte(`{"input":[{"type":"compaction","encrypted_content":`+mustJSONString(blob)+`}]} `), codec, "session-1") if err != nil { t.Fatal(err) } - if foreign != 0 || !strings.Contains(string(expanded), "This session is being continued") || strings.Contains(string(expanded), `"type":"compaction"`) || !strings.Contains(string(expanded), `"role":"user"`) { - t.Fatalf("expanded = %s, foreign = %d", expanded, foreign) + if foreign != 0 || drifted != 0 || !strings.Contains(string(expanded), "This session is being continued") || strings.Contains(string(expanded), `"type":"compaction"`) || !strings.Contains(string(expanded), `"role":"user"`) { + t.Fatalf("expanded = %s, foreign = %d, drifted = %d", expanded, foreign, drifted) } - mismatched, unusable, err := expandGatewayCompactionHistory([]byte(`{"input":[{"type":"compaction","encrypted_content":`+mustJSONString(blob)+`}]} `), codec, "other-session") - if err != nil || unusable != 1 || strings.Contains(string(mismatched), blob) || !strings.Contains(string(mismatched), "could not be decoded") { - t.Fatalf("session mismatch fallback = %s, unusable = %d, err = %v", mismatched, unusable, err) + mismatched, unusable, drifted, err := expandGatewayCompactionHistory([]byte(`{"input":[{"type":"compaction","encrypted_content":`+mustJSONString(blob)+`}]} `), codec, "other-session") + if err != nil || unusable != 0 || drifted != 1 || strings.Contains(string(mismatched), blob) || strings.Contains(string(mismatched), "could not be decoded") || !strings.Contains(string(mismatched), "This session is being continued") { + t.Fatalf("session mismatch expansion = %s, unusable = %d, drifted = %d, err = %v", mismatched, unusable, drifted, err) + } +} + +func TestForwardResponseRetainsSessionDriftedCompaction(t *testing.T) { + adapter, encrypted := newCompactionTestAdapter(t) + blob, err := adapter.compaction.encode("old-session", gatewayCompactionContinuation(healthyCompactionSummary())) + if err != nil { + t.Fatal(err) + } + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + data, readErr := io.ReadAll(request.Body) + if readErr != nil { + t.Fatal(readErr) + } + if strings.Contains(string(data), blob) || strings.Contains(string(data), "could not be decoded") || !strings.Contains(string(data), "This session is being continued") { + t.Fatalf("session-drifted summary was not retained: %s", data) + } + return sseResponse(http.StatusOK, "event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_drifted\",\"object\":\"response\",\"status\":\"completed\",\"model\":\"grok-4.5\",\"output\":[]}}\n\n", request), nil + }) + response, err := adapter.ForwardResponse(t.Context(), provider.ResponseResourceRequest{ + Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted}, + Method: http.MethodPost, Path: "/responses", Model: "grok-4.5", PromptCacheKey: "new-session", + Streaming: true, NormalizeBody: true, + Body: []byte(`{"model":"public","stream":true,"input":[{"type":"compaction","encrypted_content":` + mustJSONString(blob) + `},{"role":"user","content":"continue"}]}`), + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if !strings.Contains(response.Header.Get("X-Grok2API-Compatibility-Warnings"), "compaction_session_drifted") { + t.Fatalf("warnings = %q", response.Header.Get("X-Grok2API-Compatibility-Warnings")) + } +} + +func TestUndecodableGatewayCompactionUsesBoundary(t *testing.T) { + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + expanded, foreign, drifted, err := expandGatewayCompactionHistory([]byte(`{"input":[{"type":"compaction","encrypted_content":"g2a_compact_v1.invalid"}]}`), newGatewayCompactionCodec(cipher), "session-1") + if err != nil { + t.Fatal(err) + } + if foreign != 1 || drifted != 0 || strings.Contains(string(expanded), "g2a_compact_v1.invalid") || !strings.Contains(string(expanded), "could not be decoded") { + t.Fatalf("expanded = %s, foreign = %d, drifted = %d", expanded, foreign, drifted) } } @@ -238,12 +283,12 @@ func TestForeignCompactionNeverReachesBuildModelInput(t *testing.T) { if err != nil { t.Fatal(err) } - expanded, foreign, err := expandGatewayCompactionHistory([]byte(`{"input":[{"type":"compaction","encrypted_content":"gAAAAABforeign-codex-replay"},{"role":"user","content":"continue"}]}`), newGatewayCompactionCodec(cipher), "session-1") + expanded, foreign, drifted, err := expandGatewayCompactionHistory([]byte(`{"input":[{"type":"compaction","encrypted_content":"gAAAAABforeign-codex-replay"},{"role":"user","content":"continue"}]}`), newGatewayCompactionCodec(cipher), "session-1") if err != nil { t.Fatal(err) } - if foreign != 1 || strings.Contains(string(expanded), "gAAAAABforeign-codex-replay") || strings.Contains(string(expanded), `"type":"compaction"`) { - t.Fatalf("expanded = %s, foreign = %d", expanded, foreign) + if foreign != 1 || drifted != 0 || strings.Contains(string(expanded), "gAAAAABforeign-codex-replay") || strings.Contains(string(expanded), `"type":"compaction"`) { + t.Fatalf("expanded = %s, foreign = %d, drifted = %d", expanded, foreign, drifted) } } diff --git a/backend/internal/infra/provider/console/adapter.go b/backend/internal/infra/provider/console/adapter.go index 6c399053..b4b6bc87 100644 --- a/backend/internal/infra/provider/console/adapter.go +++ b/backend/internal/infra/provider/console/adapter.go @@ -101,6 +101,9 @@ func (a *Adapter) MarshalCredentials(values []provider.CredentialSeed) ([]byte, } func (a *Adapter) ForwardResponse(ctx context.Context, request provider.ResponseResourceRequest) (*provider.Response, error) { + if request.NormalizedMetadata != nil { + *request.NormalizedMetadata = provider.NormalizedRequestMetadata{} + } if request.Method != http.MethodPost || request.Path != "/responses" { return jsonProviderResponse(http.StatusBadRequest, map[string]any{"error": map[string]any{"type": "invalid_request_error", "message": "Grok Console 仅支持 POST /responses"}}), nil } @@ -117,11 +120,14 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response if request.NormalizeBody { if request.Operation == conversation.OperationMessages { body, conversationOptions, err = conversation.ConvertRequestWithOptions(body, request.Model, request.Operation) + if err == nil && conversationOptions.ReasoningEffortSet && request.NormalizedMetadata != nil { + request.NormalizedMetadata.ReasoningEffort = conversationOptions.ReasoningEffort + } } else { body, err = conversation.ConvertRequest(body, request.Model, request.Operation) } if err == nil { - body, err = normalizeRequest(body, spec) + body, err = normalizeRequestWithMetadata(body, spec, request.NormalizedMetadata) } if err != nil { return invalidConversationResponse(request.Operation, err), nil diff --git a/backend/internal/infra/provider/console/console_test.go b/backend/internal/infra/provider/console/console_test.go index 9cd53e1f..71ea72c5 100644 --- a/backend/internal/infra/provider/console/console_test.go +++ b/backend/internal/infra/provider/console/console_test.go @@ -470,6 +470,75 @@ func TestNormalizeRequestForwardsXSearchTimeRangeAndImageSearch(t *testing.T) { }) } +func TestNormalizeRequestAvoidsClientViewImageToolCollision(t *testing.T) { + spec, ok := Resolve("grok-4.5") + if !ok { + t.Fatal("grok-4.5 missing") + } + tests := []struct { + name string + operation string + body string + }{ + { + name: "responses", + operation: conversation.OperationResponses, + body: `{"model":"grok-4.5","input":"Reply only OK. Do not call tools.","tools":[ + {"type":"function","name":"view_image","description":"View a local image","strict":false,"parameters":{"type":"object"}}, + {"type":"web_search","enable_image_understanding":true}],"tool_choice":"auto"}`, + }, + { + name: "chat completions", + operation: conversation.OperationChat, + body: `{"model":"grok-4.5","messages":[{"role":"user","content":"Reply only OK."}],"tools":[ + {"type":"function","function":{"name":"view_image","description":"View a local image","strict":false,"parameters":{"type":"object"}}}, + {"type":"web_search"}],"tool_choice":"auto"}`, + }, + { + name: "anthropic messages", + operation: conversation.OperationMessages, + body: `{"model":"grok-4.5","max_tokens":64,"messages":[{"role":"user","content":"Reply only OK."}],"tools":[ + {"name":"view_image","description":"View a local image","input_schema":{"type":"object"}}, + {"type":"web_search_20250305","name":"web_search"}],"tool_choice":{"type":"auto"}}`, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + body := []byte(test.body) + var err error + if test.operation != conversation.OperationResponses { + body, err = conversation.ConvertRequest(body, spec.UpstreamModel, test.operation) + if err != nil { + t.Fatal(err) + } + } + body, err = normalizeRequest(body, spec) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(body, &payload); err != nil { + t.Fatal(err) + } + tools, _ := payload["tools"].([]any) + if len(tools) != 2 { + t.Fatalf("tools = %#v", tools) + } + function, _ := tools[0].(map[string]any) + if toolIdentity(function) != "function:view_image" || function["parameters"] == nil { + t.Fatalf("client view_image must be retained: %#v", function) + } + webSearch, _ := tools[1].(map[string]any) + if webSearch["type"] != "web_search" || webSearch["enable_image_understanding"] != false { + t.Fatalf("server view_image must be disabled: %#v", webSearch) + } + if payload["tool_choice"] != "auto" { + t.Fatalf("tool_choice = %#v", payload["tool_choice"]) + } + }) + } +} + func TestNormalizeRequestDoesNotInjectToolsForConsoleCatalog(t *testing.T) { for _, spec := range catalog { t.Run(spec.PublicID, func(t *testing.T) { @@ -512,7 +581,8 @@ func TestNormalizeRequestPreservesMultiAgentDefaultsWithoutInjectingTools(t *tes if len(include) != 1 || include[0] != "reasoning.encrypted_content" || payload["tools"] != nil || payload["tool_choice"] != nil { t.Fatalf("multi-agent compatibility = %#v", payload) } - explicit, err := normalizeRequest([]byte(`{"model":"grok-4.20-multi-agent-0309","input":"hello","reasoning":{"effort":"xhigh"}}`), spec) + metadata := &provider.NormalizedRequestMetadata{} + explicit, err := normalizeRequestWithMetadata([]byte(`{"model":"grok-4.20-multi-agent-0309","input":"hello","reasoning":{"effort":"xhigh"}}`), spec, metadata) if err != nil { t.Fatal(err) } @@ -520,6 +590,37 @@ func TestNormalizeRequestPreservesMultiAgentDefaultsWithoutInjectingTools(t *tes if json.Unmarshal(explicit, &payload) != nil || payload["reasoning"].(map[string]any)["effort"] != "xhigh" { t.Fatalf("explicit multi-agent effort = %#v", payload) } + if metadata.ReasoningEffort != "xhigh" { + t.Fatalf("metadata effort = %q, want xhigh", metadata.ReasoningEffort) + } +} + +func TestNormalizeRequestReasoningMetadataTracksOnlyExplicitCanonicalValues(t *testing.T) { + spec, ok := Resolve("grok-4.3") + if !ok { + t.Fatal("grok-4.3 missing") + } + tests := []struct { + name string + body string + want string + }{ + {name: "absent default stays unaudited", body: `{"input":"hello"}`}, + {name: "auto resolves to provider default", body: `{"input":"hello","reasoning":{"effort":"auto"}}`, want: "medium"}, + {name: "max resolves to xhigh", body: `{"input":"hello","reasoning":{"effort":"max"}}`, want: "xhigh"}, + {name: "arbitrary value is not persisted", body: `{"input":"hello","reasoning":{"effort":"customer@example.com"}}`}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + metadata := &provider.NormalizedRequestMetadata{} + if _, err := normalizeRequestWithMetadata([]byte(test.body), spec, metadata); err != nil { + t.Fatal(err) + } + if metadata.ReasoningEffort != test.want { + t.Fatalf("metadata effort = %q, want %q", metadata.ReasoningEffort, test.want) + } + }) + } } func TestNormalizeRequestAppliesConsoleCompatibilityBoundary(t *testing.T) { @@ -599,11 +700,12 @@ func TestNormalizeRequestStripsUnsupportedGrok420ReasoningEffort(t *testing.T) { if !spec.SupportsReasoning || spec.SupportsReasoningEffort { t.Fatalf("fixed reasoning capability = %#v", spec) } - body, err := normalizeRequest([]byte(`{ + metadata := &provider.NormalizedRequestMetadata{} + body, err := normalizeRequestWithMetadata([]byte(`{ "model":"grok-4.20-0309-reasoning", "input":"hello", "reasoning":{"effort":"low","summary":"auto"} - }`), spec) + }`), spec, metadata) if err != nil { t.Fatal(err) } @@ -615,6 +717,9 @@ func TestNormalizeRequestStripsUnsupportedGrok420ReasoningEffort(t *testing.T) { if reasoning["effort"] != nil || reasoning["summary"] != "auto" { t.Fatalf("reasoning = %#v", reasoning) } + if metadata.ReasoningEffort != "fixed" { + t.Fatalf("metadata effort = %q, want fixed", metadata.ReasoningEffort) + } effortOnly, err := normalizeRequest([]byte(`{ "model":"grok-4.20-0309-reasoning", diff --git a/backend/internal/infra/provider/console/normalize.go b/backend/internal/infra/provider/console/normalize.go index 2505ea97..1c6c5a02 100644 --- a/backend/internal/infra/provider/console/normalize.go +++ b/backend/internal/infra/provider/console/normalize.go @@ -9,6 +9,7 @@ import ( "strings" "time" + auditdomain "github.com/chenyme/grok2api/backend/internal/domain/audit" "github.com/chenyme/grok2api/backend/internal/infra/provider" ) @@ -17,6 +18,10 @@ var ( ) func normalizeRequest(body []byte, spec ModelSpec) ([]byte, error) { + return normalizeRequestWithMetadata(body, spec, nil) +} + +func normalizeRequestWithMetadata(body []byte, spec ModelSpec, metadata *provider.NormalizedRequestMetadata) ([]byte, error) { var payload map[string]any if err := json.Unmarshal(body, &payload); err != nil { return nil, fmt.Errorf("解析 Console Responses 请求: %w", err) @@ -36,13 +41,47 @@ func normalizeRequest(body []byte, spec ModelSpec) ([]byte, error) { if _, exists := payload["max_output_tokens"]; !exists && spec.MaxOutputTokens > 0 { payload["max_output_tokens"] = spec.MaxOutputTokens } + requestedEffort := metadata != nil && auditdomain.NormalizeReasoningEffort(metadata.ReasoningEffort) != "" + requestedEffort = requestedEffort || hasRecognizedConsoleReasoningEffort(payload) normalizeReasoning(payload, spec) + updateConsoleReasoningMetadata(payload, spec, requestedEffort, metadata) ensureReasoningInclude(payload) retainedClientTools := normalizeConsoleTools(payload) normalizeConsoleToolChoice(payload, retainedClientTools) return json.Marshal(payload) } +func hasRecognizedConsoleReasoningEffort(payload map[string]any) bool { + reasoning, _ := payload["reasoning"].(map[string]any) + effort, _ := reasoning["effort"].(string) + if strings.EqualFold(strings.TrimSpace(effort), "auto") { + return true + } + return normalizeEffort(effort) != "" +} + +func updateConsoleReasoningMetadata(payload map[string]any, spec ModelSpec, requested bool, metadata *provider.NormalizedRequestMetadata) { + if metadata == nil { + return + } + previous := auditdomain.NormalizeReasoningEffort(metadata.ReasoningEffort) + metadata.ReasoningEffort = "" + if !requested || !spec.SupportsReasoning { + return + } + if !spec.SupportsReasoningEffort { + metadata.ReasoningEffort = "fixed" + return + } + reasoning, _ := payload["reasoning"].(map[string]any) + effort, _ := reasoning["effort"].(string) + if normalized := auditdomain.NormalizeReasoningEffort(effort); normalized != "" { + metadata.ReasoningEffort = normalized + return + } + metadata.ReasoningEffort = previous +} + func normalizeConsoleResponseFormat(payload map[string]any) { raw, exists := payload["response_format"] if !exists { @@ -215,6 +254,7 @@ func normalizeConsoleTools(payload map[string]any) bool { delete(payload, "tool_choice") return false } + hasClientViewImage := hasConsoleFunctionTool(tools, "view_image") result := make([]any, 0, len(tools)) retainedClientTools := false for _, rawTool := range tools { @@ -225,8 +265,12 @@ func normalizeConsoleTools(payload map[string]any) bool { typeName, _ := tool["type"].(string) switch strings.ToLower(strings.TrimSpace(typeName)) { case "web_search", "web_search_preview", "web_search_preview_2025_03_11", "web_search_2025_08_26": - clean := map[string]any{"type": "web_search", "enable_image_understanding": true} - if enabled, ok := tool["enable_image_understanding"].(bool); ok { + // xAI equips web_search with a server-side tool also named view_image + // when image understanding is enabled. Prefer the client's function of + // that name so Codex can still inspect local files without mgw rejecting + // the request as a duplicate tool definition. + clean := map[string]any{"type": "web_search", "enable_image_understanding": !hasClientViewImage} + if enabled, ok := tool["enable_image_understanding"].(bool); ok && !hasClientViewImage { clean["enable_image_understanding"] = enabled } // Forward the image-search toggle (enable_image_search) so clients @@ -293,6 +337,21 @@ func normalizeConsoleTools(payload map[string]any) bool { return retainedClientTools } +func hasConsoleFunctionTool(tools []any, target string) bool { + for _, rawTool := range tools { + tool, ok := rawTool.(map[string]any) + if !ok { + continue + } + typeName, _ := tool["type"].(string) + name, _ := tool["name"].(string) + if strings.EqualFold(strings.TrimSpace(typeName), "function") && strings.EqualFold(strings.TrimSpace(name), target) { + return true + } + } + return false +} + func normalizeConsoleToolChoice(payload map[string]any, retainedClientTools bool) { if _, exists := payload["tools"]; !exists { delete(payload, "tool_choice") diff --git a/backend/internal/infra/provider/conversation/conversation_test.go b/backend/internal/infra/provider/conversation/conversation_test.go index 55ffded4..0d0d4134 100644 --- a/backend/internal/infra/provider/conversation/conversation_test.go +++ b/backend/internal/infra/provider/conversation/conversation_test.go @@ -430,7 +430,7 @@ func TestConvertAnthropicClaudeCodeRequestToResponses(t *testing.T) { if err != nil { t.Fatal(err) } - if !options.AnthropicThinking { + if !options.AnthropicThinking || !options.ReasoningEffortSet || options.ReasoningEffort != "high" { t.Fatal("thinking option 未保留") } var payload map[string]any @@ -459,6 +459,21 @@ func TestConvertAnthropicClaudeCodeRequestToResponses(t *testing.T) { } } +func TestConvertAnthropicDisabledThinkingReportsNoneMetadata(t *testing.T) { + body := []byte(`{ + "model":"public-chat","max_tokens":1024, + "messages":[{"role":"user","content":"hello"}], + "thinking":{"type":"disabled"} + }`) + _, options, err := ConvertRequestWithOptions(body, "grok-4.3", OperationMessages) + if err != nil { + t.Fatal(err) + } + if options.AnthropicThinking || !options.ReasoningEffortSet || options.ReasoningEffort != "none" { + t.Fatalf("options = %#v", options) + } +} + func TestConvertAnthropicMessagesPreservesExtendedReasoningEffort(t *testing.T) { for _, effort := range []string{"xhigh", "max"} { t.Run(effort, func(t *testing.T) { @@ -484,6 +499,26 @@ func TestConvertAnthropicMessagesPreservesExtendedReasoningEffort(t *testing.T) } } +func TestConvertAnthropicMessagesUsesThinkingEffortBeforeBudget(t *testing.T) { + body := []byte(`{ + "model":"public-chat","max_tokens":1024, + "messages":[{"role":"user","content":"hello"}], + "thinking":{"type":"enabled","effort":"high","budget_tokens":1024} + }`) + converted, options, err := ConvertRequestWithOptions(body, "grok-4.5", OperationMessages) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if json.Unmarshal(converted, &payload) != nil { + t.Fatalf("converted = %s", converted) + } + reasoning, _ := payload["reasoning"].(map[string]any) + if reasoning["effort"] != "high" || !options.ReasoningEffortSet || options.ReasoningEffort != "high" { + t.Fatalf("reasoning = %#v, options = %#v", reasoning, options) + } +} + func TestConvertAnthropicToolReferenceValidatesDeclaredTool(t *testing.T) { body := []byte(`{ "model":"public","max_tokens":64, @@ -893,6 +928,104 @@ func TestConvertResponsesStreamMarksChatReasoningStart(t *testing.T) { } } +func TestConvertResponsesStreamChatPrefersRawReasoningOverSummary(t *testing.T) { + stream := strings.Join([]string{ + `event: response.created`, + `data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.6"}}`, "", + `event: response.output_item.added`, + `data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`, "", + `event: response.reasoning_summary_text.delta`, + `data: {"type":"response.reasoning_summary_text.delta","item_id":"rs_1","delta":"raw "}`, "", + `event: response.reasoning_summary_text.delta`, + `data: {"type":"response.reasoning_summary_text.delta","item_id":"rs_1","delta":"reasoning"}`, "", + `event: response.reasoning_text.delta`, + `data: {"type":"response.reasoning_text.delta","item_id":"rs_1","delta":"raw reasoning"}`, "", + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning"}}`, "", + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed"}}`, "", "", + }, "\n") + converted, err := io.ReadAll(ConvertResponseStream(io.NopCloser(strings.NewReader(stream)), OperationChat)) + if err != nil { + t.Fatal(err) + } + text := string(converted) + if strings.Count(text, `"reasoning_content"`) != 1 || strings.Count(text, "raw reasoning") != 1 { + t.Fatalf("identical summary/raw reasoning should be emitted exactly once: %s", text) + } +} + +func TestConvertResponsesStreamChatFlushesSummaryAtEOF(t *testing.T) { + stream := strings.Join([]string{ + `event: response.reasoning_summary_text.delta`, + `data: {"type":"response.reasoning_summary_text.delta","delta":"summary only"}`, "", "", + }, "\n") + converted, err := io.ReadAll(ConvertResponseStream(io.NopCloser(strings.NewReader(stream)), OperationChat)) + if err != nil { + t.Fatal(err) + } + text := string(converted) + if strings.Count(text, `"reasoning_content":"summary only"`) != 1 || !strings.Contains(text, "data: [DONE]") { + t.Fatalf("summary fallback was not finalized at EOF: %s", text) + } +} + +func TestConvertResponsesStreamChatAdoptsLateReasoningItemID(t *testing.T) { + stream := strings.Join([]string{ + `event: response.reasoning_summary_text.delta`, + `data: {"type":"response.reasoning_summary_text.delta","delta":"summary"}`, "", + `event: response.output_item.added`, + `data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`, "", + `event: response.reasoning_text.delta`, + `data: {"type":"response.reasoning_text.delta","item_id":"rs_1","delta":"raw"}`, "", + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning"}}`, "", + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed"}}`, "", "", + }, "\n") + converted, err := io.ReadAll(ConvertResponseStream(io.NopCloser(strings.NewReader(stream)), OperationChat)) + if err != nil { + t.Fatal(err) + } + text := string(converted) + if strings.Contains(text, `"reasoning_content":"summary"`) || strings.Count(text, `"reasoning_content":"raw"`) != 1 { + t.Fatalf("late item_id created a second reasoning source: %s", text) + } +} + +func TestConvertResponsesStreamMessagesPrefersRawReasoningBeforeSignature(t *testing.T) { + stream := strings.Join([]string{ + `event: response.created`, + `data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.6"}}`, "", + `event: response.output_item.added`, + `data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`, "", + `event: response.reasoning_summary_text.delta`, + `data: {"type":"response.reasoning_summary_text.delta","item_id":"rs_1","delta":"duplicated summary"}`, "", + `event: response.reasoning_text.delta`, + `data: {"type":"response.reasoning_text.delta","item_id":"rs_1","delta":"raw reasoning"}`, "", + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"signature"}}`, "", + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed"}}`, "", "", + }, "\n") + converted, err := io.ReadAll(ConvertResponseStreamWithOptions( + io.NopCloser(strings.NewReader(stream)), OperationMessages, ResponseOptions{AnthropicThinking: true}, + )) + if err != nil { + t.Fatal(err) + } + text := string(converted) + if strings.Contains(text, "duplicated summary") { + t.Fatalf("summary leaked after raw reasoning was selected: %s", text) + } + reasoningAt := strings.Index(text, `"thinking":"raw reasoning"`) + signatureAt := strings.Index(text, `"signature":"signature"`) + stopAt := strings.Index(text, `"type":"content_block_stop"`) + if reasoningAt < 0 || signatureAt < reasoningAt || stopAt < signatureAt { + t.Fatalf("thinking/signature/block-stop order is invalid: %s", text) + } +} + func TestConvertResponsesStreamMessagesNormalizesTerminalError(t *testing.T) { stream := strings.Join([]string{ `event: response.failed`, diff --git a/backend/internal/infra/provider/conversation/messages_request.go b/backend/internal/infra/provider/conversation/messages_request.go index 68a42b91..cefed8e9 100644 --- a/backend/internal/infra/provider/conversation/messages_request.go +++ b/backend/internal/infra/provider/conversation/messages_request.go @@ -31,9 +31,14 @@ func convertMessagesRequest(body []byte, model string) ([]byte, ResponseOptions, } } thinkingEnabled := false + reasoningEffort := "" + reasoningEffortSet := false if request.Thinking != nil { switch request.Thinking.Type { - case "", "disabled": + case "": + case "disabled": + reasoningEffort = "none" + reasoningEffortSet = true case "enabled", "adaptive": thinkingEnabled = true default: @@ -83,6 +88,9 @@ func convertMessagesRequest(body []byte, model string) ([]byte, ResponseOptions, } if thinkingEnabled { effort := anthropicThinkingEffort(request.Thinking.BudgetTokens) + if request.Thinking.Effort != "" { + effort = request.Thinking.Effort + } if request.OutputConfig != nil && request.OutputConfig.Effort != "" { effort = request.OutputConfig.Effort } @@ -93,6 +101,8 @@ func convertMessagesRequest(body []byte, model string) ([]byte, ResponseOptions, default: return nil, ResponseOptions{}, fmt.Errorf("不支持 output_config.effort=%q", effort) } + reasoningEffort = effort + reasoningEffortSet = true target["reasoning"] = map[string]any{"effort": effort, "summary": "detailed"} target["include"] = []any{"reasoning.encrypted_content"} } @@ -122,6 +132,8 @@ func convertMessagesRequest(body []byte, model string) ([]byte, ResponseOptions, converted, err := json.Marshal(target) return converted, ResponseOptions{ AnthropicThinking: thinkingEnabled, + ReasoningEffort: reasoningEffort, + ReasoningEffortSet: reasoningEffortSet, AnthropicWebSearch: webSearchEnabled, AnthropicWebSearchRequired: webSearchRequired, AnthropicWebSearchQuery: webSearchQuery, @@ -141,6 +153,7 @@ type anthropicRequest struct { Metadata map[string]any `json:"metadata"` Thinking *struct { Type string `json:"type"` + Effort string `json:"effort"` BudgetTokens int `json:"budget_tokens"` } `json:"thinking"` TopK json.RawMessage `json:"top_k"` diff --git a/backend/internal/infra/provider/conversation/response.go b/backend/internal/infra/provider/conversation/response.go index 88f77df7..c8733072 100644 --- a/backend/internal/infra/provider/conversation/response.go +++ b/backend/internal/infra/provider/conversation/response.go @@ -8,7 +8,11 @@ import ( // ResponseOptions 保留无法直接交给 Responses 上游执行的下游协议语义。 type ResponseOptions struct { - AnthropicThinking bool + AnthropicThinking bool + // ReasoningEffort is the effective client-facing Messages setting after + // budget and effort aliases have been converted to a canonical level. + ReasoningEffort string + ReasoningEffortSet bool AnthropicWebSearch bool AnthropicWebSearchRequired bool AnthropicWebSearchQuery string @@ -37,7 +41,6 @@ func (o ResponseOptions) InlineCitationsEnabled() bool { return enabled } - type responseEnvelope struct { ID string `json:"id"` Model string `json:"model"` diff --git a/backend/internal/infra/provider/conversation/stream.go b/backend/internal/infra/provider/conversation/stream.go index e7ecc55e..8180c89f 100644 --- a/backend/internal/infra/provider/conversation/stream.go +++ b/backend/internal/infra/provider/conversation/stream.go @@ -10,7 +10,10 @@ import ( "time" ) -const maxDeferredSearchTextBytes = 8 << 20 +const ( + maxDeferredSearchTextBytes = 8 << 20 + maxDeferredReasoningSummaryBytes = 8 << 20 +) // ConvertResponseStream 将 Responses SSE 转换为 Chat Completions 或 Anthropic Messages SSE。 func ConvertResponseStream(source io.ReadCloser, operation string) io.ReadCloser { @@ -50,6 +53,9 @@ type streamConverter struct { thinkingIndex int thinkingItemID string chatReasoningMark bool + reasoningItems map[string]*reasoningStreamState + reasoningOrder []string + activeReasoningID string nextIndex int tools map[string]streamTool webSearch []webSearchCall @@ -72,10 +78,18 @@ type streamTool struct { Closed bool } +type reasoningStreamState struct { + summary strings.Builder + rawSeen bool + done bool + anonymous bool +} + func newStreamConverter(writer io.Writer, operation string, options ResponseOptions) *streamConverter { return &streamConverter{ writer: writer, operation: operation, created: time.Now().Unix(), tools: make(map[string]streamTool), webSearchEmitted: make(map[string]bool), + reasoningItems: make(map[string]*reasoningStreamState), deferSearchText: operation == OperationMessages && options.AnthropicWebSearch, options: options, stopFilter: newAnthropicStreamStopFilter(options.StopSequences), } @@ -245,25 +259,21 @@ func (c *streamConverter) handle(event string, data []byte) error { } return c.chatDelta(map[string]any{"annotations": []any{annotation}}) case "response.reasoning_summary_text.delta": - var delta string + var itemID, delta string + _ = json.Unmarshal(root["item_id"], &itemID) _ = json.Unmarshal(root["delta"], &delta) - if c.operation == OperationChat { - return c.chatDelta(map[string]any{"reasoning_content": delta}) - } - return c.thinkingDelta(delta) + return c.reasoningSummaryDelta(itemID, delta) case "response.reasoning_text.delta": - var delta string + var itemID, delta string + _ = json.Unmarshal(root["item_id"], &itemID) _ = json.Unmarshal(root["delta"], &delta) - if c.operation == OperationChat { - return c.chatDelta(map[string]any{"reasoning_content": delta}) - } - if c.operation == OperationMessages { - return c.thinkingDelta(delta) - } - return nil + return c.reasoningTextDelta(itemID, delta) case "response.output_item.added": var item responseItem _ = json.Unmarshal(root["item"], &item) + if item.Type == "reasoning" && c.reasoningOutputEnabled() { + c.ensureReasoningState(item.ID) + } if item.Type == "reasoning" && c.operation == OperationMessages && c.options.AnthropicThinking { return c.thinkingStart(item.ID) } @@ -299,6 +309,11 @@ func (c *streamConverter) handle(event string, data []byte) error { return c.toolArgumentsDone(item.ID, item.Arguments) } if item.Type == "reasoning" { + if c.reasoningOutputEnabled() { + if err := c.reasoningDone(item); err != nil { + return err + } + } return c.thinkingDone(item) } if item.Type == "web_search_call" && c.operation == OperationMessages && c.options.AnthropicWebSearch { @@ -329,6 +344,137 @@ func (c *streamConverter) handle(event string, data []byte) error { return nil } +func (c *streamConverter) reasoningOutputEnabled() bool { + return c.operation == OperationChat || (c.operation == OperationMessages && c.options.AnthropicThinking) +} + +func (c *streamConverter) ensureReasoningState(itemID string) (string, *reasoningStreamState) { + key := itemID + if key != "" { + if state, exists := c.reasoningItems[key]; exists { + c.activeReasoningID = key + return key, state + } + // Some compatible upstreams omit item_id on the first delta. Once the + // real item arrives, attach that anonymous state instead of creating a + // second source that could later replay the buffered summary. + if anonymous := c.activeReasoningID; anonymous != "" { + if state := c.reasoningItems[anonymous]; state != nil && state.anonymous && !state.done { + delete(c.reasoningItems, anonymous) + state.anonymous = false + c.reasoningItems[key] = state + for index, existing := range c.reasoningOrder { + if existing == anonymous { + c.reasoningOrder[index] = key + break + } + } + c.activeReasoningID = key + return key, state + } + } + } + if key == "" { + key = c.activeReasoningID + } + anonymous := false + if key == "" { + key = fmt.Sprintf("#reasoning-%d", len(c.reasoningOrder)+1) + anonymous = true + } + state, exists := c.reasoningItems[key] + if !exists { + state = &reasoningStreamState{anonymous: anonymous} + c.reasoningItems[key] = state + c.reasoningOrder = append(c.reasoningOrder, key) + } + c.activeReasoningID = key + return key, state +} + +func (c *streamConverter) reasoningSummaryDelta(itemID, delta string) error { + if delta == "" || !c.reasoningOutputEnabled() { + return nil + } + _, state := c.ensureReasoningState(itemID) + if state.done || state.rawSeen { + return nil + } + // Console can publish the same client-facing thought through summary and + // raw reasoning events. Defer summary until item completion so raw can take + // precedence without relying on chunk boundaries or text equality. + pending := state.summary.Len() + if pending >= maxDeferredReasoningSummaryBytes || len(delta) > maxDeferredReasoningSummaryBytes-pending { + return fmt.Errorf("reasoning summary 延迟缓冲超过 %d MiB", maxDeferredReasoningSummaryBytes>>20) + } + state.summary.WriteString(delta) + return nil +} + +func (c *streamConverter) reasoningTextDelta(itemID, delta string) error { + if delta == "" || !c.reasoningOutputEnabled() { + return nil + } + _, state := c.ensureReasoningState(itemID) + if state.done { + return nil + } + if !state.rawSeen { + state.rawSeen = true + state.summary.Reset() + } + return c.emitReasoningDelta(delta) +} + +func (c *streamConverter) emitReasoningDelta(delta string) error { + if c.operation == OperationChat { + return c.chatDelta(map[string]any{"reasoning_content": delta}) + } + if c.operation == OperationMessages { + return c.thinkingDelta(delta) + } + return nil +} + +func (c *streamConverter) reasoningDone(item responseItem) error { + key, state := c.ensureReasoningState(item.ID) + if state.done { + return nil + } + if err := c.flushReasoningSummary(state); err != nil { + return err + } + state.done = true + if c.activeReasoningID == key { + c.activeReasoningID = "" + } + return nil +} + +func (c *streamConverter) flushReasoningSummary(state *reasoningStreamState) error { + if state == nil || state.rawSeen || state.summary.Len() == 0 { + return nil + } + value := state.summary.String() + state.summary.Reset() + return c.emitReasoningDelta(value) +} + +func (c *streamConverter) flushPendingReasoning() error { + for _, key := range c.reasoningOrder { + state := c.reasoningItems[key] + if state.done { + continue + } + if err := c.flushReasoningSummary(state); err != nil { + return err + } + state.done = true + } + c.activeReasoningID = "" + return nil +} + func (c *streamConverter) bufferSearchText(delta string) error { pending := c.pendingSearchText.Len() if pending >= maxDeferredSearchTextBytes || len(delta) > maxDeferredSearchTextBytes-pending { @@ -434,6 +580,9 @@ func (c *streamConverter) done(status string) error { if err := c.start(); err != nil { return err } + if err := c.flushPendingReasoning(); err != nil { + return err + } if c.operation == OperationChat { return c.doneChat(status) } @@ -441,6 +590,9 @@ func (c *streamConverter) done(status string) error { } func (c *streamConverter) streamError(data []byte) error { + if err := c.flushPendingReasoning(); err != nil { + return err + } c.finished = true if c.operation == OperationMessages { return c.streamErrorMessages(data) diff --git a/backend/internal/infra/provider/provider.go b/backend/internal/infra/provider/provider.go index fa670b7d..a4e5c125 100644 --- a/backend/internal/infra/provider/provider.go +++ b/backend/internal/infra/provider/provider.go @@ -300,6 +300,16 @@ type ResponseResourceRequest struct { Streaming bool NormalizeBody bool Operation string + // NormalizedMetadata receives non-sensitive metadata from the exact payload + // normalization used for the physical upstream request. The caller owns the + // value; adapters update it synchronously before network I/O. + NormalizedMetadata *NormalizedRequestMetadata +} + +// NormalizedRequestMetadata contains safe request attributes that may be kept +// in audit records. It must never contain request content or credentials. +type NormalizedRequestMetadata struct { + ReasoningEffort string } // Response represents an upstream response that has not yet been written downstream. diff --git a/backend/internal/transport/http/audit/handler.go b/backend/internal/transport/http/audit/handler.go index 580c75b5..0c22e741 100644 --- a/backend/internal/transport/http/audit/handler.go +++ b/backend/internal/transport/http/audit/handler.go @@ -94,6 +94,7 @@ type auditResponse struct { Provider string `json:"provider"` Operation string `json:"operation"` UsageSource string `json:"usageSource"` + ReasoningEffort string `json:"reasoningEffort,omitempty"` AccountID *uint64 `json:"accountId,string,omitempty"` AccountName string `json:"accountName,omitempty"` EgressNodeID *uint64 `json:"egressNodeId,string,omitempty"` @@ -474,7 +475,8 @@ func newAuditResponse(value auditdomain.Record) auditResponse { ID: value.ID, RequestID: value.RequestID, ClientKeyID: value.ClientKeyID, ClientKeyName: value.ClientKeyName, ModelRouteID: value.ModelRouteID, ModelPublicID: value.ModelPublicID, ModelUpstreamModel: value.ModelUpstreamModel, Provider: value.Provider, Operation: string(value.Operation), UsageSource: string(value.UsageSource), - AccountID: value.AccountID, AccountName: value.AccountName, + ReasoningEffort: value.ReasoningEffort, + AccountID: value.AccountID, AccountName: value.AccountName, EgressNodeID: value.EgressNodeID, EgressNodeName: value.EgressNodeName, EgressScope: value.EgressScope, EgressMode: string(value.EgressMode), StatusCode: value.StatusCode, Streaming: value.Streaming, MediaInputImages: value.MediaInputImages, MediaOutputImages: value.MediaOutputImages, MediaOutputSeconds: value.MediaOutputSeconds, diff --git a/backend/internal/transport/http/audit/handler_test.go b/backend/internal/transport/http/audit/handler_test.go index d5a270dc..d2e8d06d 100644 --- a/backend/internal/transport/http/audit/handler_test.go +++ b/backend/internal/transport/http/audit/handler_test.go @@ -84,8 +84,8 @@ func TestAuditDetailReturnsCompleteTextAndBinaryBodies(t *testing.T) { func TestAuditResponseDerivesOutputThroughput(t *testing.T) { firstTokenMS := int64(250) - response := newAuditResponse(auditdomain.Record{StatusCode: http.StatusOK, Streaming: true, FirstTokenMS: &firstTokenMS, DurationMS: 1250, OutputTokens: 80}) - if response.FirstTokenMS == nil || *response.FirstTokenMS != 250 || response.OutputTokensPerSecond == nil || *response.OutputTokensPerSecond != 80 { + response := newAuditResponse(auditdomain.Record{StatusCode: http.StatusOK, Streaming: true, ReasoningEffort: "high", FirstTokenMS: &firstTokenMS, DurationMS: 1250, OutputTokens: 80}) + if response.ReasoningEffort != "high" || response.FirstTokenMS == nil || *response.FirstTokenMS != 250 || response.OutputTokensPerSecond == nil || *response.OutputTokensPerSecond != 80 { t.Fatalf("response = %#v", response) } diff --git a/config.example.yaml b/config.example.yaml index 788ba128..2fa23eb4 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -95,6 +95,14 @@ routing: segmentedSelectorEnabled: true segmentedSelectorMinCandidates: 3000 segmentedSelectorWindowSize: 64 + # [按需修改] 大账号池才需要打开。0 保持历史行为:不健康节点上的 auto 账号会一次性迁走。 + # 0.05–1 表示每个健康节点最多吸收该比例的活跃账号。环境变量 + # GROK2API_AUTO_ASSIGN_MAX_NODE_SHARE 可覆盖。 + autoAssignMaxNodeShare: 0 + # [按需修改] 大账号池才需要打开。0 保持历史行为:首轮疏散不限额,容量/再均衡仍最多 200 次。 + # 0.05–1 限制单轮已绑定账号迁移比例。环境变量 + # GROK2API_AUTO_ASSIGN_MAX_MIGRATION_SHARE 可覆盖。 + autoAssignMaxMigrationShare: 0 audit: # [通常不要修改] 审计批量写入参数;bufferSize 的修改需重启生效。 @@ -135,3 +143,12 @@ qualityGuard: rotationTimeout: 45s nodeIDs: [] rotatableNodeIDs: [] + # Optional request-path withhold/retry for thinking models. Disabled by default. + # Missing thinking with enough visible output is not delivered; another account + # is tried (up to maxAttempts). fail_closed returns 503 instead of the last body. + requestRetry: + enabled: false + maxAttempts: 6 + holdTimeout: 3s + minOutputTokens: 32 + onExhausted: fail_closed # fail_open | fail_closed diff --git a/docker-compose.yml b/docker-compose.yml index e11f0fbc..b6bb7ad3 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -62,6 +62,10 @@ services: build: context: . dockerfile: tools/egress-quality-guard/Dockerfile + environment: + # Default matches the Compose service name. Override for host networking + # or a renamed grok2api service, e.g. http://127.0.0.1:8000 + GROK2API_BASE_URL: ${GROK2API_BASE_URL:-http://grok2api:8000} depends_on: grok2api: condition: service_healthy diff --git a/frontend/src/features/accounts/account-quota.tsx b/frontend/src/features/accounts/account-quota.tsx index b34d7e64..82f19e47 100644 --- a/frontend/src/features/accounts/account-quota.tsx +++ b/frontend/src/features/accounts/account-quota.tsx @@ -5,7 +5,7 @@ import { useTranslation } from "react-i18next"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import type { AccountDTO, BillingDTO, QuotaDTO } from "@/features/accounts/accounts-api"; import { cn } from "@/shared/lib/cn"; -import { formatDateTime, formatNumber } from "@/shared/lib/format"; +import { formatDateTime, formatNumber, formatTokenMillions } from "@/shared/lib/format"; export function AccountQuota({ quota, billing, locale }: { quota: QuotaDTO; billing?: BillingDTO; locale: string }) { const { t } = useTranslation(); @@ -17,8 +17,8 @@ export function AccountQuota({ quota, billing, locale }: { quota: QuotaDTO; bill } const percent = Math.min(100, Math.max(0, quota.usagePercent)); - const used = formatNumber(quota.used, locale, 0); - const limit = formatNumber(quota.limit, locale, 0); + const used = formatTokenMillions(quota.used, locale); + const limit = formatTokenMillions(quota.limit, locale); const isEstimated = !quota.limitKnown; const recoveryDescription = quota.nextProbeAt ? t("accounts.waitingResetUntil", { time: formatDateTime(quota.nextProbeAt, locale) }) @@ -26,7 +26,7 @@ export function AccountQuota({ quota, billing, locale }: { quota: QuotaDTO; bill ? t("accounts.probingQuota") : t("accounts.quotaResetUnknown"); const usage = quota.limit > 0 - ? isEstimated ? t("accounts.freeEstimatedUsage", { used, limit }) : `${used} / ${limit} tokens` + ? isEstimated ? t("accounts.freeEstimatedUsage", { used, limit }) : t("accounts.freeConfirmedUsage", { used, limit }) : t("accounts.freeObservedUsage", { used }); return ( diff --git a/frontend/src/features/accounts/accounts-page.tsx b/frontend/src/features/accounts/accounts-page.tsx index e59718df..e0c4185f 100644 --- a/frontend/src/features/accounts/accounts-page.tsx +++ b/frontend/src/features/accounts/accounts-page.tsx @@ -1162,6 +1162,9 @@ export function AccountsPage() { const summary = summaryQuery.data; const recoveringAccounts = summary?.recovering ?? 0; + const cooldownAccounts = summary?.recovery.cooldown ?? 0; + const waitingResetAccounts = summary?.recovery.waitingReset ?? 0; + const probingAccounts = summary?.recovery.probing ?? 0; const disabledAccounts = summary?.issues.disabled ?? 0; const invalidAccounts = summary?.issues.reauthRequired ?? 0; const riskAccounts = summary?.risk ?? 0; @@ -1171,6 +1174,23 @@ export function AccountsPage() { const consoleSummary = summary?.providers.grok_console ?? { total: 0, available: 0 }; const summaryLoading = summaryQuery.isPending; const summaryUnavailable = summaryQuery.isError; + const abnormalBreakdown = [ + { label: t("accounts.statusCooldown"), count: cooldownAccounts, tone: "bg-amber-500/10 text-amber-700 dark:text-amber-300" }, + { label: t("accounts.waitingReset"), count: waitingResetAccounts, tone: "bg-amber-500/10 text-amber-700 dark:text-amber-300" }, + { label: t("accounts.probing"), count: probingAccounts, tone: "bg-sky-500/10 text-sky-700 dark:text-sky-300" }, + { label: t("accounts.riskFilter"), count: riskAccounts, tone: "bg-orange-500/10 text-orange-700 dark:text-orange-300" }, + { label: t("accounts.statusDisabled"), count: disabledAccounts, tone: "bg-muted text-muted-foreground" }, + { label: t("accounts.statusReauthRequired"), count: invalidAccounts, tone: "bg-red-500/10 text-red-700 dark:text-red-300" }, + ]; + const abnormalDetail = abnormalBreakdown.map((item) => `${item.label} ${formatNumber(item.count, i18n.language, 0)}`).join(" · "); + const abnormalDetailItems = summaryUnavailable + ? [{ label: "-", value: "", tone: "bg-muted text-muted-foreground" }] + : abnormalBreakdown + .filter((item) => item.count > 0) + .map((item) => ({ ...item, value: formatNumber(item.count, i18n.language, 0) })); + if (!summaryUnavailable && abnormalDetailItems.length === 0) { + abnormalDetailItems.push({ label: t("accounts.statusActive"), value: "", tone: "bg-emerald-500/10 text-emerald-700 dark:text-emerald-300", count: 0 }); + } const providerAccountTotal = provider === "grok_build" ? buildSummary.total : provider === "grok_web" ? webSummary.total : consoleSummary.total; const hasProviderAccounts = providerAccountTotal > 0 || (result?.total ?? 0) > 0; const bindableEgressNodes = (egressNodesQuery.data?.items ?? []).filter((node) => node.enabled && node.proxyConfigured && scopeSupportsAccountProvider(node.scope, provider)); @@ -1262,12 +1282,8 @@ export function AccountsPage() { loading={summaryLoading} label={t("accounts.abnormalAccountCount")} value={summaryUnavailable ? "-" : formatNumber(abnormalAccounts, i18n.language, 0)} - detail={[ - `${t("accounts.statusCooldown")} ${formatNumber(recoveringAccounts, i18n.language, 0)}`, - `${t("accounts.riskAccountCount", { count: formatNumber(riskAccounts, i18n.language, 0) })}`, - `${t("accounts.statusDisabled")} ${formatNumber(disabledAccounts, i18n.language, 0)}`, - `${t("accounts.statusReauthRequired")} ${formatNumber(invalidAccounts, i18n.language, 0)}`, - ].join(" · ")} + detail={abnormalDetail} + detailItems={abnormalDetailItems} />
{detail}
+ {detailItems ? ( +{detail}
+ )}