From b0299e5d04d49aa4452734ea6f955a39abce4c52 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Thu, 19 Nov 2026 01:21:42 +0800 Subject: [PATCH 1/7] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=20OpenAI=20?= =?UTF-8?q?=E6=97=A7=E7=89=88=E5=85=BC=E5=AE=B9=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/config/config.go | 14 +- .../issue914_legacy_compatibility_test.go | 37 +++ .../handler/openai_issue914_legacy_test.go | 276 ++++++++++++++++++ .../service/openai_400_omit_history.go | 3 + .../service/openai_409_omit_history.go | 9 + .../service/openai_409_readable_shadow.go | 3 + .../service/openai_agent_message_recovery.go | 7 +- .../service/openai_gateway_request_body.go | 4 +- .../service/openai_issue914_legacy_test.go | 80 +++++ .../service/openai_legacy_compatibility.go | 14 + .../service/openai_lossy_history_restart.go | 3 + .../service/openai_ws_agent_recovery.go | 3 + .../openai_ws_readable_continuation.go | 3 + deploy/.env.example | 3 + deploy/config.example.yaml | 4 + deploy/docker-compose.dev.yml | 1 + deploy/docker-compose.local.yml | 1 + deploy/docker-compose.standalone.yml | 1 + deploy/docker-compose.yml | 1 + docs/encrypted-agent-owner-policy.md | 2 + docs/openai-agent-continuation.md | 2 + docs/openai-legacy-compatibility.md | 28 ++ 22 files changed, 494 insertions(+), 5 deletions(-) create mode 100644 backend/internal/config/issue914_legacy_compatibility_test.go create mode 100644 backend/internal/handler/openai_issue914_legacy_test.go create mode 100644 backend/internal/service/openai_issue914_legacy_test.go create mode 100644 backend/internal/service/openai_legacy_compatibility.go create mode 100644 docs/openai-legacy-compatibility.md diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index 0ab866e180ea..a373ab860129 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -1173,8 +1173,12 @@ type GatewayConfig struct { // DisableEncryptedAgentOwnerBinding permits completed opaque agent history // on another normally eligible native Responses account. Delivery fences, // response pointers, authorization and no-replay protections still apply. - DisableEncryptedAgentOwnerBinding bool `mapstructure:"disable_encrypted_agent_owner_binding"` - UpstreamRouting upstreamroute.Config `mapstructure:"upstream_routing"` + DisableEncryptedAgentOwnerBinding bool `mapstructure:"disable_encrypted_agent_owner_binding"` + // OpenAILegacyCompatibilityMode bypasses the post-v2.20 agent recovery + // ownership, immutable projections and no-replay gates. Startup-only; false + // retains the current policy. Explicit history rebuild settings are ignored. + OpenAILegacyCompatibilityMode bool `mapstructure:"openai_legacy_compatibility_mode"` + UpstreamRouting upstreamroute.Config `mapstructure:"upstream_routing"` // PrismBrowser is the server-managed browser-session adapter for prism.openai.com. // Account settings only select this route; cookies, sandbox state and the adapter // API key remain outside account credentials. @@ -2332,6 +2336,7 @@ func configureConfigSource(setConfigFile, addConfigPath func(string)) { func setDefaults() { viper.SetDefault("gateway.disable_encrypted_agent_owner_binding", false) + viper.SetDefault("gateway.openai_legacy_compatibility_mode", false) viper.SetDefault("gateway.upstream_routing.enabled", false) viper.SetDefault("runtime.role", RuntimeRoleFull) viper.SetDefault("runtime.node_id", "") @@ -4373,3 +4378,8 @@ func (c *Config) OpenAIWSClientHistoryRecoveryEnabled() bool { func (c *Config) OpenAILossyHistoryRestartEnabled() bool { return c != nil && c.Gateway.OpenAIWS.LossyHistoryRestartEnabled } + +// OpenAILegacyCompatibilityEnabled exposes the startup policy to gateway adapters. +func (c *Config) OpenAILegacyCompatibilityEnabled() bool { + return c != nil && c.Gateway.OpenAILegacyCompatibilityMode +} diff --git a/backend/internal/config/issue914_legacy_compatibility_test.go b/backend/internal/config/issue914_legacy_compatibility_test.go new file mode 100644 index 000000000000..ddc9e9771a1f --- /dev/null +++ b/backend/internal/config/issue914_legacy_compatibility_test.go @@ -0,0 +1,37 @@ +package config + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestIssue914LegacyCompatibilityConfiguration(t *testing.T) { + for _, tc := range []struct { + name, yaml, env string + want bool + }{ + {"default", "", "", false}, + {"yaml", "gateway:\n openai_legacy_compatibility_mode: true\n", "", true}, + {"env", "", "true", true}, + {"env_over_yaml", "gateway:\n openai_legacy_compatibility_mode: true\n", "false", false}, + } { + t.Run(tc.name, func(t *testing.T) { + resetViperWithJWTSecret(t) + path := filepath.Join(t.TempDir(), "config.yaml") + require.NoError(t, os.WriteFile(path, []byte(tc.yaml), 0600)) + t.Setenv("CONFIG_FILE", path) + t.Setenv("GATEWAY_OPENAI_LEGACY_COMPATIBILITY_MODE", tc.env) + cfg, err := Load() + require.NoError(t, err) + raw, err := json.Marshal(cfg.Gateway) + require.NoError(t, err) + var got struct{ OpenAILegacyCompatibilityMode bool } + require.NoError(t, json.Unmarshal(raw, &got)) + require.Equal(t, tc.want, got.OpenAILegacyCompatibilityMode) + }) + } +} diff --git a/backend/internal/handler/openai_issue914_legacy_test.go b/backend/internal/handler/openai_issue914_legacy_test.go new file mode 100644 index 000000000000..9ef2c5474a97 --- /dev/null +++ b/backend/internal/handler/openai_issue914_legacy_test.go @@ -0,0 +1,276 @@ +//go:build unit + +package handler + +import ( + "encoding/json" + "fmt" + "net/http" + "net/url" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/repository" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/Wei-Shaw/sub2api/internal/testutil" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +func issue914Policy(t *testing.T, cfg *config.Config, enabled bool) { + t.Helper() + require.NoError(t, json.Unmarshal([]byte(fmt.Sprintf(`{"OpenAILegacyCompatibilityMode":%t,"DisableEncryptedAgentOwnerBinding":true}`, enabled)), &cfg.Gateway)) +} + +func issue914Settings() map[string]string { + settings := issue892Settings() + // Legacy takes precedence even when the saved recovery settings are on. + settings[service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled] = "true" + settings[service.SettingKeyOpenAI400OmitEncryptedHistoryEnabled] = "true" + return settings +} + +func issue914Body(t *testing.T, change string, stream bool) string { + t.Helper() + body := issue715Body(false, stream) + set := func(path string, value any) { + var err error + body, err = sjson.Set(body, path, value) + require.NoError(t, err) + } + raw := func(path, value string) { + var err error + body, err = sjson.SetRaw(body, path, value) + require.NoError(t, err) + } + set("store", false) + set("instructions", "Continue the synthetic task.") + set("client_metadata.window_id", "fixture-window-1") + switch change { + case "metadata": + set("input.0.internal_chat_message_metadata_passthrough", map[string]any{"turn_id": "fixture-turn"}) + case "schema", "reserved_name", "declaration_id": + name, schema, id := "lookup", `{"type":"object","properties":{}}`, "at_11111111222243338444555555555555" + if change == "schema" { + schema = `{"type":null,"required":null}` + } + if change == "reserved_name" { + name = "python" + } + if change == "declaration_id" { + id = "at_11111111-2222-4333-8444-555555555555" + } + raw("input.-1", fmt.Sprintf(`{"type":"additional_tools","role":"developer","id":%q,"tools":[{"type":"function","name":%q,"parameters":%s}]}`, id, name, schema)) + case "lite_namespace": + raw("tools", `[{"type":"namespace","name":"fixture_tools","tools":[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{}}}]}]`) + case "lite_search": + raw("input.-1", `{"type":"web_search_call","id":"ws_fixture","status":"completed","action":{"type":"search","query":"fixture"}}`) + case "system": + set("input.1.role", "system") + case "namespace": + set("input.1.namespace", "fixture_namespace") + case "orphan": + raw("input.-1", `{"type":"custom_tool_call_output","call_id":"call_fixture_missing","output":"fixture output"}`) + case "empty_image": + raw("input.1.content", `[{"type":"input_text","text":"Continue fixture"},{"type":"input_image","image_url":"data:image/png;base64,"}]`) + case "compaction", "compaction_order": + set("input.-1", map[string]any{"role": "user", "content": "\nAsia/Singapore\n"}) + raw("input.-1", `{"type":"compaction_trigger"}`) + if change == "compaction_order" { + raw("input.-1", `{"role":"user","content":"Continue fixture"}`) + } + case "spark", "spark_image": + set("model", "gpt-5.3-codex-spark") + if change == "spark_image" { + raw("input.-1", `{"type":"additional_tools","role":"developer","id":"at_fixture_image","tools":[{"type":"image_generation"}]}`) + } + case "custom_bridge": + raw("tools", `[{"type":"custom","name":"fixture_custom","format":{"type":"text"}}]`) + raw("input.-1", `{"type":"custom_tool_call","call_id":"call_fixture_pair","name":"fixture_custom","input":"fixture argument"}`) + raw("input.-1", `{"type":"custom_tool_call_output","call_id":"call_fixture_pair","output":"fixture result"}`) + } + return body +} + +func issue914HTTPNode(t *testing.T, u *issue805Oracle, legacy bool, accounts []service.Account) (*OpenAIGatewayHandler, *readable409UsageRepo) { + t.Helper() + srv := u.server(t) + target, err := url.Parse(srv.URL) + require.NoError(t, err) + for i := range accounts { + accounts[i].Credentials = map[string]any{"api_key": fmt.Sprintf("fixture-ws-%d", i), "access_token": fmt.Sprintf("fixture-ws-%d", i), "base_url": srv.URL} + accounts[i].Extra = map[string]any{"openai_request_timezone": "America/Los_Angeles", "codex_fingerprint_mode": "off"} + } + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + upstream := &issue842Transport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target} + usage := &readable409UsageRepo{} + clients := issue805Redis(t) + h := newOpenAIResponsesFailoverTestHandlerWithUsage(t, upstream, repository.NewGatewayCache(clients()), service.NewSettingService(&issue842Settings{values: issue914Settings()}, cfg), usage, accounts...) + h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true + issue914Policy(t, h.cfg, legacy) + return h, usage +} + +func TestIssue914LegacyHTTPCompatibility(t *testing.T) { + for _, change := range []string{"metadata", "schema", "reserved_name", "lite_namespace", "lite_search", "system", "namespace", "orphan", "empty_image", "compaction", "spark", "spark_image"} { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/stream=%t", change, stream), func(t *testing.T) { + u := &issue805Oracle{} + h, usage := issue914HTTPNode(t, u, true, issue715Accounts()[:1]) + body := issue914Body(t, change, stream) + c, rec := newIssue715Context(t, body) + c.Request.Header.Set("session_id", "fixture-914") + if change == "lite_namespace" || change == "lite_search" { + c.Request.Header.Set("X-OpenAI-Internal-Codex-Responses-Lite", "true") + } + h.Responses(c) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + issue758CompletedResponse(t, rec.Body.String(), stream) + u.mu.Lock() + frames := append([][]byte(nil), u.frames...) + u.mu.Unlock() + require.Len(t, frames, 1, "exactly one actual upstream request") + require.NotContains(t, string(frames[0]), "internal_chat_message_metadata_passthrough") + require.Contains(t, string(frames[0]), "fixture-task-reference-715", "legacy must not activate the saved 409 omission option") + if change == "compaction" { + require.Equal(t, "compaction_trigger", gjson.GetBytes(frames[0], "input.@reverse.0.type").String()) + } + require.Eventually(t, func() bool { return len(usage.snapshot()) == 1 }, 2*time.Second, 10*time.Millisecond) + row := usage.snapshot()[0] + require.EqualValues(t, 5, row.InputTokens) + require.EqualValues(t, 3, row.OutputTokens) + require.Greater(t, row.TotalCost, 0.0) + }) + } + } +} + +func TestIssue914DefaultStillRejectsFrozenMutation(t *testing.T) { + u := &issue805Oracle{} + h, _ := issue914HTTPNode(t, u, false, issue715Accounts()[:1]) + answer := issue758Request(t, h, issue914Body(t, "metadata", true)) + require.Equal(t, http.StatusConflict, answer.Code, answer.Body.String()) + require.Contains(t, answer.Body.String(), "encrypted_agent_recovery_wire_changed") + u.mu.Lock() + defer u.mu.Unlock() + require.Empty(t, u.frames) +} + +func issue914WSNode(t *testing.T, kind, mode, upstream string, cache service.GatewayCache) *openAIWSPassthroughHandlerHarness { + t.Helper() + target, err := url.Parse(upstream) + require.NoError(t, err) + h := newOpenAIWSPassthroughHandlerHarnessWithKey(t, upstream, + http.Header{"Session_id": {"fixture-914"}, "Thread-Id": {"fixture-914"}}, issue914Settings(), cache, + func(key *service.APIKey) { key.AllowLongContext = true }, + func(a *service.Account, cfg *config.Config, httpUpstream *service.HTTPUpstream, _ *service.AccountRepository) { + a.Type = kind + a.Credentials = map[string]any{"api_key": "fixture-ws-one", "access_token": "fixture-ws-one", "base_url": upstream, "chatgpt_account_id": "fixture914"} + a.Extra["openai_apikey_responses_websockets_v2_mode"] = mode + a.Extra["openai_oauth_responses_websockets_v2_enabled"] = true + a.Extra["openai_oauth_responses_websockets_v2_mode"] = mode + a.Extra["openai_request_timezone"] = "America/Los_Angeles" + a.Extra["codex_fingerprint_mode"] = "off" + cfg.Gateway.OpenAIWS.OAuthEnabled = true + cfg.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds = 15 + issue914Policy(t, cfg, true) + *httpUpstream = &issue842Transport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target} + }) + if kind == service.AccountTypeOAuth { + require.NoError(t, service.RouteIssue842OAuthSocketsToLoopbackForTest(h.handler.gatewayService, upstream)) + } + return h +} + +func TestIssue914LegacyWSCompatibility(t *testing.T) { + for _, kind := range []string{service.AccountTypeOAuth, service.AccountTypeAPIKey} { + for _, mode := range []string{service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeHTTPBridge} { + for _, change := range []string{"metadata", "declaration_id", "compaction_order", "custom_bridge", "instructions", "window"} { + t.Run(kind+"/"+mode+"/"+change, func(t *testing.T) { + clients := issue805Redis(t) + u := &issue805Oracle{} + srv := u.server(t) + h := issue914WSNode(t, kind, mode, srv.URL, repository.NewGatewayCache(clients())) + body := issue914Body(t, change, true) + body, err := sjson.Set(body, "type", "response.create") + require.NoError(t, err) + turns := 1 + if change == "instructions" || change == "window" { + turns = 2 + } + for turn := 0; turn < turns; turn++ { + issue715WSSend(t, h.clientConn, body) + answer := issue715WSRead(t, h.clientConn) + require.Equal(t, "response.completed", gjson.GetBytes(answer, "type").String(), string(answer)) + if turns == 2 && turn == 0 { + body, err = sjson.Set(body, "previous_response_id", gjson.GetBytes(answer, "response.id").String()) + require.NoError(t, err) + field := "instructions" + if change == "window" { + field = "client_metadata.window_id" + } + body, err = sjson.Set(body, field, "fixture-next-turn") + require.NoError(t, err) + } + select { + case row := <-h.usageLogs: + require.EqualValues(t, 5, row.InputTokens) + require.EqualValues(t, 3, row.OutputTokens) + require.Greater(t, row.TotalCost, 0.0) + case <-time.After(3 * time.Second): + t.Fatal("missing completed-turn usage") + } + } + issue600Finish(t, h, http.Header{"Session_id": {"fixture-914"}, "Thread-Id": {"fixture-914"}}) + u.mu.Lock() + defer u.mu.Unlock() + require.Len(t, u.frames, turns) + if mode == service.OpenAIWSIngressModeHTTPBridge { + require.Equal(t, turns, u.http) + } else { + require.Equal(t, turns, u.ws) + } + if change == "custom_bridge" && mode == service.OpenAIWSIngressModeHTTPBridge && kind == service.AccountTypeAPIKey { + require.Contains(t, string(u.frames[0]), `"type":"function_call"`) + require.NotContains(t, string(u.frames[0]), `"type":"custom_tool_call"`) + } + require.Empty(t, issue805Owners(t, clients()), "legacy must not publish strict ownership evidence") + }) + } + } + } +} + +func TestIssue914LegacyUpstreamRejectionIsPreserved(t *testing.T) { + u := &issue805Oracle{rejection: "fixture_provider_error", rejectionStatus: 400} + h, _ := issue914HTTPNode(t, u, true, issue715Accounts()[:1]) + answer := issue758Request(t, h, issue914Body(t, "metadata", false)) + require.Equal(t, http.StatusBadRequest, answer.Code, answer.Body.String()) + require.Contains(t, answer.Body.String(), "fixture_provider_error") + u.mu.Lock() + defer u.mu.Unlock() + require.Len(t, u.frames, 1) +} + +func TestIssue914LegacyAccountPoolAndCancellation(t *testing.T) { + for _, canceled := range []bool{false, true} { + t.Run(fmt.Sprint("canceled=", canceled), func(t *testing.T) { + u := &openAIResponsesFailoverCancelUpstream{} + h := newOpenAIResponsesFailoverTestHandler(t, u, issue715Accounts()...) + issue914Policy(t, h.cfg, true) + status, answer := issue715Request(t, h, issue715Body(true, false), 99, "fixture-914", canceled) + require.NotContains(t, answer, "encrypted_agent_recovery_") + calls := u.calls() + if canceled { + require.Empty(t, calls) + } else { + require.GreaterOrEqual(t, status, 400) + require.Contains(t, calls, int64(1)) + require.Contains(t, calls, int64(2), "ordinary pre-output failure must be able to select another eligible account") + } + }) + } +} diff --git a/backend/internal/service/openai_400_omit_history.go b/backend/internal/service/openai_400_omit_history.go index fe4190d2244e..8bde9edede32 100644 --- a/backend/internal/service/openai_400_omit_history.go +++ b/backend/internal/service/openai_400_omit_history.go @@ -41,6 +41,9 @@ func (s *OpenAIGatewayService) prepareOpenAI400HistoryRecovery(ctx context.Conte if d.Applied || attempts >= 3 { return refuse("retry_exhausted") } + if s.openAILegacyCompatibility() { + return refuse("legacy_compatibility") + } if s == nil || !s.settingService.IsOpenAI400OmitEncryptedHistoryEnabled(ctx) { return refuse("disabled") } diff --git a/backend/internal/service/openai_409_omit_history.go b/backend/internal/service/openai_409_omit_history.go index 59c763b35b31..b87d86280c56 100644 --- a/backend/internal/service/openai_409_omit_history.go +++ b/backend/internal/service/openai_409_omit_history.go @@ -40,6 +40,9 @@ func (s *OpenAIGatewayService) TryOmitOpenAI409History(ctx context.Context, c *g } func (s *OpenAIGatewayService) TryRebuildOpenAI409History(ctx context.Context, c *gin.Context, body []byte, session, model string, cause error) (context.Context, []byte, bool, error) { + if s.openAILegacyCompatibility() { + return ctx, body, false, nil + } var refusal *OpenAIAgentRecoveryError if !errors.As(cause, &refusal) { return ctx, body, false, nil @@ -136,6 +139,9 @@ func (s *OpenAIGatewayService) TryRebuildOpenAI409History(ctx context.Context, c // account's conversation. Rebuild before selection, after all item fences were // read. A healthy single producer without pointers retains ordinary routing. func (s *OpenAIGatewayService) PrepareOpenAI409ReadableContinuation(ctx context.Context, c *gin.Context, body []byte, session, model string) (nextCtx context.Context, nextBody []byte, changed bool, resultErr error) { + if s.openAILegacyCompatibility() { + return ctx, body, false, nil + } if next, clean, changed := s.PrepareOpenAILossyHistoryRestart(ctx, c, body, session, model); changed { return next, clean, true, nil } @@ -175,6 +181,9 @@ func (s *OpenAIGatewayService) PrepareOpenAI409ReadableContinuation(ctx context. // It may only be discarded, under the explicit Beta policy, in favor of the // caller's own readable task. Existing foreign ownership/store failures deny. func (s *OpenAIGatewayService) CanDiscardOpenAI409ResponsePointer(ctx context.Context, body []byte, groupID int64, responseID string) bool { + if s.openAILegacyCompatibility() { + return false + } if s != nil && s.settingService != nil { policy, ok := any(s.cfg).(interface{ OpenAILossyHistoryRestartEnabled() bool }) if ok && policy.OpenAILossyHistoryRestartEnabled() && utf8.Valid(body) && openAIEncryptedJSONUnambiguous(body) && diff --git a/backend/internal/service/openai_409_readable_shadow.go b/backend/internal/service/openai_409_readable_shadow.go index 69b0a46dd5fd..30510c7035e0 100644 --- a/backend/internal/service/openai_409_readable_shadow.go +++ b/backend/internal/service/openai_409_readable_shadow.go @@ -70,6 +70,9 @@ func (r *openAIAgentRecoveryRequest) shadowEpochKey(item [32]byte) string { // client intent or unpaired tool work. Existing readable requests never consult // shadow. A miss/error leaves ordinary routing/refusal intact, never invents text. func (s *OpenAIGatewayService) RestoreOpenAIReadableShadow(ctx context.Context, c *gin.Context, body []byte, session string) (restoredCtx context.Context, restoredBody []byte) { + if s.openAILegacyCompatibility() { + return ctx, body + } state := openAIRecoveryShadowState{lookup: "not_consulted", epoch: "not_checked"} defer func() { restoredCtx = context.WithValue(restoredCtx, openAIRecoveryShadowStateKey{}, state) }() if s == nil || s.settingService == nil || openAI409HasReadableIntent(body) || diff --git a/backend/internal/service/openai_agent_message_recovery.go b/backend/internal/service/openai_agent_message_recovery.go index 16f9be4330af..6a7bc04b792e 100644 --- a/backend/internal/service/openai_agent_message_recovery.go +++ b/backend/internal/service/openai_agent_message_recovery.go @@ -105,6 +105,11 @@ type openAIAgentRecoveryRequest struct { // producer; it cannot prove a provider will accept its own output in the future. // Ordinary sticky writes, HTTP 200 and reasoning are not proof. func (s *OpenAIGatewayService) WithOpenAIAgentMessageRecovery(ctx context.Context, c *gin.Context, body []byte, sessionHash, model string) context.Context { + if s.openAILegacyCompatibility() { + // Mask any inherited snapshot; compatibility must not consult or publish + // agent-owner records, nor create bound/no-replay state. + return context.WithValue(ctx, openAIAgentRecoveryContextKey{}, (*openAIAgentRecoveryRequest)(nil)) + } request := &openAIAgentRecoveryRequest{groupID: getOpenAIGroupIDFromContext(c), model: model, session: sessionHash} request.disableOwnerBinding = s != nil && s.cfg != nil && s.cfg.Gateway.DisableEncryptedAgentOwnerBinding if request.disableOwnerBinding || (openAI409HasProviderState(body) && s != nil && s.settingService != nil && s.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx)) || openAIAgentRecoveryHTTPUser(c, getAPIKeyIDFromContext(c)) > 0 { @@ -261,7 +266,7 @@ func openAIAgentRecoveryInputDigest(body []byte) [32]byte { } func (s *OpenAIGatewayService) preserveOpenAIAgentHistory(body []byte) bool { - return s != nil && s.cfg != nil && s.cfg.Gateway.DisableEncryptedAgentOwnerBinding && len(openAIAgentRecoveryItemDigests(body)) > 0 + return s != nil && !s.openAILegacyCompatibility() && s.cfg != nil && s.cfg.Gateway.DisableEncryptedAgentOwnerBinding && len(openAIAgentRecoveryItemDigests(body)) > 0 } func openAIAgentRecoveryItemDigests(body []byte) [][32]byte { diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index 3ce6582a950c..e5f6bace497e 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -1513,7 +1513,7 @@ func normalizeOpenAIResponsesWebSocketCompatibilityBody(body []byte, account *Ac } func normalizeOpenAIResponsesWebSocketCompatibilityBodyWithConfig(cfg *config.Config, body []byte, account *Account, responsesLite bool) ([]byte, bool, error) { - protected := cfg != nil && cfg.Gateway.DisableEncryptedAgentOwnerBinding && len(openAIAgentRecoveryItemDigests(body)) > 0 + protected := cfg != nil && !openAILegacyCompatibilityEnabled(cfg) && cfg.Gateway.DisableEncryptedAgentOwnerBinding && len(openAIAgentRecoveryItemDigests(body)) > 0 return normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, account, openAIResponsesCompatibilityOptions{Config: cfg, ResponsesLite: responsesLite, PreserveInput: protected}) } @@ -1650,7 +1650,7 @@ func normalizeOpenAIResponsesCompatibilityBodyWithOptions(body []byte, account * } if openAIRequestBodyImageGenerationToolNeedsNormalization(normalized) { var reqBody map[string]any - if err := json.Unmarshal(normalized, &reqBody); err != nil { + if err := decodeOpenAIJSONUseNumber(normalized, &reqBody); err != nil { return body, false, fmt.Errorf("normalize websocket image tool body: %w", err) } if normalizeOpenAIResponsesImageGenerationTools(reqBody) { diff --git a/backend/internal/service/openai_issue914_legacy_test.go b/backend/internal/service/openai_issue914_legacy_test.go new file mode 100644 index 000000000000..7dc4bca44e7e --- /dev/null +++ b/backend/internal/service/openai_issue914_legacy_test.go @@ -0,0 +1,80 @@ +package service + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func issue914LegacyPolicy(t *testing.T, cfg *config.Config, enabled bool) { + t.Helper() + raw, err := json.Marshal(map[string]bool{"OpenAILegacyCompatibilityMode": enabled}) + require.NoError(t, err) + require.NoError(t, json.Unmarshal(raw, &cfg.Gateway)) +} + +func TestIssue914LegacyRecoveryPrecedence(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{}} + svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = true + manager, c, account := issue715WSManager(t, svc, context.Background()) + defer manager.abort() + body := []byte(issue842Source) + strict := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, body, "fixture-session", "gpt-6-astra") + require.True(t, OpenAIAgentRecoveryNoReplay(strict)) + issue914LegacyPolicy(t, svc.cfg, true) + ctx := svc.WithOpenAIWSAgentRecovery(strict, c, body, "fixture-session", "gpt-6-astra") + require.Nil(t, openAIAgentRecoveryFromContext(ctx), "even an inherited strict snapshot must be masked") + require.False(t, OpenAIAgentRecoveryNoReplay(ctx)) + require.False(t, OpenAIWSAgentRecoveryBound(ctx)) + require.True(t, OpenAIWSAgentRecoveryCanRetry(ctx)) + require.Nil(t, newOpenAIWSAgentRecovery(svc, ctx, c)) + clean, err := svc.PrepareOpenAIAgentReplayBody(body) + require.NoError(t, err) + require.Equal(t, body, clean) + _, clean, changed, err := svc.PrepareOpenAI409ReadableContinuation(ctx, c, body, "fixture-session", "gpt-6-astra") + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, body, clean) + _, clean, changed = svc.PrepareOpenAILossyHistoryRestart(ctx, c, body, "fixture-session", "gpt-6-astra") + require.False(t, changed) + require.Equal(t, body, clean) + _, clean, changed, err = svc.RebuildOpenAIWSUnsentTurn(ctx, c, body, "fixture-session", "gpt-6-astra") + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, body, clean) + // Changed controls/input and compaction must not reintroduce a recovery gate. + req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://fixture.invalid/v1/responses", strings.NewReader(`{"input":[],"instructions":"compatibility projection"}`)) + require.NoError(t, err) + finish, err := svc.prepareOpenAIAgentRecoveryAttempt(ctx, account, req) + require.NoError(t, err) + finish(true) + require.NoError(t, svc.checkOpenAIAgentRecoveryCompaction(ctx, account, req)) + canceled, cancel := context.WithCancel(ctx) + cancel() + _, err = svc.prepareOpenAIAgentRecoveryAttempt(canceled, account, req) + require.ErrorIs(t, err, context.Canceled) + // Disabling legacy returns to the original policy rather than changing opt-out. + issue914LegacyPolicy(t, svc.cfg, false) + strict = svc.WithOpenAIAgentMessageRecovery(ctx, c, body, "fixture-session", "gpt-6-astra") + require.True(t, OpenAIAgentRecoveryNoReplay(strict)) +} + +func TestIssue914ImageCompatibilityPreservesNumbers(t *testing.T) { + body := []byte(`{"model":"gpt-5.1","tools":[{"type":"image_generation","format":"png"}],"input":[{"role":"user","content":"fixture","sequence":9007199254740993}]}`) + for _, legacy := range []bool{false, true} { + cfg := &config.Config{} + issue914LegacyPolicy(t, cfg, legacy) + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + got, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBodyWithConfig(cfg, body, account, false) + require.NoError(t, err) + require.True(t, changed) + require.Equal(t, "9007199254740993", gjson.GetBytes(got, "input.0.sequence").Raw) + require.Equal(t, "png", gjson.GetBytes(got, "tools.0.output_format").String()) + } +} diff --git a/backend/internal/service/openai_legacy_compatibility.go b/backend/internal/service/openai_legacy_compatibility.go new file mode 100644 index 000000000000..40410d78f1ad --- /dev/null +++ b/backend/internal/service/openai_legacy_compatibility.go @@ -0,0 +1,14 @@ +package service + +import "github.com/Wei-Shaw/sub2api/internal/config" + +// Keep historical regression overlays with an older Config buildable. An +// absent policy has the same behavior as an unconfigured production process. +func openAILegacyCompatibilityEnabled(cfg *config.Config) bool { + policy, ok := any(cfg).(interface{ OpenAILegacyCompatibilityEnabled() bool }) + return ok && policy.OpenAILegacyCompatibilityEnabled() +} + +func (s *OpenAIGatewayService) openAILegacyCompatibility() bool { + return s != nil && openAILegacyCompatibilityEnabled(s.cfg) +} diff --git a/backend/internal/service/openai_lossy_history_restart.go b/backend/internal/service/openai_lossy_history_restart.go index 25e86009c353..95aac1d3acd7 100644 --- a/backend/internal/service/openai_lossy_history_restart.go +++ b/backend/internal/service/openai_lossy_history_restart.go @@ -22,6 +22,9 @@ func initialModel(r *openAIAgentRecoveryRequest, body []byte) string { // consumes a foreign response, grants tool provenance, or retries sent work. // Disabled by default; operators must explicitly accept loss of task context. func (s *OpenAIGatewayService) PrepareOpenAILossyHistoryRestart(ctx context.Context, c *gin.Context, body []byte, session, model string) (context.Context, []byte, bool) { + if s.openAILegacyCompatibility() { + return ctx, body, false + } if s == nil { return ctx, body, false } diff --git a/backend/internal/service/openai_ws_agent_recovery.go b/backend/internal/service/openai_ws_agent_recovery.go index 4fcf22f10258..f63771f4b7dd 100644 --- a/backend/internal/service/openai_ws_agent_recovery.go +++ b/backend/internal/service/openai_ws_agent_recovery.go @@ -1264,6 +1264,9 @@ func openAIWSHistoryItemFailure(item gjson.Result) string { // carried only as user-supplied data. Callers invoke this exclusively before // dispatch and run the normal current-turn authorization/moderation again. func (s *OpenAIGatewayService) restartOpenAIWSClientReadableHistory(ctx context.Context, c *gin.Context, body []byte, session, model string, cause error) (context.Context, []byte, bool) { + if s.openAILegacyCompatibility() { + return ctx, body, false + } if s == nil || s.cfg == nil || s.settingService == nil || ctx.Err() != nil { return ctx, body, false } diff --git a/backend/internal/service/openai_ws_readable_continuation.go b/backend/internal/service/openai_ws_readable_continuation.go index e072682dec55..c52344000557 100644 --- a/backend/internal/service/openai_ws_readable_continuation.go +++ b/backend/internal/service/openai_ws_readable_continuation.go @@ -181,6 +181,9 @@ func openAIWSCompletedToolInputs(body []byte) bool { // Called before fresh admission/moderation of an unsent frame. Lookup is scoped // to this exact task; missing historical intent is never fabricated. func (s *OpenAIGatewayService) RebuildOpenAIWSUnsentTurn(ctx context.Context, c *gin.Context, body []byte, session, model string) (nextCtx context.Context, nextBody []byte, changed bool, resultErr error) { + if s.openAILegacyCompatibility() { + return ctx, body, false, nil + } originalBody := body unsent, _ := ctx.Value(openAIWSUnsentAdmissionKey{}).(*openAIWSUnsentTurnError) ctx = context.WithValue(ctx, openAIWSUnsentAdmissionKey{}, (*openAIWSUnsentTurnError)(nil)) diff --git a/deploy/.env.example b/deploy/.env.example index b7b11d9f4641..f3788ca3e44a 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -305,6 +305,9 @@ GATEWAY_FORCE_CODEX_CLI=false # 完整且已交付的加密 agent 历史可尝试其他合格账号;默认保持严格归属。 # 所有共享 Redis 节点统一配置并排空 WS 后重启,详见 docs/encrypted-agent-owner-policy.md。 GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING=false +# Opt-in legacy forwarding; overrides agent owner binding and 400/409 history rebuild. +# Startup-only, default false. See docs/openai-legacy-compatibility.md. +GATEWAY_OPENAI_LEGACY_COMPATIBILITY_MODE=false # OpenAI /responses/compact 上游模型(默认 gpt-5.5)。 # 当 compact 端点暂未支持更新模型时,可通过这里降级规避失败。 GATEWAY_OPENAI_COMPACT_MODEL=gpt-5.5 diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index 8f171779aca1..df7a1e1f03e6 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -300,6 +300,10 @@ gateway: # 默认严格;true 不保证密文兼容,不解除权限/额度/并发和交付安全检查。 # 所有节点统一配置、排空旧 WS 后重启;详见 docs/encrypted-agent-owner-policy.md。 disable_encrypted_agent_owner_binding: false + # Opt-in v2.20-style forwarding without the newer agent recovery integrity gates. + # Takes precedence over owner opt-out, 400/409 history rebuild and lossy restart. + # See docs/openai-legacy-compatibility.md; restart all traffic-serving nodes together. + openai_legacy_compatibility_mode: false # Grok text Responses first-byte timeout (seconds, 0=disabled; default 120) # Grok 文本 Responses 首字节超时时间(秒,0=禁用;默认 120) grok_response_header_timeout: 120 diff --git a/deploy/docker-compose.dev.yml b/deploy/docker-compose.dev.yml index b849a9949fe5..d8e53f69ad19 100644 --- a/deploy/docker-compose.dev.yml +++ b/deploy/docker-compose.dev.yml @@ -63,6 +63,7 @@ services: - GATEWAY_FORCE_CODEX_CLI=${GATEWAY_FORCE_CODEX_CLI:-false} - GATEWAY_OPENAI_COMPACT_MODEL=${GATEWAY_OPENAI_COMPACT_MODEL:-gpt-5.5} - GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING=${GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING:-false} + - GATEWAY_OPENAI_LEGACY_COMPATIBILITY_MODE=${GATEWAY_OPENAI_LEGACY_COMPATIBILITY_MODE:-false} - SUB2API_IMAGES_MAIN_MODEL=${SUB2API_IMAGES_MAIN_MODEL:-gpt-5.6-luna} - SUB2API_IMAGE_EDIT_FORM_ACCOUNT_IDS=${SUB2API_IMAGE_EDIT_FORM_ACCOUNT_IDS:-} - GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=${GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT:-0} diff --git a/deploy/docker-compose.local.yml b/deploy/docker-compose.local.yml index bf9a4b4bd432..7b0692e8f44e 100644 --- a/deploy/docker-compose.local.yml +++ b/deploy/docker-compose.local.yml @@ -171,6 +171,7 @@ services: - GATEWAY_FORCE_CODEX_CLI=${GATEWAY_FORCE_CODEX_CLI:-false} - GATEWAY_OPENAI_COMPACT_MODEL=${GATEWAY_OPENAI_COMPACT_MODEL:-gpt-5.5} - GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING=${GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING:-false} + - GATEWAY_OPENAI_LEGACY_COMPATIBILITY_MODE=${GATEWAY_OPENAI_LEGACY_COMPATIBILITY_MODE:-false} - SUB2API_IMAGES_MAIN_MODEL=${SUB2API_IMAGES_MAIN_MODEL:-gpt-5.6-luna} - SUB2API_IMAGE_EDIT_FORM_ACCOUNT_IDS=${SUB2API_IMAGE_EDIT_FORM_ACCOUNT_IDS:-} - GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=${GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT:-0} diff --git a/deploy/docker-compose.standalone.yml b/deploy/docker-compose.standalone.yml index afc1b47fc012..0237e4db3d28 100644 --- a/deploy/docker-compose.standalone.yml +++ b/deploy/docker-compose.standalone.yml @@ -118,6 +118,7 @@ services: - GATEWAY_FORCE_CODEX_CLI=${GATEWAY_FORCE_CODEX_CLI:-false} - GATEWAY_OPENAI_COMPACT_MODEL=${GATEWAY_OPENAI_COMPACT_MODEL:-gpt-5.5} - GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING=${GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING:-false} + - GATEWAY_OPENAI_LEGACY_COMPATIBILITY_MODE=${GATEWAY_OPENAI_LEGACY_COMPATIBILITY_MODE:-false} - SUB2API_IMAGES_MAIN_MODEL=${SUB2API_IMAGES_MAIN_MODEL:-gpt-5.6-luna} - SUB2API_IMAGE_EDIT_FORM_ACCOUNT_IDS=${SUB2API_IMAGE_EDIT_FORM_ACCOUNT_IDS:-} - GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=${GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT:-0} diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 90ff6d599f33..5afe3753f880 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -168,6 +168,7 @@ services: - GATEWAY_FORCE_CODEX_CLI=${GATEWAY_FORCE_CODEX_CLI:-false} - GATEWAY_OPENAI_COMPACT_MODEL=${GATEWAY_OPENAI_COMPACT_MODEL:-gpt-5.5} - GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING=${GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING:-false} + - GATEWAY_OPENAI_LEGACY_COMPATIBILITY_MODE=${GATEWAY_OPENAI_LEGACY_COMPATIBILITY_MODE:-false} - SUB2API_IMAGES_MAIN_MODEL=${SUB2API_IMAGES_MAIN_MODEL:-gpt-5.6-luna} - SUB2API_IMAGE_EDIT_FORM_ACCOUNT_IDS=${SUB2API_IMAGE_EDIT_FORM_ACCOUNT_IDS:-} - GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=${GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT:-0} diff --git a/docs/encrypted-agent-owner-policy.md b/docs/encrypted-agent-owner-policy.md index bb5013edb295..444d6d536798 100644 --- a/docs/encrypted-agent-owner-policy.md +++ b/docs/encrypted-agent-owner-policy.md @@ -1,5 +1,7 @@ # 加密 agent 历史账号策略 +管理员也可显式启用独立的[旧版兼容模式](openai-legacy-compatibility.md),停用新增的 agent 冻结与恢复机制;默认关闭,优先级高于本文策略。 + 后台“409 忽略/历史省略”Beta 开关属于另一个明确有损的路径,见 [HTTP 可读历史续接](encrypted-history-readable-continuation.md)。下述进程配置控制完整密文尝试,不等同于该后台开关。 默认仍按已登记的账号和原生 Responses 路线恢复加密 `agent_message`。原账号限流或过载时,保留原等待提示和恢复时间。管理员可显式允许完整历史尝试普通账号池中的其他合格账号: diff --git a/docs/openai-agent-continuation.md b/docs/openai-agent-continuation.md index 0b5c8da15a0a..7bd7802ea0f7 100644 --- a/docs/openai-agent-continuation.md +++ b/docs/openai-agent-continuation.md @@ -1,5 +1,7 @@ # 加密代理任务续接与恢复边界 +管理员也可显式启用独立的[旧版兼容模式](openai-legacy-compatibility.md),停用新增的 agent 冻结与恢复机制;默认关闭,优先级高于本文策略。 + 本页说明 #727 已合入源码的归属保护,关联 [Issue #715](https://github.com/ranxi2001/sub2api/issues/715)。源码合并、Release 和实例部署分别核实;不能只凭版本号认为当前实例已启用这些路径,也不能把离线回归当作真实供应商的格式兼容证明。 下文描述默认严格策略。管理员可通过默认 `false` 的 `gateway.disable_encrypted_agent_owner_binding` 显式允许完整已交付历史尝试其他合格账号;配置方法、交付安全、统一节点切换与回 strict 的混合 owner 限制见[加密 agent 历史账号策略](encrypted-agent-owner-policy.md)。开关不保证上游密文兼容,也不允许重放不确定交付的任务。 diff --git a/docs/openai-legacy-compatibility.md b/docs/openai-legacy-compatibility.md new file mode 100644 index 000000000000..cd54a5c971f9 --- /dev/null +++ b/docs/openai-legacy-compatibility.md @@ -0,0 +1,28 @@ +# OpenAI 旧版兼容模式 + +针对 [#914](https://github.com/ranxi2001/sub2api/issues/914) 中兼容转换与冻结摘要冲突的请求,管理员可以启用 v2.20 风格的普通转发策略。默认关闭,原来的严格策略与 owner-binding opt-out 行为保持不变。本模式只切换新增的 agent 历史恢复机制,不会降级整个应用到 v2.20.0。 + +```yaml +gateway: + openai_legacy_compatibility_mode: true +``` + +环境变量 `GATEWAY_OPENAI_LEGACY_COMPATIBILITY_MODE=true` 优先于 YAML。四套 Compose 模板均透传此变量;这是启动配置,没有后台页面或请求级覆盖。 + +## 行为与优先级 + +开启后,HTTP Responses、WS ctx_pool / passthrough / http_bridge、后续轮与原生压缩不建立新的 agent-owner 恢复上下文,不读取或发布其归属/交付记录,也不执行该机制的 input/controls 冻结、账号绑定、工具来源证明和 no-replay 限制。兼容转换按普通构造流程执行,完整历史使用普通账号池和既有重试策略。 + +该开关优先于 `disable_encrypted_agent_owner_binding`、`openai_400_omit_encrypted_history_enabled`、`openai_409_omit_encrypted_history_enabled` 以及有损历史重启配置。后几项的已保存值保留,但兼容模式内不执行这些新增的重建、shadow 恢复或省略重试,避免它们重新建立冻结摘要。 + +普通鉴权、用户/Key/分组/模型准入、额度、并发、计费、请求大小、客户端取消及协议字段校验仍执行。`previous_response_id` 沿用普通传输的粘性与协议处理,HTTP 用户/Key 所属校验保留;不允许借兼容模式读取其他用户的服务端会话。WS 普通构造主动移除续接指针后,不再被新增的 `ws_previous_removed` 检查阻断。 + +上游拒绝仍按正常错误处理路径返回。跨账号密文兼容、上游私有会话状态和任务连续性由上游实际协议决定;开启本模式不会让任意账号都能解密旧历史。普通重试恢复后,也不再提供新增恢复机制的交付去重保证。独立修正的 JSON Number 解码同时适用于默认模式和兼容模式,防止生图参数转换损坏大整数。 + +## 切换与回滚 + +所有接流量的节点统一设置,排空已有 WS 连接后重启;环境变量不会热更新。关闭开关并按同样方式重启即可恢复原策略,无数据库迁移,不清理现有 Redis 恢复记录。兼容模式期间不会新增严格恢复证明,重新开启严格模式后,这些会话可能需要客户端重新建立完整上下文;不承诺跨模式无缝续接。 + +## 验证范围 + +回归使用虚构输入与本机 mock 上游,检查 HTTP/WS 实际发送、兼容改写、连续回合、账号池选择、上游错误和用量回执。mock 完成只证明网关行为,不等同于真实供应商接受密文或原客户端任务恢复。上线前需另行固定发布产物并按部署流程验收。 From ea0d5e1b80698e2a56b610bb454a224b65a9e28a Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Thu, 19 Nov 2026 01:23:39 +0800 Subject: [PATCH 2/7] =?UTF-8?q?fix:=20=E5=85=BC=E5=AE=B9=E6=A8=A1=E5=BC=8F?= =?UTF-8?q?=E8=B7=B3=E8=BF=87=E6=A1=A5=E6=8E=A5=E7=9A=84=E7=8B=AC=E7=AB=8B?= =?UTF-8?q?=E6=81=A2=E5=A4=8D=E6=8A=95=E5=BD=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/handler/openai_issue914_legacy_test.go | 9 +++++++-- backend/internal/service/openai_ws_http_bridge.go | 4 ++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/backend/internal/handler/openai_issue914_legacy_test.go b/backend/internal/handler/openai_issue914_legacy_test.go index 9ef2c5474a97..a3ffc7e44672 100644 --- a/backend/internal/handler/openai_issue914_legacy_test.go +++ b/backend/internal/handler/openai_issue914_legacy_test.go @@ -188,17 +188,22 @@ func issue914WSNode(t *testing.T, kind, mode, upstream string, cache service.Gat func TestIssue914LegacyWSCompatibility(t *testing.T) { for _, kind := range []string{service.AccountTypeOAuth, service.AccountTypeAPIKey} { for _, mode := range []string{service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeHTTPBridge} { - for _, change := range []string{"metadata", "declaration_id", "compaction_order", "custom_bridge", "instructions", "window"} { + for _, change := range []string{"metadata", "declaration_id", "compaction_order", "custom_bridge", "instructions", "window", "plaintext_instructions"} { t.Run(kind+"/"+mode+"/"+change, func(t *testing.T) { clients := issue805Redis(t) u := &issue805Oracle{} srv := u.server(t) h := issue914WSNode(t, kind, mode, srv.URL, repository.NewGatewayCache(clients())) body := issue914Body(t, change, true) + if change == "plaintext_instructions" { + var err error + body, err = sjson.Delete(body, "input.0") + require.NoError(t, err) + } body, err := sjson.Set(body, "type", "response.create") require.NoError(t, err) turns := 1 - if change == "instructions" || change == "window" { + if change == "instructions" || change == "window" || change == "plaintext_instructions" { turns = 2 } for turn := 0; turn < turns; turn++ { diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index 810845ddd78d..03f32ff7fe36 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -575,7 +575,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( // store=false cannot carry a provider-side response pointer over HTTP. // The ingress has reconstructed this same bridge's history; retain an immutable // proof before request construction, rather than trusting final wire bytes. - if account.IsOpenAIApiKey() && s.settingService != nil && s.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx) { + if !s.openAILegacyCompatibility() && account.IsOpenAIApiKey() && s.settingService != nil && s.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx) { source, _ := ctx.Value(openAIWSAgentSourceKey{}).([]byte) previous := gjson.GetBytes(source, "previous_response_id").String() // The ingress has already stripped invalid item IDs. Derive that one @@ -888,7 +888,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( } applyOpenAIQueueTiming(result, openAIWSQueueArrival(ctx), forwardStart, turnStart, "ws_frame_http_bridge", "first_forward_including_internal_retries") replayInput := replayCollector.Items() - if account.IsOpenAIApiKey() && s.settingService != nil && s.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx) { + if !s.openAILegacyCompatibility() && account.IsOpenAIApiKey() && s.settingService != nil && s.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx) { // Same-response reconstruction needs assistant messages as well as // calls. RawMessage storage preserves numbers and tool schemas. replayInput = replayCollector.AllItems() From ca5e4efc770dddafc077fed9a7e91d10a2d3efe9 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Thu, 19 Nov 2026 01:24:50 +0800 Subject: [PATCH 3/7] =?UTF-8?q?test:=20=E8=A1=A5=E9=BD=90=E5=85=BC?= =?UTF-8?q?=E5=AE=B9=E6=A8=A1=E5=BC=8F=20Lite=20=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=E4=B8=8E=E9=BB=98=E8=AE=A4=E7=AD=96=E7=95=A5=E5=AF=B9=E7=85=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../handler/openai_issue914_legacy_test.go | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/backend/internal/handler/openai_issue914_legacy_test.go b/backend/internal/handler/openai_issue914_legacy_test.go index a3ffc7e44672..3765d71b1312 100644 --- a/backend/internal/handler/openai_issue914_legacy_test.go +++ b/backend/internal/handler/openai_issue914_legacy_test.go @@ -12,6 +12,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/repository" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/Wei-Shaw/sub2api/internal/testutil" "github.com/stretchr/testify/require" @@ -108,7 +109,11 @@ func issue914HTTPNode(t *testing.T, u *issue805Oracle, legacy bool, accounts []s upstream := &issue842Transport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target} usage := &readable409UsageRepo{} clients := issue805Redis(t) - h := newOpenAIResponsesFailoverTestHandlerWithUsage(t, upstream, repository.NewGatewayCache(clients()), service.NewSettingService(&issue842Settings{values: issue914Settings()}, cfg), usage, accounts...) + settings := issue914Settings() + if !legacy { + settings = issue892Settings() + } + h := newOpenAIResponsesFailoverTestHandlerWithUsage(t, upstream, repository.NewGatewayCache(clients()), service.NewSettingService(&issue842Settings{values: settings}, cfg), usage, accounts...) h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true issue914Policy(t, h.cfg, legacy) return h, usage @@ -122,6 +127,9 @@ func TestIssue914LegacyHTTPCompatibility(t *testing.T) { h, usage := issue914HTTPNode(t, u, true, issue715Accounts()[:1]) body := issue914Body(t, change, stream) c, rec := newIssue715Context(t, body) + key, exists := c.Get(string(middleware.ContextKeyAPIKey)) + require.True(t, exists) + key.(*service.APIKey).Group.AllowImageGeneration = true c.Request.Header.Set("session_id", "fixture-914") if change == "lite_namespace" || change == "lite_search" { c.Request.Header.Set("X-OpenAI-Internal-Codex-Responses-Lite", "true") @@ -188,13 +196,18 @@ func issue914WSNode(t *testing.T, kind, mode, upstream string, cache service.Gat func TestIssue914LegacyWSCompatibility(t *testing.T) { for _, kind := range []string{service.AccountTypeOAuth, service.AccountTypeAPIKey} { for _, mode := range []string{service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeHTTPBridge} { - for _, change := range []string{"metadata", "declaration_id", "compaction_order", "custom_bridge", "instructions", "window", "plaintext_instructions"} { + for _, change := range []string{"metadata", "declaration_id", "schema", "reserved_name", "lite_namespace", "lite_search", "compaction_order", "custom_bridge", "instructions", "window", "plaintext_instructions"} { t.Run(kind+"/"+mode+"/"+change, func(t *testing.T) { clients := issue805Redis(t) u := &issue805Oracle{} srv := u.server(t) h := issue914WSNode(t, kind, mode, srv.URL, repository.NewGatewayCache(clients())) body := issue914Body(t, change, true) + if change == "lite_namespace" || change == "lite_search" { + var err error + body, err = sjson.Set(body, "client_metadata.ws_request_header_x_openai_internal_codex_responses_lite", "true") + require.NoError(t, err) + } if change == "plaintext_instructions" { var err error body, err = sjson.Delete(body, "input.0") From d6cc72023231751724265240aba7b43628a44bc2 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Thu, 19 Nov 2026 01:26:11 +0800 Subject: [PATCH 4/7] =?UTF-8?q?test:=20=E8=A6=86=E7=9B=96=20API-key=20HTTP?= =?UTF-8?q?=20=E4=B8=8E=E5=85=BC=E5=AE=B9=E6=A8=A1=E5=BC=8F=E6=9D=83?= =?UTF-8?q?=E9=99=90=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../handler/openai_issue914_legacy_test.go | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/backend/internal/handler/openai_issue914_legacy_test.go b/backend/internal/handler/openai_issue914_legacy_test.go index 3765d71b1312..fb3ef44ad386 100644 --- a/backend/internal/handler/openai_issue914_legacy_test.go +++ b/backend/internal/handler/openai_issue914_legacy_test.go @@ -122,6 +122,10 @@ func issue914HTTPNode(t *testing.T, u *issue805Oracle, legacy bool, accounts []s func TestIssue914LegacyHTTPCompatibility(t *testing.T) { for _, change := range []string{"metadata", "schema", "reserved_name", "lite_namespace", "lite_search", "system", "namespace", "orphan", "empty_image", "compaction", "spark", "spark_image"} { for _, stream := range []bool{false, true} { + // Non-streaming compaction is a separate unary endpoint, not native v2. + if change == "compaction" && !stream { + continue + } t.Run(fmt.Sprintf("%s/stream=%t", change, stream), func(t *testing.T) { u := &issue805Oracle{} h, usage := issue914HTTPNode(t, u, true, issue715Accounts()[:1]) @@ -292,3 +296,34 @@ func TestIssue914LegacyAccountPoolAndCancellation(t *testing.T) { }) } } + +func TestIssue914LegacyAPIKeyHTTP(t *testing.T) { + for _, change := range []string{"schema", "namespace", "empty_image", "custom_bridge"} { + t.Run(change, func(t *testing.T) { + u := &issue805Oracle{} + h, usage := issue914HTTPNode(t, u, true, issue715AccountsOfType(service.AccountTypeAPIKey)[:1]) + answer := issue758Request(t, h, issue914Body(t, change, true)) + require.Equal(t, http.StatusOK, answer.Code, answer.Body.String()) + issue758CompletedResponse(t, answer.Body.String(), true) + u.mu.Lock() + count := len(u.frames) + u.mu.Unlock() + require.Equal(t, 1, count) + require.Eventually(t, func() bool { return len(usage.snapshot()) == 1 }, 2*time.Second, 10*time.Millisecond) + require.EqualValues(t, 5, usage.snapshot()[0].InputTokens) + }) + } +} + +func TestIssue914LegacyKeepsImagePermission(t *testing.T) { + u := &issue805Oracle{} + h, _ := issue914HTTPNode(t, u, true, issue715Accounts()[:1]) + body := issue914Body(t, "metadata", false) + body, err := sjson.SetRaw(body, "tools", `[{"type":"image_generation"}]`) + require.NoError(t, err) + answer := issue758Request(t, h, body) + require.Equal(t, http.StatusForbidden, answer.Code, answer.Body.String()) + u.mu.Lock() + defer u.mu.Unlock() + require.Empty(t, u.frames) +} From 53c648d52b51c4026346f2bc3cc4d74d501a9ec0 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Thu, 19 Nov 2026 01:26:54 +0800 Subject: [PATCH 5/7] =?UTF-8?q?test:=20=E4=BD=BF=E7=94=A8=20Codex=20?= =?UTF-8?q?=E5=AE=9E=E9=99=85=E7=AA=97=E5=8F=A3=E5=AD=97=E6=AE=B5=E9=AA=8C?= =?UTF-8?q?=E8=AF=81=E7=BB=AD=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/handler/openai_issue914_legacy_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/internal/handler/openai_issue914_legacy_test.go b/backend/internal/handler/openai_issue914_legacy_test.go index fb3ef44ad386..f04617118cc1 100644 --- a/backend/internal/handler/openai_issue914_legacy_test.go +++ b/backend/internal/handler/openai_issue914_legacy_test.go @@ -48,7 +48,7 @@ func issue914Body(t *testing.T, change string, stream bool) string { } set("store", false) set("instructions", "Continue the synthetic task.") - set("client_metadata.window_id", "fixture-window-1") + set("client_metadata.x-codex-window-id", "fixture-window-1") switch change { case "metadata": set("input.0.internal_chat_message_metadata_passthrough", map[string]any{"turn_id": "fixture-turn"}) @@ -232,7 +232,7 @@ func TestIssue914LegacyWSCompatibility(t *testing.T) { require.NoError(t, err) field := "instructions" if change == "window" { - field = "client_metadata.window_id" + field = "client_metadata.x-codex-window-id" } body, err = sjson.Set(body, field, "fixture-next-turn") require.NoError(t, err) From 2bb12e9735f905096dbb661ff2b20147e842d8b5 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Thu, 19 Nov 2026 01:41:43 +0800 Subject: [PATCH 6/7] =?UTF-8?q?test:=20=E4=BF=AE=E5=A4=8D=E6=97=A7?= =?UTF-8?q?=E7=89=88=E6=81=A2=E5=A4=8D=E5=9F=BA=E7=BA=BF=E7=9A=84=E5=9B=9E?= =?UTF-8?q?=E5=BD=92=E8=A3=85=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/scripts/prepare-ws-owner-red-fixtures.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/scripts/prepare-ws-owner-red-fixtures.sh b/.github/scripts/prepare-ws-owner-red-fixtures.sh index 95264f15010f..581bd4f2da5a 100644 --- a/.github/scripts/prepare-ws-owner-red-fixtures.sh +++ b/.github/scripts/prepare-ws-owner-red-fixtures.sh @@ -70,6 +70,10 @@ exclude_new_fixture backend/internal/service/openai_ws_owner_conflict_test.go # here; its own RED and every clean candidate GREEN retain both exact files. exclude_new_fixture backend/internal/handler/openai_issue892_timezone_test.go exclude_new_fixture backend/internal/service/openai_issue892_timezone_test.go +# Issue914 uses the same newer HTTP/WS harness and replay entry points. +# These tests are unrelated to the old selected defect and remain in GREEN. +exclude_new_fixture backend/internal/handler/openai_issue914_legacy_test.go +exclude_new_fixture backend/internal/service/openai_issue914_legacy_test.go # Very old Issue805 baselines intentionally exclude the later readable harness. # Only that dependency absence permits removing its new consumer as well. if ! test -f "$tree/backend/internal/handler/openai_409_ws_rebuild_test.go"; then From 32f8f4bda7f8a749aa10be4281d2cf538a3641a1 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Thu, 19 Nov 2026 02:18:45 +0800 Subject: [PATCH 7/7] =?UTF-8?q?test:=20=E5=AF=B9=E9=BD=90=E5=8E=86?= =?UTF-8?q?=E5=8F=B2=E5=9F=BA=E7=BA=BF=E5=A4=B9=E5=85=B7=E5=B9=B6=E6=89=A9?= =?UTF-8?q?=E5=B1=95=E6=95=B4=E5=8C=85=E6=B5=8B=E8=AF=95=E6=97=B6=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/ci/README.md | 2 ++ .github/ci/go_tests.py | 2 +- .../scripts/upstream-v0222-red-fixtures.txt | 18 ++++++++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/.github/ci/README.md b/.github/ci/README.md index 2f654e1c6ead..f5966d3a0128 100644 --- a/.github/ci/README.md +++ b/.github/ci/README.md @@ -25,6 +25,8 @@ python3 -m unittest discover -s .github/ci -p 'test_*.py' -v `.github/ci/go_tests.py` 从 `go list -tags=unit ./...` 动态发现全部包,再按 `go-test-weights.json` 的历史耗时从重到轻分配。新包按 1 秒估算并自动纳入;无测试包也保留。权重仅影响分配,不筛选测试。初始权重来自 [2026-11-17 的成功运行](https://github.com/ranxi2001/sub2api/actions/runs/44150112506),其中 handler 581.520 秒、service 363.216 秒。包内用例尚未进一步拆分,因此单个重包仍可能决定单元测试关键路径。 +单元测试的每个 package 显式使用 `-timeout=20m`,容纳已接近 Go 默认 10 分钟上限的 handler 全量套件;四分片仍运行全部用例,job 的 40 分钟上限继续生效。 + 运行仍经过 backend Makefile:`test-unit-packages` 接收包列表,嵌套收款模块的 `test-collection` 在第 0 片执行一次;默认 `make test-unit` 仍包含两者。单元测试保留 Go 测试结果缓存。集成测试保留 PostgreSQL/Redis、Docker testcontainers 和 `GOFLAGS=-p=1`,增加 `-count=1` 确保外部服务检查实际执行。原先单独运行的 `TestUsageTrendAggregateTimezone` 已包含在完整集成套件内,不再重复启动仓库集成环境。每个单元分片和集成 runner 都安装并检查 redis-server,分别满足快照适配器和认证缓存跨进程 Pub/Sub 用例;服务容器不能替代这些用例自行启动的独立 Redis 进程。 缓存按 OS、架构、go.mod/go.sum、suite/分片与源码 SHA 分隔,按同一依赖和分片前缀恢复最近的编译缓存;各分片不竞争同一写入 key。相同 key 的成功重跑可直接命中。分片缓存未命中时,使用与 setup-go 相同的绝对路径和键格式,按当前 Go 版本/runner 镜像回退读取 production 已有的共享缓存(先匹配 go.sum,再匹配版本前缀),只向分片 key 写入;避免新 PR 因无法读取其他 PR 的专属缓存而完全冷启动。独立 runner 会增加总资源和冷启动开销;这里不变更 Runner 账户配额,也不使用生产服务器编译。 diff --git a/.github/ci/go_tests.py b/.github/ci/go_tests.py index 4e0c4b8ac7fc..b3b539f93894 100644 --- a/.github/ci/go_tests.py +++ b/.github/ci/go_tests.py @@ -103,7 +103,7 @@ def main(): if args.shard == 0: report['runs'].append(run_command(['make', 'test-collection', 'TEST_FLAGS=-json'], output, 'collection')) if shards[args.shard]: - report['runs'].append(run_command(['make', 'test-unit-packages', 'TEST_FLAGS=-json', + report['runs'].append(run_command(['make', 'test-unit-packages', 'TEST_FLAGS=-json -timeout=20m', 'TEST_PACKAGES=' + ' '.join(shards[args.shard])], output, 'unit')) else: report['runs'].append(run_command(['make', 'test-integration', 'TEST_FLAGS=-json -count=1'], output, 'integration')) diff --git a/.github/scripts/upstream-v0222-red-fixtures.txt b/.github/scripts/upstream-v0222-red-fixtures.txt index eb12719d5285..9574fc240232 100644 --- a/.github/scripts/upstream-v0222-red-fixtures.txt +++ b/.github/scripts/upstream-v0222-red-fixtures.txt @@ -142,3 +142,21 @@ backend/migrations/group_usage_rollup_migration_test.go # Restore existing profit tests; omit provider-site tests only when absent there. backend/internal/service/profit_operations_test.go backend/internal/service/provider_profit_site_test.go + +# Later cache-tier, relogin and model-policy tests need their matching production APIs. +# Full old-source overlays use baseline fixtures; current-head GREEN retains them. +backend/internal/service/anthropic_prompt_total_test.go +backend/internal/service/antigravity_gateway_service_test.go +backend/internal/service/channel_pricing_multipliers_test.go +backend/internal/service/codex_account_availability_test.go +backend/internal/service/gateway_cache_compatibility_boundary_test.go +backend/internal/service/gateway_cache_creation_usage_test.go +backend/internal/service/gateway_cache_ttl_override_test.go +backend/internal/service/openai_cache_write_ttl_test.go +backend/internal/service/openai_gateway_native_cache_creation_test.go +backend/internal/service/openai_gpt62_fork_test.go +backend/internal/service/openai_json_object_field_edit_test.go +backend/internal/service/openai_relogin_settings_test.go +backend/internal/service/openai_subscription_long_context_test.go +backend/internal/service/openai_two_fa_login_test.go +backend/internal/service/upstream_batch_whitelist_identity_policy_test.go