diff --git a/backend/internal/service/image_generation_intent.go b/backend/internal/service/image_generation_intent.go index 927fd08765..47f59a3ec6 100644 --- a/backend/internal/service/image_generation_intent.go +++ b/backend/internal/service/image_generation_intent.go @@ -1,6 +1,7 @@ package service import ( + "bytes" "strings" "github.com/tidwall/gjson" @@ -36,21 +37,93 @@ func GroupAllowsImageGeneration(group *Group) bool { return group == nil || group.AllowImageGeneration } -// IsImageGenerationIntent classifies requests that can produce generated images. -func IsImageGenerationIntent(endpoint string, requestedModel string, body []byte) bool { - if IsImageGenerationEndpoint(endpoint) { - return true - } - if isOpenAIImageGenerationModel(requestedModel) { - return true - } - if len(body) == 0 || !gjson.ValidBytes(body) { +var ( + // imageGenLiteralBytes 覆盖扫描侧的全部非模型分支:tool type image_generation + // 自带该前缀,namespace / tool_choice / 函数引用的名字都是 image_gen。 + imageGenLiteralBytes = []byte("image_gen") + // imageModelFoldBytes 覆盖 model 分支:gpt-image-* 与 grok-imagine* 都含 imag, + // 模型名按 ToLower 比较,这里做 ASCII 折叠匹配。 + imageModelFoldBytes = []byte("imag") +) + +// openAIBodyMayDeclareImageGeneration 是生图意图扫描的字节级必要条件。 +// +// 扫描侧每个能让意图成立的取值都要求 body 里出现 image_gen 字面量,或 model 值本身 +// 是图片模型;因此不满足本判定的 body 一定不会命中扫描,可以整段跳过 +// gjson.ValidBytes 全量校验与根对象遍历(大 body 上这两步各占数百微秒)。 +// 只做字节级预检查,宁多算不漏判:含 \u 转义时交给完整扫描兜底,因为 JSON 字符串 +// 允许把 image_gen 的任意字节写成 unicode 转义。 +// +// 唯一的理论缺口:模型名比较走 strings.ToLower(Unicode 简易映射),把非 ASCII +// 字母折叠成 ASCII 的拼写(如 İ→i)不在字节折叠覆盖内;这类拼写不是真实模型 id, +// 且以 \u 形式出现时仍由上面的转义兜底放行。 +func openAIBodyMayDeclareImageGeneration(body []byte) bool { + if len(body) == 0 { return false } + if bytes.Contains(body, imageGenLiteralBytes) { + return true + } + if containsASCIIFold(body, imageModelFoldBytes) { + return true + } + return bytes.Contains(body, jsonUnicodeEscapeBytes) +} +// IsImageGenerationIntent classifies requests that can produce generated images. +func IsImageGenerationIntent(endpoint string, requestedModel string, body []byte) bool { + return openAIImageGenerationIntent(endpoint, requestedModel, body, false) +} + +// IsExplicitImageGenerationIntent 仅检测原生 image_generation 工具、图片模型和显式 tool_choice, +// 不检测被动的 image_gen namespace 声明。用于 capability 路由决策——被动 namespace 不应 +// 强制要求原生 Responses 能力,否则 Chat Completions-only 账号会被误过滤(#4476)。 +func IsExplicitImageGenerationIntent(endpoint string, requestedModel string, body []byte) bool { + return openAIImageGenerationIntent(endpoint, requestedModel, body, true) +} + +// IsImageGenerationIntentForPlatform applies platform-specific intent rules. +// +// Codex advertises the image_gen namespace on ordinary Responses requests so +// that it is available if the model needs it. Grok strips namespace and +// Responses Lite additional_tools declarations before forwarding, so those +// declarations alone must not turn every Codex request into an image request. +// Native image_generation tools, explicit image selection and image models +// remain image intent. Other platforms retain the original declaration rule. +func IsImageGenerationIntentForPlatform(endpoint string, requestedModel string, body []byte, platform string) bool { + if !strings.EqualFold(strings.TrimSpace(platform), PlatformGrok) { + return openAIImageGenerationIntent(endpoint, requestedModel, body, false) + } + // Grok removes namespace catalogs before forwarding. Native image_generation + // remains an explicit capability request. + return openAIImageGenerationIntent(endpoint, requestedModel, body, true) +} + +// openAIImageGenerationIntent 统一入口:先做 O(1) 端点/模型判断,再用字节级预检查 +// 挡住不可能命中扫描的 body,最后才校验并遍历根对象。 +func openAIImageGenerationIntent(endpoint string, requestedModel string, body []byte, explicit bool) bool { + if IsImageGenerationEndpoint(endpoint) || isOpenAIImageGenerationModel(requestedModel) { + return true + } + if !openAIBodyMayDeclareImageGeneration(body) { + return false + } + if !gjson.ValidBytes(body) { + return false + } + root := parseRawJSONView(body) + if explicit { + return explicitImageGenerationDeclarationsFromRoot(root) + } + return imageGenerationDeclarationsFromRoot(root) +} + +// imageGenerationDeclarationsFromRoot 走一遍根对象,保留「重复键取第一个」语义, +// 覆盖 model、tools、input.additional_tools 与 tool_choice。调用方负责 JSON 合法性。 +func imageGenerationDeclarationsFromRoot(root gjson.Result) bool { var modelSeen, toolsSeen, inputSeen, toolChoiceSeen bool imageIntent := false - parseRawJSONView(body).ForEach(func(key, value gjson.Result) bool { + root.ForEach(func(key, value gjson.Result) bool { // GetBytes returns the first duplicate key; retain that behavior while walking the root once. switch key.Str { case "model": @@ -79,19 +152,12 @@ func IsImageGenerationIntent(endpoint string, requestedModel string, body []byte return imageIntent } -// IsExplicitImageGenerationIntent 仅检测原生 image_generation 工具、图片模型和显式 tool_choice, -// 不检测被动的 image_gen namespace 声明。用于 capability 路由决策——被动 namespace 不应 -// 强制要求原生 Responses 能力,否则 Chat Completions-only 账号会被误过滤(#4476)。 -func IsExplicitImageGenerationIntent(endpoint string, requestedModel string, body []byte) bool { - if IsImageGenerationEndpoint(endpoint) || isOpenAIImageGenerationModel(requestedModel) { - return true - } - if len(body) == 0 || !gjson.ValidBytes(body) { - return false - } +// explicitImageGenerationDeclarationsFromRoot 只认原生 image_generation 工具、图片模型 +// 与显式 tool_choice,不认被动的 image_gen namespace 声明。 +func explicitImageGenerationDeclarationsFromRoot(root gjson.Result) bool { var modelSeen, toolsSeen, toolChoiceSeen bool imageIntent := false - parseRawJSONView(body).ForEach(func(key, value gjson.Result) bool { + root.ForEach(func(key, value gjson.Result) bool { switch key.Str { case "model": if !modelSeen { @@ -114,56 +180,6 @@ func IsExplicitImageGenerationIntent(endpoint string, requestedModel string, bod return imageIntent } -// IsImageGenerationIntentForPlatform applies platform-specific intent rules. -// -// Codex advertises the image_gen namespace on ordinary Responses requests so -// that it is available if the model needs it. Grok strips namespace and -// Responses Lite additional_tools declarations before forwarding, so those -// declarations alone must not turn every Codex request into an image request. -// Native image_generation tools, explicit image selection and image models -// remain image intent. Other platforms retain the original declaration rule. -func IsImageGenerationIntentForPlatform(endpoint string, requestedModel string, body []byte, platform string) bool { - if !strings.EqualFold(strings.TrimSpace(platform), PlatformGrok) { - return IsImageGenerationIntent(endpoint, requestedModel, body) - } - return isExplicitGrokImageGenerationIntent(endpoint, requestedModel, body) -} - -func isExplicitGrokImageGenerationIntent(endpoint string, requestedModel string, body []byte) bool { - if IsImageGenerationEndpoint(endpoint) || isOpenAIImageGenerationModel(requestedModel) { - return true - } - if len(body) == 0 || !gjson.ValidBytes(body) { - return false - } - - var modelSeen, toolsSeen, toolChoiceSeen bool - imageIntent := false - parseRawJSONView(body).ForEach(func(key, value gjson.Result) bool { - switch key.Str { - case "model": - if !modelSeen { - modelSeen = true - imageIntent = isOpenAIImageGenerationModel(strings.TrimSpace(value.String())) - } - case "tools": - if !toolsSeen { - toolsSeen = true - // Grok removes namespace catalogs before forwarding. Native - // image_generation remains an explicit capability request. - imageIntent = openAIJSONToolsContainNativeImageGeneration(value) - } - case "tool_choice": - if !toolChoiceSeen { - toolChoiceSeen = true - imageIntent = openAIJSONToolChoiceSelectsExplicitImageGeneration(value) - } - } - return !imageIntent && (!modelSeen || !toolsSeen || !toolChoiceSeen) - }) - return imageIntent -} - // IsImageGenerationIntentMap is the map-backed variant used after service-side request mutation. func IsImageGenerationIntentMap(endpoint string, requestedModel string, reqBody map[string]any) bool { if IsImageGenerationEndpoint(endpoint) { diff --git a/backend/internal/service/image_generation_intent_prefilter_benchmark_test.go b/backend/internal/service/image_generation_intent_prefilter_benchmark_test.go new file mode 100644 index 0000000000..8658bda1b0 --- /dev/null +++ b/backend/internal/service/image_generation_intent_prefilter_benchmark_test.go @@ -0,0 +1,92 @@ +package service + +import ( + "strings" + "testing" +) + +// buildImageIntentPrefilterBenchmarkBody 生成形状接近 Codex 客户端的大请求体: +// tools 在 input 之前、input 内含大量 items;withImageGen 控制是否带上 Codex +// 默认注入的 image_gen namespace 声明。 +func buildImageIntentPrefilterBenchmarkBody(targetBytes int, withImageGen bool) []byte { + var builder strings.Builder + builder.Grow(targetBytes + 512) + _, _ = builder.WriteString(`{"model":"gpt-5.5","instructions":"`) + _, _ = builder.WriteString(strings.Repeat("z", targetBytes/8)) + _, _ = builder.WriteString(`","tools":[{"type":"function","name":"shell","description":"`) + _, _ = builder.WriteString(strings.Repeat("y", targetBytes/16)) + _, _ = builder.WriteString(`"}`) + if withImageGen { + _, _ = builder.WriteString(`,{"type":"namespace","name":"image_gen"}`) + } + _, _ = builder.WriteString(`],"input":[`) + item := `{"type":"message","role":"user","content":[{"type":"input_text","text":"` + strings.Repeat("x", 4000) + `"}]}` + for i := 0; builder.Len() < targetBytes; i++ { + if i > 0 { + _, _ = builder.WriteString(`,`) + } + _, _ = builder.WriteString(item) + } + _, _ = builder.WriteString(`]}`) + return []byte(builder.String()) +} + +// 字节级预检查把「没有生图声明」的请求整段跳过校验与根对象遍历; +// scan_without_prefilter 是修复前的等价路径,两者同一次运行即可对比。 +func BenchmarkImageGenerationIntentPrefilter(b *testing.B) { + const targetBytes = 1 << 20 + plain := buildImageIntentPrefilterBenchmarkBody(targetBytes, false) + codex := buildImageIntentPrefilterBenchmarkBody(targetBytes, true) + + b.Run("prefilter_only/plain", func(b *testing.B) { + b.SetBytes(int64(len(plain))) + b.ReportAllocs() + for range b.N { + if openAIBodyMayDeclareImageGeneration(plain) { + b.Fatal("plain body must not declare image generation") + } + } + }) + + b.Run("scan_without_prefilter/plain", func(b *testing.B) { + b.SetBytes(int64(len(plain))) + b.ReportAllocs() + for range b.N { + if referenceImageGenerationIntent(plain) { + b.Fatal("plain body must not have image intent") + } + } + }) + + b.Run("intent/plain", func(b *testing.B) { + b.SetBytes(int64(len(plain))) + b.ReportAllocs() + for range b.N { + if IsImageGenerationIntent(openAIResponsesEndpoint, "gpt-5.5", plain) { + b.Fatal("plain body must not have image intent") + } + } + }) + + b.Run("scan_without_prefilter/codex", func(b *testing.B) { + b.SetBytes(int64(len(codex))) + b.ReportAllocs() + for range b.N { + if !referenceImageGenerationIntent(codex) { + b.Fatal("codex namespace body must have image intent") + } + } + }) + + // Codex 在普通请求里就带 image_gen namespace(见 IsImageGenerationIntentForPlatform + // 注释),预检查必然放行,这类流量仍需完整扫描,本项用于跟踪它的成本。 + b.Run("intent/codex_namespace", func(b *testing.B) { + b.SetBytes(int64(len(codex))) + b.ReportAllocs() + for range b.N { + if !IsImageGenerationIntent(openAIResponsesEndpoint, "gpt-5.5", codex) { + b.Fatal("codex namespace body must have image intent") + } + } + }) +} diff --git a/backend/internal/service/image_generation_intent_prefilter_test.go b/backend/internal/service/image_generation_intent_prefilter_test.go new file mode 100644 index 0000000000..beb12d259f --- /dev/null +++ b/backend/internal/service/image_generation_intent_prefilter_test.go @@ -0,0 +1,140 @@ +package service + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// 生图意图的字节级预检查只能少算、不能漏判:任何能让扫描成立的 body, +// openAIBodyMayDeclareImageGeneration 都必须放行。下面用扫描函数本身作为基准, +// 逐个语料核对「带预检查」与「不带预检查」的结果完全一致。 +func TestImageGenerationIntentPrefilterPreservesScanOutcomes(t *testing.T) { + escape := string(rune(92)) + "u005f" // _ + bodies := map[string]string{ + "no image declarations": `{"model":"gpt-5.5","input":"hello"}`, + "empty body": ``, + "invalid json": `{"tools":[{"type":"image_generation"}]`, + "native tool": `{"model":"gpt-5.5","tools":[{"type":"image_generation"}]}`, + "namespace tool": `{"model":"gpt-5.5","tools":[{"type":"namespace","name":"image_gen"}]}`, + "tool choice string": `{"model":"gpt-5.5","tool_choice":"image_generation"}`, + "tool choice namespace": `{"model":"gpt-5.5","tool_choice":{"type":"namespace","name":"image_gen"}}`, + "tool choice function": `{"model":"gpt-5.5","tool_choice":{"type":"function","function":{"name":"image_gen.imagegen"}}}`, + "input additional": `{"input":[{"type":"additional_tools","tools":[{"type":"image_generation"}]}]}`, + "escaped key": `{"tool_` + string(rune(92)) + `u0063hoice":{"type":"image_generation"}}`, + "escaped tool type": `{"tools":[{"type":"image` + escape + `generation"}]}`, + "escaped namespace": `{"tools":[{"type":"namespace","name":"image` + escape + `gen"}]}`, + "uppercase model": `{"model":"GPT-Image-2"}`, + "grok model": `{"model":"grok-imagine"}`, + "uppercase grok model": `{"model":"Grok-Imagine"}`, + "duplicate model": `{"model":"gpt-5.5","model":"gpt-image-2"}`, + "model only": `{"model":"gpt-image-2"}`, + "prose mentions image": `{"model":"gpt-5.5","input":"please imagine a cat"}`, + "namespace value": `{"tools":[{"type":"namespace","name":"image_gen","tools":[]}]}`, + } + for name, raw := range bodies { + body := []byte(raw) + t.Run(name, func(t *testing.T) { + // endpoint 与 requestedModel 都取非图片值,预检查才会真正生效。 + require.Equal(t, + referenceImageGenerationIntent(body), + IsImageGenerationIntent("/v1/responses", "gpt-5.5", body), + "declaration rule must not change with the prefilter") + require.Equal(t, + referenceExplicitImageGenerationIntent(body), + IsExplicitImageGenerationIntent("/v1/responses", "gpt-5.5", body), + "explicit rule must not change with the prefilter") + require.Equal(t, + referenceExplicitImageGenerationIntent(body), + IsImageGenerationIntentForPlatform("/v1/responses", "gpt-5.5", body, PlatformGrok), + "grok rule must not change with the prefilter") + require.Equal(t, + referenceImageGenerationIntent(body), + IsImageGenerationIntentForPlatform("/v1/responses", "gpt-5.5", body, PlatformOpenAI), + "platform rule must not change with the prefilter") + }) + } +} + +// 下面两个参考实现就是修复前的完整扫描:校验 + 根对象遍历,不带字节级预检查。 +func referenceImageGenerationIntent(body []byte) bool { + if len(body) == 0 || !gjson.ValidBytes(body) { + return false + } + return imageGenerationDeclarationsFromRoot(parseRawJSONView(body)) +} + +func referenceExplicitImageGenerationIntent(body []byte) bool { + if len(body) == 0 || !gjson.ValidBytes(body) { + return false + } + return explicitImageGenerationDeclarationsFromRoot(parseRawJSONView(body)) +} + +// 预检查的健全性:扫描能成立的 body 一定被放行。语料之外由 fuzz 继续探索。 +func TestImageGenerationIntentPrefilterIsNecessary(t *testing.T) { + seeds := []string{ + `{"model":"gpt-image-2"}`, + `{"tools":[{"type":"image_generation"}]}`, + `{"tools":[{"type":"namespace","name":"image_gen"}]}`, + `{"tool_choice":{"type":"namespace","name":"image_gen"}}`, + `{"input":[{"type":"additional_tools","tools":[{"type":"image_generation"}]}]}`, + `{"model":"grok-imagine"}`, + `{"model":"gpt-5.5","input":"nothing here"}`, + } + for _, seed := range seeds { + body := []byte(seed) + if referenceImageGenerationIntent(body) { + require.True(t, openAIBodyMayDeclareImageGeneration(body), "prefilter must not hide a detected body: %s", seed) + } + } +} + +func FuzzImageGenerationIntentPrefilter(f *testing.F) { + f.Add([]byte(`{"model":"gpt-image-2"}`)) + f.Add([]byte(`{"tools":[{"type":"namespace","name":"image_gen"}]}`)) + f.Add([]byte(`{"model":"gpt-5.5"}`)) + f.Add([]byte(`{"tools":[{"type":"image` + string(rune(92)) + `u005fgeneration"}]}`)) + f.Fuzz(func(t *testing.T, body []byte) { + if referenceImageGenerationIntent(body) && !openAIBodyMayDeclareImageGeneration(body) { + t.Fatalf("prefilter hid a detected body: %q", body) + } + if referenceExplicitImageGenerationIntent(body) && !openAIBodyMayDeclareImageGeneration(body) { + t.Fatalf("prefilter hid a detected body: %q", body) + } + }) +} + +func TestContainsASCIIFold(t *testing.T) { + cases := []struct { + name string + haystack string + needle string + want bool + }{ + {"exact", "gpt-image-2", "imag", true}, + {"upper", "GPT-IMAGE-2", "imag", true}, + {"mixed", "Gpt-ImAgE-2", "imag", true}, + {"grok", "grok-imagine", "imag", true}, + {"absent", "gpt-5.5", "imag", false}, + {"needle longer", "img", "imag", false}, + {"empty haystack", "", "imag", false}, + {"partial at end", "xxIma", "imag", false}, + {"second candidate matches", "iaaiimag", "imag", true}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + require.Equal(t, tt.want, containsASCIIFold([]byte(tt.haystack), []byte(tt.needle))) + }) + } + require.False(t, containsASCIIFold(nil, []byte("imag"))) + + // 与 strings.Contains(strings.ToLower(...)) 对拍一段混合大小写文本。 + haystack := []byte(`{"model":"Gpt-Image-2","input":"IMAGINE this, Image and IMAGE"}`) + require.True(t, containsASCIIFold(haystack, []byte("imag"))) + require.Equal(t, + strings.Contains(strings.ToLower(string(haystack)), "imag"), + containsASCIIFold(haystack, []byte("imag"))) +} diff --git a/backend/internal/service/openai_codex_tool_names.go b/backend/internal/service/openai_codex_tool_names.go index 849a45e417..ffc4b50f56 100644 --- a/backend/internal/service/openai_codex_tool_names.go +++ b/backend/internal/service/openai_codex_tool_names.go @@ -1,6 +1,7 @@ package service import ( + "bytes" "encoding/json" "fmt" "strings" @@ -165,28 +166,52 @@ func aliasOpenAIOAuthReservedToolNamesBody(body []byte) ([]byte, map[string]stri return normalized, reverse, true, nil } +// containsASCIIFold reports whether haystack contains needle under ASCII case +// folding. +// +// 逐字节比较在 1MiB 级请求体上等于整段扫描;只按首字节 memchr 又会为每个候选 +// 重新探测「大小写两种首字节」各自的整段尾部,候选一多就退化成平方级。这里给 +// 大小写两条候选游标,每条只在自身未消费的区间上前进,整体保持线性, +// 结果与逐字节折叠比较完全一致。 func containsASCIIFold(haystack, needle []byte) bool { if len(needle) == 0 || len(haystack) < len(needle) { return false } - for i := 0; i <= len(haystack)-len(needle); i++ { - matched := true - for j := range needle { - a, b := haystack[i+j], needle[j] - if a >= 'A' && a <= 'Z' { - a += 'a' - 'A' - } - if b >= 'A' && b <= 'Z' { - b += 'a' - 'A' - } - if a != b { - matched = false - break - } + first := needle[0] + upper := first + if 'a' <= first && first <= 'z' { + upper = first - ('a' - 'A') + } + last := len(haystack) - len(needle) + + lowerPos := bytes.IndexByte(haystack, first) + upperPos := -1 + if upper != first { + upperPos = bytes.IndexByte(haystack, upper) + } + for lowerPos >= 0 || upperPos >= 0 { + pos := lowerPos + if pos < 0 || (upperPos >= 0 && upperPos < pos) { + pos = upperPos } - if matched { + if pos > last { + return false + } + if bytes.EqualFold(haystack[pos:pos+len(needle)], needle) { return true } + // 只推进刚刚消费掉的那条游标。 + if pos == lowerPos { + lowerPos = -1 + if next := bytes.IndexByte(haystack[pos+1:], first); next >= 0 { + lowerPos = pos + 1 + next + } + continue + } + upperPos = -1 + if next := bytes.IndexByte(haystack[pos+1:], upper); next >= 0 { + upperPos = pos + 1 + next + } } return false }