diff --git a/README.md b/README.md index c76ad276..9a5a1af7 100644 --- a/README.md +++ b/README.md @@ -352,7 +352,7 @@ Egress nodes are scoped to Build, Web, Console, or Web assets. The admin console - Proxy-pool mode without global cooldown after one connection failure - Immediate recovery probes after fixed-proxy transport failures, with per-node coalescing and bounded waiting for fast retry - Optional [Egress Quality Guard](./tools/egress-quality-guard/README.md) for active per-node model probes, guarded quarantine, and recovery; enable it with the built-in `quality-guard` Compose profile -- Give each sticky session its own fixed node (`proxyPool=false`). Do not merge several stickies into one node, or the guard can only quarantine the whole group +- Nodes whose proxy username contains `{account}` are treated as lease-scoped: a passive anomaly temporarily removes only the audited account lease, then recovery pins the probe to that same account and node. An unhealthy probe renews the hold; an expired hold no longer blocks routing if the sidecar is unavailable, so stale guard state cannot strand an account indefinitely. The shared node is never disabled and the rendered proxy identity is never exposed. Ordinary fixed sticky sessions can still be managed as separate nodes Hysteria and TUIC are not supported yet. FlareSolverr accepts only HTTP/SOCKS proxy URLs, so automatic clearance refresh cannot use a tunnel share URL directly. diff --git a/README.zh-CN.md b/README.zh-CN.md index 5987a4b1..584b95b1 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -350,7 +350,7 @@ curl http://127.0.0.1:8000/v1/responses \ - 代理池模式,单次连接失败不会触发全局冷却 - 固定代理传输失败后立即复测;同节点复测自动合并,后续绑定请求限时等待并在恢复后快速重试 - 可选的[出口质量守护程序](./tools/egress-quality-guard/README.zh-CN.md),支持逐节点模型探测、防误杀隔离和自动恢复;通过内置的 `quality-guard` Compose profile 按需启用 -- 固定 sticky 会话应各自建成独立节点(`proxyPool=false`)。不要把多条 sticky 合成一个节点,否则质量守护只能整组摘流,无法定位坏会话 +- 代理用户名包含 `{account}` 的节点会被识别为租约级节点:被动审计异常只会临时移出对应的账号租约,冷却后固定使用同一账号和节点复测,复测异常会续期;若 sidecar 不可用,已到期的隔离不会继续阻断路由,避免孤儿状态永久卡住账号。共享节点始终不会因此停用,也不会暴露渲染后的代理身份。普通固定 sticky 会话仍可按独立节点管理 Hysteria 与 TUIC 暂未支持。FlareSolverr 仅接受 HTTP/SOCKS 代理地址,因此自动刷新 Clearance 暂不能直接使用隧道分享链接。 diff --git a/backend/internal/app/application.go b/backend/internal/app/application.go index c37c0313..17f6b12e 100644 --- a/backend/internal/app/application.go +++ b/backend/internal/app/application.go @@ -491,12 +491,13 @@ 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, - AccountCooldown: value.AccountCooldown.Value(), + Enabled: value.Enabled, + MaxAttempts: value.MaxAttempts, + HoldTimeout: value.HoldTimeout.Value(), + MinOutputTokens: int64(value.MinOutputTokens), + OnExhausted: value.OnExhausted, + AccountCooldown: value.AccountCooldown.Value(), + IdleAccountCooldown: value.IdleAccountCooldown.Value(), } } diff --git a/backend/internal/application/account/service.go b/backend/internal/application/account/service.go index bfb1843f..12646137 100644 --- a/backend/internal/application/account/service.go +++ b/backend/internal/application/account/service.go @@ -186,6 +186,10 @@ type View struct { QuotaWindows []accountdomain.QuotaWindow BuildBotFlagged bool BuildBotFlagSource int + // EnabledChanged is request-scoped update metadata. It is not persisted or + // serialized directly; the HTTP layer uses it to avoid warning when a PATCH + // merely repeats the account's existing enabled value. + EnabledChanged bool } type UpdateInput struct { @@ -2207,6 +2211,7 @@ func (s *Service) Update(ctx context.Context, id uint64, input UpdateInput) (Vie if err != nil { return View{}, mapRepositoryError(err) } + enabledChanged := input.Enabled != nil && value.Enabled != *input.Enabled if input.Name != nil { value.Name = strings.TrimSpace(*input.Name) if value.Name == "" { @@ -2276,7 +2281,30 @@ func (s *Service) Update(ctx context.Context, id uint64, input UpdateInput) (Vie } else if updated.Enabled && s.providers != nil && s.providers.SupportsCredentialRefresh(updated.Provider) { s.WakeCredentialRefresh() } - return s.Get(ctx, updated.ID) + view, err := s.Get(ctx, updated.ID) + if err != nil { + return View{}, err + } + view.EnabledChanged = enabledChanged + return view, nil +} + +// ClearCooldown resets request-path health so a cooled account can be +// scheduled again. UpdateHealth publishes InvalidationAccountHealthChanged, +// which overwrites the selector memory overlay (runtimeStore=memory). +func (s *Service) ClearCooldown(ctx context.Context, id uint64) (View, error) { + value, err := s.accounts.Get(ctx, id) + if err != nil { + return View{}, mapRepositoryError(err) + } + // missing_thinking is a durable quality strike, not a transient cooldown + // error. Clearing the timer must not turn the next miss into another first + // strike and bypass the second-miss disable policy. + healthMarker := accountdomain.NormalizeHealthMarker(value.LastError) + if err := s.accounts.UpdateHealth(ctx, value.ID, value.Provider, 0, nil, healthMarker, false); err != nil { + return View{}, mapRepositoryError(err) + } + return s.Get(ctx, id) } // MarkBuildAPIFallback 幂等写入 Build 账号 XAI 推理回退标记;失败不吞掉,调用方可重试。 diff --git a/backend/internal/application/egress/service.go b/backend/internal/application/egress/service.go index 481ead4f..8e1f3531 100644 --- a/backend/internal/application/egress/service.go +++ b/backend/internal/application/egress/service.go @@ -25,6 +25,8 @@ var ( ErrProbeStale = errors.New("代理配置在探测期间已更新,请重新测试") ErrQualityProbeUnavailable = errors.New("出口质量探测不可用") ErrQualityProbeNoAccount = errors.New("质量检测暂无可调度账号") + ErrQualityLeaseUnavailable = errors.New("租约级质量隔离不可用") + ErrQualityLeaseConflict = errors.New("租约状态已变化") ErrClearanceUnavailable = errors.New("Clearance 刷新不可用") ErrProxyProfileUnavailable = errors.New("共享代理配置功能不可用") ErrProxyProfileInUse = errors.New("共享代理配置仍被节点使用") @@ -42,6 +44,7 @@ const ( type QualityProbeInput struct { ClientKeyID uint64 + AccountID uint64 Model string Prompt string Expected string @@ -116,6 +119,7 @@ type Service struct { repository ServiceRepository proxyProfiles repository.EgressProxyProfileRepository accounts AccountBindingRepository + qualityLeases QualityLeaseRepository operations OperationsRepository cipher *security.Cipher mu sync.RWMutex @@ -131,6 +135,25 @@ type Service struct { autoAssignMaxMigrationShare float64 } +// QualityLeaseRepository is optional and deliberately separate from account +// binding administration. It exposes only the state required to isolate one +// account-bound proxy lease. +type QualityLeaseRepository interface { + Get(context.Context, uint64) (accountdomain.Credential, error) + ListEgressLeaseBlocks(context.Context, int, *accountdomain.EgressLeaseBlockCursor) ([]accountdomain.EgressLeaseBlock, error) + UpsertEgressLeaseBlock(context.Context, accountdomain.EgressLeaseBlock) (accountdomain.EgressLeaseBlock, error) + DeleteEgressLeaseBlock(context.Context, uint64, uint64, string) (bool, error) + DeleteEgressLeaseBlocksByNodes(context.Context, []uint64) (int64, error) + PruneInvalidEgressLeaseBlocks(context.Context, int) (int64, error) +} + +type QualityLeaseInput struct { + AccountID uint64 + NodeID uint64 + Reason string + QuarantineSeconds int +} + func (s *Service) SetQualityProber(value QualityProber) { s.mu.Lock() s.qualityProber = value @@ -174,6 +197,15 @@ func (s *Service) ProbeQuality(ctx context.Context, nodeID uint64, input Quality if node.Scope != domain.ScopeBuild || strings.TrimSpace(node.EncryptedProxyURL) == "" { return QualityProbeResult{}, fmt.Errorf("%w: 质量探测仅支持已配置代理的 grok_build 节点", ErrInvalidInput) } + if input.AccountID != 0 { + if !s.accountBoundProxy(node) || s.qualityLeases == nil { + return QualityProbeResult{}, fmt.Errorf("%w: 账号定向探测仅支持按账号派生代理的节点", ErrInvalidInput) + } + credential, loadErr := s.qualityLeases.Get(ctx, input.AccountID) + if loadErr != nil || credential.Provider != accountdomain.ProviderBuild || !credential.Enabled || credential.AuthStatus != accountdomain.AuthStatusActive || credential.EgressNodeID != nodeID { + return QualityProbeResult{}, ErrQualityProbeNoAccount + } + } s.mu.RLock() prober := s.qualityProber s.mu.RUnlock() @@ -241,10 +273,111 @@ func NewService(storage ServiceRepository, cipher *security.Cipher, browserUA st } if len(accounts) > 0 { service.accounts = accounts[0] + if leases, ok := accounts[0].(QualityLeaseRepository); ok { + service.qualityLeases = leases + } } return service } +func (s *Service) ListQualityLeases(ctx context.Context, limit int, cursor *accountdomain.EgressLeaseBlockCursor) ([]accountdomain.EgressLeaseBlock, error) { + if s.qualityLeases == nil { + return nil, ErrQualityLeaseUnavailable + } + if limit < 1 || limit > 1001 { + return nil, ErrInvalidInput + } + if cursor == nil { + for range 10 { + pruned, err := s.qualityLeases.PruneInvalidEgressLeaseBlocks(ctx, 1000) + if err != nil { + return nil, err + } + if pruned < 1000 { + break + } + } + nodes, err := s.repository.ListEgressNodes(ctx, domain.ScopeBuild, repository.SortQuery{}) + if err != nil { + return nil, err + } + staleNodeIDs := make([]uint64, 0) + for _, node := range nodes { + if !node.Enabled || !s.accountBoundProxy(node) { + staleNodeIDs = append(staleNodeIDs, node.ID) + } + } + if _, err := s.qualityLeases.DeleteEgressLeaseBlocksByNodes(ctx, staleNodeIDs); err != nil { + return nil, err + } + } + return s.qualityLeases.ListEgressLeaseBlocks(ctx, limit, cursor) +} + +func (s *Service) QuarantineQualityLease(ctx context.Context, input QualityLeaseInput) (accountdomain.EgressLeaseBlock, error) { + input.Reason = strings.TrimSpace(input.Reason) + if input.AccountID == 0 || input.NodeID == 0 || input.QuarantineSeconds < 30 || input.QuarantineSeconds > 86400 || !qualityLeaseReasonAllowed(input.Reason) { + return accountdomain.EgressLeaseBlock{}, ErrInvalidInput + } + if s.qualityLeases == nil { + return accountdomain.EgressLeaseBlock{}, ErrQualityLeaseUnavailable + } + node, err := s.repository.GetEgressNode(ctx, input.NodeID) + if errors.Is(err, repository.ErrNotFound) { + return accountdomain.EgressLeaseBlock{}, ErrNotFound + } + if err != nil { + return accountdomain.EgressLeaseBlock{}, err + } + if !node.Enabled || node.Scope != domain.ScopeBuild || !s.accountBoundProxy(node) { + return accountdomain.EgressLeaseBlock{}, ErrInvalidInput + } + credential, err := s.qualityLeases.Get(ctx, input.AccountID) + if err != nil || credential.Provider != accountdomain.ProviderBuild || !credential.Enabled || credential.AuthStatus != accountdomain.AuthStatusActive || credential.EgressNodeID != input.NodeID { + return accountdomain.EgressLeaseBlock{}, ErrQualityLeaseConflict + } + version, err := security.NewOpaqueToken(18) + if err != nil { + return accountdomain.EgressLeaseBlock{}, err + } + now := time.Now().UTC() + value, err := s.qualityLeases.UpsertEgressLeaseBlock(ctx, accountdomain.EgressLeaseBlock{ + AccountID: input.AccountID, NodeID: input.NodeID, Reason: input.Reason, Version: version, + CooldownUntil: now.Add(time.Duration(input.QuarantineSeconds) * time.Second), UpdatedAt: now, + }) + if errors.Is(err, repository.ErrConflict) || errors.Is(err, repository.ErrNotFound) { + return accountdomain.EgressLeaseBlock{}, ErrQualityLeaseConflict + } + return value, err +} + +func (s *Service) RestoreQualityLease(ctx context.Context, accountID, nodeID uint64, version string) (bool, error) { + version = strings.TrimSpace(version) + if accountID == 0 || nodeID == 0 || version == "" || len(version) > 64 { + return false, ErrInvalidInput + } + if s.qualityLeases == nil { + return false, ErrQualityLeaseUnavailable + } + restored, err := s.qualityLeases.DeleteEgressLeaseBlock(ctx, accountID, nodeID, version) + if err != nil { + return false, err + } + if !restored { + return false, ErrQualityLeaseConflict + } + return true, nil +} + +func qualityLeaseReasonAllowed(value string) bool { + switch value { + case "hard_tps", "soft_tps", "buffered_burst", "missing_thinking", "expected_marker_missing", "insufficient_output_tokens", "insufficient_generation_window", "probe_errors", "recovery_probe_error", "rotation_error": + return true + default: + return false + } +} + func (s *Service) UpdateDefaults(browserUA string) { s.mu.Lock() defer s.mu.Unlock() @@ -368,6 +501,7 @@ func (s *Service) Update(ctx context.Context, id uint64, input Input) (domain.Pu return domain.PublicNode{}, err } previousScope := value.Scope + previousProxyURL := value.EncryptedProxyURL value, err = s.applyInput(value, input, false) if err != nil { return domain.PublicNode{}, err @@ -386,6 +520,11 @@ func (s *Service) Update(ctx context.Context, id uint64, input Input) (domain.Pu } if err == nil { s.forgetClearance(updated.ID) + if !updated.Enabled || previousScope != updated.Scope || previousProxyURL != updated.EncryptedProxyURL { + if clearErr := s.clearQualityLeasesForNodes(ctx, []uint64{updated.ID}); clearErr != nil { + return s.publicNode(updated), clearErr + } + } } return s.publicNode(updated), err } @@ -503,6 +642,9 @@ func (s *Service) UpdateProxyProfile(ctx context.Context, id uint64, input Proxy } if proxyChanged { s.forgetClearances(nodeIDs) + if err := s.clearQualityLeasesForNodes(ctx, nodeIDs); err != nil { + return s.publicProxyProfile(updated), err + } } return s.publicProxyProfile(updated), nil } @@ -695,6 +837,11 @@ func (s *Service) UpdateManyEnabled(ctx context.Context, nodeIDs []uint64, enabl } if updated > 0 { s.forgetClearances(ids) + if !enabled { + if clearErr := s.clearQualityLeasesForNodes(ctx, ids); clearErr != nil { + return updated, clearErr + } + } } return updated, nil } @@ -718,9 +865,22 @@ func (s *Service) UpdateManyEnabled(ctx context.Context, nodeIDs []uint64, enabl s.forgetClearance(id) updated++ } + if !enabled && updated > 0 { + if err := s.clearQualityLeasesForNodes(ctx, ids); err != nil { + return updated, err + } + } return updated, nil } +func (s *Service) clearQualityLeasesForNodes(ctx context.Context, nodeIDs []uint64) error { + if s.qualityLeases == nil || len(nodeIDs) == 0 { + return nil + } + _, err := s.qualityLeases.DeleteEgressLeaseBlocksByNodes(ctx, uniqueIDs(nodeIDs)) + return err +} + func (s *Service) Delete(ctx context.Context, id uint64) error { err := s.repository.DeleteEgressNode(ctx, id) if errors.Is(err, repository.ErrNotFound) { diff --git a/backend/internal/application/gateway/quality_probe.go b/backend/internal/application/gateway/quality_probe.go index e66870af..c796bfe3 100644 --- a/backend/internal/application/gateway/quality_probe.go +++ b/backend/internal/application/gateway/quality_probe.go @@ -78,7 +78,7 @@ func (s *Service) ProbeEgressQuality(ctx context.Context, nodeID uint64, input e probeCtx := infraegress.WithQualityProbe(ctx) result, err := s.CreateChatCompletion(probeCtx, Input{ RequestID: requestID, ClientKey: key, PublicModel: publicModel, Body: body, - Streaming: true, Operation: audit.OperationChat, ForcedEgressNodeID: nodeID, + Streaming: true, Operation: audit.OperationChat, ForcedEgressNodeID: nodeID, ForcedAccountID: input.AccountID, }) if err != nil { return egressapp.QualityProbeResult{}, normalizeQualityProbeRequestError(err) diff --git a/backend/internal/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go index 78cd164e..548fca79 100644 --- a/backend/internal/application/gateway/quality_retry.go +++ b/backend/internal/application/gateway/quality_retry.go @@ -45,17 +45,24 @@ type QualityRetryRuntime struct { MinOutputTokens int64 OnExhausted string AccountCooldown time.Duration + // IdleAccountCooldown is applied to truly empty upstream streams + // (idle timeout / empty peek). Missing-thinking still uses AccountCooldown. + IdleAccountCooldown time.Duration } // 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 + HasThinking bool + // ReasoningStarted is an empty reasoning item or the Chat SSE stub + // `: grok2api-reasoning-start`. That is not proof of thinking: 降智 + // still emits the stub, then dumps visible tokens with usage 0. + ReasoningStarted bool + VisibleTokens int64 + ReasoningTokens int64 + OutputTokens int64 + Terminal bool + HoldExpired bool } // QualityVerdict is the hold decision for one upstream stream. @@ -90,6 +97,9 @@ func normalizeQualityRetry(cfg QualityRetryRuntime) QualityRetryRuntime { if cfg.AccountCooldown <= 0 { cfg.AccountCooldown = defaultMissingThinkingCooldown } + if cfg.IdleAccountCooldown <= 0 { + cfg.IdleAccountCooldown = qualityIdleAccountCooldown + } cfg.OnExhausted = normalizeQualityExhaustionPolicy(cfg.OnExhausted) return cfg } @@ -110,23 +120,37 @@ func (s *Service) qualityRetryConfig() 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. +// Streamed thinking always delivers: reasoning/summary deltas, or a +// reasoning item with encrypted_content. Usage.reasoning_tokens alone +// does not — degraded upstreams fill that field without ciphertext or +// deltas. A finished sample with enough visible output and no streamed +// thinking is withheld. // Short replies below minOutput are delivered so "ok"/"yes" is not retried. // A hold timeout with no visible output is not fail-open: keep waiting for // more bytes or a stream abort so an empty hang is not flushed as HTTP 200. +// +// An empty reasoning stub is not thinking. Wait for usage/terminal so +// encrypted thinking (tokens arrive at the end) is not withheld, and so +// 200 + 推理·高 + reasoning=0 is not delivered the moment the stub appears. func ClassifyQualityHold(sig QualityStreamSignals, minOutput int64) QualityVerdict { if minOutput <= 0 { minOutput = defaultQualityMinOutput } - if sig.HasThinking || sig.ReasoningTokens > 0 { + if sig.HasThinking { return QualityDeliver } - output := sig.OutputTokens - if output < sig.VisibleTokens { - output = sig.VisibleTokens + // Prefer observed/derived visible output. Total output includes reasoning + // tokens, which are deliberately not trusted as quality evidence above. If + // the stream exposed no visible count at all, retain OutputTokens as a + // compatibility fallback for terminal usage-only responses. + output := sig.VisibleTokens + if output <= 0 { + output = sig.OutputTokens } enough := output >= minOutput + if sig.ReasoningStarted && !sig.Terminal && !sig.HoldExpired { + return QualityWait + } if sig.Terminal { if output <= 0 { return QualityWait @@ -143,6 +167,9 @@ func ClassifyQualityHold(sig QualityStreamSignals, minOutput int64) QualityVerdi if output <= 0 { return QualityWait } + if enough { + return QualityWithhold + } return QualityDeliver } return QualityWait @@ -270,10 +297,12 @@ func shouldHoldQualityStream(input Input, ownership *inferencedomain.ResponseOwn 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) { + // Client-executed tools are safe to hold: their calls have not reached the + // client yet, and completed results in the next request are immutable input. + // Hosted tools are different. Retrying them can repeat an upstream search, + // sandbox run, image job, or remote MCP call, so retain the old no-replay + // safety boundary for any request that declares one. + if qualityRequestHasReplayUnsafeHostedTools(input.Body) { return false } // Aliases are rewritten before this gate, so inspect the effective request @@ -288,12 +317,76 @@ func shouldHoldQualityStream(input Input, ownership *inferencedomain.ResponseOwn return modeldomain.SupportsReasoningForProvider(route.Provider, route.UpstreamModel) } -func qualityRequestUsesTools(body []byte) bool { - var payload map[string]json.RawMessage - if json.Unmarshal(body, &payload) != nil { +func qualityRequestHasReplayUnsafeHostedTools(body []byte) bool { + var payload map[string]any + if json.Unmarshal(body, &payload) != nil || payload == nil { return false } - return nonEmptyJSONCollection(payload["tools"]) || nonEmptyJSONCollection(payload["functions"]) + if raw, exists := payload["web_search_options"]; exists && raw != nil { + return true + } + if raw, exists := payload["mcp_servers"]; exists && raw != nil { + servers, ok := raw.([]any) + if !ok || len(servers) > 0 { + return true + } + } + if qualityToolListHasReplayUnsafeHostedTool(payload["tools"]) { + return true + } + // Responses Tool Search can load declarations later in the request. Only + // inspect additional_tools items; arbitrary user/schema objects may also + // contain a field named "tools" and must not affect the retry policy. + items, _ := payload["input"].([]any) + for _, rawItem := range items { + item, ok := rawItem.(map[string]any) + if !ok || jsonNodeString(item["type"]) != "additional_tools" { + continue + } + if qualityToolListHasReplayUnsafeHostedTool(item["tools"]) { + return true + } + } + return false +} + +func qualityToolListHasReplayUnsafeHostedTool(value any) bool { + tools, ok := value.([]any) + if !ok { + return false + } + for _, rawTool := range tools { + tool, ok := rawTool.(map[string]any) + if !ok { + continue + } + kind := jsonNodeString(tool["type"]) + switch kind { + case "", "function", "custom", "local_shell", "apply_patch", "tool_search": + // These declarations only ask the model to return a call. Execution + // happens in the client after the held response is committed. + continue + case "shell": + environment, _ := tool["environment"].(map[string]any) + if jsonNodeString(environment["type"]) != "local" { + return true + } + case "namespace": + if qualityToolListHasReplayUnsafeHostedTool(tool["tools"]) { + return true + } + default: + // Default to no replay for every server/native tool, including types + // added by future protocol versions that this gateway does not know yet. + return true + } + } + return false +} + +func jsonNodeString(value any) string { + text, _ := value.(string) + return strings.ToLower(strings.TrimSpace(text)) } func qualityRequestDisablesReasoning(body []byte) bool { @@ -320,14 +413,6 @@ func qualityRequestDisablesReasoning(body []byte) bool { 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) diff --git a/backend/internal/application/gateway/quality_retry_scan.go b/backend/internal/application/gateway/quality_retry_scan.go index 3a29d8b9..c5aa4169 100644 --- a/backend/internal/application/gateway/quality_retry_scan.go +++ b/backend/internal/application/gateway/quality_retry_scan.go @@ -5,6 +5,7 @@ import ( "context" "encoding/json" "io" + "strings" "sync" "time" "unicode/utf8" @@ -13,23 +14,27 @@ import ( ) const ( - qualityProtocolChat = "chat" - qualityProtocolResponses = "responses" - qualityProtocolAnthropic = "anthropic" - qualityReasoningSSEComment = ": grok2api-reasoning-start" - qualityHoldMaxBufferBytes = 4 << 20 + qualityProtocolChat = "chat" + qualityProtocolResponses = "responses" + qualityProtocolAnthropic = "anthropic" + qualityReasoningSSEComment = ": grok2api-reasoning-start" + qualityReasoningEvidenceSSEComment = ": grok2api-reasoning-evidence" + qualityHoldMaxBufferBytes = 4 << 20 ) type qualityScanState struct { - protocol string - pending []byte - hasThinking bool - visibleRunes int - reasoningTokens int64 - outputTokens int64 - usage Usage - responseID string - terminal bool + protocol string + pending []byte + hasThinking bool + reasoningStarted bool + visibleRunes int + aggregateRunes int + semanticOutput bool + reasoningTokens int64 + outputTokens int64 + usage Usage + responseID string + terminal bool } type qualityReadResult struct { @@ -124,7 +129,8 @@ func qualityProtocolForOperation(operation audit.Operation) string { } func (s *qualityScanState) signals() QualityStreamSignals { - visible := int64((s.visibleRunes + 3) / 4) + visibleRunes := max(s.visibleRunes, s.aggregateRunes) + visible := int64((visibleRunes + 3) / 4) if s.usage.Reported { fromUsage := s.usage.OutputTokens - s.usage.ReasoningTokens if fromUsage > visible { @@ -135,12 +141,16 @@ func (s *qualityScanState) signals() QualityStreamSignals { if s.usage.Reported && s.usage.OutputTokens > output { output = s.usage.OutputTokens } + // Usage.reasoning_tokens is not proof of thinking. 降智 accounts report + // hundreds of reasoning tokens on completed while the stream never sent + // reasoning_text / reasoning_summary deltas (TUI shows no thoughts). 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, + HasThinking: s.hasThinking, + ReasoningStarted: s.reasoningStarted || s.hasThinking, + VisibleTokens: visible, + ReasoningTokens: max(s.reasoningTokens, s.usage.ReasoningTokens), + OutputTokens: output, + Terminal: s.terminal, } } @@ -165,6 +175,14 @@ func ObserveQualityChunk(state *qualityScanState, chunk []byte) { continue } if bytes.Equal(line, []byte(qualityReasoningSSEComment)) { + // Timing stub only. 降智 still emits this, then usage.reasoning_tokens=0. + state.reasoningStarted = true + continue + } + if bytes.Equal(line, []byte(qualityReasoningEvidenceSSEComment)) { + // Protocol converters cannot expose encrypted_content in every public + // JSON contract. This internal SSE comment preserves that evidence. + state.reasoningStarted = true state.hasThinking = true continue } @@ -201,6 +219,8 @@ func observeQualityChat(state *qualityScanState, payload []byte) { Reasoning string `json:"reasoning"` ReasoningContent string `json:"reasoning_content"` ThinkingContent string `json:"thinking_content"` + ToolCalls []any `json:"tool_calls"` + FunctionCall any `json:"function_call"` } `json:"delta"` FinishReason string `json:"finish_reason"` } `json:"choices"` @@ -228,36 +248,57 @@ func observeQualityChat(state *qualityScanState, payload []byte) { 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 != "" { + if strings.TrimSpace(delta.Reasoning) != "" || strings.TrimSpace(delta.ReasoningContent) != "" || strings.TrimSpace(delta.ThinkingContent) != "" { state.hasThinking = true } if delta.Content != "" { noteVisibleContent(state, delta.Content) } + if len(delta.ToolCalls) > 0 || delta.FunctionCall != nil { + state.semanticOutput = true + } if choice.FinishReason != "" { state.terminal = true } } } +type qualityResponsesOutputItem struct { + ID string `json:"id"` + Type string `json:"type"` + EncryptedContent string `json:"encrypted_content"` + Content []struct { + Type string `json:"type"` + Text string `json:"text"` + Refusal string `json:"refusal"` + } `json:"content"` +} + +func noteResponsesReasoningItem(state *qualityScanState, item qualityResponsesOutputItem) { + if !strings.EqualFold(strings.TrimSpace(item.Type), "reasoning") { + return + } + if strings.TrimSpace(item.ID) != "" { + state.reasoningStarted = true + } + if strings.TrimSpace(item.EncryptedContent) != "" { + state.hasThinking = 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"` + Type string `json:"type"` + Delta string `json:"delta"` + Item qualityResponsesOutputItem `json:"item"` Response *struct { - ID string `json:"id"` - Model string `json:"model"` - Usage *struct { + ID string `json:"id"` + Model string `json:"model"` + Output []qualityResponsesOutputItem `json:"output"` + Usage *struct { OutputTokens int64 `json:"output_tokens"` InputTokens int64 `json:"input_tokens"` TotalTokens int64 `json:"total_tokens"` @@ -274,22 +315,28 @@ func observeQualityResponses(state *qualityScanState, payload []byte) { 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 != "" { + if strings.TrimSpace(event.Delta) != "" { state.hasThinking = true } + case "response.output_item.added", "response.output_item.done": + noteResponsesReasoningItem(state, event.Item) + state.aggregateRunes = max(state.aggregateRunes, observeQualityResponsesOutputItem(state, event.Item)) case "response.output_text.delta": if event.Delta != "" { noteVisibleContent(state, event.Delta) } + case "response.function_call_arguments.delta", "response.custom_tool_call_input.delta", "response.mcp_call_arguments.delta": + if event.Delta != "" { + state.semanticOutput = true + } } if event.Response != nil { if state.responseID == "" { state.responseID = event.Response.ID } + for _, item := range event.Response.Output { + noteResponsesReasoningItem(state, item) + } if event.Response.Usage != nil { state.usage.Reported = true state.usage.InputTokens = event.Response.Usage.InputTokens @@ -299,11 +346,44 @@ func observeQualityResponses(state *qualityScanState, payload []byte) { 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 + } + aggregateRunes := 0 + for _, item := range event.Response.Output { + aggregateRunes += observeQualityResponsesOutputItem(state, item) + } + state.aggregateRunes = max(state.aggregateRunes, aggregateRunes) + } +} + +func observeQualityResponsesOutputItem(state *qualityScanState, item qualityResponsesOutputItem) int { + if state == nil { + return 0 + } + visibleRunes := 0 + switch item.Type { + case "", "reasoning": + return 0 + case "message": + for _, content := range item.Content { + text := content.Text + if text == "" { + text = content.Refusal + } + if text != "" { + visibleRunes += utf8.RuneCountInString(text) + state.semanticOutput = true + continue + } + if content.Type != "" && content.Type != "output_text" && content.Type != "refusal" { + state.semanticOutput = true } } + default: + // Function, shell, MCP and other call items are meaningful output even + // when the provider omits usage and argument-delta events. + state.semanticOutput = true } + return visibleRunes } func observeQualityAnthropic(state *qualityScanState, payload []byte) { @@ -311,11 +391,15 @@ func observeQualityAnthropic(state *qualityScanState, payload []byte) { Type string `json:"type"` ContentBlock struct { Type string `json:"type"` + Text string `json:"text"` + Data string `json:"data"` } `json:"content_block"` Delta struct { - Type string `json:"type"` - Text string `json:"text"` - Thinking string `json:"thinking"` + Type string `json:"type"` + Text string `json:"text"` + Thinking string `json:"thinking"` + PartialJSON string `json:"partial_json"` + Signature string `json:"signature"` } `json:"delta"` Usage *struct { OutputTokens int64 `json:"output_tokens"` @@ -331,16 +415,39 @@ func observeQualityAnthropic(state *qualityScanState, payload []byte) { case "message_stop": state.terminal = true case "content_block_start": - if event.ContentBlock.Type == "thinking" { - state.hasThinking = true + switch event.ContentBlock.Type { + case "thinking": + state.reasoningStarted = true + case "redacted_thinking": + state.reasoningStarted = true + if strings.TrimSpace(event.ContentBlock.Data) != "" { + state.hasThinking = true + } + case "text": + if event.ContentBlock.Text != "" { + noteVisibleContent(state, event.ContentBlock.Text) + state.semanticOutput = true + } + case "": + default: + state.semanticOutput = true } case "content_block_delta": - if event.Delta.Type == "thinking_delta" && event.Delta.Thinking != "" { + if event.Delta.Type == "thinking_delta" && strings.TrimSpace(event.Delta.Thinking) != "" { + state.hasThinking = true + } + if event.Delta.Type == "signature_delta" && strings.TrimSpace(event.Delta.Signature) != "" { + // Anthropic Messages represents Responses encrypted_content as a + // signature delta. A non-empty signature is encrypted thinking proof. + state.reasoningStarted = true state.hasThinking = true } if event.Delta.Type == "text_delta" && event.Delta.Text != "" { noteVisibleContent(state, event.Delta.Text) } + if event.Delta.Type == "input_json_delta" && event.Delta.PartialJSON != "" { + state.semanticOutput = true + } } if event.Usage != nil { state.usage.Reported = true @@ -348,9 +455,6 @@ func observeQualityAnthropic(state *qualityScanState, payload []byte) { 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 - } } } @@ -376,6 +480,12 @@ func peekQualityStream(ctx context.Context, body io.ReadCloser, protocol string, if verdict := ClassifyQualityHold(sig, cfg.MinOutputTokens); verdict != QualityWait { return newPrefixReplay(&held, pump), verdict, state.usage, state.responseID, nil } + // A completed empty stream must rotate immediately. Waiting for idle + // timeout after response.completed / [DONE] surfaces HTTP 200 with 0 + // tokens and makes Grok TUI retry for 50–120s. + if sig.Terminal { + return finishQualityPeek(&held, pump, &state, cfg) + } select { case <-ctx.Done(): @@ -421,6 +531,9 @@ func finishQualityPeek(held *bytes.Buffer, pump *qualityReadPump, state *quality state.terminal = true signals := state.signals() if !signals.HasThinking && signals.ReasoningTokens <= 0 && signals.OutputTokens <= 0 && signals.VisibleTokens <= 0 { + if state.semanticOutput { + return newPrefixReplay(held, pump), QualityDeliver, state.usage, state.responseID, nil + } return newPrefixReplay(held, pump), QualityWait, state.usage, state.responseID, errQualityEmptyStream } return newPrefixReplay(held, pump), ClassifyQualityHold(signals, cfg.MinOutputTokens), state.usage, state.responseID, nil diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go index 3c0035d8..1e619dc5 100644 --- a/backend/internal/application/gateway/quality_retry_test.go +++ b/backend/internal/application/gateway/quality_retry_test.go @@ -20,6 +20,7 @@ import ( 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/provider/conversation" "github.com/chenyme/grok2api/backend/internal/infra/runtime/memory" neterrorpkg "github.com/chenyme/grok2api/backend/internal/pkg/neterror" ) @@ -32,12 +33,15 @@ func TestClassifyQualityHold(t *testing.T) { 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: "usage reasoning tokens alone withhold", sig: QualityStreamSignals{ReasoningTokens: 40, VisibleTokens: 80, Terminal: true}, want: QualityWithhold}, {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 visible output ignores inflated total", sig: QualityStreamSignals{VisibleTokens: 1, OutputTokens: 80, Terminal: true}, want: QualityDeliver}, {name: "short no think delivers", sig: QualityStreamSignals{VisibleTokens: 10, Terminal: true}, want: QualityDeliver}, {name: "empty terminal waits for transport handling", sig: QualityStreamSignals{Terminal: true}, want: QualityWait}, {name: "midstream enough content withhold", sig: QualityStreamSignals{VisibleTokens: 64}, want: QualityWithhold}, + {name: "stub midstream waits even with enough visible", sig: QualityStreamSignals{ReasoningStarted: true, VisibleTokens: 64}, want: QualityWait}, + {name: "stub terminal enough withhold", sig: QualityStreamSignals{ReasoningStarted: true, VisibleTokens: 64, Terminal: true}, 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}, {name: "hold expired empty waits", sig: QualityStreamSignals{HoldExpired: true}, want: QualityWait}, @@ -263,16 +267,191 @@ func TestObserveQualityChunkShortNoThink(t *testing.T) { } } +func TestObserveQualityChunkShortNoThinkIgnoresFakeReasoningUsage(t *testing.T) { + t.Parallel() + state := qualityScanState{protocol: qualityProtocolChat} + ObserveQualityChunk(&state, []byte(sse( + ": grok2api-reasoning-start", + `data: {"choices":[{"delta":{"content":"OK"}}]}`, + `data: {"usage":{"completion_tokens":80,"completion_tokens_details":{"reasoning_tokens":79}}}`, + "data: [DONE]", + ))) + sig := state.signals() + if sig.VisibleTokens >= 32 || sig.OutputTokens != 80 || sig.ReasoningTokens != 79 { + t.Fatalf("fake-usage short reply signals = %#v", sig) + } + if got := ClassifyQualityHold(sig, 32); got != QualityDeliver { + t.Fatalf("short visible reply must not be withheld by inflated usage: %s (%#v)", got, sig) + } +} + +func TestObserveQualityConvertedEncryptedThinking(t *testing.T) { + t.Parallel() + source := sse( + `data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.6"}}`, + `data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`, + `data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"gAAAA-cipher"}}`, + `data: {"type":"response.output_text.delta","delta":"`+strings.Repeat("word ", 40)+`"}`, + `data: {"type":"response.completed","response":{"id":"resp_1","model":"grok-4.6","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`, + ) + tests := []struct { + name string + operation string + protocol string + options conversation.ResponseOptions + }{ + {name: "chat", operation: conversation.OperationChat, protocol: qualityProtocolChat}, + {name: "messages", operation: conversation.OperationMessages, protocol: qualityProtocolAnthropic, options: conversation.ResponseOptions{AnthropicThinking: true}}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + converted, err := io.ReadAll(conversation.ConvertResponseStreamWithOptions( + io.NopCloser(strings.NewReader(source)), test.operation, test.options, + )) + if err != nil { + t.Fatal(err) + } + state := qualityScanState{protocol: test.protocol} + ObserveQualityChunk(&state, converted) + sig := state.signals() + if !sig.HasThinking { + t.Fatalf("converted encrypted thinking evidence was lost:\n%s", converted) + } + if got := ClassifyQualityHold(sig, 32); got != QualityDeliver { + t.Fatalf("converted encrypted thinking verdict = %s (%#v)", got, sig) + } + }) + } +} + +func TestObserveQualityChunkWhitespaceIsNotThinking(t *testing.T) { + t.Parallel() + tests := []struct { + name string + protocol string + fixture string + }{ + {name: "chat", protocol: qualityProtocolChat, fixture: sse(`data: {"choices":[{"delta":{"reasoning_content":" \n\t"}}]}`)}, + {name: "responses", protocol: qualityProtocolResponses, fixture: sse(`data: {"type":"response.reasoning_summary_text.delta","delta":" \n\t"}`)}, + {name: "messages", protocol: qualityProtocolAnthropic, fixture: sse(`data: {"type":"content_block_delta","delta":{"type":"thinking_delta","thinking":" \n\t"}}`)}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + state := qualityScanState{protocol: test.protocol} + ObserveQualityChunk(&state, []byte(test.fixture)) + if sig := state.signals(); sig.HasThinking { + t.Fatalf("whitespace-only reasoning counted as thinking: %#v", sig) + } + }) + } +} + +func TestObserveQualityChunkAnthropicSignatureIsThinking(t *testing.T) { + t.Parallel() + state := qualityScanState{protocol: qualityProtocolAnthropic} + ObserveQualityChunk(&state, []byte(sse( + `data: {"type":"content_block_delta","delta":{"type":"signature_delta","signature":"gAAAA-cipher"}}`, + ))) + if sig := state.signals(); !sig.HasThinking || !sig.ReasoningStarted { + t.Fatalf("non-empty Anthropic signature must count as encrypted thinking: %#v", sig) + } +} + func TestObserveQualityChunkResponsesReasoningItem(t *testing.T) { t.Parallel() - state := qualityScanState{protocol: qualityProtocolResponses} - ObserveQualityChunk(&state, []byte(sse( + fake := qualityScanState{protocol: qualityProtocolResponses} + ObserveQualityChunk(&fake, []byte(sse( `data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`, + `data: {"type":"response.output_text.delta","delta":"`+strings.Repeat("hello ", 40)+`"}`, + `data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`, + ))) + fakeSig := fake.signals() + if fakeSig.HasThinking { + t.Fatalf("usage-only reasoning tokens must not count as thinking: %#v", fakeSig) + } + if !fakeSig.ReasoningStarted || fakeSig.ReasoningTokens != 60 { + t.Fatalf("usage-only signals = %#v", fakeSig) + } + if ClassifyQualityHold(fakeSig, 32) != QualityWithhold { + t.Fatalf("usage-only reasoning with no deltas must withhold: %#v", fakeSig) + } + + real := qualityScanState{protocol: qualityProtocolResponses} + ObserveQualityChunk(&real, []byte(sse( + `data: {"type":"response.reasoning_summary_text.delta","delta":"plan the fix"}`, `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()) + realSig := real.signals() + if !realSig.HasThinking || realSig.ReasoningTokens != 60 { + t.Fatalf("streamed summary must count as thinking: %#v", realSig) + } + if ClassifyQualityHold(realSig, 32) != QualityDeliver { + t.Fatalf("streamed reasoning summary should deliver: %#v", realSig) + } + + encrypted := qualityScanState{protocol: qualityProtocolResponses} + ObserveQualityChunk(&encrypted, []byte(sse( + `data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`, + `data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"gAAAA-cipher"}}`, + `data: {"type":"response.output_text.delta","delta":"hello hello hello hello hello hello hello hello"}`, + `data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`, + ))) + encSig := encrypted.signals() + if !encSig.HasThinking || encSig.ReasoningTokens != 60 { + t.Fatalf("encrypted reasoning item must count as thinking: %#v", encSig) + } + if ClassifyQualityHold(encSig, 32) != QualityDeliver { + t.Fatalf("encrypted thinking should deliver: %#v", encSig) + } +} + +func TestObserveQualityChunkEmptyReasoningStubIsNotThinking(t *testing.T) { + t.Parallel() + content := strings.Repeat("word ", 40) + chat := qualityScanState{protocol: qualityProtocolChat} + ObserveQualityChunk(&chat, []byte(sse( + ": grok2api-reasoning-start", + `data: {"choices":[{"delta":{"content":"`+content+`"}}]}`, + `data: {"usage":{"completion_tokens":45,"completion_tokens_details":{"reasoning_tokens":0}}}`, + "data: [DONE]", + ))) + chatSig := chat.signals() + if chatSig.HasThinking { + t.Fatalf("chat SSE stub must not count as thinking: %#v", chatSig) + } + if !chatSig.ReasoningStarted || !chatSig.Terminal || chatSig.ReasoningTokens != 0 { + t.Fatalf("chat stub signals = %#v", chatSig) + } + if ClassifyQualityHold(chatSig, 32) != QualityWithhold { + t.Fatalf("chat stub + 0 reasoning must withhold, got %s (%#v)", ClassifyQualityHold(chatSig, 32), chatSig) + } + + mid := qualityScanState{protocol: qualityProtocolChat} + ObserveQualityChunk(&mid, []byte(sse( + ": grok2api-reasoning-start", + `data: {"choices":[{"delta":{"content":"`+content+`"}}]}`, + ))) + midSig := mid.signals() + if midSig.HasThinking || !midSig.ReasoningStarted || midSig.Terminal { + t.Fatalf("midstream stub signals = %#v", midSig) + } + if ClassifyQualityHold(midSig, 32) != QualityWait { + t.Fatalf("midstream stub must wait for usage, got %s (%#v)", ClassifyQualityHold(midSig, 32), midSig) + } + + responses := qualityScanState{protocol: qualityProtocolResponses} + ObserveQualityChunk(&responses, []byte(sse( + `data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`, + `data: {"type":"response.output_text.delta","delta":"`+content+`"}`, + `data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":45,"output_tokens_details":{"reasoning_tokens":0}}}}`, + ))) + respSig := responses.signals() + if respSig.HasThinking { + t.Fatalf("empty responses reasoning item must not count as thinking: %#v", respSig) + } + if ClassifyQualityHold(respSig, 32) != QualityWithhold { + t.Fatalf("empty reasoning item + 0 tokens must withhold, got %s (%#v)", ClassifyQualityHold(respSig, 32), respSig) } } @@ -461,6 +640,163 @@ func TestPeekQualityStreamHoldTimeoutEmptyDoesNotFailOpen(t *testing.T) { } } +type qualityOpenPeekResult struct { + replay io.ReadCloser + verdict QualityVerdict + err error +} + +func peekOpenQualityStreamForTest(t *testing.T, protocol, stream string) qualityOpenPeekResult { + t.Helper() + reader, writer := io.Pipe() + done := make(chan qualityOpenPeekResult, 1) + go func() { + replay, verdict, _, _, err := peekQualityStream( + context.Background(), reader, protocol, + QualityRetryRuntime{MinOutputTokens: 32, HoldTimeout: 2 * time.Second}, + ) + done <- qualityOpenPeekResult{replay: replay, verdict: verdict, err: err} + }() + if _, err := io.WriteString(writer, stream); err != nil { + _ = writer.Close() + t.Fatal(err) + } + select { + case result := <-done: + _ = writer.Close() + return result + case <-time.After(500 * time.Millisecond): + _ = writer.CloseWithError(errors.New("test terminal stream timeout")) + result := <-done + if result.replay != nil { + _ = result.replay.Close() + } + t.Fatal("terminal stream waited for hold/idle instead of finishing while the connection remained open") + return qualityOpenPeekResult{} + } +} + +func TestPeekQualityStreamEmptyCompletedRetriesWithoutIdle(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + protocol string + stream string + }{ + { + name: "responses completed", + protocol: qualityProtocolResponses, + stream: sse( + `data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":0}}}`, + ), + }, + { + name: "responses completed with empty text node", + protocol: qualityProtocolResponses, + stream: sse( + `data: {"type":"response.completed","response":{"id":"resp_1","output":[{"type":"message","content":[{"type":"output_text","text":""}]}],"usage":{"output_tokens":0}}}`, + ), + }, + {name: "chat done", protocol: qualityProtocolChat, stream: sse("data: [DONE]")}, + { + name: "chat finish reason", + protocol: qualityProtocolChat, + stream: sse(`data: {"choices":[{"delta":{},"finish_reason":"stop"}]}`), + }, + {name: "anthropic message stop", protocol: qualityProtocolAnthropic, stream: sse(`data: {"type":"message_stop"}`)}, + } { + t.Run(test.name, func(t *testing.T) { + result := peekOpenQualityStreamForTest(t, test.protocol, test.stream) + if result.replay != nil { + defer result.replay.Close() + } + if !errors.Is(result.err, errQualityEmptyStream) { + t.Fatalf("peek error = %v, want empty stream", result.err) + } + if result.verdict != QualityWait { + t.Fatalf("verdict = %s, want wait so the attempt loop retries as transport", result.verdict) + } + }) + } +} + +func TestPeekQualityStreamTerminalSemanticOutputIsNotEmpty(t *testing.T) { + t.Parallel() + longText := strings.Repeat("word ", 40) + shortText := strings.Repeat("a", 80) + for _, test := range []struct { + name string + protocol string + stream string + wantVerdict QualityVerdict + }{ + { + name: "responses aggregate function call", + protocol: qualityProtocolResponses, + stream: sse( + `data: {"type":"response.completed","response":{"id":"resp_1","output":[{"type":"function_call","call_id":"call_1","name":"read_file","arguments":"{}"}]}}`, + ), + wantVerdict: QualityDeliver, + }, + { + name: "responses streamed function call", + protocol: qualityProtocolResponses, + stream: sse( + `data: {"type":"response.output_item.added","item":{"type":"function_call","call_id":"call_1","name":"read_file","arguments":""}}`, + `data: {"type":"response.completed","response":{"id":"resp_1","output":[]}}`, + ), + wantVerdict: QualityDeliver, + }, + { + name: "chat tool call", + protocol: qualityProtocolChat, + stream: sse( + `data: {"choices":[{"delta":{"tool_calls":[{"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{}"}}]},"finish_reason":"tool_calls"}]}`, + ), + wantVerdict: QualityDeliver, + }, + { + name: "anthropic tool use", + protocol: qualityProtocolAnthropic, + stream: sse( + `data: {"type":"content_block_start","content_block":{"type":"tool_use","id":"tool_1","name":"read_file","input":{}}}`, + `data: {"type":"message_stop"}`, + ), + wantVerdict: QualityDeliver, + }, + { + name: "responses aggregate long text", + protocol: qualityProtocolResponses, + stream: sse( + `data: {"type":"response.completed","response":{"id":"resp_1","output":[{"type":"message","content":[{"type":"output_text","text":"` + longText + `"}]}]}}`, + ), + wantVerdict: QualityWithhold, + }, + { + name: "responses aggregate does not double count deltas", + protocol: qualityProtocolResponses, + stream: sse( + `data: {"type":"response.output_text.delta","delta":"`+shortText+`"}`, + `data: {"type":"response.completed","response":{"id":"resp_1","output":[{"type":"message","content":[{"type":"output_text","text":"`+shortText+`"}]}]}}`, + ), + wantVerdict: QualityDeliver, + }, + } { + t.Run(test.name, func(t *testing.T) { + result := peekOpenQualityStreamForTest(t, test.protocol, test.stream) + if result.replay != nil { + defer result.replay.Close() + } + if result.err != nil { + t.Fatalf("peek error = %v, want semantic output", result.err) + } + if result.verdict != test.wantVerdict { + t.Fatalf("verdict = %s, want %s", result.verdict, test.wantVerdict) + } + }) + } +} + func TestPeekQualityStreamEmptyEOFRequestsAnotherAccount(t *testing.T) { t.Parallel() replay, verdict, _, _, err := peekQualityStream( @@ -560,17 +896,94 @@ func TestShouldHoldQualityStreamGates(t *testing.T) { {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") + t.Fatal("explicitly disabled reasoning must not be held") } }) } + for _, test := range []struct { + name string + body string + }{ + {name: "client tools schema", body: `{"tools":[{"type":"function","function":{"name":"charge"}}]}`}, + {name: "legacy functions schema", body: `{"functions":[{"name":"charge"}]}`}, + {name: "tui tools schema plus user input", body: `{"model":"grok-4.6","tools":[{"type":"function","name":"read_file"}],"input":[{"role":"user","content":"hello"}]}`}, + {name: "local shell declaration", body: `{"tools":[{"type":"local_shell"}]}`}, + {name: "local environment shell declaration", body: `{"tools":[{"type":"shell","environment":{"type":"local"}}]}`}, + {name: "apply patch declaration", body: `{"tools":[{"type":"apply_patch"}]}`}, + {name: "client namespace", body: `{"tools":[{"type":"namespace","name":"local","tools":[{"type":"function","name":"read_file"}]}]}`}, + } { + 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("tools schema alone must still hold so TUI thinking turns are classified") + } + }) + } + for _, test := range []struct { + name string + body string + }{ + {name: "function_call_output", body: `{"input":[{"type":"function_call_output","call_id":"call_1","output":"done"}]}`}, + {name: "tool_result", body: `{"input":[{"type":"tool_result","tool_use_id":"tool_1","content":"done"}]}`}, + {name: "role tool", body: `{"messages":[{"role":"tool","content":"done"}]}`}, + } { + 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("in-flight tool results must still be held so 0-thinking agent turns are classified") + } + }) + } + for _, test := range []struct { + name string + body string + }{ + {name: "responses web search", body: `{"tools":[{"type":"web_search"}]}`}, + {name: "versioned web search", body: `{"tools":[{"type":"web_search_2025_08_26"}]}`}, + {name: "x search", body: `{"tools":[{"type":"x_search"}]}`}, + {name: "image generation", body: `{"tools":[{"type":"image_generation"}]}`}, + {name: "file search", body: `{"tools":[{"type":"file_search"}]}`}, + {name: "collections search", body: `{"tools":[{"type":"collections_search"}]}`}, + {name: "code execution", body: `{"tools":[{"type":"code_execution"}]}`}, + {name: "code interpreter", body: `{"tools":[{"type":"code_interpreter"}]}`}, + {name: "hosted shell", body: `{"tools":[{"type":"shell","environment":{"type":"container_auto"}}]}`}, + {name: "future native tool skips replay", body: `{"tools":[{"type":"future_server_tool"}]}`}, + {name: "remote mcp", body: `{"tools":[{"type":"mcp","server_url":"https://example.com"}]}`}, + {name: "mixed client and hosted", body: `{"tools":[{"type":"function","name":"read_file"},{"type":"web_search"}]}`}, + {name: "chat web search options", body: `{"web_search_options":{}}`}, + {name: "messages web search", body: `{"tools":[{"type":"web_search_20250305","name":"web_search"}]}`}, + {name: "messages mcp servers", body: `{"mcp_servers":[{"type":"url","url":"https://example.com"}]}`}, + {name: "deferred hosted tool", body: `{"input":[{"type":"additional_tools","tools":[{"type":"mcp","server_url":"https://example.com"}]}]}`}, + {name: "nested hosted tool", body: `{"tools":[{"type":"namespace","name":"remote","tools":[{"type":"web_search"}]}]}`}, + {name: "after local tool with hosted declaration", body: `{"tools":[{"type":"web_search"}],"input":[{"type":"function_call_output","call_id":"call_1","output":"done"}]}`}, + } { + t.Run(test.name, func(t *testing.T) { + request := input + request.Body = []byte(test.body) + if !qualityRequestHasReplayUnsafeHostedTools(request.Body) { + t.Fatal("fixture must be classified as replay-unsafe hosted tooling") + } + if shouldHoldQualityStream(request, nil, route, audit.OperationChat, cfg) { + t.Fatal("hosted tools must not be held because account retry can execute them again") + } + }) + } + for _, body := range []string{ + `{"tools":[{"type":"function","name":"read_file","parameters":{"type":"object","properties":{"tools":{"type":"array"}}}}]}`, + `{"mcp_servers":[]}`, + `{"web_search_options":null}`, + } { + if qualityRequestHasReplayUnsafeHostedTools([]byte(body)) { + t.Fatalf("safe or empty tool metadata classified as hosted: %s", body) + } + } toolCache := input toolCache.Body = []byte(`{"messages":[{"role":"user","content":"hello"}]}`) toolCache.AllowClientToolCacheRoute = true @@ -894,7 +1307,7 @@ func TestAttemptLoopQualityFailOpenFallbackAndTotalAttemptCap(t *testing.T) { 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 || got.AccountCooldown != 24*time.Hour { + if !got.Enabled || got.MaxAttempts != 6 || got.MinOutputTokens != 32 || got.OnExhausted != qualityRetryFailClosed || got.HoldTimeout != 3*time.Second || got.AccountCooldown != 24*time.Hour || got.IdleAccountCooldown != 24*time.Hour { t.Fatalf("defaults = %#v", got) } } diff --git a/backend/internal/application/gateway/selector.go b/backend/internal/application/gateway/selector.go index 32874d16..db0fe95c 100644 --- a/backend/internal/application/gateway/selector.go +++ b/backend/internal/application/gateway/selector.go @@ -491,6 +491,11 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model earliestRetry = earlierFuture(earliestRetry, candidate.ModelQuotaBlock.CooldownUntil, now) continue } + if candidateEgressLeaseCooling(candidate, value, now) { + coolingCandidates++ + earliestRetry = earlierFuture(earliestRetry, candidate.EgressLeaseBlock.CooldownUntil, now) + continue + } if value.CooldownUntil != nil && now.Before(*value.CooldownUntil) { coolingCandidates++ earliestRetry = earlierFuture(earliestRetry, *value.CooldownUntil, now) @@ -752,14 +757,20 @@ func isSelectionUnavailable(err error, reason SelectionUnavailableReason) bool { // AcquirePinned 为 previous_response_id 等账号归属请求获取指定账号租约。 func (s *Selector) AcquirePinned(ctx context.Context, provider account.Provider, accountID, modelRouteID uint64, upstreamModel, quotaMode string, inference bool) (*accountLease, error) { - return s.acquirePinned(ctx, provider, accountID, modelRouteID, upstreamModel, quotaMode, inference, clientkeydomain.AccountScope{}) + return s.acquirePinned(ctx, provider, accountID, modelRouteID, upstreamModel, quotaMode, inference, false, clientkeydomain.AccountScope{}) } func (s *Selector) AcquirePinnedForKey(ctx context.Context, provider account.Provider, accountID, modelRouteID uint64, upstreamModel, quotaMode string, inference bool, scope clientkeydomain.AccountScope) (*accountLease, error) { - return s.acquirePinned(ctx, provider, accountID, modelRouteID, upstreamModel, quotaMode, inference, scope) + return s.acquirePinned(ctx, provider, accountID, modelRouteID, upstreamModel, quotaMode, inference, false, scope) } -func (s *Selector) acquirePinned(ctx context.Context, provider account.Provider, accountID, modelRouteID uint64, upstreamModel, quotaMode string, inference bool, requestedScope clientkeydomain.AccountScope) (lease *accountLease, err error) { +// AcquirePinnedForQualityProbe keeps every ordinary eligibility check while +// bypassing only the exact account+node lease block being recovery-tested. +func (s *Selector) AcquirePinnedForQualityProbe(ctx context.Context, provider account.Provider, accountID, modelRouteID uint64, upstreamModel, quotaMode string, scope clientkeydomain.AccountScope) (*accountLease, error) { + return s.acquirePinned(ctx, provider, accountID, modelRouteID, upstreamModel, quotaMode, true, true, scope) +} + +func (s *Selector) acquirePinned(ctx context.Context, provider account.Provider, accountID, modelRouteID uint64, upstreamModel, quotaMode string, inference, ignoreEgressLeaseBlock bool, requestedScope clientkeydomain.AccountScope) (lease *accountLease, err error) { accountScope, scopeValid := clientkeydomain.NormalizeAccountScope(requestedScope) defer annotateSelectionAccountScope(&err, accountScope) if !scopeValid || !accountScope.AllowsProvider(provider) { @@ -790,6 +801,9 @@ func (s *Selector) acquirePinned(ctx context.Context, provider account.Provider, if candidate.ModelQuotaBlock != nil && now.Before(candidate.ModelQuotaBlock.CooldownUntil) { return nil, &SelectionUnavailableError{Reason: SelectionModelCooling, RetryAfter: retryDelay(now, candidate.ModelQuotaBlock.CooldownUntil)} } + if !ignoreEgressLeaseBlock && candidateEgressLeaseCooling(candidate, value, now) { + return nil, &SelectionUnavailableError{Reason: SelectionCooling, RetryAfter: retryDelay(now, candidate.EgressLeaseBlock.CooldownUntil)} + } if value.CooldownUntil != nil && now.Before(*value.CooldownUntil) { return nil, &SelectionUnavailableError{Reason: SelectionCooling, RetryAfter: retryDelay(now, *value.CooldownUntil)} } @@ -901,6 +915,11 @@ func effectiveQuotaMode(candidate account.RoutingCandidate, fallback string) str return fallback } +func candidateEgressLeaseCooling(candidate account.RoutingCandidate, credential account.Credential, now time.Time) bool { + block := candidate.EgressLeaseBlock + return block != nil && block.AccountID == credential.ID && block.NodeID != 0 && credential.EgressNodeID == block.NodeID && now.Before(block.CooldownUntil) +} + // candidateSupportsModel treats a recognized Web catalog entry as an // effective capability for tiers that the adapter explicitly allows. This // prevents a historical capability snapshot from blocking a newly enabled @@ -1889,7 +1908,7 @@ func assembleRoutingCandidates(provider account.Provider, quotaMode string, base } result = append(result, account.RoutingCandidate{ Credential: base.Credential, Billing: base.Billing, QuotaWindow: base.QuotaWindow, QuotaRecovery: base.QuotaRecovery, - ModelQuotaBlock: overlayValue.ModelQuotaBlock, ModelCapabilityKnown: known, SupportsModel: supports, + EgressLeaseBlock: base.EgressLeaseBlock, ModelQuotaBlock: overlayValue.ModelQuotaBlock, ModelCapabilityKnown: known, SupportsModel: supports, }) } return result diff --git a/backend/internal/application/gateway/selector_session.go b/backend/internal/application/gateway/selector_session.go index 37682d89..7cbbce84 100644 --- a/backend/internal/application/gateway/selector_session.go +++ b/backend/internal/application/gateway/selector_session.go @@ -84,6 +84,11 @@ func (s *Selector) beginSelectionSessionForKey(ctx context.Context, provider acc earliestRetry = earlierFuture(earliestRetry, candidate.ModelQuotaBlock.CooldownUntil, now) continue } + if candidateEgressLeaseCooling(candidate, value, now) { + coolingCandidates++ + earliestRetry = earlierFuture(earliestRetry, candidate.EgressLeaseBlock.CooldownUntil, now) + continue + } if value.CooldownUntil != nil && now.Before(*value.CooldownUntil) { coolingCandidates++ earliestRetry = earlierFuture(earliestRetry, *value.CooldownUntil, now) diff --git a/backend/internal/application/gateway/selector_test.go b/backend/internal/application/gateway/selector_test.go index fef73bd5..ea2e267d 100644 --- a/backend/internal/application/gateway/selector_test.go +++ b/backend/internal/application/gateway/selector_test.go @@ -141,10 +141,33 @@ func TestSelectorQualityProbePinsAccountToRequestedEgressNode(t *testing.T) { if err != nil { t.Fatal(err) } - defer lease.Release() if lease.Credential.ID != second.ID || lease.Credential.ID == first.ID { t.Fatalf("selected account=%d, want=%d on node=%d", lease.Credential.ID, second.ID, secondNode.ID) } + lease.Release() + + if _, err := accounts.UpsertEgressLeaseBlock(ctx, account.EgressLeaseBlock{ + AccountID: second.ID, NodeID: secondNode.ID, Reason: "hard_tps", Version: "selector-lease-0001", CooldownUntil: time.Now().UTC().Add(time.Hour), + }); err != nil { + t.Fatal(err) + } + selector = NewSelector(accounts, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), nil, time.Hour, time.Second, time.Minute) + if _, err := selector.AcquirePinnedForKey(ctx, account.ProviderBuild, second.ID, 0, "grok-test", "", true, clientkeydomain.AccountScope{}); err == nil { + t.Fatal("ordinary pinned inference ignored the active egress lease block") + } else { + var unavailable *SelectionUnavailableError + if !errors.As(err, &unavailable) || unavailable.Reason != SelectionCooling { + t.Fatalf("ordinary pinned error = %v", err) + } + } + recoveryLease, err := selector.AcquirePinnedForQualityProbe(ctx, account.ProviderBuild, second.ID, 0, "grok-test", "", clientkeydomain.AccountScope{}) + if err != nil { + t.Fatalf("quality recovery did not bypass only the lease block: %v", err) + } + defer recoveryLease.Release() + if recoveryLease.Credential.ID != second.ID || recoveryLease.Credential.EgressNodeID != secondNode.ID { + t.Fatalf("quality recovery lease = %#v", recoveryLease.Credential) + } } func TestSelectorQualityProbeBorrowsHealthyAccountForUnavailableNode(t *testing.T) { diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index fd04898c..c587a011 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -74,6 +74,13 @@ func newRoutingAttemptPolicy(configured int) routingAttemptPolicy { return routingAttemptPolicy{limit: configured} } +func newRequestRoutingAttemptPolicy(configured int, pinned bool) routingAttemptPolicy { + if pinned { + return newRoutingAttemptPolicy(1) + } + return newRoutingAttemptPolicy(configured) +} + func (p routingAttemptPolicy) allows(attempt int) bool { return p.unlimited || attempt < p.limit } @@ -122,6 +129,9 @@ type Input struct { // ForcedEgressNodeID is an internal-only administrator probe constraint. // Public inference handlers never populate it. ForcedEgressNodeID uint64 + // ForcedAccountID is paired with ForcedEgressNodeID only by the internal + // Quality Guard recovery path. It never accepts public request input. + ForcedAccountID uint64 } type Usage struct { @@ -1012,11 +1022,11 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string if input.PreviousResponseID != "" && !supportsStoredResponses { return nil, ErrResponseStateUnsupported } - attemptPolicy := newRoutingAttemptPolicy(int(s.maxAttempts.Load())) + // A lease recovery probe stays on exactly one account and one rendered proxy + // identity. Retrying the same pinned account would provide neither failover + // nor new evidence and can multiply a slow/failing probe. + attemptPolicy := newRequestRoutingAttemptPolicy(int(s.maxAttempts.Load()), ownership != nil || input.ForcedAccountID != 0) idempotencyID, _ := security.NewOpaqueToken(18) - if ownership != nil { - attemptPolicy = newRoutingAttemptPolicy(1) - } pricingModel := s.providers.PricingModel(route.Provider, route.UpstreamModel) if err := s.checkLedgerReady(); err != nil { return nil, err @@ -1070,7 +1080,7 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string lease.completeSelectorObservation(successful) budget := newFinalizationBudget(string(operation), string(route.Provider)) if isUpstreamStreamFailure(errorCode) { - status, retryAfter := streamFailureHealthPenalty(errorCode, usage) + status, retryAfter := streamFailureHealthPenalty(errorCode, usage, s.qualityRetryConfig().IdleAccountCooldown) if err := budget.run("account_health", finalizationHealthBudget, func(stageCtx context.Context) error { return s.selector.MarkFailureAfterSuccess(stageCtx, credential, status, retryAfter) }); err != nil { @@ -1236,7 +1246,18 @@ attemptLoop: var lease *accountLease var err error selectionStarted := time.Now() - if ownership != nil { + if input.ForcedAccountID != 0 { + if input.ForcedEgressNodeID == 0 { + err = &SelectionUnavailableError{Reason: SelectionNoAccounts} + } else { + lease, err = s.selector.AcquirePinnedForQualityProbe(ctx, route.Provider, input.ForcedAccountID, route.ID, route.UpstreamModel, quotaMode, accountScope) + if err == nil && lease.Credential.EgressNodeID != input.ForcedEgressNodeID { + lease.Release() + lease = nil + err = &SelectionUnavailableError{Reason: SelectionNoAccounts} + } + } + } else if ownership != nil { lease, err = s.selector.AcquirePinnedForKey(ctx, route.Provider, ownership.AccountID, route.ID, route.UpstreamModel, quotaMode, true, accountScope) } else if input.ForcedEgressNodeID != 0 { lease, err = s.selector.AcquireForKeyOnEgressNode(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, affinityKey, excluded, !quotaProbeAttempted, accountScope, input.ForcedEgressNodeID) @@ -1268,7 +1289,7 @@ attemptLoop: // Stored Responses are pinned to one account. Return the cached 429 // immediately instead of spinning until the cooldown expires or // replaying the request on the same account. - if ownership != nil { + if ownership != nil || input.ForcedAccountID != 0 { break attemptLoop } attempt-- @@ -1575,10 +1596,10 @@ attemptLoop: logPrefix = "quality_peek_empty" } writeCtx, writeCancel := context.WithTimeout(context.WithoutCancel(ctx), finalizationTimeout) - if markErr := s.selector.MarkFailureAfterSuccess(writeCtx, credential, http.StatusGatewayTimeout, qualityIdleAccountCooldown); markErr != nil { + if markErr := s.selector.MarkFailureAfterSuccess(writeCtx, credential, http.StatusGatewayTimeout, holdCfg.IdleAccountCooldown); markErr != nil { s.logger.Warn(logPrefix+"_cooldown_failed", "request_id", input.RequestID, "account_id", credential.ID, "error", markErr) } else { - s.logger.Warn(logPrefix+"_retry", "request_id", input.RequestID, "account_id", credential.ID, "cooldown", qualityIdleAccountCooldown) + s.logger.Warn(logPrefix+"_retry", "request_id", input.RequestID, "account_id", credential.ID, "cooldown", holdCfg.IdleAccountCooldown) } writeCancel() } @@ -1723,9 +1744,12 @@ func isUpstreamStreamFailure(errorCode string) bool { } } -func streamFailureHealthPenalty(errorCode string, usage Usage) (int, time.Duration) { +func streamFailureHealthPenalty(errorCode string, usage Usage, idleCooldown time.Duration) (int, time.Duration) { if errorCode == "upstream_stream_idle_timeout" && !usage.OutputObserved && usage.OutputTokens == 0 && usage.ReasoningTokens == 0 { - return http.StatusGatewayTimeout, qualityIdleAccountCooldown + if idleCooldown <= 0 { + idleCooldown = qualityIdleAccountCooldown + } + return http.StatusGatewayTimeout, idleCooldown } return 0, 0 } diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index b85954de..8e59945e 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -555,6 +555,15 @@ func TestRoutingAttemptPolicy(t *testing.T) { } } +func TestPinnedRequestAttemptPolicyAlwaysAllowsOneAttempt(t *testing.T) { + for _, configured := range []int{1, 6, unlimitedRoutingAttempts} { + policy := newRequestRoutingAttemptPolicy(configured, true) + if !policy.allows(0) || policy.allows(1) || policy.hasNext(0) { + t.Fatalf("configured=%d pinned policy = %#v", configured, policy) + } + } +} + func TestGatewayUnlimitedAttemptsExhaustsEligiblePool(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "gateway-unlimited-attempts.db")) @@ -4350,16 +4359,20 @@ func TestIsUpstreamStreamFailureIncludesIdleTimeout(t *testing.T) { func TestStreamFailureHealthPenaltyOnlyLongCoolsTrulyEmptyIdle(t *testing.T) { t.Parallel() - status, cooldown := streamFailureHealthPenalty("upstream_stream_idle_timeout", Usage{}) - if status != http.StatusGatewayTimeout || cooldown != qualityIdleAccountCooldown { + status, cooldown := streamFailureHealthPenalty("upstream_stream_idle_timeout", Usage{}, 15*time.Minute) + if status != http.StatusGatewayTimeout || cooldown != 15*time.Minute { t.Fatalf("empty idle penalty = (%d, %s)", status, cooldown) } + status, cooldown = streamFailureHealthPenalty("upstream_stream_idle_timeout", Usage{}, 0) + if status != http.StatusGatewayTimeout || cooldown != qualityIdleAccountCooldown { + t.Fatalf("zero idle cooldown must fall back to default (%d, %s)", status, cooldown) + } for _, usage := range []Usage{ {OutputObserved: true}, {OutputTokens: 1}, {ReasoningTokens: 1}, } { - status, cooldown = streamFailureHealthPenalty("upstream_stream_idle_timeout", usage) + status, cooldown = streamFailureHealthPenalty("upstream_stream_idle_timeout", usage, 15*time.Minute) if status != 0 || cooldown != 0 { t.Fatalf("non-empty idle usage %#v received long penalty (%d, %s)", usage, status, cooldown) } diff --git a/backend/internal/domain/account/account.go b/backend/internal/domain/account/account.go index e4495b7e..cfd37229 100644 --- a/backend/internal/domain/account/account.go +++ b/backend/internal/domain/account/account.go @@ -443,6 +443,7 @@ type RoutingCandidate struct { Billing *Billing QuotaWindow *QuotaWindow QuotaRecovery *QuotaRecovery + EgressLeaseBlock *EgressLeaseBlock ModelQuotaBlock *ModelQuotaBlock ModelCapabilityKnown bool SupportsModel bool @@ -451,10 +452,11 @@ type RoutingCandidate struct { // RoutingAccountBase contains provider-level routing state reusable across // models. Credential material is hydrated only after an account is selected. type RoutingAccountBase struct { - Credential Credential - Billing *Billing - QuotaRecovery *QuotaRecovery - QuotaWindow *QuotaWindow + Credential Credential + Billing *Billing + QuotaRecovery *QuotaRecovery + QuotaWindow *QuotaWindow + EgressLeaseBlock *EgressLeaseBlock } // RoutingAccountOverlay contains model-specific eligibility state. @@ -480,6 +482,26 @@ type ModelQuotaBlock struct { UpdatedAt time.Time } +// EgressLeaseBlock temporarily removes one account-bound proxy lease from +// routing without changing the account's health or disabling the physical +// egress node shared by other leases. +type EgressLeaseBlock struct { + AccountID uint64 + NodeID uint64 + Reason string + Version string + CooldownUntil time.Time + UpdatedAt time.Time +} + +// EgressLeaseBlockCursor is the stable keyset position used to scan durable +// lease state while rows may be renewed or removed concurrently. +type EgressLeaseBlockCursor struct { + CooldownUntil time.Time + AccountID uint64 + NodeID uint64 +} + // DeviceSession 表示一次短期 Device OAuth 授权流程。 type DeviceSession struct { ID string diff --git a/backend/internal/infra/config/config.go b/backend/internal/infra/config/config.go index e5f2265e..d4052380 100644 --- a/backend/internal/infra/config/config.go +++ b/backend/internal/infra/config/config.go @@ -297,6 +297,9 @@ type QualityGuardRequestRetryConfig struct { MinOutputTokens int `yaml:"minOutputTokens"` OnExhausted string `yaml:"onExhausted"` AccountCooldown Duration `yaml:"accountCooldown"` + // IdleAccountCooldown cools an account after a truly empty upstream + // stream. Independent of accountCooldown (missing-thinking). Zero uses 24h. + IdleAccountCooldown Duration `yaml:"idleAccountCooldown"` } type ClientKeyDefaultsConfig struct { @@ -802,6 +805,9 @@ func validateQualityGuardRequestRetry(value QualityGuardRequestRetryConfig) erro if d := value.AccountCooldown.Value(); d != 0 && (d < time.Minute || d > 168*time.Hour) { return errors.New("qualityGuard.requestRetry.accountCooldown 必须在 1m 到 168h 之间") } + if d := value.IdleAccountCooldown.Value(); d != 0 && (d < time.Minute || d > 168*time.Hour) { + return errors.New("qualityGuard.requestRetry.idleAccountCooldown 必须在 1m 到 168h 之间") + } return nil } @@ -936,7 +942,7 @@ func defaultConfig() Config { MinimumGenerationWindow: Duration(time.Second), RotationTimeout: Duration(45 * time.Second), RequestRetry: QualityGuardRequestRetryConfig{ MaxAttempts: 6, HoldTimeout: Duration(3 * time.Second), MinOutputTokens: 32, OnExhausted: "fail_closed", - AccountCooldown: Duration(24 * time.Hour), + AccountCooldown: Duration(24 * time.Hour), IdleAccountCooldown: Duration(24 * time.Hour), }, }, ClientKeyDefaults: ClientKeyDefaultsConfig{RPMLimit: clientkeydomain.DefaultRPMLimit, MaxConcurrent: clientkeydomain.DefaultMaxConcurrent}, diff --git a/backend/internal/infra/config/config_test.go b/backend/internal/infra/config/config_test.go index c7441e5c..6244a68e 100644 --- a/backend/internal/infra/config/config_test.go +++ b/backend/internal/infra/config/config_test.go @@ -223,7 +223,7 @@ qualityGuard: 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" || got.AccountCooldown.Value() != 24*time.Hour { + if got.Enabled || got.MaxAttempts != 6 || got.HoldTimeout.Value() != 3*time.Second || got.MinOutputTokens != 32 || got.OnExhausted != "fail_closed" || got.AccountCooldown.Value() != 24*time.Hour || got.IdleAccountCooldown.Value() != 24*time.Hour { t.Fatalf("requestRetry defaults = %#v", got) } } @@ -248,6 +248,12 @@ func TestQualityGuardRequestRetryAccountCooldownBounds(t *testing.T) { if (err != nil) != test.wantErr { t.Fatalf("validate cooldown %s: err=%v, wantErr=%t", test.value, err, test.wantErr) } + err = validateQualityGuardRequestRetry(QualityGuardRequestRetryConfig{ + Enabled: true, IdleAccountCooldown: Duration(test.value), + }) + if (err != nil) != test.wantErr { + t.Fatalf("validate idle cooldown %s: err=%v, wantErr=%t", test.value, err, test.wantErr) + } }) } } diff --git a/backend/internal/infra/persistence/relational/account_egress_lease_test.go b/backend/internal/infra/persistence/relational/account_egress_lease_test.go new file mode 100644 index 00000000..6ba4a741 --- /dev/null +++ b/backend/internal/infra/persistence/relational/account_egress_lease_test.go @@ -0,0 +1,175 @@ +package relational + +import ( + "context" + "path/filepath" + "testing" + "time" + + "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/repository" +) + +func TestEgressLeaseBlockRoutesOnlyMatchingActiveBindingAndUsesCAS(t *testing.T) { + ctx := context.Background() + database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "egress-lease.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accounts := NewAccountRepository(database) + nodes := NewEgressRepository(database) + cipher := egressOperationsCipher(t) + firstNode := createHealthyEgressNode(t, ctx, nodes, cipher, "lease-first", 0) + secondNode := createHealthyEgressNode(t, ctx, nodes, cipher, "lease-second", 0) + credential := createEgressOperationsAccount(t, ctx, accounts, "lease-account") + if _, err := accounts.UpdateEgressBindings(ctx, account.ProviderBuild, []uint64{credential.ID}, &firstNode.ID, account.EgressAssignmentManual, time.Now().UTC()); err != nil { + t.Fatal(err) + } + + until := time.Now().UTC().Add(time.Hour) + stored, err := accounts.UpsertEgressLeaseBlock(ctx, account.EgressLeaseBlock{ + AccountID: credential.ID, NodeID: firstNode.ID, Reason: "hard_tps", Version: "lease-version-0001", CooldownUntil: until, + }) + if err != nil { + t.Fatal(err) + } + if stored.Version != "lease-version-0001" { + t.Fatalf("stored block = %#v", stored) + } + candidates, err := accounts.ListRoutingCandidates(ctx, account.ProviderBuild, 0, "grok-test", "") + if err != nil { + t.Fatal(err) + } + if len(candidates) != 1 || candidates[0].EgressLeaseBlock == nil || candidates[0].EgressLeaseBlock.NodeID != firstNode.ID { + t.Fatalf("routing candidates = %#v", candidates) + } + + shorter, err := accounts.UpsertEgressLeaseBlock(ctx, account.EgressLeaseBlock{ + AccountID: credential.ID, NodeID: firstNode.ID, Reason: "soft_tps", Version: "lease-version-0002", CooldownUntil: until.Add(-time.Minute), + }) + if err != nil { + t.Fatal(err) + } + if shorter.Version != stored.Version || !shorter.CooldownUntil.Equal(stored.CooldownUntil) { + t.Fatalf("shorter hold replaced stronger block: %#v", shorter) + } + if deleted, err := accounts.DeleteEgressLeaseBlock(ctx, credential.ID, firstNode.ID, "lease-version-stale"); err != nil || deleted { + t.Fatalf("stale CAS delete = %v, %v", deleted, err) + } + + if _, err := accounts.UpdateEgressBindings(ctx, account.ProviderBuild, []uint64{credential.ID}, &secondNode.ID, account.EgressAssignmentManual, time.Now().UTC()); err != nil { + t.Fatal(err) + } + blocks, err := accounts.ListEgressLeaseBlocks(ctx, 10, nil) + if err != nil { + t.Fatal(err) + } + if len(blocks) != 0 { + t.Fatalf("rebinding left stale lease blocks: %#v", blocks) + } +} + +func TestExpiredEgressLeaseBlockIsReconciledButNotRouted(t *testing.T) { + ctx := context.Background() + database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "expired-egress-lease.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accounts := NewAccountRepository(database) + nodes := NewEgressRepository(database) + node := createHealthyEgressNode(t, ctx, nodes, egressOperationsCipher(t), "lease-expired", 0) + credential := createEgressOperationsAccount(t, ctx, accounts, "lease-expired-account") + if _, err := accounts.UpdateEgressBindings(ctx, account.ProviderBuild, []uint64{credential.ID}, &node.ID, account.EgressAssignmentManual, time.Now().UTC()); err != nil { + t.Fatal(err) + } + if _, err := accounts.UpsertEgressLeaseBlock(ctx, account.EgressLeaseBlock{ + AccountID: credential.ID, NodeID: node.ID, Reason: "hard_tps", Version: "lease-version-0001", CooldownUntil: time.Now().UTC().Add(-time.Second), + }); err != nil { + t.Fatal(err) + } + blocks, err := accounts.ListEgressLeaseBlocks(ctx, 10, nil) + if err != nil || len(blocks) != 1 { + t.Fatalf("reconciliation blocks = %#v, %v", blocks, err) + } + candidates, err := accounts.ListRoutingCandidates(ctx, account.ProviderBuild, 0, "grok-test", "") + if err != nil { + t.Fatal(err) + } + if len(candidates) != 1 || candidates[0].EgressLeaseBlock != nil { + t.Fatalf("expired block remained routable: %#v", candidates) + } +} + +func TestEgressLeaseBlockKeysetPaginationAndInvalidPruning(t *testing.T) { + ctx := context.Background() + database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "egress-lease-page.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accounts := NewAccountRepository(database) + nodes := NewEgressRepository(database) + node := createHealthyEgressNode(t, ctx, nodes, egressOperationsCipher(t), "lease-page", 0) + base := time.Now().UTC().Add(time.Hour) + created := make([]account.Credential, 0, 5) + for index := range 5 { + credential := createEgressOperationsAccount(t, ctx, accounts, "lease-page-account-"+string(rune('a'+index))) + created = append(created, credential) + if _, err := accounts.UpdateEgressBindings(ctx, account.ProviderBuild, []uint64{credential.ID}, &node.ID, account.EgressAssignmentManual, time.Now().UTC()); err != nil { + t.Fatal(err) + } + if _, err := accounts.UpsertEgressLeaseBlock(ctx, account.EgressLeaseBlock{ + AccountID: credential.ID, NodeID: node.ID, Reason: "hard_tps", Version: "lease-page-version-" + string(rune('a'+index)), CooldownUntil: base.Add(time.Duration(index) * time.Second), + }); err != nil { + t.Fatal(err) + } + } + first, err := accounts.ListEgressLeaseBlocks(ctx, 2, nil) + if err != nil || len(first) != 2 { + t.Fatalf("first page = %#v, %v", first, err) + } + cursor := &account.EgressLeaseBlockCursor{CooldownUntil: first[1].CooldownUntil, AccountID: first[1].AccountID, NodeID: first[1].NodeID} + second, err := accounts.ListEgressLeaseBlocks(ctx, 2, cursor) + if err != nil || len(second) != 2 || second[0].AccountID == first[1].AccountID { + t.Fatalf("second page = %#v, %v", second, err) + } + if _, err := accounts.UpdateMany(ctx, account.ProviderBuild, []uint64{created[0].ID}, repository.AccountUpdates{Enabled: boolPointer(false)}); err != nil { + t.Fatal(err) + } + remaining, err := accounts.ListEgressLeaseBlocks(ctx, 10, nil) + if err != nil || len(remaining) != 4 { + t.Fatalf("remaining blocks = %#v, %v", remaining, err) + } + reauth := created[1] + reauth.AuthStatus = account.AuthStatusReauthRequired + if _, err := accounts.Update(ctx, reauth); err != nil { + t.Fatal(err) + } + remaining, err = accounts.ListEgressLeaseBlocks(ctx, 10, nil) + if err != nil || len(remaining) != 3 { + t.Fatalf("reauth cleanup blocks = %#v, %v", remaining, err) + } + + disabled := node + disabled.Enabled = false + if _, err := nodes.UpdateEgressNode(ctx, disabled); err != nil { + t.Fatal(err) + } + pruned, err := accounts.PruneInvalidEgressLeaseBlocks(ctx, 1000) + if err != nil || pruned != 3 { + t.Fatalf("pruned = %d, %v", pruned, err) + } +} + +func boolPointer(value bool) *bool { return &value } diff --git a/backend/internal/infra/persistence/relational/account_repository.go b/backend/internal/infra/persistence/relational/account_repository.go index d6f52087..faf6104e 100644 --- a/backend/internal/infra/persistence/relational/account_repository.go +++ b/backend/internal/infra/persistence/relational/account_repository.go @@ -366,6 +366,10 @@ func (r *AccountRepository) ListRoutingCandidates(ctx context.Context, provider if err != nil { return nil, err } + egressLeaseBlocks, err := r.getRoutingEgressLeaseBlocks(ctx, provider, values, time.Now().UTC()) + if err != nil { + return nil, err + } known := make(map[uint64]bool, len(values)) supported := make(map[uint64]bool, len(values)) modelQuotaBlocks := make(map[uint64]account.ModelQuotaBlock, len(values)) @@ -459,6 +463,9 @@ func (r *AccountRepository) ListRoutingCandidates(ctx context.Context, provider if block, ok := modelQuotaBlocks[value.ID]; ok { candidate.ModelQuotaBlock = &block } + if block, ok := egressLeaseBlocks[value.ID]; ok { + candidate.EgressLeaseBlock = &block + } result = append(result, candidate) } return result, nil @@ -481,6 +488,10 @@ func (r *AccountRepository) ListRoutingAccountBases(ctx context.Context, provide if err != nil { return nil, err } + egressLeaseBlocks, err := r.getRoutingEgressLeaseBlocks(ctx, provider, values, time.Now().UTC()) + if err != nil { + return nil, err + } result := make([]account.RoutingAccountBase, 0, len(values)) for _, value := range values { base := account.RoutingAccountBase{Credential: value} @@ -493,11 +504,34 @@ func (r *AccountRepository) ListRoutingAccountBases(ctx context.Context, provide if window, ok := quotaWindows[value.ID]; ok { base.QuotaWindow = &window } + if block, ok := egressLeaseBlocks[value.ID]; ok { + base.EgressLeaseBlock = &block + } result = append(result, base) } return result, nil } +func (r *AccountRepository) getRoutingEgressLeaseBlocks(ctx context.Context, provider account.Provider, values []account.Credential, now time.Time) (map[uint64]account.EgressLeaseBlock, error) { + result := make(map[uint64]account.EgressLeaseBlock) + if len(values) == 0 { + return result, nil + } + var rows []accountEgressLeaseBlockModel + if err := r.db.db.WithContext(ctx). + Table("account_egress_lease_blocks AS block"). + Select("block.*"). + Joins("JOIN provider_accounts AS account ON account.id = block.account_id"). + Where("account.provider = ? AND account.enabled = ? AND account.auth_status = ? AND account.egress_node_id = block.node_id AND block.cooldown_until > ?", provider, true, account.AuthStatusActive, now.UTC()). + Find(&rows).Error; err != nil { + return nil, err + } + for _, row := range rows { + result[row.AccountID] = egressLeaseBlockFromModel(row) + } + return result, nil +} + // listRoutingCredentials loads only the account state required to decide which // account to use. Provider secrets deliberately stay in account_credentials // until a selected account is hydrated for the upstream call. @@ -1332,6 +1366,9 @@ func upsertKnownAccountByIdentity(tx *gorm.DB, value account.Credential, existin if err := tx.Save(&row).Error; err != nil { return repository.AccountUpsertResult{}, accountModel{}, err } + if _, err := deleteInvalidEgressLeaseBlocksForAccount(tx, row); err != nil { + return repository.AccountUpsertResult{}, accountModel{}, err + } if err := saveAccountRelations(tx, value, row.ID); err != nil { return repository.AccountUpsertResult{}, accountModel{}, err } @@ -1382,6 +1419,9 @@ func (r *AccountRepository) Update(ctx context.Context, value account.Credential if err := tx.Save(&row).Error; err != nil { return err } + if _, err := deleteInvalidEgressLeaseBlocksForAccount(tx, row); err != nil { + return err + } return saveAccountRelations(tx, value, row.ID) }); err != nil { return account.Credential{}, mapError(err) @@ -1577,6 +1617,11 @@ func (r *AccountRepository) UpdateMany(ctx context.Context, providerValue accoun } updated += result.RowsAffected } + if providerValue == account.ProviderBuild && updates.Enabled != nil && !*updates.Enabled { + if err := tx.Where("account_id IN ?", ids).Delete(&accountEgressLeaseBlockModel{}).Error; err != nil { + return err + } + } return nil }) if err != nil { @@ -1604,10 +1649,32 @@ func (r *AccountRepository) UpdateEgressBindings(ctx context.Context, providerVa values["egress_assignment_mode"] = string(mode) values["egress_assigned_at"] = assignedAt.UTC() } - result := r.db.db.WithContext(ctx).Model(&accountModel{}). - Where("provider = ? AND id IN ?", providerValue, ids). - Updates(values) - return result.RowsAffected, mapError(result.Error) + var updated int64 + var clearedLeaseBlocks int64 + err := r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + result := tx.Model(&accountModel{}).Where("provider = ? AND id IN ?", providerValue, ids).Updates(values) + if result.Error != nil { + return result.Error + } + updated = result.RowsAffected + if providerValue != account.ProviderBuild { + return nil + } + query := tx.Where("account_id IN ?", ids) + if nodeID != nil { + query = query.Where("node_id <> ?", *nodeID) + } + deleted := query.Delete(&accountEgressLeaseBlockModel{}) + if deleted.Error != nil { + return deleted.Error + } + clearedLeaseBlocks = deleted.RowsAffected + return nil + }) + if err == nil && clearedLeaseBlocks > 0 { + r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountEgressLeaseChanged, Provider: providerValue}) + } + return updated, mapError(err) } // ListEgressAssignments returns all accounts for one provider with their @@ -2163,6 +2230,181 @@ func (r *AccountRepository) UpsertModelQuotaBlock(ctx context.Context, value acc return err } +func egressLeaseBlockFromModel(row accountEgressLeaseBlockModel) account.EgressLeaseBlock { + return account.EgressLeaseBlock{ + AccountID: row.AccountID, NodeID: row.NodeID, Reason: row.Reason, Version: row.Version, + CooldownUntil: row.CooldownUntil.UTC(), UpdatedAt: row.UpdatedAt.UTC(), + } +} + +// ListEgressLeaseBlocks returns the durable guard-owned lease state, including +// expired rows. The sidecar uses expired rows for recovery reconciliation; the +// selector independently ignores them after CooldownUntil as a fail-safe. +func (r *AccountRepository) ListEgressLeaseBlocks(ctx context.Context, limit int, after *account.EgressLeaseBlockCursor) ([]account.EgressLeaseBlock, error) { + if limit <= 0 || limit > 1001 { + return nil, repository.ErrConflict + } + var rows []accountEgressLeaseBlockModel + query := r.db.db.WithContext(ctx). + Table("account_egress_lease_blocks AS block").Select("block.*"). + Joins("JOIN provider_accounts AS account ON account.id = block.account_id"). + Joins("JOIN egress_nodes AS node ON node.id = block.node_id"). + Where("account.provider = ? AND account.enabled = ? AND account.auth_status = ? AND account.egress_node_id = block.node_id AND node.enabled = ? AND node.scope = ?", account.ProviderBuild, true, account.AuthStatusActive, true, "grok_build"). + Order("block.cooldown_until ASC, block.account_id ASC, block.node_id ASC").Limit(limit) + if after != nil { + cursorTime := after.CooldownUntil.UTC() + query = query.Where( + "block.cooldown_until > ? OR (block.cooldown_until = ? AND (block.account_id > ? OR (block.account_id = ? AND block.node_id > ?)))", + cursorTime, cursorTime, after.AccountID, after.AccountID, after.NodeID, + ) + } + if err := query.Find(&rows).Error; err != nil { + return nil, err + } + values := make([]account.EgressLeaseBlock, 0, len(rows)) + for _, row := range rows { + values = append(values, egressLeaseBlockFromModel(row)) + } + return values, nil +} + +func deleteInvalidEgressLeaseBlocksForAccount(tx *gorm.DB, row accountModel) (int64, error) { + if account.Provider(row.Provider) != account.ProviderBuild { + return 0, nil + } + query := tx.Where("account_id = ?", row.ID) + if row.Enabled && account.AuthStatus(row.AuthStatus) == account.AuthStatusActive && row.EgressNodeID != nil { + query = query.Where("node_id <> ?", *row.EgressNodeID) + } + result := query.Delete(&accountEgressLeaseBlockModel{}) + return result.RowsAffected, result.Error +} + +func (r *AccountRepository) PruneInvalidEgressLeaseBlocks(ctx context.Context, limit int) (int64, error) { + if limit < 1 || limit > 1000 { + return 0, repository.ErrConflict + } + var rows []accountEgressLeaseBlockModel + err := r.db.db.WithContext(ctx). + Table("account_egress_lease_blocks AS block").Select("block.*"). + Joins("LEFT JOIN provider_accounts AS account ON account.id = block.account_id"). + Joins("LEFT JOIN egress_nodes AS node ON node.id = block.node_id"). + Where("account.id IS NULL OR account.provider <> ? OR account.enabled <> ? OR account.auth_status <> ? OR account.egress_node_id IS NULL OR account.egress_node_id <> block.node_id OR node.id IS NULL OR node.enabled <> ? OR node.scope <> ?", account.ProviderBuild, true, account.AuthStatusActive, true, "grok_build"). + Order("block.cooldown_until ASC, block.account_id ASC, block.node_id ASC").Limit(limit).Find(&rows).Error + if err != nil || len(rows) == 0 { + return 0, err + } + var deleted int64 + err = r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + for start := 0; start < len(rows); start += 400 { + end := min(start+400, len(rows)) + pairs := make([][]any, 0, end-start) + for _, row := range rows[start:end] { + pairs = append(pairs, []any{row.AccountID, row.NodeID}) + } + result := tx.Where("(account_id, node_id) IN ?", pairs).Delete(&accountEgressLeaseBlockModel{}) + if result.Error != nil { + return result.Error + } + deleted += result.RowsAffected + } + return nil + }) + if err == nil && deleted > 0 { + r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountEgressLeaseChanged, Provider: account.ProviderBuild}) + } + return deleted, err +} + +func (r *AccountRepository) DeleteEgressLeaseBlocksByNodes(ctx context.Context, nodeIDs []uint64) (int64, error) { + if len(nodeIDs) == 0 { + return 0, nil + } + result := r.db.db.WithContext(ctx).Where("node_id IN ?", nodeIDs).Delete(&accountEgressLeaseBlockModel{}) + if result.Error == nil && result.RowsAffected > 0 { + r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountEgressLeaseChanged, Provider: account.ProviderBuild}) + } + return result.RowsAffected, result.Error +} + +// UpsertEgressLeaseBlock atomically verifies that the Build account is still +// bound to the requested node. A shorter concurrent hold cannot replace a +// longer one or rotate its CAS version. +func (r *AccountRepository) UpsertEgressLeaseBlock(ctx context.Context, value account.EgressLeaseBlock) (account.EgressLeaseBlock, error) { + value.Reason = strings.TrimSpace(value.Reason) + value.Version = strings.TrimSpace(value.Version) + if value.AccountID == 0 || value.NodeID == 0 || value.Reason == "" || len(value.Version) < 16 || len(value.Version) > 64 || value.CooldownUntil.IsZero() { + return account.EgressLeaseBlock{}, repository.ErrConflict + } + value.Reason = truncate(value.Reason, 100) + value.CooldownUntil = value.CooldownUntil.UTC() + value.UpdatedAt = time.Now().UTC() + stored := value + err := r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + var owner accountModel + if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Select("id", "provider", "enabled", "auth_status", "egress_node_id").First(&owner, value.AccountID).Error; err != nil { + return mapError(err) + } + if account.Provider(owner.Provider) != account.ProviderBuild || !owner.Enabled || account.AuthStatus(owner.AuthStatus) != account.AuthStatusActive || owner.EgressNodeID == nil || *owner.EgressNodeID != value.NodeID { + return repository.ErrConflict + } + var existing accountEgressLeaseBlockModel + load := tx.Where("account_id = ? AND node_id = ?", value.AccountID, value.NodeID).Limit(1).Find(&existing) + if load.Error != nil { + return load.Error + } + if load.RowsAffected > 0 && existing.CooldownUntil.After(value.CooldownUntil) { + stored = egressLeaseBlockFromModel(existing) + return nil + } + row := accountEgressLeaseBlockModel{ + AccountID: value.AccountID, NodeID: value.NodeID, Reason: value.Reason, Version: value.Version, + CooldownUntil: value.CooldownUntil, UpdatedAt: value.UpdatedAt, + } + created := tx.Clauses(clause.OnConflict{ + Columns: []clause.Column{{Name: "account_id"}, {Name: "node_id"}}, + DoUpdates: clause.AssignmentColumns([]string{"reason", "version", "cooldown_until", "updated_at"}), + Where: clause.Where{Exprs: []clause.Expression{clause.Expr{ + SQL: "account_egress_lease_blocks.cooldown_until <= excluded.cooldown_until", + }}}, + }).Create(&row) + if created.Error != nil { + return created.Error + } + if created.RowsAffected == 0 { + if err := tx.Where("account_id = ? AND node_id = ?", value.AccountID, value.NodeID).First(&existing).Error; err != nil { + return err + } + stored = egressLeaseBlockFromModel(existing) + return nil + } + stored = egressLeaseBlockFromModel(row) + return nil + }) + if err == nil { + r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountEgressLeaseChanged, Provider: account.ProviderBuild, AccountID: value.AccountID}) + } + return stored, err +} + +// DeleteEgressLeaseBlock uses the opaque version as a compare-and-swap token, +// so a stale recovery probe cannot clear a newer quarantine. +func (r *AccountRepository) DeleteEgressLeaseBlock(ctx context.Context, accountID, nodeID uint64, version string) (bool, error) { + version = strings.TrimSpace(version) + if accountID == 0 || nodeID == 0 || version == "" { + return false, repository.ErrConflict + } + result := r.db.db.WithContext(ctx).Where("account_id = ? AND node_id = ? AND version = ?", accountID, nodeID, version).Delete(&accountEgressLeaseBlockModel{}) + if result.Error != nil { + return false, result.Error + } + if result.RowsAffected == 1 { + r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountEgressLeaseChanged, Provider: account.ProviderBuild, AccountID: accountID}) + return true, nil + } + return false, nil +} + func (r *AccountRepository) PruneExpiredModelQuotaBlocks(ctx context.Context, now time.Time, limit int) (int64, error) { if limit <= 0 || limit > 1000 { limit = 100 diff --git a/backend/internal/infra/persistence/relational/models.go b/backend/internal/infra/persistence/relational/models.go index 4c275628..8824c6a6 100644 --- a/backend/internal/infra/persistence/relational/models.go +++ b/backend/internal/infra/persistence/relational/models.go @@ -243,6 +243,19 @@ type accountModelQuotaBlockModel struct { func (accountModelQuotaBlockModel) TableName() string { return "account_model_quota_blocks" } +type accountEgressLeaseBlockModel struct { + AccountID uint64 `gorm:"primaryKey"` + NodeID uint64 `gorm:"primaryKey"` + Reason string `gorm:"size:100;not null;check:chk_account_egress_lease_blocks_reason,length(trim(reason)) BETWEEN 1 AND 100"` + Version string `gorm:"size:64;not null;check:chk_account_egress_lease_blocks_version,length(trim(version)) BETWEEN 16 AND 64"` + CooldownUntil time.Time `gorm:"not null"` + UpdatedAt time.Time `gorm:"not null"` + Account *accountModel `gorm:"foreignKey:AccountID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"` + Node *egressNodeModel `gorm:"foreignKey:NodeID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"` +} + +func (accountEgressLeaseBlockModel) TableName() string { return "account_egress_lease_blocks" } + type clientKeyModel struct { ID uint64 `gorm:"primaryKey;autoIncrement"` Name string `gorm:"size:160;not null;check:chk_client_keys_name,length(trim(name)) BETWEEN 1 AND 160"` diff --git a/backend/internal/infra/persistence/relational/schema.go b/backend/internal/infra/persistence/relational/schema.go index 8ef00f58..6ac13538 100644 --- a/backend/internal/infra/persistence/relational/schema.go +++ b/backend/internal/infra/persistence/relational/schema.go @@ -42,6 +42,7 @@ var schemaModels = []any{ &accountModelCapabilityModel{}, &accountModelSyncStateModel{}, &accountModelQuotaBlockModel{}, + &accountEgressLeaseBlockModel{}, &clientKeyModel{}, &clientKeyModelPermission{}, &billingReservationModel{}, @@ -67,6 +68,7 @@ var schemaIndexes = []string{ "CREATE INDEX IF NOT EXISTS idx_accounts_auto_clean_reauth_cursor ON provider_accounts(auth_status, enabled, id, reauth_marked_at)", "CREATE INDEX IF NOT EXISTS idx_account_credentials_refresh_due ON account_credentials(refresh_due_at, account_id)", "CREATE INDEX IF NOT EXISTS idx_account_credentials_build_bot_flag ON account_credentials(build_bot_flag_source, account_id)", + "CREATE INDEX IF NOT EXISTS idx_account_egress_lease_blocks_due ON account_egress_lease_blocks(cooldown_until, account_id, node_id)", "CREATE INDEX IF NOT EXISTS idx_quota_windows_due ON account_quota_windows(remaining, reset_at, account_id)", "CREATE INDEX IF NOT EXISTS idx_model_routes_public_id_lookup ON model_routes(public_id)", // Catalog/discovered rows remain idempotent per API capability. One public diff --git a/backend/internal/infra/provider/conversation/conversation_test.go b/backend/internal/infra/provider/conversation/conversation_test.go index 0d0d4134..425cf81c 100644 --- a/backend/internal/infra/provider/conversation/conversation_test.go +++ b/backend/internal/infra/provider/conversation/conversation_test.go @@ -928,6 +928,50 @@ func TestConvertResponsesStreamMarksChatReasoningStart(t *testing.T) { } } +func TestConvertResponsesStreamMarksEncryptedChatReasoningEvidence(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.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(ConvertResponseStream(io.NopCloser(strings.NewReader(stream)), OperationChat)) + if err != nil { + t.Fatal(err) + } + text := string(converted) + if strings.Count(text, ": grok2api-reasoning-start\n\n") != 1 || strings.Count(text, ": grok2api-reasoning-evidence\n\n") != 1 { + t.Fatalf("encrypted reasoning markers missing or duplicated: %s", text) + } + if strings.Contains(text, "signature") || strings.Contains(text, "encrypted_content") { + t.Fatalf("encrypted reasoning leaked into Chat JSON: %s", text) + } +} + +func TestConvertResponsesStreamMarksFinalEnvelopeReasoningEvidence(t *testing.T) { + stream := strings.Join([]string{ + `event: response.created`, + `data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.6"}}`, "", + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"id":"rs_1","type":"reasoning","encrypted_content":"signature"}]}}`, "", "", + }, "\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, ": grok2api-reasoning-evidence\n\n") != 1 { + t.Fatalf("final-envelope reasoning evidence missing or duplicated: %s", text) + } + if strings.Contains(text, "signature") || strings.Contains(text, "encrypted_content") { + t.Fatalf("final-envelope encrypted reasoning leaked into Chat JSON: %s", text) + } +} + func TestConvertResponsesStreamChatPrefersRawReasoningOverSummary(t *testing.T) { stream := strings.Join([]string{ `event: response.created`, diff --git a/backend/internal/infra/provider/conversation/stream.go b/backend/internal/infra/provider/conversation/stream.go index 8180c89f..ad889908 100644 --- a/backend/internal/infra/provider/conversation/stream.go +++ b/backend/internal/infra/provider/conversation/stream.go @@ -53,6 +53,7 @@ type streamConverter struct { thinkingIndex int thinkingItemID string chatReasoningMark bool + evidenceMarked bool reasoningItems map[string]*reasoningStreamState reasoningOrder []string activeReasoningID string @@ -95,6 +96,23 @@ func newStreamConverter(writer io.Writer, operation string, options ResponseOpti } } +// markReasoningEvidence preserves non-empty upstream encrypted_content for the +// request-path quality scanner after protocol conversion. SSE clients ignore +// comments, so Chat and Messages public event payloads remain unchanged. +func (c *streamConverter) markReasoningEvidence() error { + if c.evidenceMarked { + return nil + } + if err := c.start(); err != nil { + return err + } + if _, err := io.WriteString(c.writer, ": grok2api-reasoning-evidence\n\n"); err != nil { + return err + } + c.evidenceMarked = true + return nil +} + // noteWebSearch records a Build web_search_call. Emission is deferred to doneMessages // so we always use the completed action.sources payload from the final envelope when available. // For progressive UI we still emit server_tool_use as soon as we see the call. @@ -314,6 +332,11 @@ func (c *streamConverter) handle(event string, data []byte) error { return err } } + if strings.TrimSpace(item.Encrypted) != "" { + if err := c.markReasoningEvidence(); err != nil { + return err + } + } return c.thinkingDone(item) } if item.Type == "web_search_call" && c.operation == OperationMessages && c.options.AnthropicWebSearch { @@ -325,6 +348,13 @@ func (c *streamConverter) handle(event string, data []byte) error { var response responseEnvelope _ = json.Unmarshal(root["response"], &response) c.setResponse(response) + for _, item := range response.Output { + if item.Type == "reasoning" && strings.TrimSpace(item.Encrypted) != "" { + if err := c.markReasoningEvidence(); err != nil { + return err + } + } + } if c.operation == OperationMessages && c.options.AnthropicWebSearch { parsed := parseResponse(response) for _, call := range parsed.WebSearch { diff --git a/backend/internal/repository/runtime.go b/backend/internal/repository/runtime.go index a5dd5d34..ec67889b 100644 --- a/backend/internal/repository/runtime.go +++ b/backend/internal/repository/runtime.go @@ -96,14 +96,15 @@ const ( // InvalidationAccountHealthChanged carries the exact request-path health // mutation for one account. Unlike an arbitrary account state change, it can // be applied as a small runtime overlay without rebuilding the provider pool. - InvalidationAccountHealthChanged InvalidationKind = "account_health_changed" - InvalidationAccountCredentialChanged InvalidationKind = "account_credential_changed" - InvalidationAccountCapabilityChanged InvalidationKind = "account_capability_changed" - InvalidationAccountBillingChanged InvalidationKind = "account_billing_changed" - InvalidationAccountQuotaChanged InvalidationKind = "account_quota_changed" - InvalidationAccountRecoveryChanged InvalidationKind = "account_recovery_changed" - InvalidationAccountModelQuotaChanged InvalidationKind = "account_model_quota_changed" - InvalidationClientKeyChanged InvalidationKind = "client_key_changed" + InvalidationAccountHealthChanged InvalidationKind = "account_health_changed" + InvalidationAccountCredentialChanged InvalidationKind = "account_credential_changed" + InvalidationAccountCapabilityChanged InvalidationKind = "account_capability_changed" + InvalidationAccountBillingChanged InvalidationKind = "account_billing_changed" + InvalidationAccountQuotaChanged InvalidationKind = "account_quota_changed" + InvalidationAccountRecoveryChanged InvalidationKind = "account_recovery_changed" + InvalidationAccountEgressLeaseChanged InvalidationKind = "account_egress_lease_changed" + InvalidationAccountModelQuotaChanged InvalidationKind = "account_model_quota_changed" + InvalidationClientKeyChanged InvalidationKind = "client_key_changed" ) type InvalidationLayer string @@ -137,7 +138,7 @@ func (e InvalidationEvent) Layer() InvalidationLayer { return InvalidationLayerRoute case InvalidationModelBindingChanged, InvalidationAccountCapabilityChanged, InvalidationAccountModelQuotaChanged: return InvalidationLayerOverlay - case InvalidationAccountStateChanged, InvalidationAccountHealthChanged, InvalidationAccountCredentialChanged, InvalidationAccountBillingChanged, InvalidationAccountQuotaChanged, InvalidationAccountRecoveryChanged: + case InvalidationAccountStateChanged, InvalidationAccountHealthChanged, InvalidationAccountCredentialChanged, InvalidationAccountBillingChanged, InvalidationAccountQuotaChanged, InvalidationAccountRecoveryChanged, InvalidationAccountEgressLeaseChanged: return InvalidationLayerBase case InvalidationClientKeyChanged: return InvalidationLayerClientKey diff --git a/backend/internal/transport/http/account/handler.go b/backend/internal/transport/http/account/handler.go index 729ea2b0..1f67d595 100644 --- a/backend/internal/transport/http/account/handler.go +++ b/backend/internal/transport/http/account/handler.go @@ -165,6 +165,7 @@ func (h *Handler) Register(router *gin.RouterGroup) { router.DELETE("/accounts", h.batchDelete) router.PATCH("/accounts/:id", h.update) router.DELETE("/accounts/:id", h.delete) + router.POST("/accounts/:id/clear-cooldown", h.clearCooldown) router.POST("/accounts/:id/refresh-token", h.refreshToken) router.POST("/accounts/:id/refresh-billing", h.refreshBilling) router.POST("/accounts/:id/refresh-quota", h.refreshWebQuota) @@ -307,6 +308,9 @@ type accountResponse struct { FailureCount int `json:"failureCount"` CooldownUntil *time.Time `json:"cooldownUntil,omitempty"` LastError string `json:"lastError,omitempty"` + // EnabledDoesNotClearCooldown is set on PATCH when enabled was changed + // while the account is still cooling. Toggling enabled is not a health reset. + EnabledDoesNotClearCooldown bool `json:"enabledDoesNotClearCooldown,omitempty"` LastUsedAt *time.Time `json:"lastUsedAt,omitempty"` LinkedAccountID uint64 `json:"linkedAccountId,omitempty,string"` LinkedName string `json:"linkedAccountName,omitempty"` @@ -1255,6 +1259,9 @@ func (h *Handler) update(c *gin.Context) { return } result := newAccountResponse(value) + if value.EnabledChanged && result.CooldownUntil != nil && time.Now().UTC().Before(*result.CooldownUntil) { + result.EnabledDoesNotClearCooldown = true + } if request.BuildSuperEntitled != nil { if synchronizer, ok := h.sync.(accountModelSynchronizer); ok { result.ModelSyncFailed = synchronizer.SyncModels(c.Request.Context(), id) != nil @@ -1263,6 +1270,19 @@ func (h *Handler) update(c *gin.Context) { response.Success(c, http.StatusOK, result) } +func (h *Handler) clearCooldown(c *gin.Context) { + id, ok := pathID(c) + if !ok { + return + } + value, err := h.service.ClearCooldown(c.Request.Context(), id) + if err != nil { + h.writeServiceError(c, "accountClearCooldownFailed", err, http.StatusInternalServerError, "清除账号冷却失败") + return + } + response.Success(c, http.StatusOK, newAccountResponse(value)) +} + func (h *Handler) delete(c *gin.Context) { id, ok := pathID(c) if !ok { diff --git a/backend/internal/transport/http/account/handler_test.go b/backend/internal/transport/http/account/handler_test.go index fdb1c23e..18d96901 100644 --- a/backend/internal/transport/http/account/handler_test.go +++ b/backend/internal/transport/http/account/handler_test.go @@ -11,6 +11,7 @@ import ( "net/http" "net/http/httptest" "path/filepath" + "strconv" "strings" "sync/atomic" "testing" @@ -18,11 +19,14 @@ import ( accountapp "github.com/chenyme/grok2api/backend/internal/application/account" accountsyncapp "github.com/chenyme/grok2api/backend/internal/application/accountsync" + gatewayapp "github.com/chenyme/grok2api/backend/internal/application/gateway" accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" "github.com/chenyme/grok2api/backend/internal/infra/persistence/relational" "github.com/chenyme/grok2api/backend/internal/infra/provider" cliprovider "github.com/chenyme/grok2api/backend/internal/infra/provider/cli" + "github.com/chenyme/grok2api/backend/internal/infra/runtime/memory" "github.com/chenyme/grok2api/backend/internal/infra/security" + "github.com/chenyme/grok2api/backend/internal/repository" "github.com/gin-gonic/gin" ) @@ -224,6 +228,139 @@ func TestLinkedDeleteMissingAccountReturnsNotFound(t *testing.T) { } } +func TestClearCooldownResetsHealthAndSelectorCache(t *testing.T) { + gin.SetMode(gin.TestMode) + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "clear-cooldown.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + repo := relational.NewAccountRepository(database) + selector := gatewayapp.NewSelector(repo, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), nil, time.Hour, time.Second, time.Minute) + repo.SetInvalidationObserver(func(_ context.Context, event repository.InvalidationEvent) { + selector.ApplyInvalidation(event) + }) + until := time.Now().UTC().Add(24 * time.Hour) + created, _, err := repo.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderBuild, Name: "cooled", SourceKey: "cooled", + EncryptedAccessToken: "token", Enabled: true, AuthStatus: accountdomain.AuthStatusActive, + Priority: 100, MaxConcurrent: 1, + }) + if err != nil { + t.Fatal(err) + } + if err := repo.SaveBilling(ctx, accountdomain.Billing{ + AccountID: created.ID, PlanCode: "pro", PlanName: "Pro", MonthlyLimit: 100, Used: 25, SyncedAt: time.Now().UTC(), + }); err != nil { + t.Fatal(err) + } + if err := repo.UpdateHealth(ctx, created.ID, created.Provider, 3, &until, accountdomain.LastErrorMissingThinking, false); err != nil { + t.Fatal(err) + } + if lease, acquireErr := selector.Acquire(ctx, accountdomain.ProviderBuild, 0, "grok-test", "", "", map[uint64]bool{}, false); acquireErr == nil { + lease.Release() + t.Fatal("cooled account was schedulable before clear") + } + service := accountapp.NewService(repo, relational.NewAuditRepository(database), nil, nil, nil, nil, nil) + handler := NewHandler(service, nil) + + recorder := httptest.NewRecorder() + ginContext, _ := gin.CreateTestContext(recorder) + ginContext.Params = []gin.Param{{Key: "id", Value: strconv.FormatUint(created.ID, 10)}} + ginContext.Request = httptest.NewRequest("POST", "/api/admin/v1/accounts/"+strconv.FormatUint(created.ID, 10)+"/clear-cooldown", nil) + handler.clearCooldown(ginContext) + if recorder.Code != 200 { + t.Fatalf("status = %d, body = %s", recorder.Code, recorder.Body.String()) + } + if strings.Contains(recorder.Body.String(), `"cooldownUntil"`) || strings.Contains(recorder.Body.String(), `"failureCount":3`) { + t.Fatalf("cooldown still present: %s", recorder.Body.String()) + } + if !strings.Contains(recorder.Body.String(), `"failureCount":0`) { + t.Fatalf("failureCount not reset: %s", recorder.Body.String()) + } + if !strings.Contains(recorder.Body.String(), `"lastError":"missing_thinking"`) { + t.Fatalf("missing-thinking strike was cleared: %s", recorder.Body.String()) + } + if !strings.Contains(recorder.Body.String(), `"planCode":"pro"`) || !strings.Contains(recorder.Body.String(), `"billing"`) { + t.Fatalf("complete account view was not returned: %s", recorder.Body.String()) + } + + stored, err := repo.Get(ctx, created.ID) + if err != nil { + t.Fatal(err) + } + if stored.FailureCount != 0 || stored.CooldownUntil != nil || stored.LastError != accountdomain.LastErrorMissingThinking { + t.Fatalf("persisted health = failure=%d cooldown=%v last=%q", stored.FailureCount, stored.CooldownUntil, stored.LastError) + } + lease, err := selector.Acquire(ctx, accountdomain.ProviderBuild, 0, "grok-test", "", "", map[uint64]bool{}, false) + if err != nil { + t.Fatalf("account remained unavailable in selector after clear: %v", err) + } + if lease.Credential.ID != created.ID || lease.Credential.LastError != accountdomain.LastErrorMissingThinking { + t.Fatalf("lease credential = %#v", lease.Credential) + } + lease.Release() + + missing := httptest.NewRecorder() + missingCtx, _ := gin.CreateTestContext(missing) + missingCtx.Params = []gin.Param{{Key: "id", Value: "999999"}} + missingCtx.Request = httptest.NewRequest("POST", "/api/admin/v1/accounts/999999/clear-cooldown", nil) + handler.clearCooldown(missingCtx) + if missing.Code != 404 { + t.Fatalf("missing status = %d, body = %s", missing.Code, missing.Body.String()) + } +} + +func TestUpdateCooldownWarningRequiresEnabledChange(t *testing.T) { + gin.SetMode(gin.TestMode) + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "update-cooldown-warning.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + repo := relational.NewAccountRepository(database) + created, _, err := repo.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderBuild, Name: "cooled", SourceKey: "cooled-warning", + EncryptedAccessToken: "token", Enabled: true, AuthStatus: accountdomain.AuthStatusActive, + Priority: 100, MaxConcurrent: 1, + }) + if err != nil { + t.Fatal(err) + } + until := time.Now().UTC().Add(time.Hour) + if err := repo.UpdateHealth(ctx, created.ID, created.Provider, 1, &until, "upstream status 504", false); err != nil { + t.Fatal(err) + } + handler := NewHandler(accountapp.NewService(repo, relational.NewAuditRepository(database), nil, nil, nil, nil, nil), nil) + + update := func(body string) *httptest.ResponseRecorder { + recorder := httptest.NewRecorder() + ginContext, _ := gin.CreateTestContext(recorder) + ginContext.Params = []gin.Param{{Key: "id", Value: strconv.FormatUint(created.ID, 10)}} + ginContext.Request = httptest.NewRequest("PATCH", "/api/admin/v1/accounts/"+strconv.FormatUint(created.ID, 10), strings.NewReader(body)) + ginContext.Request.Header.Set("Content-Type", "application/json") + handler.update(ginContext) + return recorder + } + + same := update(`{"enabled":true}`) + if same.Code != http.StatusOK || strings.Contains(same.Body.String(), `"enabledDoesNotClearCooldown":true`) { + t.Fatalf("unchanged enabled warning: status=%d body=%s", same.Code, same.Body.String()) + } + changed := update(`{"enabled":false}`) + if changed.Code != http.StatusOK || !strings.Contains(changed.Body.String(), `"enabledDoesNotClearCooldown":true`) { + t.Fatalf("changed enabled warning missing: status=%d body=%s", changed.Code, changed.Body.String()) + } +} + func (s *accountSynchronizerStub) Sync(_ context.Context, accountIDs ...uint64) accountsyncapp.Result { s.accountIDs = append(s.accountIDs, accountIDs...) return accountsyncapp.Result{Succeeded: len(accountIDs)} diff --git a/backend/internal/transport/http/audit/handler.go b/backend/internal/transport/http/audit/handler.go index 7f6ff739..d53f87a3 100644 --- a/backend/internal/transport/http/audit/handler.go +++ b/backend/internal/transport/http/audit/handler.go @@ -43,6 +43,7 @@ type qualityGuardAuditResponse struct { RequestID string `json:"requestId"` QualityProbe bool `json:"qualityProbe"` Provider string `json:"provider"` + AccountID *uint64 `json:"accountId,string,omitempty"` EgressNodeID *uint64 `json:"egressNodeId,string,omitempty"` EgressNodeName string `json:"egressNodeName,omitempty"` StatusCode int `json:"statusCode"` @@ -74,7 +75,7 @@ func (h *Handler) listQualityGuard(c *gin.Context) { for _, value := range result.Items { items = append(items, qualityGuardAuditResponse{ ID: value.ID, RequestID: value.RequestID, QualityProbe: value.ClientKeyID == h.qualityGuardClientKeyID, - Provider: value.Provider, EgressNodeID: value.EgressNodeID, EgressNodeName: value.EgressNodeName, + Provider: value.Provider, AccountID: value.AccountID, EgressNodeID: value.EgressNodeID, EgressNodeName: value.EgressNodeName, StatusCode: value.StatusCode, Streaming: value.Streaming, OutputTokens: value.OutputTokens, ReasoningTokens: value.ReasoningTokens, FirstTokenMS: value.FirstTokenMS, DurationMS: value.DurationMS, ErrorCode: value.ErrorCode, diff --git a/backend/internal/transport/http/egress/handler.go b/backend/internal/transport/http/egress/handler.go index 5b602eb3..63145686 100644 --- a/backend/internal/transport/http/egress/handler.go +++ b/backend/internal/transport/http/egress/handler.go @@ -1,6 +1,7 @@ package egress import ( + "encoding/base64" "encoding/json" "errors" "fmt" @@ -97,6 +98,9 @@ func (h *Handler) RegisterQualityGuard(router *gin.RouterGroup) { router.PATCH("/egress-nodes/batch", h.updateMany) router.POST("/egress-nodes/:id/test", h.testNode) router.POST("/egress-nodes/:id/quality-test", h.testQualityGuardNode) + router.GET("/egress-leases", h.listQualityGuardLeases) + router.POST("/egress-leases/quarantine", h.quarantineQualityGuardLease) + router.POST("/egress-leases/restore", h.restoreQualityGuardLease) router.GET("/egress-operations", h.operationsConfig) } @@ -159,6 +163,9 @@ type qualityGuardConfig struct { } type qualityGuardNodeState struct { + ObserveOnly bool `json:"observe_only"` + ObserveOnlyReason string `json:"observe_only_reason"` + QuarantinedLeases int `json:"quarantined_lease_count"` ActiveSoftStrikes int `json:"active_soft_strikes"` PassiveSoftStrikes int `json:"passive_soft_strikes"` ErrorStrikes int `json:"error_strikes"` @@ -180,9 +187,12 @@ type qualityGuardEvent struct { Event string `json:"event"` NodeID string `json:"node_id"` NodeName string `json:"node_name"` + AccountID string `json:"account_id,omitempty"` + RequestID string `json:"request_id,omitempty"` Reason string `json:"reason"` Classification string `json:"classification"` OutputTPS float64 `json:"output_tps"` + CooldownUntil float64 `json:"cooldown_until,omitempty"` } func (h *Handler) qualityGuardStatus(c *gin.Context) { @@ -384,6 +394,7 @@ func (h *Handler) testQualityGuardNode(c *gin.Context) { } var request struct { ProfileID string `json:"profileId"` + AccountID string `json:"accountId"` } _ = c.ShouldBindJSON(&request) input, err := h.resolveProbeInput(strings.TrimSpace(request.ProfileID)) @@ -395,6 +406,14 @@ func (h *Handler) testQualityGuardNode(c *gin.Context) { response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "质量守护配置暂不可用") return } + if strings.TrimSpace(request.AccountID) != "" { + accountID, parseErr := strconv.ParseUint(request.AccountID, 10, 64) + if parseErr != nil || accountID == 0 { + response.Error(c, http.StatusBadRequest, "invalidAccountId", "账号 ID 无效") + return + } + input.AccountID = accountID + } value, err := h.service.ProbeQuality(c.Request.Context(), nodeID, input) if err != nil { h.writeQualityProbeError(c, err) @@ -413,6 +432,149 @@ func (h *Handler) testQualityGuardNode(c *gin.Context) { }) } +type qualityLeaseRequest struct { + AccountID string `json:"accountId" binding:"required"` + NodeID string `json:"nodeId" binding:"required"` + Reason string `json:"reason"` + Version string `json:"version"` + QuarantineSeconds int `json:"quarantineSeconds"` +} + +type qualityLeaseCursor struct { + CooldownUntil int64 `json:"t"` + AccountID uint64 `json:"a"` + NodeID uint64 `json:"n"` +} + +func qualityLeaseResponse(value accountdomain.EgressLeaseBlock) gin.H { + return gin.H{ + "accountId": strconv.FormatUint(value.AccountID, 10), "nodeId": strconv.FormatUint(value.NodeID, 10), + "reason": value.Reason, "version": value.Version, "cooldownUntil": float64(value.CooldownUntil.UnixMilli()) / 1000, + "updatedAt": value.UpdatedAt.UTC(), + } +} + +func (h *Handler) listQualityGuardLeases(c *gin.Context) { + limit, parseErr := strconv.Atoi(c.DefaultQuery("limit", "500")) + if parseErr != nil || limit < 1 || limit > 1000 { + response.Error(c, http.StatusBadRequest, "invalidPageSize", "分页大小无效") + return + } + cursor, cursorErr := decodeQualityLeaseCursor(c.Query("cursor")) + if cursorErr != nil { + response.Error(c, http.StatusBadRequest, "invalidCursor", "分页游标无效") + return + } + values, err := h.service.ListQualityLeases(c.Request.Context(), limit+1, cursor) + if err != nil { + h.writeQualityLeaseError(c, err) + return + } + hasMore := len(values) > limit + if hasMore { + values = values[:limit] + } + items := make([]gin.H, 0, len(values)) + for _, value := range values { + items = append(items, qualityLeaseResponse(value)) + } + nextCursor := "" + if hasMore && len(values) > 0 { + nextCursor = encodeQualityLeaseCursor(values[len(values)-1]) + } + response.Success(c, http.StatusOK, gin.H{"items": items, "hasMore": hasMore, "nextCursor": nextCursor}) +} + +func decodeQualityLeaseCursor(raw string) (*accountdomain.EgressLeaseBlockCursor, error) { + raw = strings.TrimSpace(raw) + if raw == "" { + return nil, nil + } + if len(raw) > 256 { + return nil, errors.New("cursor too long") + } + decoded, err := base64.RawURLEncoding.DecodeString(raw) + if err != nil { + return nil, err + } + var value qualityLeaseCursor + decoder := json.NewDecoder(strings.NewReader(string(decoded))) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&value); err != nil || value.CooldownUntil <= 0 || value.AccountID == 0 || value.NodeID == 0 { + return nil, errors.New("invalid cursor") + } + if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) { + return nil, errors.New("invalid cursor") + } + return &accountdomain.EgressLeaseBlockCursor{ + CooldownUntil: time.Unix(0, value.CooldownUntil).UTC(), AccountID: value.AccountID, NodeID: value.NodeID, + }, nil +} + +func encodeQualityLeaseCursor(value accountdomain.EgressLeaseBlock) string { + payload, _ := json.Marshal(qualityLeaseCursor{ + CooldownUntil: value.CooldownUntil.UTC().UnixNano(), AccountID: value.AccountID, NodeID: value.NodeID, + }) + return base64.RawURLEncoding.EncodeToString(payload) +} + +func (h *Handler) quarantineQualityGuardLease(c *gin.Context) { + var request qualityLeaseRequest + if c.ShouldBindJSON(&request) != nil { + response.Error(c, http.StatusBadRequest, "invalidRequest", "请求参数无效") + return + } + accountID, accountErr := strconv.ParseUint(request.AccountID, 10, 64) + nodeID, nodeErr := strconv.ParseUint(request.NodeID, 10, 64) + if accountErr != nil || nodeErr != nil || accountID == 0 || nodeID == 0 { + response.Error(c, http.StatusBadRequest, "invalidId", "账号或节点 ID 无效") + return + } + value, err := h.service.QuarantineQualityLease(c.Request.Context(), egressapp.QualityLeaseInput{ + AccountID: accountID, NodeID: nodeID, Reason: request.Reason, QuarantineSeconds: request.QuarantineSeconds, + }) + if err != nil { + h.writeQualityLeaseError(c, err) + return + } + response.Success(c, http.StatusOK, qualityLeaseResponse(value)) +} + +func (h *Handler) restoreQualityGuardLease(c *gin.Context) { + var request qualityLeaseRequest + if c.ShouldBindJSON(&request) != nil { + response.Error(c, http.StatusBadRequest, "invalidRequest", "请求参数无效") + return + } + accountID, accountErr := strconv.ParseUint(request.AccountID, 10, 64) + nodeID, nodeErr := strconv.ParseUint(request.NodeID, 10, 64) + if accountErr != nil || nodeErr != nil || accountID == 0 || nodeID == 0 { + response.Error(c, http.StatusBadRequest, "invalidId", "账号或节点 ID 无效") + return + } + restored, err := h.service.RestoreQualityLease(c.Request.Context(), accountID, nodeID, request.Version) + if err != nil { + h.writeQualityLeaseError(c, err) + return + } + response.Success(c, http.StatusOK, gin.H{"restored": restored}) +} + +func (h *Handler) writeQualityLeaseError(c *gin.Context, err error) { + switch { + case errors.Is(err, egressapp.ErrInvalidInput): + response.Error(c, http.StatusBadRequest, "invalidQualityLease", "租约隔离参数无效") + case errors.Is(err, egressapp.ErrNotFound): + response.Error(c, http.StatusNotFound, "egressNodeNotFound", "代理节点不存在") + case errors.Is(err, egressapp.ErrQualityLeaseConflict): + response.Error(c, http.StatusConflict, "qualityLeaseConflict", "租约绑定或隔离版本已变化") + case errors.Is(err, egressapp.ErrQualityLeaseUnavailable): + response.Error(c, http.StatusServiceUnavailable, "qualityLeaseUnavailable", "租约级质量隔离暂不可用") + default: + response.Error(c, http.StatusInternalServerError, "qualityLeaseOperationFailed", "租约级质量隔离操作失败") + } +} + func (h *Handler) cleanupPreview(c *gin.Context) { value, err := h.service.PreviewUnhealthyCleanup(c.Request.Context()) if err != nil { diff --git a/backend/internal/transport/http/egress/handler_test.go b/backend/internal/transport/http/egress/handler_test.go index cec713d0..dfeb1599 100644 --- a/backend/internal/transport/http/egress/handler_test.go +++ b/backend/internal/transport/http/egress/handler_test.go @@ -14,12 +14,38 @@ import ( "time" egressapp "github.com/chenyme/grok2api/backend/internal/application/egress" + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress" "github.com/chenyme/grok2api/backend/internal/infra/security" "github.com/chenyme/grok2api/backend/internal/repository" "github.com/gin-gonic/gin" ) +func TestQualityLeaseCursorRoundTripAndValidation(t *testing.T) { + want := accountdomain.EgressLeaseBlock{ + AccountID: 42, + NodeID: 9, + CooldownUntil: time.Date(2026, time.August, 19, 8, 7, 6, 123456789, time.UTC), + } + encoded := encodeQualityLeaseCursor(want) + got, err := decodeQualityLeaseCursor(encoded) + if err != nil { + t.Fatal(err) + } + if got.AccountID != want.AccountID || got.NodeID != want.NodeID || !got.CooldownUntil.Equal(want.CooldownUntil) { + t.Fatalf("cursor = %#v, want %#v", got, want) + } + for _, raw := range []string{ + "not-base64", + "eyJ0IjoxLCJhIjowLCJuIjoxfQ", + "eyJ0IjoxLCJhIjoxLCJuIjoxfXsic2Vjb25kIjp0cnVlfQ", + } { + if _, err := decodeQualityLeaseCursor(raw); err == nil { + t.Fatalf("decodeQualityLeaseCursor(%q) succeeded", raw) + } + } +} + type proxyRevealRepository struct { node egressdomain.Node profile egressdomain.ProxyProfile @@ -131,7 +157,7 @@ func TestProxyProfileListUsesBoundedPaginationAndSearch(t *testing.T) { func TestQualityGuardStatusReadsOnlyPublicState(t *testing.T) { path := t.TempDir() + "/state.json" - state := `{"version":1,"started_at":10,"updated_at":20,"last_active_cycle_at":15,"last_passive_poll_at":19,"password":"must-not-leak","guard":{"mode":"hybrid","model":"grok-4.5","client_key_id":"6","node_ids":["8"],"active_interval_seconds":1800,"passive_poll_seconds":5,"soft_tps":500,"hard_tps":1000,"consecutive_soft":2,"consecutive_errors":2,"quarantine_seconds":300,"min_healthy_nodes":3,"max_output_tokens":384,"fail_closed":true,"min_generation_ms":1234,"prompt":"private-probe-prompt","expected":"private-marker"},"protected_node_ids":["9"],"nodes":{"8":{"active_soft_strikes":0,"passive_soft_strikes":0,"error_strikes":0,"quarantined_until":0,"disabled_by_guard":false,"last_reason":"","last_probe_at":15,"last_observed_at":19,"last_source":"passive","last_classification":"healthy","last_output_tps":42.5,"last_output_tokens":100,"last_first_token_ms":900,"last_duration_ms":4000}},"statistics":{"started_at":11,"active":{"total":7,"healthy":6,"soft":1,"hard":0,"errors":0,"output_tokens":1400},"passive":{"total":9,"healthy":8,"soft":0,"hard":1,"errors":0,"output_tokens":1800},"actions":{"quarantined":1,"restored":0,"suppressed":0}}}` + state := `{"version":1,"started_at":10,"updated_at":20,"last_active_cycle_at":15,"last_passive_poll_at":19,"password":"must-not-leak","guard":{"mode":"hybrid","model":"grok-4.5","client_key_id":"6","node_ids":["8"],"active_interval_seconds":1800,"passive_poll_seconds":5,"soft_tps":500,"hard_tps":1000,"consecutive_soft":2,"consecutive_errors":2,"quarantine_seconds":300,"min_healthy_nodes":3,"max_output_tokens":384,"fail_closed":true,"min_generation_ms":1234,"prompt":"private-probe-prompt","expected":"private-marker"},"protected_node_ids":["9"],"nodes":{"8":{"observe_only":true,"observe_only_reason":"account_bound_proxy","active_soft_strikes":0,"passive_soft_strikes":0,"error_strikes":0,"quarantined_until":0,"disabled_by_guard":false,"last_reason":"","last_probe_at":15,"last_observed_at":19,"last_source":"passive","last_classification":"healthy","last_output_tps":42.5,"last_output_tokens":100,"last_first_token_ms":900,"last_duration_ms":4000}},"statistics":{"started_at":11,"active":{"total":7,"healthy":6,"soft":1,"hard":0,"errors":0,"output_tokens":1400},"passive":{"total":9,"healthy":8,"soft":0,"hard":1,"errors":0,"output_tokens":1800},"actions":{"quarantined":1,"restored":0,"suppressed":0}}}` if err := os.WriteFile(path, []byte(state), 0o600); err != nil { t.Fatal(err) } @@ -139,7 +165,7 @@ func TestQualityGuardStatusReadsOnlyPublicState(t *testing.T) { context, _ := gin.CreateTestContext(recorder) context.Request = httptest.NewRequest("GET", "/egress-quality-guard", nil) NewHandler(nil, path).qualityGuardStatus(context) - if recorder.Code != 200 || !strings.Contains(recorder.Body.String(), `"available":true`) || !strings.Contains(recorder.Body.String(), `"last_output_tps":42.5`) || !strings.Contains(recorder.Body.String(), `"output_tokens":1400`) || !strings.Contains(recorder.Body.String(), `"protectedNodeIds":["9"]`) || !strings.Contains(recorder.Body.String(), `"fail_closed":true`) || !strings.Contains(recorder.Body.String(), `"min_generation_ms":1234`) { + if recorder.Code != 200 || !strings.Contains(recorder.Body.String(), `"available":true`) || !strings.Contains(recorder.Body.String(), `"observe_only":true`) || !strings.Contains(recorder.Body.String(), `"observe_only_reason":"account_bound_proxy"`) || !strings.Contains(recorder.Body.String(), `"last_output_tps":42.5`) || !strings.Contains(recorder.Body.String(), `"output_tokens":1400`) || !strings.Contains(recorder.Body.String(), `"protectedNodeIds":["9"]`) || !strings.Contains(recorder.Body.String(), `"fail_closed":true`) || !strings.Contains(recorder.Body.String(), `"min_generation_ms":1234`) { t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String()) } if strings.Contains(recorder.Body.String(), "must-not-leak") || strings.Contains(recorder.Body.String(), "private-probe-prompt") || strings.Contains(recorder.Body.String(), "private-marker") || strings.Contains(recorder.Body.String(), "client_key_id") || !strings.Contains(recorder.Body.String(), `"recentEvents":[]`) { diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index 765c62a3..d2b519af 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -1172,7 +1172,7 @@ func (h *Handler) handleCreate(c *gin.Context, compact bool) { writeGatewayError(c, err) return } - h.writeResult(c, result, request.Stream && !compact, streamProtocolResponses) + h.writeResponsesResult(c, result, request.Stream && !compact, request.Model) } func isJSONRequest(c *gin.Context) bool { @@ -1232,14 +1232,18 @@ func (h *Handler) handleOwnedResource(c *gin.Context, deleteResource bool) { } func (h *Handler) writeResult(c *gin.Context, result *gateway.Result, stream bool, protocol streamProtocol) { - h.writeProtocolResult(c, result, stream, false, protocol) + h.writeProtocolResult(c, result, stream, false, protocol, "") +} + +func (h *Handler) writeResponsesResult(c *gin.Context, result *gateway.Result, stream bool, fallbackModel string) { + h.writeProtocolResult(c, result, stream, false, streamProtocolResponses, fallbackModel) } func (h *Handler) writeAnthropicResult(c *gin.Context, result *gateway.Result, stream bool) { - h.writeProtocolResult(c, result, stream, true, streamProtocolAnthropic) + h.writeProtocolResult(c, result, stream, true, streamProtocolAnthropic, "") } -func (h *Handler) writeProtocolResult(c *gin.Context, result *gateway.Result, stream, anthropic bool, protocol streamProtocol) { +func (h *Handler) writeProtocolResult(c *gin.Context, result *gateway.Result, stream, anthropic bool, protocol streamProtocol, fallbackModel string) { usage := gateway.Usage{} responseID := "" errorCode := "" @@ -1278,7 +1282,7 @@ func (h *Handler) writeProtocolResult(c *gin.Context, result *gateway.Result, st } var err error if stream { - metadata, copyErr := copyStream(c.Writer, result.Body, protocol, result.MarkFirstToken) + metadata, copyErr := copyStreamWithFallbackModel(c.Writer, result.Body, protocol, result.MarkFirstToken, fallbackModel) usage, responseID, responseBody, err = metadata.Usage, metadata.ResponseID, metadata.ResponseBody, copyErr if metadata.StreamFailure != nil && result.RecordStreamFailure != nil { result.RecordStreamFailure(*metadata.StreamFailure) @@ -1316,9 +1320,14 @@ type responseMetadata struct { } func copyStream(writer gin.ResponseWriter, source io.Reader, protocol streamProtocol, onFirstToken func()) (responseMetadata, error) { + return copyStreamWithFallbackModel(writer, source, protocol, onFirstToken, "") +} + +func copyStreamWithFallbackModel(writer gin.ResponseWriter, source io.Reader, protocol streamProtocol, onFirstToken func(), fallbackModel string) (responseMetadata, error) { inspector := &responseInspector{protocol: protocol, onFirstToken: onFirstToken} - markerFilter := internalSSEMarkerFilter{enabled: protocol == streamProtocolChat} + markerFilter := internalSSEMarkerFilter{enabled: protocol == streamProtocolChat || protocol == streamProtocolAnthropic} var compat responsesCompatState + compat.model = strings.TrimSpace(fallbackModel) buffer := make([]byte, responseCopyBufferBytes) received := 0 transferred := 0 @@ -1447,21 +1456,29 @@ func streamAbortTrailer(protocol streamProtocol, cause error, meta responseMetad } compat.rememberFromMeta(meta) id := compat.ensureID() - response := map[string]any{ - "id": id, - "object": "response", - "created_at": compat.createdAt, - "completed_at": compat.createdAt, - "status": "incomplete", - "output": []any{}, - "error": nil, - "incomplete_details": map[string]any{"reason": code}, + // Grok TUI 0.2.93 treats any response.incomplete as fatal + // max_tokens_truncation (not retryable), ignoring incomplete_details.reason. + // Stream aborts are transport failures — emit response.failed so the + // client can retry instead of killing the turn. + model := strings.TrimSpace(meta.Model) + if model == "" { + model = strings.TrimSpace(compat.model) } - if model := strings.TrimSpace(meta.Model); model != "" { - response["model"] = model + response := map[string]any{ + "id": id, + "object": "response", + "created_at": compat.createdAt, + "completed_at": compat.createdAt, + "status": "failed", + "model": model, + "output": []any{}, + "error": map[string]any{ + "code": "server_error", + "message": code + ": " + message, + }, } event := map[string]any{ - "type": "response.incomplete", + "type": "response.failed", "id": id, "sequence_number": meta.SequenceNumber + 1, "response": response, @@ -1471,7 +1488,7 @@ func streamAbortTrailer(protocol streamProtocol, cause error, meta responseMetad if err != nil { return nil } - return []byte("event: response.incomplete\ndata: " + string(payload) + "\n\n") + return []byte("event: response.failed\ndata: " + string(payload) + "\n\n") case streamProtocolAnthropic: payload, err := json.Marshal(map[string]any{ "type": "error", @@ -1495,13 +1512,13 @@ func (f *internalSSEMarkerFilter) Filter(chunk []byte, final bool) []byte { if !f.enabled { return chunk } - marker := []byte(reasoningStartSSEComment + "\n\n") f.pending = append(f.pending, chunk...) result := make([]byte, 0, len(f.pending)) for { - if index := bytes.Index(f.pending, marker); index >= 0 { + index, markerLength := nextInternalSSEMarker(f.pending) + if index >= 0 { result = append(result, f.pending[:index]...) - f.pending = f.pending[index+len(marker):] + f.pending = f.pending[index+markerLength:] continue } if final { @@ -1510,11 +1527,13 @@ func (f *internalSSEMarkerFilter) Filter(chunk []byte, final bool) []byte { return result } keep := 0 - limit := min(len(f.pending), len(marker)-1) - for size := limit; size > 0; size-- { - if bytes.Equal(f.pending[len(f.pending)-size:], marker[:size]) { - keep = size - break + for _, marker := range internalSSEMarkers { + limit := min(len(f.pending), len(marker)-1) + for size := limit; size > keep; size-- { + if bytes.Equal(f.pending[len(f.pending)-size:], marker[:size]) { + keep = size + break + } } } result = append(result, f.pending[:len(f.pending)-keep]...) @@ -1523,6 +1542,19 @@ func (f *internalSSEMarkerFilter) Filter(chunk []byte, final bool) []byte { } } +func nextInternalSSEMarker(value []byte) (int, int) { + index := -1 + length := 0 + for _, marker := range internalSSEMarkers { + candidate := bytes.Index(value, marker) + if candidate >= 0 && (index < 0 || candidate < index) { + index = candidate + length = len(marker) + } + } + return index, length +} + func copyJSON(writer gin.ResponseWriter, source io.Reader, protocol streamProtocol) (responseMetadata, error) { buffer := make([]byte, responseCopyBufferBytes) metadataBody := make([]byte, 0, responseCopyBufferBytes) @@ -1593,7 +1625,15 @@ type responseInspector struct { terminalFailure bool } -const reasoningStartSSEComment = ": grok2api-reasoning-start" +const ( + reasoningStartSSEComment = ": grok2api-reasoning-start" + reasoningEvidenceSSEComment = ": grok2api-reasoning-evidence" +) + +var internalSSEMarkers = [][]byte{ + []byte(reasoningStartSSEComment + "\n\n"), + []byte(reasoningEvidenceSSEComment + "\n\n"), +} func (i *responseInspector) Inspect(chunk []byte) { i.pending = append(i.pending, chunk...) diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go index 9215bd34..9be28f23 100644 --- a/backend/internal/transport/http/inference/handler_test.go +++ b/backend/internal/transport/http/inference/handler_test.go @@ -927,8 +927,8 @@ func TestStreamInspectorMarksChatReasoningComment(t *testing.T) { } func TestInternalSSEMarkerFilterAcrossChunkBoundaries(t *testing.T) { - marker := reasoningStartSSEComment + "\n\n" - input := []byte("data: before\n\n" + marker + "data: after\n\n") + markers := reasoningStartSSEComment + "\n\n" + reasoningEvidenceSSEComment + "\n\n" + input := []byte("data: before\n\n" + markers + "data: after\n\n") want := "data: before\n\ndata: after\n\n" for split := 0; split <= len(input); split++ { filter := internalSSEMarkerFilter{enabled: true} @@ -948,6 +948,7 @@ func TestCopyStreamConsumesInternalReasoningMarker(t *testing.T) { context, _ := gin.CreateTestContext(recorder) body := `data: {"choices":[{"delta":{"role":"assistant"}}]}` + "\n\n" + ": grok2api-reasoning-start\n\n" + + ": grok2api-reasoning-evidence\n\n" + `data: {"choices":[{"delta":{"content":"hello"}}]}` + "\n\n" + "data: [DONE]\n\n" marked := 0 @@ -957,7 +958,7 @@ func TestCopyStreamConsumesInternalReasoningMarker(t *testing.T) { if marked != 1 { t.Fatalf("first token marked %d times", marked) } - if strings.Contains(recorder.Body.String(), "grok2api-reasoning-start") { + if strings.Contains(recorder.Body.String(), "grok2api-reasoning-") { t.Fatalf("internal marker leaked to client: %q", recorder.Body.String()) } if !strings.Contains(recorder.Body.String(), `"content":"hello"`) { @@ -965,6 +966,26 @@ func TestCopyStreamConsumesInternalReasoningMarker(t *testing.T) { } } +func TestCopyStreamConsumesAnthropicReasoningEvidenceMarker(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + context, _ := gin.CreateTestContext(recorder) + body := ": grok2api-reasoning-evidence\n\n" + + "event: content_block_delta\n" + + `data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"sig"}}` + "\n\n" + + "event: message_stop\n" + + `data: {"type":"message_stop"}` + "\n\n" + if _, err := copyStream(context.Writer, strings.NewReader(body), streamProtocolAnthropic, nil); err != nil { + t.Fatal(err) + } + if strings.Contains(recorder.Body.String(), "grok2api-reasoning-evidence") { + t.Fatalf("internal Anthropic marker leaked to client: %q", recorder.Body.String()) + } + if !strings.Contains(recorder.Body.String(), `"signature":"sig"`) { + t.Fatalf("Anthropic signature delta missing: %q", recorder.Body.String()) + } +} + func TestCopyStreamPreservesBufferedTailOnReadError(t *testing.T) { gin.SetMode(gin.TestMode) recorder := httptest.NewRecorder() @@ -991,14 +1012,14 @@ func TestCopyStreamWritesTerminalOnIdleTimeout(t *testing.T) { want []string }{ {name: "chat", protocol: streamProtocolChat, want: []string{`"code":"upstream_stream_idle_timeout"`, "data: [DONE]"}}, - {name: "responses", protocol: streamProtocolResponses, want: []string{`"type":"response.incomplete"`, `"id":"resp_abort"`, `"created_at":`, `"sequence_number":`, `"incomplete_details"`}}, + {name: "responses", protocol: streamProtocolResponses, want: []string{`"type":"response.failed"`, `"id":"resp_abort"`, `"created_at":`, `"sequence_number":`, `"code":"server_error"`, `"message":"upstream_stream_idle_timeout:`, `"status":"failed"`, `"model":"grok-test"`}}, {name: "anthropic", protocol: streamProtocolAnthropic, want: []string{`"type":"error"`, "上游流式响应长时间无数据"}}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { recorder := httptest.NewRecorder() context, _ := gin.CreateTestContext(recorder) - _, err := copyStream(context.Writer, &idleErrorReader{}, test.protocol, nil) + _, err := copyStreamWithFallbackModel(context.Writer, &idleErrorReader{}, test.protocol, nil, "grok-test") if !errors.Is(err, errUpstreamStreamRead) || !errors.Is(err, neterror.ErrUpstreamStreamIdleTimeout) { t.Fatalf("copy error = %v", err) } @@ -1046,7 +1067,7 @@ func TestCopyStreamFlushesUnterminatedResponsesTailBeforeAbort(t *testing.T) { t.Fatalf("copy error = %v", err) } got := recorder.Body.String() - if !strings.Contains(got, `"delta":"partial"`) || !strings.Contains(got, "\n\nevent: response.incomplete") { + if !strings.Contains(got, `"delta":"partial"`) || !strings.Contains(got, "\n\nevent: response.failed") { t.Fatalf("unterminated tail and abort event were not separated: %q", got) } if marked != 1 { @@ -1070,7 +1091,7 @@ func TestCopyStreamDropsMalformedResponsesTailBeforeAbort(t *testing.T) { if strings.Contains(got, string(malformed)) { t.Fatalf("malformed tail leaked before terminal event: %q", got) } - if !strings.Contains(got, `"type":"response.incomplete"`) { + if !strings.Contains(got, `"type":"response.failed"`) { t.Fatalf("abort event missing after malformed tail: %q", got) } } @@ -1094,25 +1115,87 @@ func TestCopyStreamWritesTerminalOnIncompleteEOF(t *testing.T) { gin.SetMode(gin.TestMode) recorder := httptest.NewRecorder() context, _ := gin.CreateTestContext(recorder) - _, err := copyStream(context.Writer, strings.NewReader(""), streamProtocolResponses, nil) + _, err := copyStreamWithFallbackModel(context.Writer, strings.NewReader(""), streamProtocolResponses, nil, "grok-test") if !errors.Is(err, errUpstreamStreamIncomplete) { t.Fatalf("copy error = %v", err) } got := recorder.Body.String() - if !strings.Contains(got, `"type":"response.incomplete"`) || !strings.Contains(got, `"reason":"upstream_stream_incomplete"`) { + if !strings.Contains(got, `"type":"response.failed"`) || !strings.Contains(got, `"code":"server_error"`) || !strings.Contains(got, `"message":"upstream_stream_incomplete:`) || !strings.Contains(got, `"model":"grok-test"`) { t.Fatalf("incomplete EOF missing terminal SSE event: %q", got) } } func TestSanitizeResponsesFillsMissingIDs(t *testing.T) { - state := &responsesCompatState{} + state := &responsesCompatState{model: "grok-test"} got := rewriteResponsesDataLine([]byte(`data: {"type":"response.output_item.added","item":{"type":"reasoning"}}`+"\n"), state) if !bytes.Contains(got, []byte(`"id":"item_1"`)) { t.Fatalf("item id not filled: %s", got) } got = rewriteResponsesDataLine([]byte(`data: {"type":"response.created","response":{"status":"in_progress"}}`+"\n"), state) - if !bytes.Contains(got, []byte(`"id":"resp_abort"`)) || !bytes.Contains(got, []byte(`"created_at":`)) { - t.Fatalf("response id/created_at not filled: %s", got) + if !bytes.Contains(got, []byte(`"id":"resp_abort"`)) || !bytes.Contains(got, []byte(`"created_at":`)) || !bytes.Contains(got, []byte(`"model":"grok-test"`)) { + t.Fatalf("response id/created_at/model not filled: %s", got) + } +} + +func TestCopyStreamAbortTrailerAlwaysIncludesModel(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + context, _ := gin.CreateTestContext(recorder) + _, err := copyStreamWithFallbackModel(context.Writer, &idleErrorReader{}, streamProtocolResponses, nil, "grok-test") + if !errors.Is(err, errUpstreamStreamRead) { + t.Fatalf("copy error = %v", err) + } + got := recorder.Body.String() + if !strings.Contains(got, `"type":"response.failed"`) || !strings.Contains(got, `"model":"grok-test"`) { + t.Fatalf("abort trailer missing model: %q", got) + } +} + +func TestCopyStreamAbortTrailerPrefersUpstreamModel(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + context, _ := gin.CreateTestContext(recorder) + body := []byte(`data: {"type":"response.created","response":{"id":"resp_real","model":"upstream-model","status":"in_progress"}}` + "\n\n") + _, err := copyStreamWithFallbackModel(context.Writer, &chunkErrorReader{data: body}, streamProtocolResponses, nil, "request-model") + if !errors.Is(err, errUpstreamStreamRead) { + t.Fatalf("copy error = %v", err) + } + got := recorder.Body.String() + failedAt := strings.LastIndex(got, "event: response.failed") + if failedAt < 0 { + t.Fatalf("abort trailer missing: %q", got) + } + failed := got[failedAt:] + if !strings.Contains(failed, `"model":"upstream-model"`) || strings.Contains(failed, `"model":"request-model"`) { + t.Fatalf("abort trailer did not prefer upstream model: %q", failed) + } +} + +func TestResponsesAbortTrailerUsesStandardErrorShape(t *testing.T) { + trailer := streamAbortTrailer( + streamProtocolResponses, + neterror.ErrUpstreamStreamIdleTimeout, + responseMetadata{}, + &responsesCompatState{model: "grok-test"}, + ) + dataAt := bytes.Index(trailer, []byte("data: ")) + if dataAt < 0 { + t.Fatalf("abort trailer missing data line: %q", trailer) + } + payload := bytes.TrimSpace(trailer[dataAt+len("data: "):]) + var event struct { + Response struct { + Error map[string]any `json:"error"` + } `json:"response"` + } + if err := json.Unmarshal(payload, &event); err != nil { + t.Fatalf("decode abort trailer: %v; payload=%q", err, payload) + } + if event.Response.Error["code"] != "server_error" || !strings.Contains(stringAny(event.Response.Error["message"]), "upstream_stream_idle_timeout") { + t.Fatalf("unexpected Responses error: %#v", event.Response.Error) + } + if _, exists := event.Response.Error["type"]; exists { + t.Fatalf("Responses error contains non-protocol type: %#v", event.Response.Error) } } @@ -1166,6 +1249,26 @@ func TestSanitizeResponsesDoesNotAddResponseIDToErrorEvent(t *testing.T) { } } +func TestSanitizeResponsesFillsMissingOutputTextAnnotations(t *testing.T) { + state := &responsesCompatState{} + added := rewriteResponsesDataLine([]byte(`data: {"type":"response.output_item.added","item":{"type":"message","content":[{"type":"output_text","text":"hi"}]}}`+"\n"), state) + if !bytes.Contains(added, []byte(`"annotations":[]`)) { + t.Fatalf("item output_text missing annotations: %s", added) + } + completed := rewriteResponsesDataLine([]byte(`data: {"type":"response.completed","response":{"id":"resp_1","output":[{"type":"message","content":[{"type":"output_text","text":"hi"}]}]}}`+"\n"), state) + if !bytes.Contains(completed, []byte(`"annotations":[]`)) { + t.Fatalf("completed output_text missing annotations: %s", completed) + } + part := rewriteResponsesDataLine([]byte(`data: {"type":"response.content_part.added","part":{"type":"output_text","text":"hi"}}`+"\n"), state) + if !bytes.Contains(part, []byte(`"annotations":[]`)) { + t.Fatalf("content_part output_text missing annotations: %s", part) + } + kept := rewriteResponsesDataLine([]byte(`data: {"type":"response.output_item.done","item":{"type":"message","content":[{"type":"output_text","text":"hi","annotations":[{"type":"url_citation","url":"https://x.test"}]}]}}`+"\n"), state) + if !bytes.Contains(kept, []byte(`"url":"https://x.test"`)) || bytes.Contains(kept, []byte(`"annotations":[]`)) { + t.Fatalf("existing annotations were replaced: %s", kept) + } +} + func TestResponsesCompatBoundsUnterminatedLineBuffer(t *testing.T) { state := &responsesCompatState{} chunk := bytes.Repeat([]byte{'x'}, maxStreamEventInspectionBytes+1) diff --git a/backend/internal/transport/http/inference/responses_compat.go b/backend/internal/transport/http/inference/responses_compat.go index 4926d54b..e82cfb2c 100644 --- a/backend/internal/transport/http/inference/responses_compat.go +++ b/backend/internal/transport/http/inference/responses_compat.go @@ -12,6 +12,7 @@ import ( type responsesCompatState struct { responseID string createdAt int64 + model string itemSeq int itemIDs map[int64]string usedItemIDs map[string]struct{} @@ -102,6 +103,9 @@ func (s *responsesCompatState) rememberFromMeta(meta responseMetadata) { if id := strings.TrimSpace(meta.ResponseID); id != "" { s.responseID = id } + if model := strings.TrimSpace(meta.Model); model != "" { + s.model = model + } s.ensureID() } @@ -173,6 +177,13 @@ func sanitizeResponsesEvent(event map[string]any, state *responsesCompatState) b resp["output"] = []any{} changed = true } + if model := strings.TrimSpace(stringAny(resp["model"])); model != "" { + state.model = model + } else { + // Grok TUI serde requires `model` on response.failed / completed. + resp["model"] = state.model + changed = true + } if errObj, ok := resp["error"].(map[string]any); ok && strings.TrimSpace(stringAny(errObj["id"])) == "" { errObj["id"] = "err_" + strings.TrimPrefix(state.ensureID(), "resp_") changed = true @@ -221,6 +232,35 @@ func sanitizeResponsesEvent(event map[string]any, state *responsesCompatState) b } } } + if ensureOutputTextAnnotations(event) { + changed = true + } + return changed +} + +// Grok CLI serde requires output_text.annotations even when there are no +// citations. Missing the field makes a retry fail with +// "serialization error: missing field `annotations`". +func ensureOutputTextAnnotations(node any) bool { + changed := false + switch typed := node.(type) { + case map[string]any: + if stringAny(typed["type"]) == "output_text" && typed["annotations"] == nil { + typed["annotations"] = []any{} + changed = true + } + for _, key := range []string{"item", "part", "response", "content", "output", "delta"} { + if ensureOutputTextAnnotations(typed[key]) { + changed = true + } + } + case []any: + for _, child := range typed { + if ensureOutputTextAnnotations(child) { + changed = true + } + } + } return changed } diff --git a/config.example.yaml b/config.example.yaml index be69a127..52cc1765 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -159,3 +159,7 @@ qualityGuard: # First missing-thinking hit cools the account; a later hit after the # cooldown expires disables it. accountCooldown: 24h + # Empty SSE / idle-timeout penalty. Independent of accountCooldown. + # Single-account pools should set this lower; toggling enabled does not + # clear cooldown — use POST /api/admin/v1/accounts/:id/clear-cooldown. + idleAccountCooldown: 24h diff --git a/frontend/src/features/accounts/accounts-api.ts b/frontend/src/features/accounts/accounts-api.ts index 5e25d3a6..02cb10e3 100644 --- a/frontend/src/features/accounts/accounts-api.ts +++ b/frontend/src/features/accounts/accounts-api.ts @@ -102,6 +102,7 @@ export type AccountDTO = { failureCount: number; cooldownUntil?: string; lastError?: string; + enabledDoesNotClearCooldown?: boolean; lastUsedAt?: string; linkedAccountId?: string; linkedAccountName?: string; @@ -123,7 +124,7 @@ export type LinkedAccountDTO = { export type AccountUpdateInput = { name: string; - enabled: boolean; + enabled?: boolean; priority: number; maxConcurrent: number; minimumRemaining: number; @@ -193,6 +194,7 @@ const accountValidator = hasShape({ egressNodeId: isOptional(isString), egressAssignmentMode: isOptional(isOneOf("manual", "auto")), lastRefreshErrorStatus: isOptional(isNumber), lastRefreshErrorCode: isOptional(isString), lastRefreshErrorMessage: isOptional(isString), lastRefreshErrorResponse: isOptional(isString), priority: isNumber, maxConcurrent: isNumber, minimumRemaining: isNumber, failureCount: isNumber, cooldownUntil: isOptional(isString), lastError: isOptional(isString), lastUsedAt: isOptional(isString), + enabledDoesNotClearCooldown: isOptional(isBoolean), linkedAccountId: isOptional(isString), linkedAccountName: isOptional(isString), linkedProvider: isOptional(isOneOf("grok_build", "grok_web")), linkedAccounts: isOptional(isArrayOf(linkedAccountValidator)), createdAt: isString, billing: isOptional(billingValidator), quota: quotaValidator, quotaWindows: isOptional(isArrayOf(quotaWindowValidator)), }); @@ -309,6 +311,10 @@ export function refreshAccountToken(id: string): Promise { return apiRequest(`/api/admin/v1/accounts/${id}/refresh-token`, { method: "POST" }, decodeAccount); } +export function clearAccountCooldown(id: string): Promise { + return apiRequest(`/api/admin/v1/accounts/${id}/clear-cooldown`, { method: "POST" }, decodeAccount); +} + export function acceptWebAccountTerms(id: string): Promise<{ completed: boolean }> { return apiRequest(`/api/admin/v1/accounts/web/${id}/accept-terms`, { method: "POST" }, decodeBooleanResult<{ completed: boolean }>("completed")); } diff --git a/frontend/src/features/accounts/accounts-page.tsx b/frontend/src/features/accounts/accounts-page.tsx index e0c4185f..7d1ef40b 100644 --- a/frontend/src/features/accounts/accounts-page.tsx +++ b/frontend/src/features/accounts/accounts-page.tsx @@ -1,6 +1,6 @@ import { zodResolver } from "@hookform/resolvers/zod"; import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { ArrowRight, ClipboardPaste, Compass, Download, ExternalLink, FileUp, Link, MoreHorizontal, Pencil, Plus, RefreshCw, RotateCw, Search, SquareTerminal, Trash2, TriangleAlert, Webhook } from "lucide-react"; +import { ArrowRight, ClipboardPaste, Compass, Download, ExternalLink, FileUp, Link, MoreHorizontal, Pencil, Plus, RefreshCw, RotateCw, Search, SquareTerminal, TimerOff, Trash2, TriangleAlert, Webhook } from "lucide-react"; import { useCallback, useEffect, useRef, useState, type ReactNode } from "react"; import { useForm, useWatch } from "react-hook-form"; import { useTranslation } from "react-i18next"; @@ -37,6 +37,7 @@ import { nextTableSort, type SortOrder, type TableSort } from "@/shared/lib/tabl import { acceptWebAccountTerms, cleanupAccounts, + clearAccountCooldown, deleteAccount, deleteAccounts, previewAccountDeletion, @@ -324,11 +325,11 @@ export function AccountsPage() { if (!editing) throw new Error(t("errors.generic")); const input: AccountUpdateInput = { name: values.name, - enabled: values.enabled, priority: values.priority, maxConcurrent: values.maxConcurrent, minimumRemaining: values.minimumRemaining, }; + if (values.enabled !== editing.enabled) input.enabled = values.enabled; if (editing.provider !== "grok_build") { if (values.clearCloudflareCookies) input.clearCloudflareCookies = true; else if (values.cloudflareCookies.trim()) input.cloudflareCookies = values.cloudflareCookies; @@ -344,6 +345,7 @@ export function AccountsPage() { if (entitlementChanged) void queryClient.invalidateQueries({ queryKey: ["models"] }); setEditing(null); if (account.modelSyncFailed) toast.warning(t("accounts.updatedWithModelSyncFailure")); + else if (account.enabledDoesNotClearCooldown) toast.warning(t("accounts.enabledDoesNotClearCooldown")); else toast.success(t("accounts.updated")); }, onError: showError, @@ -507,6 +509,15 @@ export function AccountsPage() { onError: showError, }); + const clearCooldownMutation = useMutation({ + mutationFn: clearAccountCooldown, + onSuccess: () => { + invalidateAccountData(); + toast.success(t("accounts.cooldownCleared")); + }, + onError: showError, + }); + const quotaMutation = useMutation({ mutationFn: refreshAccountQuota, onSuccess: () => { @@ -1512,6 +1523,11 @@ export function AccountsPage() { /> ) : null} {provider === "grok_build" ? tokenMutation.mutate(account.id)}>{t("accounts.refreshToken")} : null} + {account.cooldownUntil && new Date(account.cooldownUntil) > new Date() ? ( + clearCooldownMutation.mutate(account.id)} disabled={clearCooldownMutation.isPending}> + {t("accounts.clearCooldown")} + + ) : null} provider === "grok_build" ? billingMutation.mutate(account.id) : quotaMutation.mutate(account.id)}>{provider === "grok_build" ? t("accounts.refreshBilling") : t("accounts.refreshModeQuota")} { resetLinkedDeleteState(); setDeleting(account); }}>{t("common.delete")} diff --git a/frontend/src/features/quality-guard/quality-guard-api.ts b/frontend/src/features/quality-guard/quality-guard-api.ts index 39a49b4b..3c7aa9db 100644 --- a/frontend/src/features/quality-guard/quality-guard-api.ts +++ b/frontend/src/features/quality-guard/quality-guard-api.ts @@ -14,6 +14,9 @@ export type QualityGuardPolicy = { }; export type QualityGuardNodeState = { + observe_only?: boolean; + observe_only_reason?: string; + quarantined_lease_count?: number; active_soft_strikes: number; passive_soft_strikes: number; error_strikes: number; @@ -35,9 +38,12 @@ export type QualityGuardEvent = { event: string; node_id: string; node_name: string; + account_id?: string; + request_id?: string; reason: string; classification: string; output_tps: number; + cooldown_until?: number; }; export type QualityGuardDetectionStats = { @@ -122,6 +128,7 @@ export type QualityTestResult = { }; const nodeStateValidator = hasShape({ + observe_only: isOptional(isBoolean), observe_only_reason: isOptional(isString), quarantined_lease_count: isOptional(isNumber), active_soft_strikes: isNumber, passive_soft_strikes: isNumber, error_strikes: isNumber, quarantined_until: isNumber, disabled_by_guard: isBoolean, last_reason: isString, last_probe_at: isNumber, last_observed_at: isNumber, last_source: isString, @@ -130,7 +137,9 @@ const nodeStateValidator = hasShape({ }); const eventValidator = hasShape({ ts: isNumber, event: isString, node_id: isString, node_name: isString, + account_id: isOptional(isString), request_id: isOptional(isString), reason: isString, classification: isString, output_tps: isNumber, + cooldown_until: isOptional(isNumber), }); const configValidator = hasShape({ mode: isOneOf("active", "passive", "hybrid"), model: isString, diff --git a/frontend/src/features/quality-guard/quality-guard-page.tsx b/frontend/src/features/quality-guard/quality-guard-page.tsx index a754e13f..84d61053 100644 --- a/frontend/src/features/quality-guard/quality-guard-page.tsx +++ b/frontend/src/features/quality-guard/quality-guard-page.tsx @@ -147,6 +147,7 @@ export function QualityGuardPage() { const fresh = isFresh(status); const guardedNodes = status?.nodes ?? {}; const quarantined = Object.values(guardedNodes).filter((node) => node.disabled_by_guard).length; + const quarantinedLeases = Object.values(guardedNodes).reduce((total, node) => total + (node.quarantined_lease_count ?? 0), 0); const enabled = nodes.filter((node) => node.enabled).length; return ( @@ -186,7 +187,7 @@ export function QualityGuardPage() { - + {status.statistics ? : null} @@ -261,7 +262,7 @@ function StatisticsPanel({ statistics, locale }: { statistics: QualityGuardStati { icon: Eye, label: t("qualityGuard.statisticsPassive"), value: formatCount(statistics.passive.total, locale), detail: t("qualityGuard.statisticsPassiveDetail", { healthy: formatCount(statistics.passive.healthy, locale) }) }, { icon: Coins, label: t("qualityGuard.statisticsTokens"), value: formatCount(statistics.active.output_tokens, locale), detail: t("qualityGuard.statisticsTokensHelp") }, { icon: AlertTriangle, label: t("qualityGuard.statisticsAnomalies"), value: formatCount(anomalies, locale), detail: t("qualityGuard.statisticsAnomalyDetail", { soft: formatCount(statistics.active.soft + statistics.passive.soft, locale), hard: formatCount(statistics.active.hard + statistics.passive.hard, locale) }) }, - { icon: Shield, label: t("qualityGuard.statisticsQuarantines"), value: formatCount(statistics.actions.quarantined, locale), detail: t("qualityGuard.statisticsActionDetail", { restored: formatCount(statistics.actions.restored, locale), suppressed: formatCount(statistics.actions.suppressed, locale) }) }, + { icon: Shield, label: t("qualityGuard.statisticsQuarantines"), value: formatCount(statistics.actions.quarantined, locale), detail: t("qualityGuard.statisticsSuppressedActionDetail", { restored: formatCount(statistics.actions.restored, locale), suppressed: formatCount(statistics.actions.suppressed, locale) }) }, ]; return
@@ -377,6 +378,9 @@ function StateBadge({ node, state, protectedNode }: { node: EgressNodeDTO; state if (state?.disabled_by_guard) return {t("qualityGuard.quarantined")}; if (protectedNode) return {t("qualityGuard.fixedFallback")}; if (!node.enabled) return {t("common.disabled")}; + if (state?.quarantined_lease_count) return {t("qualityGuard.leaseQuarantined", { count: state.quarantined_lease_count })}; + if (state?.observe_only) return {t("qualityGuard.leaseScopedObserveOnly")}; + if (node.accountBoundProxy) return {t("qualityGuard.leaseScoped")}; if (state?.error_strikes) return {t("qualityGuard.probeFailed")}; if (state?.last_classification === "hard" || state?.last_classification === "soft") return {t("qualityGuard.suspect")}; if (state?.last_classification === "healthy") return {t("qualityGuard.healthy")}; @@ -389,13 +393,29 @@ function EventList({ events, locale }: { events: QualityGuardEvent[]; locale: st

{t("qualityGuard.events")}

{events.length === 0 ?

{t("qualityGuard.noEvents")}

:
{[...events].reverse().slice(0, 10).map((event, index) =>
-

{event.node_name || `ID ${event.node_id}`} · {t(`qualityGuard.eventTypes.${event.event}`)}

{t(`qualityGuard.reasons.${event.reason || "unknown"}`)}{event.output_tps ? ` · ${formatTPS(event.output_tps)}` : ""}

+

{event.node_name || `ID ${event.node_id}`} · {t(eventLabelKey(event.event))}

{t(reasonLabelKey(event.reason))}{event.account_id ? ` · ${t("qualityGuard.accountLease", { id: event.account_id })}` : ""}{event.request_id ? ` · ${event.request_id}` : ""}{event.cooldown_until ? ` · ${t("qualityGuard.leaseUntil", { time: formatTime(event.cooldown_until, locale) })}` : ""}{event.output_tps ? ` · ${formatTPS(event.output_tps)}` : ""}

)}
}
; } +function eventLabelKey(event: string): string { + if (event === "lease_scoped_quarantine_suppressed") return "qualityGuard.leaseScopedQuarantineSuppressedEvent"; + if (event === "lease_scoped_guard_released") return "qualityGuard.leaseScopedGuardReleasedEvent"; + if (event === "lease_quarantined") return "qualityGuard.leaseQuarantinedEvent"; + if (event === "lease_restored") return "qualityGuard.leaseRestoredEvent"; + if (event === "lease_quarantine_extended") return "qualityGuard.leaseQuarantineExtendedEvent"; + if (event === "lease_quarantine_failed" || event === "lease_quarantine_suppressed") return "qualityGuard.leaseQuarantineFailedEvent"; + return `qualityGuard.eventTypes.${event}`; +} + +function reasonLabelKey(reason: string): string { + if (reason === "lease_scoped_node") return "qualityGuard.leaseScopedNodeReason"; + if (reason === "fixed_fallback_node") return "qualityGuard.fixedFallback"; + return `qualityGuard.reasons.${reason || "unknown"}`; +} + function Policy({ status, onEdit }: { status: QualityGuardStatus; onEdit: () => void }) { const { t } = useTranslation(); const config = status.config; @@ -535,6 +555,7 @@ function qualityTestState(result: QualityTestResult, status: QualityGuardStatus) else if (result.outputTokensPerSecond >= softTPS) { classification = "soft"; reason = "soft_tps"; } const now = Date.now() / 1000; return { + observe_only: false, observe_only_reason: "", quarantined_lease_count: 0, active_soft_strikes: classification === "soft" ? 1 : classification === "hard" ? (status.config?.consecutive_soft ?? 2) : 0, passive_soft_strikes: 0, error_strikes: 0, quarantined_until: 0, disabled_by_guard: false, last_reason: reason, last_probe_at: now, last_observed_at: now, last_source: "active", diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index ae7bad1d..c12eadba 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -471,17 +471,32 @@ const resources = { }, qualityGuard: { title: "质量守护", description: "监测 Grok 出口质量并在异常时自动隔离节点。", overview: "质量守护概览", - serviceStatus: "守护服务", running: "运行正常", stale: "状态滞后", mode: "检测模式", availableNodes: "已启用节点", quarantinedNodes: "已隔离节点", + serviceStatus: "守护服务", running: "运行正常", stale: "状态滞后", mode: "检测模式", availableNodes: "已启用节点", quarantinedNodes: "已隔离节点", quarantinedTargets: "隔离对象", modes: { active: "主动检测", passive: "被动审计", hybrid: "混合模式" }, nodes: "节点质量", nodesHelp: "速度与 grok2api 面板同口径:输出 Token 包含推理 Token。首字后窗口短于首字等待且不足 1 秒时改用全程,避免加密思考被挤进最后几十毫秒。完整用户请求出现速度异常后会立即隔离,并在隔离期结束后使用受控探针复测。", updatedAt: "状态更新于 {{time}}", node: "节点", state: "状态", outputTPS: "面板输出速度", firstToken: "首字延迟", source: "数据来源", strikes: "打击计数", lastObserved: "最近观测", test: "检测", sources: { active: "主动探针", passive: "请求审计" }, quarantined: "已隔离", fixedFallback: "固定回退(受保护)", suspect: "可疑", healthy: "正常", pending: "待观测", probeFailed: "检测失败", - events: "最近事件", noEvents: "暂无异常或恢复事件", eventTypes: { node_quarantined: "节点已隔离", node_restored: "节点已恢复", node_rotated: "节点已更换 IP", passive_audit_anomaly: "检测到异常请求" }, + events: "最近事件", noEvents: "暂无异常或恢复事件", eventTypes: { node_quarantined: "节点已隔离", node_restored: "节点已恢复", node_rotated: "节点已更换 IP", passive_audit_anomaly: "检测到异常请求", lease_quarantined: "账号租约已隔离", lease_restored: "账号租约已恢复", lease_quarantine_extended: "账号租约隔离已延长", lease_quarantine_failed: "账号租约隔离未执行" }, statistics: "自动检测统计", statisticsSince: "自 {{time}} 开始累计,不含手动检测。", statisticsChecks: "有效检测总数", statisticsChecksHelp: "主动探测与有效被动审计", statisticsActive: "主动探测", statisticsActiveDetail: "正常 {{healthy}},错误 {{errors}}", statisticsPassive: "被动审计", statisticsPassiveDetail: "正常 {{healthy}},来自真实请求", statisticsTokens: "主动探测输出 Token", statisticsTokensHelp: "包含推理 Token,不代表代理流量", statisticsAnomalies: "异常命中", statisticsAnomalyDetail: "软异常 {{soft}},硬异常 {{hard}}", statisticsQuarantines: "执行隔离", statisticsActionDetail: "已恢复 {{restored}},受保护未隔离 {{suppressed}}", reasons: { unknown: "未记录原因", hard_tps: "超过硬阈值", soft_tps: "超过软阈值", buffered_burst: "短窗口输出突增,等待原 IP 复测", missing_thinking: "输出缺少 thinking", passive_hard_tps: "请求速度超过硬阈值", passive_soft_tps: "请求速度超过软阈值", quality_probe_healthy: "模型质量检测恢复正常", expected_marker_missing: "响应标记缺失", insufficient_output_tokens: "输出 Token 不足", insufficient_visible_tokens: "可见 Token 不足", insufficient_generation_window: "有效生成窗口不足", probe_errors: "主动检测连续失败", probe_no_account: "暂无可调度账号,已延后复测", recovery_probe_error: "恢复检测失败", rotation_error: "更换 IP 失败" }, policy: "当前策略", editPolicy: "编辑策略", editPolicyTitle: "编辑质量守护策略", editPolicyDescription: "保存后由守护进程热加载,无需重启服务。", restoreDefaults: "恢复默认值", policySaved: "策略已保存,正在热加载", invalidPolicyValue: "数值超出允许范围", softThresholdMustBeLower: "软阈值必须低于硬阈值", activeIntervalSeconds: "主动检测间隔(秒)", passiveIntervalSeconds: "被动审计间隔(秒)", consecutiveSoft: "主动软异常连续次数", consecutiveErrors: "检测错误连续次数", quarantineSeconds: "隔离时长(秒)", softThreshold: "软阈值", hardThreshold: "硬阈值", activeInterval: "主动间隔", passiveInterval: "审计间隔", quarantineDuration: "隔离时长", minimumNodes: "最少保留节点", unavailable: "质量守护尚未连接", unavailableHelp: "在 config.yaml 中启用 qualityGuard,并启动 quality-guard Compose profile 后,这里会显示实时状态。", testing: "正在检测节点质量", testComplete: "检测完成:{{speed}}", testFailed: "质量检测暂不可用,请稍后重试", nodesTab: "节点质量", + leaseScopedObserveOnly: "租约级(仅观测)", + leaseScoped: "租约级", + leaseQuarantined: "租约隔离 {{count}}", + leaseScopedHelp: "该节点按账号生成不同粘性租约;异常请求只隔离对应账号租约,不会停用整个共享节点。", + leaseScopedObserveOnlyHelp: "当前异常缺少账号身份或租约接口不可用,因此仅记录观测,不会停用整个共享节点。", + leaseQuarantinedEvent: "账号租约已隔离", + leaseRestoredEvent: "账号租约已恢复", + leaseQuarantineExtendedEvent: "账号租约隔离已延长", + leaseQuarantineFailedEvent: "账号租约隔离未执行", + leaseScopedQuarantineSuppressedEvent: "已阻止整节点隔离", + leaseScopedGuardReleasedEvent: "已解除旧版整节点隔离", + leaseScopedNodeReason: "节点包含多个账号粘性租约", + accountLease: "账号 {{id}}", + leaseUntil: "隔离至 {{time}}", + statisticsSuppressedActionDetail: "已恢复 {{restored}},策略抑制 {{suppressed}}", profilesTab: "探针方案", profilesHelp: "主动质量探测用的 Prompt 与预期标记。标记缺失记为硬异常。", profileActive: "当前使用", @@ -1604,6 +1619,22 @@ const resources = { shell: { appearance: "Appearance", dark: "Dark", light: "Light", system: "System", language: "Language", navigation: "Navigation", openNavigation: "Open navigation" }, qualityGuard: { title: "Quality guard", description: "Monitor Grok egress quality and quarantine anomalous nodes automatically.", overview: "Quality guard overview", serviceStatus: "Guard service", running: "Running", stale: "Status stale", mode: "Detection mode", availableNodes: "Enabled nodes", quarantinedNodes: "Quarantined", modes: { active: "Active probes", passive: "Passive audits", hybrid: "Hybrid" }, nodes: "Node quality", nodesHelp: "Speed matches the grok2api panel: output tokens include reasoning tokens. A tail shorter than the first-token wait and under 1s uses the full request duration so encrypted thinking is not crushed into the flush. A completed user request with anomalous throughput is isolated immediately, then verified with a controlled probe after the hold.", updatedAt: "Updated {{time}}", node: "Node", state: "State", outputTPS: "Panel output speed", firstToken: "First token", source: "Source", strikes: "Strikes", lastObserved: "Last observed", test: "Test", sources: { active: "Active probe", passive: "Request audit" }, quarantined: "Quarantined", fixedFallback: "Fixed fallback (protected)", suspect: "Suspect", healthy: "Healthy", pending: "Pending", probeFailed: "Probe failed", events: "Recent events", noEvents: "No anomaly or recovery events", eventTypes: { node_quarantined: "Node quarantined", node_restored: "Node restored", node_rotated: "Node IP rotated", passive_audit_anomaly: "Anomalous request detected" }, statistics: "Automatic detection statistics", statisticsSince: "Accumulated since {{time}}. Manual tests are excluded.", statisticsChecks: "Valid checks", statisticsChecksHelp: "Active probes and valid passive audits", statisticsActive: "Active probes", statisticsActiveDetail: "Healthy {{healthy}}, errors {{errors}}", statisticsPassive: "Passive audits", statisticsPassiveDetail: "Healthy {{healthy}}, from real requests", statisticsTokens: "Active output tokens", statisticsTokensHelp: "Includes reasoning tokens; not proxy traffic", statisticsAnomalies: "Anomaly hits", statisticsAnomalyDetail: "Soft {{soft}}, hard {{hard}}", statisticsQuarantines: "Quarantines applied", statisticsActionDetail: "Restored {{restored}}, protected {{suppressed}}", reasons: { unknown: "No reason recorded", hard_tps: "Hard threshold exceeded", soft_tps: "Soft threshold exceeded", buffered_burst: "Short-window output burst; retesting the same IP", missing_thinking: "Missing thinking tokens", passive_hard_tps: "Request exceeded hard threshold", passive_soft_tps: "Request exceeded soft threshold", quality_probe_healthy: "Model quality probe recovered", expected_marker_missing: "Expected marker missing", insufficient_output_tokens: "Too few output tokens", insufficient_visible_tokens: "Too few visible tokens", insufficient_generation_window: "Generation window too short", probe_errors: "Repeated probe errors", probe_no_account: "No schedulable probe account; retry deferred", recovery_probe_error: "Recovery probe failed", rotation_error: "IP rotation failed" }, policy: "Current policy", editPolicy: "Edit policy", editPolicyTitle: "Edit quality guard policy", editPolicyDescription: "The guard hot-reloads saved changes without a service restart.", restoreDefaults: "Restore defaults", policySaved: "Policy saved and queued for hot reload", invalidPolicyValue: "Value is outside the allowed range", softThresholdMustBeLower: "The soft threshold must be lower than the hard threshold", activeIntervalSeconds: "Active interval (seconds)", passiveIntervalSeconds: "Passive interval (seconds)", consecutiveSoft: "Consecutive active soft strikes", consecutiveErrors: "Consecutive probe errors", quarantineSeconds: "Quarantine (seconds)", softThreshold: "Soft threshold", hardThreshold: "Hard threshold", activeInterval: "Active interval", passiveInterval: "Audit interval", quarantineDuration: "Quarantine", minimumNodes: "Minimum nodes", unavailable: "Quality guard is not connected", unavailableHelp: "Enable qualityGuard in config.yaml and start the quality-guard Compose profile to display live status here.", testing: "Testing node quality", testComplete: "Test complete: {{speed}}", testFailed: "Quality test is temporarily unavailable. Try again shortly.", refreshNodes: "Refresh nodes", nodeEnabled: "Node enabled", nodeDisabled: "Node disabled", nodesEnabled: "Selected nodes enabled", nodesDisabled: "Selected nodes disabled", enableNode: "Enable node {{name}}", disableNode: "Disable node {{name}}", nodeEditorDescription: "Manage Grok Build egress used by the quality guard. Proxy URLs are write-only; leave the field blank while editing to keep the current value.", nodeCapacityHelp: "Maximum number of bound accounts; 0 means unlimited.", deleteNodeTitle: "Delete proxy node?", deleteNodeDescription: "Node “{{name}}” will be permanently deleted. This action cannot be undone.", deleteNodesTitle: "Delete {{count}} selected nodes?", deleteNodesDescription: "The selected proxy nodes will be permanently deleted. This action cannot be undone.", nodesTab: "Node quality", + quarantinedTargets: "Quarantined targets", + leaseScopedObserveOnly: "Lease-scoped (observe only)", + leaseScoped: "Lease-scoped", + leaseQuarantined: "{{count}} lease quarantined", + leaseScopedHelp: "This node renders a different sticky lease per account. An anomalous request quarantines only that account lease, never the shared node.", + leaseScopedObserveOnlyHelp: "The anomaly lacks an account identity or the lease API is unavailable, so it is observed without disabling the shared node.", + leaseQuarantinedEvent: "Account lease quarantined", + leaseRestoredEvent: "Account lease restored", + leaseQuarantineExtendedEvent: "Account lease quarantine extended", + leaseQuarantineFailedEvent: "Account lease quarantine not applied", + leaseScopedQuarantineSuppressedEvent: "Whole-node quarantine prevented", + leaseScopedGuardReleasedEvent: "Legacy whole-node quarantine released", + leaseScopedNodeReason: "Node contains multiple account-specific sticky leases", + accountLease: "Account {{id}}", + leaseUntil: "Quarantined until {{time}}", + statisticsSuppressedActionDetail: "Restored {{restored}}, suppressed {{suppressed}}", profilesTab: "Probe profiles", profilesHelp: "Prompt and expected marker for active quality probes. A missing marker is a hard failure.", profileActive: "In use", @@ -2273,6 +2304,9 @@ Object.assign(resources["zh-CN"].translation.settings.egress as unknown as Recor }); Object.assign(resources["zh-CN"].translation.accounts as unknown as Record, { + clearCooldown: "解除冷却", + cooldownCleared: "账号冷却已清除,可重新调度", + enabledDoesNotClearCooldown: "已开关账号,但冷却状态未变。请用「解除冷却」清除 cooldownUntil。", importAuth: "导入账号或 RT 文件", quickImportRT: "快速导入 RT", quickImportRTTitle: "快速导入 Grok Build Refresh Token", quickImportRTDescription: "支持粘贴多个 xAI Refresh Token,或上传每行一个 RT 的 TXT 文件。导入时会先换取 access token,后续自动续期会沿用对应的 OAuth client ID。", refreshTokens: "Refresh Token(每行一个)", refreshTokenPlaceholder: "refresh_token_1\nrt=refresh_token_2\nrefresh_token=refresh_token_3", @@ -2285,6 +2319,9 @@ Object.assign(resources["zh-CN"].translation.accounts as unknown as Record, { + clearCooldown: "Clear cooldown", + cooldownCleared: "Account cooldown cleared; the account can be scheduled again", + enabledDoesNotClearCooldown: "Enabled state changed, but cooldown is unchanged. Use Clear cooldown to reset cooldownUntil.", importAuth: "Import accounts or RTs", quickImportRT: "Quick import RTs", quickImportRTTitle: "Quick import Grok Build refresh tokens", quickImportRTDescription: "Paste xAI refresh tokens or upload a TXT file with one RT per line. Import exchanges each RT for an access token, and later renewals retain its OAuth client ID.", refreshTokens: "Refresh tokens (one per line)", refreshTokenPlaceholder: "refresh_token_1\nrt=refresh_token_2\nrefresh_token=refresh_token_3", diff --git a/tools/egress-quality-guard/README.md b/tools/egress-quality-guard/README.md index 2b37b06c..7c5d254b 100644 --- a/tools/egress-quality-guard/README.md +++ b/tools/egress-quality-guard/README.md @@ -43,6 +43,20 @@ your own traffic before allowing automatic quarantine. records a generic connectivity probe for diagnosis, then uses the real model-quality probe as the authority before re-enabling the node. +Account-bound proxy templates such as Resin usernames containing `{account}` +render a distinct sticky lease for each account. Scheduled node probes remain +suppressed because one lease cannot represent its siblings. A passive anomaly +removes only the audited account lease; after the hold, recovery pins a probe to +that same account and node, renews an unhealthy hold, and clears the durable +marker only with a matching CAS version. Routing stops enforcing a hold after +its deadline, so a stopped sidecar cannot strand an account indefinitely. +Rebinding an account atomically removes its old marker. If identity or the lease +API is unavailable, the guard falls back to observation and never disables the +shared node. Rendered proxy usernames and credentials never cross the API. +Lease reconciliation uses opaque keyset pagination and scans the complete +durable set. Recovery probes are capped per cycle and retry with exponential +backoff, so a large expired queue cannot monopolize one guard cycle. + The public inference API cannot request a specific egress node or bypass a disabled node. This capability is confined to the authenticated internal route. Ambiguous probe-only 403 responses do not cool borrowed accounts; definitive @@ -112,6 +126,10 @@ probe prompt, or model response body. - Never deletes a node or changes account bindings. - Never restores a node disabled by an operator. +- Never applies whole-node quarantine to an account-bound `{account}` proxy. A + legacy quarantine still owned by the guard is released during reconciliation. +- Lease recovery is pinned to the same account and node and uses an opaque CAS + version so stale probes cannot clear a newer quarantine. - Refuses to quarantine below `qualityGuard.minimumHealthyNodes`. - Strict mode overrides that floor rather than scheduling an unverified exit. - Uses an exclusive process lock to prevent duplicate guards. diff --git a/tools/egress-quality-guard/README.zh-CN.md b/tools/egress-quality-guard/README.zh-CN.md index 6f4b07b1..2e8d2e23 100644 --- a/tools/egress-quality-guard/README.zh-CN.md +++ b/tools/egress-quality-guard/README.zh-CN.md @@ -23,6 +23,15 @@ Token/s,因此建议先观察 JSON 日志,再根据实际流量调整阈值 6. 隔离节点仍可接受管理员探测,但不会承载普通用户请求。 7. 冷却结束后记录一次通用连接探测用于诊断,再以真实模型质量探测作为恢复判据,账号绑定保持不变。 +Resin 用户名等代理模板包含 `{account}` 时,同一逻辑节点会按账号生成不同的粘性租约。 +这类节点不会执行无法代表全部租约的定时节点探测;被动审计出现异常时,后端只临时移出该 +审计关联的账号租约。冷却到期后,恢复探针固定使用同一账号与同一节点;异常会续期,健康时 +通过版本校验清理持久化标记。路由在隔离期限到期后不再强制摘流,避免 sidecar 停止时让孤儿 +状态永久卡住账号。账号换绑会原子清理旧标记;sidecar 或接口异常时只记录观测,绝不回退为 +整节点禁用。内部接口只传账号 ID、节点 ID 和随机版本号,不返回渲染后的 Resin 用户名或代理凭据。 +租约对账采用不透明游标完整分页;每轮恢复探针有固定上限,失败后按指数退避,避免大量到期租约 +长期占满单次守护循环。 + 普通 `/v1/*` 请求不能指定出口节点,也不能绕过节点禁用状态。 仅发生在质量探测中的模糊 403 不会冷却借用账号;明确的凭据失效、账号封禁和额度信号仍按原有规则处理。 @@ -70,6 +79,7 @@ Webhook,确认出口发生变化,再执行一次真实模型质量检测; - 不删除节点,不修改账号绑定。 - 不会恢复管理员手动禁用的节点。 +- 不会对账号绑定的 `{account}` 代理执行整节点隔离;升级前仍由守护程序持有的旧隔离会在状态对账时解除。 - 启用节点数低于 `qualityGuard.minimumHealthyNodes` 时拒绝继续隔离。 - 严格模式会覆盖最低健康节点保护:无法确认质量时宁可无可用节点,也不调度可疑出口。 - 使用进程锁防止重复运行。 diff --git a/tools/egress-quality-guard/quality_guard.py b/tools/egress-quality-guard/quality_guard.py index 584d10b6..0eb25be7 100755 --- a/tools/egress-quality-guard/quality_guard.py +++ b/tools/egress-quality-guard/quality_guard.py @@ -47,6 +47,11 @@ INTERNAL_API_PREFIX = "/api/internal/v1/quality-guard" QUALITY_MARKER_PROFILE_ID = "quality-marker" THROUGHPUT_PROFILE_ID = "throughput" THINKING_GUARD_MIN_OUTPUT_TOKENS = 64 +LEASE_PAGE_SIZE = 1000 +LEASE_SCAN_MAX_PAGES = 1000 +LEASE_RECOVERY_MAX_PER_CYCLE = 8 +LEASE_RECOVERY_BACKOFF_BASE_SECONDS = 30 +LEASE_RECOVERY_BACKOFF_MAX_SECONDS = 1800 class GuardDisabled(RuntimeError): @@ -321,8 +326,10 @@ class ApiClient: result.add(node_id) return result - def quality_test(self, node_id: str, profile_id: str = "") -> dict[str, Any]: + def quality_test(self, node_id: str, profile_id: str = "", account_id: str = "") -> dict[str, Any]: body = {"profileId": profile_id} if profile_id else {} + if account_id: + body["accountId"] = account_id return self._request("POST", f"{INTERNAL_API_PREFIX}/egress-nodes/{node_id}/quality-test", body or None) def connectivity_test(self, node_id: str) -> dict[str, Any]: @@ -342,6 +349,42 @@ class ApiClient: result = self._request("PATCH", f"{INTERNAL_API_PREFIX}/egress-nodes/batch", {"ids": [node_id], "enabled": enabled}) return int(result.get("updated") or 0) + def list_leases(self) -> list[dict[str, Any]]: + values: list[dict[str, Any]] = [] + cursor = "" + seen_cursors: set[str] = set() + for _page in range(LEASE_SCAN_MAX_PAGES): + query = {"limit": LEASE_PAGE_SIZE} + if cursor: + query["cursor"] = cursor + payload = self._request("GET", f"{INTERNAL_API_PREFIX}/egress-leases?{urllib.parse.urlencode(query)}") + items = list(payload.get("items") or []) + values.extend(items) + if not payload.get("hasMore"): + return values + next_cursor = str(payload.get("nextCursor") or "") + if not next_cursor or next_cursor == cursor or next_cursor in seen_cursors: + raise RuntimeError("lease pagination did not advance") + seen_cursors.add(next_cursor) + cursor = next_cursor + raise RuntimeError("lease pagination exceeded the safety limit") + + def quarantine_lease(self, node_id: str, account_id: str, reason: str) -> dict[str, Any]: + return self._request("POST", f"{INTERNAL_API_PREFIX}/egress-leases/quarantine", { + "nodeId": node_id, + "accountId": account_id, + "reason": reason, + "quarantineSeconds": self.config.quarantine_seconds, + }) + + def restore_lease(self, node_id: str, account_id: str, version: str) -> bool: + result = self._request("POST", f"{INTERNAL_API_PREFIX}/egress-leases/restore", { + "nodeId": node_id, + "accountId": account_id, + "version": version, + }) + return bool(result.get("restored")) + def rotate_node(self, node_id: str, old_exit_ip: str = "") -> dict[str, Any]: if not self.config.rotation_url: raise RuntimeError("rotation endpoint is not configured") @@ -517,6 +560,9 @@ def generation_window_ms(first_token_ms: int, duration_ms: int, reasoning_tokens def default_node_state() -> dict[str, Any]: return { + "observe_only": False, + "observe_only_reason": "", + "quarantined_lease_count": 0, "active_soft_strikes": 0, "passive_soft_strikes": 0, "error_strikes": 0, @@ -630,6 +676,8 @@ class Guard: self._resolved_node_ids = list(config.node_ids) self.state.setdefault("started_at", time.time()) self.state.setdefault("recent_events", []) + self.state.setdefault("leases", {}) + self.state.setdefault("lease_recovery", {}) ensure_statistics(self.state) self._update_guard_metadata() self._save() @@ -678,6 +726,11 @@ class Guard: current.setdefault(key, value) return current + @staticmethod + def _is_lease_scoped(node: dict[str, Any]) -> bool: + """Return whether one logical node expands to account-specific sticky leases.""" + return bool(node.get("accountBoundProxy")) + def _defer_no_account(self, state: dict[str, Any], node: dict[str, Any], now: float, event: str, **fields: Any) -> None: state["last_probe_at"] = now state["last_reason"] = "probe_no_account" @@ -732,9 +785,213 @@ class Guard: def _probe_account_unavailable(exc: Exception) -> bool: return isinstance(exc, ApiError) and exc.code == "egressQualityProbeNoAccount" + @staticmethod + def _lease_key(node_id: str, account_id: str) -> str: + return f"{node_id}:{account_id}" + + def _clear_lease_recovery(self, key: str) -> None: + self.state.setdefault("lease_recovery", {}).pop(key, None) + + def _defer_lease_recovery(self, key: str, now: float) -> None: + recovery = self.state.setdefault("lease_recovery", {}) + current = recovery.get(key) or {} + failures = min(16, int(current.get("failures") or 0) + 1) + delay = min(LEASE_RECOVERY_BACKOFF_MAX_SECONDS, LEASE_RECOVERY_BACKOFF_BASE_SECONDS * (2 ** (failures - 1))) + recovery[key] = {"failures": failures, "next_attempt_at": now + delay} + + def _quarantine_lease(self, node: dict[str, Any], audit_value: dict[str, Any], reason: str, now: float) -> None: + node_id = str(node.get("id") or "") + account_id = str(audit_value.get("accountId") or "") + state = self._state_for(node_id) + request_id = str(audit_value.get("requestId") or "") + if not account_id: + state.update({"observe_only": True, "observe_only_reason": "missing_account_identity", "last_reason": reason}) + self._bump_statistic("actions", "suppressed") + append_state_event(self.state, "lease_quarantine_suppressed", node_id=node_id, node_name=node.get("name"), reason=reason, request_id=request_id) + log_event("lease_quarantine_suppressed", node_id=node_id, node_name=node.get("name"), reason=reason, cause="missing_account_identity") + return + try: + lease = self.api.quarantine_lease(node_id, account_id, reason) + except Exception as exc: + state.update({"observe_only": True, "observe_only_reason": "lease_api_unavailable", "last_reason": reason}) + self._bump_statistic("actions", "suppressed") + append_state_event(self.state, "lease_quarantine_failed", node_id=node_id, node_name=node.get("name"), reason=reason, account_id=account_id, request_id=request_id) + log_event("lease_quarantine_failed", node_id=node_id, node_name=node.get("name"), reason=reason, error_type=type(exc).__name__) + return + key = self._lease_key(node_id, account_id) + leases = self.state.setdefault("leases", {}) + already_quarantined = key in leases + leases[key] = lease + self._clear_lease_recovery(key) + state.update({"observe_only": False, "observe_only_reason": "", "last_reason": reason}) + event = "lease_quarantine_extended" if already_quarantined else "lease_quarantined" + if not already_quarantined: + state["quarantined_lease_count"] = int(state.get("quarantined_lease_count", 0)) + 1 + self._bump_statistic("actions", "quarantined") + append_state_event(self.state, event, node_id=node_id, node_name=node.get("name"), reason=reason, account_id=account_id, request_id=request_id, cooldown_until=lease.get("cooldownUntil")) + self._save() + log_event(event, node_id=node_id, node_name=node.get("name"), reason=reason, account_id=account_id, cooldown_until=lease.get("cooldownUntil")) + + def _extend_lease(self, node: dict[str, Any], lease: dict[str, Any], reason: str) -> bool: + node_id = str(lease.get("nodeId") or node.get("id") or "") + account_id = str(lease.get("accountId") or "") + try: + replacement = self.api.quarantine_lease(node_id, account_id, reason) + except Exception as exc: + log_event("lease_quarantine_extension_failed", node_id=node_id, node_name=node.get("name"), reason=reason, error_type=type(exc).__name__) + return False + key = self._lease_key(node_id, account_id) + self.state.setdefault("leases", {})[key] = replacement + self._clear_lease_recovery(key) + append_state_event(self.state, "lease_quarantine_extended", node_id=node_id, node_name=node.get("name"), reason=reason, account_id=account_id, cooldown_until=replacement.get("cooldownUntil")) + log_event("lease_quarantine_extended", node_id=node_id, node_name=node.get("name"), reason=reason, account_id=account_id) + return True + + def _recover_lease(self, node: dict[str, Any], lease: dict[str, Any], now: float) -> None: + node_id = str(lease.get("nodeId") or "") + account_id = str(lease.get("accountId") or "") + version = str(lease.get("version") or "") + if not node_id or not account_id or not version: + return + key = self._lease_key(node_id, account_id) + profile_id, profile = resolve_probe_profile(self.config.profiles_file, QUALITY_MARKER_PROFILE_ID) + self._bump_statistic("active", "total") + try: + result = self.api.quality_test(node_id, profile_id, account_id) + classification, reason = classify_result(result, self.config, profile) + except Exception as exc: + self._bump_statistic("active", "errors") + if not self._extend_lease(node, lease, "recovery_probe_error"): + self._defer_lease_recovery(key, now) + log_event("lease_recovery_probe_failed", node_id=node_id, node_name=node.get("name"), account_id=account_id, error_type=type(exc).__name__) + return + self._record_probe(node, result, classification, reason, now) + if classification != "healthy": + if not self._extend_lease(node, lease, reason): + self._defer_lease_recovery(key, now) + return + try: + restored = self.api.restore_lease(node_id, account_id, version) + except ApiError as exc: + if exc.code == "qualityLeaseConflict": + self._clear_lease_recovery(key) + log_event("lease_restore_stale", node_id=node_id, node_name=node.get("name"), account_id=account_id) + return + self._defer_lease_recovery(key, now) + log_event("lease_restore_failed", node_id=node_id, node_name=node.get("name"), account_id=account_id, error_type=type(exc).__name__) + return + except Exception as exc: + self._defer_lease_recovery(key, now) + log_event("lease_restore_failed", node_id=node_id, node_name=node.get("name"), account_id=account_id, error_type=type(exc).__name__) + return + if not restored: + self._defer_lease_recovery(key, now) + return + self.state.setdefault("leases", {}).pop(key, None) + self._clear_lease_recovery(key) + node_state = self._state_for(node_id) + node_state["quarantined_lease_count"] = max(0, int(node_state.get("quarantined_lease_count", 0)) - 1) + self._bump_statistic("actions", "restored") + append_state_event(self.state, "lease_restored", node_id=node_id, node_name=node.get("name"), reason="quality_probe_healthy", account_id=account_id) + log_event("lease_restored", node_id=node_id, node_name=node.get("name"), account_id=account_id, reason="quality_probe_healthy") + + def _reconcile_leases(self, nodes: list[dict[str, Any]], now: float) -> bool: + node_by_id = {str(node.get("id") or ""): node for node in nodes} + try: + values = self.api.list_leases() + except Exception as exc: + log_event("lease_reconciliation_failed", error_type=type(exc).__name__) + return False + state_leases = self.state.setdefault("leases", {}) + recovery_state = self.state.setdefault("lease_recovery", {}) + backend_keys: set[str] = set() + due: list[tuple[dict[str, Any], dict[str, Any]]] = [] + for node in nodes: + if self._is_lease_scoped(node): + self._state_for(str(node["id"]))["quarantined_lease_count"] = 0 + for lease in values: + node_id = str(lease.get("nodeId") or "") + account_id = str(lease.get("accountId") or "") + if not node_id or not account_id: + continue + key = self._lease_key(node_id, account_id) + backend_keys.add(key) + state_leases[key] = lease + node = node_by_id.get(node_id) + if node is None or not self._is_lease_scoped(node): + continue + state = self._state_for(node_id) + state["observe_only"] = False + state["observe_only_reason"] = "" + state["quarantined_lease_count"] = int(state.get("quarantined_lease_count", 0)) + 1 + if now >= float(lease.get("cooldownUntil") or 0): + retry = recovery_state.get(key) or {} + if now >= float(retry.get("next_attempt_at") or 0): + due.append((node, lease)) + for key in list(state_leases): + if key not in backend_keys: + state_leases.pop(key, None) + recovery_state.pop(key, None) + for key in list(recovery_state): + if key not in backend_keys: + recovery_state.pop(key, None) + for node, lease in due[:LEASE_RECOVERY_MAX_PER_CYCLE]: + self._recover_lease(node, lease, now) + deferred = max(0, len(due) - LEASE_RECOVERY_MAX_PER_CYCLE) + if deferred: + log_event("lease_recovery_budget_exhausted", due=len(due), deferred=deferred, limit=LEASE_RECOVERY_MAX_PER_CYCLE) + return True + + def _release_protected_leases(self, protected_node_ids: set[str], nodes: list[dict[str, Any]]) -> None: + if not protected_node_ids: + return + node_by_id = {str(node.get("id") or ""): node for node in nodes} + state_leases = self.state.setdefault("leases", {}) + for key, lease in list(state_leases.items()): + node_id = str(lease.get("nodeId") or "") + if node_id not in protected_node_ids: + continue + account_id = str(lease.get("accountId") or "") + version = str(lease.get("version") or "") + try: + restored = self.api.restore_lease(node_id, account_id, version) + except Exception as exc: + log_event("protected_lease_release_failed", node_id=node_id, error_type=type(exc).__name__) + continue + if not restored: + continue + state_leases.pop(key, None) + node = node_by_id.get(node_id) or {} + state = self._state_for(node_id) + state["quarantined_lease_count"] = max(0, int(state.get("quarantined_lease_count", 0)) - 1) + self._bump_statistic("actions", "restored") + append_state_event(self.state, "lease_restored", node_id=node_id, node_name=node.get("name"), reason="fixed_fallback_node", account_id=account_id) + log_event("protected_lease_released", node_id=node_id, node_name=node.get("name"), account_id=account_id) + def _quarantine(self, nodes: list[dict[str, Any]], node: dict[str, Any], reason: str, now: float, recover_now: bool = True) -> None: node_id = str(node["id"]) state = self._state_for(node_id) + if self._is_lease_scoped(node): + state.update({ + "observe_only": True, + "observe_only_reason": "account_bound_proxy", + "last_reason": reason, + }) + self._bump_statistic("actions", "suppressed") + append_state_event( + self.state, + "lease_scoped_quarantine_suppressed", + node_id=node_id, + node_name=node.get("name"), + reason=reason, + ) + log_event( + "lease_scoped_quarantine_suppressed", + node_id=node_id, + node_name=node.get("name"), + reason=reason, + ) + return if not self._can_quarantine(nodes, node_id): self._bump_statistic("actions", "suppressed") log_event("quarantine_suppressed", node_id=node_id, node_name=node.get("name"), reason=reason, minimum_healthy=self.config.min_healthy_nodes) @@ -993,13 +1250,80 @@ class Guard: def _prepare_nodes(self, now: float) -> tuple[list[dict[str, Any]], list[dict[str, Any]], set[str]]: all_nodes = self.api.list_nodes() + lease_api_ready = self._reconcile_leases(all_nodes, now) protected_node_ids = self.api.fixed_fallback_node_ids() + if lease_api_ready: + self._release_protected_leases(protected_node_ids, all_nodes) previous_protected = set(str(value) for value in self.state.get("protected_node_ids", [])) if protected_node_ids != previous_protected: self.state["protected_node_ids"] = sorted(protected_node_ids) for node_id in sorted(protected_node_ids - previous_protected): log_event("fixed_fallback_node_skipped", node_id=node_id) state_nodes = self.state.setdefault("nodes", {}) + release_failed_ids: set[str] = set() + # An account-bound proxy renders a different sticky lease for each + # account. Release any whole-node quarantine left by an older guard; + # current versions isolate the audited account lease instead. + for node in all_nodes: + node_id = str(node.get("id") or "") + if not node_id or not node.get("proxyConfigured"): + continue + existing = state_nodes.get(node_id) + if not self._is_lease_scoped(node): + if existing: + existing["observe_only"] = False + existing["observe_only_reason"] = "" + continue + state = self._state_for(node_id) + if not lease_api_ready: + state["observe_only"] = True + state["observe_only_reason"] = "lease_api_unavailable" + elif state.get("observe_only_reason") in {"account_bound_proxy", "lease_api_unavailable"}: + state["observe_only"] = False + state["observe_only_reason"] = "" + if not state.get("disabled_by_guard"): + continue + if not node.get("enabled"): + try: + updated = self.api.set_enabled(node_id, True) + except Exception as exc: + release_failed_ids.add(node_id) + log_event( + "lease_scoped_guard_release_failed", + node_id=node_id, + node_name=node.get("name"), + error_type=type(exc).__name__, + ) + continue + if updated != 1: + release_failed_ids.add(node_id) + log_event( + "lease_scoped_guard_release_not_applied", + node_id=node_id, + node_name=node.get("name"), + updated=updated, + ) + continue + node["enabled"] = True + self._bump_statistic("actions", "restored") + state.update({ + "active_soft_strikes": 0, + "passive_soft_strikes": 0, + "error_strikes": 0, + "quarantined_until": 0.0, + "disabled_by_guard": False, + "last_reason": "", + "quarantine_source": "", + }) + append_state_event( + self.state, + "lease_scoped_guard_released", + node_id=node_id, + node_name=node.get("name"), + reason="lease_scoped_node", + ) + self._save() + log_event("lease_scoped_guard_released", node_id=node_id, node_name=node.get("name")) # Making an enabled node a fixed fallback is an explicit operator # override. Relinquish stale guard ownership before eligibility checks # so strict mode cannot repeatedly attempt an invalid disable. A @@ -1030,7 +1354,7 @@ class Guard: tracked = bool((state_nodes.get(stale_id) or {}).get("disabled_by_guard")) if stale_id not in present_ids or (stale_id not in managed_ids and not tracked): del state_nodes[stale_id] - skip_ids: set[str] = set() + skip_ids: set[str] = set(release_failed_ids) if not nodes: log_event("no_eligible_nodes") return all_nodes, [], skip_ids @@ -1067,6 +1391,8 @@ class Guard: continue if state.get("disabled_by_guard"): skip_ids.add(node_id) + if self._is_lease_scoped(node): + continue self._probe_quarantined(node, now) return all_nodes, nodes, skip_ids @@ -1076,6 +1402,9 @@ class Guard: for node in nodes: node_id = str(node["id"]) state = self._state_for(node_id) + if self._is_lease_scoped(node): + self._save() + continue if node_id not in skip_ids and node.get("enabled") and not state.get("disabled_by_guard"): self._probe_active(all_nodes, node, now) self._save() @@ -1175,15 +1504,18 @@ class Guard: duration_ms=int(audit_value.get("durationMs") or 0), strikes=int(state.get("passive_soft_strikes", 0)), ) - log_event( - "passive_immediate_quarantine", - node_id=node_id, - node_name=node.get("name"), - classification=classification, - reason=reason, - output_tps=round(speed, 3), - ) - self._quarantine(all_nodes, node, reason, now, recover_now=False) + if self._is_lease_scoped(node): + self._quarantine_lease(node, audit_value, reason, now) + else: + log_event( + "passive_immediate_quarantine", + node_id=node_id, + node_name=node.get("name"), + classification=classification, + reason=reason, + output_tps=round(speed, 3), + ) + self._quarantine(all_nodes, node, reason, now, recover_now=False) def run_passive_cycle(self) -> None: now = time.time() diff --git a/tools/egress-quality-guard/quality_guard_test.py b/tools/egress-quality-guard/quality_guard_test.py index d6b574b7..e6ef7d9c 100644 --- a/tools/egress-quality-guard/quality_guard_test.py +++ b/tools/egress-quality-guard/quality_guard_test.py @@ -342,6 +342,28 @@ class ApiClientTests(unittest.TestCase): } self.assertEqual(client.fixed_fallback_node_ids(), {"9", "11"}) + def test_list_leases_uses_stable_cursor_until_complete(self): + client = quality_guard.ApiClient(config()) + requested_cursors = [] + + def request(_method, path, _body=None): + query = quality_guard.urllib.parse.parse_qs(quality_guard.urllib.parse.urlparse(path).query) + cursor = (query.get("cursor") or [""])[0] + requested_cursors.append(cursor) + if not cursor: + return {"items": [{"accountId": "1"}], "hasMore": True, "nextCursor": "next-page"} + return {"items": [{"accountId": "2"}], "hasMore": False, "nextCursor": ""} + + client._request = request + self.assertEqual([value["accountId"] for value in client.list_leases()], ["1", "2"]) + self.assertEqual(requested_cursors, ["", "next-page"]) + + def test_list_leases_rejects_non_advancing_cursor(self): + client = quality_guard.ApiClient(config()) + client._request = lambda *_args, **_kwargs: {"items": [], "hasMore": True, "nextCursor": "same"} + with self.assertRaises(RuntimeError): + client.list_leases() + class FakeApi: def __init__(self, nodes, results, audit_pages=None, fixed_fallback_ids=None): @@ -352,7 +374,9 @@ class FakeApi: self.enabled_calls = [] self.quality_calls = [] self.quality_profile_calls = [] + self.quality_account_calls = [] self.rotation_calls = [] + self.leases = {} def list_nodes(self): return self.nodes @@ -360,9 +384,10 @@ class FakeApi: def fixed_fallback_node_ids(self): return set(self.fixed_fallback_ids) - def quality_test(self, node_id, profile_id=""): + def quality_test(self, node_id, profile_id="", account_id=""): self.quality_calls.append(node_id) self.quality_profile_calls.append(profile_id) + self.quality_account_calls.append(account_id) value = self.results.pop(0) if isinstance(value, Exception): raise value @@ -388,6 +413,26 @@ class FakeApi: return self.audit_pages.pop(0) return {"items": [], "hasMore": False, "nextCursor": ""} + def list_leases(self): + return list(self.leases.values()) + + def quarantine_lease(self, node_id, account_id, reason): + key = f"{node_id}:{account_id}" + value = { + "nodeId": node_id, "accountId": account_id, "reason": reason, + "version": f"version-{len(self.leases) + 1:09d}", "cooldownUntil": time.time() + 300, + } + self.leases[key] = value + return value + + def restore_lease(self, node_id, account_id, version): + key = f"{node_id}:{account_id}" + current = self.leases.get(key) + if current is None or current.get("version") != version: + raise quality_guard.ApiError(409, "qualityLeaseConflict", "stale") + del self.leases[key] + return True + class GuardTests(unittest.TestCase): @staticmethod @@ -444,6 +489,182 @@ class GuardTests(unittest.TestCase): self.assertEqual(api.quality_calls, ["2"]) self.assertEqual(guard.state["protected_node_ids"], ["1"]) + def test_fixed_fallback_releases_existing_account_lease_without_probe(self): + with tempfile.TemporaryDirectory() as directory: + cfg = config(state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock", node_ids=("1",)) + nodes = self.nodes(2) + nodes[0]["accountBoundProxy"] = True + api = FakeApi(nodes, [], fixed_fallback_ids={"1"}) + api.leases["1:101"] = { + "nodeId": "1", "accountId": "101", "reason": "hard_tps", + "version": "lease-version-0001", "cooldownUntil": time.time() + 300, + } + guard = quality_guard.Guard(cfg, api) + guard.run_active_cycle() + self.assertEqual(api.leases, {}) + self.assertEqual(api.quality_calls, []) + self.assertEqual(guard.state["statistics"]["actions"]["restored"], 1) + self.assertEqual(guard.state["recent_events"][-1]["event"], "lease_restored") + + def test_account_bound_proxy_skips_scheduled_probe_and_stays_observable(self): + with tempfile.TemporaryDirectory() as directory: + cfg = config( + state_file=Path(directory) / "state.json", + lock_file=Path(directory) / "lock", + node_ids=("1",), + ) + nodes = self.nodes(3) + nodes[0]["accountBoundProxy"] = True + api = FakeApi(nodes, []) + guard = quality_guard.Guard(cfg, api) + guard.run_active_cycle() + + self.assertEqual(api.quality_calls, []) + self.assertEqual(api.enabled_calls, []) + self.assertTrue(nodes[0]["enabled"]) + self.assertFalse(guard.state["nodes"]["1"]["observe_only"]) + self.assertEqual(guard.state["nodes"]["1"]["observe_only_reason"], "") + + def test_account_bound_proxy_records_passive_anomaly_without_node_quarantine(self): + with tempfile.TemporaryDirectory() as directory: + cfg = config( + state_file=Path(directory) / "state.json", + lock_file=Path(directory) / "lock", + mode="passive", + node_ids=("1",), + ) + nodes = self.nodes(3) + nodes[0]["accountBoundProxy"] = True + api = FakeApi(nodes, [{"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 100}], [ + {"items": [], "hasMore": False, "nextCursor": ""}, + {"items": [self.audit("lease-hit", "1", 1200)], "hasMore": False, "nextCursor": ""}, + ]) + guard = quality_guard.Guard(cfg, api) + guard.run_passive_cycle() + guard.run_passive_cycle() + + state = guard.state["nodes"]["1"] + self.assertEqual(api.enabled_calls, []) + self.assertTrue(nodes[0]["enabled"]) + self.assertFalse(state["disabled_by_guard"]) + self.assertEqual(state["last_classification"], "hard") + self.assertEqual(state["last_reason"], "hard_tps") + self.assertEqual(guard.state["statistics"]["actions"]["quarantined"], 1) + self.assertEqual(len(api.leases), 1) + self.assertEqual( + [event["event"] for event in guard.state["recent_events"]], + ["passive_audit_anomaly", "lease_quarantined"], + ) + next(iter(api.leases.values()))["cooldownUntil"] = 0 + guard.run_active_cycle() + self.assertEqual(api.quality_account_calls, ["101"]) + self.assertEqual(api.leases, {}) + self.assertEqual(guard.state["recent_events"][-1]["event"], "lease_restored") + + def test_repeated_account_anomaly_extends_one_lease_without_double_counting(self): + with tempfile.TemporaryDirectory() as directory: + cfg = config(state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock", node_ids=("1",)) + nodes = self.nodes(2) + nodes[0]["accountBoundProxy"] = True + api = FakeApi(nodes, []) + guard = quality_guard.Guard(cfg, api) + audit = {"accountId": "101"} + + guard._quarantine_lease(nodes[0], audit, "hard_tps", time.time()) + guard._quarantine_lease(nodes[0], audit, "hard_tps", time.time()) + + self.assertEqual(len(api.leases), 1) + self.assertEqual(guard.state["nodes"]["1"]["quarantined_lease_count"], 1) + self.assertEqual(guard.state["statistics"]["actions"]["quarantined"], 1) + self.assertEqual(guard.state["recent_events"][-1]["event"], "lease_quarantine_extended") + + def test_due_lease_recovery_has_a_per_cycle_budget(self): + with tempfile.TemporaryDirectory() as directory: + cfg = config(state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock", node_ids=("1",)) + nodes = self.nodes(2) + nodes[0]["accountBoundProxy"] = True + healthy = {"expectedMatched": True, "outputTokens": 100, "reasoningTokens": 40, "outputTokensPerSecond": 100} + api = FakeApi(nodes, [healthy] * 20) + for index in range(20): + account_id = str(1000 + index) + api.leases[f"1:{account_id}"] = { + "nodeId": "1", "accountId": account_id, "reason": "hard_tps", + "version": f"lease-version-{index:04d}", "cooldownUntil": 0, + } + guard = quality_guard.Guard(cfg, api) + guard.run_active_cycle() + self.assertEqual(len(api.quality_account_calls), quality_guard.LEASE_RECOVERY_MAX_PER_CYCLE) + self.assertEqual(len(api.leases), 20 - quality_guard.LEASE_RECOVERY_MAX_PER_CYCLE) + guard.run_active_cycle() + self.assertEqual(len(api.quality_account_calls), quality_guard.LEASE_RECOVERY_MAX_PER_CYCLE * 2) + + def test_failed_lease_recovery_is_backed_off(self): + with tempfile.TemporaryDirectory() as directory: + cfg = config(state_file=Path(directory) / "state.json", lock_file=Path(directory) / "lock", node_ids=("1",)) + nodes = self.nodes(2) + nodes[0]["accountBoundProxy"] = True + api = FakeApi(nodes, [RuntimeError("probe failed"), RuntimeError("must not run immediately")]) + api.leases["1:101"] = { + "nodeId": "1", "accountId": "101", "reason": "hard_tps", + "version": "lease-version-0001", "cooldownUntil": 0, + } + api.quarantine_lease = mock.Mock(side_effect=RuntimeError("backend unavailable")) + guard = quality_guard.Guard(cfg, api) + guard.run_active_cycle() + guard.run_active_cycle() + self.assertEqual(api.quality_account_calls, ["101"]) + retry = guard.state["lease_recovery"]["1:101"] + self.assertGreater(retry["next_attempt_at"], time.time()) + + def test_account_bound_proxy_releases_only_guard_owned_legacy_quarantine(self): + with tempfile.TemporaryDirectory() as directory: + cfg = config( + state_file=Path(directory) / "state.json", + lock_file=Path(directory) / "lock", + node_ids=("1",), + ) + nodes = self.nodes(3) + nodes[0].update({"accountBoundProxy": True, "enabled": False}) + api = FakeApi(nodes, []) + guard = quality_guard.Guard(cfg, api) + state = guard._state_for("1") + state.update({"disabled_by_guard": True, "last_reason": "hard_tps", "quarantined_until": time.time() + 300}) + guard.run_active_cycle() + + self.assertEqual(api.enabled_calls, [("1", True)]) + self.assertTrue(nodes[0]["enabled"]) + self.assertFalse(state["disabled_by_guard"]) + self.assertFalse(state["observe_only"]) + self.assertEqual(guard.state["statistics"]["actions"]["restored"], 1) + self.assertEqual(guard.state["recent_events"][-1]["event"], "lease_scoped_guard_released") + + nodes[0]["enabled"] = False + guard.run_active_cycle() + self.assertEqual(api.enabled_calls, [("1", True)]) + self.assertFalse(nodes[0]["enabled"]) + + def test_account_bound_proxy_keeps_ownership_when_legacy_release_fails(self): + with tempfile.TemporaryDirectory() as directory: + cfg = config( + state_file=Path(directory) / "state.json", + lock_file=Path(directory) / "lock", + node_ids=("1",), + ) + nodes = self.nodes(3) + nodes[0].update({"accountBoundProxy": True, "enabled": False}) + api = FakeApi(nodes, []) + api.set_enabled = mock.Mock(side_effect=RuntimeError("temporary backend failure")) + guard = quality_guard.Guard(cfg, api) + state = guard._state_for("1") + state.update({"disabled_by_guard": True, "last_reason": "hard_tps", "quarantined_until": 0}) + guard.run_active_cycle() + + api.set_enabled.assert_called_once_with("1", True) + self.assertEqual(api.quality_calls, []) + self.assertFalse(nodes[0]["enabled"]) + self.assertTrue(state["disabled_by_guard"]) + self.assertFalse(state["observe_only"]) + def test_enabled_node_promoted_to_fixed_fallback_releases_guard_ownership(self): with tempfile.TemporaryDirectory() as directory: cfg = config( @@ -990,7 +1211,7 @@ class GuardTests(unittest.TestCase): "provider": "grok_build", "streaming": True, "statusCode": 200, "firstTokenMs": 200, "durationMs": 200 + generation_ms, "outputTokens": output_tokens, "reasoningTokens": min(100, max(0, output_tokens - 1)), - "egressNodeId": node_id, "errorCode": None, + "accountId": "101", "egressNodeId": node_id, "errorCode": None, }