From 5efc09a29fd3ed2f8764f97857131e9431d4e0f3 Mon Sep 17 00:00:00 2001 From: buddhism5080 Date: Mon, 31 Aug 2026 16:04:05 +0800 Subject: [PATCH 1/3] fix: lift Build function parameter root unions for xAI grammar Codex/OpenAI Responses tools often send a root oneOf/anyOf whose branches are $ref or nested unions. xAI/Build grammar requires a root object or a root union of inline objects. Lift only the root union, keep property $ref/$defs, and fail locally if the result is still illegal. Also treat streamed 400 JSON as ClassifyUpstreamHTTPError instead of copyStream, so invalid-argument is request-scoped and does not rotate accounts. Compatibility warning is function_parameters_root_normalized. --- .../internal/application/gateway/failure.go | 26 +++ .../application/gateway/failure_test.go | 16 ++ .../cli/responses_parameters_root_test.go | 197 ++++++++++++++++ .../cli/responses_tool_declarations.go | 220 +++++++++++++----- .../provider/cli/responses_tools_test.go | 12 +- .../infra/provider/console/console_test.go | 38 +++ .../infra/provider/console/normalize.go | 24 +- .../transport/http/inference/handler.go | 23 +- .../transport/http/inference/handler_test.go | 32 +++ 9 files changed, 523 insertions(+), 65 deletions(-) create mode 100644 backend/internal/infra/provider/cli/responses_parameters_root_test.go diff --git a/backend/internal/application/gateway/failure.go b/backend/internal/application/gateway/failure.go index 920c4f3f..993c7bf4 100644 --- a/backend/internal/application/gateway/failure.go +++ b/backend/internal/application/gateway/failure.go @@ -153,6 +153,21 @@ func newHTTPUpstreamFailure(status int, body []byte, accountID uint64, accountNa failure.SpendingLimitBlocked = isPaidQuotaExhaustion(metadataText) failure.CredentialRejected = !failure.QuotaExhausted && containsAny(metadataText, "authentication", "unauthorized", "invalid token", "token expired") failure.AccountScoped = failure.AccountBlocked || failure.PermanentAccountDenial || failure.QuotaExhausted || failure.CredentialRejected || isAccountScopedForbidden(metadataText) + case http.StatusBadRequest: + if isRequestScopedForbidden(upstreamCode, metadataText) { + failure.Code = "invalid_argument" + failure.RequestScopedForbidden = true + if upstreamMessage != "" { + failure.PublicMessage = upstreamMessage + } else { + failure.PublicMessage = "请求参数无效" + } + break + } + failure.Code = "upstream_error" + if upstreamMessage != "" { + failure.PublicMessage = upstreamMessage + } case http.StatusTooManyRequests: failure.Code = "upstream_rate_limited" failure.PublicMessage = "上游请求频率受限" @@ -174,6 +189,17 @@ func newHTTPUpstreamFailure(status int, body []byte, accountID uint64, accountNa return failure } +// ClassifyUpstreamHTTPError maps an upstream HTTP error body to a client-facing +// error code and message. Request-scoped 400s (invalid-argument) keep the +// upstream text so the client can see the tool name. +func ClassifyUpstreamHTTPError(status int, body []byte) (string, string) { + failure := newHTTPUpstreamFailure(status, body, 0, "") + if failure == nil { + return "upstream_error", "上游服务返回错误" + } + return failure.Code, failure.PublicMessage +} + func newTransportUpstreamFailure(err error, accountID uint64, accountName string) *UpstreamFailure { code, message := "upstream_network_error", "连接上游服务失败" status := http.StatusBadGateway diff --git a/backend/internal/application/gateway/failure_test.go b/backend/internal/application/gateway/failure_test.go index b93aff5d..ae318f82 100644 --- a/backend/internal/application/gateway/failure_test.go +++ b/backend/internal/application/gateway/failure_test.go @@ -126,6 +126,11 @@ func TestHTTPUpstreamFailureClassifiesBuildForbiddenBodies(t *testing.T) { name: "invalid argument code", body: `{"code":"invalid-argument","error":"unsupported request field"}`, requestScopedForbidden: true, upstreamCode: "invalid-argument", }, + { + name: "400 tool schema union", status: http.StatusBadRequest, + body: `{"code":"invalid-argument","error":"mcp__codex_app__automation_update: tool parameter root must be an object type (root schema is an anyOf/oneOf union with a non-object branch)"}`, + requestScopedForbidden: true, upstreamCode: "invalid-argument", + }, { name: "request-level access denied sentence", body: `{"code":"operation-denied","error":"Access denied because this operation is unavailable under ZDR"}`, requestScopedForbidden: true, upstreamCode: "operation-denied", @@ -160,6 +165,17 @@ func TestHTTPUpstreamFailureClassifiesBuildForbiddenBodies(t *testing.T) { } } +func TestClassifyUpstreamHTTPErrorInvalidArgument(t *testing.T) { + code, message := ClassifyUpstreamHTTPError(http.StatusBadRequest, []byte(`{"code":"invalid-argument","error":"mcp__codex_app__automation_update: tool parameter root must be an object type (root schema is an anyOf/oneOf union with a non-object branch)"}`)) + if code != "invalid_argument" || !strings.Contains(message, "mcp__codex_app__automation_update") { + t.Fatalf("code=%q message=%q", code, message) + } + failure := newHTTPUpstreamFailure(http.StatusBadRequest, []byte(`{"code":"invalid-argument","error":"mcp__codex_app__automation_update: tool parameter root must be an object type"}`), 42, "build") + if !failure.RequestScopedForbidden || failure.AccountScoped || failure.Code != "invalid_argument" { + t.Fatalf("failure = %#v", failure) + } +} + func TestHTTPUpstreamFailureClassifiesDPoPRequirementAsSystemic(t *testing.T) { failure := newHTTPUpstreamFailure(http.StatusForbidden, []byte(`{"code":"unauthorized:dpop-required","error":"DPoP proof required but was not verified."}`), 42, "console") if failure.AccountScoped || failure.CredentialRejected || !failure.RequestScopedForbidden { diff --git a/backend/internal/infra/provider/cli/responses_parameters_root_test.go b/backend/internal/infra/provider/cli/responses_parameters_root_test.go new file mode 100644 index 00000000..f6409c18 --- /dev/null +++ b/backend/internal/infra/provider/cli/responses_parameters_root_test.go @@ -0,0 +1,197 @@ +package cli + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestNormalizeBuildFunctionParametersRootLiftsNestedUnionRefs(t *testing.T) { + schema := map[string]any{ + "$defs": map[string]any{ + "ID": map[string]any{"type": "string"}, + "View": map[string]any{"type": "object", "properties": map[string]any{"mode": map[string]any{"enum": []any{"view"}, "type": "string"}, "id": map[string]any{"$ref": "#/$defs/ID"}}, "required": []any{"mode", "id"}, "additionalProperties": false}, + "Create": map[string]any{"oneOf": []any{ + map[string]any{"$ref": "#/$defs/CreateCron"}, + map[string]any{"$ref": "#/$defs/CreateHB"}, + }}, + "CreateCron": map[string]any{"type": "object", "properties": map[string]any{"mode": map[string]any{"enum": []any{"create"}, "type": "string"}, "kind": map[string]any{"enum": []any{"cron"}, "type": "string"}, "name": map[string]any{"$ref": "#/$defs/ID"}}, "required": []any{"mode", "kind", "name"}, "additionalProperties": false}, + "CreateHB": map[string]any{"type": "object", "properties": map[string]any{"mode": map[string]any{"enum": []any{"create"}, "type": "string"}, "kind": map[string]any{"enum": []any{"heartbeat"}, "type": "string"}, "name": map[string]any{"$ref": "#/$defs/ID"}}, "required": []any{"mode", "kind", "name"}, "additionalProperties": false}, + "Delete": map[string]any{"type": "object", "properties": map[string]any{"mode": map[string]any{"enum": []any{"delete"}, "type": "string"}, "id": map[string]any{"$ref": "#/$defs/ID"}}, "required": []any{"mode", "id"}, "additionalProperties": false}, + }, + "type": "object", + "properties": map[string]any{}, + "oneOf": []any{ + map[string]any{"$ref": "#/$defs/View"}, + map[string]any{"$ref": "#/$defs/Create"}, + map[string]any{"$ref": "#/$defs/Delete"}, + }, + } + normalized, changed, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters") + if err != nil { + t.Fatal(err) + } + out, ok := normalized.(map[string]any) + if !ok || !changed { + t.Fatalf("normalized=%#v changed=%v", normalized, changed) + } + if _, exists := out["$ref"]; exists { + t.Fatalf("root still has $ref: %#v", out) + } + branches, _ := out["oneOf"].([]any) + if out["type"] != nil || len(branches) != 4 { + t.Fatalf("want root oneOf[4] without type wrapper, got %#v", out) + } + for i, raw := range branches { + branch, _ := raw.(map[string]any) + if branch["type"] != "object" { + t.Fatalf("branch[%d] type=%v %#v", i, branch["type"], branch) + } + if _, exists := branch["oneOf"]; exists { + t.Fatalf("branch[%d] still nested oneOf: %#v", i, branch) + } + if _, exists := branch["$ref"]; exists { + t.Fatalf("branch[%d] still $ref: %#v", i, branch) + } + props, _ := branch["properties"].(map[string]any) + if id, ok := props["id"].(map[string]any); ok { + if id["$ref"] != "#/$defs/ID" { + t.Fatalf("property $ref was inlined: %#v", id) + } + } + if name, ok := props["name"].(map[string]any); ok { + if name["$ref"] != "#/$defs/ID" { + t.Fatalf("property $ref was inlined: %#v", name) + } + } + } + defs, _ := out["$defs"].(map[string]any) + if _, ok := defs["ID"]; !ok { + t.Fatalf("$defs.ID dropped: %#v", defs) + } +} + +func TestNormalizeBuildFunctionParametersRootKeepsNestedPropertyUnion(t *testing.T) { + schema := map[string]any{ + "type": "object", + "properties": map[string]any{"value": map[string]any{ + "anyOf": []any{map[string]any{"type": "string"}, map[string]any{"type": "null"}}, + }}, + } + normalized, changed, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters") + if err != nil { + t.Fatal(err) + } + out := normalized.(map[string]any) + value := out["properties"].(map[string]any)["value"].(map[string]any) + if changed || value["anyOf"] == nil { + t.Fatalf("nested anyOf was rewritten: %#v changed=%v", out, changed) + } +} + +func TestNormalizeBuildFunctionParametersRootLiftsOneOfNestedAnyOf(t *testing.T) { + schema := map[string]any{ + "oneOf": []any{ + map[string]any{"type": "object", "properties": map[string]any{"a": map[string]any{"type": "string"}}}, + map[string]any{"anyOf": []any{ + map[string]any{"type": "object", "properties": map[string]any{"b": map[string]any{"type": "string"}}}, + map[string]any{"type": "null"}, + }}, + }, + } + normalized, changed, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters") + if err != nil { + t.Fatal(err) + } + out := normalized.(map[string]any) + branches, _ := out["oneOf"].([]any) + if !changed || len(branches) != 2 { + t.Fatalf("want 2 object leaves, got %#v", out) + } + for i, raw := range branches { + if raw.(map[string]any)["type"] != "object" { + t.Fatalf("branch[%d]=%#v", i, raw) + } + } +} + +func TestNormalizeBuildFunctionParametersRootRejectsRootCycle(t *testing.T) { + schema := map[string]any{ + "$defs": map[string]any{ + "Loop": map[string]any{"$ref": "#/$defs/Loop"}, + }, + "oneOf": []any{map[string]any{"$ref": "#/$defs/Loop"}}, + } + _, _, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters") + requestErr, ok := err.(*responsesRequestError) + if !ok || requestErr.Param != "tools[0].parameters" { + t.Fatalf("error = %#v", err) + } +} + +func TestNormalizeBuildFunctionParametersRootKeepsPropertyCycle(t *testing.T) { + schema := map[string]any{ + "$defs": map[string]any{ + "Node": map[string]any{ + "type": "object", + "properties": map[string]any{ + "child": map[string]any{"$ref": "#/$defs/Node"}, + }, + }, + }, + "type": "object", + "properties": map[string]any{ + "root": map[string]any{"$ref": "#/$defs/Node"}, + }, + } + normalized, changed, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters") + if err != nil { + t.Fatal(err) + } + out := normalized.(map[string]any) + if changed { + t.Fatalf("property cycle should not rewrite root: %#v", out) + } + root := out["properties"].(map[string]any)["root"].(map[string]any) + if root["$ref"] != "#/$defs/Node" { + t.Fatalf("property $ref rewritten: %#v", root) + } +} + +func TestNormalizeResponsesRequestLiftsAutomationUpdateStyleUnion(t *testing.T) { + body := []byte(`{ + "model":"public","input":"hello", + "tools":[{"type":"function","name":"mcp__codex_app__automation_update","parameters":{ + "$defs":{ + "ID":{"type":"string"}, + "View":{"type":"object","properties":{"mode":{"enum":["view"],"type":"string"},"id":{"$ref":"#/$defs/ID"}},"required":["mode","id"]}, + "Create":{"oneOf":[ + {"type":"object","properties":{"mode":{"enum":["create"],"type":"string"},"name":{"$ref":"#/$defs/ID"}},"required":["mode","name"]} + ]} + }, + "type":"object", + "properties":{}, + "oneOf":[{"$ref":"#/$defs/View"},{"$ref":"#/$defs/Create"}] + }}] + }`) + normalized, compatibility, err := normalizeResponsesRequest(body, "grok-4.5") + if err != nil { + t.Fatal(err) + } + if compatibility == nil || !strings.Contains(compatibility.warningHeader(), "function_parameters_root_normalized") { + t.Fatalf("compatibility = %#v", compatibility) + } + var payload map[string]any + if err := json.Unmarshal(normalized, &payload); err != nil { + t.Fatal(err) + } + parameters := payload["tools"].([]any)[0].(map[string]any)["parameters"].(map[string]any) + branches, _ := parameters["oneOf"].([]any) + if len(branches) != 2 { + t.Fatalf("upstream parameters = %#v", parameters) + } + visible := compatibility.visibleTools[0].(map[string]any)["parameters"].(map[string]any) + if _, ok := visible["$defs"]; !ok { + t.Fatalf("visible schema lost $defs: %#v", visible) + } +} diff --git a/backend/internal/infra/provider/cli/responses_tool_declarations.go b/backend/internal/infra/provider/cli/responses_tool_declarations.go index d6b9ef75..42986d85 100644 --- a/backend/internal/infra/provider/cli/responses_tool_declarations.go +++ b/backend/internal/infra/provider/cli/responses_tool_declarations.go @@ -179,7 +179,7 @@ func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, cl if changed { converted["parameters"] = normalized c.changed = true - c.addWarning("function_parameters_nullable_root_normalized") + c.addWarning("function_parameters_root_normalized") } } identity := responsesToolIdentity{Kind: responsesFunctionTool, Namespace: namespace, Name: name} @@ -273,9 +273,19 @@ func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, cl } } -// normalizeBuildFunctionParametersRoot removes root-level nullability from function schemas. -// Build requires the parameter root to be an object, while Codex can emit `object | null` -// for tools with an optional argument object. Nested nullable fields remain untouched. +const maxRootUnionDepth = 32 +const maxRootUnionLeaves = 32 + +// NormalizeBuildFunctionParametersRoot rewrites a function parameters schema so +// Grok Build can compile it: the root is an object, or a oneOf of object +// leaves. Nested oneOf/anyOf at the root are lifted; $ref inside properties +// and recursive property $ref are left alone. +func NormalizeBuildFunctionParametersRoot(value any, param string) (any, bool, error) { + return normalizeBuildFunctionParametersRoot(value, param) +} + +// normalizeBuildFunctionParametersRoot removes root-level nullability from function schemas +// and lifts nested root unions. Nested nullable fields remain untouched. func normalizeBuildFunctionParametersRoot(value any, param string) (any, bool, error) { schema, ok := value.(map[string]any) if !ok { @@ -302,56 +312,162 @@ func normalizeBuildFunctionParametersRoot(value any, param string) (any, bool, e } } - for _, keyword := range []string{"anyOf", "oneOf"} { - rawBranches, exists := normalized[keyword] - if !exists { - continue - } - branches, ok := rawBranches.([]any) - if !ok { - continue - } - filtered := make([]any, 0, len(branches)) - removedNull := false - for _, rawBranch := range branches { - if isNullOnlySchema(rawBranch) { - removedNull = true - continue - } - filtered = append(filtered, rawBranch) - } - if !removedNull { - continue - } - changed = true - if len(filtered) == 0 { - return nil, false, invalidBuildFunctionParametersRoot(param) - } - if len(filtered) == 1 { - branch, ok := filtered[0].(map[string]any) - if !ok || !isObjectRootSchema(branch, normalized, nil) { - return nil, false, invalidBuildFunctionParametersRoot(param) - } - if len(normalized) == 1 { - normalized = cloneJSONObject(branch) - normalized["type"] = "object" - continue - } - normalized[keyword] = cloneJSONArray(filtered) - normalized["type"] = "object" - continue - } - for _, rawBranch := range filtered { - branch, ok := rawBranch.(map[string]any) - if !ok || !isObjectRootSchema(branch, normalized, nil) { - return nil, false, invalidBuildFunctionParametersRoot(param) - } - } - normalized[keyword] = cloneJSONArray(filtered) - normalized["type"] = "object" + if !rootHasUnion(normalized) { + return normalized, changed, nil } + leaves, err := collectRootObjectLeaves(normalized, param) + if err != nil { + return nil, false, err + } + if len(leaves) == 0 { + return nil, false, invalidBuildFunctionParametersRoot(param) + } + var out map[string]any + if len(leaves) == 1 { + out = leaves[0] + } else { + branches := make([]any, len(leaves)) + for i, leaf := range leaves { + branches[i] = leaf + } + out = map[string]any{"oneOf": branches} + } + if defs := referencedDefs(out, normalized); len(defs) > 0 { + out["$defs"] = defs + } + return out, true, nil +} - return normalized, changed, nil +func rootHasUnion(schema map[string]any) bool { + for _, keyword := range []string{"anyOf", "oneOf"} { + if _, ok := schema[keyword].([]any); ok { + return true + } + } + return false +} + +func collectRootObjectLeaves(doc map[string]any, param string) ([]map[string]any, error) { + var leaves []map[string]any + if err := walkRootUnion(doc, doc, param, nil, 0, &leaves); err != nil { + return nil, err + } + return leaves, nil +} + +func walkRootUnion(node any, doc map[string]any, param string, seen map[string]struct{}, depth int, leaves *[]map[string]any) error { + if depth > maxRootUnionDepth || len(*leaves) > maxRootUnionLeaves { + return invalidBuildFunctionParametersRoot(param) + } + schema, ok := node.(map[string]any) + if !ok { + return invalidBuildFunctionParametersRoot(param) + } + if ref, ok := schema["$ref"].(string); ok && !hasUnionKeys(schema) && schema["type"] == nil && schema["properties"] == nil { + if !strings.HasPrefix(ref, "#/") { + return invalidBuildFunctionParametersRoot(param) + } + if _, loop := seen[ref]; loop { + return invalidBuildFunctionParametersRoot(param) + } + resolved, ok := resolveLocalSchemaRef(doc, ref) + if !ok { + return invalidBuildFunctionParametersRoot(param) + } + next := cloneRefSeen(seen) + next[ref] = struct{}{} + return walkRootUnion(resolved, doc, param, next, depth+1, leaves) + } + if isNullOnlySchema(schema) { + return nil + } + if hasUnionKeys(schema) { + for _, keyword := range []string{"anyOf", "oneOf"} { + raw, ok := schema[keyword].([]any) + if !ok { + continue + } + for _, branch := range raw { + if err := walkRootUnion(branch, doc, param, cloneRefSeen(seen), depth+1, leaves); err != nil { + return err + } + } + } + return nil + } + if !isObjectRootSchema(schema, doc, nil) { + return invalidBuildFunctionParametersRoot(param) + } + leaf := cloneJSONObject(schema) + leaf["type"] = "object" + *leaves = append(*leaves, leaf) + if len(*leaves) > maxRootUnionLeaves { + return invalidBuildFunctionParametersRoot(param) + } + return nil +} + +func hasUnionKeys(schema map[string]any) bool { + _, anyOf := schema["anyOf"] + _, oneOf := schema["oneOf"] + return anyOf || oneOf +} + +func cloneRefSeen(seen map[string]struct{}) map[string]struct{} { + out := make(map[string]struct{}, len(seen)+1) + for key, value := range seen { + out[key] = value + } + return out +} + +func referencedDefs(node any, doc map[string]any) map[string]any { + rawDefs, _ := doc["$defs"].(map[string]any) + if len(rawDefs) == 0 { + return nil + } + needed := map[string]struct{}{} + collectDefRefs(node, needed) + changed := true + for changed { + changed = false + for name := range needed { + extra := map[string]struct{}{} + collectDefRefs(rawDefs[name], extra) + for key := range extra { + if _, exists := needed[key]; !exists { + needed[key] = struct{}{} + changed = true + } + } + } + } + if len(needed) == 0 { + return nil + } + out := make(map[string]any, len(needed)) + for name := range needed { + if def, ok := rawDefs[name]; ok { + out[name] = cloneJSONValue(def) + } + } + return out +} + +func collectDefRefs(node any, needed map[string]struct{}) { + switch typed := node.(type) { + case map[string]any: + if ref, ok := typed["$ref"].(string); ok && strings.HasPrefix(ref, "#/$defs/") { + needed[strings.TrimPrefix(ref, "#/$defs/")] = struct{}{} + } + for _, value := range typed { + collectDefRefs(value, needed) + } + case []any: + for _, value := range typed { + collectDefRefs(value, needed) + } + } } func withoutNullSchemaTypes(types []any) ([]any, bool) { diff --git a/backend/internal/infra/provider/cli/responses_tools_test.go b/backend/internal/infra/provider/cli/responses_tools_test.go index 4bb7a27c..93070718 100644 --- a/backend/internal/infra/provider/cli/responses_tools_test.go +++ b/backend/internal/infra/provider/cli/responses_tools_test.go @@ -279,7 +279,7 @@ func TestNormalizeResponsesRequestRemovesNullableFunctionParameterRoot(t *testin if err != nil { t.Fatal(err) } - if compatibility == nil || !strings.Contains(compatibility.warningHeader(), "function_parameters_nullable_root_normalized") { + if compatibility == nil || !strings.Contains(compatibility.warningHeader(), "function_parameters_root_normalized") { t.Fatalf("compatibility = %#v", compatibility) } var payload map[string]any @@ -328,7 +328,7 @@ func TestNormalizeResponsesRequestRemovesNullableLocalRefFunctionRoot(t *testing if err != nil { t.Fatal(err) } - if compatibility == nil || !strings.Contains(compatibility.warningHeader(), "function_parameters_nullable_root_normalized") { + if compatibility == nil || !strings.Contains(compatibility.warningHeader(), "function_parameters_root_normalized") { t.Fatalf("compatibility = %#v", compatibility) } var payload map[string]any @@ -336,12 +336,12 @@ func TestNormalizeResponsesRequestRemovesNullableLocalRefFunctionRoot(t *testing t.Fatal(err) } parameters := payload["tools"].([]any)[0].(map[string]any)["parameters"].(map[string]any) - if parameters["type"] != "object" { + if parameters["type"] != "object" || parameters["anyOf"] != nil { t.Fatalf("upstream parameters = %#v", parameters) } - branches := parameters["anyOf"].([]any) - if len(branches) != 1 || branches[0].(map[string]any)["$ref"] != "#/$defs/Args" { - t.Fatalf("upstream branches = %#v", branches) + properties := parameters["properties"].(map[string]any) + if properties["query"].(map[string]any)["type"] != "string" { + t.Fatalf("upstream properties = %#v", properties) } visibleParameters := compatibility.visibleTools[0].(map[string]any)["parameters"].(map[string]any) visibleBranches := visibleParameters["anyOf"].([]any) diff --git a/backend/internal/infra/provider/console/console_test.go b/backend/internal/infra/provider/console/console_test.go index 4aa2a813..22537aa8 100644 --- a/backend/internal/infra/provider/console/console_test.go +++ b/backend/internal/infra/provider/console/console_test.go @@ -336,6 +336,44 @@ func TestNormalizeRequestAppliesConsoleContract(t *testing.T) { } } +func TestNormalizeRequestLiftsFunctionParameterUnion(t *testing.T) { + spec, ok := Resolve("grok-4.3") + if !ok { + t.Fatal("grok-4.3 missing") + } + body, err := normalizeRequest([]byte(`{ + "model":"grok-4.3", + "input":"hello", + "tools":[{"type":"function","name":"automation_update","parameters":{ + "$defs":{ + "View":{"type":"object","properties":{"mode":{"enum":["view"],"type":"string"}},"required":["mode"]}, + "Create":{"oneOf":[{"type":"object","properties":{"mode":{"enum":["create"],"type":"string"}},"required":["mode"]}]} + }, + "type":"object", + "properties":{}, + "oneOf":[{"$ref":"#/$defs/View"},{"$ref":"#/$defs/Create"}] + }}] + }`), spec) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(body, &payload); err != nil { + t.Fatal(err) + } + parameters := payload["tools"].([]any)[0].(map[string]any)["parameters"].(map[string]any) + branches, _ := parameters["oneOf"].([]any) + if len(branches) != 2 { + t.Fatalf("parameters = %#v", parameters) + } + for i, raw := range branches { + branch, _ := raw.(map[string]any) + if branch["type"] != "object" || branch["$ref"] != nil || branch["oneOf"] != nil { + t.Fatalf("branch[%d] = %#v", i, branch) + } + } +} + func TestNormalizeRequestForwardsXSearchTimeRangeAndImageSearch(t *testing.T) { spec, ok := Resolve("grok-4.3") if !ok { diff --git a/backend/internal/infra/provider/console/normalize.go b/backend/internal/infra/provider/console/normalize.go index 1c6c5a02..b62564c5 100644 --- a/backend/internal/infra/provider/console/normalize.go +++ b/backend/internal/infra/provider/console/normalize.go @@ -11,6 +11,7 @@ import ( auditdomain "github.com/chenyme/grok2api/backend/internal/domain/audit" "github.com/chenyme/grok2api/backend/internal/infra/provider" + "github.com/chenyme/grok2api/backend/internal/infra/provider/cli" ) var ( @@ -46,7 +47,10 @@ func normalizeRequestWithMetadata(body []byte, spec ModelSpec, metadata *provide normalizeReasoning(payload, spec) updateConsoleReasoningMetadata(payload, spec, requestedEffort, metadata) ensureReasoningInclude(payload) - retainedClientTools := normalizeConsoleTools(payload) + retainedClientTools, err := normalizeConsoleTools(payload) + if err != nil { + return nil, err + } normalizeConsoleToolChoice(payload, retainedClientTools) return json.Marshal(payload) } @@ -241,18 +245,18 @@ func ensureReasoningInclude(payload map[string]any) { payload["include"] = result } -func normalizeConsoleTools(payload map[string]any) bool { +func normalizeConsoleTools(payload map[string]any) (bool, error) { value, exists := payload["tools"] if !exists || value == nil { delete(payload, "tools") delete(payload, "tool_choice") - return false + return false, nil } tools, ok := value.([]any) if !ok { delete(payload, "tools") delete(payload, "tool_choice") - return false + return false, nil } hasClientViewImage := hasConsoleFunctionTool(tools, "view_image") result := make([]any, 0, len(tools)) @@ -315,6 +319,14 @@ func normalizeConsoleTools(payload map[string]any) bool { clean := map[string]any{"type": "function", "name": strings.TrimSpace(name)} for _, field := range []string{"description", "parameters", "strict"} { if fieldValue, exists := tool[field]; exists { + if field == "parameters" { + normalized, _, err := cli.NormalizeBuildFunctionParametersRoot(fieldValue, "tools.parameters") + if err != nil { + return false, err + } + clean[field] = normalized + continue + } clean[field] = fieldValue } } @@ -331,10 +343,10 @@ func normalizeConsoleTools(payload map[string]any) bool { if len(result) == 0 { delete(payload, "tools") delete(payload, "tool_choice") - return false + return false, nil } payload["tools"] = result - return retainedClientTools + return retainedClientTools, nil } func hasConsoleFunctionTool(tools []any, target string) bool { diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index 31ed8b21..21967c5e 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -1292,10 +1292,26 @@ func (h *Handler) writeProtocolResult(c *gin.Context, result *gateway.Result, st return } copyHeaders(c.Writer.Header(), result.Header) - c.Status(result.StatusCode) if result.StatusCode >= 400 { errorCode = "upstream_error" + if stream && !isEventStreamContentType(result.Header.Get("Content-Type")) { + raw, readErr := io.ReadAll(io.LimitReader(result.Body, maxJSONResponseTransferBytes+1)) + if readErr != nil { + writeOpenAIError(c, http.StatusBadGateway, "upstream_error", "读取上游错误响应失败") + return + } + c.Writer.Header().Del("Content-Length") + code, message := gateway.ClassifyUpstreamHTTPError(result.StatusCode, raw) + errorCode = code + if anthropic { + writeAnthropicError(c, result.StatusCode, "invalid_request_error", message, errorCode) + } else { + writeOpenAIError(c, result.StatusCode, errorCode, message) + } + return + } } + c.Status(result.StatusCode) var err error if stream { metadata, copyErr := copyStreamWithFallbackModel(c.Writer, result.Body, protocol, result.MarkFirstToken, fallbackModel) @@ -2224,6 +2240,11 @@ func copyHeaders(destination, source http.Header) { } } +func isEventStreamContentType(value string) bool { + mediaType, _, err := mime.ParseMediaType(value) + return err == nil && strings.EqualFold(mediaType, "text/event-stream") +} + func writeOpenAIError(c *gin.Context, status int, code, message string) { errorType := "invalid_request_error" switch { diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go index 45d24066..580184f7 100644 --- a/backend/internal/transport/http/inference/handler_test.go +++ b/backend/internal/transport/http/inference/handler_test.go @@ -1605,6 +1605,38 @@ func TestWriteResultUpstreamCutStaysUpstreamInterrupted(t *testing.T) { } } +func TestWriteProtocolResultMapsJSONInvalidArgumentWithoutCopyStream(t *testing.T) { + gin.SetMode(gin.TestMode) + handler := NewHandler(nil, nil, 1<<20) + body := `{"code":"invalid-argument","error":"mcp__codex_app__automation_update: tool parameter root must be an object type (root schema is an anyOf/oneOf union with a non-object branch)"}` + var finalCode string + recorded := false + result := &gateway.Result{ + StatusCode: http.StatusBadRequest, + Status: "400 Bad Request", + Header: http.Header{"Content-Type": {"application/json"}, "Content-Length": {fmt.Sprintf("%d", len(body))}}, + Body: io.NopCloser(strings.NewReader(body)), + RecordStreamFailure: func(gateway.StreamFailureDiagnostic) { + recorded = true + }, + Finalize: func(_ gateway.Usage, _, code string) { + finalCode = code + }, + } + router := gin.New() + router.GET("/", func(c *gin.Context) { + handler.writeResponsesResult(c, result, true, "") + }) + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) + if recorder.Code != http.StatusBadRequest || recorded || finalCode != "invalid_argument" { + t.Fatalf("status=%d recorded=%v final=%q body=%s", recorder.Code, recorded, finalCode, recorder.Body.String()) + } + if !strings.Contains(recorder.Body.String(), "mcp__codex_app__automation_update") || strings.Contains(recorder.Body.String(), "upstream_stream_incomplete") { + t.Fatalf("body=%s", recorder.Body.String()) + } +} + func TestProjectStreamFailureDiagnosticBoundsErrorMessage(t *testing.T) { diagnostic := projectStreamFailureDiagnostic([]byte(`{"type":"error","error":{"code":"server_error","message":"` + strings.Repeat("错误", maxStreamFailureDiagnosticBytes) + `"},"output":"must-not-be-audited"}`)) if !diagnostic.BodyTruncated || len(diagnostic.Body) > maxStreamFailureDiagnosticBytes || len(diagnostic.Body) == 0 || !utf8.Valid(diagnostic.Body) || strings.Contains(string(diagnostic.Body), "must-not-be-audited") { From d3ba8ff6d585a4cc32e37bdbe7d6703759777e20 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Mon, 31 Aug 2026 23:41:13 +0800 Subject: [PATCH 2/3] fix: safely normalize Build function parameter root unions --- .../internal/application/gateway/failure.go | 12 +- .../application/gateway/failure_test.go | 7 + .../cli/responses_parameters_root_test.go | 166 ++++++- .../cli/responses_tool_declarations.go | 448 ++++++++++++++---- .../provider/cli/responses_tools_test.go | 9 + .../infra/provider/console/console_test.go | 15 + .../infra/provider/console/normalize.go | 2 +- .../transport/http/inference/handler.go | 23 +- .../transport/http/inference/handler_test.go | 60 +++ 9 files changed, 643 insertions(+), 99 deletions(-) diff --git a/backend/internal/application/gateway/failure.go b/backend/internal/application/gateway/failure.go index 993c7bf4..324523a6 100644 --- a/backend/internal/application/gateway/failure.go +++ b/backend/internal/application/gateway/failure.go @@ -178,8 +178,16 @@ func newHTTPUpstreamFailure(status int, body []byte, accountID uint64, accountNa failure.ModelQuotaExhausted = isModelQuotaExhaustion(metadataText) failure.QuotaExhausted = failure.FreeQuotaExhausted || isPaidQuotaExhaustion(metadataText) default: - failure.Code = "upstream_server_error" - failure.PublicMessage = "上游服务暂时异常" + if status >= 400 && status < 500 { + failure.Code = "upstream_error" + failure.PublicMessage = "上游拒绝了该请求" + if upstreamMessage != "" { + failure.PublicMessage = upstreamMessage + } + } else { + failure.Code = "upstream_server_error" + failure.PublicMessage = "上游服务暂时异常" + } } fingerprintPart := normalizeFailureCode(firstNonEmptyFailure(upstreamCode, upstreamType, upstreamMessage)) if fingerprintPart == "" { diff --git a/backend/internal/application/gateway/failure_test.go b/backend/internal/application/gateway/failure_test.go index ae318f82..f5cec947 100644 --- a/backend/internal/application/gateway/failure_test.go +++ b/backend/internal/application/gateway/failure_test.go @@ -176,6 +176,13 @@ func TestClassifyUpstreamHTTPErrorInvalidArgument(t *testing.T) { } } +func TestClassifyUpstreamHTTPErrorKeepsOther4xxMessage(t *testing.T) { + code, message := ClassifyUpstreamHTTPError(http.StatusNotFound, []byte(`{"error":{"code":"not_found","message":"requested response is missing"}}`)) + if code != "upstream_error" || message != "requested response is missing" { + t.Fatalf("code=%q message=%q", code, message) + } +} + func TestHTTPUpstreamFailureClassifiesDPoPRequirementAsSystemic(t *testing.T) { failure := newHTTPUpstreamFailure(http.StatusForbidden, []byte(`{"code":"unauthorized:dpop-required","error":"DPoP proof required but was not verified."}`), 42, "console") if failure.AccountScoped || failure.CredentialRejected || !failure.RequestScopedForbidden { diff --git a/backend/internal/infra/provider/cli/responses_parameters_root_test.go b/backend/internal/infra/provider/cli/responses_parameters_root_test.go index f6409c18..abd27d47 100644 --- a/backend/internal/infra/provider/cli/responses_parameters_root_test.go +++ b/backend/internal/infra/provider/cli/responses_parameters_root_test.go @@ -92,9 +92,17 @@ func TestNormalizeBuildFunctionParametersRootKeepsNestedPropertyUnion(t *testing func TestNormalizeBuildFunctionParametersRootLiftsOneOfNestedAnyOf(t *testing.T) { schema := map[string]any{ "oneOf": []any{ - map[string]any{"type": "object", "properties": map[string]any{"a": map[string]any{"type": "string"}}}, + map[string]any{ + "type": "object", + "properties": map[string]any{"kind": map[string]any{"const": "a"}}, + "required": []any{"kind"}, + }, map[string]any{"anyOf": []any{ - map[string]any{"type": "object", "properties": map[string]any{"b": map[string]any{"type": "string"}}}, + map[string]any{ + "type": "object", + "properties": map[string]any{"kind": map[string]any{"const": "b"}}, + "required": []any{"kind"}, + }, map[string]any{"type": "null"}, }}, }, @@ -115,6 +123,160 @@ func TestNormalizeBuildFunctionParametersRootLiftsOneOfNestedAnyOf(t *testing.T) } } +func TestNormalizeBuildFunctionParametersRootFollowsBareRootRef(t *testing.T) { + schema := map[string]any{ + "$defs": map[string]any{ + "Args": map[string]any{"oneOf": []any{ + map[string]any{"type": "object", "properties": map[string]any{"mode": map[string]any{"const": "view"}}, "required": []any{"mode"}}, + map[string]any{"type": "object", "properties": map[string]any{"mode": map[string]any{"const": "create"}}, "required": []any{"mode"}}, + }}, + }, + "$ref": "#/$defs/Args", + } + + normalized, changed, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters") + if err != nil { + t.Fatal(err) + } + out := normalized.(map[string]any) + branches, _ := out["oneOf"].([]any) + if !changed || len(branches) != 2 || out["$ref"] != nil { + t.Fatalf("normalized=%#v changed=%v", out, changed) + } + for index, raw := range branches { + branch, _ := raw.(map[string]any) + if branch["type"] != "object" || branch["$ref"] != nil { + t.Fatalf("branch[%d]=%#v", index, branch) + } + } +} + +func TestNormalizeBuildFunctionParametersRootPreservesUnionSiblingConstraints(t *testing.T) { + schema := map[string]any{ + "$defs": map[string]any{ + "Read": map[string]any{"type": "object", "properties": map[string]any{"mode": map[string]any{"const": "read"}}, "required": []any{"mode"}}, + "Write": map[string]any{"type": "object", "properties": map[string]any{"mode": map[string]any{"const": "write"}}, "required": []any{"mode"}}, + }, + "type": "object", + "properties": map[string]any{"tenant": map[string]any{"type": "string"}}, + "required": []any{"tenant"}, + "additionalProperties": false, + "oneOf": []any{ + map[string]any{"$ref": "#/$defs/Read"}, + map[string]any{"$ref": "#/$defs/Write"}, + }, + } + + normalized, changed, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters") + if err != nil { + t.Fatal(err) + } + out := normalized.(map[string]any) + branches, _ := out["oneOf"].([]any) + if !changed || len(branches) != 2 { + t.Fatalf("normalized=%#v changed=%v", out, changed) + } + for index, raw := range branches { + branch := raw.(map[string]any) + allOf, _ := branch["allOf"].([]any) + if branch["type"] != "object" || len(allOf) != 2 { + t.Fatalf("branch[%d]=%#v", index, branch) + } + common := allOf[0].(map[string]any) + if common["additionalProperties"] != false || len(common["required"].([]any)) != 1 { + t.Fatalf("branch[%d] lost common constraints: %#v", index, branch) + } + if _, ok := common["properties"].(map[string]any)["tenant"]; !ok { + t.Fatalf("branch[%d] lost tenant property: %#v", index, branch) + } + } +} + +func TestNormalizeBuildFunctionParametersRootPreservesAnyOf(t *testing.T) { + schema := map[string]any{ + "$defs": map[string]any{ + "A": map[string]any{"type": "object", "properties": map[string]any{"a": map[string]any{"type": "string"}}}, + "B": map[string]any{"type": "object", "properties": map[string]any{"b": map[string]any{"type": "string"}}}, + }, + "anyOf": []any{ + map[string]any{"$ref": "#/$defs/A"}, + map[string]any{"$ref": "#/$defs/B"}, + }, + } + + normalized, changed, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters") + if err != nil { + t.Fatal(err) + } + out := normalized.(map[string]any) + if !changed || len(out["anyOf"].([]any)) != 2 || out["oneOf"] != nil { + t.Fatalf("normalized=%#v changed=%v", out, changed) + } +} + +func TestNormalizeBuildFunctionParametersRootRejectsUnsafeNestedUnionFlatten(t *testing.T) { + schema := map[string]any{ + "oneOf": []any{ + map[string]any{"type": "object", "properties": map[string]any{"a": map[string]any{"type": "string"}}}, + map[string]any{"oneOf": []any{ + map[string]any{"type": "object", "properties": map[string]any{"b": map[string]any{"type": "string"}}}, + map[string]any{"type": "object", "properties": map[string]any{"c": map[string]any{"type": "string"}}}, + }}, + }, + } + + if _, _, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters"); err == nil { + t.Fatal("overlapping nested oneOf should fail locally instead of changing semantics") + } +} + +func TestNormalizeBuildFunctionParametersRootKeepsDefinitionForSubpathRef(t *testing.T) { + schema := map[string]any{ + "$defs": map[string]any{ + "Config": map[string]any{"type": "object", "properties": map[string]any{"id": map[string]any{"type": "string"}}}, + "Args": map[string]any{ + "type": "object", + "properties": map[string]any{"id": map[string]any{"$ref": "#/$defs/Config/properties/id"}}, + }, + }, + "$ref": "#/$defs/Args", + } + + normalized, changed, err := normalizeBuildFunctionParametersRoot(schema, "tools[0].parameters") + if err != nil { + t.Fatal(err) + } + out := normalized.(map[string]any) + defs, _ := out["$defs"].(map[string]any) + if !changed || defs["Config"] == nil || defs["Config/properties/id"] != nil { + t.Fatalf("normalized=%#v changed=%v", out, changed) + } +} + +func TestNormalizeBuildFunctionParametersRootRejectsIllegalRootWithToolName(t *testing.T) { + _, _, err := normalizeBuildFunctionParametersRootForTool( + map[string]any{"type": "string"}, + "tools[0].parameters", + "mcp__codex_app__automation_update", + ) + requestErr, ok := err.(*responsesRequestError) + if !ok || !strings.Contains(requestErr.Message, "mcp__codex_app__automation_update") { + t.Fatalf("error=%#v", err) + } +} + +func TestNormalizeResponsesRequestIllegalFunctionRootNamesTool(t *testing.T) { + _, _, err := normalizeResponsesRequest([]byte(`{ + "model":"public", + "input":"hello", + "tools":[{"type":"function","name":"mcp__codex_app__automation_update","parameters":{"type":"string"}}] + }`), "grok-4.5") + requestErr, ok := err.(*responsesRequestError) + if !ok || requestErr.Param != "tools[0].parameters" || !strings.Contains(requestErr.Message, "mcp__codex_app__automation_update") { + t.Fatalf("error=%#v", err) + } +} + func TestNormalizeBuildFunctionParametersRootRejectsRootCycle(t *testing.T) { schema := map[string]any{ "$defs": map[string]any{ diff --git a/backend/internal/infra/provider/cli/responses_tool_declarations.go b/backend/internal/infra/provider/cli/responses_tool_declarations.go index 42986d85..0307b8ea 100644 --- a/backend/internal/infra/provider/cli/responses_tool_declarations.go +++ b/backend/internal/infra/provider/cli/responses_tool_declarations.go @@ -3,6 +3,7 @@ package cli import ( "encoding/json" "fmt" + "reflect" "strings" ) @@ -172,7 +173,7 @@ func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, cl } converted := cloneJSONObject(tool) if parameters, exists := converted["parameters"]; exists { - normalized, changed, normalizeErr := normalizeBuildFunctionParametersRoot(parameters, param+".parameters") + normalized, changed, normalizeErr := normalizeBuildFunctionParametersRootForTool(parameters, param+".parameters", name) if normalizeErr != nil { return nil, normalizeErr } @@ -276,141 +277,245 @@ func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, cl const maxRootUnionDepth = 32 const maxRootUnionLeaves = 32 +type buildFunctionParametersRootContext struct { + param string + toolName string +} + +type rootObjectLeafCollector struct { + doc map[string]any + context buildFunctionParametersRootContext + leaves []map[string]any + rootUnionKeyword string + requiresDisjoint bool + changed bool +} + // NormalizeBuildFunctionParametersRoot rewrites a function parameters schema so -// Grok Build can compile it: the root is an object, or a oneOf of object +// Grok Build can compile it: the root is an object, or a root union of object // leaves. Nested oneOf/anyOf at the root are lifted; $ref inside properties // and recursive property $ref are left alone. -func NormalizeBuildFunctionParametersRoot(value any, param string) (any, bool, error) { - return normalizeBuildFunctionParametersRoot(value, param) +func NormalizeBuildFunctionParametersRoot(value any, param, toolName string) (any, bool, error) { + return normalizeBuildFunctionParametersRootForTool(value, param, toolName) } // normalizeBuildFunctionParametersRoot removes root-level nullability from function schemas // and lifts nested root unions. Nested nullable fields remain untouched. func normalizeBuildFunctionParametersRoot(value any, param string) (any, bool, error) { + return normalizeBuildFunctionParametersRootForTool(value, param, "") +} + +func normalizeBuildFunctionParametersRootForTool(value any, param, toolName string) (any, bool, error) { schema, ok := value.(map[string]any) if !ok { - return value, false, nil + return nil, false, invalidBuildFunctionParametersRoot(buildFunctionParametersRootContext{param: param, toolName: toolName}) } - normalized := cloneJSONObject(schema) - changed := false - - if rawTypes, ok := normalized["type"].([]any); ok { - filtered, removedNull := withoutNullSchemaTypes(rawTypes) - if removedNull { - changed = true - switch len(filtered) { - case 0: - return nil, false, invalidBuildFunctionParametersRoot(param) - case 1: - if filtered[0] != "object" { - return nil, false, invalidBuildFunctionParametersRoot(param) - } - normalized["type"] = "object" - default: - return nil, false, invalidBuildFunctionParametersRoot(param) - } - } - } - - if !rootHasUnion(normalized) { - return normalized, changed, nil - } - leaves, err := collectRootObjectLeaves(normalized, param) - if err != nil { + doc := cloneJSONObject(schema) + context := buildFunctionParametersRootContext{param: param, toolName: toolName} + collector := rootObjectLeafCollector{doc: doc, context: context} + if err := collector.walk(doc, nil, nil, 0, 0); err != nil { return nil, false, err } - if len(leaves) == 0 { - return nil, false, invalidBuildFunctionParametersRoot(param) + if len(collector.leaves) == 0 { + return nil, false, invalidBuildFunctionParametersRoot(context) + } + if collector.requiresDisjoint && !rootObjectLeavesPairwiseDisjoint(collector.leaves, doc) { + return nil, false, invalidBuildFunctionParametersRoot(context) + } + if !collector.changed { + return doc, false, nil } var out map[string]any - if len(leaves) == 1 { - out = leaves[0] + if len(collector.leaves) == 1 { + out = collector.leaves[0] } else { - branches := make([]any, len(leaves)) - for i, leaf := range leaves { + if collector.rootUnionKeyword == "" { + return nil, false, invalidBuildFunctionParametersRoot(context) + } + branches := make([]any, len(collector.leaves)) + for i, leaf := range collector.leaves { branches[i] = leaf } - out = map[string]any{"oneOf": branches} + out = map[string]any{collector.rootUnionKeyword: branches} } - if defs := referencedDefs(out, normalized); len(defs) > 0 { + delete(out, "$defs") + if defs := referencedDefs(out, doc); len(defs) > 0 { out["$defs"] = defs } - return out, true, nil + return out, !reflect.DeepEqual(out, schema), nil } -func rootHasUnion(schema map[string]any) bool { - for _, keyword := range []string{"anyOf", "oneOf"} { - if _, ok := schema[keyword].([]any); ok { - return true - } - } - return false -} - -func collectRootObjectLeaves(doc map[string]any, param string) ([]map[string]any, error) { - var leaves []map[string]any - if err := walkRootUnion(doc, doc, param, nil, 0, &leaves); err != nil { - return nil, err - } - return leaves, nil -} - -func walkRootUnion(node any, doc map[string]any, param string, seen map[string]struct{}, depth int, leaves *[]map[string]any) error { - if depth > maxRootUnionDepth || len(*leaves) > maxRootUnionLeaves { - return invalidBuildFunctionParametersRoot(param) +func (c *rootObjectLeafCollector) walk(node any, constraints []map[string]any, seen map[string]struct{}, depth, unionDepth int) error { + if depth > maxRootUnionDepth || len(c.leaves) > maxRootUnionLeaves { + return invalidBuildFunctionParametersRoot(c.context) } schema, ok := node.(map[string]any) if !ok { - return invalidBuildFunctionParametersRoot(param) + return invalidBuildFunctionParametersRoot(c.context) } - if ref, ok := schema["$ref"].(string); ok && !hasUnionKeys(schema) && schema["type"] == nil && schema["properties"] == nil { + if ref, ok := schema["$ref"].(string); ok { if !strings.HasPrefix(ref, "#/") { - return invalidBuildFunctionParametersRoot(param) + return invalidBuildFunctionParametersRoot(c.context) } if _, loop := seen[ref]; loop { - return invalidBuildFunctionParametersRoot(param) + return invalidBuildFunctionParametersRoot(c.context) } - resolved, ok := resolveLocalSchemaRef(doc, ref) + resolved, ok := resolveLocalSchemaRef(c.doc, ref) if !ok { - return invalidBuildFunctionParametersRoot(param) + return invalidBuildFunctionParametersRoot(c.context) + } + sibling, siblingErr := rootSchemaSiblingConstraint(schema, "$ref") + if siblingErr != nil { + return invalidBuildFunctionParametersRoot(c.context) + } + if len(sibling) > 0 { + constraints = append(cloneRootConstraints(constraints), sibling) } next := cloneRefSeen(seen) next[ref] = struct{}{} - return walkRootUnion(resolved, doc, param, next, depth+1, leaves) + c.changed = true + return c.walk(resolved, constraints, next, depth+1, unionDepth) } - if isNullOnlySchema(schema) { + normalized, nullOnly, typeChanged := normalizeRootObjectType(schema) + if nullOnly { + c.changed = true return nil } - if hasUnionKeys(schema) { - for _, keyword := range []string{"anyOf", "oneOf"} { - raw, ok := schema[keyword].([]any) - if !ok { - continue + if typeChanged { + c.changed = true + } + keyword, branches, unionErr := rootUnion(normalized) + if unionErr != nil { + return invalidBuildFunctionParametersRoot(c.context) + } + if keyword != "" { + if c.rootUnionKeyword == "" { + c.rootUnionKeyword = keyword + } else { + c.changed = true + if c.rootUnionKeyword == "oneOf" || keyword != c.rootUnionKeyword { + c.requiresDisjoint = true } - for _, branch := range raw { - if err := walkRootUnion(branch, doc, param, cloneRefSeen(seen), depth+1, leaves); err != nil { - return err - } + } + sibling, siblingErr := rootSchemaSiblingConstraint(normalized, keyword) + if siblingErr != nil { + return invalidBuildFunctionParametersRoot(c.context) + } + if len(sibling) > 0 { + constraints = append(cloneRootConstraints(constraints), sibling) + } + for _, branch := range branches { + if err := c.walk(branch, constraints, cloneRefSeen(seen), depth+1, unionDepth+1); err != nil { + return err } } return nil } - if !isObjectRootSchema(schema, doc, nil) { - return invalidBuildFunctionParametersRoot(param) + if unionDepth == 0 && c.rootUnionKeyword != "" { + return invalidBuildFunctionParametersRoot(c.context) } - leaf := cloneJSONObject(schema) - leaf["type"] = "object" - *leaves = append(*leaves, leaf) - if len(*leaves) > maxRootUnionLeaves { - return invalidBuildFunctionParametersRoot(param) + if !isObjectRootSchema(normalized, c.doc, nil) { + return invalidBuildFunctionParametersRoot(c.context) + } + leaf := cloneJSONObject(normalized) + if leaf["type"] != "object" { + leaf["type"] = "object" + c.changed = true + } + delete(leaf, "$defs") + leaf = applyRootConstraints(leaf, constraints) + c.leaves = append(c.leaves, leaf) + if len(c.leaves) > maxRootUnionLeaves { + return invalidBuildFunctionParametersRoot(c.context) } return nil } -func hasUnionKeys(schema map[string]any) bool { - _, anyOf := schema["anyOf"] - _, oneOf := schema["oneOf"] - return anyOf || oneOf +func rootUnion(schema map[string]any) (string, []any, error) { + var keyword string + var branches []any + for _, candidate := range []string{"anyOf", "oneOf"} { + raw, exists := schema[candidate] + if !exists { + continue + } + if keyword != "" { + return "", nil, fmt.Errorf("multiple root unions") + } + parsed, ok := raw.([]any) + if !ok || len(parsed) == 0 { + return "", nil, fmt.Errorf("invalid root union") + } + keyword, branches = candidate, parsed + } + return keyword, branches, nil +} + +func normalizeRootObjectType(schema map[string]any) (map[string]any, bool, bool) { + out := cloneJSONObject(schema) + rawTypes, isArray := out["type"].([]any) + if !isArray { + return out, out["type"] == "null", false + } + filtered, removedNull := withoutNullSchemaTypes(rawTypes) + if len(filtered) == 0 { + return out, true, removedNull + } + for _, value := range filtered { + if value != "object" { + return out, false, false + } + } + out["type"] = "object" + return out, false, true +} + +func rootSchemaSiblingConstraint(schema map[string]any, excluded string) (map[string]any, error) { + constraint := make(map[string]any) + for key, value := range schema { + switch key { + case excluded, "$defs": + continue + case "anyOf", "oneOf": + return nil, fmt.Errorf("multiple root expressions") + case "type": + if value == "object" { + continue + } + case "properties": + if properties, ok := value.(map[string]any); ok && len(properties) == 0 { + continue + } + case "required": + if required, ok := value.([]any); ok && len(required) == 0 { + continue + } + case "additionalProperties": + if allowed, ok := value.(bool); ok && allowed { + continue + } + } + constraint[key] = cloneJSONValue(value) + } + return constraint, nil +} + +func cloneRootConstraints(constraints []map[string]any) []map[string]any { + return append([]map[string]any(nil), constraints...) +} + +func applyRootConstraints(leaf map[string]any, constraints []map[string]any) map[string]any { + if len(constraints) == 0 { + return leaf + } + allOf := make([]any, 0, len(constraints)+1) + for _, constraint := range constraints { + if len(constraint) > 0 { + allOf = append(allOf, cloneJSONObject(constraint)) + } + } + allOf = append(allOf, leaf) + return map[string]any{"type": "object", "allOf": allOf} } func cloneRefSeen(seen map[string]struct{}) map[string]struct{} { @@ -421,6 +526,150 @@ func cloneRefSeen(seen map[string]struct{}) map[string]struct{} { return out } +func rootObjectLeavesPairwiseDisjoint(leaves []map[string]any, doc map[string]any) bool { + for i := 0; i < len(leaves); i++ { + for j := i + 1; j < len(leaves); j++ { + if !rootObjectSchemasDisjoint(leaves[i], leaves[j], doc) { + return false + } + } + } + return true +} + +type rootObjectSchemaFacts struct { + required map[string]struct{} + values map[string]map[string]struct{} +} + +func rootObjectSchemasDisjoint(left, right map[string]any, doc map[string]any) bool { + leftFacts := collectRootObjectSchemaFacts(left, doc, nil) + rightFacts := collectRootObjectSchemaFacts(right, doc, nil) + for property := range leftFacts.required { + if _, required := rightFacts.required[property]; !required { + continue + } + leftValues, leftKnown := leftFacts.values[property] + rightValues, rightKnown := rightFacts.values[property] + if leftKnown && rightKnown && finiteValueSetsDisjoint(leftValues, rightValues) { + return true + } + } + return false +} + +func collectRootObjectSchemaFacts(schema map[string]any, doc map[string]any, seen map[string]struct{}) rootObjectSchemaFacts { + facts := rootObjectSchemaFacts{required: map[string]struct{}{}, values: map[string]map[string]struct{}{}} + collectRootObjectSchemaFactsInto(schema, doc, seen, &facts) + return facts +} + +func collectRootObjectSchemaFactsInto(schema map[string]any, doc map[string]any, seen map[string]struct{}, facts *rootObjectSchemaFacts) { + if ref, ok := schema["$ref"].(string); ok { + if _, loop := seen[ref]; !loop { + if resolved, resolvedOK := resolveLocalSchemaRef(doc, ref); resolvedOK { + next := cloneRefSeen(seen) + next[ref] = struct{}{} + collectRootObjectSchemaFactsInto(resolved, doc, next, facts) + } + } + } + if required, ok := schema["required"].([]any); ok { + for _, raw := range required { + if property, ok := raw.(string); ok { + facts.required[property] = struct{}{} + } + } + } + if properties, ok := schema["properties"].(map[string]any); ok { + for property, raw := range properties { + propertySchema, ok := raw.(map[string]any) + if !ok { + continue + } + values, known := finiteSchemaValues(propertySchema, doc, nil) + if !known { + continue + } + if existing, exists := facts.values[property]; exists { + facts.values[property] = intersectFiniteValueSets(existing, values) + } else { + facts.values[property] = values + } + } + } + if allOf, ok := schema["allOf"].([]any); ok { + for _, raw := range allOf { + if part, ok := raw.(map[string]any); ok { + collectRootObjectSchemaFactsInto(part, doc, cloneRefSeen(seen), facts) + } + } + } +} + +func finiteSchemaValues(schema map[string]any, doc map[string]any, seen map[string]struct{}) (map[string]struct{}, bool) { + if ref, ok := schema["$ref"].(string); ok { + if _, loop := seen[ref]; loop { + return nil, false + } + resolved, resolvedOK := resolveLocalSchemaRef(doc, ref) + if !resolvedOK { + return nil, false + } + next := cloneRefSeen(seen) + next[ref] = struct{}{} + return finiteSchemaValues(resolved, doc, next) + } + if value, exists := schema["const"]; exists { + key, ok := finiteSchemaValueKey(value) + if !ok { + return nil, false + } + return map[string]struct{}{key: {}}, true + } + if values, ok := schema["enum"].([]any); ok { + result := make(map[string]struct{}, len(values)) + for _, value := range values { + key, valid := finiteSchemaValueKey(value) + if !valid { + return nil, false + } + result[key] = struct{}{} + } + return result, true + } + return nil, false +} + +func finiteSchemaValueKey(value any) (string, bool) { + switch value.(type) { + case nil, bool, float64, string: + raw, err := json.Marshal(value) + return string(raw), err == nil + default: + return "", false + } +} + +func finiteValueSetsDisjoint(left, right map[string]struct{}) bool { + for value := range left { + if _, exists := right[value]; exists { + return false + } + } + return true +} + +func intersectFiniteValueSets(left, right map[string]struct{}) map[string]struct{} { + intersection := make(map[string]struct{}) + for value := range left { + if _, exists := right[value]; exists { + intersection[value] = struct{}{} + } + } + return intersection +} + func referencedDefs(node any, doc map[string]any) map[string]any { rawDefs, _ := doc["$defs"].(map[string]any) if len(rawDefs) == 0 { @@ -458,7 +707,9 @@ func collectDefRefs(node any, needed map[string]struct{}) { switch typed := node.(type) { case map[string]any: if ref, ok := typed["$ref"].(string); ok && strings.HasPrefix(ref, "#/$defs/") { - needed[strings.TrimPrefix(ref, "#/$defs/")] = struct{}{} + if name, nameOK := rootDefinitionName(ref); nameOK { + needed[name] = struct{}{} + } } for _, value := range typed { collectDefRefs(value, needed) @@ -470,6 +721,15 @@ func collectDefRefs(node any, needed map[string]struct{}) { } } +func rootDefinitionName(ref string) (string, bool) { + tail := strings.TrimPrefix(ref, "#/$defs/") + if tail == ref || tail == "" { + return "", false + } + encoded := strings.SplitN(tail, "/", 2)[0] + return strings.ReplaceAll(strings.ReplaceAll(encoded, "~1", "/"), "~0", "~"), true +} + func withoutNullSchemaTypes(types []any) ([]any, bool) { filtered := make([]any, 0, len(types)) removed := false @@ -563,10 +823,14 @@ func resolveLocalSchemaRef(root map[string]any, ref string) (map[string]any, boo return resolved, ok } -func invalidBuildFunctionParametersRoot(param string) error { +func invalidBuildFunctionParametersRoot(context buildFunctionParametersRootContext) error { + message := context.param + " 顶层必须是非 nullable 的 object schema" + if context.toolName != "" { + message = fmt.Sprintf("工具 %s 的 %s 顶层必须是非 nullable 的 object schema", context.toolName, context.param) + } return &responsesRequestError{ - Message: param + " 顶层必须是非 nullable 的 object schema", - Param: param, + Message: message, + Param: context.param, Code: "invalid_parameter", } } diff --git a/backend/internal/infra/provider/cli/responses_tools_test.go b/backend/internal/infra/provider/cli/responses_tools_test.go index 93070718..4c01afd7 100644 --- a/backend/internal/infra/provider/cli/responses_tools_test.go +++ b/backend/internal/infra/provider/cli/responses_tools_test.go @@ -381,6 +381,15 @@ func TestNormalizeBuildFunctionParametersRootVariants(t *testing.T) { } }, }, + { + name: "single object type array", + schema: map[string]any{"type": []any{"object"}, "properties": map[string]any{}}, + check: func(t *testing.T, normalized map[string]any, changed bool) { + if !changed || normalized["type"] != "object" { + t.Fatalf("normalized=%#v changed=%v", normalized, changed) + } + }, + }, { name: "oneOf", schema: map[string]any{"oneOf": []any{ diff --git a/backend/internal/infra/provider/console/console_test.go b/backend/internal/infra/provider/console/console_test.go index 22537aa8..cb2a48ce 100644 --- a/backend/internal/infra/provider/console/console_test.go +++ b/backend/internal/infra/provider/console/console_test.go @@ -374,6 +374,21 @@ func TestNormalizeRequestLiftsFunctionParameterUnion(t *testing.T) { } } +func TestNormalizeRequestIllegalFunctionRootNamesTool(t *testing.T) { + spec, ok := Resolve("grok-4.3") + if !ok { + t.Fatal("grok-4.3 missing") + } + _, err := normalizeRequest([]byte(`{ + "model":"grok-4.3", + "input":"hello", + "tools":[{"type":"function","name":"automation_update","parameters":{"type":"string"}}] + }`), spec) + if err == nil || !strings.Contains(err.Error(), "automation_update") { + t.Fatalf("error=%v", err) + } +} + func TestNormalizeRequestForwardsXSearchTimeRangeAndImageSearch(t *testing.T) { spec, ok := Resolve("grok-4.3") if !ok { diff --git a/backend/internal/infra/provider/console/normalize.go b/backend/internal/infra/provider/console/normalize.go index b62564c5..aa31dd59 100644 --- a/backend/internal/infra/provider/console/normalize.go +++ b/backend/internal/infra/provider/console/normalize.go @@ -320,7 +320,7 @@ func normalizeConsoleTools(payload map[string]any) (bool, error) { for _, field := range []string{"description", "parameters", "strict"} { if fieldValue, exists := tool[field]; exists { if field == "parameters" { - normalized, _, err := cli.NormalizeBuildFunctionParametersRoot(fieldValue, "tools.parameters") + normalized, _, err := cli.NormalizeBuildFunctionParametersRoot(fieldValue, "tools.parameters", strings.TrimSpace(name)) if err != nil { return false, err } diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index 21967c5e..9515b896 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -1297,14 +1297,18 @@ func (h *Handler) writeProtocolResult(c *gin.Context, result *gateway.Result, st if stream && !isEventStreamContentType(result.Header.Get("Content-Type")) { raw, readErr := io.ReadAll(io.LimitReader(result.Body, maxJSONResponseTransferBytes+1)) if readErr != nil { - writeOpenAIError(c, http.StatusBadGateway, "upstream_error", "读取上游错误响应失败") + if anthropic { + writeAnthropicError(c, http.StatusBadGateway, "api_error", "读取上游错误响应失败", "upstream_error") + } else { + writeOpenAIError(c, http.StatusBadGateway, "upstream_error", "读取上游错误响应失败") + } return } c.Writer.Header().Del("Content-Length") code, message := gateway.ClassifyUpstreamHTTPError(result.StatusCode, raw) errorCode = code if anthropic { - writeAnthropicError(c, result.StatusCode, "invalid_request_error", message, errorCode) + writeAnthropicError(c, result.StatusCode, anthropicUpstreamHTTPErrorType(result.StatusCode), message, errorCode) } else { writeOpenAIError(c, result.StatusCode, errorCode, message) } @@ -1328,6 +1332,21 @@ func (h *Handler) writeProtocolResult(c *gin.Context, result *gateway.Result, st } } +func anthropicUpstreamHTTPErrorType(status int) string { + switch status { + case http.StatusBadRequest, http.StatusConflict, http.StatusUnprocessableEntity: + return "invalid_request_error" + case http.StatusNotFound: + return "not_found_error" + case http.StatusTooManyRequests: + return "rate_limit_error" + case http.StatusRequestTimeout, http.StatusGatewayTimeout: + return "timeout_error" + default: + return "api_error" + } +} + func classifyCopyError(ctx context.Context, err error) string { if err == nil { return "" diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go index 580184f7..81998435 100644 --- a/backend/internal/transport/http/inference/handler_test.go +++ b/backend/internal/transport/http/inference/handler_test.go @@ -1637,6 +1637,66 @@ func TestWriteProtocolResultMapsJSONInvalidArgumentWithoutCopyStream(t *testing. } } +func TestWriteProtocolResultAnthropicJSONReadFailureKeepsAnthropicShape(t *testing.T) { + gin.SetMode(gin.TestMode) + handler := NewHandler(nil, nil, 1<<20) + var finalCode string + result := &gateway.Result{ + StatusCode: http.StatusBadRequest, + Status: "400 Bad Request", + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(&chunkErrorReader{data: []byte(`{"error":"partial"}`)}), + Finalize: func(_ gateway.Usage, _, code string) { + finalCode = code + }, + } + router := gin.New() + router.GET("/", func(c *gin.Context) { + handler.writeAnthropicResult(c, result, true) + }) + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) + + var payload struct { + Type string `json:"type"` + Error struct { + Type string `json:"type"` + Code string `json:"code"` + } `json:"error"` + } + if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil { + t.Fatal(err) + } + if recorder.Code != http.StatusBadGateway || payload.Type != "error" || payload.Error.Type != "api_error" || payload.Error.Code != "upstream_error" || finalCode != "upstream_error" { + t.Fatalf("status=%d payload=%#v final=%q body=%s", recorder.Code, payload, finalCode, recorder.Body.String()) + } +} + +func TestWriteProtocolResultDoesNotRemapOtherJSON4xxAsServerError(t *testing.T) { + gin.SetMode(gin.TestMode) + handler := NewHandler(nil, nil, 1<<20) + body := `{"error":{"code":"not_found","message":"requested response is missing"}}` + var finalCode string + result := &gateway.Result{ + StatusCode: http.StatusNotFound, + Status: "404 Not Found", + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(body)), + Finalize: func(_ gateway.Usage, _, code string) { + finalCode = code + }, + } + router := gin.New() + router.GET("/", func(c *gin.Context) { + handler.writeResponsesResult(c, result, true, "") + }) + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) + if recorder.Code != http.StatusNotFound || finalCode != "upstream_error" || !strings.Contains(recorder.Body.String(), "requested response is missing") { + t.Fatalf("status=%d final=%q body=%s", recorder.Code, finalCode, recorder.Body.String()) + } +} + func TestProjectStreamFailureDiagnosticBoundsErrorMessage(t *testing.T) { diagnostic := projectStreamFailureDiagnostic([]byte(`{"type":"error","error":{"code":"server_error","message":"` + strings.Repeat("错误", maxStreamFailureDiagnosticBytes) + `"},"output":"must-not-be-audited"}`)) if !diagnostic.BodyTruncated || len(diagnostic.Body) > maxStreamFailureDiagnosticBytes || len(diagnostic.Body) == 0 || !utf8.Valid(diagnostic.Body) || strings.Contains(string(diagnostic.Body), "must-not-be-audited") { From 44807b28ac4a09b0586431904bc060396e8ba7f7 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Mon, 31 Aug 2026 23:48:02 +0800 Subject: [PATCH 3/3] fix: avoid allocation size overflow in schema normalization --- .../infra/provider/cli/responses_tool_declarations.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/internal/infra/provider/cli/responses_tool_declarations.go b/backend/internal/infra/provider/cli/responses_tool_declarations.go index 0307b8ea..0b46d784 100644 --- a/backend/internal/infra/provider/cli/responses_tool_declarations.go +++ b/backend/internal/infra/provider/cli/responses_tool_declarations.go @@ -508,7 +508,7 @@ func applyRootConstraints(leaf map[string]any, constraints []map[string]any) map if len(constraints) == 0 { return leaf } - allOf := make([]any, 0, len(constraints)+1) + allOf := make([]any, 0, len(constraints)) for _, constraint := range constraints { if len(constraint) > 0 { allOf = append(allOf, cloneJSONObject(constraint)) @@ -519,7 +519,7 @@ func applyRootConstraints(leaf map[string]any, constraints []map[string]any) map } func cloneRefSeen(seen map[string]struct{}) map[string]struct{} { - out := make(map[string]struct{}, len(seen)+1) + out := make(map[string]struct{}, len(seen)) for key, value := range seen { out[key] = value }