diff --git a/.github/scripts/assert-issue999-history.py b/.github/scripts/assert-issue999-history.py new file mode 100644 index 000000000000..43b98dec4873 --- /dev/null +++ b/.github/scripts/assert-issue999-history.py @@ -0,0 +1,80 @@ +"""CI evidence for Issue999: require named behavioral RED and clean candidate GREEN.""" + +import json +import runpy +import sys +from collections import Counter +from pathlib import Path + +HANDLER = "github.com/Wei-Shaw/sub2api/internal/handler" +SERVICE = "github.com/Wei-Shaw/sub2api/internal/service" +HISTORY = "TestIssue999HTTPBridgeAssistantHistory" +POINTER = "TestIssue999HTTPBridgeRejectsForeignContinuation" +DELIVERY = "TestIssue999HTTPBridgeDeliveryControls" +HISTORY_LEAVES = {f"{HISTORY}/{name}" for name in ("empty_terminal", "full_terminal")} +POINTER_LEAVES = {f"{POINTER}/{name}" for name in ("wrong_pointer", "wrong_session", "omitted_identity")} +DELIVERY_LEAVES = { + f"{DELIVERY}/{name}" for name in ( + "completed", "full_terminal_only", "legacy_implicit_completed", "failed", + "incomplete", "completed_with_incomplete_status", "cancelled", "completed_with_error", + "eof_before_terminal", "added_only", "unfinished_item", "failed_item", "invalid_index", + "fractional_index", "missing_index", "undelivered_item", "undelivered_terminal", + "item_write_error", "terminal_write_error", + ) +} + + +def validate(phase, exit_code, path): + if phase not in {"RED", "GREEN"}: + raise ValueError("unknown phase") + transcript = Path(path).read_text() + # Shared scanner rejects raw setup/compiler diagnostics, races, timeouts, + # recovered panics and skips. These are never acceptable behavioral RED. + runpy.run_path(str(Path(__file__).with_name("assert-readable-continuation.py")))["check_clean"](transcript) + rows = [] + for line in transcript.splitlines(): + try: + row = json.loads(line) + except json.JSONDecodeError: + continue + if not isinstance(row, dict): + raise ValueError("invalid go test event") + rows.append(row) + if any(r.get("Action") in {"build-fail", "skip"} for r in rows): + raise ValueError("build failure or skip cannot prove behavior") + expected = {HANDLER: HISTORY_LEAVES | {HISTORY}} + if phase == "GREEN": + expected[HANDLER] |= POINTER_LEAVES | {POINTER} + expected[SERVICE] = DELIVERY_LEAVES | {DELIVERY} + actions = Counter((r.get("Package"), r.get("Action"), r.get("Test")) for r in rows) + for package, names in expected.items(): + for name in names: + if actions[package, "run", name] != 1 or actions[package, "pass", name] + actions[package, "fail", name] != 1: + raise ValueError(f"missing/repeated test execution or terminal: {name}") + terminal = "pass" if phase == "GREEN" else "fail" + if actions[package, terminal, None] != 1 or actions[package, "pass", None] + actions[package, "fail", None] != 1: + raise ValueError("missing or incorrect package terminal") + if phase == "RED": + if exit_code != 1: + raise ValueError("old code did not fail normally") + for name in HISTORY_LEAVES: + output = "".join(r.get("Output", "") for r in rows if r.get("Package") == HANDLER and r.get("Test") == name) + if actions[HANDLER, "fail", name] != 1 or "ISSUE999_ASSISTANT_HISTORY_LOST" not in output: + raise ValueError(f"missing named assistant-history behavioral failure: {name}") + for row in rows: + if row.get("Action") == "fail" and (row.get("Package") != HANDLER or row.get("Test") not in expected[HANDLER] | {None}): + raise ValueError("unrelated failure cannot prove RED") + else: + if exit_code != 0 or any(r.get("Action") == "fail" for r in rows): + raise ValueError("candidate failed") + for package, names in expected.items(): + if any(actions[package, "pass", name] != 1 for name in names): + raise ValueError("not all candidate behavior scenarios passed") + print(f"{phase}: named Issue999 history evidence accepted") + + +if __name__ == "__main__": + try: + validate(sys.argv[1], int(sys.argv[2]), sys.argv[3]) + except ValueError as exc: + raise SystemExit(str(exc)) from exc diff --git a/.github/workflows/ws-http-bridge-warmup.yml b/.github/workflows/ws-http-bridge-warmup.yml index c6241fc3696e..65c05c4af68e 100644 --- a/.github/workflows/ws-http-bridge-warmup.yml +++ b/.github/workflows/ws-http-bridge-warmup.yml @@ -10,6 +10,8 @@ on: - 'backend/internal/handler/openai_gateway_handler.go' - 'backend/internal/handler/openai_http_bridge_warmup_test.go' - 'backend/internal/handler/openai_ws_tool_result_bridge_test.go' + - 'backend/internal/handler/openai_ws_http_bridge_history_test.go' + - '.github/scripts/assert-issue999-history.py' - '.github/workflows/ws-http-bridge-warmup.yml' permissions: contents: read @@ -17,6 +19,62 @@ concurrency: group: ws-http-warmup-${{ github.event.pull_request.number }} cancel-in-progress: true jobs: + assistant-history: + runs-on: ubuntu-24.04 + timeout-minutes: 25 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Preserve regressions on pinned old production in disposable checkout + run: | + set -euo pipefail + baseline=8dedf05db37c870265e04327defb9e96e7787603 + old="$RUNNER_TEMP/issue999-old" + git worktree add --detach "$old" "$baseline" + cp backend/internal/handler/openai_ws_http_bridge_history_test.go "$old/backend/internal/handler/" + { + git rev-parse HEAD + git -C "$old" rev-parse HEAD + git rev-parse HEAD:backend/internal/service/openai_ws_http_bridge.go + git -C "$old" rev-parse HEAD:backend/internal/service/openai_ws_http_bridge.go + sha256sum backend/internal/handler/openai_ws_http_bridge_history_test.go "$old/backend/internal/handler/openai_ws_http_bridge_history_test.go" + } > "$RUNNER_TEMP/issue999-identities.txt" + cmp backend/internal/handler/openai_ws_http_bridge_history_test.go "$old/backend/internal/handler/openai_ws_http_bridge_history_test.go" + git -C "$old" diff --exit-code -- backend/internal/service + set +e + (cd "$old/backend" && go test -race -json -tags=unit,bridgewarmup ./internal/handler -run '^TestIssue999HTTPBridgeAssistantHistory$' -count=1 -timeout=8m) > "$RUNNER_TEMP/issue999-red.jsonl" 2>&1 + result=$? + set -e + echo "$result" > "$RUNNER_TEMP/issue999-red.exit" + cat "$RUNNER_TEMP/issue999-red.jsonl" + python3 .github/scripts/assert-issue999-history.py RED "$result" "$RUNNER_TEMP/issue999-red.jsonl" + - name: Candidate complete ordered history and delivery controls + if: ${{ !cancelled() }} + run: | + set -euo pipefail + set +e + (cd backend && go test -race -json -tags=unit,bridgewarmup ./internal/handler ./internal/service -run '^TestIssue999HTTPBridge' -count=1 -timeout=8m) > "$RUNNER_TEMP/issue999-green.jsonl" 2>&1 + result=$? + set -e + echo "$result" > "$RUNNER_TEMP/issue999-green.exit" + cat "$RUNNER_TEMP/issue999-green.jsonl" + python3 .github/scripts/assert-issue999-history.py GREEN "$result" "$RUNNER_TEMP/issue999-green.jsonl" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: issue999-assistant-history-${{ github.event.pull_request.head.sha }} + path: | + ${{ runner.temp }}/issue999-*.jsonl + ${{ runner.temp }}/issue999-*.exit + ${{ runner.temp }}/issue999-identities.txt + if-no-files-found: error behavior: runs-on: ubuntu-24.04 timeout-minutes: 20 diff --git a/backend/internal/handler/openai_ws_http_bridge_history_test.go b/backend/internal/handler/openai_ws_http_bridge_history_test.go new file mode 100644 index 000000000000..c09adc2b3b57 --- /dev/null +++ b/backend/internal/handler/openai_ws_http_bridge_history_test.go @@ -0,0 +1,206 @@ +//go:build unit && bridgewarmup + +package handler + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/Wei-Shaw/sub2api/internal/testutil" + ws "github.com/coder/websocket" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const issue999Message = `{"type":"message","id":"msg_fixture_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"synthetic answer 1","annotations":[]}]}` +const issue999Call = `{"type":"function_call","id":"fc_fixture_1","call_id":"call_fixture_1","name":"fixture_lookup","arguments":"{}","status":"completed"}` +const issue999Extra = `{"type":"message","id":"msg_fixture_extra","role":"assistant","status":"completed","content":[{"type":"output_text","text":"streamed extra","annotations":[]}]}` +const issue999Second = `{"type":"message","id":"msg_fixture_2","role":"assistant","status":"completed","content":[{"type":"output_text","text":"synthetic answer 2","annotations":[]}]}` +const issue999Result = `{"type":"function_call_output","call_id":"call_fixture_1","output":"synthetic result"}` +const issue999Tools = `[{"type":"function","name":"fixture_lookup","parameters":{"type":"object","properties":{},"additionalProperties":false},"strict":true}]` + +func issue999OAuthHarness(t *testing.T, upstreamURL string, headers http.Header, legacy bool, threshold int64) *openAIWSPassthroughHandlerHarness { + t.Helper() + return newOpenAIWSPassthroughHandlerHarnessWithKey(t, upstreamURL, headers, + map[string]string{service.SettingKeyCyberSessionBlockEnabled: "false", service.SettingKeyOpenAI400OmitEncryptedHistoryEnabled: "false", service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "false"}, nil, + func(k *service.APIKey) { k.AllowLongContext = true }, + func(a *service.Account, cfg *config.Config, transport *service.HTTPUpstream, _ *service.AccountRepository) { + a.Type = service.AccountTypeOAuth + a.Credentials = map[string]any{"access_token": "fixture-token", "chatgpt_account_id": "fixture-account"} + a.Extra["openai_oauth_responses_websockets_v2_enabled"] = true + a.Extra["openai_oauth_responses_websockets_v2_mode"] = service.OpenAIWSIngressModeCtxPool + cfg.Gateway.OpenAILegacyCompatibilityMode = legacy + cfg.Gateway.DisableEncryptedAgentOwnerBinding = true + cfg.Gateway.OpenAIWS.OAuthEnabled = true + cfg.Gateway.OpenAIWS.HTTPBridgeEnabled = true + cfg.Gateway.OpenAIWS.HTTPBridgeThresholdBytes = threshold + cfg.Gateway.OpenAIWS.ClientReadLimitBytes = 64 << 20 + cfg.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds = 60 + target, err := url.Parse(upstreamURL) + require.NoError(t, err) + *transport = &httpRebuildTransport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target} + }) +} + +func issue999ReadCompleted(t *testing.T, ctx context.Context, conn *ws.Conn, id string) { + t.Helper() + for i := 0; i < 16; i++ { + _, raw, err := conn.Read(ctx) + require.NoError(t, err, "ISSUE999_CONTINUATION_REFUSED") + kind := gjson.GetBytes(raw, "type").String() + require.NotEqual(t, "error", kind, string(raw)) + if kind == "response.completed" { + require.Equal(t, id, gjson.GetBytes(raw, "response.id").String()) + return + } + } + t.Fatal("missing completed event") +} + +func TestIssue999HTTPBridgeAssistantHistory(t *testing.T) { + for _, tc := range []struct { + name string + full, legacy bool + size int + }{ + {"empty_terminal", false, true, 24 << 20}, + {"full_terminal", true, true, 24 << 20}, + } { + t.Run(tc.name, func(t *testing.T) { + var calls atomic.Int32 + bodies := make(chan []byte, 4) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + raw, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + return + } + bodies <- raw + n := calls.Add(1) + w.Header().Set("Content-Type", "text/event-stream") + output := "[]" + if n == 1 { + // Deliberately out of order, repeated at the same index and + // repeated under a different index. All delivered events remain visible. + for _, e := range []struct { + index int + item string + }{{2, issue999Extra}, {1, issue999Call}, {0, issue999Message}, {1, issue999Call}, {3, issue999Message}} { + fmt.Fprintf(w, "data: {\"type\":\"response.output_item.done\",\"output_index\":%d,\"item\":%s}\n\n", e.index, e.item) + } + if tc.full { + // Terminal order/content/membership override all done events. + output = "[" + issue999Call + "," + strings.ReplaceAll(issue999Message, "synthetic answer 1", "authoritative answer 1") + "]" + } + } else if n == 2 { + output = "[" + issue999Second + "]" + } + fmt.Fprintf(w, "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_fixture_%d\",\"status\":\"completed\",\"output\":%s,\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n", n, output) + })) + defer upstream.Close() + threshold := int64(128) + if tc.legacy { + threshold = 15 << 20 + } + h := issue999OAuthHarness(t, upstream.URL, http.Header{"Session-Id": {"issue999-session"}, "Thread-Id": {"issue999-thread"}}, tc.legacy, threshold) + defer h.clientConn.CloseNow() + ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second) + defer cancel() + prior := []string{ + `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"prior context"}]}`, + `{"type":"function_call","call_id":"prior","name":"fixture_lookup","arguments":"{}","status":"completed"}`, + `{"type":"function_call_output","call_id":"prior","output":"prior receipt"}`, + `{"type":"message","role":"user","content":"` + strings.Repeat("p", tc.size) + `"}`, + } + first := `{"type":"response.create","model":"gpt-6.1-sol","stream":true,"store":false,"tools":` + issue999Tools + `,"input":[` + strings.Join(prior, ",") + `]}` + require.NoError(t, h.clientConn.Write(ctx, ws.MessageText, []byte(first))) + issue999ReadCompleted(t, ctx, h.clientConn, "resp_fixture_1") + firstBody := <-bodies + require.False(t, gjson.GetBytes(firstBody, "previous_response_id").Exists()) + // Capture accepted input after ordinary request normalization. Subsequent + // exact item comparisons ensure every prior item survives once. + var want []json.RawMessage + require.NoError(t, json.Unmarshal([]byte(gjson.GetBytes(firstBody, "input").Raw), &want)) + require.Len(t, want, len(prior)) + if tc.full { + want = append(want, json.RawMessage(issue999Call), json.RawMessage(strings.ReplaceAll(issue999Message, "synthetic answer 1", "authoritative answer 1"))) + } else { + want = append(want, json.RawMessage(issue999Message), json.RawMessage(issue999Call), json.RawMessage(issue999Extra)) + } + want = append(want, json.RawMessage(issue999Result)) + next := `{"type":"response.create","model":"gpt-6.1-sol","stream":true,"store":false,"tools":` + issue999Tools + `,"previous_response_id":"resp_fixture_1","input":[` + issue999Result + `]}` + require.NoError(t, h.clientConn.Write(ctx, ws.MessageText, []byte(next))) + issue999ReadCompleted(t, ctx, h.clientConn, "resp_fixture_2") + assertInput := func(raw []byte) { + t.Helper() + require.False(t, gjson.GetBytes(raw, "previous_response_id").Exists()) + var got []json.RawMessage + require.NoError(t, json.Unmarshal([]byte(gjson.GetBytes(raw, "input").Raw), &got)) + require.Len(t, got, len(want), "ISSUE999_ASSISTANT_HISTORY_LOST") + for i := range want { + require.JSONEq(t, string(want[i]), string(got[i]), "ISSUE999_ASSISTANT_HISTORY_LOST item=%d", i) + } + require.Equal(t, `["function_call","function_call_output"]`, gjson.GetBytes(raw, `input.#(call_id=="call_fixture_1")#.type`).Raw) + require.Equal(t, `["function_call","function_call_output"]`, gjson.GetBytes(raw, `input.#(call_id=="prior")#.type`).Raw) + } + assertInput(<-bodies) + const user3 = `{"type":"message","role":"user","content":"third round"}` + want = append(want, json.RawMessage(issue999Second), json.RawMessage(user3)) + third := `{"type":"response.create","model":"gpt-6.1-sol","stream":true,"store":false,"tools":` + issue999Tools + `,"previous_response_id":"resp_fixture_2","input":[` + user3 + `]}` + require.NoError(t, h.clientConn.Write(ctx, ws.MessageText, []byte(third))) + issue999ReadCompleted(t, ctx, h.clientConn, "resp_fixture_3") + assertInput(<-bodies) + require.EqualValues(t, 3, calls.Load()) + }) + } +} + +func TestIssue999HTTPBridgeRejectsForeignContinuation(t *testing.T) { + for _, tc := range []struct{ name, previous, thread string }{ + {"wrong_pointer", "resp_foreign", "thread-one"}, + {"wrong_session", "resp_fixture_1", "thread-two"}, + {"omitted_identity", "resp_fixture_1", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + var calls atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprintf(w, "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_fixture_1\",\"status\":\"completed\",\"output\":[%s]}}\n\n", issue999Message) + })) + defer upstream.Close() + h := issue999OAuthHarness(t, upstream.URL, nil, true, 1) + defer h.clientConn.CloseNow() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + first := `{"type":"response.create","model":"gpt-6.1-sol","store":false,"client_metadata":{"thread_id":"thread-one"},"input":[{"role":"user","content":"fixture"}]}` + require.NoError(t, h.clientConn.Write(ctx, ws.MessageText, []byte(first))) + issue999ReadCompleted(t, ctx, h.clientConn, "resp_fixture_1") + next := fmt.Sprintf(`{"type":"response.create","model":"gpt-6.1-sol","store":false,"previous_response_id":%q,"client_metadata":{"thread_id":%q},"input":[{"role":"user","content":"delta"}]}`, tc.previous, tc.thread) + require.NoError(t, h.clientConn.Write(ctx, ws.MessageText, []byte(next))) + if tc.thread == "" { + issue999ReadCompleted(t, ctx, h.clientConn, "resp_fixture_1") + require.EqualValues(t, 2, calls.Load()) + return + } + _, raw, err := h.clientConn.Read(ctx) + if err == nil { + require.Equal(t, "error", gjson.GetBytes(raw, "type").String()) + } else { + require.NotEqual(t, ws.StatusCode(-1), ws.CloseStatus(err)) + } + require.EqualValues(t, 1, calls.Load(), "foreign continuation must not dispatch") + }) + } +} diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index a180f7104a31..a5208fa2acc4 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -1380,6 +1380,9 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( bridgeReplayInputExists := false var bridgeAccountFailoverInput []json.RawMessage bridgeAccountFailoverInputExists := false + preserveOAuthOutput := account.IsOpenAIOAuth() && openAIWSPlaintextBridgeAccount(account) && !smartStateful + bridgeResponseID := "" + bridgeIdentity := openAIWSBridgeFrameIdentity(c, firstPayload.clientPayloadRaw) for turn := 1; ; turn++ { if turn > 1 && hooks != nil { if err := hooks.beforeRequest(turn, currentBridgePayload.payloadRaw, currentBridgePayload.clientPayloadRaw, currentBridgePayload.originalModel); err != nil { @@ -1431,6 +1434,26 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( if smartStrict && currentBridgePayload.previousResponseID != "" && currentBridgePayload.previousResponseID != smartSession.LastResponse { return NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "continuation does not belong to this HTTP session", nil) } + if preserveOAuthOutput { + identity := openAIWSBridgeFrameIdentity(c, currentBridgePayload.clientPayloadRaw) + conflict := bridgeIdentity.conflicts(identity) + if currentBridgePayload.previousResponseID != "" && (currentBridgePayload.previousResponseID != bridgeResponseID || conflict) { + return NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "continuation does not belong to this HTTP session", nil) + } + if conflict { + bridgeReplayInput, bridgeAccountFailoverInput = nil, nil + bridgeReplayInputExists, bridgeAccountFailoverInputExists = false, false + bridgeResponseID, turnState = "", "" + bridgeIdentity = identity + } else { + if identity.thread != "" { + bridgeIdentity.thread = identity.thread + } + if identity.session != "" { + bridgeIdentity.session = identity.session + } + } + } bridgePayloadRaw := currentBridgePayload.payloadRaw bridgePayloadBytes := currentBridgePayload.payloadBytes toolOutputCoverage := AnalyzeToolCallOutputContextCoverageBytes(currentBridgePayload.payloadRaw) @@ -1604,6 +1627,15 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( ) bridgeAccountFailoverInputExists = true } + if preserveOAuthOutput { + bridgeResponseID = "" + if result.wsReplayInputExists { + bridgeResponseID = strings.TrimSpace(result.RequestID) + } else { + bridgeReplayInput, bridgeAccountFailoverInput = nil, nil + bridgeReplayInputExists, bridgeAccountFailoverInputExists = false, false + } + } if bridgeTurnState := strings.TrimSpace(result.ResponseHeaders.Get(openAIWSTurnStateHeader)); bridgeTurnState != "" { // Follow-up turns on this bridge retain their own upstream state; // publishing it by session hash would leak it to independent bridges. diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index cebfecb28e6a..5fe288db8a08 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -834,6 +834,8 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( tokenEventCount := 0 terminalEventCount := 0 replayCollector := &openAIWSToolCallReplayCollector{} + var deliveredOutput openAIWSHTTPBridgeOutputHistory + preserveOAuthOutput := account.IsOpenAIOAuth() && openAIWSPlaintextBridgeAccount(account) firstEventType := "" lastEventType := "" upstreamTerminalEvent := "" @@ -900,6 +902,18 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( result.wsReplayInputExists = true } result.wsAccountFailoverReplayInput = replayCollector.AllItems() + if preserveOAuthOutput { + // Both continuation and account-failover history must exclude failed, + // incomplete and undelivered turns, including disconnect usage drains. + result.wsReplayInput = nil + result.wsReplayInputExists = false + result.wsAccountFailoverReplayInput = nil + if deliveredOutput.completed && !clientDisconnected && ctx.Err() == nil && deliveredOutput.responseID == responseID { + result.wsReplayInput = slices.Clone(deliveredOutput.output) + result.wsReplayInputExists = true + result.wsAccountFailoverReplayInput = slices.Clone(deliveredOutput.output) + } + } if imageCount > 0 { result.ImageCount = imageCount result.ImageSize = imageSizeTier @@ -1183,6 +1197,9 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( if !isKeepalive { wroteDownstream = true } + if preserveOAuthOutput { + deliveredOutput.delivered(message) + } } } } diff --git a/backend/internal/service/openai_ws_http_bridge_history.go b/backend/internal/service/openai_ws_http_bridge_history.go new file mode 100644 index 000000000000..4d01c84ccd8f --- /dev/null +++ b/backend/internal/service/openai_ws_http_bridge_history.go @@ -0,0 +1,119 @@ +package service + +import ( + "encoding/json" + "slices" + "strings" + "unicode/utf8" + + "github.com/gin-gonic/gin" + "github.com/tidwall/gjson" +) + +// Each bridge has a single authenticated connection. Compare declared identity +// components separately: a follow-up can omit a thread or first supply one. +type openAIWSBridgeIdentity struct { + thread, session, lane string +} + +func openAIWSBridgeFrameIdentity(c *gin.Context, raw []byte) openAIWSBridgeIdentity { + return openAIWSBridgeIdentity{ + thread: resolveOpenAIWSClientThreadID(c, raw), + session: explicitOpenAIRequestSessionID(c, raw), + lane: resolveOpenAIWSExecutionLane(c, raw), + } +} + +func (id openAIWSBridgeIdentity) conflicts(next openAIWSBridgeIdentity) bool { + return (id.thread != "" && next.thread != "" && next.thread != id.thread) || + (id.session != "" && next.session != "" && next.session != id.session) || id.lane != next.lane +} + +// This history belongs to one ordinary OAuth bridge turn. Observe only events +// whose client write succeeded; an upstream completion alone is not delivery. +type openAIWSHTTPBridgeOutputHistory struct { + done map[int64]json.RawMessage + output []json.RawMessage + responseID string + completed bool +} + +func (h *openAIWSHTTPBridgeOutputHistory) delivered(message []byte) { + switch gjson.GetBytes(message, "type").String() { + case "response.output_item.done": + index := gjson.GetBytes(message, "output_index") + item := gjson.GetBytes(message, "item") + if index.Type != gjson.Number || index.Int() < 0 || index.Float() != float64(index.Int()) || !openAIWSHTTPBridgeCompletedItem(item) { + return + } + if h.done == nil { + h.done = make(map[int64]json.RawMessage) + } + h.done[index.Int()] = json.RawMessage(item.Raw) + case "response.completed", "response.done": + response := gjson.GetBytes(message, "response") + // Older compatible providers omit status on a completed event. Preserve + // that convention while rejecting every explicit unsuccessful status. + status := response.Get("status") + if !utf8.Valid(message) || !openAIEncryptedJSONUnambiguous(message) || + response.Get("error").Type != gjson.Null || response.Get("incomplete_details").Type != gjson.Null || + (status.Exists() && status.String() != "completed") { + return + } + h.responseID = strings.TrimSpace(gjson.GetBytes(message, "response.id").String()) + if h.responseID == "" { + return + } + h.completed = true + output := gjson.GetBytes(message, "response.output").Array() + if len(output) > 0 { + // The complete terminal array replaces streamed bodies, order and + // membership. Never append the earlier done items to it. + for _, item := range output { + if openAIWSHTTPBridgeCompletedItem(item) { + h.output = append(h.output, json.RawMessage(item.Raw)) + } + } + } else { + indices := make([]int64, 0, len(h.done)) + for index := range h.done { + indices = append(indices, index) + } + slices.Sort(indices) + for _, index := range indices { + h.output = append(h.output, h.done[index]) + } + } + h.output = deduplicateOpenAIWSHTTPBridgeOutput(h.output) + } +} + +func openAIWSHTTPBridgeCompletedItem(item gjson.Result) bool { + if !item.IsObject() || strings.TrimSpace(item.Get("type").String()) == "" { + return false + } + // item.done itself completes items whose type has no status field. + status := item.Get("status").String() + return status == "" || status == "completed" +} + +func deduplicateOpenAIWSHTTPBridgeOutput(items []json.RawMessage) []json.RawMessage { + seen := make(map[string]struct{}, len(items)) + output := make([]json.RawMessage, 0, len(items)) + for _, raw := range items { + item := gjson.ParseBytes(raw) + key := item.Get("id").String() + if key == "" { + key = item.Get("type").String() + "\x00" + item.Get("call_id").String() + if item.Get("call_id").String() == "" { + key = string(raw) + } + } + if _, exists := seen[key]; exists { + continue + } + seen[key] = struct{}{} + output = append(output, raw) + } + return output +} diff --git a/backend/internal/service/openai_ws_http_bridge_history_test.go b/backend/internal/service/openai_ws_http_bridge_history_test.go new file mode 100644 index 000000000000..3916e46e31df --- /dev/null +++ b/backend/internal/service/openai_ws_http_bridge_history_test.go @@ -0,0 +1,85 @@ +package service + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestIssue999HTTPBridgeDeliveryControls(t *testing.T) { + const message = `{"type":"message","id":"msg_fixture","role":"assistant","status":"completed","content":[{"type":"output_text","text":"fixture complete"}]}` + done := `{"type":"response.output_item.done","output_index":0,"item":` + message + `}` + completed := `{"type":"response.completed","response":{"id":"resp_fixture","status":"completed","output":[]}}` + for _, tc := range []struct { + name string + events []string + failWrite string + writeErr error + wantHistory bool + wantError bool + }{ + {name: "completed", events: []string{done, completed}, wantHistory: true}, + {name: "full_terminal_only", events: []string{strings.Replace(completed, `"output":[]`, `"output":[`+message+`]`, 1)}, wantHistory: true}, + {name: "legacy_implicit_completed", events: []string{done, strings.Replace(completed, `"status":"completed",`, "", 1)}, wantHistory: true}, + {name: "failed", events: []string{done, `{"type":"response.failed","response":{"id":"resp_fixture","status":"failed","output":[]}}`}}, + {name: "incomplete", events: []string{done, `{"type":"response.incomplete","response":{"id":"resp_fixture","status":"incomplete","output":[]}}`}}, + {name: "completed_with_incomplete_status", events: []string{done, strings.Replace(completed, `"status":"completed"`, `"status":"incomplete"`, 1)}}, + {name: "cancelled", events: []string{done, strings.Replace(completed, `"status":"completed"`, `"status":"cancelled"`, 1)}}, + {name: "completed_with_error", events: []string{done, strings.Replace(completed, `"output":[]`, `"error":{"message":"fixture refusal"},"output":[]`, 1)}}, + {name: "eof_before_terminal", events: []string{done}, wantError: true}, + {name: "added_only", events: []string{strings.Replace(done, "output_item.done", "output_item.added", 1), completed}}, + {name: "unfinished_item", events: []string{strings.Replace(done, `"status":"completed"`, `"status":"in_progress"`, 1), completed}}, + {name: "failed_item", events: []string{strings.Replace(done, `"status":"completed"`, `"status":"failed"`, 1), completed}}, + {name: "invalid_index", events: []string{strings.Replace(done, `"output_index":0`, `"output_index":-1`, 1), completed}}, + {name: "fractional_index", events: []string{strings.Replace(done, `"output_index":0`, `"output_index":0.5`, 1), completed}}, + {name: "missing_index", events: []string{strings.Replace(done, `"output_index":0,`, "", 1), completed}}, + {name: "undelivered_item", events: []string{done, completed}, failWrite: "response.output_item.done", writeErr: io.EOF}, + {name: "undelivered_terminal", events: []string{done, completed}, failWrite: "response.completed", writeErr: io.EOF}, + {name: "item_write_error", events: []string{done, completed}, failWrite: "response.output_item.done", writeErr: errors.New("fixture write failed"), wantError: true}, + {name: "terminal_write_error", events: []string{done, completed}, failWrite: "response.completed", writeErr: errors.New("fixture write failed"), wantError: true}, + } { + t.Run(tc.name, func(t *testing.T) { + var stream strings.Builder + for _, event := range tc.events { + fmt.Fprintf(&stream, "data: %s\n\n", event) + } + upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(stream.String()))}} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := &Account{ID: 999, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/responses", nil) + payload := []byte(`{"type":"response.create","model":"gpt-6.1-sol","store":false,"stream":true,"input":[{"role":"user","content":"fixture"}]}`) + result, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "fixture-token", payload, len(payload), "gpt-6.1-sol", "", "", "", "", 1, func(raw []byte) error { + if gjson.GetBytes(raw, "type").String() == tc.failWrite { + return tc.writeErr + } + return nil + }) + if tc.wantError { + require.Error(t, err) + } else { + require.NoError(t, err) + } + if tc.wantHistory { + require.NotNil(t, result) + require.True(t, result.wsReplayInputExists) + require.Len(t, result.wsReplayInput, 1) + require.JSONEq(t, message, string(result.wsReplayInput[0]), "ISSUE999_ASSISTANT_HISTORY_LOST") + require.Equal(t, result.wsReplayInput, result.wsAccountFailoverReplayInput) + } else if result != nil { + require.Empty(t, result.wsReplayInput, "unsuccessful or undelivered output cannot become history") + require.Empty(t, result.wsAccountFailoverReplayInput, "failover cannot bypass delivery controls") + } + }) + } +}