mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 08:05:12 +00:00
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>
This commit is contained in:
1 parent
f7ec8b3cee
commit
4e694a3745
2 files changed
+95
-9
No files matched your search
@@ -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
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user