From 4e694a37457da2bd9bffdf54191b16dc33c90d3e Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 4 Dec 2026 18:24:50 +0800 Subject: [PATCH] fix(openai-ws): reconcile HTTP bridge parent check with history limit and sticky continuations Follow-up to #8302 (f7ec8b3ce). Placing the unresolved `previous_response_id` 1008 rejection at the top of the HTTP bridge turn loop ran before `hooks.BeforeTurn` and before the `historyLost` 1013 (`StatusTryAgainLater`) check from #9203, and rejected valid turn-1 sticky API-key continuations (`store != false` bound in `stateStore`) as well as Grok HTTP bridge turns. Move the 1008 check after `BeforeTurn` and `historyLost`, allow turn-1 API-key continuations bound to the selected account when `store != false`, and preserve Grok HTTP bridge handling while keeping all #8302 unresolved-parent cases closed with 1008. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../service/openai_ws_forwarder_ingress.go | 31 +++++--- .../service/openai_ws_http_bridge_p2_test.go | 73 +++++++++++++++++++ 2 files changed, 95 insertions(+), 9 deletions(-) diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 317d647f70..37bbe215c5 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -607,15 +607,6 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( return err } } - // HTTP cannot resolve an opaque parent; only this connection's replay can. - if parent := currentBridgePayload.previousResponseID; parent != "" && - (parent != bridgeLastResponseID || !bridgeReplayInputExists || len(bridgeReplayInput) == 0) { - return NewOpenAIWSClientCloseError( - coderws.StatusPolicyViolation, - "previous_response_id cannot be resolved on this connection; resend full input without previous_response_id", - nil, - ) - } if hooks != nil && hooks.BeforeTurn != nil { if err := hooks.BeforeTurn(turn); err != nil { return err @@ -652,6 +643,28 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( if needsBridgeReplay && historyLost { return NewResponsesWSBridgeHistoryCloseError() } + // HTTP cannot resolve an opaque parent unless this connection holds its + // replay chain, the platform handles continuations natively on HTTP bridge, + // or turn 1 sticky-routed to the API-key account bound to that response ID. + if parent := currentBridgePayload.previousResponseID; parent != "" { + resolvedInConnection := parent == bridgeLastResponseID && bridgeReplayInputExists && len(bridgeReplayInput) > 0 + resolvedBoundAPIKey := turn == 1 && + account != nil && + account.IsOpenAIApiKey() && + !s.isOpenAIWSStoreDisabledInRequestRaw(currentBridgePayload.payloadRaw, account) && + stateStore != nil && + func() bool { + boundAccountID, getErr := stateStore.GetResponseAccount(ctx, groupID, parent) + return getErr == nil && boundAccountID == account.ID + }() + if !resolvedInConnection && !resolvedBoundAPIKey && (account == nil || account.Platform != PlatformGrok) { + return NewOpenAIWSClientCloseError( + coderws.StatusPolicyViolation, + "previous_response_id cannot be resolved on this connection; resend full input without previous_response_id", + nil, + ) + } + } if !needsBridgeReplay { // A self-contained request replaces the previous replay chain. bridgeReplayInput, bridgeAccountFailoverInput = nil, nil diff --git a/backend/internal/service/openai_ws_http_bridge_p2_test.go b/backend/internal/service/openai_ws_http_bridge_p2_test.go index c0ed7e58b6..f2861432d0 100644 --- a/backend/internal/service/openai_ws_http_bridge_p2_test.go +++ b/backend/internal/service/openai_ws_http_bridge_p2_test.go @@ -114,4 +114,77 @@ func TestOpenAIWSHTTPBridgeRejectsUnresolvedPreviousResponseID(t *testing.T) { require.Len(t, upstream.bodies, priorTurns, "never POST a delta whose parent cannot be reconstructed") }) } + + t.Run("bound_apikey_cross_connection_turn1_allowed_but_store_false_rejected", func(t *testing.T) { + upstream := &httpUpstreamRecorder{ + responses: []*http.Response{ + { + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader("data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_next\",\"output\":[]}}\n\n")), + }, + }, + } + cfg := &config.Config{} + cfg.Gateway.OpenAIWS.Enabled = true + cfg.Gateway.OpenAIWS.APIKeyEnabled = true + cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true + cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true + cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3 + cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3 + svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream, cache: &stubGatewayCache{}, openaiWSResolver: NewOpenAIWSProtocolResolver(cfg)} + account := &Account{ + ID: 9006, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{"openai_apikey_responses_websockets_v2_mode": OpenAIWSIngressModeHTTPBridge}, + Status: StatusActive, Schedulable: true, Concurrency: 1, + } + require.NoError(t, svc.getOpenAIWSStateStore().BindResponseAccount(context.Background(), 0, "resp_bound", account.ID, time.Hour)) + + runTurn1 := func(frame string) (int, coderws.StatusCode) { + wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, nil) + if err != nil { + return + } + defer func() { _ = conn.CloseNow() }() + readCtx, cancel := context.WithTimeout(r.Context(), 3*time.Second) + _, firstMessage, err := conn.Read(readCtx) + cancel() + if err != nil { + return + } + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = r.Clone(r.Context()) + proxyErr := svc.ProxyResponsesWebSocketFromClient(r.Context(), c, conn, account, "sk-test", firstMessage, nil) + var closeErr *OpenAIWSClientCloseError + if errors.As(proxyErr, &closeErr) { + _ = conn.Close(closeErr.StatusCode(), closeErr.Reason()) + } + })) + defer wsServer.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + client, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(wsServer.URL, "http"), nil) + require.NoError(t, err) + defer func() { _ = client.CloseNow() }() + require.NoError(t, client.Write(ctx, coderws.MessageText, []byte(frame))) + _, event, readErr := client.Read(ctx) + if readErr != nil { + return len(upstream.bodies), coderws.CloseStatus(readErr) + } + require.Equal(t, "response.completed", gjson.GetBytes(event, "type").String()) + _ = client.Close(coderws.StatusNormalClosure, "done") + return len(upstream.bodies), coderws.StatusNormalClosure + } + + posts, status := runTurn1(`{"type":"response.create","model":"gpt-6.1-sol","store":false,"previous_response_id":"resp_bound","input":[{"role":"user","content":"delta"}]}`) + require.Equal(t, coderws.StatusPolicyViolation, status) + require.Zero(t, posts) + + posts, status = runTurn1(`{"type":"response.create","model":"gpt-6.1-sol","previous_response_id":"resp_bound","input":[{"role":"user","content":"delta"}]}`) + require.Equal(t, coderws.StatusNormalClosure, status) + require.Equal(t, 1, posts) + }) }