mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 16:01:07 +00:00
Merge branch 'main' into fix/voice-ws-timeout-and-stt-billing
This commit is contained in:
34 files changed
+1037
-98
No files matched your search
@@ -407,11 +407,13 @@ qualityGuard:
|
||||
holdTimeout: 30s
|
||||
minOutputTokens: 8
|
||||
onExhausted: fail_closed # fail_open | fail_closed
|
||||
# Disable on the first confirmed missing-thinking or degraded-speed hit.
|
||||
autoDisable: true
|
||||
accountCooldown: 12h
|
||||
idleAccountCooldown: 15m
|
||||
```
|
||||
|
||||
`requestRetry` runs on the gateway request path and is independent of the sidecar. `config.example.yaml` keeps `enabled: false`; set it true to intercept. When enabled, a thinking-model stream with enough visible output and no streamed reasoning is **not delivered**; replay-safe stateless requests may try another account. TUI follow-ups (`previous_response_id`) and hosted-tool turns are still held for classification, but a quality withhold never replays account-bound state or side-effecting tools across accounts; `onExhausted` returns `503 quality_degraded` or releases that held body. Context compaction, image, video, and ForcedEgress probe requests are unchanged.
|
||||
`requestRetry` runs on the gateway request path and is independent of the sidecar. The example above explicitly enables it; built-in defaults and `config.example.yaml` leave both `enabled` and `autoDisable` off. Either switch enables request-path quality checks and retries. A thinking-model stream with enough visible output and no streamed reasoning is **not delivered**; another account is tried. `autoDisable: true` disables an account on the first confirmed missing-thinking or degraded output-speed hit (soft-TPS, hard-TPS, or buffered-burst). The Account Maintenance switch controls `autoDisable`; turning it off restores the YAML `requestRetry.enabled` policy. If every attempt still has no reasoning, `onExhausted` either returns `503 quality_degraded` or delivers the last body. Context compaction is exempt from both missing-thinking and output-speed account penalties. Image, video, stored-response, and ForcedEgress probe requests are unchanged. Grok TUI tool turns stay held so 0-thinking dumps cannot skip the gate.
|
||||
|
||||
```bash
|
||||
docker compose --profile quality-guard up -d --build
|
||||
|
||||
+3
-1
@@ -373,11 +373,13 @@ qualityGuard:
|
||||
holdTimeout: 30s
|
||||
minOutputTokens: 8
|
||||
onExhausted: fail_closed # fail_open | fail_closed
|
||||
# 首次确认缺 thinking 或吞吐降智(soft/hard/burst)时立即禁用账号。
|
||||
autoDisable: true
|
||||
accountCooldown: 12h
|
||||
idleAccountCooldown: 15m
|
||||
```
|
||||
|
||||
`requestRetry` 在网关请求路径上生效,与 sidecar 探测/隔离相互独立。`config.example.yaml` 里 `enabled` 仍为 false,打开后才拦截。开启后,可见输出达到 `minOutputTokens` 且全程无流式 reasoning 时**不发给用户**;只有可安全重放的无状态请求才会排除账号重试。TUI 续聊(`previous_response_id`)和 hosted tools 仍会进入 hold 检测,但质量拦截不会把账号绑定状态或有副作用的工具跨账号重放,最终按 `onExhausted` 返回 `503 quality_degraded` 或放出当前响应。上下文压缩、图片、视频和 ForcedEgress 探针不受影响。
|
||||
`requestRetry` 在网关请求路径上生效,与 sidecar 探测/隔离相互独立。上面的示例显式开启;内置默认值和 `config.example.yaml` 均将 `enabled`、`autoDisable` 设为关闭。任一开关开启后都会启用请求内质量检测与重试。可见输出达到 `minOutputTokens` 且全程无流式 reasoning 时**不发给用户**,排除该账号再试;`autoDisable: true` 会在首次确认缺 thinking 或吞吐降智(soft/hard/burst)时直接禁用账号。管理页面的“自动停用降智账号”控制 `autoDisable`,关闭后恢复 YAML 中 `requestRetry.enabled` 的原有策略。全部仍无推理则按 `onExhausted` 返回 `503 quality_degraded` 或放出最后一枪。上下文压缩同时豁免缺 thinking 和输出速度的账号惩罚。不处理图/视频、stored response 钉账号和 ForcedEgress 探针。Grok TUI 带 tools 的回合仍会 hold,避免 0-thinking 降智流跳过闸门。
|
||||
|
||||
```bash
|
||||
docker compose --profile quality-guard up -d --build
|
||||
|
||||
@@ -352,7 +352,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat
|
||||
modelRepo.SetInvalidationObserver(invalidationService.Notify)
|
||||
clientKeyRepo.SetInvalidationObserver(invalidationService.Notify)
|
||||
gatewayService := gateway.NewService(modelService, auditService, accountService, clientKeyService, providers, selector, responseRepo, cfg.Routing.MaxAttempts)
|
||||
gatewayService.UpdateQualityRetry(qualityRetryRuntime(cfg.QualityGuard.RequestRetry))
|
||||
gatewayService.UpdateQualityRetry(qualityRetryRuntime(cfg.QualityGuard))
|
||||
gatewayService.UpdateVideoMaxAttempts(cfg.Routing.VideoMaxAttempts)
|
||||
gatewayService.UpdateMarkBuildChatDeniedAsReauth(cfg.Routing.MarkBuildChatDeniedAsReauth)
|
||||
gatewayService.SetLogger(logger)
|
||||
@@ -409,7 +409,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat
|
||||
egressManager.UpdateAccountIsolatedConnections(next.Routing.AccountIsolatedConnections)
|
||||
reasoningReplay.UpdateConfig(reasoningreplay.Config{Enabled: next.Routing.ReasoningReplayEnabled, TTL: next.Routing.ReasoningReplayTTL.Value()})
|
||||
gatewayService.UpdateMaxAttempts(next.Routing.MaxAttempts)
|
||||
gatewayService.UpdateQualityRetry(qualityRetryRuntime(next.QualityGuard.RequestRetry))
|
||||
gatewayService.UpdateQualityRetry(qualityRetryRuntime(next.QualityGuard))
|
||||
gatewayService.UpdateVideoMaxAttempts(next.Routing.VideoMaxAttempts)
|
||||
gatewayService.UpdateMarkBuildChatDeniedAsReauth(next.Routing.MarkBuildChatDeniedAsReauth)
|
||||
gatewayService.UpdateBuildForbiddenReauthPolicy(next.Accounts.MarkBuildForbiddenReauth, next.Accounts.BuildForbiddenReauthCodes)
|
||||
@@ -490,17 +490,26 @@ func accountAutoCleanConfig(value config.AccountsConfig) accountapp.AutoCleanCon
|
||||
}
|
||||
}
|
||||
|
||||
func qualityRetryRuntime(value config.QualityGuardRequestRetryConfig) gateway.QualityRetryRuntime {
|
||||
func qualityRetryRuntime(value config.QualityGuardConfig) gateway.QualityRetryRuntime {
|
||||
retry := value.RequestRetry
|
||||
return gateway.QualityRetryRuntime{
|
||||
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(),
|
||||
MinEncryptedBytes: value.MinEncryptedBytes,
|
||||
EncryptedBytesPerReasoningToken: value.EncryptedBytesPerReasoningToken,
|
||||
// Auto-disable needs request-path detection even when the YAML retry
|
||||
// switch is off. Derive this at runtime so turning auto-disable off
|
||||
// restores the original policy without persisting a second switch.
|
||||
Enabled: retry.Enabled || retry.AutoDisable,
|
||||
MaxAttempts: retry.MaxAttempts,
|
||||
HoldTimeout: retry.HoldTimeout.Value(),
|
||||
MinOutputTokens: int64(retry.MinOutputTokens),
|
||||
OnExhausted: retry.OnExhausted,
|
||||
AutoDisable: retry.AutoDisable,
|
||||
AccountCooldown: retry.AccountCooldown.Value(),
|
||||
IdleAccountCooldown: retry.IdleAccountCooldown.Value(),
|
||||
MinEncryptedBytes: retry.MinEncryptedBytes,
|
||||
EncryptedBytesPerReasoningToken: retry.EncryptedBytesPerReasoningToken,
|
||||
SoftTPS: value.SoftTPS,
|
||||
HardTPS: value.HardTPS,
|
||||
MinGenerationMS: value.MinimumGenerationWindow.Value().Milliseconds(),
|
||||
FailClosed: value.FailClosed,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/application/gateway"
|
||||
settingsapp "github.com/chenyme/grok2api/backend/internal/application/settings"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/config"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/persistence/relational"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/security"
|
||||
)
|
||||
|
||||
func TestDegradedAccountSwitchAppliesAndRestoresRequestRetryPolicy(t *testing.T) {
|
||||
for _, retryEnabled := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("yaml_retry_%t", retryEnabled), func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
path := filepath.Join(t.TempDir(), "config.yaml")
|
||||
if err := os.WriteFile(path, []byte(`secrets:
|
||||
jwtSecret: "12345678901234567890123456789012"
|
||||
credentialEncryptionKey: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
|
||||
`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := config.Load(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.QualityGuard.RequestRetry.Enabled = retryEnabled
|
||||
db, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "settings.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err := db.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cipher, err := security.NewCipher(cfg.Secrets.CredentialEncryptionKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := relational.NewRuntimeSettingsRepository(db, cipher)
|
||||
var applied gateway.QualityRetryRuntime
|
||||
service := settingsapp.NewService(cfg, time.Time{}, 0, repo, nil, func(next config.Config) {
|
||||
applied = qualityRetryRuntime(next.QualityGuard)
|
||||
if next.QualityGuard.RequestRetry.Enabled != retryEnabled {
|
||||
t.Fatal("management switch changed the YAML retry policy")
|
||||
}
|
||||
})
|
||||
for _, autoDisable := range []bool{true, false} {
|
||||
snapshot := service.Get()
|
||||
input := snapshot.Config
|
||||
input.Accounts.AutoDisableDegradedAccounts = autoDisable
|
||||
input.Accounts.AutoDisableDegradedAccountsProvided = true
|
||||
if _, err := service.Update(ctx, snapshot.Revision, input); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantEnabled := retryEnabled || autoDisable
|
||||
if applied.Enabled != wantEnabled || applied.AutoDisable != autoDisable {
|
||||
t.Fatalf("hot reload: autoDisable=%t runtime=%#v", autoDisable, applied)
|
||||
}
|
||||
reloaded, _, _, err := settingsapp.LoadPersisted(ctx, cfg, repo)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runtime := qualityRetryRuntime(reloaded.QualityGuard)
|
||||
if runtime.Enabled != wantEnabled || runtime.AutoDisable != autoDisable || reloaded.QualityGuard.RequestRetry.Enabled != retryEnabled {
|
||||
t.Fatalf("restart: autoDisable=%t runtime=%#v", autoDisable, runtime)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,9 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -1349,6 +1351,9 @@ func NormalizeProxyURL(value string) (string, error) {
|
||||
return "", errors.New("代理地址包含保留的账号占位符文本")
|
||||
}
|
||||
parseValue := strings.ReplaceAll(value, ProxyAccountPlaceholder, proxyAccountSentinel)
|
||||
if normalized, ok := normalizeLegacyHTTPProxy(parseValue); ok {
|
||||
parseValue = normalized
|
||||
}
|
||||
parsed, err := url.Parse(parseValue)
|
||||
if err != nil {
|
||||
return "", errors.New("代理地址格式无效")
|
||||
@@ -1384,6 +1389,22 @@ func NormalizeProxyURL(value string) (string, error) {
|
||||
return parsed.String(), nil
|
||||
}
|
||||
|
||||
func normalizeLegacyHTTPProxy(value string) (string, bool) {
|
||||
parts := strings.SplitN(value, ":", 4)
|
||||
if len(parts) != 4 || net.ParseIP(parts[0]).To4() == nil || parts[2] == "" || parts[3] == "" {
|
||||
return "", false
|
||||
}
|
||||
port, err := strconv.ParseUint(parts[1], 10, 16)
|
||||
if err != nil || port == 0 {
|
||||
return "", false
|
||||
}
|
||||
return (&url.URL{
|
||||
Scheme: "http",
|
||||
Host: net.JoinHostPort(parts[0], strconv.FormatUint(port, 10)),
|
||||
User: url.UserPassword(parts[2], parts[3]),
|
||||
}).String(), true
|
||||
}
|
||||
|
||||
func SanitizeCloudflareCookies(value string) string {
|
||||
allowed := make([]string, 0, 4)
|
||||
seen := make(map[string]struct{})
|
||||
|
||||
@@ -3,6 +3,7 @@ package egress
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -49,6 +50,37 @@ func TestNormalizeProxyURLValidatesStructure(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeProxyURLAcceptsLegacyHTTPProxyFormat(t *testing.T) {
|
||||
value, err := NormalizeProxyURL("127.0.0.1:8080:user:password")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if value != "http://user:password@127.0.0.1:8080" {
|
||||
t.Fatalf("normalized legacy HTTP proxy = %q", value)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeProxyURLPreservesLegacyCredentials(t *testing.T) {
|
||||
for _, password := range []string{"pass:with:colons", "pass:@/?#%中文"} {
|
||||
t.Run(password, func(t *testing.T) {
|
||||
value, err := NormalizeProxyURL("127.0.0.1:8080:user@domain:" + password)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parsed, err := url.Parse(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if parsed.Scheme != "http" || parsed.Host != "127.0.0.1:8080" || parsed.User == nil || parsed.User.Username() != "user@domain" {
|
||||
t.Fatalf("unexpected normalized proxy = %q", value)
|
||||
}
|
||||
if got, ok := parsed.User.Password(); !ok || got != password {
|
||||
t.Fatalf("password = %q, want %q", got, password)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeProxyURLStripsTunnelRemarks(t *testing.T) {
|
||||
base := "trojan://password@proxy.example:443?security=tls&sni=edge.example"
|
||||
one, err := NormalizeProxyURL(base + "#one")
|
||||
@@ -65,21 +97,32 @@ func TestNormalizeProxyURLStripsTunnelRemarks(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestNormalizeProxyURLAllowsAccountPlaceholderOnlyInUsername(t *testing.T) {
|
||||
value, err := NormalizeProxyURL("socks5h://Default.{account}:token@resin:2260")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if value != "socks5h://Default.%7Baccount%7D:token@resin:2260" && value != "socks5h://Default.{account}:token@resin:2260" {
|
||||
t.Fatalf("normalized Resin proxy = %q", value)
|
||||
}
|
||||
if !strings.Contains(value, ProxyAccountPlaceholder) {
|
||||
t.Fatalf("account placeholder was lost: %q", value)
|
||||
for _, raw := range []string{
|
||||
"socks5h://Default.{account}:token@resin:2260",
|
||||
"127.0.0.1:8080:Default.{account}:token",
|
||||
} {
|
||||
t.Run(raw, func(t *testing.T) {
|
||||
value, err := NormalizeProxyURL(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(value, ProxyAccountPlaceholder) {
|
||||
t.Fatalf("account placeholder was lost: %q", value)
|
||||
}
|
||||
if again, err := NormalizeProxyURL(value); err != nil || again != value {
|
||||
t.Fatalf("proxy normalization is not stable: %q, err = %v", again, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, invalid := range []string{
|
||||
"socks5h://user:token@{account}:2260",
|
||||
"socks5h://user:{account}@resin:2260",
|
||||
"socks5h://{account}:{account}@resin:2260",
|
||||
"socks5h://grok2api_account_placeholder:token@{account}:2260",
|
||||
"127.0.0.1:8080:user:{account}",
|
||||
"127.0.0.1:8080:{account}:{account}",
|
||||
"127.0.0.1:8080:{account}.{account}:token",
|
||||
"127.0.0.1:8080:grok2api_account_placeholder:{account}",
|
||||
} {
|
||||
if _, err := NormalizeProxyURL(invalid); err == nil {
|
||||
t.Fatalf("invalid account placeholder accepted: %q", invalid)
|
||||
|
||||
@@ -45,6 +45,7 @@ func TestParseProxySubscriptionAcceptsPlainAndBase64Lists(t *testing.T) {
|
||||
plain, skipped, err := parseProxySubscription(strings.Join([]string{
|
||||
"# proxy list",
|
||||
"http://user:pass@one.example:8080",
|
||||
"127.0.0.1:3128:legacy:password",
|
||||
"socks5h://two.example:1080",
|
||||
"http://user:pass@one.example:8080",
|
||||
"not a proxy",
|
||||
@@ -52,9 +53,12 @@ func TestParseProxySubscriptionAcceptsPlainAndBase64Lists(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(plain) != 2 || skipped != 2 {
|
||||
if len(plain) != 3 || skipped != 2 {
|
||||
t.Fatalf("plain entries=%d skipped=%d", len(plain), skipped)
|
||||
}
|
||||
if plain[1].ProxyURL != "http://legacy:password@127.0.0.1:3128" {
|
||||
t.Fatalf("legacy HTTP proxy = %q", plain[1].ProxyURL)
|
||||
}
|
||||
for _, entry := range plain {
|
||||
if entry.ProxyURL == "" || len(entry.Key) != 64 {
|
||||
t.Fatalf("unsafe parsed entry: %#v", entry)
|
||||
@@ -71,6 +75,31 @@ func TestParseProxySubscriptionAcceptsPlainAndBase64Lists(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseProxySubscriptionPreservesLegacyAccountPlaceholder(t *testing.T) {
|
||||
content := strings.Join([]string{
|
||||
"127.0.0.1:8080:Default.{account}:pass:word",
|
||||
"http://Default.{account}:pass%3Aword@127.0.0.1:8080",
|
||||
"127.0.0.1:8080:user:{account}",
|
||||
}, "\n")
|
||||
for name, input := range map[string]string{
|
||||
"plain": content,
|
||||
"base64": base64.StdEncoding.EncodeToString([]byte(content)),
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
entries, skipped, err := parseProxySubscription(input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 1 || skipped != 2 {
|
||||
t.Fatalf("entries=%d skipped=%d, want one entry, one duplicate and one invalid placeholder", len(entries), skipped)
|
||||
}
|
||||
if entries[0].ProxyURL != "http://Default.{account}:pass%3Aword@127.0.0.1:8080" {
|
||||
t.Fatalf("legacy account proxy = %q", entries[0].ProxyURL)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseProxySubscriptionRejectsNoUsableEntries(t *testing.T) {
|
||||
if _, _, err := parseProxySubscription("# only comments\nfile:///tmp/proxies\n"); err == nil {
|
||||
t.Fatal("invalid proxy subscription was accepted")
|
||||
|
||||
@@ -59,12 +59,17 @@ type QualityRetryRuntime struct {
|
||||
HoldTimeout time.Duration
|
||||
MinOutputTokens int64
|
||||
OnExhausted string
|
||||
AutoDisable bool
|
||||
AccountCooldown time.Duration
|
||||
// IdleAccountCooldown is applied to truly empty upstream streams
|
||||
// (idle timeout / empty peek). Missing-thinking still uses AccountCooldown.
|
||||
IdleAccountCooldown time.Duration
|
||||
MinEncryptedBytes int
|
||||
EncryptedBytesPerReasoningToken int
|
||||
SoftTPS float64
|
||||
HardTPS float64
|
||||
MinGenerationMS int64
|
||||
FailClosed bool
|
||||
}
|
||||
|
||||
// QualityStreamSignals is the hold classifier input. Tests drive this
|
||||
@@ -129,6 +134,15 @@ func normalizeQualityRetry(cfg QualityRetryRuntime) QualityRetryRuntime {
|
||||
if cfg.EncryptedBytesPerReasoningToken <= 0 {
|
||||
cfg.EncryptedBytesPerReasoningToken = defaultEncryptedBytesPerReasoningToken
|
||||
}
|
||||
if cfg.SoftTPS <= 0 {
|
||||
cfg.SoftTPS = audit.DefaultDegradeSoftTPS
|
||||
}
|
||||
if cfg.HardTPS <= cfg.SoftTPS {
|
||||
cfg.HardTPS = audit.DefaultDegradeHardTPS
|
||||
}
|
||||
if cfg.MinGenerationMS <= 0 {
|
||||
cfg.MinGenerationMS = audit.DefaultDegradeMinGenMS
|
||||
}
|
||||
cfg.OnExhausted = normalizeQualityExhaustionPolicy(cfg.OnExhausted)
|
||||
return cfg
|
||||
}
|
||||
@@ -565,10 +579,10 @@ func jsonStringEquals(raw json.RawMessage, want string) bool {
|
||||
return json.Unmarshal(raw, &value) == nil && strings.EqualFold(strings.TrimSpace(value), want)
|
||||
}
|
||||
|
||||
func (s *Service) applyMissingThinkingPenalty(ctx context.Context, requestID string, credential accountdomain.Credential, cooldown time.Duration) {
|
||||
func (s *Service) applyMissingThinkingPenalty(ctx context.Context, requestID string, credential accountdomain.Credential, cooldown time.Duration, autoDisable bool) {
|
||||
writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), finalizationTimeout)
|
||||
defer cancel()
|
||||
action, err := s.selector.markMissingThinking(writeCtx, credential, cooldown)
|
||||
action, err := s.selector.markMissingThinking(writeCtx, credential, cooldown, autoDisable)
|
||||
if err != nil {
|
||||
s.logger.Error("quality_degraded_penalty_failed", "request_id", requestID, "account_id", credential.ID, "action", action, "error", err)
|
||||
return
|
||||
@@ -581,6 +595,26 @@ func (s *Service) applyMissingThinkingPenalty(ctx context.Context, requestID str
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) applyOutputSpeedPenalty(ctx context.Context, record audit.Record, credential accountdomain.Credential, cfg QualityRetryRuntime, forcedEgress bool) error {
|
||||
// Both explicit and TUI compaction are classified in the audit record.
|
||||
// System summaries stay exempt from account quality penalties.
|
||||
if record.Operation == audit.OperationCompaction {
|
||||
return nil
|
||||
}
|
||||
if !cfg.Enabled || !cfg.AutoDisable || forcedEgress || credential.Provider != accountdomain.ProviderBuild || !record.Streaming || record.FirstTokenMS == nil || record.OutputTokens < cfg.MinOutputTokens || !auditRequestSucceeded(record.StatusCode, record.ErrorCode) {
|
||||
return nil
|
||||
}
|
||||
class, tps, _ := audit.ClassifyOutputSpeed(record.OutputTokens, record.ReasoningTokens, *record.FirstTokenMS, record.DurationMS, cfg.SoftTPS, cfg.HardTPS, cfg.MinGenerationMS, cfg.FailClosed)
|
||||
if class == "" {
|
||||
return nil
|
||||
}
|
||||
if err := s.selector.disableAccount(ctx, credential); err != nil {
|
||||
return err
|
||||
}
|
||||
s.logger.Info("quality_degraded_disabled", "request_id", record.RequestID, "account_id", credential.ID, "class", class, "output_tps", tps)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) recordQualityDegraded(ctx context.Context, base audit.Record, credential accountdomain.Credential, usage Usage, startedAt time.Time, trace *infraegress.Trace, provider accountdomain.Provider) {
|
||||
record := base
|
||||
record.EventID = newAuditEventID()
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
@@ -220,6 +221,58 @@ func TestEncryptedThinkingFloorSaturates(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoDisableFirstOutputSpeedHit(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "output-speed-disable.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accounts := relational.NewAccountRepository(database)
|
||||
credential, _, err := accounts.UpsertByIdentity(ctx, accountdomain.Credential{
|
||||
Provider: accountdomain.ProviderBuild, Name: "degraded-speed", SourceKey: "degraded-speed", EncryptedAccessToken: "encrypted",
|
||||
Enabled: true, AuthStatus: accountdomain.AuthStatusActive, Priority: 10, MaxConcurrent: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
selector := NewSelector(accounts, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), nil, time.Hour, time.Second, time.Minute)
|
||||
service := &Service{selector: selector, logger: slog.Default()}
|
||||
firstTokenMS := int64(1_000)
|
||||
record := audit.Record{
|
||||
RequestID: "degraded-speed", Provider: string(accountdomain.ProviderBuild), Streaming: true, StatusCode: http.StatusOK,
|
||||
OutputTokens: 120, FirstTokenMS: &firstTokenMS, DurationMS: 1_300,
|
||||
}
|
||||
cfg := normalizeQualityRetry(QualityRetryRuntime{Enabled: true, AutoDisable: true, MinOutputTokens: 32})
|
||||
if err := service.applyOutputSpeedPenalty(ctx, record, credential, cfg, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
healthy, err := accounts.Get(ctx, credential.ID)
|
||||
if err != nil || !healthy.Enabled {
|
||||
t.Fatalf("below-threshold hit must remain scheduled: %#v, err=%v", healthy, err)
|
||||
}
|
||||
record.DurationMS = 1_200
|
||||
record.Operation = audit.OperationCompaction
|
||||
if err := service.applyOutputSpeedPenalty(ctx, record, credential, cfg, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
compacted, err := accounts.Get(ctx, credential.ID)
|
||||
if err != nil || !compacted.Enabled {
|
||||
t.Fatalf("compaction must remain exempt from speed penalties: %#v, err=%v", compacted, err)
|
||||
}
|
||||
record.Operation = audit.OperationResponses
|
||||
if err := service.applyOutputSpeedPenalty(ctx, record, credential, cfg, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
disabled, err := accounts.Get(ctx, credential.ID)
|
||||
if err != nil || disabled.Enabled {
|
||||
t.Fatalf("first degraded-speed hit must disable: %#v, err=%v", disabled, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecideQualityRetry(t *testing.T) {
|
||||
t.Parallel()
|
||||
if got := DecideQualityRetry(QualityDeliver, 0, 2, qualityRetryFailOpen); got != QualityActionDeliver {
|
||||
|
||||
@@ -1232,27 +1232,19 @@ func (s *Selector) clearQuotaConsumptionAccount(provider account.Provider, accou
|
||||
s.quotaMu.Unlock()
|
||||
}
|
||||
|
||||
// markMissingThinking cools an account for the first no-thinking hit and
|
||||
// disables it if missing thinking appears again after that cooldown.
|
||||
func (s *Selector) markMissingThinking(ctx context.Context, credential account.Credential, cooldown time.Duration) (missingThinkingPenaltyResult, error) {
|
||||
// markMissingThinking disables immediately when configured; otherwise it
|
||||
// cools the first no-thinking hit and disables a later hit after the cooldown.
|
||||
func (s *Selector) markMissingThinking(ctx context.Context, credential account.Credential, cooldown time.Duration, autoDisable bool) (missingThinkingPenaltyResult, error) {
|
||||
if cooldown <= 0 {
|
||||
cooldown = defaultMissingThinkingCooldown
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
inCooldown := credential.CooldownUntil != nil && now.Before(*credential.CooldownUntil)
|
||||
if isMissingThinkingStrike(credential.LastError) && !inCooldown {
|
||||
disabled := false
|
||||
if _, err := s.accounts.UpdateMany(ctx, credential.Provider, []uint64{credential.ID}, repository.AccountUpdates{Enabled: &disabled}); err != nil {
|
||||
if autoDisable || (isMissingThinkingStrike(credential.LastError) && !inCooldown) {
|
||||
if err := s.disableAccount(ctx, credential); err != nil {
|
||||
return missingThinkingPenaltyUnchanged, err
|
||||
}
|
||||
healthErr := s.accounts.UpdateHealth(ctx, credential.ID, credential.Provider, credential.FailureCount, nil, lastErrorMissingThinkingDisabled, false)
|
||||
s.ApplyInvalidation(repository.InvalidationEvent{
|
||||
Kind: repository.InvalidationAccountStateChanged, Provider: credential.Provider, AccountID: credential.ID,
|
||||
})
|
||||
s.evictCandidate(credential.Provider, credential.ID)
|
||||
if s.sticky != nil {
|
||||
_ = s.sticky.DeleteByAccount(ctx, credential.ID)
|
||||
}
|
||||
return missingThinkingPenaltyDisabled, healthErr
|
||||
}
|
||||
if inCooldown {
|
||||
@@ -1270,6 +1262,21 @@ func (s *Selector) markMissingThinking(ctx context.Context, credential account.C
|
||||
return missingThinkingPenaltyCooled, nil
|
||||
}
|
||||
|
||||
func (s *Selector) disableAccount(ctx context.Context, credential account.Credential) error {
|
||||
disabled := false
|
||||
if _, err := s.accounts.UpdateMany(ctx, credential.Provider, []uint64{credential.ID}, repository.AccountUpdates{Enabled: &disabled}); err != nil {
|
||||
return err
|
||||
}
|
||||
s.ApplyInvalidation(repository.InvalidationEvent{
|
||||
Kind: repository.InvalidationAccountStateChanged, Provider: credential.Provider, AccountID: credential.ID,
|
||||
})
|
||||
s.evictCandidate(credential.Provider, credential.ID)
|
||||
if s.sticky != nil {
|
||||
_ = s.sticky.DeleteByAccount(ctx, credential.ID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Selector) MarkFailure(ctx context.Context, credential account.Credential, status int, retryAfter time.Duration) {
|
||||
retryAfter = s.boundUpstreamRetryAfter(retryAfter)
|
||||
_ = s.markFailure(ctx, credential, credential.FailureCount, credential.FailureCount+1, status, retryAfter, status == 0)
|
||||
|
||||
@@ -1611,7 +1611,7 @@ func TestMarkMissingThinkingCoolsThenDisables(t *testing.T) {
|
||||
}
|
||||
selector := NewSelector(accounts, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), nil, time.Hour, 30*time.Second, 30*time.Minute, 500*time.Millisecond)
|
||||
before := time.Now().UTC()
|
||||
if action, err := selector.markMissingThinking(ctx, credential, time.Hour); err != nil || action != missingThinkingPenaltyCooled {
|
||||
if action, err := selector.markMissingThinking(ctx, credential, time.Hour, false); err != nil || action != missingThinkingPenaltyCooled {
|
||||
t.Fatalf("first penalty = (%s, %v)", action, err)
|
||||
}
|
||||
first, err := accounts.Get(ctx, credential.ID)
|
||||
@@ -1624,7 +1624,7 @@ func TestMarkMissingThinkingCoolsThenDisables(t *testing.T) {
|
||||
if wait := first.CooldownUntil.Sub(before); wait < 50*time.Minute || wait > 70*time.Minute {
|
||||
t.Fatalf("first cooldown = %s", wait)
|
||||
}
|
||||
if action, err := selector.markMissingThinking(ctx, first, time.Hour); err != nil || action != missingThinkingPenaltyUnchanged {
|
||||
if action, err := selector.markMissingThinking(ctx, first, time.Hour, false); err != nil || action != missingThinkingPenaltyUnchanged {
|
||||
t.Fatalf("in-cooldown penalty = (%s, %v)", action, err)
|
||||
}
|
||||
stillCooling, err := accounts.Get(ctx, credential.ID)
|
||||
@@ -1636,7 +1636,7 @@ func TestMarkMissingThinkingCoolsThenDisables(t *testing.T) {
|
||||
}
|
||||
expired := time.Now().UTC().Add(-time.Second)
|
||||
stillCooling.CooldownUntil = &expired
|
||||
if action, err := selector.markMissingThinking(ctx, stillCooling, time.Hour); err != nil || action != missingThinkingPenaltyDisabled {
|
||||
if action, err := selector.markMissingThinking(ctx, stillCooling, time.Hour, false); err != nil || action != missingThinkingPenaltyDisabled {
|
||||
t.Fatalf("second penalty = (%s, %v)", action, err)
|
||||
}
|
||||
second, err := accounts.Get(ctx, credential.ID)
|
||||
@@ -1657,7 +1657,7 @@ func TestMarkMissingThinkingCoolsThenDisables(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if action, err := selector.markMissingThinking(ctx, ok, time.Hour); err != nil || action != missingThinkingPenaltyCooled {
|
||||
if action, err := selector.markMissingThinking(ctx, ok, time.Hour, false); err != nil || action != missingThinkingPenaltyCooled {
|
||||
t.Fatalf("recovery penalty = (%s, %v)", action, err)
|
||||
}
|
||||
cooled, err := accounts.Get(ctx, ok.ID)
|
||||
@@ -1672,6 +1672,24 @@ func TestMarkMissingThinkingCoolsThenDisables(t *testing.T) {
|
||||
if kept.LastError != lastErrorMissingThinking || kept.CooldownUntil != nil || kept.FailureCount != 0 {
|
||||
t.Fatalf("success must keep thinking strike and clear cooldown, got %#v", kept)
|
||||
}
|
||||
|
||||
immediate, _, err := accounts.UpsertByIdentity(ctx, account.Credential{
|
||||
Provider: account.ProviderBuild, Name: "auto-disable", SourceKey: "auto-disable", EncryptedAccessToken: "encrypted", Enabled: true,
|
||||
AuthStatus: account.AuthStatusActive, Priority: 10, MaxConcurrent: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if action, err := selector.markMissingThinking(ctx, immediate, time.Hour, true); err != nil || action != missingThinkingPenaltyDisabled {
|
||||
t.Fatalf("auto-disable penalty = (%s, %v)", action, err)
|
||||
}
|
||||
disabled, err := accounts.Get(ctx, immediate.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if disabled.Enabled || disabled.LastError != lastErrorMissingThinkingDisabled || disabled.CooldownUntil != nil {
|
||||
t.Fatalf("auto-disable first strike = %#v", disabled)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarkFailureSoftNetworkCooldown(t *testing.T) {
|
||||
|
||||
@@ -1128,6 +1128,11 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
|
||||
}
|
||||
record.CreatedAt = now
|
||||
applyAuditEgress(&record, egressTrace, route.Provider)
|
||||
if err := budget.run("quality_disable", finalizationHealthBudget, func(stageCtx context.Context) error {
|
||||
return s.applyOutputSpeedPenalty(stageCtx, record, credential, holdCfg, input.ForcedEgressNodeID != 0)
|
||||
}); err != nil {
|
||||
s.logger.Error("quality_degraded_penalty_failed", "request_id", input.RequestID, "account_id", credential.ID, "error", err)
|
||||
}
|
||||
if supportsStoredResponses && operation == audit.OperationResponses && responseID != "" && successful {
|
||||
err := budget.run("response_ownership", finalizationOwnershipBudget, func(stageCtx context.Context) error {
|
||||
return s.responses.Save(stageCtx, inferencedomain.ResponseOwnership{ResponseID: responseID, AccountID: accountID, ClientKeyID: input.ClientKey.ID, ModelRouteID: route.ID, Provider: route.Provider, PromptCacheKey: ownershipPromptCacheKey, ReasoningReplayKey: reasoningReplayKey, ExpiresAt: now.Add(responseOwnershipTTL), CreatedAt: now, UpdatedAt: now})
|
||||
@@ -1554,7 +1559,7 @@ attemptLoop:
|
||||
} else if s.providers.SupportsCredentialRefresh(credential.Provider) && lastFailure.CredentialRejected {
|
||||
failureHandled = s.markReauthRequired(ctx, input.RequestID, credential, fmt.Sprintf("%s credential rejected", credential.Provider))
|
||||
}
|
||||
if lastFailure.AccountScoped && !failureHandled {
|
||||
if !failureHandled && (lastFailure.AccountScoped || credential.Provider == accountdomain.ProviderBuild && response.StatusCode == http.StatusForbidden) {
|
||||
s.selector.MarkFailure(ctx, credential, response.StatusCode, retryAfter)
|
||||
} else if !lastFailure.AccountScoped && response.StatusCode >= http.StatusInternalServerError {
|
||||
// Provider-wide 5xx responses should rotate this request and briefly
|
||||
@@ -1615,7 +1620,7 @@ attemptLoop:
|
||||
}
|
||||
commit := CommitQualityHold(verdict, qualityAccountAttempts-1, holdCfg.MaxAttempts, hasNextAccount, holdCfg.OnExhausted)
|
||||
if verdict == QualityWithhold {
|
||||
s.applyMissingThinkingPenalty(ctx, input.RequestID, credential, holdCfg.AccountCooldown)
|
||||
s.applyMissingThinkingPenalty(ctx, input.RequestID, credential, holdCfg.AccountCooldown, holdCfg.AutoDisable)
|
||||
}
|
||||
deferFailOpenAudit := commit.Action == QualityActionRetry && holdCfg.OnExhausted == qualityRetryFailOpen
|
||||
if commit.Audit && !deferFailOpenAudit {
|
||||
|
||||
@@ -253,6 +253,9 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) {
|
||||
t.Fatalf("ownership = %#v, err = %v", ownership, err)
|
||||
}
|
||||
|
||||
service.UpdateQualityRetry(QualityRetryRuntime{
|
||||
Enabled: true, AutoDisable: true, MinOutputTokens: 32, SoftTPS: 1, HardTPS: 2,
|
||||
})
|
||||
compacted, err := service.CreateResponse(ctx, Input{
|
||||
RequestID: "req-compact", ClientKey: clientKey, PublicModel: "grok-test", PromptCacheSeed: "claude-session",
|
||||
Body: []byte(`{"model":"grok-test","stream":true,"input":[{"role":"user","content":"continue"},{"type":"compaction_trigger"}]}`), Streaming: true,
|
||||
@@ -265,12 +268,25 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) {
|
||||
t.Fatal("first token marker is nil")
|
||||
}
|
||||
compacted.MarkFirstToken()
|
||||
compacted.Finalize(Usage{}, "resp-compact", "")
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
compacted.Finalize(Usage{Reported: true, OutputTokens: 120}, "resp-compact", "")
|
||||
_ = compacted.Body.Close()
|
||||
logs, total, err = auditRepo.List(ctx, 0, 10)
|
||||
if err != nil || total != 2 || logs[0].Operation != audit.OperationCompaction || !logs[0].Streaming || logs[0].FirstTokenMS == nil {
|
||||
t.Fatalf("compaction audit = %#v, total=%d, err=%v", logs, total, err)
|
||||
}
|
||||
assertCompactionSpeedExempt := func(record audit.Record) {
|
||||
t.Helper()
|
||||
class, _, _ := audit.ClassifyOutputSpeed(record.OutputTokens, record.ReasoningTokens, *record.FirstTokenMS, record.DurationMS, 1, 2, 1000, false)
|
||||
if class == "" {
|
||||
t.Fatal("compaction fixture must exceed the speed threshold")
|
||||
}
|
||||
credential, err := accountRepo.Get(ctx, second.ID)
|
||||
if err != nil || !credential.Enabled {
|
||||
t.Fatalf("compaction must not disable its account: %#v, err=%v", credential, err)
|
||||
}
|
||||
}
|
||||
assertCompactionSpeedExempt(logs[0])
|
||||
if _, err := responseRepo.Get(ctx, "resp-compact", clientKey.ID, time.Now().UTC()); !errors.Is(err, repository.ErrNotFound) {
|
||||
t.Fatalf("compaction response ownership err = %v", err)
|
||||
}
|
||||
@@ -279,7 +295,7 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) {
|
||||
// the quality hold and is labeled compaction only in the audit record, so
|
||||
// Provider routing and stored-response ownership must remain intact.
|
||||
service.UpdateQualityRetry(QualityRetryRuntime{
|
||||
Enabled: true, MaxAttempts: 2, MinOutputTokens: 32,
|
||||
Enabled: true, AutoDisable: true, MaxAttempts: 2, MinOutputTokens: 32, SoftTPS: 1, HardTPS: 2,
|
||||
OnExhausted: qualityRetryFailClosed, HoldTimeout: time.Second,
|
||||
})
|
||||
adapter.resetAttempts()
|
||||
@@ -298,7 +314,8 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) {
|
||||
t.Fatalf("TUI compaction body = %q", tuiBody)
|
||||
}
|
||||
tuiCompacted.MarkFirstToken()
|
||||
tuiCompacted.Finalize(Usage{}, "resp-tui-compact", "")
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
tuiCompacted.Finalize(Usage{Reported: true, OutputTokens: 120}, "resp-tui-compact", "")
|
||||
_ = tuiCompacted.Body.Close()
|
||||
if len(adapter.attempts) != 1 || adapter.lastOperation != string(audit.OperationResponses) {
|
||||
t.Fatalf("TUI compaction attempts = %#v, Provider operation = %q", adapter.attempts, adapter.lastOperation)
|
||||
@@ -307,6 +324,7 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) {
|
||||
if err != nil || total != 3 || logs[0].Operation != audit.OperationCompaction {
|
||||
t.Fatalf("TUI compaction audit = %#v, total=%d, err=%v", logs, total, err)
|
||||
}
|
||||
assertCompactionSpeedExempt(logs[0])
|
||||
if ownership, err := responseRepo.Get(ctx, "resp-tui-compact", clientKey.ID, time.Now().UTC()); err != nil || ownership.AccountID != second.ID {
|
||||
t.Fatalf("TUI compaction ownership = %#v, err=%v", ownership, err)
|
||||
}
|
||||
@@ -1963,7 +1981,7 @@ func TestParseFreeQuotaExhaustionCurrentBuildFreeLimit(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayUnknownBuildForbiddenTraversesAllAccountsWithoutCooldown(t *testing.T) {
|
||||
func TestGatewayUnknownBuildForbiddenTraversesAllAccountsWithCooldown(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "systemic-forbidden.db"))
|
||||
if err != nil {
|
||||
@@ -2033,8 +2051,8 @@ func TestGatewayUnknownBuildForbiddenTraversesAllAccountsWithoutCooldown(t *test
|
||||
if getErr != nil {
|
||||
t.Fatal(getErr)
|
||||
}
|
||||
if observed.FailureCount != 0 || observed.CooldownUntil != nil || observed.AuthStatus != account.AuthStatusActive {
|
||||
t.Fatalf("account %d was penalized after unknown 403: %#v", credential.ID, observed)
|
||||
if observed.FailureCount == 0 || observed.CooldownUntil == nil || observed.AuthStatus != account.AuthStatusActive {
|
||||
t.Fatalf("account %d was not cooled down after unknown Build 403: %#v", credential.ID, observed)
|
||||
}
|
||||
}
|
||||
logs, total, err := auditRepo.List(ctx, 0, 10)
|
||||
@@ -3946,8 +3964,8 @@ func TestGatewayUnknownBuildForbiddenRotatesWithoutPenalizingAccount(t *testing.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if observed.AuthStatus != account.AuthStatusActive || observed.FailureCount != 0 || observed.CooldownUntil != nil {
|
||||
t.Fatalf("unknown 403 penalized first account: %#v", observed)
|
||||
if observed.AuthStatus != account.AuthStatusActive || observed.FailureCount == 0 || observed.CooldownUntil == nil {
|
||||
t.Fatalf("unknown Build 403 did not cool down first account: %#v", observed)
|
||||
}
|
||||
candidates, err := accountRepo.ListRoutingCandidates(ctx, account.ProviderBuild, 0, model, "")
|
||||
if err != nil {
|
||||
|
||||
@@ -531,6 +531,26 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model
|
||||
|
||||
quotaMode := videoQuotaMode(route.Provider, s.providers.QuotaMode(route.Provider, route.UpstreamModel), job.Quality)
|
||||
quotaRefreshGroup := s.providers.QuotaRefreshGroup(route.Provider, route.UpstreamModel)
|
||||
// The initial creation path (selectSchedulableEligibleMediaRouteWithQuotaMode,
|
||||
// called from CreateVideoJob) always scopes account selection to the
|
||||
// requesting client key's AccountScope. A retry here must not silently
|
||||
// widen that: falling back to the unscoped account pool would let a key
|
||||
// restricted to e.g. free-tier/web-only accounts consume a premium or
|
||||
// console/build-only account's quota purely because its originally
|
||||
// pinned account had a transient failure.
|
||||
accountScope := clientkey.AccountScope{}
|
||||
if job.ClientKeyID > 0 {
|
||||
key, keyErr := s.clientKeys.Get(ctx, job.ClientKeyID)
|
||||
if keyErr != nil {
|
||||
if parent.Err() != nil {
|
||||
s.deferVideoJob(parent, job)
|
||||
return
|
||||
}
|
||||
s.failVideoJob(ctx, job, "client_key_unavailable", keyErr, 0, nil)
|
||||
return
|
||||
}
|
||||
accountScope = key.AccountScope()
|
||||
}
|
||||
attemptPolicy := s.videoAttemptPolicy()
|
||||
excluded := make(map[uint64]bool)
|
||||
forbiddenEgressRetried := make(map[uint64]bool)
|
||||
@@ -564,7 +584,7 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model
|
||||
}
|
||||
if lease == nil {
|
||||
if selection == nil {
|
||||
selection, err = s.selector.beginSelectionSession(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, "", excluded, false)
|
||||
selection, err = s.selector.beginSelectionSessionForKey(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, "", excluded, false, accountScope)
|
||||
}
|
||||
if err == nil {
|
||||
lease, err = selection.Acquire(ctx, excluded, false)
|
||||
|
||||
@@ -900,3 +900,130 @@ func TestVideoWebForbiddenRetriesPinnedAccountOnceThenFailsOver(t *testing.T) {
|
||||
t.Fatalf("unclassified failed job = %#v", stored)
|
||||
}
|
||||
}
|
||||
|
||||
// The initial creation path (CreateVideoJob) always scopes account selection
|
||||
// to the requesting client key's AccountScope. This confirms the retry path
|
||||
// inside runVideoJob does not silently widen that scope when the originally
|
||||
// pinned account fails: a key restricted to Super-tier accounts must never
|
||||
// fail over to a Free-tier account, even though one is available in the pool.
|
||||
func TestVideoRetryDoesNotEscapeClientKeyAccountScope(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "video-retry-scope.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
accountRepo := relational.NewAccountRepository(database)
|
||||
modelRepo := relational.NewModelRepository(database)
|
||||
auditRepo := relational.NewAuditRepository(database)
|
||||
mediaRepo := relational.NewMediaJobRepository(database)
|
||||
keyRepo := relational.NewClientKeyRepository(database)
|
||||
key, err := keyRepo.Create(ctx, clientkey.Key{
|
||||
Name: "video-scope-test", Prefix: "video-scope-test", SecretHash: strings.Repeat("b", 64),
|
||||
EncryptedSecret: "encrypted", Enabled: true, RPMLimit: 60, MaxConcurrent: 4,
|
||||
// Restricted to Super-tier Web accounts only.
|
||||
ProviderScope: clientkey.ProviderScopeWeb, TierScope: clientkey.TierScopeSuper,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
createAccount := func(name string, tier account.WebTier, priority int) account.Credential {
|
||||
credential, _, createErr := accountRepo.UpsertByIdentity(ctx, account.Credential{
|
||||
Provider: account.ProviderWeb, AuthType: account.AuthTypeSSO, WebTier: tier,
|
||||
Name: name, SourceKey: name, EncryptedAccessToken: name + "-token", ExpiresAt: time.Now().Add(time.Hour),
|
||||
Enabled: true, AuthStatus: account.AuthStatusActive, Priority: priority, MaxConcurrent: 1,
|
||||
})
|
||||
if createErr != nil {
|
||||
t.Fatal(createErr)
|
||||
}
|
||||
return credential
|
||||
}
|
||||
// pinned is the Super-tier account the job was originally created against
|
||||
// (in scope); outOfScope is a Free-tier account that must never be used
|
||||
// for this key, even as a failover target.
|
||||
pinned := createAccount("pinned-super", account.WebTierSuper, 200)
|
||||
outOfScope := createAccount("free-out-of-scope", account.WebTierBasic, 100)
|
||||
if err := modelRepo.UpsertDiscovered(ctx, account.ProviderWeb, []string{"grok-imagine-video"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, accountID := range []uint64{pinned.ID, outOfScope.ID} {
|
||||
if err := modelRepo.ReplaceAccountCapabilities(ctx, accountID, []string{"grok-imagine-video"}, time.Now().UTC()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
route, err := modelRepo.GetByProviderUpstream(ctx, account.ProviderWeb, "grok-imagine-video")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// The pinned account always fails (forbidden), forcing the retry path to
|
||||
// look for a replacement. Without the fix, that replacement search ignores
|
||||
// the client key's scope entirely and would pick the Free-tier account.
|
||||
adapter := &videoCreateFailoverAdapter{
|
||||
failures: map[uint64]int{pinned.ID: 999},
|
||||
status: http.StatusForbidden,
|
||||
}
|
||||
registry := provider.NewRegistry(adapter)
|
||||
sticky := memory.NewStickyStore()
|
||||
accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil)
|
||||
selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute)
|
||||
service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(keyRepo, nil, nil, 60, 4, nil), registry, selector, nil, 3)
|
||||
service.ConfigureMedia(mediaRepo, 1)
|
||||
service.UpdateVideoMaxAttempts(3)
|
||||
|
||||
now := time.Now().UTC()
|
||||
job := media.Job{
|
||||
ID: "video_scope_retry", RequestID: "request-video-scope-retry", ClientKeyID: key.ID, ClientKeyName: key.Name,
|
||||
AccountID: pinned.ID, AccountName: pinned.Name, Provider: string(account.ProviderWeb),
|
||||
Model: route.PublicID, ModelRouteID: route.ID, UpstreamModel: route.UpstreamModel,
|
||||
Operation: provider.VideoOperationGenerate, Prompt: "test", Seconds: 5, Quality: "720p",
|
||||
Status: media.StatusInProgress, InputJSON: `{}`, CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
t.Run("worker shutdown during key lookup preserves recovery", func(t *testing.T) {
|
||||
shutdownJob := job
|
||||
shutdownJob.ID = "video_scope_worker_shutdown"
|
||||
shutdownJob.RequestID = "request-video-scope-worker-shutdown"
|
||||
if err := mediaRepo.CreateMediaJob(ctx, shutdownJob); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
workerCtx, stopWorker := context.WithCancel(ctx)
|
||||
stopWorker()
|
||||
service.runVideoJob(workerCtx, shutdownJob, route)
|
||||
|
||||
stored, err := mediaRepo.GetMediaJob(ctx, shutdownJob.ID, key.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored.Status != media.StatusInProgress || stored.LeaseUntil == nil || !stored.LeaseUntil.After(time.Now().UTC()) {
|
||||
t.Fatalf("job must remain eligible for recovery after worker shutdown, got %#v", stored)
|
||||
}
|
||||
if stored.ErrorCode != "" || stored.ErrorMessage != "" || stored.CompletedAt != nil || stored.UsageRecordedAt != nil {
|
||||
t.Fatalf("worker shutdown must not finalize the job, got %#v", stored)
|
||||
}
|
||||
if attempts := adapter.Attempts(); len(attempts) != 0 {
|
||||
t.Fatalf("worker shutdown must not invoke the upstream, got attempts %#v", attempts)
|
||||
}
|
||||
})
|
||||
|
||||
if err := mediaRepo.CreateMediaJob(ctx, job); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.runVideoJob(ctx, job, route)
|
||||
|
||||
for _, attemptedAccountID := range adapter.Attempts() {
|
||||
if attemptedAccountID == outOfScope.ID {
|
||||
t.Fatalf("out-of-scope Free-tier account %d was used for a key scoped to Super tier only", outOfScope.ID)
|
||||
}
|
||||
}
|
||||
stored, err := mediaRepo.GetMediaJob(ctx, job.ID, job.ClientKeyID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored.Status != media.StatusFailed {
|
||||
t.Fatalf("expected the job to fail rather than complete via an out-of-scope account, got %#v", stored)
|
||||
}
|
||||
}
|
||||
@@ -377,8 +377,12 @@ func (s *Service) validateBoundAccounts(ctx context.Context, providerValue accou
|
||||
return result, nil
|
||||
}
|
||||
values, _, err := s.accounts.List(ctx, repository.AccountListQuery{
|
||||
Page: repository.PageQuery{Offset: 0, Limit: 1000},
|
||||
Filter: repository.AccountListFilter{Provider: string(providerValue)},
|
||||
Page: repository.PageQuery{Offset: 0, Limit: len(result)},
|
||||
Filter: repository.AccountListFilter{
|
||||
Provider: string(providerValue),
|
||||
RestrictIDs: true,
|
||||
AccountIDs: result,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -111,6 +111,57 @@ func TestNormalizeBatchIDsAllowsGroupedRouteExpansion(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateBoundAccountsSupportsAccountsFilteredByIDs(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "model-bound-accounts.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
modelRepo := relational.NewModelRepository(database)
|
||||
accountRepo := relational.NewAccountRepository(database)
|
||||
registry := provider.NewRegistry(&modelRouteAdapter{modelCapabilityAdapter: &modelCapabilityAdapter{}})
|
||||
service := NewService(modelRepo, accountRepo, nil, registry)
|
||||
|
||||
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
encrypted, err := cipher.Encrypt("access-token")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
targetAccount, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{
|
||||
Provider: account.ProviderBuild,
|
||||
Name: "target-account",
|
||||
SourceKey: "target-account",
|
||||
EncryptedAccessToken: encrypted,
|
||||
ExpiresAt: time.Now().Add(time.Hour),
|
||||
AuthStatus: account.AuthStatusActive,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
bound, err := service.validateBoundAccounts(ctx, account.ProviderBuild, []uint64{targetAccount.ID})
|
||||
if err != nil {
|
||||
t.Fatalf("validateBoundAccounts failed: %v", err)
|
||||
}
|
||||
if len(bound) != 1 || bound[0] != targetAccount.ID {
|
||||
t.Fatalf("bound accounts = %v, want [%d]", bound, targetAccount.ID)
|
||||
}
|
||||
|
||||
_, err = service.validateBoundAccounts(ctx, account.ProviderWeb, []uint64{targetAccount.ID})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for mismatched provider, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func TestSyncAggregatesCapabilitiesFromAllAccounts(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "model-sync.db"))
|
||||
|
||||
@@ -137,8 +137,9 @@ type ClientKeyDefaultsConfig struct {
|
||||
|
||||
// AccountsConfig 是管理接口使用的账号池维护策略输入。
|
||||
type AccountsConfig struct {
|
||||
MarkBuildForbiddenReauth bool
|
||||
BuildForbiddenReauthCodes []string
|
||||
AutoDisableDegradedAccounts bool
|
||||
MarkBuildForbiddenReauth bool
|
||||
BuildForbiddenReauthCodes []string
|
||||
// ExcludeBuildBotFlaggedFromScheduling drops bot-risk Build accounts from scheduling only.
|
||||
ExcludeBuildBotFlaggedFromScheduling bool
|
||||
AutoCleanReauthEnabled bool
|
||||
@@ -151,6 +152,8 @@ type AccountsConfig struct {
|
||||
BuildForbiddenReauthCodesProvided bool
|
||||
// ExcludeBuildBotFlaggedFromSchedulingProvided preserves the value when an older management client omits the field.
|
||||
ExcludeBuildBotFlaggedFromSchedulingProvided bool
|
||||
// AutoDisableDegradedAccountsProvided preserves config.yaml when an older management client omits the field.
|
||||
AutoDisableDegradedAccountsProvided bool
|
||||
}
|
||||
|
||||
// EditableConfig 聚合管理端允许修改的运行参数。
|
||||
@@ -439,12 +442,16 @@ func applyDomainConfig(base config.Config, value settingsdomain.Config) config.C
|
||||
base.Accounts.BuildForbiddenReauthCodes = append([]string(nil), value.Accounts.BuildForbiddenReauthCodes...)
|
||||
}
|
||||
base.Accounts.ExcludeBuildBotFlaggedFromScheduling = value.Accounts.ExcludeBuildBotFlaggedFromScheduling
|
||||
if value.Accounts.AutoDisableDegradedAccounts != nil {
|
||||
base.QualityGuard.RequestRetry.AutoDisable = *value.Accounts.AutoDisableDegradedAccounts
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
func toDomainConfig(value config.Config) settingsdomain.Config {
|
||||
randomDelay := value.Batch.RandomDelay.Value()
|
||||
accountIsolatedConnections := value.Routing.AccountIsolatedConnections
|
||||
autoDisableDegradedAccounts := value.QualityGuard.RequestRetry.AutoDisable
|
||||
return settingsdomain.Config{
|
||||
Server: settingsdomain.ServerConfig{MaxConcurrentRequests: value.Server.MaxConcurrentRequests},
|
||||
ProviderBuild: settingsdomain.ProviderBuildConfig{
|
||||
@@ -502,6 +509,7 @@ func toDomainConfig(value config.Config) settingsdomain.Config {
|
||||
RPMLimit: value.ClientKeyDefaults.RPMLimit, MaxConcurrent: value.ClientKeyDefaults.MaxConcurrent,
|
||||
},
|
||||
Accounts: settingsdomain.AccountsConfig{
|
||||
AutoDisableDegradedAccounts: &autoDisableDegradedAccounts,
|
||||
MarkBuildForbiddenReauth: value.Accounts.MarkBuildForbiddenReauth,
|
||||
BuildForbiddenReauthCodes: append([]string(nil), value.Accounts.BuildForbiddenReauthCodes...),
|
||||
ExcludeBuildBotFlaggedFromScheduling: value.Accounts.ExcludeBuildBotFlaggedFromScheduling,
|
||||
@@ -600,6 +608,9 @@ func mergeEditable(current config.Config, input EditableConfig) (config.Config,
|
||||
next.ClientKeyDefaults.RPMLimit = input.ClientKeyDefaults.RPMLimit
|
||||
next.ClientKeyDefaults.MaxConcurrent = input.ClientKeyDefaults.MaxConcurrent
|
||||
if input.AccountsProvided {
|
||||
if input.Accounts.AutoDisableDegradedAccountsProvided {
|
||||
next.QualityGuard.RequestRetry.AutoDisable = input.Accounts.AutoDisableDegradedAccounts
|
||||
}
|
||||
if input.Accounts.MarkBuildForbiddenReauthProvided {
|
||||
next.Accounts.MarkBuildForbiddenReauth = input.Accounts.MarkBuildForbiddenReauth
|
||||
}
|
||||
@@ -740,6 +751,8 @@ func toEditable(cfg config.Config) EditableConfig {
|
||||
},
|
||||
ClientKeyDefaults: ClientKeyDefaultsConfig{RPMLimit: cfg.ClientKeyDefaults.RPMLimit, MaxConcurrent: cfg.ClientKeyDefaults.MaxConcurrent},
|
||||
Accounts: AccountsConfig{
|
||||
AutoDisableDegradedAccounts: cfg.QualityGuard.RequestRetry.AutoDisable,
|
||||
AutoDisableDegradedAccountsProvided: true,
|
||||
MarkBuildForbiddenReauth: cfg.Accounts.MarkBuildForbiddenReauth,
|
||||
BuildForbiddenReauthCodes: append([]string(nil), cfg.Accounts.BuildForbiddenReauthCodes...),
|
||||
ExcludeBuildBotFlaggedFromScheduling: cfg.Accounts.ExcludeBuildBotFlaggedFromScheduling,
|
||||
|
||||
@@ -835,6 +835,50 @@ func TestUpdateAccountsAutoCleanRoundTrip(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateAutoDisableDegradedAccountsRoundTrip(t *testing.T) {
|
||||
cfg := testConfig(t)
|
||||
cfg.QualityGuard.RequestRetry.AutoDisable = false
|
||||
repo := &runtimeSettingsRepositoryStub{}
|
||||
var applied config.Config
|
||||
service := NewService(cfg, time.Time{}, 0, repo, nil, func(next config.Config) { applied = next })
|
||||
input := service.Get().Config
|
||||
input.Accounts.AutoDisableDegradedAccounts = true
|
||||
input.Accounts.AutoDisableDegradedAccountsProvided = true
|
||||
|
||||
snapshot, err := service.Update(context.Background(), 0, input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !applied.QualityGuard.RequestRetry.AutoDisable || !snapshot.Config.Accounts.AutoDisableDegradedAccounts {
|
||||
t.Fatalf("auto-disable switch was not applied: applied=%v snapshot=%#v", applied.QualityGuard.RequestRetry.AutoDisable, snapshot.Config.Accounts)
|
||||
}
|
||||
if repo.value.Accounts.AutoDisableDegradedAccounts == nil || !*repo.value.Accounts.AutoDisableDegradedAccounts {
|
||||
t.Fatalf("auto-disable switch was not persisted: %#v", repo.value.Accounts)
|
||||
}
|
||||
reloaded, _, _, err := LoadPersisted(context.Background(), cfg, repo)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reloaded.QualityGuard.RequestRetry.AutoDisable {
|
||||
t.Fatal("persisted auto-disable switch was not restored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadPersistedKeepsYAMLAutoDisableForOlderPayload(t *testing.T) {
|
||||
cfg := testConfig(t)
|
||||
cfg.QualityGuard.RequestRetry.AutoDisable = true
|
||||
value := toDomainConfig(cfg)
|
||||
value.Accounts.AutoDisableDegradedAccounts = nil
|
||||
|
||||
loaded, _, _, err := LoadPersisted(context.Background(), cfg, &runtimeSettingsRepositoryStub{value: value, found: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !loaded.QualityGuard.RequestRetry.AutoDisable {
|
||||
t.Fatal("legacy runtime settings overrode config.yaml autoDisable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateWithoutAccountsPreservesCurrentAutoCleanConfig(t *testing.T) {
|
||||
cfg := testConfig(t)
|
||||
cfg.Accounts.AutoCleanReauthEnabled = true
|
||||
|
||||
@@ -147,6 +147,9 @@ type ClientKeyDefaultsConfig struct {
|
||||
|
||||
// AccountsConfig 定义账号池后台维护策略;默认全部关闭。
|
||||
type AccountsConfig struct {
|
||||
// AutoDisableDegradedAccounts is optional so legacy persisted settings keep
|
||||
// the qualityGuard.requestRetry.autoDisable value supplied by config.yaml.
|
||||
AutoDisableDegradedAccounts *bool
|
||||
// MarkBuildForbiddenReauth marks high-confidence Grok Build permission denials as requiring reauthorization.
|
||||
MarkBuildForbiddenReauth bool
|
||||
// BuildForbiddenReauthCodes contains exact upstream error codes that opt into account invalidation.
|
||||
|
||||
@@ -295,6 +295,8 @@ type QualityGuardRequestRetryConfig struct {
|
||||
HoldTimeout Duration `yaml:"holdTimeout"`
|
||||
MinOutputTokens int `yaml:"minOutputTokens"`
|
||||
OnExhausted string `yaml:"onExhausted"`
|
||||
// AutoDisable also enables request-path detection without changing Enabled.
|
||||
AutoDisable bool `yaml:"autoDisable"`
|
||||
AccountCooldown Duration `yaml:"accountCooldown"`
|
||||
// IdleAccountCooldown cools an account after a truly empty upstream
|
||||
// stream. Independent of accountCooldown (missing-thinking). Zero uses 15m.
|
||||
@@ -740,6 +742,15 @@ func validateQualityGuardConfig(value QualityGuardConfig) error {
|
||||
if err := validateQualityGuardRequestRetry(value.RequestRetry); err != nil {
|
||||
return err
|
||||
}
|
||||
// Automatic account disabling uses these thresholds without the sidecar.
|
||||
if value.Enabled || value.RequestRetry.AutoDisable {
|
||||
if value.SoftTPS < 1 || value.HardTPS <= value.SoftTPS || value.HardTPS > 10000 {
|
||||
return errors.New("qualityGuard TPS 阈值无效")
|
||||
}
|
||||
if value.MinimumGenerationWindow.Value() < time.Millisecond || value.MinimumGenerationWindow.Value() > 2*time.Minute {
|
||||
return errors.New("qualityGuard.minimumGenerationWindow 必须在 1 毫秒到 2 分钟之间")
|
||||
}
|
||||
}
|
||||
if !value.Enabled {
|
||||
return nil
|
||||
}
|
||||
@@ -758,9 +769,6 @@ func validateQualityGuardConfig(value QualityGuardConfig) error {
|
||||
if value.PassivePollInterval.Value() < time.Second || value.PassivePollInterval.Value() > 5*time.Minute {
|
||||
return errors.New("qualityGuard.passivePollInterval 必须在 1 秒到 5 分钟之间")
|
||||
}
|
||||
if value.SoftTPS < 1 || value.HardTPS <= value.SoftTPS || value.HardTPS > 10000 {
|
||||
return errors.New("qualityGuard TPS 阈值无效")
|
||||
}
|
||||
if value.ConsecutiveSoft < 1 || value.ConsecutiveSoft > 20 || value.ConsecutiveErrors < 1 || value.ConsecutiveErrors > 20 {
|
||||
return errors.New("qualityGuard 连续异常次数必须在 1 到 20 之间")
|
||||
}
|
||||
@@ -773,9 +781,6 @@ func validateQualityGuardConfig(value QualityGuardConfig) error {
|
||||
if value.MaxOutputTokens < 32 || value.MaxOutputTokens > 4096 {
|
||||
return errors.New("qualityGuard.maxOutputTokens 必须在 32 到 4096 之间")
|
||||
}
|
||||
if value.MinimumGenerationWindow.Value() < time.Millisecond || value.MinimumGenerationWindow.Value() > 2*time.Minute {
|
||||
return errors.New("qualityGuard.minimumGenerationWindow 必须在 1 毫秒到 2 分钟之间")
|
||||
}
|
||||
if value.RotationTimeout.Value() < 5*time.Second || value.RotationTimeout.Value() > 5*time.Minute {
|
||||
return errors.New("qualityGuard.rotationTimeout 必须在 5 秒到 5 分钟之间")
|
||||
}
|
||||
@@ -792,7 +797,7 @@ func validateQualityGuardConfig(value QualityGuardConfig) error {
|
||||
}
|
||||
|
||||
func validateQualityGuardRequestRetry(value QualityGuardRequestRetryConfig) error {
|
||||
if !value.Enabled {
|
||||
if !value.Enabled && !value.AutoDisable {
|
||||
return nil
|
||||
}
|
||||
if value.MaxAttempts != 0 && (value.MaxAttempts < 1 || value.MaxAttempts > 6) {
|
||||
|
||||
@@ -203,6 +203,9 @@ qualityGuard:
|
||||
nodeIDs: [2, 9]
|
||||
minimumHealthyNodes: 1
|
||||
activeInterval: 45m
|
||||
requestRetry:
|
||||
enabled: true
|
||||
autoDisable: true
|
||||
`)
|
||||
if err := os.WriteFile(path, data, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -215,7 +218,7 @@ qualityGuard:
|
||||
t.Fatalf("qualityGuard = %#v", value.QualityGuard)
|
||||
}
|
||||
retry := value.QualityGuard.RequestRetry
|
||||
if retry.Enabled || retry.MaxAttempts != 6 || retry.HoldTimeout.Value() != 30*time.Second || retry.MinOutputTokens != 8 || retry.OnExhausted != "fail_closed" || retry.AccountCooldown.Value() != 12*time.Hour {
|
||||
if !retry.Enabled || !retry.AutoDisable || retry.MaxAttempts != 6 || retry.HoldTimeout.Value() != 30*time.Second || retry.MinOutputTokens != 8 || retry.OnExhausted != "fail_closed" || retry.AccountCooldown.Value() != 12*time.Hour || retry.IdleAccountCooldown.Value() != 15*time.Minute {
|
||||
t.Fatalf("loaded requestRetry defaults = %#v", retry)
|
||||
}
|
||||
}
|
||||
@@ -223,11 +226,39 @@ qualityGuard:
|
||||
func TestDefaultQualityGuardRequestRetryContract(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := defaultConfig().QualityGuard.RequestRetry
|
||||
if got.Enabled || got.MaxAttempts != 6 || got.HoldTimeout.Value() != 30*time.Second || got.MinOutputTokens != 8 || got.OnExhausted != "fail_closed" || got.AccountCooldown.Value() != 12*time.Hour || got.IdleAccountCooldown.Value() != 15*time.Minute || got.MinEncryptedBytes != 256 || got.EncryptedBytesPerReasoningToken != 4 {
|
||||
if got.Enabled || got.AutoDisable || got.MaxAttempts != 6 || got.HoldTimeout.Value() != 30*time.Second || got.MinOutputTokens != 8 || got.OnExhausted != "fail_closed" || got.AccountCooldown.Value() != 12*time.Hour || got.IdleAccountCooldown.Value() != 15*time.Minute || got.MinEncryptedBytes != 256 || got.EncryptedBytesPerReasoningToken != 4 {
|
||||
t.Fatalf("requestRetry defaults = %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoDisableValidatesRequestPolicyWithoutSidecar(t *testing.T) {
|
||||
t.Parallel()
|
||||
base := defaultConfig().QualityGuard
|
||||
base.RequestRetry.AutoDisable = true
|
||||
if err := validateQualityGuardConfig(base); err != nil {
|
||||
t.Fatalf("auto-disable with default policy: %v", err)
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
change func(*QualityGuardConfig)
|
||||
}{
|
||||
{"retry limit", func(c *QualityGuardConfig) { c.RequestRetry.MaxAttempts = 7 }},
|
||||
{"hold timeout", func(c *QualityGuardConfig) { c.RequestRetry.HoldTimeout = Duration(time.Minute) }},
|
||||
{"output floor", func(c *QualityGuardConfig) { c.RequestRetry.MinOutputTokens = 1 }},
|
||||
{"soft TPS", func(c *QualityGuardConfig) { c.SoftTPS = 0 }},
|
||||
{"hard TPS", func(c *QualityGuardConfig) { c.HardTPS = c.SoftTPS }},
|
||||
{"generation window", func(c *QualityGuardConfig) { c.MinimumGenerationWindow = 0 }},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
cfg := base
|
||||
test.change(&cfg)
|
||||
if err := validateQualityGuardConfig(cfg); err == nil {
|
||||
t.Fatal("invalid active request-path policy must be rejected even when the sidecar is disabled")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestQualityGuardRequestRetryAccountCooldownBounds(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, test := range []struct {
|
||||
|
||||
@@ -65,6 +65,7 @@ type imagineSlot struct {
|
||||
}
|
||||
|
||||
type imagineCollector struct {
|
||||
requestID string
|
||||
slots map[string]*imagineSlot
|
||||
terminalCount int
|
||||
}
|
||||
@@ -88,8 +89,12 @@ func imageGenerationUserError(message, param, code string) (*provider.Response,
|
||||
}}), nil
|
||||
}
|
||||
|
||||
func newImagineCollector() *imagineCollector {
|
||||
return &imagineCollector{slots: make(map[string]*imagineSlot)}
|
||||
func newImagineCollector(requestID ...string) *imagineCollector {
|
||||
var reqID string
|
||||
if len(requestID) > 0 {
|
||||
reqID = strings.TrimSpace(requestID[0])
|
||||
}
|
||||
return &imagineCollector{requestID: reqID, slots: make(map[string]*imagineSlot)}
|
||||
}
|
||||
|
||||
func (c *imagineCollector) Accept(message map[string]any) {
|
||||
@@ -97,6 +102,17 @@ func (c *imagineCollector) Accept(message map[string]any) {
|
||||
if typeName != "image" && typeName != "json" {
|
||||
return
|
||||
}
|
||||
if c.requestID != "" {
|
||||
msgReqID := firstString(message, "requestId", "request_id", "req_id", "reqId")
|
||||
if msgReqID == "" {
|
||||
if item, ok := message["item"].(map[string]any); ok {
|
||||
msgReqID = firstString(item, "requestId", "request_id")
|
||||
}
|
||||
}
|
||||
if msgReqID != c.requestID {
|
||||
return
|
||||
}
|
||||
}
|
||||
rawURL, _ := message["url"].(string)
|
||||
imageID := firstString(message, "image_id", "job_id", "id")
|
||||
if imageID == "" && rawURL != "" {
|
||||
@@ -706,7 +722,8 @@ func (a *Adapter) generateWSImageAttempt(ctx context.Context, request provider.I
|
||||
a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, 0, err)
|
||||
return nil, err
|
||||
}
|
||||
if err := connection.WriteJSON(imagineRequestMessage(newWebID("img"), request.Prompt, ratio, cfg.AllowNSFW, modelConfig.Pro, modelConfig.ExpectedCount)); err != nil {
|
||||
reqID := newWebID("img")
|
||||
if err := connection.WriteJSON(imagineRequestMessage(reqID, request.Prompt, ratio, cfg.AllowNSFW, modelConfig.Pro, modelConfig.ExpectedCount)); err != nil {
|
||||
a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, 0, err)
|
||||
return nil, err
|
||||
}
|
||||
@@ -715,11 +732,11 @@ func (a *Adapter) generateWSImageAttempt(ctx context.Context, request provider.I
|
||||
streamCtx, cancel := context.WithCancel(ctx)
|
||||
leaseOwned = false
|
||||
connectionOwned = false
|
||||
go a.streamImagineImages(streamCtx, writer, connection, lease, request.Credential, count, request.PartialImages, modelConfig)
|
||||
go a.streamImagineImages(streamCtx, writer, connection, lease, request.Credential, count, request.PartialImages, modelConfig, reqID)
|
||||
return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: &cancelBody{ReadCloser: reader, cancel: cancel}, QuotaUnits: count}, nil
|
||||
}
|
||||
|
||||
collector := newImagineCollector()
|
||||
collector := newImagineCollector(reqID)
|
||||
for collector.UsableCount() < count && !collector.Done(modelConfig.ExpectedCount) {
|
||||
messageType, data, readErr := connection.ReadMessage()
|
||||
if readErr != nil {
|
||||
@@ -1521,7 +1538,7 @@ func (a *Adapter) imageBytes(ctx context.Context, credential account.Credential,
|
||||
return a.downloadImage(ctx, credential, image.URL)
|
||||
}
|
||||
|
||||
func (a *Adapter) streamImagineImages(ctx context.Context, writer *io.PipeWriter, connection *websocket.Conn, lease *egress.Lease, credential account.Credential, count, partialImages int, modelConfig imagineModelConfig) {
|
||||
func (a *Adapter) streamImagineImages(ctx context.Context, writer *io.PipeWriter, connection *websocket.Conn, lease *egress.Lease, credential account.Credential, count, partialImages int, modelConfig imagineModelConfig, requestID ...string) {
|
||||
defer lease.Release()
|
||||
defer connection.Close()
|
||||
done := make(chan struct{})
|
||||
@@ -1533,7 +1550,7 @@ func (a *Adapter) streamImagineImages(ctx context.Context, writer *io.PipeWriter
|
||||
case <-done:
|
||||
}
|
||||
}()
|
||||
collector := newImagineCollector()
|
||||
collector := newImagineCollector(requestID...)
|
||||
emitted := 0
|
||||
partialIndex := 0
|
||||
for emitted < count {
|
||||
|
||||
@@ -88,18 +88,33 @@ func TestGenerateWSImageReacquiresAfterChallengeHandshake(t *testing.T) {
|
||||
return
|
||||
}
|
||||
defer connection.Close()
|
||||
var requestIDForResponse string
|
||||
for range 2 {
|
||||
var message map[string]any
|
||||
if err := connection.ReadJSON(&message); err != nil {
|
||||
t.Errorf("read Imagine request: %v", err)
|
||||
return
|
||||
}
|
||||
if item, ok := message["item"].(map[string]any); ok {
|
||||
if content, ok := item["content"].([]any); ok && len(content) > 0 {
|
||||
if first, ok := content[0].(map[string]any); ok {
|
||||
if requestID, ok := first["requestId"].(string); ok && requestID != "" {
|
||||
// The Imagine collector binds response frames to the request ID.
|
||||
requestIDForResponse = requestID
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if requestIDForResponse == "" {
|
||||
t.Error("Imagine request did not include requestId")
|
||||
return
|
||||
}
|
||||
_ = connection.WriteJSON(map[string]any{
|
||||
"type": "image", "id": "image-1", "blob": "aW1hZ2U=", "percentage_complete": 100, "grid_index": 0,
|
||||
"type": "image", "id": "image-1", "requestId": requestIDForResponse, "blob": "aW1hZ2U=", "percentage_complete": 100, "grid_index": 0,
|
||||
})
|
||||
_ = connection.WriteJSON(map[string]any{
|
||||
"type": "json", "id": "image-1", "current_status": "completed", "moderated": false, "order": 0,
|
||||
"type": "json", "id": "image-1", "requestId": requestIDForResponse, "current_status": "completed", "moderated": false, "order": 0,
|
||||
})
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
@@ -1786,3 +1786,73 @@ func MarshalJSONBytes(value any) []byte {
|
||||
data, _ := json.Marshal(value)
|
||||
return data
|
||||
}
|
||||
|
||||
func TestImagineCollectorFiltersMismatchedRequestIDs(t *testing.T) {
|
||||
reqID := "img_target_12345"
|
||||
collector := newImagineCollector(reqID)
|
||||
|
||||
// 1. Frame from another/stale request with mismatched requestId must be ignored
|
||||
collector.Accept(map[string]any{
|
||||
"type": "image",
|
||||
"id": "stale-image-1",
|
||||
"requestId": "img_stale_99999",
|
||||
"url": "https://imagine-public.x.ai/imagine-public/images/stale.jpg",
|
||||
"percentage_complete": 100.0,
|
||||
})
|
||||
collector.Accept(map[string]any{
|
||||
"type": "json",
|
||||
"image_id": "stale-image-1",
|
||||
"requestId": "img_stale_99999",
|
||||
"current_status": "completed",
|
||||
"moderated": false,
|
||||
})
|
||||
|
||||
if collector.UsableCount() != 0 || len(collector.Images()) != 0 {
|
||||
t.Fatalf("collector accepted stale image with mismatched requestId: %#v", collector.Images())
|
||||
}
|
||||
|
||||
// 2. Nested item.requestId must also be matched
|
||||
staleNestedCollector := newImagineCollector(reqID)
|
||||
staleNestedCollector.Accept(map[string]any{
|
||||
"type": "image",
|
||||
"id": "stale-nested-1",
|
||||
"item": map[string]any{
|
||||
"requestId": "img_stale_88888",
|
||||
},
|
||||
"url": "https://imagine-public.x.ai/imagine-public/images/stale2.jpg",
|
||||
"percentage_complete": 100.0,
|
||||
})
|
||||
staleNestedCollector.Accept(map[string]any{
|
||||
"type": "json",
|
||||
"image_id": "stale-nested-1",
|
||||
"item": map[string]any{"requestId": "img_stale_88888"},
|
||||
"current_status": "completed",
|
||||
"moderated": false,
|
||||
})
|
||||
if len(staleNestedCollector.Images()) != 0 || staleNestedCollector.Done(1) {
|
||||
t.Fatalf("collector accepted nested stale image")
|
||||
}
|
||||
|
||||
// 3. Matching target request frames are accepted normally
|
||||
collector.Accept(map[string]any{
|
||||
"type": "image",
|
||||
"id": "target-image-1",
|
||||
"requestId": reqID,
|
||||
"url": "https://imagine-public.x.ai/imagine-public/images/target.jpg",
|
||||
"percentage_complete": 100.0,
|
||||
})
|
||||
collector.Accept(map[string]any{
|
||||
"type": "json",
|
||||
"image_id": "target-image-1",
|
||||
"requestId": reqID,
|
||||
"current_status": "completed",
|
||||
"moderated": false,
|
||||
})
|
||||
|
||||
if collector.UsableCount() != 1 || len(collector.Images()) != 1 {
|
||||
t.Fatalf("collector failed to accept matching target image: %#v", collector.Images())
|
||||
}
|
||||
if collector.Images()[0].ID != "target-image-1" {
|
||||
t.Fatalf("expected target-image-1, got %s", collector.Images()[0].ID)
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -19,6 +20,7 @@ import (
|
||||
infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/security"
|
||||
"golang.org/x/net/html"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -62,7 +64,7 @@ func (a *Adapter) ConvertToBuild(ctx context.Context, credential accountdomain.C
|
||||
defer cancel()
|
||||
flow := &ssoBuildFlow{
|
||||
client: lease, userAgent: lease.UserAgent,
|
||||
cookies: map[string]string{"sso": token, "sso-rw": token},
|
||||
cookies: ssoBuildCookies(token, lease.CFCookies),
|
||||
}
|
||||
seed, err := flow.convert(requestCtx, credential)
|
||||
if err != nil {
|
||||
@@ -101,9 +103,11 @@ func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Cre
|
||||
device.ExpiresIn = 1800
|
||||
}
|
||||
|
||||
// verify/approve 已在 auth.x.ai 完成状态变更。重定向目标只是结果页,
|
||||
// 因此不访问 accounts.x.ai,直接解析首个 3xx Location 的状态路径。
|
||||
status, finalURL, _, err := f.doWithFollow(ctx, http.MethodPost, ssoVerifyURL, url.Values{"user_code": {device.UserCode}}, false)
|
||||
// verify → consent。xAI 2025-09 起在 device 授权流程加入防伪令牌:consent 页面内嵌一个
|
||||
// 一次性 consent_token(ES256 JWT,typ=consent+jwt),approve 必须回传它,否则返回
|
||||
// 403「Request could not be verified」。因此这里不能只看 3xx 的状态路径,还要取到
|
||||
// consent 页面来解析该令牌。
|
||||
status, finalURL, verifyBody, err := f.doWithFollow(ctx, http.MethodPost, ssoVerifyURL, url.Values{"user_code": {device.UserCode}}, false)
|
||||
if err != nil {
|
||||
return provider.CredentialSeed{}, err
|
||||
}
|
||||
@@ -119,9 +123,37 @@ func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Cre
|
||||
}
|
||||
return provider.CredentialSeed{}, fmt.Errorf("SSO 自动验证 Device Flow 失败")
|
||||
}
|
||||
status, finalURL, _, err = f.doWithFollow(ctx, http.MethodPost, ssoApproveURL, url.Values{
|
||||
consentPageURL := finalURL
|
||||
|
||||
// verify 以 3xx 跳转到 consent 时响应体为空,需要 GET consent 页面本身来解析 consent_token。
|
||||
consentToken := extractConsentToken(verifyBody)
|
||||
if consentToken == "" {
|
||||
consentStatus, _, consentBody, cerr := f.do(ctx, http.MethodGet, consentPageURL, nil)
|
||||
if cerr != nil {
|
||||
return provider.CredentialSeed{}, fmt.Errorf("获取 xAI consent 页面失败: %w", cerr)
|
||||
}
|
||||
if consentStatus < 200 || consentStatus >= 300 {
|
||||
return provider.CredentialSeed{}, fmt.Errorf("获取 xAI consent 页面失败: %w", conversionHTTPError{status: consentStatus})
|
||||
}
|
||||
consentToken = extractConsentToken(consentBody)
|
||||
}
|
||||
if !consentTokenMatchesDevice(consentToken, device.DeviceCode) {
|
||||
return provider.CredentialSeed{}, fmt.Errorf("SSO 自动批准 Device Flow 失败:未获取 consent_token")
|
||||
}
|
||||
|
||||
status, finalURL, _, err = f.doWithFollowHeaders(ctx, http.MethodPost, ssoApproveURL, url.Values{
|
||||
"user_code": {device.UserCode}, "action": {"allow"}, "principal_type": {"User"}, "principal_id": {""},
|
||||
}, false)
|
||||
"consent_token": {consentToken},
|
||||
}, false, map[string]string{
|
||||
"Origin": "https://accounts.x.ai",
|
||||
"Referer": consentPageURL,
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
||||
"Sec-Fetch-Dest": "document",
|
||||
"Sec-Fetch-Mode": "navigate",
|
||||
"Sec-Fetch-Site": "same-site",
|
||||
"Sec-Fetch-User": "?1",
|
||||
"Upgrade-Insecure-Requests": "1",
|
||||
})
|
||||
if err != nil {
|
||||
return provider.CredentialSeed{}, err
|
||||
}
|
||||
@@ -223,6 +255,10 @@ func (f *ssoBuildFlow) do(ctx context.Context, method, endpoint string, form url
|
||||
// doWithFollow 在 follow=false 时遇到 3xx 直接返回状态码与解析后的 Location 作为 finalURL,
|
||||
// 用于重定向目标域会被 Cloudflare 拦截(accounts.x.ai)的请求。
|
||||
func (f *ssoBuildFlow) doWithFollow(ctx context.Context, method, endpoint string, form url.Values, follow bool) (int, string, []byte, error) {
|
||||
return f.doWithFollowHeaders(ctx, method, endpoint, form, follow, nil)
|
||||
}
|
||||
|
||||
func (f *ssoBuildFlow) doWithFollowHeaders(ctx context.Context, method, endpoint string, form url.Values, follow bool, extraHeaders map[string]string) (int, string, []byte, error) {
|
||||
if !safeXAIURL(endpoint) {
|
||||
return 0, "", nil, fmt.Errorf("xAI OAuth URL 不安全")
|
||||
}
|
||||
@@ -242,6 +278,17 @@ func (f *ssoBuildFlow) doWithFollow(ctx context.Context, method, endpoint string
|
||||
request.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
|
||||
request.Header.Set("User-Agent", f.userAgent)
|
||||
request.Header.Set("Cookie", f.cookieHeader())
|
||||
if currentMethod == http.MethodGet && ssoDeviceRedirectState(currentURL) == "consent" {
|
||||
request.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")
|
||||
request.Header.Set("Referer", "https://auth.x.ai/")
|
||||
request.Header.Set("Sec-Fetch-Dest", "document")
|
||||
request.Header.Set("Sec-Fetch-Mode", "navigate")
|
||||
request.Header.Set("Sec-Fetch-Site", "same-site")
|
||||
request.Header.Set("Upgrade-Insecure-Requests", "1")
|
||||
}
|
||||
for key, value := range extraHeaders {
|
||||
request.Header.Set(key, value)
|
||||
}
|
||||
if currentForm != nil {
|
||||
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
@@ -275,7 +322,7 @@ func (f *ssoBuildFlow) doWithFollow(ctx context.Context, method, endpoint string
|
||||
return response.StatusCode, currentURL, data, fmt.Errorf("xAI OAuth 重定向到非受信域名")
|
||||
}
|
||||
if !follow {
|
||||
return response.StatusCode, currentURL, nil, nil
|
||||
return response.StatusCode, currentURL, data, nil
|
||||
}
|
||||
if response.StatusCode == http.StatusSeeOther || ((response.StatusCode == http.StatusMovedPermanently || response.StatusCode == http.StatusFound) && currentMethod != http.MethodGet && currentMethod != http.MethodHead) {
|
||||
currentMethod = http.MethodGet
|
||||
@@ -331,6 +378,17 @@ func (f *ssoBuildFlow) cookieHeader() string {
|
||||
return strings.Join(parts, "; ")
|
||||
}
|
||||
|
||||
func ssoBuildCookies(token, cloudflareCookies string) map[string]string {
|
||||
cookies := make(map[string]string)
|
||||
for _, part := range strings.Split(infraegress.BuildSSOCookie(token, cloudflareCookies), ";") {
|
||||
name, value, ok := strings.Cut(strings.TrimSpace(part), "=")
|
||||
if ok && name != "" {
|
||||
cookies[name] = value
|
||||
}
|
||||
}
|
||||
return cookies
|
||||
}
|
||||
|
||||
func safeXAIURL(raw string) bool {
|
||||
parsed, err := url.Parse(raw)
|
||||
if err != nil || parsed.Scheme != "https" || parsed.User != nil || parsed.Hostname() == "" {
|
||||
@@ -351,6 +409,53 @@ func normalizeSSOToken(value string) string {
|
||||
return strings.NewReplacer("\r", "", "\n", "", "\x00", "").Replace(value)
|
||||
}
|
||||
|
||||
var (
|
||||
consentTokenJSONRe = regexp.MustCompile(`(?i)\\?["']?(?:consentToken|consent_token)\\?["']?\s*[:=]\s*\\?["'](eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)\\?["']`)
|
||||
)
|
||||
|
||||
// extractConsentToken 从 consent 页面 HTML 中解析一次性 consent_token:
|
||||
// 优先取表单隐藏字段 name="consent_token",回退到 RSC/JSON 里的 consentToken。
|
||||
func extractConsentToken(body []byte) string {
|
||||
tokenizer := html.NewTokenizer(strings.NewReader(string(body)))
|
||||
for {
|
||||
tokenType := tokenizer.Next()
|
||||
if tokenType == html.ErrorToken {
|
||||
break
|
||||
}
|
||||
if tokenType != html.StartTagToken {
|
||||
continue
|
||||
}
|
||||
token := tokenizer.Token()
|
||||
if !strings.EqualFold(token.Data, "input") {
|
||||
continue
|
||||
}
|
||||
var name, value string
|
||||
for _, attribute := range token.Attr {
|
||||
switch strings.ToLower(attribute.Key) {
|
||||
case "name":
|
||||
name = attribute.Val
|
||||
case "value":
|
||||
value = attribute.Val
|
||||
}
|
||||
}
|
||||
if strings.EqualFold(name, "consent_token") && value != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
if m := consentTokenJSONRe.FindSubmatch(body); m != nil {
|
||||
return string(m[1])
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func consentTokenMatchesDevice(token, deviceCode string) bool {
|
||||
parts := strings.Split(token, ".")
|
||||
if len(parts) != 3 || parts[0] == "" || parts[2] == "" {
|
||||
return false
|
||||
}
|
||||
return claimString(decodeBuildClaims(token), "dc") == deviceCode && deviceCode != ""
|
||||
}
|
||||
|
||||
func decodeBuildClaims(token string) map[string]any {
|
||||
parts := strings.Split(token, ".")
|
||||
if len(parts) < 2 {
|
||||
|
||||
@@ -69,36 +69,78 @@ func TestSSOBuildFlowMapsDeadSSOToUnauthorized(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSOBuildFlowUsesAuthEndpointsOnly(t *testing.T) {
|
||||
func TestSSOBuildFlowConvertsEndToEndWithConsentToken(t *testing.T) {
|
||||
client := &scriptedSSOClient{responses: []*http.Response{
|
||||
{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(
|
||||
`{"device_code":"dc","user_code":"uc","interval":1,"expires_in":1800}`))},
|
||||
{StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device/consent"}}, Body: io.NopCloser(strings.NewReader(""))},
|
||||
{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(
|
||||
`<form method="post"><input value="eyJhbGciOiJFUzI1NiJ9.eyJkYyI6ImRjIn0.sig" type="hidden" name="consent_token"></form>`))},
|
||||
{StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device/done"}}, Body: io.NopCloser(strings.NewReader(""))},
|
||||
{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(
|
||||
`{"access_token":"access","refresh_token":"refresh","expires_in":3600}`))},
|
||||
}}
|
||||
flow := &ssoBuildFlow{client: client, userAgent: "lease-agent", cookies: map[string]string{"sso": "live", "sso-rw": "live"}}
|
||||
flow := &ssoBuildFlow{client: client, userAgent: "lease-agent", cookies: ssoBuildCookies("live", "cf_clearance=clearance")}
|
||||
seed, err := flow.convert(context.Background(), fakeCredential())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if seed.AccessToken != "access" || seed.RefreshToken != "refresh" || len(client.requests) != 4 {
|
||||
if seed.AccessToken != "access" || seed.RefreshToken != "refresh" || len(client.requests) != 5 {
|
||||
t.Fatalf("seed=%#v requests=%d", seed, len(client.requests))
|
||||
}
|
||||
for _, request := range client.requests {
|
||||
if request.URL.Hostname() != "auth.x.ai" {
|
||||
hosts := []string{"auth.x.ai", "auth.x.ai", "accounts.x.ai", "auth.x.ai", "auth.x.ai"}
|
||||
for index, request := range client.requests {
|
||||
if request.URL.Hostname() != hosts[index] {
|
||||
t.Fatalf("device flow visited unexpected host %q", request.URL.Hostname())
|
||||
}
|
||||
}
|
||||
if client.requests[3].URL.RawQuery != "" {
|
||||
t.Fatalf("approve must post a form body, got query %q", client.requests[3].URL.RawQuery)
|
||||
}
|
||||
approve := client.requests[3]
|
||||
if approve.Method != http.MethodPost {
|
||||
t.Fatalf("approve method = %q, want POST", approve.Method)
|
||||
}
|
||||
wantHeaders := map[string]string{
|
||||
"Origin": "https://accounts.x.ai",
|
||||
"Referer": "https://accounts.x.ai/oauth2/device/consent",
|
||||
"Sec-Fetch-Dest": "document",
|
||||
"Sec-Fetch-Mode": "navigate",
|
||||
"Sec-Fetch-Site": "same-site",
|
||||
"Sec-Fetch-User": "?1",
|
||||
"Upgrade-Insecure-Requests": "1",
|
||||
}
|
||||
for name, want := range wantHeaders {
|
||||
if got := approve.Header.Get(name); got != want {
|
||||
t.Errorf("approve %s = %q, want %q", name, got, want)
|
||||
}
|
||||
}
|
||||
consentCookie := client.requests[2].Header.Get("Cookie")
|
||||
if !strings.Contains(consentCookie, "sso=live") || !strings.Contains(consentCookie, "cf_clearance=clearance") {
|
||||
t.Fatalf("consent request cookies = %q", consentCookie)
|
||||
}
|
||||
if client.requests[2].Header.Get("Sec-Fetch-Mode") != "navigate" || client.requests[2].Header.Get("Sec-Fetch-Dest") != "document" {
|
||||
t.Fatalf("consent request is missing navigation headers: %#v", client.requests[2].Header)
|
||||
}
|
||||
body, err := io.ReadAll(client.requests[3].Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
approveForm, err := url.ParseQuery(string(body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if approveForm.Get("consent_token") != "eyJhbGciOiJFUzI1NiJ9.eyJkYyI6ImRjIn0.sig" {
|
||||
t.Fatalf("approve form missing consent_token: %q", approveForm.Get("consent_token"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSOBuildFlowVerifyDoesNotFollowRedirect(t *testing.T) {
|
||||
client := &scriptedSSOClient{responses: []*http.Response{
|
||||
{StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device/consent"}}, Body: io.NopCloser(strings.NewReader(""))},
|
||||
{StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device/consent"}}, Body: io.NopCloser(strings.NewReader("verify response"))},
|
||||
}}
|
||||
flow := &ssoBuildFlow{client: client, userAgent: "lease-agent", cookies: map[string]string{"sso": "live"}}
|
||||
status, finalURL, _, err := flow.doWithFollow(context.Background(), http.MethodPost, ssoVerifyURL, url.Values{"user_code": {"uc"}}, false)
|
||||
status, finalURL, body, err := flow.doWithFollow(context.Background(), http.MethodPost, ssoVerifyURL, url.Values{"user_code": {"uc"}}, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -111,6 +153,9 @@ func TestSSOBuildFlowVerifyDoesNotFollowRedirect(t *testing.T) {
|
||||
if len(client.requests) != 1 {
|
||||
t.Fatalf("redirect must not be followed, requests = %d", len(client.requests))
|
||||
}
|
||||
if string(body) != "verify response" {
|
||||
t.Fatalf("redirect response body = %q", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSODeviceRedirectStateRequiresExactTrustedPath(t *testing.T) {
|
||||
@@ -131,6 +176,47 @@ func TestSSODeviceRedirectStateRequiresExactTrustedPath(t *testing.T) {
|
||||
|
||||
func fakeCredential() accountdomain.Credential { return accountdomain.Credential{} }
|
||||
|
||||
func TestExtractConsentToken(t *testing.T) {
|
||||
form := []byte(`<input value="eyJhbGciOiJFUzI1NiJ9.a.b" type="hidden" name="consent_token">`)
|
||||
if token := extractConsentToken(form); token != "eyJhbGciOiJFUzI1NiJ9.a.b" {
|
||||
t.Fatalf("form token = %q", token)
|
||||
}
|
||||
jsonPayload := []byte(`{"consentToken":"eyJhbGciOiJFUzI1NiJ9.c.d","other":1}`)
|
||||
if token := extractConsentToken(jsonPayload); token != "eyJhbGciOiJFUzI1NiJ9.c.d" {
|
||||
t.Fatalf("json token = %q", token)
|
||||
}
|
||||
rscPayload := []byte(`{\"consentToken\":\"eyJhbGciOiJFUzI1NiJ9.e.f\"}`)
|
||||
if token := extractConsentToken(rscPayload); token != "eyJhbGciOiJFUzI1NiJ9.e.f" {
|
||||
t.Fatalf("escaped RSC token = %q", token)
|
||||
}
|
||||
if token := extractConsentToken([]byte("<html>nothing</html>")); token != "" {
|
||||
t.Fatalf("unexpected token = %q", token)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsentTokenMustMatchDeviceCode(t *testing.T) {
|
||||
token := "eyJhbGciOiJFUzI1NiJ9.eyJkYyI6ImRjIn0.sig"
|
||||
if !consentTokenMatchesDevice(token, "dc") {
|
||||
t.Fatal("consent token for current device code was rejected")
|
||||
}
|
||||
if consentTokenMatchesDevice(token, "other-device") {
|
||||
t.Fatal("consent token for a different device code was accepted")
|
||||
}
|
||||
if consentTokenMatchesDevice("not-a-jwt", "dc") {
|
||||
t.Fatal("malformed consent token was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSOBuildCookiesCarrySanitizedCloudflareClearance(t *testing.T) {
|
||||
cookies := ssoBuildCookies("sso-token", "cf_clearance=clearance; __cf_bm=bm; sso=attacker")
|
||||
if cookies["sso"] != "sso-token" || cookies["sso-rw"] != "sso-token" {
|
||||
t.Fatalf("SSO cookies = %#v", cookies)
|
||||
}
|
||||
if cookies["cf_clearance"] != "clearance" || cookies["__cf_bm"] != "bm" {
|
||||
t.Fatalf("Cloudflare cookies = %#v", cookies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSOBuildConversionSanitizesTokenAndURLs(t *testing.T) {
|
||||
if token := normalizeSSOToken("sso=token-value; x-userid=drop"); token != "token-value" {
|
||||
t.Fatalf("token = %q", token)
|
||||
|
||||
@@ -130,6 +130,7 @@ type clientKeyDefaultsConfigDTO struct {
|
||||
}
|
||||
|
||||
type accountsConfigDTO struct {
|
||||
AutoDisableDegradedAccounts *bool `json:"autoDisableDegradedAccounts,omitempty"`
|
||||
MarkBuildForbiddenReauth *bool `json:"markBuildForbiddenReauth,omitempty"`
|
||||
BuildForbiddenReauthCodes *[]string `json:"buildForbiddenReauthCodes,omitempty"`
|
||||
ExcludeBuildBotFlaggedFromScheduling *bool `json:"excludeBuildBotFlaggedFromScheduling,omitempty"`
|
||||
@@ -252,6 +253,8 @@ func (value settingsConfigDTO) toApplication() settingsapp.EditableConfig {
|
||||
}
|
||||
if value.Accounts != nil {
|
||||
result.Accounts = settingsapp.AccountsConfig{
|
||||
AutoDisableDegradedAccounts: boolValue(value.Accounts.AutoDisableDegradedAccounts),
|
||||
AutoDisableDegradedAccountsProvided: value.Accounts.AutoDisableDegradedAccounts != nil,
|
||||
MarkBuildForbiddenReauth: boolValue(value.Accounts.MarkBuildForbiddenReauth),
|
||||
BuildForbiddenReauthCodes: stringSliceValue(value.Accounts.BuildForbiddenReauthCodes),
|
||||
ExcludeBuildBotFlaggedFromScheduling: boolValue(value.Accounts.ExcludeBuildBotFlaggedFromScheduling),
|
||||
@@ -329,6 +332,7 @@ func newSettingsResponse(value settingsapp.Snapshot) settingsResponse {
|
||||
RPMLimit: config.ClientKeyDefaults.RPMLimit, MaxConcurrent: config.ClientKeyDefaults.MaxConcurrent,
|
||||
},
|
||||
Accounts: &accountsConfigDTO{
|
||||
AutoDisableDegradedAccounts: boolPointer(config.Accounts.AutoDisableDegradedAccounts),
|
||||
MarkBuildForbiddenReauth: boolPointer(config.Accounts.MarkBuildForbiddenReauth),
|
||||
BuildForbiddenReauthCodes: stringSlicePointer(config.Accounts.BuildForbiddenReauthCodes),
|
||||
ExcludeBuildBotFlaggedFromScheduling: boolPointer(config.Accounts.ExcludeBuildBotFlaggedFromScheduling),
|
||||
|
||||
@@ -152,7 +152,7 @@ func TestLegacySettingsRequestPreservesBuildForbiddenCodesWhenOmitted(t *testing
|
||||
t.Fatal(err)
|
||||
}
|
||||
input := dto.toApplication()
|
||||
if !input.AccountsProvided || !input.Accounts.MarkBuildForbiddenReauthProvided || input.Accounts.BuildForbiddenReauthCodesProvided {
|
||||
if !input.AccountsProvided || !input.Accounts.MarkBuildForbiddenReauthProvided || input.Accounts.BuildForbiddenReauthCodesProvided || input.Accounts.AutoDisableDegradedAccountsProvided {
|
||||
t.Fatalf("legacy field presence was not preserved: %#v", input.Accounts)
|
||||
}
|
||||
}
|
||||
|
||||
+8
-4
@@ -150,8 +150,8 @@ qualityGuard:
|
||||
nodeIDs: []
|
||||
rotatableNodeIDs: []
|
||||
# Optional request-path withhold/retry for thinking models.
|
||||
# Recommended lab values are filled in; enabled stays false so stock
|
||||
# installs do not intercept. Set enabled: true to turn the hold on.
|
||||
# Recommended lab values are filled in; enabled and autoDisable stay false
|
||||
# so stock installs do not intercept. Either switch enables detection.
|
||||
# Observe up to 30s for real reasoning evidence. A reasoning-item stub plus
|
||||
# enough visible output at the deadline is withheld (TUI dump after 30s),
|
||||
# not released as late ciphertext. Empty stub-only streams keep waiting.
|
||||
@@ -170,8 +170,12 @@ qualityGuard:
|
||||
holdTimeout: 30s
|
||||
minOutputTokens: 8
|
||||
onExhausted: fail_closed # fail_open | fail_closed
|
||||
# First missing-thinking hit cools the account; a later hit after the
|
||||
# cooldown expires disables it.
|
||||
# Immediately disable an account on its first confirmed missing-thinking
|
||||
# or degraded output-speed hit (soft-TPS, hard-TPS, or buffered-burst).
|
||||
# Also enables request-path detection independently of enabled above.
|
||||
# When false, enabled controls the historical cooldown/second-hit policy.
|
||||
# Context compaction and forced egress probes remain exempt.
|
||||
autoDisable: false
|
||||
accountCooldown: 12h
|
||||
# Empty SSE / idle-timeout penalty. Independent of accountCooldown.
|
||||
# Single-account pools should set this lower; toggling enabled does not
|
||||
|
||||
@@ -27,6 +27,7 @@ export type SettingsConfigDTO = {
|
||||
audit: { bufferSize: number; batchSize: number; flushInterval: string; commitDelayMS: number; retentionDays?: number };
|
||||
clientKeyDefaults: { rpmLimit: number; maxConcurrent: number };
|
||||
accounts: {
|
||||
autoDisableDegradedAccounts: boolean;
|
||||
markBuildForbiddenReauth: boolean;
|
||||
buildForbiddenReauthCodes: string[];
|
||||
excludeBuildBotFlaggedFromScheduling: boolean;
|
||||
@@ -139,6 +140,7 @@ const settingsConfigValidator = hasShape({
|
||||
clientKeyDefaults: hasShape({ rpmLimit: isNumber, maxConcurrent: isNumber }),
|
||||
// Older backends may omit accounts; withSettingsDefaults supplies a safe local default.
|
||||
accounts: isOptional(hasShape({
|
||||
autoDisableDegradedAccounts: isOptional(isBoolean),
|
||||
markBuildForbiddenReauth: isOptional(isBoolean),
|
||||
buildForbiddenReauthCodes: isOptional(isArrayOf(isString)),
|
||||
excludeBuildBotFlaggedFromScheduling: isOptional(isBoolean),
|
||||
@@ -149,6 +151,7 @@ const settingsConfigValidator = hasShape({
|
||||
})),
|
||||
});
|
||||
const defaultAccountsConfig = (): SettingsConfigDTO["accounts"] => ({
|
||||
autoDisableDegradedAccounts: false,
|
||||
markBuildForbiddenReauth: false,
|
||||
buildForbiddenReauthCodes: ["permission-denied"],
|
||||
excludeBuildBotFlaggedFromScheduling: false,
|
||||
@@ -188,6 +191,7 @@ function withSettingsDefaults(snapshot: SettingsSnapshotDTO): SettingsSnapshotDT
|
||||
},
|
||||
},
|
||||
accounts: {
|
||||
autoDisableDegradedAccounts: accounts.autoDisableDegradedAccounts ?? false,
|
||||
markBuildForbiddenReauth: accounts.markBuildForbiddenReauth ?? false,
|
||||
buildForbiddenReauthCodes: accounts.buildForbiddenReauthCodes ?? ["permission-denied"],
|
||||
excludeBuildBotFlaggedFromScheduling: accounts.excludeBuildBotFlaggedFromScheduling ?? false,
|
||||
|
||||
@@ -163,6 +163,7 @@ export const settingsSchema = z.object({
|
||||
.refine((value) => value.batchSize <= value.bufferSize, { path: ["batchSize"] }),
|
||||
clientKeyDefaults: z.object({ rpmLimit: positiveInteger.max(100_000), maxConcurrent: positiveInteger.max(1_024) }),
|
||||
accounts: z.object({
|
||||
autoDisableDegradedAccounts: z.boolean(),
|
||||
markBuildForbiddenReauth: z.boolean(),
|
||||
buildForbiddenReauthCodes: z.string().superRefine((value, context) => {
|
||||
const codes = parseForbiddenCodes(value);
|
||||
@@ -226,6 +227,7 @@ export function toSettingsForm(config: SettingsConfigDTO): SettingsForm {
|
||||
},
|
||||
clientKeyDefaults: config.clientKeyDefaults,
|
||||
accounts: {
|
||||
autoDisableDegradedAccounts: config.accounts.autoDisableDegradedAccounts,
|
||||
markBuildForbiddenReauth: config.accounts.markBuildForbiddenReauth,
|
||||
buildForbiddenReauthCodes: config.accounts.buildForbiddenReauthCodes.join("\n"),
|
||||
excludeBuildBotFlaggedFromScheduling: config.accounts.excludeBuildBotFlaggedFromScheduling,
|
||||
@@ -275,6 +277,7 @@ export function toSettingsDTO(config: SettingsForm): SettingsConfigDTO {
|
||||
},
|
||||
clientKeyDefaults: config.clientKeyDefaults,
|
||||
accounts: {
|
||||
autoDisableDegradedAccounts: config.accounts.autoDisableDegradedAccounts,
|
||||
markBuildForbiddenReauth: config.accounts.markBuildForbiddenReauth,
|
||||
buildForbiddenReauthCodes: parseForbiddenCodes(config.accounts.buildForbiddenReauthCodes),
|
||||
excludeBuildBotFlaggedFromScheduling: config.accounts.excludeBuildBotFlaggedFromScheduling,
|
||||
|
||||
@@ -436,6 +436,18 @@ export function SettingsPage() {
|
||||
</SettingsPane>
|
||||
|
||||
<SettingsPane value="accounts">
|
||||
<SettingsSection title={t("settings.accounts.degradedAccountTitle")}>
|
||||
<div className="space-y-0">
|
||||
<SettingsField controlId="accounts-auto-disable-degraded" label={t("settings.accounts.autoDisableDegradedAccounts")} description={t("settings.accounts.autoDisableDegradedAccountsHelp")}>
|
||||
<Controller control={form.control} name="accounts.autoDisableDegradedAccounts" render={({ field }) => (
|
||||
<div className="flex h-9 items-center">
|
||||
<Switch id="accounts-auto-disable-degraded" checked={Boolean(field.value)} onCheckedChange={field.onChange} />
|
||||
</div>
|
||||
)} />
|
||||
</SettingsField>
|
||||
</div>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title={t("settings.accounts.invalidationTitle")}>
|
||||
<div className="space-y-0">
|
||||
<SettingsField controlId="accounts-mark-build-forbidden-reauth" label={t("settingsBuildForbidden.markInvalid")} description={t("settingsBuildForbidden.markInvalidHelp")}>
|
||||
|
||||
@@ -1022,7 +1022,7 @@ const resources = {
|
||||
console: { baseURLHelp: "Grok Console 请求与账号操作使用的基础端点。", chatTimeoutHelp: "Grok Console 聊天请求完成前允许等待的最长时间。", streamIdleTimeout: "流式空闲超时", streamIdleTimeoutHelp: "仅文本 SSE 连续无上游数据时允许等待的最长时间;不影响媒体和非流式请求。" },
|
||||
batch: { title: "批量任务", importConcurrency: "导入同步并发", importConcurrencyHelp: "批量导入后并行执行账号初始化与信息同步的任务数。", conversionConcurrency: "账号转换并发", conversionConcurrencyHelp: "跨 Provider 转换账号时允许同时处理的任务数。", syncConcurrency: "数据同步并发", syncConcurrencyHelp: "批量同步账号额度、状态与能力时允许同时处理的任务数。", refreshConcurrency: "凭据刷新并发", refreshConcurrencyHelp: "批量刷新账号凭据时允许同时处理的任务数。", randomDelay: "随机延迟上限(ms)", randomDelayHelp: "批量任务启动前增加的随机延迟上限,用于平滑上游请求峰值。" },
|
||||
media: { title: "媒体存储", maxImageSize: "单张图片上限", maxImageSizeHelp: "单个图片文件允许写入本地媒体存储的最大大小。", maxTotalSize: "媒体存储上限", maxTotalSizeHelp: "本地图片与视频文件允许占用的总存储空间。", cleanupThresholdPercent: "自动清理阈值", cleanupThresholdPercentHelp: "存储使用率达到该比例后,系统按时间清理较早的媒体文件。", cleanupInterval: "容量检查间隔", cleanupIntervalHelp: "后台检查媒体存储使用量并触发清理的时间间隔。", sizeUnit: "存储单位", publicApiBaseURL: "公共 API 地址", publicApiBaseURLHelp: "用于生成图片公开 URL 与文档示例地址。留空时回退到服务启动值,默认为 http://127.0.0.1:8000。" },
|
||||
egress: { title: "出口代理", description: "节点按 Grok Build、Grok Web、Grok Console 或 Web 资源独立管理代理和健康状态。Build 沿用 Provider 的 User-Agent;Web 与 Console 节点单独管理浏览器 User-Agent 和 Cookie。代理地址和 Cloudflare Cookie 仅写入。", add: "添加节点", saved: "代理节点已保存", deleted: "代理节点已删除", name: "名称", scope: "作用域", proxy: "代理", clearance: "Clearance", health: "健康度", directFallback: "未配置节点时使用直连", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web(仅资源)", configured: "已配置", direct: "直连", none: "无", editTitle: "编辑代理节点", addTitle: "添加代理节点", dialogDescription: "Build 节点只配置代理并沿用 Provider 的 User-Agent;Web 与 Console 节点使用各自的浏览器 User-Agent 和 Cloudflare Cookie。", enabled: "启用", proxyURL: "代理地址", proxyProtocols: "支持 HTTP、HTTPS、SOCKS4/4A、SOCKS5/5H、Trojan、VLESS、Shadowsocks 和 VMess。\n隧道协议支持 TCP、WebSocket 与 TLS;Resin 可在用户名中使用 {account}。", proxyPool: "代理池模式", proxyPoolHelp: "共享代理池的单次连接失败不会使整个出口节点进入冷却;包含 {account} 的代理会自动启用此策略。", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "已配置,留空保持不变", operationFailed: "操作失败", refreshClearance: "刷新 Clearance", clearanceRefreshed: "Clearance 已刷新", clearanceManaged: "Cloudflare Cookie 与 User-Agent 由 FlareSolverr 自动维护;Resin 等账号粘性代理会按账号隔离。", accounts: "已绑定", probe: "探测", healthy: "可用", unhealthy: "不可用", notTested: "未测试", test: "测试代理", testedOne: "代理测试完成", operations: "代理运营", automation: "自动任务", subscriptions: "代理订阅", testAll: "测试全部", rebalance: "立即调配", importText: "导入文本", addSource: "添加订阅", source: "订阅源", sync: "同步", capacity: "账号容量", noSources: "暂无订阅源", never: "从未", unlimited: "无限制", sourceSaved: "订阅源已保存", sourceDeleted: "订阅源已删除", sourceSynced: "订阅同步完成:导入 {{imported}},跳过 {{skipped}}", imported: "代理导入完成:导入 {{imported}},跳过 {{skipped}}", tested: "代理测试完成:可用 {{healthy}},不可用 {{unhealthy}}", rebalanced: "账号调配完成:新增 {{assigned}},均衡 {{rebalanced}},未分配 {{unplaced}}", automationSaved: "自动任务已保存", editSource: "编辑订阅", subscriptionURL: "订阅地址", sourceDialogDescription: "配置订阅来源、作用域、刷新周期和单节点账号容量。", importDialogDescription: "支持明文或 Base64 代理列表,每行一个 HTTP、SOCKS、Trojan、VLESS、SS 或 VMess 地址。", probeInterval: "探测间隔(秒)", probeIntervalHelp: "后台重新测试已启用代理节点的间隔。", assignmentInterval: "调配间隔(秒)", assignmentIntervalHelp: "后台检查自动分配与节点容量的间隔。", autoAssign: "自动分配未绑定账号", autoAssignHelp: "将可调度且未绑定的账号分配到近期探测可用的节点。", autoBalance: "自动均衡自动绑定账号", autoBalanceHelp: "在健康节点之间调整自动绑定;手工绑定始终保持不变。", refreshInterval: "订阅刷新间隔(秒)", proxyList: "代理列表" },
|
||||
egress: { title: "出口代理", description: "节点按 Grok Build、Grok Web、Grok Console 或 Web 资源独立管理代理和健康状态。Build 沿用 Provider 的 User-Agent;Web 与 Console 节点单独管理浏览器 User-Agent 和 Cookie。代理地址和 Cloudflare Cookie 仅写入。", add: "添加节点", saved: "代理节点已保存", deleted: "代理节点已删除", name: "名称", scope: "作用域", proxy: "代理", clearance: "Clearance", health: "健康度", directFallback: "未配置节点时使用直连", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web(仅资源)", configured: "已配置", direct: "直连", none: "无", editTitle: "编辑代理节点", addTitle: "添加代理节点", dialogDescription: "Build 节点只配置代理并沿用 Provider 的 User-Agent;Web 与 Console 节点使用各自的浏览器 User-Agent 和 Cloudflare Cookie。", enabled: "启用", proxyURL: "代理地址", proxyProtocols: "支持 HTTP、HTTPS、SOCKS4/4A、SOCKS5/5H、Trojan、VLESS、Shadowsocks 和 VMess。\n隧道协议支持 TCP、WebSocket 与 TLS;Resin 可在用户名中使用 {account}。", proxyPool: "代理池模式", proxyPoolHelp: "共享代理池的单次连接失败不会使整个出口节点进入冷却;包含 {account} 的代理会自动启用此策略。", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "已配置,留空保持不变", operationFailed: "操作失败", refreshClearance: "刷新 Clearance", clearanceRefreshed: "Clearance 已刷新", clearanceManaged: "Cloudflare Cookie 与 User-Agent 由 FlareSolverr 自动维护;Resin 等账号粘性代理会按账号隔离。", accounts: "已绑定", probe: "探测", healthy: "可用", unhealthy: "不可用", notTested: "未测试", test: "测试代理", testedOne: "代理测试完成", operations: "代理运营", automation: "自动任务", subscriptions: "代理订阅", testAll: "测试全部", rebalance: "立即调配", importText: "导入文本", addSource: "添加订阅", source: "订阅源", sync: "同步", capacity: "账号容量", noSources: "暂无订阅源", never: "从未", unlimited: "无限制", sourceSaved: "订阅源已保存", sourceDeleted: "订阅源已删除", sourceSynced: "订阅同步完成:导入 {{imported}},跳过 {{skipped}}", imported: "代理导入完成:导入 {{imported}},跳过 {{skipped}}", tested: "代理测试完成:可用 {{healthy}},不可用 {{unhealthy}}", rebalanced: "账号调配完成:新增 {{assigned}},均衡 {{rebalanced}},未分配 {{unplaced}}", automationSaved: "自动任务已保存", editSource: "编辑订阅", subscriptionURL: "订阅地址", sourceDialogDescription: "配置订阅来源、作用域、刷新周期和单节点账号容量。", importDialogDescription: "支持明文或 Base64 代理列表,每行一个标准代理地址,HTTP 代理也可使用 IP:端口:用户名:密码。", probeInterval: "探测间隔(秒)", probeIntervalHelp: "后台重新测试已启用代理节点的间隔。", assignmentInterval: "调配间隔(秒)", assignmentIntervalHelp: "后台检查自动分配与节点容量的间隔。", autoAssign: "自动分配未绑定账号", autoAssignHelp: "将可调度且未绑定的账号分配到近期探测可用的节点。", autoBalance: "自动均衡自动绑定账号", autoBalanceHelp: "在健康节点之间调整自动绑定;手工绑定始终保持不变。", refreshInterval: "订阅刷新间隔(秒)", proxyList: "代理列表" },
|
||||
routing: { title: "路由策略", stickyTTL: "会话粘性时长", stickyTTLHelp: "同一会话优先复用已选账号的有效时长;到期后重新参与调度。", cooldownBase: "基础冷却时间", cooldownBaseHelp: "账号发生可恢复故障后首次进入冷却的时长。", cooldownMax: "最大冷却时间", cooldownMaxHelp: "连续故障触发指数退避时允许达到的最长冷却时间。", capacityWait: "账号满载等待", capacityWaitHelp: "全部候选账号并发已满时,切换或失败前等待容量释放的时间。", maxAttempts: "最大尝试次数", maxAttemptsHelp: "单次请求在可用账号之间切换并重试的最大次数,范围为 1–200。", videoMaxAttempts: "视频最大尝试次数", videoMaxAttemptsHelp: "仅作用于视频任务创建阶段的切号重试,可单独设置数值,或开启无限制。创建成功后的轮询不会换号。", preferFreeBuild: "Grok Build Free 账号优先", preferFreeBuildHelp: "启用后优先选择已确认可用的 Free 账号,其他路由条件保持不变。", accountIsolatedConnections: "按账号隔离上游连接", accountIsolatedConnectionsHelp: "开启后,不同账号使用各自的上游 TCP/HTTP 连接池,便于外部 L4 或按连接哈希的负载均衡器分散流量;同一账号仍可复用连接。适用于 Build / Web / Console 出站及 Web 转 Build。会增加连接数、TLS 握手、内存和文件描述符占用,建议仅在确有外部连接级负载均衡需求时开启。" },
|
||||
audit: {
|
||||
title: "请求审计与日志设置",
|
||||
@@ -1043,6 +1043,9 @@ const resources = {
|
||||
clientKeys: { title: "密钥默认限制", rpmLimit: "默认 RPM", rpmLimitHelp: "新建客户端密钥默认允许的每分钟请求数。", maxConcurrent: "默认并发数", maxConcurrentHelp: "新建客户端密钥默认允许同时执行的请求数。" },
|
||||
accounts: {
|
||||
title: "账号维护",
|
||||
degradedAccountTitle: "降智账号处理",
|
||||
autoDisableDegradedAccounts: "自动停用降智账号",
|
||||
autoDisableDegradedAccountsHelp: "开启后启用请求内质量检测与重试,首次确认缺少 thinking 或吞吐降智时立即停用账号;关闭后不因吞吐降智停用,缺少 thinking 的拦截与冷却按原有配置执行。",
|
||||
invalidationTitle: "自动拦截判定",
|
||||
botRiskSchedulingTitle: "风控调度",
|
||||
excludeBuildBotFlaggedFromScheduling: "风控 Build 号移出调度",
|
||||
@@ -1815,7 +1818,7 @@ const resources = {
|
||||
errorFrameCount_one: "{{count}} error frame",
|
||||
errorFrameCount_other: "{{count}} error frames",
|
||||
},
|
||||
settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies", audit: "Audit & Logs", accounts: "Account maintenance", about: "About" }, server: { title: "Service capacity", maxConcurrentRequests: "API request concurrency limit", maxConcurrentRequestsHelp: "Maximum simultaneous /v1 requests per instance. Lowering the limit does not interrupt active requests." }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", baseURLHelp: "Primary upstream endpoint used for Grok Build requests.", fallbackBaseURL: "XAI fallback URL", fallbackBaseURLHelp: "Endpoint used when routing to XAI or falling back from Grok Build.", clientVersion: "Client version", clientVersionHelp: "Version sent with Build requests. Use a version that has passed compatibility validation.", clientIdentifier: "Client identifier", clientIdentifierHelp: "Client identity sent with requests; keep it aligned with the upstream protocol.", tokenAuth: "Token auth", tokenAuthHelp: "Client protocol identifier sent with Grok Build requests; normally keep xai-grok-cli.", userAgent: "User-Agent", userAgentHelp: "Used by Grok Build inference requests and their egress nodes. Direct XAI media requests derive the official xai-grok-build User-Agent from the client version.", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync latest version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill the form with the validated version and User-Agent; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", baseURLHelp: "Base endpoint used for Grok Web API calls and account operations.", statsigMode: "x-statsig source", statsigModeHelp: "Use a fixed value or retrieve request identity dynamically from a signer service.", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigValueHelp: "Fixed x-statsig-id attached to Grok Web requests.", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", statsigSignerURLHelp: "Internal signer endpoint used to retrieve x-statsig-id per request.", quotaTimeout: "Quota timeout", quotaTimeoutHelp: "Maximum time to wait for upstream quota and account-status queries.", chatTimeout: "Chat timeout", chatTimeoutHelp: "Maximum time to wait for a Grok Web chat request to complete.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum period without upstream data for raw text-chat streams; image, video, and other media requests are unaffected.", imageTimeout: "Image timeout", imageTimeoutHelp: "Maximum time to wait for image generation or editing to complete.", videoTimeout: "Video timeout", videoTimeoutHelp: "Maximum time to wait for a Grok Web video generation request to complete.", freeVideoDurationCap: "Free-account video duration cap", freeVideoDurationCapHelp: "Caps duration sent to Grok Web for free-tier accounts so requests over the upstream limit do not 429 and rotate accounts uselessly. Default 6 seconds, range 1–15.", mediaConcurrency: "Media job concurrency", mediaConcurrencyHelp: "Image and video jobs one instance may run concurrently. Changes require a restart.", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffBaseHelp: "Initial retry interval after consecutive quota-recovery check failures.", recoveryBackoffMax: "Maximum recovery backoff", recoveryBackoffMaxHelp: "Maximum interval reached by exponential backoff for quota-recovery checks.", allowNSFW: "Allow NSFW images", allowNSFWHelp: "Allow Grok Web image requests to enable the adult-content preference.", clearanceMode: "Clearance management", clearanceModeHelp: "Maintain Cloudflare credentials manually or let FlareSolverr acquire and refresh them on the actual egress.", clearanceManual: "Manual", clearanceFlareSolverr: "FlareSolverr", flareSolverrURL: "FlareSolverr URL", flareSolverrURLHelp: "Internal FlareSolverr endpoint used to solve Cloudflare Clearance.", clearanceTimeout: "Solve timeout", clearanceTimeoutHelp: "Maximum time allowed for one FlareSolverr solve.", clearanceRefresh: "Refresh interval", clearanceRefreshHelp: "Periodic refresh interval for fixed egress; account-bound proxies are maintained independently during requests." }, console: { baseURLHelp: "Base endpoint used for Grok Console requests and account operations.", chatTimeoutHelp: "Maximum time to wait for a Grok Console chat request to complete.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum period without upstream data for text SSE only; media and non-streaming requests are unaffected." }, batch: { title: "BaLine truncated
|
||||
settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies", audit: "Audit & Logs", accounts: "Account maintenance", about: "About" }, server: { title: "Service capacity", maxConcurrentRequests: "API request concurrency limit", maxConcurrentRequestsHelp: "Maximum simultaneous /v1 requests per instance. Lowering the limit does not interrupt active requests." }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", baseURLHelp: "Primary upstream endpoint used for Grok Build requests.", fallbackBaseURL: "XAI fallback URL", fallbackBaseURLHelp: "Endpoint used when routing to XAI or falling back from Grok Build.", clientVersion: "Client version", clientVersionHelp: "Version sent with Build requests. Use a version that has passed compatibility validation.", clientIdentifier: "Client identifier", clientIdentifierHelp: "Client identity sent with requests; keep it aligned with the upstream protocol.", tokenAuth: "Token auth", tokenAuthHelp: "Client protocol identifier sent with Grok Build requests; normally keep xai-grok-cli.", userAgent: "User-Agent", userAgentHelp: "Used by Grok Build inference requests and their egress nodes. Direct XAI media requests derive the official xai-grok-build User-Agent from the client version.", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync latest version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill the form with the validated version and User-Agent; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", baseURLHelp: "Base endpoint used for Grok Web API calls and account operations.", statsigMode: "x-statsig source", statsigModeHelp: "Use a fixed value or retrieve request identity dynamically from a signer service.", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigValueHelp: "Fixed x-statsig-id attached to Grok Web requests.", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", statsigSignerURLHelp: "Internal signer endpoint used to retrieve x-statsig-id per request.", quotaTimeout: "Quota timeout", quotaTimeoutHelp: "Maximum time to wait for upstream quota and account-status queries.", chatTimeout: "Chat timeout", chatTimeoutHelp: "Maximum time to wait for a Grok Web chat request to complete.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum period without upstream data for raw text-chat streams; image, video, and other media requests are unaffected.", imageTimeout: "Image timeout", imageTimeoutHelp: "Maximum time to wait for image generation or editing to complete.", videoTimeout: "Video timeout", videoTimeoutHelp: "Maximum time to wait for a Grok Web video generation request to complete.", freeVideoDurationCap: "Free-account video duration cap", freeVideoDurationCapHelp: "Caps duration sent to Grok Web for free-tier accounts so requests over the upstream limit do not 429 and rotate accounts uselessly. Default 6 seconds, range 1–15.", mediaConcurrency: "Media job concurrency", mediaConcurrencyHelp: "Image and video jobs one instance may run concurrently. Changes require a restart.", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffBaseHelp: "Initial retry interval after consecutive quota-recovery check failures.", recoveryBackoffMax: "Maximum recovery backoff", recoveryBackoffMaxHelp: "Maximum interval reached by exponential backoff for quota-recovery checks.", allowNSFW: "Allow NSFW images", allowNSFWHelp: "Allow Grok Web image requests to enable the adult-content preference.", clearanceMode: "Clearance management", clearanceModeHelp: "Maintain Cloudflare credentials manually or let FlareSolverr acquire and refresh them on the actual egress.", clearanceManual: "Manual", clearanceFlareSolverr: "FlareSolverr", flareSolverrURL: "FlareSolverr URL", flareSolverrURLHelp: "Internal FlareSolverr endpoint used to solve Cloudflare Clearance.", clearanceTimeout: "Solve timeout", clearanceTimeoutHelp: "Maximum time allowed for one FlareSolverr solve.", clearanceRefresh: "Refresh interval", clearanceRefreshHelp: "Periodic refresh interval for fixed egress; account-bound proxies are maintained independently during requests." }, console: { baseURLHelp: "Base endpoint used for Grok Console requests and account operations.", chatTimeoutHelp: "Maximum time to wait for a Grok Console chat request to complete.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum period without upstream data for text SSE only; media and non-streaming requests are unaffected." }, batch: { title: "BaLine truncated
|
||||
|
||||
egressProxyProfiles: { title: "Proxy address library", libraryTitle: "Proxy address library", libraryDescription: "Manage reusable proxy addresses in one place. Changes sync to every node using the address.", description: "Save proxy addresses that need to be reused across nodes.", add: "Add proxy address", addTitle: "Add proxy address", editTitle: "Edit proxy address", dialogDescription: "Changing the proxy address updates every bound node. Capacity and operational state remain isolated per node.", name: "Address name", endpoint: "Proxy address", nodes: "Used by", search: "Search address names", empty: "No proxy addresses", emptyLibrary: "The library is empty. Add an address to reuse it across nodes.", noMatches: "No matching proxy addresses", loadingSelection: "Loading selected address…", selectionUnavailable: "Proxy address #{{id}} is unavailable", saved: "Proxy address saved", deleted: "Proxy address deleted", deleteTitle: "Delete proxy address?", deleteDescription: "This deletes {{name}}. Addresses currently used by nodes cannot be deleted.", deleteBlocked: "Used by {{count}} nodes", assignment: "Proxy address source", assignmentHelp: "Select an address from the library to reuse it across Provider nodes. Health, capacity, User-Agent, and Clearance remain isolated per node.", independent: "Configure this node separately", managedByProfile: "Managed by the proxy address library", nodeCount: "{{count}} nodes", backToLibrary: "Back to address library", createFromPicker: "Add and use a proxy address", refreshNodes: "Refresh proxy nodes", reveal: "Reveal full proxy URL", hide: "Hide full proxy URL", revealUnavailable: "Only a saved proxy address can reveal its URL" },
|
||||
settingsBuildTransport: { responseHeaderTimeout: "Response header timeout", responseHeaderTimeoutHelp: "Maximum time to wait for the first Grok Build response headers after the request body is sent.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum wait for useful generated content or tool progress. Keepalives and private control events do not extend the deadline." },
|
||||
@@ -2166,7 +2169,7 @@ Object.assign(resources.en.translation.settings.egress as unknown as Record<stri
|
||||
rebalanced: "Account allocation completed: {{assigned}} assigned, {{rebalanced}} balanced, {{unplaced}} unplaced", automationSaved: "Automation saved",
|
||||
editSource: "Edit subscription", subscriptionURL: "Subscription URL", sourceDialogDescription: "Configure the subscription URL, fetch route, scope, sync interval, and per-node account capacity.",
|
||||
subscriptionProxy: "Fetch through a proxy", subscriptionProxyURL: "Subscription fetch proxy", subscriptionRoute: "Fetch route", subscriptionProxyShort: "Proxy", invalidSubscriptionProxy: "Enter a valid HTTP, SOCKS, Trojan, VLESS, SS, or VMess proxy URL; {account} is not supported here",
|
||||
importDialogDescription: "Supports plain-text or Base64 proxy lists with one HTTP, SOCKS, Trojan, VLESS, SS, or VMess address per line.",
|
||||
importDialogDescription: "Supports one proxy per line; HTTP proxies may also use IP:port:username:password.",
|
||||
probeInterval: "Node check interval", probeIntervalHelp: "How often to check whether enabled proxy nodes are available.",
|
||||
assignmentInterval: "Account assignment interval", assignmentIntervalHelp: "When automatic binding or balancing is enabled, controls how often account bindings and available node capacity are checked.",
|
||||
autoAssign: "Automatically bind accounts", autoAssignHelp: "Assign accounts without a proxy binding to available nodes automatically.",
|
||||
|
||||
Reference in new issue
Block a user