From 243cec5e5b3036e0f6b0d153ef9e93c262d238f0 Mon Sep 17 00:00:00 2001 From: akihitohyh <79531840+akihitohyh@users.noreply.github.com> Date: Tue, 10 Nov 2026 12:40:13 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=8E=9F=E9=80=9A=E9=81=93=E6=9C=AA?= =?UTF-8?q?=E5=8F=98=E6=97=B6=E6=94=BE=E8=A1=8C=E5=8A=A0=E5=AF=86=E4=BB=A3?= =?UTF-8?q?=E7=90=86=E4=BC=9A=E8=AF=9D=E7=9A=84=E5=8E=9F=E7=94=9F=E5=8E=8B?= =?UTF-8?q?=E7=BC=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 已登记归属的加密 agent_message 会话在 Codex 自动压缩(原生 remote compaction v2)时,发送前门禁对所有压缩请求一律返回 encrypted_agent_recovery_route_changed,即使原账号、凭据和路由都没有变, 长会话到达压缩阈值后无法继续。 - 原生 v2 压缩不再因"是压缩"被拒;仍要求回到原 owner,并在真实发送前 复核账号配置、URL、身份头、模型和完整 opaque 项,只容忍网关给压缩 回合补注的 remote_compaction_v2 协商 token(API Key 普通回合没有该头)。 - 压缩仍不登记、不刷新归属;owner 不可用或凭据变化照旧拒绝。 - legacy /responses/compact 和 DeepSeek 压缩转 Chat Completions 仍在契约外。 Co-Authored-By: Claude Opus 5.5 --- .../openai_issue715_compaction_test.go | 146 ++++++++++++++++++ .../service/openai_agent_message_recovery.go | 99 +++++++++++- ..._agent_message_recovery_compaction_test.go | 54 +++++++ 3 files changed, 294 insertions(+), 5 deletions(-) create mode 100644 backend/internal/handler/openai_issue715_compaction_test.go create mode 100644 backend/internal/service/openai_agent_message_recovery_compaction_test.go diff --git a/backend/internal/handler/openai_issue715_compaction_test.go b/backend/internal/handler/openai_issue715_compaction_test.go new file mode 100644 index 000000000000..3d2b9853a69e --- /dev/null +++ b/backend/internal/handler/openai_issue715_compaction_test.go @@ -0,0 +1,146 @@ +//go:build unit + +package handler + +import ( + "fmt" + "net/http" + "strings" + "sync" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// Codex sends remote compaction v2 on the bare streaming /responses wire once a +// long agent session reaches its auto-compaction threshold. The history still +// carries the proven opaque agent_message items. +func issue715CompactionBody() string { + return strings.TrimSuffix(issue715Body(true, true), "]}") + `,{"type":"compaction_trigger"}]}` +} + +type issue715HeaderUpstream struct { + *issue715Upstream + mu sync.Mutex + headers []http.Header +} + +func (u *issue715HeaderUpstream) Do(req *http.Request, proxyURL string, accountID int64, concurrency int) (*http.Response, error) { + u.mu.Lock() + u.headers = append(u.headers, req.Header.Clone()) + u.mu.Unlock() + return u.issue715Upstream.Do(req, proxyURL, accountID, concurrency) +} + +func issue715AccountsOfType(accountType string) []service.Account { + accounts := issue715Accounts() + if accountType == service.AccountTypeAPIKey { + for i := range accounts { + accounts[i].Type = service.AccountTypeAPIKey + accounts[i].Credentials = map[string]any{ + "api_key": fmt.Sprintf("fixture-key-%d", accounts[i].ID), + "base_url": "https://api.openai.com", + } + } + } + return accounts +} + +func issue715PathRequest(t *testing.T, handler *OpenAIGatewayHandler, path, body string) (int, string) { + t.Helper() + c, rec := newIssue715Context(t, body) + c.Request.URL.Path = path + c.Request.Header.Set("session_id", "fixture-715-thread") + key, _ := c.Get(string(middleware.ContextKeyAPIKey)) + key.(*service.APIKey).ID = 99 + handler.Responses(c) + return rec.Code, rec.Body.String() +} + +func TestIssue715HTTPNativeCompactionReachesProvenOwner(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, accountType := range []string{service.AccountTypeOAuth, service.AccountTypeAPIKey} { + t.Run(accountType, func(t *testing.T) { + accounts := issue715AccountsOfType(accountType) + upstream := &issue715HeaderUpstream{issue715Upstream: &issue715Upstream{}} + handler := newOpenAIResponsesFailoverTestHandler(t, upstream, accounts...) + status, first := issue715Request(t, handler, issue715Body(false, true), 99, "fixture-715-thread", false) + require.Equal(t, 200, status, first) + accounts[0].Priority, accounts[1].Priority = 100, 0 + + status, answer := issue715Request(t, handler, issue715CompactionBody(), 99, "fixture-715-thread", false) + + require.Equal(t, 200, status, answer) + require.NotContains(t, answer, "encrypted_agent_recovery_") + require.Equal(t, []int64{1, 1}, upstream.ids, "compaction must stay on the proven owner despite scheduler drift") + sent := upstream.bodies[1] + require.Contains(t, string(sent), "fixture-task-reference-715", "compaction must carry the intact task") + require.Equal(t, "compaction_trigger", gjson.GetBytes(sent, "input.@reverse.0.type").String()) + require.Contains(t, upstream.headers[1].Get("x-codex-beta-features"), "remote_compaction_v2") + }) + } +} + +func TestIssue715HTTPNativeCompactionDoesNotRelaxOwnerChecks(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, change := range []string{"credentials", "disabled"} { + t.Run(change, func(t *testing.T) { + accounts := issue715Accounts() + upstream := &issue715Upstream{} + handler := newOpenAIResponsesFailoverTestHandler(t, upstream, accounts...) + status, _ := issue715Request(t, handler, issue715Body(false, true), 99, "fixture-715-thread", false) + require.Equal(t, 200, status) + accounts[0].Priority, accounts[1].Priority = 100, 0 + code := "encrypted_agent_recovery_route_changed" + if change == "credentials" { + accounts[0].Credentials = map[string]any{"access_token": "fixture-rotated"} + } else { + accounts[0].Schedulable = false + code = "encrypted_agent_recovery_owner_unavailable" + } + + status, answer := issue715Request(t, handler, issue715CompactionBody(), 99, "fixture-715-thread", false) + + require.NotEqual(t, 200, status, answer) + require.Contains(t, answer, code) + require.Equal(t, []int64{1}, upstream.ids, "a changed or unavailable owner must not receive or leak the compaction") + }) + } +} + +func TestIssue715HTTPLegacyCompactStaysOutsideContract(t *testing.T) { + gin.SetMode(gin.TestMode) + accounts := issue715Accounts() + upstream := &issue715Upstream{} + handler := newOpenAIResponsesFailoverTestHandler(t, upstream, accounts...) + status, _ := issue715Request(t, handler, issue715Body(false, false), 99, "fixture-715-thread", false) + require.Equal(t, 200, status) + + status, answer := issue715PathRequest(t, handler, "/v1/responses/compact", issue715Body(true, false)) + + require.Equal(t, http.StatusConflict, status, answer) + require.Contains(t, answer, "encrypted_agent_recovery_route_changed") + require.Equal(t, []int64{1}, upstream.ids) +} + +func TestIssue715HTTPNativeCompactionNeverGrantsOwner(t *testing.T) { + gin.SetMode(gin.TestMode) + accounts := issue715Accounts() + upstream := &issue715Upstream{} + handler := newOpenAIResponsesFailoverTestHandler(t, upstream, accounts...) + // No prior proof: an unseen task compacts through ordinary admission and + // must not turn that compaction into an ownership observation. + status, answer := issue715Request(t, handler, issue715CompactionBody(), 99, "fixture-715-thread", false) + require.Equal(t, 200, status, answer) + require.Equal(t, []int64{1}, upstream.ids) + accounts[0].Priority, accounts[1].Priority = 100, 0 + + issue715Request(t, handler, issue715Body(true, true), 99, "fixture-715-thread", false) + + require.GreaterOrEqual(t, len(upstream.ids), 2) + require.Equal(t, int64(2), upstream.ids[1], "compaction is not a compatibility observation") +} diff --git a/backend/internal/service/openai_agent_message_recovery.go b/backend/internal/service/openai_agent_message_recovery.go index a3bab8cc7715..7b72f5a26087 100644 --- a/backend/internal/service/openai_agent_message_recovery.go +++ b/backend/internal/service/openai_agent_message_recovery.go @@ -50,6 +50,7 @@ type openAIAgentRecoveryRequest struct { delivery *openAIAgentRecoveryDelivery outputs [][32]byte disallowLearning bool + nativeCompaction bool lookupErr error toolResult bool known map[[32]byte]bool @@ -73,7 +74,8 @@ func (s *OpenAIGatewayService) WithOpenAIAgentMessageRecovery(ctx context.Contex keyID := getAPIKeyIDFromContext(c) request.keyID = keyID request.userID = openAIAgentRecoveryHTTPUser(c, keyID) - request.disallowLearning = isOpenAIResponsesCompactPath(c) || isOpenAINativeCompactionV2(c) + request.nativeCompaction = isOpenAINativeCompactionV2(c) + request.disallowLearning = isOpenAIResponsesCompactPath(c) || request.nativeCompaction if s == nil || keyID <= 0 || sessionHash == "" || model == "" { return context.WithValue(ctx, openAIAgentRecoveryContextKey{}, request) } @@ -227,10 +229,15 @@ func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryDispatch(ctx context.Cont return nil } model := gjson.GetBytes(body, "model").String() + // Native remote compaction v2 stays on the proven HTTP Responses route and is + // rechecked against the owner's exact wire at send time. The legacy + // /responses/compact bridge rewrites the body and endpoint, so it remains + // outside this contract. if !account.IsOpenAI() || account.HasManagedOpenAIConnections() || account.AuthConnectionID != "" || account.IsOpenAIPassthroughEnabled() || account.IsCopilotSDKEnabled() || account.IsSIWCEnabled() || account.IsExcelBPSEnabledForModel(model) || account.IsPrismBrowserEnabledForModel(model) || - isOpenAIResponsesCompactPath(c) || isOpenAINativeCompactionV2(c) || + isOpenAIResponsesCompactPath(c) || + (isOpenAINativeCompactionV2(c) && shouldForwardDeepSeekResponsesCompactViaChatCompletions(account, body)) || shouldForwardDeepSeekResponsesLiteViaChatCompletions(account, body) || s.resolveUpstreamProtocolFor(ctx, account, APIProtocolResponses, upstreamRoutingModel(account, body, "")) != APIProtocolResponses { return openAIAgentRecoveryError("route_changed") @@ -252,6 +259,9 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con return noop, nil } if request.disallowLearning { + if request.nativeCompaction && request.owner != nil { + return noop, s.checkOpenAIAgentRecoveryCompaction(ctx, account, req) + } return noop, nil } if request.delivery != nil { @@ -312,9 +322,8 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con return noop, nil } } - wire, _ := json.Marshal([]any{req.URL.String(), openAIAgentRecoveryWireHeaders(req.Header), - gjson.GetBytes(body, "model").String()}) - binding := openAIAgentRecoveryBinding{accountID: account.ID, config: openAIAgentRecoveryConfig(account, request.model), wire: sha256.Sum256(wire), expiresAt: time.Now().Add(s.openAIWSSessionStickyTTL())} + wire := openAIAgentRecoveryWireDigest(req.URL.String(), req.Header, gjson.GetBytes(body, "model").String()) + binding := openAIAgentRecoveryBinding{accountID: account.ID, config: openAIAgentRecoveryConfig(account, request.model), wire: wire, expiresAt: time.Now().Add(s.openAIWSSessionStickyTTL())} if request.owner != nil && !sameOpenAIAgentRecoveryRoute(*request.owner, binding) { return noop, openAIAgentRecoveryError("wire_changed") } @@ -448,6 +457,86 @@ func OpenAIAgentToolResultContinuation(ctx context.Context) bool { return r != nil && r.owner != nil && r.toolResult } +// Native remote compaction v2 consumes an already proven task but proves no new +// route, so it is never published. It must reach the recorded owner with the +// same account configuration, URL, identity headers, model and intact opaque +// items. The only tolerated wire difference is the remote_compaction_v2 +// negotiation token that the gateway adds to every v2 compaction turn (API key +// routes do not advertise it on ordinary turns). +func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryCompaction(ctx context.Context, account *Account, req *http.Request) error { + request := openAIAgentRecoveryFromContext(ctx) + if request == nil || request.owner == nil { + return nil + } + if err := s.checkOpenAIAgentRecoveryAccount(ctx, account); err != nil { + return err + } + if !account.IsOpenAI() || account.HasManagedOpenAIConnections() || account.AuthConnectionID != "" || + account.IsOpenAIPassthroughEnabled() || account.IsCopilotSDKEnabled() || account.IsSIWCEnabled() || + req == nil || req.URL == nil || req.GetBody == nil { + return openAIAgentRecoveryError("wire_changed") + } + reader, err := req.GetBody() + if err != nil { + return openAIAgentRecoveryError("wire_changed") + } + body, err := io.ReadAll(reader) + _ = reader.Close() + if err != nil || !utf8.Valid(body) || !openAIEncryptedJSONUnambiguous(body) { + return openAIAgentRecoveryError("wire_changed") + } + items := openAIAgentRecoveryItemDigests(body) + if len(items) != len(request.items) { + return openAIAgentRecoveryError("wire_changed") + } + for i := range items { + if items[i] != request.items[i] { + return openAIAgentRecoveryError("wire_changed") + } + } + model := gjson.GetBytes(body, "model").String() + url := req.URL.String() + if openAIAgentRecoveryWireDigest(url, req.Header, model) == request.owner.wire || + openAIAgentRecoveryWireDigest(url, withoutOpenAIRemoteCompactionV2Feature(req.Header), model) == request.owner.wire { + return nil + } + return openAIAgentRecoveryError("wire_changed") +} + +func openAIAgentRecoveryWireDigest(url string, header http.Header, model string) [32]byte { + wire, _ := json.Marshal([]any{url, openAIAgentRecoveryWireHeaders(header), model}) + return sha256.Sum256(wire) +} + +// withoutOpenAIRemoteCompactionV2Feature removes only the compaction +// negotiation token; every other beta feature and header stays significant. +func withoutOpenAIRemoteCompactionV2Feature(header http.Header) http.Header { + stripped := header.Clone() + for key, values := range stripped { + if !strings.EqualFold(key, "x-codex-beta-features") { + continue + } + kept := make([]string, 0, len(values)) + for _, value := range values { + tokens := make([]string, 0, 2) + for _, token := range strings.Split(value, ",") { + if token = strings.TrimSpace(token); token != "" && token != openAIRemoteCompactionV2Feature { + tokens = append(tokens, token) + } + } + if len(tokens) > 0 { + kept = append(kept, strings.Join(tokens, ",")) + } + } + if len(kept) == 0 { + delete(stripped, key) + } else { + stripped[key] = kept + } + } + return stripped +} + // Header overrides may retain wire casing rather than net/http's canonical // spelling. Header.Get/Values would miss those actual outbound identity fields. // Include every spelling/value deterministically, including duplicate variants. diff --git a/backend/internal/service/openai_agent_message_recovery_compaction_test.go b/backend/internal/service/openai_agent_message_recovery_compaction_test.go new file mode 100644 index 000000000000..d37341dacc98 --- /dev/null +++ b/backend/internal/service/openai_agent_message_recovery_compaction_test.go @@ -0,0 +1,54 @@ +//go:build unit + +package service + +import ( + "net/http" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestWithoutOpenAIRemoteCompactionV2FeatureKeepsOtherWireIdentity(t *testing.T) { + header := http.Header{} + header.Set("Authorization", "Bearer fixture") + header["x-codex-beta-features"] = []string{"alpha, remote_compaction_v2 ,beta", "remote_compaction_v2"} + + stripped := withoutOpenAIRemoteCompactionV2Feature(header) + + require.Equal(t, []string{"alpha,beta"}, stripped["x-codex-beta-features"]) + require.Equal(t, "Bearer fixture", stripped.Get("Authorization")) + require.Equal(t, []string{"alpha, remote_compaction_v2 ,beta", "remote_compaction_v2"}, header["x-codex-beta-features"], "the outbound request header must not be modified") + + onlyV2 := http.Header{} + ensureOpenAIRemoteCompactionV2BetaFeature(onlyV2) + require.Empty(t, withoutOpenAIRemoteCompactionV2Feature(onlyV2), "an API key compaction turn differs from its ordinary turn only by this token") +} + +func TestOpenAIAgentRecoveryCompactionWireToleratesOnlyV2Negotiation(t *testing.T) { + const url, model = "https://api.openai.com/v1/responses", "gpt-5.1" + ordinary := http.Header{} + ordinary.Set("Authorization", "Bearer fixture") + owner := openAIAgentRecoveryWireDigest(url, ordinary, model) + + compaction := ordinary.Clone() + ensureOpenAIRemoteCompactionV2BetaFeature(compaction) + require.NotEqual(t, owner, openAIAgentRecoveryWireDigest(url, compaction, model)) + require.Equal(t, owner, openAIAgentRecoveryWireDigest(url, withoutOpenAIRemoteCompactionV2Feature(compaction), model)) + + for name, mutate := range map[string]func(http.Header) (string, string){ + "credential": func(h http.Header) (string, string) { h.Set("Authorization", "Bearer other"); return url, model }, + "feature": func(h http.Header) (string, string) { + h.Set("x-codex-beta-features", "other,remote_compaction_v2") + return url, model + }, + "url": func(http.Header) (string, string) { return "https://other.example/v1/responses", model }, + "model": func(http.Header) (string, string) { return url, "gpt-5.1-mini" }, + } { + t.Run(name, func(t *testing.T) { + changed := compaction.Clone() + changedURL, changedModel := mutate(changed) + require.NotEqual(t, owner, openAIAgentRecoveryWireDigest(changedURL, withoutOpenAIRemoteCompactionV2Feature(changed), changedModel)) + }) + } +}