Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 146 additions & 0 deletions backend/internal/handler/openai_issue715_compaction_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
99 changes: 94 additions & 5 deletions backend/internal/service/openai_agent_message_recovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
}
Expand Down Expand Up @@ -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")
Expand All @@ -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 {
Expand Down Expand Up @@ -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")
}
Expand Down Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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))
})
}
}
Loading