From e3af4fce458bcce8632611e22fa8f3419dddb6f8 Mon Sep 17 00:00:00 2001 From: AmPlace <81105770+AmPlace@users.noreply.github.com> Date: Tue, 28 Jul 2026 09:46:05 +0800 Subject: [PATCH 1/6] fix(responses): normalize integer tool arguments --- .../infra/provider/cli/responses_arguments.go | 169 ++++++++++++++++++ .../provider/cli/responses_arguments_test.go | 128 +++++++++++++ .../infra/provider/cli/responses_response.go | 46 ++++- .../cli/responses_tool_declarations.go | 5 +- .../provider/cli/responses_tool_state.go | 2 + 5 files changed, 346 insertions(+), 4 deletions(-) create mode 100644 backend/internal/infra/provider/cli/responses_arguments.go create mode 100644 backend/internal/infra/provider/cli/responses_arguments_test.go diff --git a/backend/internal/infra/provider/cli/responses_arguments.go b/backend/internal/infra/provider/cli/responses_arguments.go new file mode 100644 index 00000000..fbfc2bf9 --- /dev/null +++ b/backend/internal/infra/provider/cli/responses_arguments.go @@ -0,0 +1,169 @@ +package cli + +import ( + "encoding/json" + "io" + "math" + "strconv" + "strings" +) + +const maxExactJSONInteger = float64(1<<53 - 1) + +// normalizeFunctionArguments repairs semantically integral JSON numbers that strict +// downstream decoders reject for integer fields. Grok Build can emit 60000.0 where +// clients such as Codex require the integer spelling 60000. +func normalizeFunctionArguments(arguments string, schema any) (string, bool) { + if strings.TrimSpace(arguments) == "" { + return arguments, false + } + decoder := json.NewDecoder(strings.NewReader(arguments)) + decoder.UseNumber() + var value any + if err := decoder.Decode(&value); err != nil { + return arguments, false + } + if err := decoder.Decode(new(any)); err != io.EOF { + return arguments, false + } + root, ok := schema.(map[string]any) + if !ok { + return arguments, false + } + normalized, changed := normalizeArgumentValue(value, root, root, 0) + if !changed { + return arguments, false + } + encoded, err := json.Marshal(normalized) + if err != nil { + return arguments, false + } + return string(encoded), true +} + +func normalizeArgumentValue(value any, schema, root map[string]any, depth int) (any, bool) { + if depth > 64 { + return value, false + } + changed := false + if ref, ok := schema["$ref"].(string); ok { + if resolved, ok := resolveLocalSchemaRef(root, ref); ok { + var current bool + value, current = normalizeArgumentValue(value, resolved, root, depth+1) + changed = changed || current + } + } + for _, keyword := range []string{"allOf", "anyOf", "oneOf"} { + branches, _ := schema[keyword].([]any) + for _, rawBranch := range branches { + branch, ok := rawBranch.(map[string]any) + if !ok { + continue + } + var current bool + value, current = normalizeArgumentValue(value, branch, root, depth+1) + changed = changed || current + } + } + if number, ok := value.(json.Number); ok && schemaRequiresInteger(schema) { + if normalized, ok := normalizeIntegralNumber(number); ok { + return normalized, true + } + return value, changed + } + switch typed := value.(type) { + case map[string]any: + properties, _ := schema["properties"].(map[string]any) + additional, _ := schema["additionalProperties"].(map[string]any) + for key, item := range typed { + property, ok := properties[key].(map[string]any) + if !ok { + property = additional + } + if property == nil { + continue + } + normalized, current := normalizeArgumentValue(item, property, root, depth+1) + if current { + typed[key] = normalized + changed = true + } + } + case []any: + prefixItems, _ := schema["prefixItems"].([]any) + items, _ := schema["items"].(map[string]any) + for index, item := range typed { + itemSchema := items + if index < len(prefixItems) { + if prefixSchema, ok := prefixItems[index].(map[string]any); ok { + itemSchema = prefixSchema + } + } + if itemSchema == nil { + continue + } + normalized, current := normalizeArgumentValue(item, itemSchema, root, depth+1) + if current { + typed[index] = normalized + changed = true + } + } + } + return value, changed +} + +func schemaRequiresInteger(schema map[string]any) bool { + switch value := schema["type"].(type) { + case string: + return value == "integer" + case []any: + integer := false + for _, item := range value { + kind, _ := item.(string) + if kind == "number" { + return false + } + integer = integer || kind == "integer" + } + return integer + default: + return false + } +} + +func normalizeIntegralNumber(number json.Number) (json.Number, bool) { + raw := number.String() + if !strings.ContainsAny(raw, ".eE") { + return number, false + } + value, err := strconv.ParseFloat(raw, 64) + if err != nil || math.IsInf(value, 0) || math.IsNaN(value) || math.Trunc(value) != value || math.Abs(value) > maxExactJSONInteger { + return number, false + } + normalized := strconv.FormatFloat(value, 'f', -1, 64) + if normalized == "-0" { + normalized = "0" + } + return json.Number(normalized), normalized != raw +} + +func schemaContainsInteger(value any) bool { + switch typed := value.(type) { + case map[string]any: + if schemaRequiresInteger(typed) { + return true + } + for _, child := range typed { + if schemaContainsInteger(child) { + return true + } + } + case []any: + for _, child := range typed { + if schemaContainsInteger(child) { + return true + } + } + } + return false +} diff --git a/backend/internal/infra/provider/cli/responses_arguments_test.go b/backend/internal/infra/provider/cli/responses_arguments_test.go new file mode 100644 index 00000000..99092fec --- /dev/null +++ b/backend/internal/infra/provider/cli/responses_arguments_test.go @@ -0,0 +1,128 @@ +package cli + +import ( + "encoding/json" + "io" + "strings" + "testing" +) + +func TestNormalizeFunctionArgumentsCoercesSchemaIntegers(t *testing.T) { + schema := map[string]any{ + "type": "object", + "properties": map[string]any{ + "timeout_ms": map[string]any{"type": "integer"}, + "ratio": map[string]any{"type": "number"}, + "items": map[string]any{ + "type": "array", + "items": map[string]any{"anyOf": []any{map[string]any{"type": "integer"}, map[string]any{"type": "null"}}}, + }, + }, + } + arguments := `{"timeout_ms":60000.0,"ratio":2.0,"items":[1.0,null,2.5]}` + normalized, changed := normalizeFunctionArguments(arguments, schema) + if !changed { + t.Fatal("expected integer arguments to be normalized") + } + if normalized != `{"items":[1,null,2.5],"ratio":2.0,"timeout_ms":60000}` { + t.Fatalf("normalized arguments = %s", normalized) + } +} + +func TestNormalizeFunctionArgumentsPreservesUnsafeValues(t *testing.T) { + schema := map[string]any{"type": "object", "properties": map[string]any{ + "fraction": map[string]any{"type": "integer"}, + "large": map[string]any{"type": "integer"}, + }} + arguments := `{"fraction":1.5,"large":9007199254740992.0}` + if normalized, changed := normalizeFunctionArguments(arguments, schema); changed || normalized != arguments { + t.Fatalf("unsafe arguments changed: changed=%v value=%s", changed, normalized) + } +} + +func TestNormalizeFunctionArgumentsFollowsLocalRefs(t *testing.T) { + schema := map[string]any{ + "$ref": "#/$defs/arguments", + "$defs": map[string]any{"arguments": map[string]any{ + "type": "object", + "properties": map[string]any{"timeout_ms": map[string]any{"type": "integer"}}, + }}, + } + normalized, changed := normalizeFunctionArguments(`{"timeout_ms":6e4}`, schema) + if !changed || normalized != `{"timeout_ms":60000}` { + t.Fatalf("referenced integer was not normalized: changed=%v value=%s", changed, normalized) + } +} + +func TestResponsesIntegerArgumentsNormalizedInJSONResponse(t *testing.T) { + request := []byte(`{ + "model":"public", + "tools":[{"type":"function","name":"wait_agent","parameters":{"type":"object","properties":{"timeout_ms":{"type":"integer"}}}}] + }`) + _, compatibility, err := normalizeResponsesRequest(request, "grok-4.5") + if err != nil { + t.Fatal(err) + } + if compatibility == nil { + t.Fatal("integer schema did not enable response compatibility") + } + response, err := compatibility.normalizeResponseJSON([]byte(`{ + "id":"resp_1","object":"response", + "output":[{"type":"function_call","call_id":"call_1","name":"wait_agent","arguments":"{\"timeout_ms\":60000.0}"}] + }`)) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(response, &payload); err != nil { + t.Fatal(err) + } + call := payload["output"].([]any)[0].(map[string]any) + if call["arguments"] != `{"timeout_ms":60000}` { + t.Fatalf("function arguments = %q", call["arguments"]) + } +} + +func TestResponsesIntegerArgumentsNormalizedInStream(t *testing.T) { + request := []byte(`{ + "model":"public", + "stream":true, + "tools":[{"type":"function","name":"wait_agent","parameters":{"type":"object","properties":{"timeout_ms":{"type":"integer"}}}}] + }`) + _, compatibility, err := normalizeResponsesRequest(request, "grok-4.5") + if err != nil { + t.Fatal(err) + } + stream := strings.Join([]string{ + `event: response.output_item.added`, + `data: {"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"wait_agent","arguments":""}}`, + ``, + `event: response.function_call_arguments.delta`, + `data: {"type":"response.function_call_arguments.delta","item_id":"fc_1","delta":"{\"timeout_ms\":60000"}`, + ``, + `event: response.function_call_arguments.delta`, + `data: {"type":"response.function_call_arguments.delta","item_id":"fc_1","delta":".0}"}`, + ``, + `event: response.function_call_arguments.done`, + `data: {"type":"response.function_call_arguments.done","item_id":"fc_1","arguments":"{\"timeout_ms\":60000.0}"}`, + ``, + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"wait_agent","arguments":"{\"timeout_ms\":60000.0}"}}`, + ``, + }, "\n") + body, err := io.ReadAll(compatibility.normalizeResponseStream(io.NopCloser(strings.NewReader(stream)))) + if err != nil { + t.Fatal(err) + } + text := string(body) + if strings.Contains(text, `60000.0`) { + t.Fatalf("stream retained floating integer: %s", text) + } + if strings.Count(text, `response.function_call_arguments.delta`) != 2 { + // One occurrence is the event line and one is the JSON type field. + t.Fatalf("unexpected normalized delta count: %s", text) + } + if !strings.Contains(text, `{\"timeout_ms\":60000}`) { + t.Fatalf("normalized arguments missing: %s", text) + } +} diff --git a/backend/internal/infra/provider/cli/responses_response.go b/backend/internal/infra/provider/cli/responses_response.go index cded75c6..a63f908c 100644 --- a/backend/internal/infra/provider/cli/responses_response.go +++ b/backend/internal/infra/provider/cli/responses_response.go @@ -80,6 +80,7 @@ type responsesStreamOutput struct { type responsesStreamCall struct { identity responsesToolIdentity + schema any arguments strings.Builder lastDelta map[string]any addedPayload map[string]any @@ -117,6 +118,11 @@ func (c *responsesToolCompatibility) rewriteStreamData(event string, data []byte } if kind == "response.function_call_arguments.delta" { identity, state, found := c.streamIdentity(payload) + if found && identity.Kind == responsesFunctionTool && state.schema != nil { + state.arguments.WriteString(stringField(payload, "delta")) + state.lastDelta = cloneJSONObject(payload) + return nil, nil + } if found && (identity.Kind == responsesToolSearch || identity.Kind == responsesCustomTool || identity.Kind == responsesApplyPatchTool) { state.arguments.WriteString(stringField(payload, "delta")) if identity.Kind == responsesCustomTool { @@ -127,6 +133,31 @@ func (c *responsesToolCompatibility) rewriteStreamData(event string, data []byte } if kind == "response.function_call_arguments.done" { identity, state, found := c.streamIdentity(payload) + if found && identity.Kind == responsesFunctionTool && state.schema != nil { + arguments := stringField(payload, "arguments") + if arguments == "" { + arguments = state.arguments.String() + } + normalized, _ := normalizeFunctionArguments(arguments, state.schema) + outputs := make([]responsesStreamOutput, 0, 2) + if state.lastDelta != nil { + delta := cloneJSONObject(state.lastDelta) + delta["delta"] = normalized + encoded, err := json.Marshal(delta) + if err != nil { + return nil, fmt.Errorf("编码 function arguments delta: %w", err) + } + outputs = append(outputs, responsesStreamOutput{Event: "response.function_call_arguments.delta", Data: encoded}) + } + done := cloneJSONObject(payload) + done["arguments"] = normalized + encoded, err := json.Marshal(done) + if err != nil { + return nil, fmt.Errorf("编码 function arguments done: %w", err) + } + outputs = append(outputs, responsesStreamOutput{Event: "response.function_call_arguments.done", Data: encoded}) + return outputs, nil + } if found && (identity.Kind == responsesToolSearch || identity.Kind == responsesApplyPatchTool) { // Tool Search 的 arguments 是结构化对象;等 output_item.done 带齐参数后再对下游可见。 return nil, nil @@ -184,7 +215,7 @@ func (c *responsesToolCompatibility) rememberStreamCall(item map[string]any) *re if !exists { return nil } - state := &responsesStreamCall{identity: identity} + state := &responsesStreamCall{identity: identity, schema: c.functionSchemas[stringField(item, "name")]} for _, key := range []string{stringField(item, "id"), stringField(item, "call_id")} { if key != "" { c.streamCalls[key] = state @@ -203,7 +234,7 @@ func (c *responsesToolCompatibility) streamIdentity(payload map[string]any) (res if !exists { return responsesToolIdentity{}, nil, false } - state := &responsesStreamCall{identity: identity} + state := &responsesStreamCall{identity: identity, schema: c.functionSchemas[stringField(payload, "name")]} for _, key := range []string{stringField(payload, "item_id"), stringField(payload, "call_id")} { if key != "" { c.streamCalls[key] = state @@ -241,12 +272,21 @@ func (c *responsesToolCompatibility) rewriteResponseValue(value any) error { } func (c *responsesToolCompatibility) rewriteFunctionCall(call map[string]any) error { - identity, exists := c.aliases[stringField(call, "name")] + alias := stringField(call, "name") + identity, exists := c.aliases[alias] if !exists { return nil } switch identity.Kind { case responsesFunctionTool: + if schema := c.functionSchemas[alias]; schema != nil { + if arguments, ok := call["arguments"].(string); ok { + normalized, changed := normalizeFunctionArguments(arguments, schema) + if changed { + call["arguments"] = normalized + } + } + } call["name"] = identity.Name if identity.Namespace != "" { call["namespace"] = identity.Namespace diff --git a/backend/internal/infra/provider/cli/responses_tool_declarations.go b/backend/internal/infra/provider/cli/responses_tool_declarations.go index 68574873..d6b9ef75 100644 --- a/backend/internal/infra/provider/cli/responses_tool_declarations.go +++ b/backend/internal/infra/provider/cli/responses_tool_declarations.go @@ -69,7 +69,7 @@ func normalizeResponsesTools(payload map[string]json.RawMessage) (*responsesTool if err := compatibility.normalizeToolChoice(payload, normalizedTools); err != nil { return nil, err } - if !compatibility.changed { + if !compatibility.changed && len(compatibility.functionSchemas) == 0 { return nil, nil } return compatibility, nil @@ -184,6 +184,9 @@ func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, cl } identity := responsesToolIdentity{Kind: responsesFunctionTool, Namespace: namespace, Name: name} alias := c.alias(identity) + if parameters, exists := tool["parameters"]; exists && schemaContainsInteger(parameters) { + c.functionSchemas[alias] = cloneJSONValue(parameters) + } converted["name"] = alias if namespace != "" || alias != name { c.changed = true diff --git a/backend/internal/infra/provider/cli/responses_tool_state.go b/backend/internal/infra/provider/cli/responses_tool_state.go index bfdbfc76..726fad3b 100644 --- a/backend/internal/infra/provider/cli/responses_tool_state.go +++ b/backend/internal/infra/provider/cli/responses_tool_state.go @@ -36,6 +36,7 @@ func (i responsesToolIdentity) key() string { type responsesToolCompatibility struct { aliases map[string]responsesToolIdentity identityAliases map[string]string + functionSchemas map[string]any visibleTools []any deferredSurfaces []string clientSearchTool map[string]any @@ -64,6 +65,7 @@ func newResponsesToolCompatibility() *responsesToolCompatibility { return &responsesToolCompatibility{ aliases: make(map[string]responsesToolIdentity), identityAliases: make(map[string]string), + functionSchemas: make(map[string]any), streamCalls: make(map[string]*responsesStreamCall), warningSet: make(map[string]struct{}), } From 75f4f7a7f36d669746d118acb14fbec724b32f1d Mon Sep 17 00:00:00 2001 From: AmPlace <81105770+AmPlace@users.noreply.github.com> Date: Tue, 28 Jul 2026 11:55:57 +0800 Subject: [PATCH 2/6] fix: rotate Build proxy-pool tunnels per request --- backend/internal/infra/egress/manager.go | 12 ++++- backend/internal/infra/egress/manager_test.go | 7 ++- .../infra/egress/sticky_retry_test.go | 49 +++++++++++++++++++ 3 files changed, 65 insertions(+), 3 deletions(-) diff --git a/backend/internal/infra/egress/manager.go b/backend/internal/infra/egress/manager.go index baa95370..b3281e99 100644 --- a/backend/internal/infra/egress/manager.go +++ b/backend/internal/infra/egress/manager.go @@ -68,6 +68,7 @@ type Lease struct { browser *browserClient sticky bool proxyPool bool + freshTunnel bool clearanceKey string clearanceManager *Manager release func() @@ -92,6 +93,14 @@ func (l *Lease) doRequest(request *http.Request, invalidateForbidden bool) (*htt if l == nil || l.client == nil { return nil, errors.New("出口客户端未初始化") } + // Rotating proxy endpoints choose an exit when a new CONNECT tunnel is + // established. Reusing a Build keep-alive/HTTP2 connection would pin many + // otherwise independent requests to one exit and defeat proxy-pool + // rotation. Proxy-pool mode is explicit, so trade the extra handshake for a + // fresh tunnel without changing fixed-proxy, direct, Web, or Console paths. + if l.Scope == domain.ScopeBuild && l.freshTunnel { + request.Close = true + } response, err := l.do(request) recordPhysicalCall(request.Context(), response, err) if invalidateForbidden && err == nil && response != nil && response.StatusCode == http.StatusForbidden { @@ -891,6 +900,7 @@ func (m *Manager) leaseForNode(ctx context.Context, scope domain.Scope, affinity } sticky := strings.Contains(proxyURL, application.ProxyAccountPlaceholder) proxyPool := selected.ProxyPool || sticky + freshTunnel := selected.ProxyPool && !sticky if sticky { accountKey := accountFromContext(ctx) if accountKey == "" && strings.TrimSpace(affinity) != "" { @@ -942,7 +952,7 @@ func (m *Manager) leaseForNode(ctx context.Context, scope domain.Scope, affinity m.incrementInflight(selected.ID) recordSelection(ctx, Selection{NodeID: selected.ID, NodeName: selected.Name, Scope: scope, Proxied: proxyURL != ""}) var once sync.Once - return &Lease{NodeID: selected.ID, NodeName: selected.Name, Scope: scope, ProxyURL: proxyURL, UserAgent: userAgent, CFCookies: cookies, client: client.client, browser: client.browser, sticky: sticky, proxyPool: proxyPool, clearanceKey: clearanceKey, clearanceManager: m, release: func() { + return &Lease{NodeID: selected.ID, NodeName: selected.Name, Scope: scope, ProxyURL: proxyURL, UserAgent: userAgent, CFCookies: cookies, client: client.client, browser: client.browser, sticky: sticky, proxyPool: proxyPool, freshTunnel: freshTunnel, clearanceKey: clearanceKey, clearanceManager: m, release: func() { once.Do(func() { m.decrementInflight(selected.ID) }) diff --git a/backend/internal/infra/egress/manager_test.go b/backend/internal/infra/egress/manager_test.go index da01859b..4b54ceb2 100644 --- a/backend/internal/infra/egress/manager_test.go +++ b/backend/internal/infra/egress/manager_test.go @@ -1396,6 +1396,9 @@ func TestProxyPoolTransportFailureDoesNotCreateGlobalCooldown(t *testing.T) { if err != nil || !configured || lease == nil { t.Fatalf("pool lease blocked by stale cooldown: configured=%v lease=%#v err=%v", configured, lease, err) } + if !lease.freshTunnel { + t.Fatal("explicit proxy-pool lease must request a fresh Build tunnel") + } lease.Release() manager.FeedbackForScope(context.Background(), domain.ScopeBuild, 1, 0, errors.New("connection refused")) if repository.updates != 0 || repository.node.FailureCount != 3 || repository.node.CooldownUntil == nil { @@ -1439,8 +1442,8 @@ func TestAccountTemplateIsAnEffectiveProxyPool(t *testing.T) { t.Fatalf("account-template lease blocked by stale cooldown: configured=%v lease=%#v err=%v", configured, lease, err) } defer lease.Release() - if !lease.sticky || !lease.proxyPool { - t.Fatalf("account-template lease flags: sticky=%v proxyPool=%v", lease.sticky, lease.proxyPool) + if !lease.sticky || !lease.proxyPool || lease.freshTunnel { + t.Fatalf("account-template lease flags: sticky=%v proxyPool=%v freshTunnel=%v", lease.sticky, lease.proxyPool, lease.freshTunnel) } } diff --git a/backend/internal/infra/egress/sticky_retry_test.go b/backend/internal/infra/egress/sticky_retry_test.go index 43794487..26b636e7 100644 --- a/backend/internal/infra/egress/sticky_retry_test.go +++ b/backend/internal/infra/egress/sticky_retry_test.go @@ -8,6 +8,8 @@ import ( "net/http/httptrace" "strings" "testing" + + egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress" ) type scriptedRequestClient struct { @@ -23,6 +25,53 @@ func (c *scriptedRequestClient) Do(request *http.Request) (*http.Response, error func (c *scriptedRequestClient) CloseIdleConnections() { c.closedIdle++ } +func TestBuildProxyPoolLeaseForcesFreshTunnel(t *testing.T) { + client := &scriptedRequestClient{do: func(_ int, request *http.Request) (*http.Response, error) { + if !request.Close { + t.Fatal("Build proxy-pool request must disable connection reuse") + } + return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody, Header: make(http.Header)}, nil + }} + lease := &Lease{client: client, Scope: egressdomain.ScopeBuild, proxyPool: true, freshTunnel: true} + request, err := http.NewRequest(http.MethodPost, "https://example.com/generate", bytes.NewReader([]byte("payload"))) + if err != nil { + t.Fatal(err) + } + if _, err := lease.Do(request); err != nil { + t.Fatal(err) + } +} + +func TestFixedBuildWebAndAccountBoundProxyKeepConnectionReuse(t *testing.T) { + for _, test := range []struct { + name string + scope egressdomain.Scope + proxyPool bool + freshTunnel bool + }{ + {name: "fixed Build proxy", scope: egressdomain.ScopeBuild}, + {name: "Web proxy pool", scope: egressdomain.ScopeWeb, proxyPool: true, freshTunnel: true}, + {name: "account-bound Build proxy", scope: egressdomain.ScopeBuild, proxyPool: true}, + } { + t.Run(test.name, func(t *testing.T) { + client := &scriptedRequestClient{do: func(_ int, request *http.Request) (*http.Response, error) { + if request.Close { + t.Fatal("request unexpectedly disabled connection reuse") + } + return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody, Header: make(http.Header)}, nil + }} + lease := &Lease{client: client, Scope: test.scope, proxyPool: test.proxyPool, freshTunnel: test.freshTunnel} + request, err := http.NewRequest(http.MethodGet, "https://example.com/models", nil) + if err != nil { + t.Fatal(err) + } + if _, err := lease.Do(request); err != nil { + t.Fatal(err) + } + }) + } +} + func TestStickyLeaseRetriesSafeProxyConnectFailure(t *testing.T) { client := &scriptedRequestClient{do: func(call int, _ *http.Request) (*http.Response, error) { if call == 1 { From 3481139291305bc42de256e9d702871fb5679683 Mon Sep 17 00:00:00 2001 From: AmPlace <81105770+AmPlace@users.noreply.github.com> Date: Tue, 28 Jul 2026 12:26:22 +0800 Subject: [PATCH 3/6] fix: update Build free quota estimate --- backend/internal/application/account/quota_test.go | 6 +++--- backend/internal/application/account/service.go | 4 +++- backend/internal/application/gateway/service_test.go | 8 ++++++++ 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/backend/internal/application/account/quota_test.go b/backend/internal/application/account/quota_test.go index 20a60b1a..68225ea2 100644 --- a/backend/internal/application/account/quota_test.go +++ b/backend/internal/application/account/quota_test.go @@ -35,10 +35,10 @@ func (r *quotaResetRepository) ResetQuotaState(_ context.Context, provider accou func TestNewQuotaViewFreeUsesObservedRollingTokens(t *testing.T) { quota := newQuotaView(&accountdomain.Billing{IsUnifiedBillingUser: true}, 250_000, nil, "grok-4.5-build-free", false) - if quota.Type != QuotaTypeFree || quota.Unit != "tokens" || quota.Limit != 1_000_000 || quota.LimitKnown || quota.Confidence != "observed" { + if quota.Type != QuotaTypeFree || quota.Unit != "tokens" || quota.Limit != 500_000 || quota.LimitKnown || quota.Confidence != "observed" { t.Fatalf("quota = %#v", quota) } - if quota.Used != 250_000 || quota.Remaining != 750_000 || quota.UsagePercent != 25 || quota.WindowHours != 24 || !quota.Observed { + if quota.Used != 250_000 || quota.Remaining != 250_000 || quota.UsagePercent != 50 || quota.WindowHours != 24 || !quota.Observed { t.Fatalf("quota = %#v", quota) } } @@ -74,7 +74,7 @@ func TestNewQuotaViewUnknownWithoutBillingSnapshot(t *testing.T) { func TestNewQuotaViewEstimatesFreeFromObservedZeroBillingProfile(t *testing.T) { quota := newQuotaView(&accountdomain.Billing{PlanName: "Free", IsUnifiedBillingUser: true, TopUpMethod: "TOP_UP_METHOD_SAVED_PAYMENT_METHOD"}, 100, nil, "", false) - if quota.Type != QuotaTypeFree || quota.Source != "billingProfile" || quota.Confidence != "estimated" || quota.Limit != 1_000_000 || quota.LimitKnown { + if quota.Type != QuotaTypeFree || quota.Source != "billingProfile" || quota.Confidence != "estimated" || quota.Limit != 500_000 || quota.LimitKnown { t.Fatalf("quota = %#v", quota) } } diff --git a/backend/internal/application/account/service.go b/backend/internal/application/account/service.go index 9c77f343..7c3abc08 100644 --- a/backend/internal/application/account/service.go +++ b/backend/internal/application/account/service.go @@ -39,7 +39,9 @@ var ( var ErrCredentialRefreshPermanent = errors.New("OAuth refresh token 已永久失效") const ( - estimatedFreeTokenLimit int64 = 1_000_000 + // estimatedFreeTokenLimit is only a fallback until an upstream exhaustion + // response supplies the account-specific actual/limit pair. + estimatedFreeTokenLimit int64 = 500_000 freeUsageWindow time.Duration = 24 * time.Hour forcedRefreshMinInterval time.Duration = 30 * time.Second paidProbeRetryInterval time.Duration = 15 * time.Minute diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index 7fec6c94..16fd60c7 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -1120,6 +1120,14 @@ func TestParseFreeQuotaExhaustion(t *testing.T) { } } +func TestParseFreeQuotaExhaustionCurrentBuildFreeLimit(t *testing.T) { + body := []byte(`{"code":"subscription:free-usage-exhausted","error":"You've used all the included free usage for model grok-4.5-build-free for now. Usage resets over a rolling 24-hour window — tokens (actual/limit): 537365/500000."}`) + used, limit, exhausted := parseFreeQuotaExhaustion(body) + if !exhausted || used != 537_365 || limit != 500_000 { + t.Fatalf("exhausted=%v used=%d limit=%d", exhausted, used, limit) + } +} + func TestGatewayCoolsFreeBuildAccountsAfterForbidden(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "systemic-forbidden.db")) From f4f439a462a92b031f94dfe24fcbe0b9e67522fc Mon Sep 17 00:00:00 2001 From: AmPlace <81105770+AmPlace@users.noreply.github.com> Date: Tue, 28 Jul 2026 12:26:31 +0800 Subject: [PATCH 4/6] feat: batch update account concurrency --- .../src/features/accounts/accounts-api.ts | 4 ++ .../src/features/accounts/accounts-page.tsx | 54 +++++++++++++++++++ frontend/src/shared/i18n/index.ts | 6 ++- 3 files changed, 63 insertions(+), 1 deletion(-) diff --git a/frontend/src/features/accounts/accounts-api.ts b/frontend/src/features/accounts/accounts-api.ts index ba5493cf..71531404 100644 --- a/frontend/src/features/accounts/accounts-api.ts +++ b/frontend/src/features/accounts/accounts-api.ts @@ -541,6 +541,10 @@ export function updateAccountsEnabled(ids: string[], enabled: boolean, provider: return apiRequest("/api/admin/v1/accounts/batch", { method: "PATCH", body: { ids, enabled, provider } }, decodeCountResult<{ updated: number }>("updated")); } +export function updateAccountsMaxConcurrent(ids: string[], maxConcurrent: number, provider: AccountProvider): Promise<{ updated: number }> { + return apiRequest("/api/admin/v1/accounts/batch", { method: "PATCH", body: { ids, maxConcurrent, provider } }, decodeCountResult<{ updated: number }>("updated")); +} + export function refreshAccountsQuota(ids: string[], provider: AccountProvider): Promise<{ succeeded: number; failed: number }> { return apiRequest("/api/admin/v1/accounts/batch/refresh-quotas", { method: "POST", body: { ids, provider } }, createObjectDecoder("account batch", { succeeded: isNumber, failed: isNumber })); } diff --git a/frontend/src/features/accounts/accounts-page.tsx b/frontend/src/features/accounts/accounts-page.tsx index 49c49c1b..69758600 100644 --- a/frontend/src/features/accounts/accounts-page.tsx +++ b/frontend/src/features/accounts/accounts-page.tsx @@ -68,6 +68,7 @@ import { syncWebAccountsToConsole, updateAccount, updateAccountsEnabled, + updateAccountsMaxConcurrent, type AccountDTO, type AccountCleanupStatus, type AccountProvider, @@ -133,6 +134,8 @@ export function AccountsPage() { const [sort, setSort] = useState({ field: "createdAt", order: "desc" }); const [selection, setSelection] = useState(() => ({ provider: "grok_build", ids: new Set() })); const [batchDeleteOpen, setBatchDeleteOpen] = useState(false); + const [batchConcurrencyOpen, setBatchConcurrencyOpen] = useState(false); + const [batchMaxConcurrent, setBatchMaxConcurrent] = useState("1"); const [batchQuotaTaskOpen, setBatchQuotaTaskOpen] = useState(false); const [batchQuotaTask, setBatchQuotaTask] = useState("sync"); const [egressConfigurationOpen, setEgressConfigurationOpen] = useState(false); @@ -645,6 +648,17 @@ export function AccountsPage() { onError: showError, }); + const batchConcurrencyMutation = useMutation({ + mutationFn: (maxConcurrent: number) => updateAccountsMaxConcurrent([...selected], maxConcurrent, provider), + onSuccess: () => { + setBatchConcurrencyOpen(false); + clearSelection(); + invalidateAccountData(); + toast.success(t("accounts.batchConcurrencyUpdated")); + }, + onError: showError, + }); + const batchBillingMutation = useMutation({ mutationFn: () => refreshAccountsQuota([...selected], provider), onSuccess: (result) => { @@ -1024,6 +1038,7 @@ export function AccountsPage() { || webConsoleSyncMutation.isPending || importMutation.isPending || batchUpdateMutation.isPending + || batchConcurrencyMutation.isPending || batchBillingMutation.isPending || batchQuotaResetMutation.isPending || batchTokenMutation.isPending @@ -1172,6 +1187,10 @@ export function AccountsPage() { + + + + + + { if (!open && batchDeleteMutation.isPending) return; setBatchDeleteOpen(open); diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index 448cf1e7..77a61712 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -589,6 +589,10 @@ const resources = { linkedDeleteHint: "仅删除已关联的账号;未关联账号保持不变。", linkedDeletePreviewFailed: "关联数量加载失败,请取消勾选后重试,或稍后再删。", batchUpdated: "所选账号已更新", + batchSetConcurrency: "设置并发", + batchConcurrencyTitle: "设置所选 {{count}} 个账号的并发?", + batchConcurrencyDescription: "同一账号同时处理的请求数,允许范围为 1–256。大号池可从 1 开始,降低单账号并发压力。", + batchConcurrencyUpdated: "所选账号并发已更新", batchBillingRefreshed: "额度同步完成:成功 {{succeeded}},失败 {{failed}}", batchDeleteTitle: "删除所选 {{count}} 个账号?", cleanupAction: "账号清理", @@ -1295,7 +1299,7 @@ const resources = { accountQuotaTask: { title: "Process quota for {{count}} selected accounts", description: "Choose the quota task to run for the selected Grok Build accounts.", allTitle: "Process quota for all accounts", allDescription: "Choose the quota task to run for all enabled Grok Build accounts.", syncDescription: "Request upstream Billing and update local quota snapshots, account tiers, and recovery state.", resetAllDescription: "Clear local waiting-reset and exhausted-quota blocks for all enabled Grok Build accounts without changing upstream Billing or audit history.", execute: "Run task" }, accountExport: { countDescription: "Exports accounts in stable order, up to 10,000 per batch.", batchProgress: "Exported {{count}} accounts; the next download is batch {{batch}}.", nextBatch: "Export next batch", batchCompleted: "Exported {{count}} accounts in this batch", completed: "Export complete: {{count}} accounts" }, dashboard: { title: "Dashboard", subtitle: "Welcome, {{name}}", lastUpdated: "Updated {{time}}", welcome: "Welcome, {{name}}", gatewayOnline: "Gateway healthy", gatewayOffline: "Unavailable", gatewayReady: "The gateway is ready to process API requests.", gatewayNeedsAccount: "Connect an available account to process API requests.", manageAccounts: "Manage accounts", usage: "Usage overview", seeAll: "View audits", activeAccounts: "Available accounts", accountCapacity: "{{total}} accounts · {{rate}}% success", manage: "Manage", tokens: "Total tokens", requests: "Requests", successRate: "Success rate", accountCount: "Accounts", accountDistribution: "Build {{build}} · Web {{web}} · Console {{console}}", requestSuccessRate: "{{rate}}% success", averageRequestCost: "{{cost}} per request", availableSummary: "{{active}} / {{total}} available", requestBreakdown: "{{success}} succeeded · {{failed}} failed", requestQualitySummary: "{{success}}% success · {{failed}} failed", periodSummary: "Current {{period}} range", successSummary: "{{success}} / {{total}} requests succeeded", trend: "Usage trend", trendRequests: "Requests", trendTokens: "Tokens", trendSummary: "{{requests}} requests · {{rate}}% success", resourcesTitle: "Resource availability", availability: "Account availability", unavailableAccounts: "Unavailable accounts", unavailableSummary: "{{unavailable}} / {{total}} unavailable", enabledModels: "Enabled models", modelsAvailableSummary: "{{enabled}} / {{total}} enabled", activeClientKeys: "Available keys", keysAvailableSummary: "{{active}} / {{total}} available", allTimeRequests: "All-time requests", allTimeRequestsSummary: "Since the first recorded request", qualityTitle: "Request quality", successfulRequests: "Successful requests", failedRequests: "Failed requests", topModels: "Top 10 model billing", model: "Model", share: "Call share", noTopModels: "No model calls in this period", noTrendData: "No usage data in this period", billing: "Billing", billingSummary: "Accumulated in the current {{period}} range", inputTokens: "Input", cachedTokens: "Cached", outputTokens: "Output", reasoningTokens: "Reasoning", uncachedInput: "Uncached input", visibleOutput: "Visible output", otherModels: "Other models", providerDistribution: "Provider distribution", providerDetail: "{{rate}}% success · {{tokens}} tokens", providerStripeDetail: "{{provider}} · {{requests}} requests · {{share}}%", providerNoRequests: "No provider requests", activityTitle: "Request activity", lastDays: "Last {{count}} days", activityDay: "{{date}} · {{requests}} requests", activityLess: "Less", activityMore: "More", tokenBreakdown: "Input {{input}} · Cached {{cached}} · Output {{output}} · Reasoning {{reasoning}}", tokenEfficiency: "Cache hit rate {{rate}}%", explore: "Manage resources", accountsProduct: "Upstream accounts", accountsProductDescription: "Manage OAuth credentials, health, quota, and concurrency.", keysProduct: "Client keys", keysProductDescription: "Create downstream API keys and control models, RPM, and concurrency.", modelsProduct: "Model routes", modelsProductDescription: "Manage public model IDs, upstream mappings, and availability.", auditsProduct: "Request audits", auditsProductDescription: "Inspect status, latency, and token usage records.", gatewayFooter: "A lightweight API gateway", learnMore: "View models", unknown: "Unknown" }, - accounts: { title: "Upstream accounts", description: "Manage separate Grok Build OAuth and Grok Web SSO pools, health, concurrency, and quotas.", add: "Connect account", connectAccount: "Connect account", convertToBuild: "Convert to Build", convertToBuildTitle: "Convert Grok Web accounts to Build?", convertToBuildDescription: "Choose the conversion scope for the selected {{count}} Web accounts. Conversion may take a moment.", convertingProgress: "Converting {{completed}} / {{total}}", syncingProgress: "Syncing {{completed}} / {{total}}", conversionCompleted: "Conversion complete: {{created}} created, {{linked}} linked, {{skipped}} skipped, {{failed}} failed", linkedAccountTooltip: "Linked account: {{name}}", syncAll: "Sync all", renewAll: "Renew all", syncAllTitle: "Sync all accounts?", syncAllDescription: "Refresh quota data for every enabled Grok Build account.", syncAllWebDescription: "Refresh real quota data for every enabled Grok Web account.", renewAllTitle: "Renew all accounts?", renewAllDescription: "Refresh every renewable Grok Build credential. Accounts without automatic renewal will be skipped.", search: "Search accounts", deviceLogin: "Device OAuth", importAuth: "Import account files", importSSO: "Import SSO JSON", quickImportSSO: "Quick import SSO", importWebFile: "Import account files", quickImportTitle: "Quick import Grok Web accounts", quickImportDescription: "Paste multiple SSO tokens or upload a TXT file with one token per line. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", uploadTXT: "Upload TXT", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export account file", exported: "Account credentials exported", exportTitle: "Export {{provider}} accounts?", exportDescription: "The JSON contains credentials for the current provider and any configured Cloudflare cookies, and can be imported back into this project. Store it only in a trusted location.", exportCount: "Export count", exportCountDescription: "Exports newest accounts first, up to 10,000 per batch.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", buildAccountCount: "Grok Build accounts", webAccountCount: "Grok Web accounts", consoleAccountCount: "Grok Console accounts", abnormalAccountCount: "Abnormal accounts", routableAccountCount: "{{count}} routable", abnormalAccountBreakdown: "Recovering {{recovering}} · Needs attention {{attention}}", riskAccountCount: "Risk {{count}}", riskFilter: "Risk", riskNormal: "Normal", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", updatedWithModelSyncFailure: "Account updated, but model capability sync failed. Run model sync again later.", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", botRisk: "Risk", botRiskTooltip: "Bot risk control. This may affect video generation and other permissions.", nsfwEnabledMark: "NSFW", nsfwEnabledTooltip: "NSFW enabled · {{time}}", agreementFilter: "Account agreements", agreementNsfwEnabled: "NSFW enabled", agreementNsfwDisabled: "NSFW not enabled", agreementTermsAccepted: "Terms accepted", agreementTermsNotAccepted: "Terms not accepted", agreementAllAccepted: "All accepted", agreementAllNotAccepted: "All not accepted", associationFilter: "Account links", associationWebLinked: "Web linked", associationWebUnlinked: "Web not linked", associationBuildLinked: "Build linked", associationBuildUnlinked: "Build not linked", associationConsoleLinked: "Console linked", associationConsoleUnlinked: "Console not linked", associationAllLinked: "All linked", associationAllUnlinked: "All not linked", buildRouteMode: { label: "Upstream endpoint", auto: "Automatic", build: "Build", xai: "XAI", autoDescription: "Selects an upstream based on account tier and risk status.", buildDescription: "Routes all requests to Build with XAI fallback disabled.", xaiDescription: "Routes all inference and video requests to XAI.", xaiUnconfirmedWarning: "This account has not been confirmed for XAI access; the upstream may reject requests." }, buildSuperEntitled: { label: "Mark as Super manually", description: "Use only when automatic tier detection is inaccurate. Enabled accounts sync models with Super access." }, quotaFree: "Free", quotaSuper: "Super", quotaPaid: "Super", quotaUnknown: "Unknown", paidQuotaUsage: "Upstream quota usage", weeklyQuota: "Weekly", monthlyQuota: "Monthly", weeklyLimit: "Weekly limit {{percent}}% remaining", freeObservedUsage: "{{used}} tokens observed in the last 24 hours", freeEstimatedUsage: "About {{used}} / {{limit}} tokens", freeEstimatedDescription: "Estimated from observed Grok Build Free characteristics; upstream exhaustion data takes precedence", observedRolling: "Free accounts use this proxy's rolling observation and may differ from upstream billing data", upstreamConfirmed: "Exhaustion confirmed by upstream", waitingReset: "Waiting reset", waitingResetUntil: "Waiting for reset · probe after {{time}} on real traffic", paidWaitingResetUntil: "Waiting for reset · check the upstream Billing period after {{time}}", probing: "Probing", probingQuota: "Checking quota recovery with real traffic", paidProbingQuota: "Checking whether the upstream Billing period has recovered", upstreamBilling: "Upstream billing data", deviceTitle: "Connect Grok Build", deviceDescription: "Complete authorization in a new window. This page will check status automatically.", userCode: "Device code", openVerification: "Continue to authorization", waiting: "Waiting for authorization", expiresAt: "Expires {{time}}", deleteTitle: "Delete account?", deleteDescription: "Credentials and quota snapshots will be removed. This cannot be undone.", deleteConfirm: "Delete", linkedDeleteTitle: "Also delete linked accounts?", linkedDeleteSelectAll: "Select all linked", linkedDeleteClearAll: "Clear linked selection", linkedDeleteExtra: "+{{count}}", linkedDeleteExtraPending: "+—", linkedDeleteExtraFailed: "!", linkedDeleteHint: "Only linked accounts are deleted; unlinked accounts remain unchanged.", linkedDeletePreviewFailed: "Failed to load linked counts. Uncheck and retry, or delete later.", batchUpdated: "Selected accounts updated", batchBillingRefreshed: "Quota sync complete: {{succeeded}} succeeded, {{failed}} failed", batchDeleteTitle: "Delete {{count}} selected accounts?", cleanupAction: "Clean up accounts", cleanupTitle: "Clean up {{provider}} accounts", cleanupDescription: "Delete accounts in the selected states from this provider, including their quota data. Normal accounts are never affected. This cannot be undone.", cleanupCompleted: "Deleted {{deleted}} accounts", deletedWithSkipped: "Deleted {{deleted}} accounts, skipped {{skipped}} groups with active video jobs", cleanupCompletedDetailed: "Deleted {{deleted}} accounts ({{linked}} linked), skipped {{skipped}} groups", cleanupLinkedWarning: "Warning: linked accounts are not limited to the selected states and may include healthy accounts; they will be deleted too.", cleanupPreviewFailed: "Failed to load estimated counts. Adjust selection and retry, or clean up later.", cleanupPreviewTotal: "About {{total}} accounts will be deleted", cleanupStart: "Start cleanup" }, + accounts: { title: "Upstream accounts", description: "Manage separate Grok Build OAuth and Grok Web SSO pools, health, concurrency, and quotas.", add: "Connect account", connectAccount: "Connect account", convertToBuild: "Convert to Build", convertToBuildTitle: "Convert Grok Web accounts to Build?", convertToBuildDescription: "Choose the conversion scope for the selected {{count}} Web accounts. Conversion may take a moment.", convertingProgress: "Converting {{completed}} / {{total}}", syncingProgress: "Syncing {{completed}} / {{total}}", conversionCompleted: "Conversion complete: {{created}} created, {{linked}} linked, {{skipped}} skipped, {{failed}} failed", linkedAccountTooltip: "Linked account: {{name}}", syncAll: "Sync all", renewAll: "Renew all", syncAllTitle: "Sync all accounts?", syncAllDescription: "Refresh quota data for every enabled Grok Build account.", syncAllWebDescription: "Refresh real quota data for every enabled Grok Web account.", renewAllTitle: "Renew all accounts?", renewAllDescription: "Refresh every renewable Grok Build credential. Accounts without automatic renewal will be skipped.", search: "Search accounts", deviceLogin: "Device OAuth", importAuth: "Import account files", importSSO: "Import SSO JSON", quickImportSSO: "Quick import SSO", importWebFile: "Import account files", quickImportTitle: "Quick import Grok Web accounts", quickImportDescription: "Paste multiple SSO tokens or upload a TXT file with one token per line. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", uploadTXT: "Upload TXT", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export account file", exported: "Account credentials exported", exportTitle: "Export {{provider}} accounts?", exportDescription: "The JSON contains credentials for the current provider and any configured Cloudflare cookies, and can be imported back into this project. Store it only in a trusted location.", exportCount: "Export count", exportCountDescription: "Exports newest accounts first, up to 10,000 per batch.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", buildAccountCount: "Grok Build accounts", webAccountCount: "Grok Web accounts", consoleAccountCount: "Grok Console accounts", abnormalAccountCount: "Abnormal accounts", routableAccountCount: "{{count}} routable", abnormalAccountBreakdown: "Recovering {{recovering}} · Needs attention {{attention}}", riskAccountCount: "Risk {{count}}", riskFilter: "Risk", riskNormal: "Normal", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", updatedWithModelSyncFailure: "Account updated, but model capability sync failed. Run model sync again later.", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", botRisk: "Risk", botRiskTooltip: "Bot risk control. This may affect video generation and other permissions.", nsfwEnabledMark: "NSFW", nsfwEnabledTooltip: "NSFW enabled · {{time}}", agreementFilter: "Account agreements", agreementNsfwEnabled: "NSFW enabled", agreementNsfwDisabled: "NSFW not enabled", agreementTermsAccepted: "Terms accepted", agreementTermsNotAccepted: "Terms not accepted", agreementAllAccepted: "All accepted", agreementAllNotAccepted: "All not accepted", associationFilter: "Account links", associationWebLinked: "Web linked", associationWebUnlinked: "Web not linked", associationBuildLinked: "Build linked", associationBuildUnlinked: "Build not linked", associationConsoleLinked: "Console linked", associationConsoleUnlinked: "Console not linked", associationAllLinked: "All linked", associationAllUnlinked: "All not linked", buildRouteMode: { label: "Upstream endpoint", auto: "Automatic", build: "Build", xai: "XAI", autoDescription: "Selects an upstream based on account tier and risk status.", buildDescription: "Routes all requests to Build with XAI fallback disabled.", xaiDescription: "Routes all inference and video requests to XAI.", xaiUnconfirmedWarning: "This account has not been confirmed for XAI access; the upstream may reject requests." }, buildSuperEntitled: { label: "Mark as Super manually", description: "Use only when automatic tier detection is inaccurate. Enabled accounts sync models with Super access." }, quotaFree: "Free", quotaSuper: "Super", quotaPaid: "Super", quotaUnknown: "Unknown", paidQuotaUsage: "Upstream quota usage", weeklyQuota: "Weekly", monthlyQuota: "Monthly", weeklyLimit: "Weekly limit {{percent}}% remaining", freeObservedUsage: "{{used}} tokens observed in the last 24 hours", freeEstimatedUsage: "About {{used}} / {{limit}} tokens", freeEstimatedDescription: "Estimated from observed Grok Build Free characteristics; upstream exhaustion data takes precedence", observedRolling: "Free accounts use this proxy's rolling observation and may differ from upstream billing data", upstreamConfirmed: "Exhaustion confirmed by upstream", waitingReset: "Waiting reset", waitingResetUntil: "Waiting for reset · probe after {{time}} on real traffic", paidWaitingResetUntil: "Waiting for reset · check the upstream Billing period after {{time}}", probing: "Probing", probingQuota: "Checking quota recovery with real traffic", paidProbingQuota: "Checking whether the upstream Billing period has recovered", upstreamBilling: "Upstream billing data", deviceTitle: "Connect Grok Build", deviceDescription: "Complete authorization in a new window. This page will check status automatically.", userCode: "Device code", openVerification: "Continue to authorization", waiting: "Waiting for authorization", expiresAt: "Expires {{time}}", deleteTitle: "Delete account?", deleteDescription: "Credentials and quota snapshots will be removed. This cannot be undone.", deleteConfirm: "Delete", linkedDeleteTitle: "Also delete linked accounts?", linkedDeleteSelectAll: "Select all linked", linkedDeleteClearAll: "Clear linked selection", linkedDeleteExtra: "+{{count}}", linkedDeleteExtraPending: "+—", linkedDeleteExtraFailed: "!", linkedDeleteHint: "Only linked accounts are deleted; unlinked accounts remain unchanged.", linkedDeletePreviewFailed: "Failed to load linked counts. Uncheck and retry, or delete later.", batchUpdated: "Selected accounts updated", batchSetConcurrency: "Set concurrency", batchConcurrencyTitle: "Set concurrency for {{count}} selected accounts?", batchConcurrencyDescription: "Sets the number of simultaneous requests per account from 1 to 256. Large pools can start at 1 to reduce per-account pressure.", batchConcurrencyUpdated: "Concurrency updated for selected accounts", batchBillingRefreshed: "Quota sync complete: {{succeeded}} succeeded, {{failed}} failed", batchDeleteTitle: "Delete {{count}} selected accounts?", cleanupAction: "Clean up accounts", cleanupTitle: "Clean up {{provider}} accounts", cleanupDescription: "Delete accounts in the selected states from this provider, including their quota data. Normal accounts are never affected. This cannot be undone.", cleanupCompleted: "Deleted {{deleted}} accounts", deletedWithSkipped: "Deleted {{deleted}} accounts, skipped {{skipped}} groups with active video jobs", cleanupCompletedDetailed: "Deleted {{deleted}} accounts ({{linked}} linked), skipped {{skipped}} groups", cleanupLinkedWarning: "Warning: linked accounts are not limited to the selected states and may include healthy accounts; they will be deleted too.", cleanupPreviewFailed: "Failed to load estimated counts. Adjust selection and retry, or clean up later.", cleanupPreviewTotal: "About {{total}} accounts will be deleted", cleanupStart: "Start cleanup" }, models: { title: "Model routes", description: "Map one client-facing model name to provider-specific Build, Web, and Console routes. Multiple public names may also target the same upstream model.", sync: "Sync models", search: "Search models", model: "Public model name", publicId: "Public model name", upstream: "Upstream model", provider: "Model source", providerGrokBuild: "Grok Build", providerGrokWeb: "Grok Web", accountSupport: "Supported accounts", lastSyncedAt: "Last synced", capability: "Account model capabilities", supportSummary: "{{supported}} available / {{total}} total", awaitingCapabilitySync: "Awaiting model capability sync", unknownCapability: "Pending sync", partialCapability: "Awaiting remaining accounts", available: "Available", unavailable: "Unavailable", status: "Status", create: "Add model", createTitle: "Add model route", createDescription: "Add a custom Grok Build route. The public model name has no source prefix; the upstream model uses Build/ to identify its actual channel.", editTitle: "Edit model route", bindAccounts: "Bind specific accounts", boundAccounts: "Bound accounts", bindAccountsDescription: "Route only through selected accounts; when disabled, use synchronized model capabilities.", enabledDescription: "Controls whether this route participates in model discovery and request scheduling.", searchAccounts: "Search account name or ID", selectedAccounts: "{{count}} accounts selected", selectAccountRequired: "Select at least one account", noBindableAccounts: "No accounts from this provider can be bound", deleteTitle: "Delete model route?", deleteDescription: "This removes {{name}} and its client-key permissions. A later sync recreates it if upstream accounts still support the model.", batchDeleteTitle: "Delete {{count}} selected model routes?", batchDeleteDescription: "This removes the selected routes and their client-key permissions. Models still supported by upstream accounts are recreated on a later sync.", synced: "Synced {{count}} models", created: "Model route created", updated: "Model route updated", deleted: "Model route deleted", batchDeleted: "Deleted {{count}} model routes", batchUpdated: "Selected models updated" }, keys: { title: "Client keys", description: "Control downstream model access, RPM, concurrency, billed usage, and expiration.", search: "Search keys", create: "Create key", name: "Name", prefix: "Key", limits: "Limits", rpmLimit: "RPM limit", concurrencyLimit: "Concurrency limit", rpmShort: "RPM", concurrencyShort: "Concurrency", billingLimit: "Usage limit", models: "Allowed models", status: "Status", statusActive: "Active", statusExpired: "Expired", modelScope: "Model scope", restrictedModels: "Selected models", expires: "Expires", lastUsed: "Last used", rpm: "Requests per minute", maxConcurrent: "Max concurrency", rpmValue: "{{value}} RPM", concurrentValue: "{{value}} concurrent", unlimited: "Unlimited", billedUsage: "{{value}} billed", billingLimitDescription: "Accumulates billed request audits, preferring upstream-reported cost and otherwise using the official price estimate.", enabledDescription: "Controls whether this key can make API requests.", modelAliases: "Model aliases", modelAliasesDescription: "Suffix aliases are generated only for available models with multiple supported reasoning levels.", modelAliasesBuildSupport: "Grok Build: grok-4.5, grok-3-mini, and grok-3-mini-fast support low / medium / high.", modelAliasesConsoleSupport: "Grok Console: grok-4.3 supports none / low / medium / high; grok-4.20-0309-reasoning supports low / medium / high; grok-4.20-multi-agent-0309 also supports xhigh.", modelAliasesUnsupported: "Grok Web, image models, and video models do not generate reasoning-effort suffixes.", modelAliasesOn: "On: discover and call the reasoning aliases supported by available models.", modelAliasesOff: "Off: dynamic reasoning aliases are disabled; existing Console compatibility aliases remain available.", allModels: "All models", modelSearch: "Search models. Leave blank to allow all models.", selectedModels: "{{count}} models selected", neverExpires: "Never expires", selectExpiry: "Select expiration date", clearExpiry: "Clear expiration", expiryTime: "Expiration time", createTitle: "Create client key", editTitle: "Edit client key", secretTitle: "Client key created", secretDescription: "Store this key securely.", secretLabel: "Key", copySecret: "Copy", copySecretTitle: "Copy key", copySecretDescription: "Use the button below to copy your key.", secretReady: "Ready", created: "Client key created", updated: "Client key updated", deleted: "Client key deleted", deleteTitle: "Delete client key?", deleteDescription: "All downstream requests using this key will stop immediately.", batchUpdated: "Selected keys updated", batchDeleteTitle: "Delete {{count}} selected keys?" }, audits: { From 8b5c1ed6376504e80979e0ed22b02833f77a39e1 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Tue, 28 Jul 2026 15:28:19 +0800 Subject: [PATCH 5/6] fix: safely normalize streamed integer tool arguments --- .../infra/provider/cli/responses_arguments.go | 137 +++++++++++++--- .../provider/cli/responses_arguments_test.go | 155 +++++++++++++++++- .../infra/provider/cli/responses_response.go | 134 ++++++++++----- .../provider/cli/responses_tool_state.go | 3 + 4 files changed, 363 insertions(+), 66 deletions(-) diff --git a/backend/internal/infra/provider/cli/responses_arguments.go b/backend/internal/infra/provider/cli/responses_arguments.go index fbfc2bf9..69608951 100644 --- a/backend/internal/infra/provider/cli/responses_arguments.go +++ b/backend/internal/infra/provider/cli/responses_arguments.go @@ -3,12 +3,15 @@ package cli import ( "encoding/json" "io" - "math" "strconv" "strings" ) -const maxExactJSONInteger = float64(1<<53 - 1) +const ( + maxExactJSONInteger int64 = 1<<53 - 1 + maxNormalizedNumberBytes = 256 + maxExactJSONIntegerText = "9007199254740991" +) // normalizeFunctionArguments repairs semantically integral JSON numbers that strict // downstream decoders reject for integer fields. Grok Build can emit 60000.0 where @@ -133,37 +136,129 @@ func schemaRequiresInteger(schema map[string]any) bool { func normalizeIntegralNumber(number json.Number) (json.Number, bool) { raw := number.String() - if !strings.ContainsAny(raw, ".eE") { + if len(raw) > maxNormalizedNumberBytes || !strings.ContainsAny(raw, ".eE") { return number, false } - value, err := strconv.ParseFloat(raw, 64) - if err != nil || math.IsInf(value, 0) || math.IsNaN(value) || math.Trunc(value) != value || math.Abs(value) > maxExactJSONInteger { + mantissa := raw + exponentText := "" + if index := strings.IndexAny(mantissa, "eE"); index >= 0 { + exponentText = mantissa[index+1:] + mantissa = mantissa[:index] + } + negative := strings.HasPrefix(mantissa, "-") + if negative { + mantissa = strings.TrimPrefix(mantissa, "-") + } + whole, fraction, hasFraction := strings.Cut(mantissa, ".") + if !hasFraction { + fraction = "" + } + digits := strings.TrimLeft(whole+fraction, "0") + if digits == "" { + return json.Number("0"), raw != "0" + } + exponent, ok := parseBoundedDecimalExponent(exponentText) + if !ok { return number, false } - normalized := strconv.FormatFloat(value, 'f', -1, 64) - if normalized == "-0" { - normalized = "0" + decimalShift := exponent - len(fraction) + if decimalShift < 0 { + fractionalDigits := -decimalShift + if fractionalDigits > len(digits) || strings.Trim(digits[len(digits)-fractionalDigits:], "0") != "" { + return number, false + } + digits = strings.TrimLeft(digits[:len(digits)-fractionalDigits], "0") + if digits == "" { + return json.Number("0"), true + } + } else if decimalShift > 0 { + if decimalShift > len(maxExactJSONIntegerText)-len(digits) { + return number, false + } + digits += strings.Repeat("0", decimalShift) + } + if len(digits) > len(maxExactJSONIntegerText) || len(digits) == len(maxExactJSONIntegerText) && digits > maxExactJSONIntegerText { + return number, false + } + normalized := digits + if negative { + normalized = "-" + normalized } return json.Number(normalized), normalized != raw } +func parseBoundedDecimalExponent(raw string) (int, bool) { + if raw == "" { + return 0, true + } + sign := 1 + if raw[0] == '+' || raw[0] == '-' { + if raw[0] == '-' { + sign = -1 + } + raw = raw[1:] + if raw == "" { + return 0, false + } + } + raw = strings.TrimLeft(raw, "0") + if raw == "" { + return 0, true + } + if len(raw) > 9 { + return 0, false + } + exponent, err := strconv.Atoi(raw) + if err != nil { + return 0, false + } + return sign * exponent, true +} + func schemaContainsInteger(value any) bool { - switch typed := value.(type) { - case map[string]any: - if schemaRequiresInteger(typed) { - return true - } - for _, child := range typed { - if schemaContainsInteger(child) { - return true - } - } - case []any: - for _, child := range typed { - if schemaContainsInteger(child) { + root, ok := value.(map[string]any) + if !ok { + return false + } + return schemaContainsReachableInteger(root, root, make(map[string]struct{}), 0) +} + +func schemaContainsReachableInteger(schema, root map[string]any, visitedRefs map[string]struct{}, depth int) bool { + if depth > 64 || schema == nil { + return false + } + if schemaRequiresInteger(schema) { + return true + } + if ref, ok := schema["$ref"].(string); ok { + if _, visited := visitedRefs[ref]; !visited { + visitedRefs[ref] = struct{}{} + if resolved, resolvedOK := resolveLocalSchemaRef(root, ref); resolvedOK && schemaContainsReachableInteger(resolved, root, visitedRefs, depth+1) { return true } } } + for _, keyword := range []string{"allOf", "anyOf", "oneOf", "prefixItems"} { + branches, _ := schema[keyword].([]any) + for _, rawBranch := range branches { + branch, ok := rawBranch.(map[string]any) + if ok && schemaContainsReachableInteger(branch, root, visitedRefs, depth+1) { + return true + } + } + } + for _, keyword := range []string{"items", "additionalProperties"} { + child, _ := schema[keyword].(map[string]any) + if schemaContainsReachableInteger(child, root, visitedRefs, depth+1) { + return true + } + } + properties, _ := schema["properties"].(map[string]any) + for _, rawProperty := range properties { + property, ok := rawProperty.(map[string]any) + if ok && schemaContainsReachableInteger(property, root, visitedRefs, depth+1) { + return true + } + } return false } diff --git a/backend/internal/infra/provider/cli/responses_arguments_test.go b/backend/internal/infra/provider/cli/responses_arguments_test.go index 99092fec..9d85c528 100644 --- a/backend/internal/infra/provider/cli/responses_arguments_test.go +++ b/backend/internal/infra/provider/cli/responses_arguments_test.go @@ -29,17 +29,68 @@ func TestNormalizeFunctionArgumentsCoercesSchemaIntegers(t *testing.T) { } } +func TestNormalizeIntegralNumberUsesExactBoundedDecimalArithmetic(t *testing.T) { + tests := []struct { + name string + input string + expected string + shouldChange bool + }{ + {name: "decimal", input: "60000.0", expected: "60000", shouldChange: true}, + {name: "exponent", input: "6e4", expected: "60000", shouldChange: true}, + {name: "negative exponent integer", input: "1000e-3", expected: "1", shouldChange: true}, + {name: "fraction with exponent", input: "1.2300e2", expected: "123", shouldChange: true}, + {name: "negative zero", input: "-0.0", expected: "0", shouldChange: true}, + {name: "positive exact limit", input: "9007199254740991.0", expected: "9007199254740991", shouldChange: true}, + {name: "negative exact limit", input: "-9007199254740991.0", expected: "-9007199254740991", shouldChange: true}, + {name: "fraction", input: "1e-1", expected: "1e-1", shouldChange: false}, + {name: "rounded fraction", input: "9007199254740990.5", expected: "9007199254740990.5", shouldChange: false}, + {name: "outside exact limit", input: "9007199254740992.0", expected: "9007199254740992.0", shouldChange: false}, + {name: "huge exponent", input: "1e1000000000", expected: "1e1000000000", shouldChange: false}, + {name: "zero huge exponent", input: "0e1000000000", expected: "0", shouldChange: true}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + normalized, changed := normalizeIntegralNumber(json.Number(test.input)) + if changed != test.shouldChange || normalized.String() != test.expected { + t.Fatalf("normalizeIntegralNumber(%q) = (%q, %v), want (%q, %v)", test.input, normalized, changed, test.expected, test.shouldChange) + } + }) + } +} + func TestNormalizeFunctionArgumentsPreservesUnsafeValues(t *testing.T) { schema := map[string]any{"type": "object", "properties": map[string]any{ - "fraction": map[string]any{"type": "integer"}, - "large": map[string]any{"type": "integer"}, + "fraction": map[string]any{"type": "integer"}, + "roundedFraction": map[string]any{"type": "integer"}, + "large": map[string]any{"type": "integer"}, + "hugeExponent": map[string]any{"type": "integer"}, }} - arguments := `{"fraction":1.5,"large":9007199254740992.0}` + arguments := `{"fraction":1.5,"roundedFraction":9007199254740990.5,"large":9007199254740992.0,"hugeExponent":1e1000000000}` if normalized, changed := normalizeFunctionArguments(arguments, schema); changed || normalized != arguments { t.Fatalf("unsafe arguments changed: changed=%v value=%s", changed, normalized) } } +func TestSchemaContainsIntegerOnlyFollowsReachableConstraints(t *testing.T) { + unreferenced := map[string]any{ + "type": "object", + "properties": map[string]any{"value": map[string]any{"type": "string"}}, + "$defs": map[string]any{"unused": map[string]any{"type": "integer"}}, + } + if schemaContainsInteger(unreferenced) { + t.Fatal("unreferenced integer definition enabled argument normalization") + } + referenced := map[string]any{ + "type": "object", + "properties": map[string]any{"value": map[string]any{"$ref": "#/$defs/count"}}, + "$defs": map[string]any{"count": map[string]any{"type": "integer"}}, + } + if !schemaContainsInteger(referenced) { + t.Fatal("referenced integer definition was not detected") + } +} + func TestNormalizeFunctionArgumentsFollowsLocalRefs(t *testing.T) { schema := map[string]any{ "$ref": "#/$defs/arguments", @@ -126,3 +177,101 @@ func TestResponsesIntegerArgumentsNormalizedInStream(t *testing.T) { t.Fatalf("normalized arguments missing: %s", text) } } + +func TestResponsesIntegerArgumentsParallelStreamSequenceIsMonotonic(t *testing.T) { + request := []byte(`{ + "model":"public", + "stream":true, + "parallel_tool_calls":true, + "tools":[{"type":"function","name":"wait_agent","parameters":{"type":"object","properties":{"timeout_ms":{"type":"integer"}}}}] + }`) + _, compatibility, err := normalizeResponsesRequest(request, "grok-4.5") + if err != nil { + t.Fatal(err) + } + stream := strings.Join([]string{ + `event: response.output_item.added`, + `data: {"type":"response.output_item.added","sequence_number":0,"item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"wait_agent","arguments":""}}`, + ``, + `event: response.output_item.added`, + `data: {"type":"response.output_item.added","sequence_number":1,"item":{"id":"fc_2","type":"function_call","call_id":"call_2","name":"wait_agent","arguments":""}}`, + ``, + `event: response.function_call_arguments.delta`, + `data: {"type":"response.function_call_arguments.delta","sequence_number":2,"item_id":"fc_1","delta":"{\"timeout_ms\":1.0}"}`, + ``, + `event: response.function_call_arguments.delta`, + `data: {"type":"response.function_call_arguments.delta","sequence_number":3,"item_id":"fc_2","delta":"{\"timeout_ms\":2.0}"}`, + ``, + `event: response.function_call_arguments.done`, + `data: {"type":"response.function_call_arguments.done","sequence_number":4,"item_id":"fc_1","arguments":"{\"timeout_ms\":1.0}"}`, + ``, + `event: response.function_call_arguments.done`, + `data: {"type":"response.function_call_arguments.done","sequence_number":5,"item_id":"fc_2","arguments":"{\"timeout_ms\":2.0}"}`, + ``, + }, "\n") + body, err := io.ReadAll(compatibility.normalizeResponseStream(io.NopCloser(strings.NewReader(stream)))) + if err != nil { + t.Fatal(err) + } + lastSequence := int64(-1) + for _, line := range strings.Split(string(body), "\n") { + if !strings.HasPrefix(line, "data: ") { + continue + } + var payload map[string]any + if err := json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &payload); err != nil { + t.Fatal(err) + } + sequence, ok := payload["sequence_number"].(float64) + if !ok { + continue + } + current := int64(sequence) + if current <= lastSequence { + t.Fatalf("sequence_number is not strictly increasing: previous=%d current=%d\n%s", lastSequence, current, body) + } + lastSequence = current + } +} + +func TestResponsesIntegerArgumentsBufferOverflowFallsBackToStreaming(t *testing.T) { + request := []byte(`{ + "model":"public", + "stream":true, + "tools":[{"type":"function","name":"write","parameters":{"type":"object","properties":{"content":{"type":"string"},"mode":{"type":"integer"}}}}] + }`) + _, compatibility, err := normalizeResponsesRequest(request, "grok-4.5") + if err != nil { + t.Fatal(err) + } + added := []byte(`{"type":"response.output_item.added","sequence_number":0,"item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"write","arguments":""}}`) + if _, err := compatibility.rewriteStreamData("response.output_item.added", added); err != nil { + t.Fatal(err) + } + first := strings.Repeat("a", maxBufferedFunctionArgumentsBytes) + firstPayload, _ := json.Marshal(map[string]any{"type": "response.function_call_arguments.delta", "sequence_number": 1, "item_id": "fc_1", "delta": first}) + outputs, err := compatibility.rewriteStreamData("response.function_call_arguments.delta", firstPayload) + if err != nil || len(outputs) != 0 { + t.Fatalf("first buffered delta: outputs=%d err=%v", len(outputs), err) + } + overflowPayload := []byte(`{"type":"response.function_call_arguments.delta","sequence_number":2,"item_id":"fc_1","delta":"b"}`) + outputs, err = compatibility.rewriteStreamData("response.function_call_arguments.delta", overflowPayload) + if err != nil { + t.Fatal(err) + } + if len(outputs) != 2 { + t.Fatalf("overflow outputs = %d", len(outputs)) + } + flushed := outputs[0].Payload + if delta, _ := flushed["delta"].(string); len(delta) != maxBufferedFunctionArgumentsBytes { + t.Fatalf("flushed delta length = %d", len(delta)) + } + current := outputs[1].Payload + if current["delta"] != "b" { + t.Fatalf("current delta = %q", current["delta"]) + } + state := compatibility.streamCalls["fc_1"] + if state == nil || !state.passthrough || state.arguments.Len() != 0 || compatibility.streamArgumentBytes != 0 { + t.Fatal("overflow did not release the buffered arguments") + } +} diff --git a/backend/internal/infra/provider/cli/responses_response.go b/backend/internal/infra/provider/cli/responses_response.go index a63f908c..db879009 100644 --- a/backend/internal/infra/provider/cli/responses_response.go +++ b/backend/internal/infra/provider/cli/responses_response.go @@ -10,8 +10,10 @@ import ( ) const ( - maxCompatibleResponseBytes = 128 << 20 - maxCompatibleSSEEventBytes = 8 << 20 + maxCompatibleResponseBytes = 128 << 20 + maxCompatibleSSEEventBytes = 8 << 20 + maxBufferedFunctionArgumentsBytes = 1 << 20 + maxTotalBufferedFunctionArgsBytes = 4 << 20 ) // normalizeResponseJSON 将上游普通函数别名恢复为下游 namespace 和 Tool Search 输出项。 @@ -51,6 +53,15 @@ func (c *responsesToolCompatibility) normalizeResponseStream(source io.ReadClose return rewriteErr } for index, output := range outputs { + outputData := output.Data + if output.Payload != nil { + c.resequenceStreamPayload(output.Payload) + encoded, encodeErr := json.Marshal(output.Payload) + if encodeErr != nil { + return fmt.Errorf("编码兼容 Responses SSE: %w", encodeErr) + } + outputData = encoded + } current := event if output.Event != "" { current.Event = output.Event @@ -61,7 +72,7 @@ func (c *responsesToolCompatibility) normalizeResponseStream(source io.ReadClose current.Comments = nil current.Other = nil } - current.SetData(output.Data) + current.SetData(outputData) if err := current.writeTo(writer); err != nil { return err } @@ -74,14 +85,16 @@ func (c *responsesToolCompatibility) normalizeResponseStream(source io.ReadClose } type responsesStreamOutput struct { - Event string - Data []byte + Event string + Data []byte + Payload map[string]any } type responsesStreamCall struct { identity responsesToolIdentity schema any arguments strings.Builder + passthrough bool lastDelta map[string]any addedPayload map[string]any } @@ -119,9 +132,28 @@ func (c *responsesToolCompatibility) rewriteStreamData(event string, data []byte if kind == "response.function_call_arguments.delta" { identity, state, found := c.streamIdentity(payload) if found && identity.Kind == responsesFunctionTool && state.schema != nil { - state.arguments.WriteString(stringField(payload, "delta")) - state.lastDelta = cloneJSONObject(payload) - return nil, nil + delta := stringField(payload, "delta") + callLimitExceeded := state.arguments.Len()+len(delta) > maxBufferedFunctionArgumentsBytes + totalLimitExceeded := c.streamArgumentBytes+len(delta) > maxTotalBufferedFunctionArgsBytes + if !state.passthrough && (callLimitExceeded || totalLimitExceeded) { + buffered := state.arguments.String() + c.releaseBufferedFunctionArguments(state) + state.passthrough = true + outputs := make([]responsesStreamOutput, 0, 2) + if buffered != "" { + flushed := cloneJSONObject(payload) + flushed["delta"] = buffered + outputs = append(outputs, responsesStreamOutput{Event: "response.function_call_arguments.delta", Payload: flushed}) + } + outputs = append(outputs, responsesStreamOutput{Event: "response.function_call_arguments.delta", Payload: payload}) + return outputs, nil + } + if !state.passthrough { + state.arguments.WriteString(delta) + c.streamArgumentBytes += len(delta) + state.lastDelta = cloneJSONObject(payload) + return nil, nil + } } if found && (identity.Kind == responsesToolSearch || identity.Kind == responsesCustomTool || identity.Kind == responsesApplyPatchTool) { state.arguments.WriteString(stringField(payload, "delta")) @@ -139,23 +171,21 @@ func (c *responsesToolCompatibility) rewriteStreamData(event string, data []byte arguments = state.arguments.String() } normalized, _ := normalizeFunctionArguments(arguments, state.schema) + if state.passthrough { + done := cloneJSONObject(payload) + done["arguments"] = normalized + return []responsesStreamOutput{{Event: "response.function_call_arguments.done", Payload: done}}, nil + } outputs := make([]responsesStreamOutput, 0, 2) if state.lastDelta != nil { delta := cloneJSONObject(state.lastDelta) delta["delta"] = normalized - encoded, err := json.Marshal(delta) - if err != nil { - return nil, fmt.Errorf("编码 function arguments delta: %w", err) - } - outputs = append(outputs, responsesStreamOutput{Event: "response.function_call_arguments.delta", Data: encoded}) + outputs = append(outputs, responsesStreamOutput{Event: "response.function_call_arguments.delta", Payload: delta}) } done := cloneJSONObject(payload) done["arguments"] = normalized - encoded, err := json.Marshal(done) - if err != nil { - return nil, fmt.Errorf("编码 function arguments done: %w", err) - } - outputs = append(outputs, responsesStreamOutput{Event: "response.function_call_arguments.done", Data: encoded}) + outputs = append(outputs, responsesStreamOutput{Event: "response.function_call_arguments.done", Payload: done}) + c.releaseBufferedFunctionArguments(state) return outputs, nil } if found && (identity.Kind == responsesToolSearch || identity.Kind == responsesApplyPatchTool) { @@ -171,18 +201,10 @@ func (c *responsesToolCompatibility) rewriteStreamData(event string, data []byte outputs := make([]responsesStreamOutput, 0, 2) if state.lastDelta != nil { delta := customToolStreamPayload(state.lastDelta, "response.custom_tool_call_input.delta", "delta", input) - encoded, err := json.Marshal(delta) - if err != nil { - return nil, fmt.Errorf("编码 custom tool delta: %w", err) - } - outputs = append(outputs, responsesStreamOutput{Event: "response.custom_tool_call_input.delta", Data: encoded}) + outputs = append(outputs, responsesStreamOutput{Event: "response.custom_tool_call_input.delta", Payload: delta}) } done := customToolStreamPayload(payload, "response.custom_tool_call_input.done", "input", input) - encoded, err := json.Marshal(done) - if err != nil { - return nil, fmt.Errorf("编码 custom tool done: %w", err) - } - outputs = append(outputs, responsesStreamOutput{Event: "response.custom_tool_call_input.done", Data: encoded}) + outputs = append(outputs, responsesStreamOutput{Event: "response.custom_tool_call_input.done", Payload: done}) return outputs, nil } } @@ -200,11 +222,47 @@ func (c *responsesToolCompatibility) rewriteStreamData(event string, data []byte if response, ok := payload["response"].(map[string]any); ok { c.restoreVisibleTools(response) } - converted, err := json.Marshal(payload) - if err != nil { - return nil, fmt.Errorf("编码兼容 Responses SSE: %w", err) + return []responsesStreamOutput{{Payload: payload}}, nil +} + +func (c *responsesToolCompatibility) releaseBufferedFunctionArguments(state *responsesStreamCall) { + if c == nil || state == nil { + return } - return []responsesStreamOutput{{Data: converted}}, nil + c.streamArgumentBytes -= state.arguments.Len() + if c.streamArgumentBytes < 0 { + c.streamArgumentBytes = 0 + } + state.arguments.Reset() + state.lastDelta = nil +} + +func (c *responsesToolCompatibility) resequenceStreamPayload(payload map[string]any) { + if c == nil || payload == nil { + return + } + rawSequence, exists := payload["sequence_number"] + if !exists { + return + } + if !c.streamSequenceSet { + sequence, ok := exactJSONInt64(rawSequence) + if !ok { + return + } + c.streamSequenceNext = sequence + c.streamSequenceSet = true + } + payload["sequence_number"] = c.streamSequenceNext + c.streamSequenceNext++ +} + +func exactJSONInt64(value any) (int64, bool) { + number, ok := value.(float64) + if !ok || number < 0 || number > float64(maxExactJSONInteger) || number != float64(int64(number)) { + return 0, false + } + return int64(number), true } func (c *responsesToolCompatibility) rememberStreamCall(item map[string]any) *responsesStreamCall { @@ -355,17 +413,9 @@ func (c *responsesToolCompatibility) rewriteApplyPatchDoneEvent(payload, item ma addedItem := cloneJSONObject(doneItem) addedItem["status"] = "in_progress" added["item"] = addedItem - addedData, err := json.Marshal(added) - if err != nil { - return nil, fmt.Errorf("编码 apply_patch added event: %w", err) - } - doneData, err := json.Marshal(done) - if err != nil { - return nil, fmt.Errorf("编码 apply_patch done event: %w", err) - } return []responsesStreamOutput{ - {Event: "response.output_item.added", Data: addedData}, - {Event: "response.output_item.done", Data: doneData}, + {Event: "response.output_item.added", Payload: added}, + {Event: "response.output_item.done", Payload: done}, }, nil } diff --git a/backend/internal/infra/provider/cli/responses_tool_state.go b/backend/internal/infra/provider/cli/responses_tool_state.go index 726fad3b..ad0a94dc 100644 --- a/backend/internal/infra/provider/cli/responses_tool_state.go +++ b/backend/internal/infra/provider/cli/responses_tool_state.go @@ -43,6 +43,9 @@ type responsesToolCompatibility struct { clientSearchParam string serverSearchEager bool streamCalls map[string]*responsesStreamCall + streamArgumentBytes int + streamSequenceNext int64 + streamSequenceSet bool legacyLocalShell bool nativeShell bool webSearchDisabled bool From 2a336686fdf8714935e4e2a11c7a17490a8ef5c4 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Tue, 28 Jul 2026 16:16:06 +0800 Subject: [PATCH 6/6] feat: enhance BatchUpdate to validate account provider and handle account pool mismatches --- .../application/account/batch_update_test.go | 79 ++++++++++++ .../internal/application/account/service.go | 54 +++++---- .../relational/account_batch_update_test.go | 112 ++++++++++++++++++ .../relational/account_repository.go | 38 +++++- .../postgres_account_batch_update_test.go | 44 +++++++ .../relational/postgres_integration_test.go | 2 +- .../relational/routing_projection_test.go | 2 +- backend/internal/repository/account.go | 2 +- backend/internal/repository/errors.go | 9 +- .../transport/http/account/handler.go | 7 +- .../src/features/accounts/accounts-page.tsx | 5 +- 11 files changed, 317 insertions(+), 37 deletions(-) create mode 100644 backend/internal/application/account/batch_update_test.go create mode 100644 backend/internal/infra/persistence/relational/account_batch_update_test.go create mode 100644 backend/internal/infra/persistence/relational/postgres_account_batch_update_test.go diff --git a/backend/internal/application/account/batch_update_test.go b/backend/internal/application/account/batch_update_test.go new file mode 100644 index 00000000..e1e16289 --- /dev/null +++ b/backend/internal/application/account/batch_update_test.go @@ -0,0 +1,79 @@ +package account + +import ( + "context" + "errors" + "slices" + "testing" + + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/repository" +) + +type batchUpdateRepository struct { + repository.AccountRepository + updateErr error + updatedIDs []uint64 +} + +func (r *batchUpdateRepository) UpdateMany(_ context.Context, providerValue accountdomain.Provider, ids []uint64, _ repository.AccountUpdates) (int64, error) { + if providerValue != accountdomain.ProviderBuild { + return 0, errors.New("unexpected provider") + } + r.updatedIDs = append([]uint64(nil), ids...) + if r.updateErr != nil { + return 0, r.updateErr + } + return int64(len(ids)), nil +} + +func TestBatchUpdateSupportsMoreThanAdminPageLimit(t *testing.T) { + ids := make([]uint64, 2501) + for index := range ids { + ids[index] = uint64(index + 1) + } + repo := &batchUpdateRepository{} + service := NewService(repo, nil, nil, nil, nil, nil, nil) + maxConcurrent := 3 + + updated, err := service.BatchUpdate(context.Background(), accountdomain.ProviderBuild, ids, UpdateInput{MaxConcurrent: &maxConcurrent}) + if err != nil { + t.Fatal(err) + } + if updated != int64(len(ids)) || !slices.Equal(repo.updatedIDs, ids) { + t.Fatalf("updated = %d, ids = %d", updated, len(repo.updatedIDs)) + } +} + +func TestBatchUpdatePreservesProviderMismatchSemantics(t *testing.T) { + ids := make([]uint64, 501) + for index := range ids { + ids[index] = uint64(index + 1) + } + repo := &batchUpdateRepository{updateErr: repository.ErrAccountPoolMismatch} + service := NewService(repo, nil, nil, nil, nil, nil, nil) + maxConcurrent := 3 + + _, err := service.BatchUpdate(context.Background(), accountdomain.ProviderBuild, ids, UpdateInput{MaxConcurrent: &maxConcurrent}) + if !errors.Is(err, ErrAccountPoolMismatch) { + t.Fatalf("error = %v, want account pool mismatch", err) + } +} + +func TestBatchUpdateRetainsBoundedRequestSize(t *testing.T) { + ids := make([]uint64, maxBatchUpdateAccounts+1) + for index := range ids { + ids[index] = uint64(index + 1) + } + repo := &batchUpdateRepository{} + service := NewService(repo, nil, nil, nil, nil, nil, nil) + maxConcurrent := 3 + + _, err := service.BatchUpdate(context.Background(), accountdomain.ProviderBuild, ids, UpdateInput{MaxConcurrent: &maxConcurrent}) + if !errors.Is(err, ErrInvalidInput) { + t.Fatalf("error = %v, want invalid input", err) + } + if len(repo.updatedIDs) != 0 { + t.Fatal("oversized update reached repository") + } +} diff --git a/backend/internal/application/account/service.go b/backend/internal/application/account/service.go index 9c77f343..ac32b117 100644 --- a/backend/internal/application/account/service.go +++ b/backend/internal/application/account/service.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "log/slog" + "slices" "strconv" "strings" "sync" @@ -22,18 +23,19 @@ import ( ) var ( - ErrDevicePending = errors.New("Device OAuth 等待用户授权") - ErrDeviceSlowDown = errors.New("Device OAuth 轮询过快") - ErrDeviceDenied = errors.New("Device OAuth 已拒绝或过期") - ErrInvalidFilter = errors.New("账号筛选条件无效") - ErrInvalidInput = errors.New("账号参数无效") - ErrInvalidImport = errors.New("账号凭据格式无效") - ErrImportLimit = errors.New("导入账号数量超过限制") - ErrExportLimit = errors.New("导出账号数量超过限制") - ErrNotFound = errors.New("账号不存在") - ErrUnsupported = errors.New("账号来源不支持该操作") - ErrConversionBusy = errors.New("账号正在转换为 Grok Build") - ErrConflict = errors.New("账号操作存在冲突") + ErrDevicePending = errors.New("Device OAuth 等待用户授权") + ErrDeviceSlowDown = errors.New("Device OAuth 轮询过快") + ErrDeviceDenied = errors.New("Device OAuth 已拒绝或过期") + ErrInvalidFilter = errors.New("账号筛选条件无效") + ErrInvalidInput = errors.New("账号参数无效") + ErrInvalidImport = errors.New("账号凭据格式无效") + ErrImportLimit = errors.New("导入账号数量超过限制") + ErrExportLimit = errors.New("导出账号数量超过限制") + ErrNotFound = errors.New("账号不存在") + ErrUnsupported = errors.New("账号来源不支持该操作") + ErrConversionBusy = errors.New("账号正在转换为 Grok Build") + ErrConflict = errors.New("账号操作存在冲突") + ErrAccountPoolMismatch = errors.New("批量操作包含不属于当前号池的账号") ) var ErrCredentialRefreshPermanent = errors.New("OAuth refresh token 已永久失效") @@ -63,6 +65,7 @@ const ( credentialImportChunkSize = 100 maxQuotaResetAccounts = 10000 quotaResetChunkSize = 500 + maxBatchUpdateAccounts = 10000 maxBuildConversionAccounts = 1000 maxWebConsoleSyncAccounts = 1000 accountTaskBatchSize = 1000 @@ -561,12 +564,16 @@ func validAssociationFilter(providerValue, association string) bool { } } -// BatchUpdate 对一组账号应用同一组路由参数,单次最多处理一个管理端最大分页。 -func (s *Service) BatchUpdate(ctx context.Context, ids []uint64, input UpdateInput) (int64, error) { - ids, err := normalizeBatchIDs(ids) +// BatchUpdate 对同一号池的一组账号应用相同路由参数。 +func (s *Service) BatchUpdate(ctx context.Context, providerValue accountdomain.Provider, ids []uint64, input UpdateInput) (int64, error) { + ids, err := normalizeIDs(ids, maxBatchUpdateAccounts) if err != nil { return 0, err } + if !providerValue.IsValid() { + return 0, invalidInput("账号来源无效") + } + slices.Sort(ids) if input.MaxConcurrent != nil && (*input.MaxConcurrent < 1 || *input.MaxConcurrent > accountdomain.MaxConcurrent) { return 0, invalidInput("maxConcurrent 必须在 1 到 256 之间") } @@ -576,13 +583,17 @@ func (s *Service) BatchUpdate(ctx context.Context, ids []uint64, input UpdateInp if input.Name != nil { return 0, invalidInput("批量更新不支持修改账号名称") } - updated, err := s.accounts.UpdateMany(ctx, ids, repository.AccountUpdates{Enabled: input.Enabled, Priority: input.Priority, MaxConcurrent: input.MaxConcurrent, MinimumRemaining: input.MinimumRemaining}) + updated, err := s.accounts.UpdateMany(ctx, providerValue, ids, repository.AccountUpdates{Enabled: input.Enabled, Priority: input.Priority, MaxConcurrent: input.MaxConcurrent, MinimumRemaining: input.MinimumRemaining}) if err != nil { - return 0, err + return 0, mapRepositoryError(err) } - if input.Enabled != nil && !*input.Enabled { - for _, id := range ids { - _ = s.sticky.DeleteByAccount(ctx, id) + if input.Enabled != nil && !*input.Enabled && s.sticky != nil { + if batchDeleter, ok := s.sticky.(repository.StickySessionBatchDeleter); ok { + _ = batchDeleter.DeleteByAccounts(ctx, ids) + } else { + for _, id := range ids { + _ = s.sticky.DeleteByAccount(ctx, id) + } } } return updated, nil @@ -3277,6 +3288,9 @@ func mapLinkedDeleteError(err error) error { } func mapRepositoryError(err error) error { + if errors.Is(err, repository.ErrAccountPoolMismatch) { + return ErrAccountPoolMismatch + } if errors.Is(err, repository.ErrNotFound) { return ErrNotFound } diff --git a/backend/internal/infra/persistence/relational/account_batch_update_test.go b/backend/internal/infra/persistence/relational/account_batch_update_test.go new file mode 100644 index 00000000..9c8fe4e4 --- /dev/null +++ b/backend/internal/infra/persistence/relational/account_batch_update_test.go @@ -0,0 +1,112 @@ +package relational + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/repository" +) + +func TestAccountRepositoryUpdateManyChunksLargeAccountPool(t *testing.T) { + ctx := context.Background() + database := openTestDatabase(t) + repo := NewAccountRepository(database) + rows := seedBatchUpdateAccounts(t, database, 2001) + ids := accountModelIDs(rows) + maxConcurrent := 3 + + updated, err := repo.UpdateMany(ctx, account.ProviderBuild, ids, repository.AccountUpdates{MaxConcurrent: &maxConcurrent}) + if err != nil { + t.Fatal(err) + } + if updated != int64(len(ids)) { + t.Fatalf("updated = %d, want %d", updated, len(ids)) + } + var count int64 + if err := database.db.Model(&accountModel{}).Where("max_concurrent = ?", maxConcurrent).Count(&count).Error; err != nil { + t.Fatal(err) + } + if count != int64(len(ids)) { + t.Fatalf("stored count = %d, want %d", count, len(ids)) + } +} + +func TestAccountRepositoryUpdateManyRollsBackAllChunks(t *testing.T) { + ctx := context.Background() + database := openTestDatabase(t) + repo := NewAccountRepository(database) + rows := seedBatchUpdateAccounts(t, database, accountUpdateBatchSize+1) + ids := accountModelIDs(rows) + failingID := ids[len(ids)-1] + trigger := fmt.Sprintf(`CREATE TRIGGER fail_batch_account_update BEFORE UPDATE OF max_concurrent ON provider_accounts WHEN NEW.id = %d BEGIN SELECT RAISE(ABORT, 'forced batch failure'); END`, failingID) + if err := database.db.Exec(trigger).Error; err != nil { + t.Fatal(err) + } + maxConcurrent := 3 + + updated, err := repo.UpdateMany(ctx, account.ProviderBuild, ids, repository.AccountUpdates{MaxConcurrent: &maxConcurrent}) + if err == nil || updated != 0 { + t.Fatalf("updated = %d, error = %v", updated, err) + } + var changed int64 + if err := database.db.Model(&accountModel{}).Where("id IN ? AND max_concurrent = ?", ids, maxConcurrent).Count(&changed).Error; err != nil { + t.Fatal(err) + } + if changed != 0 { + t.Fatalf("transaction left %d changed rows", changed) + } +} + +func TestAccountRepositoryUpdateManyRejectsMixedProviderBeforeWriting(t *testing.T) { + ctx := context.Background() + database := openTestDatabase(t) + repo := NewAccountRepository(database) + rows := seedBatchUpdateAccounts(t, database, accountUpdateBatchSize+1) + ids := accountModelIDs(rows) + if err := database.db.Model(&accountModel{}).Where("id = ?", ids[len(ids)-1]).Update("provider", account.ProviderWeb).Error; err != nil { + t.Fatal(err) + } + maxConcurrent := 3 + + updated, err := repo.UpdateMany(ctx, account.ProviderBuild, ids, repository.AccountUpdates{MaxConcurrent: &maxConcurrent}) + if !errors.Is(err, repository.ErrAccountPoolMismatch) || updated != 0 { + t.Fatalf("updated = %d, error = %v", updated, err) + } + var changed int64 + if err := database.db.Model(&accountModel{}).Where("id IN ? AND max_concurrent = ?", ids, maxConcurrent).Count(&changed).Error; err != nil { + t.Fatal(err) + } + if changed != 0 { + t.Fatalf("provider mismatch left %d changed rows", changed) + } +} + +func seedBatchUpdateAccounts(t *testing.T, database *Database, count int) []accountModel { + t.Helper() + now := time.Now().UTC() + rows := make([]accountModel, count) + for index := range rows { + rows[index] = accountModel{ + IdentityKey: fmt.Sprintf("%064x", index+1), + Provider: string(account.ProviderBuild), Name: fmt.Sprintf("batch-%d", index+1), SourceKey: fmt.Sprintf("batch-%d", index+1), + Enabled: true, AuthStatus: string(account.AuthStatusActive), Priority: account.DefaultPriority, MaxConcurrent: account.DefaultMaxConcurrent, + BuildRouteMode: string(account.BuildRouteAuto), CreatedAt: now, UpdatedAt: now, + } + } + if err := database.db.CreateInBatches(&rows, 200).Error; err != nil { + t.Fatal(err) + } + return rows +} + +func accountModelIDs(rows []accountModel) []uint64 { + ids := make([]uint64, len(rows)) + for index := range rows { + ids[index] = rows[index].ID + } + return ids +} diff --git a/backend/internal/infra/persistence/relational/account_repository.go b/backend/internal/infra/persistence/relational/account_repository.go index 8454da74..7684b0b8 100644 --- a/backend/internal/infra/persistence/relational/account_repository.go +++ b/backend/internal/infra/persistence/relational/account_repository.go @@ -38,6 +38,7 @@ type quotaBreakdownJSON struct { } const ( + accountUpdateBatchSize = 500 accountPaidPlanSignal = `(LOWER(REPLACE(REPLACE(REPLACE(REPLACE(TRIM(billing.plan_code), ' ', ''), '_', ''), '-', ''), '+', 'plus')) IN ('super', 'supergrok', 'supergrokpro', 'supergrokheavy', 'supergroklite', 'grokpro', 'xpremium', 'xpremiumplus', 'apikey') OR LOWER(REPLACE(REPLACE(REPLACE(REPLACE(TRIM(billing.plan_name), ' ', ''), '_', ''), '-', ''), '+', 'plus')) IN ('super', 'supergrok', 'supergrokpro', 'supergrokheavy', 'supergroklite', 'grokpro', 'xpremium', 'xpremiumplus', 'apikey'))` accountFreePlanSignal = `(LOWER(REPLACE(REPLACE(REPLACE(REPLACE(TRIM(billing.plan_code), ' ', ''), '_', ''), '-', ''), '+', 'plus')) IN ('free', 'grokfree', 'freetier', 'basic', 'grokbasic', 'xbasic') OR LOWER(REPLACE(REPLACE(REPLACE(REPLACE(TRIM(billing.plan_name), ' ', ''), '_', ''), '-', ''), '+', 'plus')) IN ('free', 'grokfree', 'freetier', 'basic', 'grokbasic', 'xbasic'))` accountPaidBillingSignals = `(` + accountPaidPlanSignal + ` OR billing.monthly_limit > 0 OR billing.on_demand_cap > 0 OR billing.on_demand_used > 0 OR billing.prepaid_balance > 0)` @@ -1255,7 +1256,7 @@ func (r *AccountRepository) markWebProfileTimestamp(ctx context.Context, id uint })) } -func (r *AccountRepository) UpdateMany(ctx context.Context, ids []uint64, updates repository.AccountUpdates) (int64, error) { +func (r *AccountRepository) UpdateMany(ctx context.Context, providerValue account.Provider, ids []uint64, updates repository.AccountUpdates) (int64, error) { if len(ids) == 0 { return 0, nil } @@ -1275,11 +1276,40 @@ func (r *AccountRepository) UpdateMany(ctx context.Context, ids []uint64, update if len(values) == 0 { return 0, nil } - result := r.db.db.WithContext(ctx).Model(&accountModel{}).Where("id IN ?", ids).Updates(values) - if result.Error == nil && result.RowsAffected > 0 { + var updated int64 + err := r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + for start := 0; start < len(ids); start += accountUpdateBatchSize { + end := min(start+accountUpdateBatchSize, len(ids)) + var rows []accountModel + if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Select("id", "provider").Where("id IN ?", ids[start:end]).Order("id ASC").Find(&rows).Error; err != nil { + return err + } + if len(rows) != end-start { + return repository.ErrAccountPoolMismatch + } + for _, row := range rows { + if account.Provider(row.Provider) != providerValue { + return repository.ErrAccountPoolMismatch + } + } + } + for start := 0; start < len(ids); start += accountUpdateBatchSize { + end := min(start+accountUpdateBatchSize, len(ids)) + result := tx.Model(&accountModel{}).Where("provider = ? AND id IN ?", providerValue, ids[start:end]).Updates(values) + if result.Error != nil { + return result.Error + } + updated += result.RowsAffected + } + return nil + }) + if err != nil { + return 0, err + } + if updated > 0 { r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountStateChanged}) } - return result.RowsAffected, result.Error + return updated, nil } // UpdateEgressBindings assigns one egress node to multiple accounts of one diff --git a/backend/internal/infra/persistence/relational/postgres_account_batch_update_test.go b/backend/internal/infra/persistence/relational/postgres_account_batch_update_test.go new file mode 100644 index 00000000..37af7c1b --- /dev/null +++ b/backend/internal/infra/persistence/relational/postgres_account_batch_update_test.go @@ -0,0 +1,44 @@ +package relational + +import ( + "context" + "os" + "testing" + + "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/repository" +) + +func TestPostgresAccountBatchUpdateBeyondAdminPageLimit(t *testing.T) { + dsn := os.Getenv("TEST_POSTGRES_DSN") + if dsn == "" { + t.Skip("TEST_POSTGRES_DSN is not configured") + } + ctx := context.Background() + database, err := OpenPostgres(ctx, dsn, 5, 2) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + rows := seedBatchUpdateAccounts(t, database, 2001) + ids := accountModelIDs(rows) + maxConcurrent := 3 + + updated, err := NewAccountRepository(database).UpdateMany(ctx, account.ProviderBuild, ids, repository.AccountUpdates{MaxConcurrent: &maxConcurrent}) + if err != nil { + t.Fatal(err) + } + if updated != int64(len(ids)) { + t.Fatalf("updated = %d, want %d", updated, len(ids)) + } + var count int64 + if err := database.db.Model(&accountModel{}).Where("id IN ? AND max_concurrent = ?", ids, maxConcurrent).Count(&count).Error; err != nil { + t.Fatal(err) + } + if count != int64(len(ids)) { + t.Fatalf("stored count = %d, want %d", count, len(ids)) + } +} diff --git a/backend/internal/infra/persistence/relational/postgres_integration_test.go b/backend/internal/infra/persistence/relational/postgres_integration_test.go index bdf48f0d..a41334c5 100644 --- a/backend/internal/infra/persistence/relational/postgres_integration_test.go +++ b/backend/internal/infra/persistence/relational/postgres_integration_test.go @@ -959,7 +959,7 @@ func TestPostgresRoutingProjectionAndCredentialHydration(t *testing.T) { t.Fatalf("cross-provider credential error = %v, want ErrNotFound", err) } disabled := false - if _, err := accounts.UpdateMany(ctx, []uint64{created.ID}, repository.AccountUpdates{Enabled: &disabled}); err != nil { + if _, err := accounts.UpdateMany(ctx, account.ProviderBuild, []uint64{created.ID}, repository.AccountUpdates{Enabled: &disabled}); err != nil { t.Fatal(err) } if _, err := accounts.GetCredentialMaterial(ctx, created.ID, account.ProviderWeb); !errors.Is(err, repository.ErrNotFound) { diff --git a/backend/internal/infra/persistence/relational/routing_projection_test.go b/backend/internal/infra/persistence/relational/routing_projection_test.go index c317fcdc..3d90cdd7 100644 --- a/backend/internal/infra/persistence/relational/routing_projection_test.go +++ b/backend/internal/infra/persistence/relational/routing_projection_test.go @@ -146,7 +146,7 @@ func TestGetCredentialMaterialHydratesOneAccountAndMapsNotFound(t *testing.T) { t.Fatalf("cross-provider credential material error = %v, want ErrNotFound", err) } disabled := false - if _, err := accounts.UpdateMany(ctx, []uint64{created.ID}, repository.AccountUpdates{Enabled: &disabled}); err != nil { + if _, err := accounts.UpdateMany(ctx, account.ProviderBuild, []uint64{created.ID}, repository.AccountUpdates{Enabled: &disabled}); err != nil { t.Fatal(err) } if _, err := accounts.GetCredentialMaterial(ctx, created.ID, account.ProviderBuild); !errors.Is(err, repository.ErrNotFound) { diff --git a/backend/internal/repository/account.go b/backend/internal/repository/account.go index a71e58da..541de173 100644 --- a/backend/internal/repository/account.go +++ b/backend/internal/repository/account.go @@ -87,7 +87,7 @@ type AccountRepository interface { GetQuotaRecoveries(ctx context.Context, accountIDs []uint64) (map[uint64]account.QuotaRecovery, error) UpsertByIdentity(ctx context.Context, value account.Credential) (account.Credential, bool, error) Update(ctx context.Context, value account.Credential) (account.Credential, error) - UpdateMany(ctx context.Context, ids []uint64, updates AccountUpdates) (int64, error) + UpdateMany(ctx context.Context, provider account.Provider, ids []uint64, updates AccountUpdates) (int64, error) Delete(ctx context.Context, id uint64) error DeleteMany(ctx context.Context, ids []uint64) (int64, error) // ResolveLinkedDeleteIDs expands root account IDs with one-hop (or Build/Console two-hop via Web) diff --git a/backend/internal/repository/errors.go b/backend/internal/repository/errors.go index 42fcb1ef..b59de8fe 100644 --- a/backend/internal/repository/errors.go +++ b/backend/internal/repository/errors.go @@ -6,10 +6,11 @@ import ( ) var ( - ErrNotFound = errors.New("repository: not found") - ErrConflict = errors.New("repository: conflict") - ErrLimitExceeded = errors.New("repository: limit exceeded") - ErrInvalidRecord = errors.New("repository: invalid record") + ErrNotFound = errors.New("repository: not found") + ErrConflict = errors.New("repository: conflict") + ErrLimitExceeded = errors.New("repository: limit exceeded") + ErrInvalidRecord = errors.New("repository: invalid record") + ErrAccountPoolMismatch = errors.New("repository: account pool mismatch") ) // InvalidBatchRecordError identifies a deterministic invalid record without diff --git a/backend/internal/transport/http/account/handler.go b/backend/internal/transport/http/account/handler.go index efaca4ee..aa16ebe8 100644 --- a/backend/internal/transport/http/account/handler.go +++ b/backend/internal/transport/http/account/handler.go @@ -438,10 +438,7 @@ func (h *Handler) batchUpdate(c *gin.Context) { response.Error(c, http.StatusBadRequest, "invalidId", err.Error()) return } - if !h.validateProviderIDs(c, ids, request.Provider) { - return - } - updated, err := h.service.BatchUpdate(c.Request.Context(), ids, accountapp.UpdateInput{Enabled: request.Enabled, Priority: request.Priority, MaxConcurrent: request.MaxConcurrent, MinimumRemaining: request.MinimumRemaining}) + updated, err := h.service.BatchUpdate(c.Request.Context(), accountdomain.Provider(request.Provider), ids, accountapp.UpdateInput{Enabled: request.Enabled, Priority: request.Priority, MaxConcurrent: request.MaxConcurrent, MinimumRemaining: request.MinimumRemaining}) if err != nil { h.writeServiceError(c, "accountBatchUpdateFailed", err, http.StatusInternalServerError, "批量更新账号失败") return @@ -1284,6 +1281,8 @@ func (h *Handler) writeServiceError(c *gin.Context, code string, err error, fall response.Error(c, http.StatusBadRequest, "accountExportLimitExceeded", err.Error()) case errors.Is(err, accountapp.ErrInvalidInput), errors.Is(err, accountapp.ErrInvalidImport): response.Error(c, http.StatusBadRequest, code, err.Error()) + case errors.Is(err, accountapp.ErrAccountPoolMismatch): + response.Error(c, http.StatusConflict, "accountPoolMismatch", err.Error()) case errors.Is(err, accountapp.ErrConflict): response.Error(c, http.StatusConflict, code, err.Error()) case errors.Is(err, accountapp.ErrNotFound): diff --git a/frontend/src/features/accounts/accounts-page.tsx b/frontend/src/features/accounts/accounts-page.tsx index 69758600..d6274127 100644 --- a/frontend/src/features/accounts/accounts-page.tsx +++ b/frontend/src/features/accounts/accounts-page.tsx @@ -1636,7 +1636,7 @@ export function AccountsPage() { if (!open && batchConcurrencyMutation.isPending) return; setBatchConcurrencyOpen(open); }}> - + {t("accounts.batchConcurrencyTitle", { count: selected.size })} {t("accounts.batchConcurrencyDescription")} @@ -1654,9 +1654,10 @@ export function AccountsPage() { /> - +