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
5 changes: 5 additions & 0 deletions .github/scripts/upstream-v0222-red-fixtures.txt
Original file line number Diff line number Diff line change
Expand Up @@ -169,3 +169,8 @@ backend/internal/service/image_usage_billing_test.go
backend/internal/service/account_ops_balance_notification_test.go
backend/internal/service/grok_rate_limit_history_test.go
backend/internal/service/new_api_cost_test.go
backend/internal/service/new_api_wallet_test.go

# Controls diagnostics require the newer recovery APIs, not historical RED sources.
backend/internal/service/openai_409_controls_diagnostics_test.go
backend/internal/handler/openai_owner_conflict_diagnostics_test.go
3 changes: 3 additions & 0 deletions .github/workflows/rebuilt-request-dispatch.yml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ jobs:
test "$(git hash-object "$target")" = "$expected"
echo "$target compatibility=$source blob=$expected" >> "$RUNNER_TEMP/dispatch-compatibility.txt"
done
# These candidate-only diagnostic tests require APIs absent from the pinned RED source.
rm backend/internal/service/openai_409_controls_diagnostics_test.go
bash "$GITHUB_WORKSPACE/.github/scripts/prepare-ws-owner-red-fixtures.sh" "$baseline" . HEAD | tee "$RUNNER_TEMP/dispatch-ws-owner-red-blobs.txt"
- name: Same network and tool-loop regressions
env:
Expand All @@ -87,6 +89,7 @@ jobs:
terminals={e['Test']:e['Action'] for e in events if 'Test' in e and e.get('Action') in ('pass','fail','skip')}
assert terminals and 'skip' not in terminals.values(), terminals
expected=[
'TestOpenAI409NamespaceProjectionPreservesNumbers',
'TestOpenAI409HTTPProjectionAndPassthrough/oauth/stream=false/internal_metadata',
'TestOpenAI409HTTPProjectionAndPassthrough/oauth/stream=true/message_namespace',
'TestOpenAI409HTTPProjectionAndPassthrough/apikey/stream=true/passthrough',
Expand Down
7 changes: 4 additions & 3 deletions .github/workflows/ws-readable-continuation.yml
Original file line number Diff line number Diff line change
Expand Up @@ -257,9 +257,10 @@ jobs:
# do not exclude the same files again in this loop.
# The later WS close diagnostic fixture also requires candidate-only APIs.
# Never change the selected ticket oracle or candidate GREEN tests.
# Balance notifications, Grok rate history, New API cost sync and
# Codex compression also have newer test-only API dependencies.
for target in backend/internal/service/temp_unsched_pending_test.go backend/internal/service/temp_unsched_stream_timing_test.go backend/internal/service/temp_unsched_ws_forward_test.go backend/internal/service/openai_auth_connection_status_test.go backend/internal/service/openai_auth_connections_account_type_test.go backend/internal/service/account_ops_balance_test.go backend/internal/service/openai_excel_bps_bridge_failure_test.go backend/internal/service/quality_5xx_immediate_test.go backend/internal/service/openai_ws_agent_recovery_test.go backend/internal/service/openai_excel_bps_search_business_test.go backend/internal/service/gemini_compat_response_format_test.go backend/internal/service/openai_ws_close_logging_test.go backend/internal/service/upstream_request_id_test.go backend/internal/service/account_ops_balance_notification_test.go backend/internal/service/grok_rate_limit_history_test.go backend/internal/service/new_api_cost_test.go backend/internal/service/openai_gateway_service_test.go; do
# The shared replay manifest already owns balance notifications,
# Grok rate history and New API cost sync. Only this loop owns
# the remaining Codex compression fixture.
for target in backend/internal/service/temp_unsched_pending_test.go backend/internal/service/temp_unsched_stream_timing_test.go backend/internal/service/temp_unsched_ws_forward_test.go backend/internal/service/openai_auth_connection_status_test.go backend/internal/service/openai_auth_connections_account_type_test.go backend/internal/service/account_ops_balance_test.go backend/internal/service/openai_excel_bps_bridge_failure_test.go backend/internal/service/quality_5xx_immediate_test.go backend/internal/service/openai_ws_agent_recovery_test.go backend/internal/service/openai_excel_bps_search_business_test.go backend/internal/service/gemini_compat_response_format_test.go backend/internal/service/openai_ws_close_logging_test.go backend/internal/service/upstream_request_id_test.go backend/internal/service/openai_gateway_service_test.go; do
candidate_blob=$(git rev-parse "$CANDIDATE_SHA:$target")
test "$(git hash-object "$tested_tree/$target")" = "$candidate_blob"
if git cat-file -e "$baseline:$target" 2>/dev/null; then
Expand Down
2 changes: 1 addition & 1 deletion backend/internal/handler/openai_agent_message_recovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,6 @@ func markOpenAIRecoveryFailure(c *gin.Context, recovery *service.OpenAIAgentReco
service.MarkOpsStreamErrorValue(c, service.OpsStreamError{
ErrType: recovery.ClientType(), Code: recovery.ClientCode(), Message: recovery.ClientMessage(),
IntendedStatus: recovery.HTTPStatus(), CountTowardsSLA: true, NonStream: protocol == "http",
RecoveryFailure: &service.OpsRecoveryFailure{Protocol: protocol, Phase: phase, RequestWritten: written, Subreason: recovery.InternalSubreason()},
RecoveryFailure: &service.OpsRecoveryFailure{Protocol: protocol, Phase: phase, RequestWritten: written, Subreason: recovery.InternalSubreason(), Controls: recovery.RecoveryControlsDiagnostic()},
})
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ func TestOwnerConflictPersistenceKeepsTurnAndSafeSubreason(t *testing.T) {
service.SetOpenAIClientTransport(c, service.OpenAIClientTransportWS)
service.BeginOpsStreamTurn(c, 53)
written := false
failure := &service.OpsRecoveryFailure{Protocol: "websocket", Phase: "before_dispatch", RequestWritten: &written}
failure := &service.OpsRecoveryFailure{Protocol: "websocket", Phase: "before_dispatch", RequestWritten: &written,
Controls: &service.OpsRecoveryControls{Observation: "complete", Snapshot: "oauth_replay", Tools: "changed", ToolChoice: "match", ParallelToolCalls: "match", Instructions: "match", DigestChanged: true}}
// Baseline RED compiles this independent fixture but does not run it;
// old production ignores the new diagnostic field during decoding.
encoded, err := json.Marshal(map[string]string{"Subreason": tc.detail})
Expand All @@ -41,6 +42,10 @@ func TestOwnerConflictPersistenceKeepsTurnAndSafeSubreason(t *testing.T) {
require.EqualValues(t, 53, gjson.Get(body, "error.turn").Int())
require.EqualValues(t, 101, gjson.Get(body, "error.wire_status").Int())
require.Equal(t, gjson.False, gjson.Get(body, "error.request_written").Type)
if tc.detail == "tool_unpaired" {
require.Equal(t, "changed", gjson.Get(body, "error.controls.tools").String())
require.Equal(t, "oauth_replay", gjson.Get(body, "error.controls.snapshot").String())
}
require.NotContains(t, body, "credential-and-body-canary")
})
}
Expand Down
3 changes: 3 additions & 0 deletions backend/internal/handler/ops_error_logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -1561,6 +1561,9 @@ func logOpsStreamErrorValue(c *gin.Context, ops *service.OpsService, wireStatus
if failure.RequestWritten != nil {
fields["request_written"] = *failure.RequestWritten
}
if failure.Controls != nil {
fields["controls"] = failure.Controls
}
if payload, err := json.Marshal(gin.H{"error": fields}); err == nil {
errorBody = string(payload)
}
Expand Down
94 changes: 94 additions & 0 deletions backend/internal/service/openai_409_controls_diagnostics_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package service

import (
"bytes"
"context"
"encoding/json"
"net/http"
"testing"

"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/stretchr/testify/require"
)

func TestOpenAI409OAuthReplayDiagnosesWebSearchHistoryProjection(t *testing.T) {
svc := &OpenAIGatewayService{cfg: &config.Config{}}
c, _ := newTurnStateTestContext(t, 715, "fixture-session")
body := []byte(`{"model":"gpt-6-astra","instructions":"continue from recorded search results","input":[{"type":"message","role":"user","content":"continue"},{"type":"web_search_call","id":"ws_1"}],"tools":[]}`)
r := &openAIAgentRecoveryRequest{
omittedHistory: true,
keyID: 715,
model: "gpt-6-astra",
session: "fixture-session",
inputDigest: openAIAgentRecoveryInputDigest(body),
replayControlsDigest: openAI409ControlsDigest(body),
}
ctx := context.WithValue(context.Background(), openAIAgentRecoveryContextKey{}, r)
var decoded map[string]any
require.NoError(t, decodeOpenAIJSONUseNumber(body, &decoded))
require.NoError(t, prepareOpenAI409OAuthReplay(ctx, c, decoded))

transformed := applyCodexOAuthTransformWithOptions(decoded, codexOAuthTransformOptions{
SkipDefaultInstructions: true,
PreserveReadableReplay: true,
})
require.NoError(t, transformed.Error)
require.Len(t, decoded["tools"], 1, "the normal Codex transform declares the historical web_search call")

wire, err := json.Marshal(decoded)
require.NoError(t, err)
req, err := http.NewRequest(http.MethodPost, "https://chatgpt.com/backend-api/codex/responses", bytes.NewReader(wire))
require.NoError(t, err)
_, err = svc.prepareOpenAIAgentRecoveryAttempt(ctx, &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeOAuth}, req)
var recovery *OpenAIAgentRecoveryError
require.ErrorAs(t, err, &recovery)
require.Equal(t, "controls_integrity", recovery.InternalSubreason())
report := recovery.RecoveryControlsDiagnostic()
require.NotNil(t, report)
require.Equal(t, "oauth_replay", report.Snapshot)
require.Equal(t, "changed", report.Tools)
require.Equal(t, "changed", report.ToolChoice)
require.Equal(t, "match", report.ParallelToolCalls)
require.Equal(t, "match", report.Instructions)
require.True(t, report.DigestChanged)
encoded, err := json.Marshal(report)
require.NoError(t, err)
require.NotContains(t, string(encoded), "ws_1")
require.NotContains(t, string(encoded), "continue from recorded search results")
}

func TestOpenAI409ControlDiagnosticReportsEachControlAndSessionMarker(t *testing.T) {
base := []byte(`{"tools":[],"tool_choice":"auto","parallel_tool_calls":true,"instructions":"private instruction"}`)
expected := openAI409FingerprintControls(base)
for _, tc := range []struct {
field string
body string
}{
{"tools", `{"tools":[{"type":"function","name":"private-tool"}],"tool_choice":"auto","parallel_tool_calls":true,"instructions":"private instruction"}`},
{"tool_choice", `{"tools":[],"tool_choice":"none","parallel_tool_calls":true,"instructions":"private instruction"}`},
{"parallel_tool_calls", `{"tools":[],"tool_choice":"auto","parallel_tool_calls":false,"instructions":"private instruction"}`},
{"instructions", `{"tools":[],"tool_choice":"auto","parallel_tool_calls":true,"instructions":"changed private instruction"}`},
} {
t.Run(tc.field, func(t *testing.T) {
report := openAI409ControlDiagnostic([]byte(tc.body), expected, "original_replay", true, true, false)
require.Equal(t, "complete", report.Observation)
for field, got := range map[string]string{
"tools": report.Tools, "tool_choice": report.ToolChoice,
"parallel_tool_calls": report.ParallelToolCalls, "instructions": report.Instructions,
} {
want := "match"
if field == tc.field {
want = "changed"
}
require.Equal(t, want, got, field)
}
require.True(t, report.PreviousResponseIDPresent)
require.False(t, report.ConversationPresent)
})
}

unknown := openAI409ControlDiagnostic(base, openAI409ControlFingerprints{}, "original_replay", true, false, true)
require.Equal(t, "partial", unknown.Observation)
require.Equal(t, "unknown", unknown.Tools)
require.True(t, unknown.ConversationPresent)
}
80 changes: 80 additions & 0 deletions backend/internal/service/openai_409_omit_history.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ func (s *OpenAIGatewayService) TryRebuildOpenAI409History(ctx context.Context, c
request.omittedHistory = true
request.inputDigest = openAIAgentRecoveryInputDigest(clean)
request.replayControlsDigest = openAI409ControlsDigest(clean)
request.controlFingerprints = openAI409FingerprintControls(clean)
request.omittedSource = r
request.toolProofs = r.toolProofs
return next, clean, true, nil
Expand Down Expand Up @@ -583,6 +584,64 @@ func openAI409ControlsDigest(raw []byte) [32]byte {
return sha256.Sum256(canonical)
}

type openAI409ControlFingerprints struct {
values [4][32]byte
observed [4]bool
}

var openAI409ControlFields = [...]string{"tools", "tool_choice", "parallel_tool_calls", "instructions"}

func openAI409FingerprintControls(raw []byte) openAI409ControlFingerprints {
var fingerprints openAI409ControlFingerprints
for i, field := range openAI409ControlFields {
value := gjson.GetBytes(raw, field)
var encoded []byte
if !value.Exists() {
encoded, _ = json.Marshal([]any{false})
} else {
decoder := json.NewDecoder(strings.NewReader(value.Raw))
decoder.UseNumber()
var decoded any
if decoder.Decode(&decoded) != nil {
continue
}
encoded, _ = json.Marshal([]any{true, decoded})
}
if encoded == nil {
continue
}
fingerprints.values[i] = sha256.Sum256(encoded)
fingerprints.observed[i] = true
}
return fingerprints
}

func openAI409ControlDiagnostic(raw []byte, expected openAI409ControlFingerprints, source string, digestChanged, previousResponsePresent, conversationPresent bool) OpsRecoveryControls {
actual := openAI409FingerprintControls(raw)
checks := [4]string{}
complete := true
for i := range openAI409ControlFields {
switch {
case !expected.observed[i] || !actual.observed[i]:
checks[i] = "unknown"
complete = false
case expected.values[i] != actual.values[i]:
checks[i] = "changed"
default:
checks[i] = "match"
}
}
observation := "complete"
if !complete {
observation = "partial"
}
return OpsRecoveryControls{
Observation: observation, Snapshot: source,
Tools: checks[0], ToolChoice: checks[1], ParallelToolCalls: checks[2], Instructions: checks[3],
DigestChanged: digestChanged, PreviousResponseIDPresent: previousResponsePresent, ConversationPresent: conversationPresent,
}
}

func prepareOpenAI409APIKeyReplay(ctx context.Context, body []byte, responsesLite bool) ([]byte, error) {
r := openAIAgentRecoveryFromContext(ctx)
if r == nil || !r.omittedHistory {
Expand All @@ -596,6 +655,7 @@ func prepareOpenAI409APIKeyReplay(ctx context.Context, body []byte, responsesLit
return nil, err
}
r.apiControlsDigest = openAI409ControlsDigest(prepared)
r.apiFingerprints = openAI409FingerprintControls(prepared)
r.apiInputDigest = openAIAgentRecoveryInputDigest(prepared)
r.apiReplayPrepared = true
return prepared, nil
Expand Down Expand Up @@ -640,6 +700,7 @@ func prepareOpenAI409OAuthReplay(ctx context.Context, c *gin.Context, body map[s
// Only this narrowly derived OAuth expectation is used at its final send.
r.oauthInputDigest = openAIAgentRecoveryInputDigest(prepared)
r.oauthControlsDigest = openAI409ControlsDigest(prepared)
r.oauthFingerprints = openAI409FingerprintControls(prepared)
r.oauthReplayPrepared = true
return nil
}
Expand All @@ -661,6 +722,24 @@ func openAIRecoveryWireRefusal(ctx context.Context, stage string, details ...zap
return openAIRecoveryDiagnosticError("wire_changed", stage, openAIAgentRecoveryFromContext(ctx))
}

func openAIRecoveryControlsWireRefusal(ctx context.Context, report OpsRecoveryControls) error {
logger.FromContext(ctx).Warn("openai.encrypted_history_409_refused",
zap.String("stage", "controls_integrity"),
zap.String("controls_observation", report.Observation), zap.String("controls_snapshot", report.Snapshot),
zap.String("tools", report.Tools), zap.String("tool_choice", report.ToolChoice),
zap.String("parallel_tool_calls", report.ParallelToolCalls), zap.String("instructions", report.Instructions),
zap.Bool("controls_digest_changed", report.DigestChanged),
zap.Bool("previous_response_id_present", report.PreviousResponseIDPresent),
zap.Bool("conversation_present", report.ConversationPresent))
err := openAIRecoveryDiagnosticError("wire_changed", "controls_integrity", openAIAgentRecoveryFromContext(ctx))
if recovery, ok := err.(*OpenAIAgentRecoveryError); ok {
diagnostic := *recovery.diagnostic
diagnostic.controls = &report
recovery.diagnostic = &diagnostic
}
return err
}

func checkOpenAIRecoveryProjectionSource(ctx context.Context, stage string, body []byte, r *openAIAgentRecoveryRequest) error {
inputChanged := openAIAgentRecoveryInputDigest(body) != r.inputDigest
controlsChanged := openAI409ControlsDigest(body) != r.replayControlsDigest
Expand Down Expand Up @@ -732,6 +811,7 @@ func (s *OpenAIGatewayService) prepareOpenAI409HTTPProjection(ctx context.Contex
snapshot := *r
snapshot.inputDigest = openAIAgentRecoveryInputDigest(clean)
snapshot.replayControlsDigest = openAI409ControlsDigest(clean)
snapshot.controlFingerprints = openAI409FingerprintControls(clean)
snapshot.apiReplayPrepared, snapshot.oauthReplayPrepared = false, false
return context.WithValue(ctx, openAIAgentRecoveryContextKey{}, &snapshot), clean, nil
}
Expand Down
17 changes: 14 additions & 3 deletions backend/internal/service/openai_agent_message_recovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,13 @@ type openAIAgentRecoveryRequest struct {
nativeAccountID int64
replayControlsDigest [32]byte
apiControlsDigest [32]byte
controlFingerprints openAI409ControlFingerprints
apiFingerprints openAI409ControlFingerprints
apiInputDigest [32]byte
apiReplayPrepared bool
oauthInputDigest [32]byte
oauthControlsDigest [32]byte
oauthFingerprints openAI409ControlFingerprints
oauthReplayPrepared bool
omittedSource *openAIAgentRecoveryRequest
shadowModel string // original requested model, independent of account/channel projection
Expand Down Expand Up @@ -491,6 +494,7 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con
return noop, openAIAgentRecoveryRefusal(ctx, "body_unreadable")
}
expectedInput, expectedControls := request.inputDigest, request.replayControlsDigest
expectedFingerprints, fingerprintSource := request.controlFingerprints, "original_replay"
if request.nativeReplayPrepared && !request.omittedHistory {
if request.nativeAccountID != account.ID {
return noop, openAIAgentRecoveryRefusal(ctx, "route_identity")
Expand All @@ -499,22 +503,29 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con
}
if request.omittedHistory && account.IsOpenAIApiKey() && request.apiReplayPrepared {
expectedInput, expectedControls = request.apiInputDigest, request.apiControlsDigest
expectedFingerprints, fingerprintSource = request.apiFingerprints, "api_key_replay"
}
if request.omittedHistory && account.UsesOpenAICodexProtocol() {
if !request.oauthReplayPrepared {
return noop, openAIAgentRecoveryError("wire_changed")
}
expectedInput, expectedControls = request.oauthInputDigest, request.oauthControlsDigest
expectedFingerprints, fingerprintSource = request.oauthFingerprints, "oauth_replay"
}
if request.preservesHistory() && openAIAgentRecoveryInputDigest(body) != expectedInput {
if request.omittedHistory {
logger.FromContext(ctx).Warn("openai.encrypted_history_409_refused", zap.String("stage", "input_integrity"))
}
return noop, openAIAgentRecoveryRefusal(ctx, "input_integrity")
}
if request.omittedHistory && (gjson.GetBytes(body, "previous_response_id").Exists() || gjson.GetBytes(body, "conversation").Exists() ||
openAI409ControlsDigest(body) != expectedControls) {
return noop, openAIRecoveryWireRefusal(ctx, "controls_integrity")
if request.omittedHistory {
previousResponsePresent := gjson.GetBytes(body, "previous_response_id").Exists()
conversationPresent := gjson.GetBytes(body, "conversation").Exists()
controlsDigestChanged := openAI409ControlsDigest(body) != expectedControls
if previousResponsePresent || conversationPresent || controlsDigestChanged {
report := openAI409ControlDiagnostic(body, expectedFingerprints, fingerprintSource, controlsDigestChanged, previousResponsePresent, conversationPresent)
return noop, openAIRecoveryControlsWireRefusal(ctx, report)
}
}
if request.previousResponseID != "" && gjson.GetBytes(body, "previous_response_id").String() != request.previousResponseID {
return noop, openAIAgentRecoveryError("owner_unavailable")
Expand Down
Loading
Loading