From 950b2b66e6827d568eb12877df662c95e615ba8f Mon Sep 17 00:00:00 2001 From: xiaomo <90334896+akayedi@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:28:01 +0800 Subject: [PATCH 1/5] feat: add encrypted history controls diagnostics --- .../handler/openai_agent_message_recovery.go | 2 +- .../openai_owner_conflict_diagnostics_test.go | 7 +- backend/internal/handler/ops_error_logger.go | 3 + .../service/openai_409_omit_history.go | 80 ++++++++++++++++++ .../service/openai_409_omit_history_test.go | 82 +++++++++++++++++++ .../service/openai_agent_message_recovery.go | 17 +++- .../openai_agent_recovery_diagnostics.go | 11 +++ .../service/openai_lossy_history_restart.go | 1 + .../service/openai_ws_agent_recovery.go | 2 + .../openai_ws_readable_continuation.go | 1 + .../internal/service/ops_upstream_context.go | 15 ++++ .../__tests__/OpsErrorDetailModal.spec.ts | 19 +++++ 12 files changed, 235 insertions(+), 5 deletions(-) diff --git a/backend/internal/handler/openai_agent_message_recovery.go b/backend/internal/handler/openai_agent_message_recovery.go index db8b4e043240..32f556e74d36 100644 --- a/backend/internal/handler/openai_agent_message_recovery.go +++ b/backend/internal/handler/openai_agent_message_recovery.go @@ -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()}, }) } diff --git a/backend/internal/handler/openai_owner_conflict_diagnostics_test.go b/backend/internal/handler/openai_owner_conflict_diagnostics_test.go index d9b327575ddd..50ad684ec1fd 100644 --- a/backend/internal/handler/openai_owner_conflict_diagnostics_test.go +++ b/backend/internal/handler/openai_owner_conflict_diagnostics_test.go @@ -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}) @@ -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") }) } diff --git a/backend/internal/handler/ops_error_logger.go b/backend/internal/handler/ops_error_logger.go index 24e7f5731366..02f9676a34eb 100644 --- a/backend/internal/handler/ops_error_logger.go +++ b/backend/internal/handler/ops_error_logger.go @@ -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) } diff --git a/backend/internal/service/openai_409_omit_history.go b/backend/internal/service/openai_409_omit_history.go index b87d86280c56..5017cf41e09d 100644 --- a/backend/internal/service/openai_409_omit_history.go +++ b/backend/internal/service/openai_409_omit_history.go @@ -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 @@ -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 { @@ -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 @@ -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 } @@ -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 @@ -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 } diff --git a/backend/internal/service/openai_409_omit_history_test.go b/backend/internal/service/openai_409_omit_history_test.go index 8aa1adecf1f0..174e5081b24b 100644 --- a/backend/internal/service/openai_409_omit_history_test.go +++ b/backend/internal/service/openai_409_omit_history_test.go @@ -321,6 +321,88 @@ func TestOpenAI409OAuthReplayKeepsOriginalSnapshotAndFinalControls(t *testing.T) } } +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) +} + func TestOpenAI409NamespaceProjectionPreservesNumbers(t *testing.T) { body := []byte(`{"tools":[{"type":"namespace","name":"math","tools":[{"type":"function","name":"sum","parameters":{"type":"object","properties":{"count":{"type":"integer","enum":[9007199254740993]}}}}]}],"input":[{"role":"user","content":"continue with the recorded value","sequence":9007199254740993}]}`) projected, err := flattenOpenAIResponsesNamespaces(nil, body) diff --git a/backend/internal/service/openai_agent_message_recovery.go b/backend/internal/service/openai_agent_message_recovery.go index 6a7bc04b792e..b486a2e5ca79 100644 --- a/backend/internal/service/openai_agent_message_recovery.go +++ b/backend/internal/service/openai_agent_message_recovery.go @@ -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 @@ -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") @@ -499,12 +503,14 @@ 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 { @@ -512,9 +518,14 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con } 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") diff --git a/backend/internal/service/openai_agent_recovery_diagnostics.go b/backend/internal/service/openai_agent_recovery_diagnostics.go index b6eea2173da6..9c8d7c2040be 100644 --- a/backend/internal/service/openai_agent_recovery_diagnostics.go +++ b/backend/internal/service/openai_agent_recovery_diagnostics.go @@ -107,6 +107,7 @@ type openAIRecoveryDiagnostics struct { owners openAIRecoveryOwnerCounts tools openAIRecoveryToolCounts shadow openAIRecoveryShadowState + controls *OpsRecoveryControls } func openAIRecoveryDiagnosticError(reason, detail string, r *openAIAgentRecoveryRequest) error { @@ -194,3 +195,13 @@ func LogOpenAIAgentRecoveryRefusal(ctx context.Context, recovery *OpenAIAgentRec zap.String("shadow_lookup", safeOpenAIRecoveryShadowState(d.shadow.lookup)), zap.String("shadow_epoch", safeOpenAIRecoveryShadowState(d.shadow.epoch)), ) } + +// RecoveryControlsDiagnostic returns only fixed comparison categories and +// presence flags. Field contents and fingerprints are never exposed. +func (e *OpenAIAgentRecoveryError) RecoveryControlsDiagnostic() *OpsRecoveryControls { + if e == nil || e.diagnostic == nil || e.diagnostic.controls == nil { + return nil + } + copy := *e.diagnostic.controls + return © +} diff --git a/backend/internal/service/openai_lossy_history_restart.go b/backend/internal/service/openai_lossy_history_restart.go index 95aac1d3acd7..f1eec69bde3e 100644 --- a/backend/internal/service/openai_lossy_history_restart.go +++ b/backend/internal/service/openai_lossy_history_restart.go @@ -52,6 +52,7 @@ func (s *OpenAIGatewayService) PrepareOpenAILossyHistoryRestart(ctx context.Cont r := openAIAgentRecoveryFromContext(next) r.omittedHistory, r.omittedSource = true, nil r.inputDigest, r.replayControlsDigest = openAIAgentRecoveryInputDigest(clean), openAI409ControlsDigest(clean) + r.controlFingerprints = openAI409FingerprintControls(clean) return next, clean, true } diff --git a/backend/internal/service/openai_ws_agent_recovery.go b/backend/internal/service/openai_ws_agent_recovery.go index f63771f4b7dd..b62b17294666 100644 --- a/backend/internal/service/openai_ws_agent_recovery.go +++ b/backend/internal/service/openai_ws_agent_recovery.go @@ -327,6 +327,7 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte, } snapshot := *r.readable snapshot.apiInputDigest, snapshot.apiControlsDigest = openAIAgentRecoveryInputDigest(projected), openAI409ControlsDigest(projected) + snapshot.apiFingerprints = openAI409FingerprintControls(projected) ctx = context.WithValue(ctx, openAIAgentRecoveryContextKey{}, &snapshot) } } @@ -1329,6 +1330,7 @@ func (s *OpenAIGatewayService) restartOpenAIWSClientReadableHistory(ctx context. r.omittedSource = nil r.inputDigest = openAIAgentRecoveryInputDigest(clean) r.replayControlsDigest = openAI409ControlsDigest(clean) + r.controlFingerprints = openAI409FingerprintControls(clean) return next, clean, true } diff --git a/backend/internal/service/openai_ws_readable_continuation.go b/backend/internal/service/openai_ws_readable_continuation.go index c52344000557..91211f2f748a 100644 --- a/backend/internal/service/openai_ws_readable_continuation.go +++ b/backend/internal/service/openai_ws_readable_continuation.go @@ -291,6 +291,7 @@ func (s *OpenAIGatewayService) RebuildOpenAIWSUnsentTurn(ctx context.Context, c next = WithOpenAIEncryptedReasoningAffinity(next, clean) r.omittedHistory, r.omittedSource = true, nil r.inputDigest, r.replayControlsDigest = openAIAgentRecoveryInputDigest(clean), openAI409ControlsDigest(clean) + r.controlFingerprints = openAI409FingerprintControls(clean) return next, clean, true, nil } next, clean, changed, err := s.TryRebuildOpenAI409History(next, c, body, session, model, openAIAgentRecoveryError("owner_unavailable")) diff --git a/backend/internal/service/ops_upstream_context.go b/backend/internal/service/ops_upstream_context.go index b348c5d5356a..62b2ac11fce3 100644 --- a/backend/internal/service/ops_upstream_context.go +++ b/backend/internal/service/ops_upstream_context.go @@ -187,6 +187,21 @@ type OpsRecoveryFailure struct { Protocol string Phase string RequestWritten *bool // nil means no proof of whether the generation was sent + Controls *OpsRecoveryControls +} + +// OpsRecoveryControls contains value-free comparison outcomes for the final +// encrypted-history wire check. It must never contain field values or hashes. +type OpsRecoveryControls struct { + Observation string `json:"observation"` + Snapshot string `json:"snapshot"` + Tools string `json:"tools"` + ToolChoice string `json:"tool_choice"` + ParallelToolCalls string `json:"parallel_tool_calls"` + Instructions string `json:"instructions"` + DigestChanged bool `json:"digest_changed"` + PreviousResponseIDPresent bool `json:"previous_response_id_present"` + ConversationPresent bool `json:"conversation_present"` } // OpsUpstreamWSFailure is set at the native upstream socket boundary, never diff --git a/frontend/src/views/admin/ops/components/__tests__/OpsErrorDetailModal.spec.ts b/frontend/src/views/admin/ops/components/__tests__/OpsErrorDetailModal.spec.ts index 3a7b23089d54..7207b111712a 100644 --- a/frontend/src/views/admin/ops/components/__tests__/OpsErrorDetailModal.spec.ts +++ b/frontend/src/views/admin/ops/components/__tests__/OpsErrorDetailModal.spec.ts @@ -132,3 +132,22 @@ it('labels HTTP 200 as wire status when the stream failed', async () => { expect(wrapper.text()).toContain('200') wrapper.unmount() }) + +it('shows value-free encrypted-history control diagnostics from the error body', async () => { + vi.clearAllMocks() + mocks.listRequestErrorUpstreamErrors.mockResolvedValue({ items: [] }) + mocks.getRequestErrorDetail.mockResolvedValue({ + id: 1, status_code: 409, phase: 'request', type: 'invalid_request_error', + message: 'Encrypted history recovery refused', + error_body: JSON.stringify({ error: { code: 'encrypted_agent_recovery_wire_changed', controls: { snapshot: 'oauth_replay', tools: 'changed', tool_choice: 'match', previous_response_id_present: false } } }), + }) + const wrapper = shallowMount(OpsErrorDetailModal, { + props: { show: true, errorId: 1, errorType: 'request' }, + global: { stubs: { BaseDialog: { template: '
' }, Icon: true } }, + }) + await flushPromises() + expect(wrapper.text()).toContain('"snapshot": "oauth_replay"') + expect(wrapper.text()).toContain('"tools": "changed"') + expect(wrapper.text()).toContain('"previous_response_id_present": false') + wrapper.unmount() +}) From 076026136cfac2da483933c6d714c4f385ff309b Mon Sep 17 00:00:00 2001 From: xiaomo <90334896+akayedi@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:14:30 +0800 Subject: [PATCH 2/5] test: keep 409 RED oracle compatible with baseline --- .github/workflows/rebuilt-request-dispatch.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/rebuilt-request-dispatch.yml b/.github/workflows/rebuilt-request-dispatch.yml index 1df82ba413c9..504e3253db28 100644 --- a/.github/workflows/rebuilt-request-dispatch.yml +++ b/.github/workflows/rebuilt-request-dispatch.yml @@ -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. + git show "$baseline:backend/internal/service/openai_409_omit_history_test.go" > backend/internal/service/openai_409_omit_history_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: From 1dbc83e1f4a558a4e0103c5385d1974119a60a5f Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Thu, 19 Nov 2026 22:43:54 +0800 Subject: [PATCH 3/5] =?UTF-8?q?test:=20=E4=BF=AE=E5=A4=8D=E5=8E=86?= =?UTF-8?q?=E5=8F=B2=20WS=20=E5=9B=9E=E5=BD=92=E7=9A=84=E9=87=8D=E5=A4=8D?= =?UTF-8?q?=E5=87=86=E5=A4=87=E4=B8=8E=E8=AF=8A=E6=96=AD=E5=85=BC=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/scripts/upstream-v0222-red-fixtures.txt | 4 ++++ .github/workflows/ws-readable-continuation.yml | 7 ++++--- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/.github/scripts/upstream-v0222-red-fixtures.txt b/.github/scripts/upstream-v0222-red-fixtures.txt index 39ce571661ac..1c607e29e7e0 100644 --- a/.github/scripts/upstream-v0222-red-fixtures.txt +++ b/.github/scripts/upstream-v0222-red-fixtures.txt @@ -169,3 +169,7 @@ 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 + +# Controls diagnostics require the newer recovery APIs, not historical RED sources. +backend/internal/service/openai_409_omit_history_test.go +backend/internal/handler/openai_owner_conflict_diagnostics_test.go diff --git a/.github/workflows/ws-readable-continuation.yml b/.github/workflows/ws-readable-continuation.yml index b26e30050763..e57b6eece2c2 100644 --- a/.github/workflows/ws-readable-continuation.yml +++ b/.github/workflows/ws-readable-continuation.yml @@ -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 From 2cc1de5f70d2130e10fe7339c3dc0e30f144c34d Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Thu, 19 Nov 2026 23:07:12 +0800 Subject: [PATCH 4/5] =?UTF-8?q?test:=20=E4=BF=9D=E7=95=99=E5=8E=86?= =?UTF-8?q?=E5=8F=B2=E8=B0=83=E5=BA=A6=E5=9B=9E=E5=BD=92=E4=B8=AD=E7=9A=84?= =?UTF-8?q?=E6=95=B0=E5=AD=97=E7=B2=BE=E5=BA=A6=E6=96=AD=E8=A8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../scripts/upstream-v0222-red-fixtures.txt | 2 +- .../workflows/rebuilt-request-dispatch.yml | 3 +- .../openai_409_controls_diagnostics_test.go | 94 +++++++++++++++++++ .../service/openai_409_omit_history_test.go | 82 ---------------- 4 files changed, 97 insertions(+), 84 deletions(-) create mode 100644 backend/internal/service/openai_409_controls_diagnostics_test.go diff --git a/.github/scripts/upstream-v0222-red-fixtures.txt b/.github/scripts/upstream-v0222-red-fixtures.txt index 1c607e29e7e0..74e7bfb2b223 100644 --- a/.github/scripts/upstream-v0222-red-fixtures.txt +++ b/.github/scripts/upstream-v0222-red-fixtures.txt @@ -171,5 +171,5 @@ backend/internal/service/grok_rate_limit_history_test.go backend/internal/service/new_api_cost_test.go # Controls diagnostics require the newer recovery APIs, not historical RED sources. -backend/internal/service/openai_409_omit_history_test.go +backend/internal/service/openai_409_controls_diagnostics_test.go backend/internal/handler/openai_owner_conflict_diagnostics_test.go diff --git a/.github/workflows/rebuilt-request-dispatch.yml b/.github/workflows/rebuilt-request-dispatch.yml index 504e3253db28..02100d3411b0 100644 --- a/.github/workflows/rebuilt-request-dispatch.yml +++ b/.github/workflows/rebuilt-request-dispatch.yml @@ -64,7 +64,7 @@ jobs: 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. - git show "$baseline:backend/internal/service/openai_409_omit_history_test.go" > backend/internal/service/openai_409_omit_history_test.go + 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: @@ -89,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', diff --git a/backend/internal/service/openai_409_controls_diagnostics_test.go b/backend/internal/service/openai_409_controls_diagnostics_test.go new file mode 100644 index 000000000000..e7ed2b861141 --- /dev/null +++ b/backend/internal/service/openai_409_controls_diagnostics_test.go @@ -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) +} diff --git a/backend/internal/service/openai_409_omit_history_test.go b/backend/internal/service/openai_409_omit_history_test.go index 174e5081b24b..8aa1adecf1f0 100644 --- a/backend/internal/service/openai_409_omit_history_test.go +++ b/backend/internal/service/openai_409_omit_history_test.go @@ -321,88 +321,6 @@ func TestOpenAI409OAuthReplayKeepsOriginalSnapshotAndFinalControls(t *testing.T) } } -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) -} - func TestOpenAI409NamespaceProjectionPreservesNumbers(t *testing.T) { body := []byte(`{"tools":[{"type":"namespace","name":"math","tools":[{"type":"function","name":"sum","parameters":{"type":"object","properties":{"count":{"type":"integer","enum":[9007199254740993]}}}}]}],"input":[{"role":"user","content":"continue with the recorded value","sequence":9007199254740993}]}`) projected, err := flattenOpenAIResponsesNamespaces(nil, body) From a1e58eb4b5e40bad0cb01629afa7411b179fd9f9 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Thu, 19 Nov 2026 23:59:27 +0800 Subject: [PATCH 5/5] =?UTF-8?q?test:=20=E5=8C=B9=E9=85=8D=E5=8E=86?= =?UTF-8?q?=E5=8F=B2=20WS=20=E5=9B=9E=E5=BD=92=E4=B8=AD=E7=9A=84=20New=20A?= =?UTF-8?q?PI=20=E9=92=B1=E5=8C=85=E6=B5=8B=E8=AF=95=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/scripts/upstream-v0222-red-fixtures.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/scripts/upstream-v0222-red-fixtures.txt b/.github/scripts/upstream-v0222-red-fixtures.txt index 74e7bfb2b223..7f53bbd07e79 100644 --- a/.github/scripts/upstream-v0222-red-fixtures.txt +++ b/.github/scripts/upstream-v0222-red-fixtures.txt @@ -169,6 +169,7 @@ 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