fix(openai-ws): keep fail-loud for unbound API-key continuations; add replay regression test

Drop the API-key exemption: the HTTP path also rejects a previous_response_id
whose owner record expired, and the HTTP bridge would strip the id silently.
Only the per-selection strict affinity re-evaluation remains, now pinned by
a regression test for a current-turn failover replay after a continuation.
This commit is contained in:
shaw committed 2026-12-03 16:06:59 +08:00
1 parent 5746b50e8b
commit e7bf4232cf
3 files changed
+209 -151

No files matched your search

@@ -2936,11 +2936,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
}
account := selection.Account
// API-key accounts resolve previous_response_id upstream (same as the HTTP
// path), so a missing local binding is forwarded and the upstream decides;
// only OAuth-like accounts, whose chain lives on the bound upstream session,
// fail loudly here.
if strictPreviousResponseAffinity && !scheduleDecision.StickyPreviousHit && !account.IsOpenAIApiKey() {
if strictPreviousResponseAffinity && !scheduleDecision.StickyPreviousHit {
if selection.ReleaseFunc != nil {
selection.ReleaseFunc()
selection.ReleaseFunc = nil
@@ -0,0 +1,202 @@
package handler
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
coderws "github.com/coder/websocket"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
type wsReplayFailoverUpstream struct {
mu sync.Mutex
calls map[int64]int
bodies map[int64][][]byte
}
func (u *wsReplayFailoverUpstream) Do(req *http.Request, proxyURL string, accountID int64, accountConcurrency int) (*http.Response, error) {
u.mu.Lock()
defer u.mu.Unlock()
body, _ := io.ReadAll(req.Body)
u.calls[accountID]++
u.bodies[accountID] = append(u.bodies[accountID], body)
n := u.calls[accountID]
sse := func(id string) *http.Response {
return &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\":\"" + id + "\",\"output\":[{\"id\":\"msg_" + id + "\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"ok-" + id + "\"}]}],\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n",
)),
}
}
if accountID == 9921 {
switch n {
case 1:
return sse("resp_f1_seed"), nil
case 2:
return sse("resp_f1_turn1"), nil
default:
return &http.Response{
StatusCode: http.StatusTooManyRequests,
Header: http.Header{"Content-Type": []string{"application/json"}, "Retry-After": []string{"600"}},
Body: io.NopCloser(strings.NewReader(`{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached"}}`)),
}, nil
}
}
return sse("resp_f1_replayed"), nil
}
func (u *wsReplayFailoverUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, accountConcurrency int, profile *tlsfingerprint.Profile) (*http.Response, error) {
return u.Do(req, proxyURL, accountID, accountConcurrency)
}
func TestOpenAIResponsesWebSocket_CurrentTurnReplayAfterContinuationIsNotRejected(t *testing.T) {
gin.SetMode(gin.TestMode)
upstream := &wsReplayFailoverUpstream{calls: map[int64]int{}, bodies: map[int64][][]byte{}}
groupID := int64(4291)
accounts := []service.Account{
{
ID: 9921, Name: "f1-apikey", Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey,
Status: service.StatusActive, Schedulable: true, Concurrency: 2, Priority: 0,
Credentials: map[string]any{"api_key": "sk-a", "base_url": "http://127.0.0.1:1"},
Extra: map[string]any{
"openai_apikey_responses_websockets_v2_enabled": true,
"openai_apikey_responses_websockets_v2_mode": service.OpenAIWSIngressModeHTTPBridge,
},
},
{
ID: 9922, Name: "f1-oauth", Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth,
Status: service.StatusActive, Schedulable: true, Concurrency: 2, Priority: 5,
Credentials: map[string]any{"access_token": "tok", "chatgpt_account_id": "acct"},
Extra: map[string]any{
"openai_oauth_responses_websockets_v2_enabled": true,
"openai_oauth_responses_websockets_v2_mode": service.OpenAIWSIngressModeHTTPBridge,
},
},
}
cfg := &config.Config{}
cfg.RunMode = config.RunModeSimple
cfg.Default.RateMultiplier = 1
cfg.Security.URLAllowlist.Enabled = false
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
cfg.Gateway.OpenAIWS.Enabled = true
cfg.Gateway.OpenAIWS.OAuthEnabled = true
cfg.Gateway.OpenAIWS.APIKeyEnabled = true
cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true
cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true
cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3
cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3
cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3
cfg.Gateway.MaxAccountSwitches = 2
accountRepo := &openAIWSFailoverHandlerAccountRepoStub{accounts: accounts}
rateLimitSvc := service.NewRateLimitService(accountRepo, nil, cfg, nil, nil)
billingCacheSvc := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCacheSvc.Stop)
gatewaySvc := service.NewOpenAIGatewayService(
accountRepo, nil, nil, nil, nil, nil, nil, cfg, nil, nil,
service.NewBillingService(cfg, nil), rateLimitSvc, billingCacheSvc,
upstream, &service.DeferredService{},
nil, nil, nil, nil, nil, nil, nil,
)
cache := &concurrencyCacheMock{
acquireUserSlotFn: func(ctx context.Context, userID int64, maxConcurrency int, requestID string) (bool, error) {
return true, nil
},
acquireAccountSlotFn: func(ctx context.Context, accountID int64, maxConcurrency int, requestID string) (bool, error) {
return true, nil
},
}
h := &OpenAIGatewayHandler{
gatewayService: gatewaySvc,
billingCacheService: billingCacheSvc,
apiKeyService: &service.APIKeyService{},
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second),
maxAccountSwitches: 2,
}
apiKey := &service.APIKey{
ID: 1891, GroupID: &groupID,
User: &service.User{ID: 1791, Status: service.StatusActive},
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive},
}
router := gin.New()
router.Use(func(c *gin.Context) {
c.Set(string(middleware.ContextKeyAPIKey), apiKey)
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.User.ID, Concurrency: 1})
c.Next()
})
router.GET("/openai/v1/responses", h.ResponsesWebSocket)
srv := httptest.NewServer(router)
defer srv.Close()
wsURL := "ws" + strings.TrimPrefix(srv.URL, "http") + "/openai/v1/responses"
dial := func() *coderws.Conn {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
c, _, err := coderws.Dial(ctx, wsURL, nil)
require.NoError(t, err)
return c
}
write := func(c *coderws.Conn, s string) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
require.NoError(t, c.Write(ctx, coderws.MessageText, []byte(s)))
}
readUntilTerminal := func(c *coderws.Conn) ([]byte, error) {
for {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
_, msg, err := c.Read(ctx)
cancel()
if err != nil {
return nil, err
}
switch gjson.GetBytes(msg, "type").String() {
case "response.completed", "error", "response.failed":
return msg, nil
}
}
}
// Seed connection binds resp_f1_seed to the API-key account 9921.
c1 := dial()
write(c1, `{"type":"response.create","model":"gpt-5.1","input":[{"type":"message","role":"user","content":"seed"}]}`)
msg, err := readUntilTerminal(c1)
require.NoError(t, err)
require.Equal(t, "resp_f1_seed", gjson.GetBytes(msg, "response.id").String(), string(msg))
require.NoError(t, c1.Close(coderws.StatusNormalClosure, "done"))
// Continuation connection: first frame continues resp_f1_seed (sticky hit 9921).
c2 := dial()
defer func() { _ = c2.CloseNow() }()
write(c2, `{"type":"response.create","model":"gpt-5.1","previous_response_id":"resp_f1_seed","input":[{"type":"message","role":"user","content":"turn1"}]}`)
msg, err = readUntilTerminal(c2)
require.NoError(t, err)
require.Equal(t, "resp_f1_turn1", gjson.GetBytes(msg, "response.id").String(), string(msg))
// Turn 2 fails on 9921 with 429 -> current-turn failover replay on 9922.
write(c2, `{"type":"response.create","model":"gpt-5.1","previous_response_id":"resp_f1_turn1","input":[{"type":"message","role":"user","content":"turn2"}]}`)
msg, err = readUntilTerminal(c2)
require.NoError(t, err, "connection closed instead of replaying on replacement account")
require.Equal(t, "response.completed", gjson.GetBytes(msg, "type").String(), string(msg))
require.Equal(t, "resp_f1_replayed", gjson.GetBytes(msg, "response.id").String())
upstream.mu.Lock()
defer upstream.mu.Unlock()
require.Len(t, upstream.bodies[9922], 1)
require.False(t, gjson.GetBytes(upstream.bodies[9922][0], "previous_response_id").Exists())
}
@@ -18,7 +18,7 @@ import (
"github.com/tidwall/gjson"
)
func TestOpenAIResponsesWebSocket_OAuthFirstFrameStickyMissFailsLoudlyWithPreviousResponseNotFound(t *testing.T) {
func TestOpenAIResponsesWebSocket_FirstFrameStickyMissFailsLoudlyWithPreviousResponseNotFound(t *testing.T) {
gin.SetMode(gin.TestMode)
var upstreamHits atomic.Int32
@@ -34,18 +34,18 @@ func TestOpenAIResponsesWebSocket_OAuthFirstFrameStickyMissFailsLoudlyWithPrevio
ID: 9911,
Name: "openai-ws-sticky-miss-acct",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 2,
Priority: 1,
Credentials: map[string]any{
"access_token": "oauth-token",
"base_url": upstream.URL,
"api_key": "sk-first",
"base_url": upstream.URL,
},
Extra: map[string]any{
"openai_oauth_responses_websockets_v2_enabled": true,
"openai_oauth_responses_websockets_v2_mode": service.OpenAIWSIngressModeCtxPool,
"openai_apikey_responses_websockets_v2_enabled": true,
"openai_apikey_responses_websockets_v2_mode": service.OpenAIWSIngressModeCtxPool,
},
},
}
@@ -57,7 +57,6 @@ func TestOpenAIResponsesWebSocket_OAuthFirstFrameStickyMissFailsLoudlyWithPrevio
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
cfg.Gateway.OpenAIWS.Enabled = true
cfg.Gateway.OpenAIWS.APIKeyEnabled = true
cfg.Gateway.OpenAIWS.OAuthEnabled = true
cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true
cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true
cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3
@@ -323,145 +322,6 @@ func TestOpenAIResponsesWebSocket_FirstFrameStickyHitContinuesWithPreviousRespon
require.Equal(t, "resp_ws_sticky_turn_1", gjson.GetBytes(secondUpstreamPayload, "previous_response_id").String())
}
func TestOpenAIResponsesWebSocket_APIKeyFirstFrameStickyMissForwardsPreviousResponseID(t *testing.T) {
gin.SetMode(gin.TestMode)
receivedCh := make(chan []byte, 2)
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := coderws.Accept(w, r, &coderws.AcceptOptions{CompressionMode: coderws.CompressionContextTakeover})
if err != nil {
return
}
defer func() { _ = conn.CloseNow() }()
readCtx, cancelRead := context.WithTimeout(r.Context(), 3*time.Second)
_, payload, readErr := conn.Read(readCtx)
cancelRead()
if readErr != nil {
return
}
receivedCh <- append([]byte(nil), payload...)
writeCtx, cancelWrite := context.WithTimeout(r.Context(), 3*time.Second)
_ = conn.Write(writeCtx, coderws.MessageText, []byte(`{"type":"response.completed","response":{"id":"resp_apikey_forwarded","model":"gpt-5.1","usage":{"input_tokens":5,"output_tokens":2}}}`))
cancelWrite()
}))
defer upstream.Close()
groupID := int64(4214)
accounts := []service.Account{
{
ID: 9915,
Name: "openai-ws-apikey-sticky-miss",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 2,
Priority: 1,
Credentials: map[string]any{
"api_key": "sk-first",
"base_url": upstream.URL,
},
Extra: map[string]any{
"openai_apikey_responses_websockets_v2_enabled": true,
"openai_apikey_responses_websockets_v2_mode": service.OpenAIWSIngressModeCtxPool,
},
},
}
cfg := &config.Config{}
cfg.RunMode = config.RunModeSimple
cfg.Default.RateMultiplier = 1
cfg.Security.URLAllowlist.Enabled = false
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
cfg.Gateway.OpenAIWS.Enabled = true
cfg.Gateway.OpenAIWS.APIKeyEnabled = true
cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true
cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true
cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3
cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3
cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3
cfg.Gateway.MaxAccountSwitches = 2
accountRepo := &openAIWSFailoverHandlerAccountRepoStub{accounts: accounts}
rateLimitSvc := service.NewRateLimitService(accountRepo, nil, cfg, nil, nil)
billingCacheSvc := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCacheSvc.Stop)
gatewaySvc := service.NewOpenAIGatewayService(
accountRepo,
nil, nil, nil, nil, nil, nil,
cfg,
nil, nil,
service.NewBillingService(cfg, nil),
rateLimitSvc,
billingCacheSvc,
nil,
&service.DeferredService{},
nil, nil, nil, nil, nil, nil, nil,
)
cache := &concurrencyCacheMock{
acquireUserSlotFn: func(ctx context.Context, userID int64, maxConcurrency int, requestID string) (bool, error) {
return true, nil
},
acquireAccountSlotFn: func(ctx context.Context, accountID int64, maxConcurrency int, requestID string) (bool, error) {
return true, nil
},
}
h := &OpenAIGatewayHandler{
gatewayService: gatewaySvc,
billingCacheService: billingCacheSvc,
apiKeyService: &service.APIKeyService{},
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second),
maxAccountSwitches: 2,
}
apiKey := &service.APIKey{
ID: 1813,
GroupID: &groupID,
User: &service.User{ID: 1713, Status: service.StatusActive},
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive},
}
router := gin.New()
router.Use(func(c *gin.Context) {
c.Set(string(middleware.ContextKeyAPIKey), apiKey)
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.User.ID, Concurrency: 1})
c.Next()
})
router.GET("/openai/v1/responses", h.ResponsesWebSocket)
handlerServer := httptest.NewServer(router)
defer handlerServer.Close()
dialCtx, cancelDial := context.WithTimeout(context.Background(), 3*time.Second)
clientConn, _, err := coderws.Dial(
dialCtx,
"ws"+strings.TrimPrefix(handlerServer.URL, "http")+"/openai/v1/responses",
&coderws.DialOptions{CompressionMode: coderws.CompressionContextTakeover},
)
cancelDial()
require.NoError(t, err)
defer func() { _ = clientConn.CloseNow() }()
writeCtx, cancelWrite := context.WithTimeout(context.Background(), 3*time.Second)
require.NoError(t, clientConn.Write(writeCtx, coderws.MessageText, []byte(
`{"type":"response.create","model":"gpt-5.1","previous_response_id":"resp_unbound_apikey_1","input":[{"type":"message","role":"user","content":"continue"}]}`,
)))
cancelWrite()
readCtx, cancelRead := context.WithTimeout(context.Background(), 3*time.Second)
_, rawEvent, err := clientConn.Read(readCtx)
cancelRead()
require.NoError(t, err)
require.Equal(t, "response.completed", gjson.GetBytes(rawEvent, "type").String())
select {
case payload := <-receivedCh:
require.Equal(t, "resp_unbound_apikey_1", gjson.GetBytes(payload, "previous_response_id").String(),
"API-key accounts resolve previous_response_id upstream; the gateway must forward it unchanged")
case <-time.After(3 * time.Second):
t.Fatal("upstream did not receive the forwarded first frame")
}
}
func TestOpenAIResponsesWebSocket_GrokFirstFramePreviousResponseIDNotRejectedByOpenAIStickyCheck(t *testing.T) {
got := runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"public-alias","previous_response_id":"resp_grok_prev_1","input":[{"type":"message","role":"user","content":"full history"}]}`,