Merge pull request #968 from lij768423-svg/feat/empty-hold-idle-sse

fix: do not fail-open empty held streams as HTTP 200
This commit is contained in:
Chenyme authored and GitHub committed 2026-08-19 11:06:49 +08:00
commit 0c51ca8bf1
9 files changed
+927 -72

No files matched your search

@@ -181,6 +181,8 @@ func newTransportUpstreamFailure(err error, accountID uint64, accountName string
status, code, message = http.StatusGatewayTimeout, "upstream_header_timeout", "等待上游响应头超时"
} else if neterrorpkg.IsUpstreamStreamIdleTimeout(err) {
status, code, message = http.StatusGatewayTimeout, "upstream_stream_idle_timeout", "上游流式响应长时间无数据"
} else if errors.Is(err, errQualityEmptyStream) {
status, code, message = http.StatusBadGateway, "upstream_stream_empty", "上游流式响应为空"
} else if errors.Is(err, context.DeadlineExceeded) {
code, message = "upstream_timeout", "上游服务响应超时"
}
@@ -13,6 +13,7 @@ import (
inferencedomain "github.com/chenyme/grok2api/backend/internal/domain/inference"
modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model"
infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress"
neterrorpkg "github.com/chenyme/grok2api/backend/internal/pkg/neterror"
)
const (
@@ -22,9 +23,15 @@ const (
defaultQualityMaxAttempts = 6
defaultQualityHoldTimeout = 3 * time.Second
defaultQualityMinOutput = int64(32)
// An empty stream that idles while held is treated as an account-quality
// failure: the request can still rotate before any bytes reach the client.
qualityIdleAccountCooldown = 24 * time.Hour
)
var errQualityDegraded = errors.New("上游响应缺少推理")
var (
errQualityDegraded = errors.New("上游响应缺少推理")
errQualityEmptyStream = errors.New("上游流式响应为空")
)
// QualityRetryRuntime is the isolated request-path withhold/retry policy.
// Zero Enabled leaves production behavior unchanged.
@@ -99,6 +106,8 @@ func (s *Service) qualityRetryConfig() QualityRetryRuntime {
// Thinking (or reasoning tokens) always delivers. A finished or expired
// sample with enough visible output and no reasoning is 降智 and withheld.
// Short replies below minOutput are delivered so "ok"/"yes" is not retried.
// A hold timeout with no visible output is not fail-open: keep waiting for
// more bytes or a stream abort so an empty hang is not flushed as HTTP 200.
func ClassifyQualityHold(sig QualityStreamSignals, minOutput int64) QualityVerdict {
if minOutput <= 0 {
minOutput = defaultQualityMinOutput
@@ -112,6 +121,9 @@ func ClassifyQualityHold(sig QualityStreamSignals, minOutput int64) QualityVerdi
}
enough := output >= minOutput
if sig.Terminal {
if output <= 0 {
return QualityWait
}
if enough {
return QualityWithhold
}
@@ -121,11 +133,50 @@ func ClassifyQualityHold(sig QualityStreamSignals, minOutput int64) QualityVerdi
return QualityWithhold
}
if sig.HoldExpired {
if output <= 0 {
return QualityWait
}
return QualityDeliver
}
return QualityWait
}
// qualityPeekAbortError prefers the idle-timeout cause over a plain
// context.Canceled so the attempt loop can retry instead of treating the
// abort as a client 499.
func qualityPeekAbortError(ctx context.Context, err error) error {
if ctx != nil {
if cause := context.Cause(ctx); neterrorpkg.IsUpstreamStreamIdleTimeout(cause) {
return cause
}
}
if neterrorpkg.IsUpstreamStreamIdleTimeout(err) {
return err
}
if err != nil {
return err
}
if ctx != nil {
return ctx.Err()
}
return nil
}
// isClientRequestCancel reports a real client disconnect. Upstream idle
// timeouts cancel the same context and must not be classified as 499.
func isClientRequestCancel(ctx context.Context, err error) bool {
if neterrorpkg.IsUpstreamStreamIdleTimeout(err) {
return false
}
if ctx != nil && neterrorpkg.IsUpstreamStreamIdleTimeout(context.Cause(ctx)) {
return false
}
if ctx != nil && ctx.Err() != nil {
return true
}
return errors.Is(err, context.Canceled)
}
// DecideQualityRetry caps withhold recovery at maxAttempts (default 6:
// original + five extra accounts). The last withhold
// (attemptIndex == maxAttempts-1) is fail-open unless OnExhausted is fail_closed.
@@ -364,7 +364,7 @@ func noteVisibleContent(state *qualityScanState, text string) {
func peekQualityStream(ctx context.Context, body io.ReadCloser, protocol string, cfg QualityRetryRuntime) (io.ReadCloser, QualityVerdict, Usage, string, error) {
cfg = normalizeQualityRetry(cfg)
if body == nil {
return io.NopCloser(bytes.NewReader(nil)), QualityDeliver, Usage{}, "", nil
return io.NopCloser(bytes.NewReader(nil)), QualityWait, Usage{}, "", errQualityEmptyStream
}
pump := newQualityReadPump(body)
state := qualityScanState{protocol: protocol}
@@ -380,14 +380,15 @@ func peekQualityStream(ctx context.Context, body io.ReadCloser, protocol string,
select {
case <-ctx.Done():
_ = pump.Close()
return io.NopCloser(bytes.NewReader(held.Bytes())), QualityDeliver, state.usage, state.responseID, ctx.Err()
return io.NopCloser(bytes.NewReader(held.Bytes())), QualityWait, state.usage, state.responseID, qualityPeekAbortError(ctx, ctx.Err())
case <-holdTimer.C:
sig.HoldExpired = true
return newPrefixReplay(&held, pump), ClassifyQualityHold(sig, cfg.MinOutputTokens), state.usage, state.responseID, nil
if verdict := ClassifyQualityHold(sig, cfg.MinOutputTokens); verdict != QualityWait {
return newPrefixReplay(&held, pump), verdict, state.usage, state.responseID, nil
}
case result, ok := <-pump.results:
if !ok {
state.terminal = true
return newPrefixReplay(&held, pump), ClassifyQualityHold(state.signals(), cfg.MinOutputTokens), state.usage, state.responseID, nil
return finishQualityPeek(&held, pump, &state, cfg)
}
if len(result.data) > 0 {
if held.Len()+len(result.data) > qualityHoldMaxBufferBytes {
@@ -398,17 +399,33 @@ func peekQualityStream(ctx context.Context, body io.ReadCloser, protocol string,
ObserveQualityChunk(&state, result.data)
}
if result.err == io.EOF {
state.terminal = true
return newPrefixReplay(&held, pump), ClassifyQualityHold(state.signals(), cfg.MinOutputTokens), state.usage, state.responseID, nil
return finishQualityPeek(&held, pump, &state, cfg)
}
if result.err != nil {
_ = pump.Close()
return io.NopCloser(bytes.NewReader(held.Bytes())), QualityDeliver, state.usage, state.responseID, result.err
return io.NopCloser(bytes.NewReader(held.Bytes())), QualityWait, state.usage, state.responseID, qualityPeekAbortError(ctx, result.err)
}
}
}
}
func finishQualityPeek(held *bytes.Buffer, pump *qualityReadPump, state *qualityScanState, cfg QualityRetryRuntime) (io.ReadCloser, QualityVerdict, Usage, string, error) {
if state == nil {
return io.NopCloser(bytes.NewReader(nil)), QualityWait, Usage{}, "", errQualityEmptyStream
}
if len(state.pending) > 0 {
// Process a final valid SSE data line even when the upstream omitted its
// trailing newline.
ObserveQualityChunk(state, []byte{'\n'})
}
state.terminal = true
signals := state.signals()
if !signals.HasThinking && signals.ReasoningTokens <= 0 && signals.OutputTokens <= 0 && signals.VisibleTokens <= 0 {
return newPrefixReplay(held, pump), QualityWait, state.usage, state.responseID, errQualityEmptyStream
}
return newPrefixReplay(held, pump), ClassifyQualityHold(signals, cfg.MinOutputTokens), state.usage, state.responseID, nil
}
func newPrefixReplay(held *bytes.Buffer, rest io.ReadCloser) io.ReadCloser {
if rest == nil {
rest = io.NopCloser(bytes.NewReader(nil))
@@ -2,6 +2,7 @@ package gateway
import (
"context"
"errors"
"fmt"
"io"
"net/http"
@@ -20,6 +21,7 @@ import (
"github.com/chenyme/grok2api/backend/internal/infra/persistence/relational"
"github.com/chenyme/grok2api/backend/internal/infra/provider"
"github.com/chenyme/grok2api/backend/internal/infra/runtime/memory"
neterrorpkg "github.com/chenyme/grok2api/backend/internal/pkg/neterror"
)
func TestClassifyQualityHold(t *testing.T) {
@@ -34,9 +36,12 @@ func TestClassifyQualityHold(t *testing.T) {
{name: "visible 32 no think withhold", sig: QualityStreamSignals{VisibleTokens: 32, Terminal: true}, want: QualityWithhold},
{name: "output 40 no think withhold", sig: QualityStreamSignals{OutputTokens: 40, Terminal: true}, want: QualityWithhold},
{name: "short no think delivers", sig: QualityStreamSignals{VisibleTokens: 10, Terminal: true}, want: QualityDeliver},
{name: "empty terminal waits for transport handling", sig: QualityStreamSignals{Terminal: true}, want: QualityWait},
{name: "midstream enough content withhold", sig: QualityStreamSignals{VisibleTokens: 64}, want: QualityWithhold},
{name: "wait for more", sig: QualityStreamSignals{VisibleTokens: 8}, want: QualityWait},
{name: "hold expired short delivers", sig: QualityStreamSignals{VisibleTokens: 8, HoldExpired: true}, want: QualityDeliver},
{name: "hold expired empty waits", sig: QualityStreamSignals{HoldExpired: true}, want: QualityWait},
{name: "hold expired zero tokens waits", sig: QualityStreamSignals{VisibleTokens: 0, OutputTokens: 0, HoldExpired: true}, want: QualityWait},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
@@ -422,51 +427,90 @@ func TestPeekQualityStreamHoldTimeoutInterruptsBlockedReadAndPreservesRemainder(
}
}
func TestPeekQualityStreamHoldTimeoutCoversBlockedFirstByte(t *testing.T) {
func TestPeekQualityStreamHoldTimeoutEmptyDoesNotFailOpen(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancelCause(context.Background())
reader, writer := io.Pipe()
continueWrite := make(chan struct{})
writeErr := make(chan error, 1)
defer writer.Close()
done := make(chan struct{})
var verdict QualityVerdict
var peekErr error
go func() {
select {
case <-continueWrite:
case <-time.After(500 * time.Millisecond):
}
_, err := io.WriteString(writer, sse(
`data: {"choices":[{"delta":{"content":"late first byte"}}]}`,
"data: [DONE]",
))
if closeErr := writer.Close(); err == nil {
err = closeErr
}
writeErr <- err
defer close(done)
_, verdict, _, _, peekErr = peekQualityStream(ctx, reader, qualityProtocolChat, QualityRetryRuntime{
MinOutputTokens: 32,
HoldTimeout: 20 * time.Millisecond,
})
}()
select {
case <-done:
t.Fatal("empty hold timeout must keep reading, not fail-open")
case <-time.After(50 * time.Millisecond):
}
cancel(neterrorpkg.ErrUpstreamStreamIdleTimeout)
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("peekQualityStream did not return after idle cancel")
}
if !neterrorpkg.IsUpstreamStreamIdleTimeout(peekErr) {
t.Fatalf("peekErr = %v, want idle timeout", peekErr)
}
if verdict != QualityWait {
t.Fatalf("verdict=%s, want wait so the loop does not fail-open", verdict)
}
}
started := time.Now()
replay, verdict, _, _, err := peekQualityStream(context.Background(), reader, qualityProtocolChat, QualityRetryRuntime{
MinOutputTokens: 32,
HoldTimeout: 30 * time.Millisecond,
})
func TestPeekQualityStreamEmptyEOFRequestsAnotherAccount(t *testing.T) {
t.Parallel()
replay, verdict, _, _, err := peekQualityStream(
context.Background(),
io.NopCloser(strings.NewReader("")),
qualityProtocolResponses,
QualityRetryRuntime{MinOutputTokens: 32, HoldTimeout: time.Second},
)
if replay != nil {
defer replay.Close()
}
if !errors.Is(err, errQualityEmptyStream) {
t.Fatalf("peek error = %v, want empty stream", err)
}
if verdict != QualityWait {
t.Fatalf("verdict = %s, want wait", verdict)
}
}
func TestPeekQualityStreamProcessesUnterminatedFinalEvent(t *testing.T) {
t.Parallel()
body := io.NopCloser(strings.NewReader(`data: {"type":"response.output_text.delta","delta":"ok"}`))
replay, verdict, _, _, err := peekQualityStream(
context.Background(), body, qualityProtocolResponses,
QualityRetryRuntime{MinOutputTokens: 32, HoldTimeout: time.Second},
)
if err != nil {
t.Fatal(err)
}
defer replay.Close()
close(continueWrite)
if elapsed := time.Since(started); elapsed < 20*time.Millisecond || elapsed > 200*time.Millisecond {
t.Fatalf("first-byte hold returned after %s, want the 30ms timeout", elapsed)
}
if verdict != QualityDeliver {
t.Fatalf("empty timed-out prefix verdict = %s", verdict)
t.Fatalf("verdict = %s, want deliver for a real short response", verdict)
}
body, err := io.ReadAll(replay)
if err != nil {
t.Fatal(err)
}
func TestQualityPeekAbortErrorPrefersIdleCause(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancelCause(context.Background())
cancel(neterrorpkg.ErrUpstreamStreamIdleTimeout)
got := qualityPeekAbortError(ctx, context.Canceled)
if !neterrorpkg.IsUpstreamStreamIdleTimeout(got) {
t.Fatalf("abort error = %v, want idle timeout", got)
}
if err := <-writeErr; err != nil {
t.Fatal(err)
if isClientRequestCancel(ctx, got) {
t.Fatal("idle timeout must not look like a client cancel")
}
if !strings.Contains(string(body), "late first byte") {
t.Fatalf("replay lost post-timeout first byte: %q", body)
plain, plainCancel := context.WithCancel(context.Background())
plainCancel()
if !isClientRequestCancel(plain, context.Canceled) {
t.Fatal("plain cancel must still be a client cancel")
}
}
@@ -538,8 +582,8 @@ func TestAttemptLoopQualityHold(t *testing.T) {
responseRepo := relational.NewResponseRepository(database)
keyRepo := relational.NewClientKeyRepository(database)
credentials := make([]accountdomain.Credential, 0, 2)
for index, name := range []string{"quality-a", "quality-b"} {
credentials := make([]accountdomain.Credential, 0, 3)
for index, name := range []string{"quality-empty", "quality-no-think", "quality-thinking"} {
credential, _, createErr := accountRepo.UpsertByIdentity(ctx, accountdomain.Credential{
Provider: accountdomain.ProviderBuild, Name: name, SourceKey: name, EncryptedAccessToken: name,
EncryptedRefreshToken: "refresh-" + name, ExpiresAt: time.Now().Add(time.Hour),
@@ -578,15 +622,16 @@ func TestAttemptLoopQualityHold(t *testing.T) {
"data: [DONE]",
)
adapter := &scriptedBuildAdapter{responses: map[uint64][]scriptedBuildResponse{
credentials[0].ID: {{status: http.StatusOK, body: noThink}},
credentials[1].ID: {{status: http.StatusOK, body: thinking}},
credentials[0].ID: {{status: http.StatusOK, body: ""}},
credentials[1].ID: {{status: http.StatusOK, body: noThink}},
credentials[2].ID: {{status: http.StatusOK, body: thinking}},
}}
registry := provider.NewRegistry(adapter)
sticky := memory.NewStickyStore()
accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil)
selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute)
service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(nil, nil, nil, 60, 4, nil), registry, selector, responseRepo, 3)
service.UpdateQualityRetry(QualityRetryRuntime{Enabled: true, MaxAttempts: 2, MinOutputTokens: 32, OnExhausted: qualityRetryFailOpen, HoldTimeout: time.Second})
service.UpdateQualityRetry(QualityRetryRuntime{Enabled: true, MaxAttempts: 3, MinOutputTokens: 32, OnExhausted: qualityRetryFailOpen, HoldTimeout: time.Second})
result, err := service.CreateChatCompletion(ctx, Input{
RequestID: "req-quality-hold", ClientKey: clientKey, PublicModel: "grok-4.6", Streaming: true,
@@ -608,8 +653,18 @@ func TestAttemptLoopQualityHold(t *testing.T) {
t.Fatal("first no-think body must not be delivered")
}
attempts := adapter.Attempts()
if len(attempts) != 2 || attempts[0] != credentials[0].ID || attempts[1] != credentials[1].ID {
t.Fatalf("expected account exclude+retry, attempts=%#v want [%d %d]", attempts, credentials[0].ID, credentials[1].ID)
if len(attempts) != 3 || attempts[0] != credentials[0].ID || attempts[1] != credentials[1].ID || attempts[2] != credentials[2].ID {
t.Fatalf("expected empty+no-think account exclusion and retry, attempts=%#v", attempts)
}
emptyAccount, err := accountRepo.Get(ctx, credentials[0].ID)
if err != nil {
t.Fatal(err)
}
if emptyAccount.FailureCount != 1 || emptyAccount.CooldownUntil == nil {
t.Fatalf("empty stream account was not cooled: %#v", emptyAccount)
}
if remaining := time.Until(*emptyAccount.CooldownUntil); remaining < 23*time.Hour || remaining > 24*time.Hour+time.Minute {
t.Fatalf("empty stream cooldown = %s, want about 24h", remaining)
}
logs, total, err := auditRepo.List(ctx, 0, 20)
if err != nil {
@@ -617,7 +672,7 @@ func TestAttemptLoopQualityHold(t *testing.T) {
}
var degraded, delivered bool
for _, rec := range logs {
if rec.ErrorCode == ErrorQualityDegraded && rec.AccountID != nil && *rec.AccountID == credentials[0].ID {
if rec.ErrorCode == ErrorQualityDegraded && rec.AccountID != nil && *rec.AccountID == credentials[1].ID {
degraded = true
}
if rec.RequestID == "req-quality-hold" && rec.ErrorCode == "" && rec.StatusCode == http.StatusOK {
@@ -117,7 +117,10 @@ type Usage struct {
// zero value used when a response fails before usage is available. Token
// counts may legitimately all be zero, so the numeric fields cannot carry
// this presence information by themselves.
Reported bool
Reported bool
// OutputObserved records that the transport actually forwarded generated
// content even when an interrupted upstream never emitted final usage.
OutputObserved bool
InputTokens int64
CachedInputTokens int64
OutputTokens int64
@@ -454,7 +457,9 @@ func (s *Service) UpdateMaxAttempts(maxAttempts int) { s.maxAttempts.Store(int64
// UpdateVideoMaxAttempts configures create-phase account failover for video jobs.
// 0 is treated as the general default pool size for legacy configs.
func (s *Service) UpdateVideoMaxAttempts(maxAttempts int) { s.videoMaxAttempts.Store(int64(maxAttempts)) }
func (s *Service) UpdateVideoMaxAttempts(maxAttempts int) {
s.videoMaxAttempts.Store(int64(maxAttempts))
}
// UpdateMarkBuildChatDeniedAsReauth 热更新 Build chat 永久拒绝是否标 reauthRequired。
// 默认 false:仅模型级冷却;true 时按旧逻辑将账号标为失效并出池。
@@ -1036,8 +1041,9 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
lease.completeSelectorObservation(successful)
budget := newFinalizationBudget(string(operation), string(route.Provider))
if isUpstreamStreamFailure(errorCode) {
status, retryAfter := streamFailureHealthPenalty(errorCode, usage)
if err := budget.run("account_health", finalizationHealthBudget, func(stageCtx context.Context) error {
return s.selector.MarkFailureAfterSuccess(stageCtx, credential, 0, 0)
return s.selector.MarkFailureAfterSuccess(stageCtx, credential, status, retryAfter)
}); err != nil {
s.logger.Warn("stream_failure_health_write_failed", "account_id", credential.ID, "provider", credential.Provider, "error", err)
}
@@ -1501,11 +1507,27 @@ attemptLoop:
}
lease.Release()
lastErr = peekErr
if ctx.Err() != nil || errors.Is(peekErr, context.Canceled) {
if isClientRequestCancel(ctx, peekErr) {
lastFailure = &UpstreamFailure{HTTPStatus: 499, Code: "request_canceled", PublicMessage: "请求已取消", AccountID: credential.ID, AccountName: credential.Name, Cause: firstError(ctx.Err(), peekErr)}
break
}
lastFailure = newTransportUpstreamFailure(peekErr, credential.ID, credential.Name)
if neterrorpkg.IsUpstreamStreamIdleTimeout(peekErr) || neterrorpkg.IsUpstreamStreamIdleTimeout(context.Cause(ctx)) || errors.Is(peekErr, errQualityEmptyStream) {
logPrefix := "quality_peek_idle"
if errors.Is(peekErr, errQualityEmptyStream) {
logPrefix = "quality_peek_empty"
}
writeCtx, writeCancel := context.WithTimeout(context.WithoutCancel(ctx), finalizationTimeout)
if markErr := s.selector.MarkFailureAfterSuccess(writeCtx, credential, http.StatusGatewayTimeout, qualityIdleAccountCooldown); markErr != nil {
s.logger.Warn(logPrefix+"_cooldown_failed", "request_id", input.RequestID, "account_id", credential.ID, "error", markErr)
} else {
s.logger.Warn(logPrefix+"_retry", "request_id", input.RequestID, "account_id", credential.ID, "cooldown", qualityIdleAccountCooldown)
}
writeCancel()
}
if shouldStopForNonAccountFingerprint(failureFingerprints, lastFailure) {
break
}
continue
}
response.Body = replay
@@ -1634,13 +1656,20 @@ attemptLoop:
func isUpstreamStreamFailure(errorCode string) bool {
switch errorCode {
case "upstream_stream_incomplete", "upstream_stream_interrupted":
case "upstream_stream_incomplete", "upstream_stream_interrupted", "upstream_stream_idle_timeout":
return true
default:
return false
}
}
func streamFailureHealthPenalty(errorCode string, usage Usage) (int, time.Duration) {
if errorCode == "upstream_stream_idle_timeout" && !usage.OutputObserved && usage.OutputTokens == 0 && usage.ReasoningTokens == 0 {
return http.StatusGatewayTimeout, qualityIdleAccountCooldown
}
return 0, 0
}
// auditRequestSucceeded keeps transport truth (the HTTP status) separate from
// the terminal request outcome. A stream that fails after 2xx headers is not a
// successful request even though its HTTP status remains 2xx.
@@ -1937,7 +1966,7 @@ func shouldStopForNonAccountFingerprint(fingerprints map[string]int, failure *Up
}
fingerprints[failure.Fingerprint]++
limit := nonAccountFailureFingerprintLimit
if failure.Code == "upstream_stream_idle_timeout" || failure.Fingerprint == "upstream_stream_idle_timeout" {
if failure.Code == "upstream_stream_idle_timeout" || failure.Fingerprint == "upstream_stream_idle_timeout" || failure.Code == "upstream_stream_empty" || failure.Fingerprint == "upstream_stream_empty" {
limit = streamIdleFailureFingerprintLimit
}
return fingerprints[failure.Fingerprint] >= limit
@@ -379,7 +379,7 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) {
selector.accounts = healthBlocker
finalized := make(chan struct{})
go func() {
interrupted.Finalize(Usage{}, "", "upstream_stream_incomplete")
interrupted.Finalize(Usage{}, "", "upstream_stream_idle_timeout")
close(finalized)
}()
select {
@@ -402,9 +402,13 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) {
}
_ = interrupted.Body.Close()
interruptedAccount, err := accountRepo.Get(ctx, adapter.attempts[0])
if err != nil || interruptedAccount.FailureCount != 0 || interruptedAccount.CooldownUntil == nil {
if err != nil || interruptedAccount.FailureCount != 1 || interruptedAccount.CooldownUntil == nil {
t.Fatalf("interrupted account health = %#v, err=%v", interruptedAccount, err)
}
remaining := time.Until(*interruptedAccount.CooldownUntil)
if remaining < 23*time.Hour || remaining > 24*time.Hour+time.Minute {
t.Fatalf("idle stream cooldown = %s, want about 24h", remaining)
}
}
func TestGatewayBuildResponseHeaderTimeoutDoesNotSwitchAccounts(t *testing.T) {
@@ -4273,6 +4277,7 @@ func TestAuditRequestSucceeded(t *testing.T) {
{name: "2xx without error succeeds", statusCode: 200, errorCode: "", want: true},
{name: "2xx stream interruption fails", statusCode: 200, errorCode: "upstream_stream_interrupted", want: false},
{name: "2xx stream incomplete fails", statusCode: 200, errorCode: "upstream_stream_incomplete", want: false},
{name: "2xx stream idle timeout fails", statusCode: 200, errorCode: "upstream_stream_idle_timeout", want: false},
{name: "any 2xx error fails", statusCode: 201, errorCode: "stream_interrupted", want: false},
{name: "4xx fails", statusCode: 404, errorCode: "upstream_error", want: false},
{name: "5xx fails", statusCode: 502, errorCode: "upstream_server_error", want: false},
@@ -4285,3 +4290,33 @@ func TestAuditRequestSucceeded(t *testing.T) {
})
}
}
func TestIsUpstreamStreamFailureIncludesIdleTimeout(t *testing.T) {
if !isUpstreamStreamFailure("upstream_stream_idle_timeout") {
t.Fatal("idle timeout must cool the hanging account")
}
if !isUpstreamStreamFailure("upstream_stream_interrupted") || !isUpstreamStreamFailure("upstream_stream_incomplete") {
t.Fatal("existing stream-failure codes must stay classified")
}
if isUpstreamStreamFailure("") || isUpstreamStreamFailure("quality_degraded") {
t.Fatal("non-stream codes must not look like mid-stream failures")
}
}
func TestStreamFailureHealthPenaltyOnlyLongCoolsTrulyEmptyIdle(t *testing.T) {
t.Parallel()
status, cooldown := streamFailureHealthPenalty("upstream_stream_idle_timeout", Usage{})
if status != http.StatusGatewayTimeout || cooldown != qualityIdleAccountCooldown {
t.Fatalf("empty idle penalty = (%d, %s)", status, cooldown)
}
for _, usage := range []Usage{
{OutputObserved: true},
{OutputTokens: 1},
{ReasoningTokens: 1},
} {
status, cooldown = streamFailureHealthPenalty("upstream_stream_idle_timeout", usage)
if status != 0 || cooldown != 0 {
t.Fatalf("non-empty idle usage %#v received long penalty (%d, %s)", usage, status, cooldown)
}
}
}
@@ -1282,20 +1282,40 @@ type responseMetadata struct {
cacheCreationInputTokens int64
ResponseID string
Model string
SequenceNumber int64
StreamFailure *gateway.StreamFailureDiagnostic
}
func copyStream(writer gin.ResponseWriter, source io.Reader, protocol streamProtocol, onFirstToken func()) (responseMetadata, error) {
inspector := &responseInspector{protocol: protocol, onFirstToken: onFirstToken}
markerFilter := internalSSEMarkerFilter{enabled: protocol == streamProtocolChat}
var compat responsesCompatState
buffer := make([]byte, responseCopyBufferBytes)
received := 0
transferred := 0
for {
n, readErr := source.Read(buffer)
if n > 0 {
if received+n > maxStreamResponseTransferBytes {
return inspector.Metadata(), fmt.Errorf("%w: 流式响应超过 %d MiB", errResponseTransferLimit, maxStreamResponseTransferBytes>>20)
}
received += n
chunk := buffer[:n]
inspector.Inspect(chunk)
if protocol == streamProtocolChat {
// The internal reasoning marker is intentionally removed before
// forwarding, but still counts as generation start.
inspector.Inspect(chunk)
}
chunk = markerFilter.Filter(chunk, false)
if protocol == streamProtocolResponses {
chunk = rewriteResponsesStreamChunk(chunk, &compat)
}
if protocol != streamProtocolChat {
// Inspect the actual downstream representation so compatibility
// fields such as generated item IDs participate in timing and
// output-observed classification.
inspector.Inspect(chunk)
}
if transferred+len(chunk) > maxStreamResponseTransferBytes {
return inspector.Metadata(), fmt.Errorf("%w: 流式响应超过 %d MiB", errResponseTransferLimit, maxStreamResponseTransferBytes>>20)
}
@@ -1325,19 +1345,118 @@ func copyStream(writer gin.ResponseWriter, source io.Reader, protocol streamProt
writer.Flush()
transferred += len(tail)
}
if protocol == streamProtocolResponses {
if tail := flushResponsesStreamTail(&compat); len(tail) > 0 {
inspector.Inspect(tail)
if transferred+len(tail) > maxStreamResponseTransferBytes {
return inspector.Metadata(), fmt.Errorf("%w: 流式响应超过 %d MiB", errResponseTransferLimit, maxStreamResponseTransferBytes>>20)
}
if err := setResponseWriteDeadline(writer); err != nil {
return inspector.Metadata(), err
}
if _, err := writer.Write(tail); err != nil {
return inspector.Metadata(), err
}
writer.Flush()
transferred += len(tail)
}
}
inspector.Finish()
inspector.markFirstTokenForwarded()
terminalErr := inspector.TerminalError()
if terminalErr == nil || errors.Is(terminalErr, errUpstreamStreamFailed) {
return inspector.Metadata(), terminalErr
}
if errors.Is(readErr, io.EOF) {
inspector.Finish()
return inspector.Metadata(), inspector.TerminalError()
}
if inspector.terminalSuccess {
return inspector.Metadata(), nil
writeStreamAbortTrailer(writer, protocol, terminalErr, inspector.Metadata(), &compat, transferred)
return inspector.Metadata(), terminalErr
}
writeStreamAbortTrailer(writer, protocol, readErr, inspector.Metadata(), &compat, transferred)
return inspector.Metadata(), fmt.Errorf("%w: %w", errUpstreamStreamRead, readErr)
}
}
}
func writeStreamAbortTrailer(writer gin.ResponseWriter, protocol streamProtocol, cause error, meta responseMetadata, compat *responsesCompatState, transferred int) {
trailer := streamAbortTrailer(protocol, cause, meta, compat)
if len(trailer) == 0 || transferred+len(trailer) > maxStreamResponseTransferBytes {
return
}
if err := setResponseWriteDeadline(writer); err != nil {
return
}
if _, err := writer.Write(trailer); err == nil {
writer.Flush()
}
}
func streamAbortTrailer(protocol streamProtocol, cause error, meta responseMetadata, compat *responsesCompatState) []byte {
code, message := "upstream_stream_interrupted", "上游流式响应中断"
switch {
case errors.Is(cause, neterror.ErrUpstreamStreamIdleTimeout):
code, message = "upstream_stream_idle_timeout", "上游流式响应长时间无数据"
case errors.Is(cause, errUpstreamStreamIncomplete):
code, message = "upstream_stream_incomplete", "上游流式响应未完整结束"
}
switch protocol {
case streamProtocolChat:
payload, err := json.Marshal(map[string]any{
"type": "error",
"error": map[string]any{
"code": code,
"message": message,
"type": "server_error",
},
})
if err != nil {
return []byte("data: [DONE]\n\n")
}
return []byte("data: " + string(payload) + "\n\ndata: [DONE]\n\n")
case streamProtocolResponses:
if compat == nil {
compat = &responsesCompatState{}
}
compat.rememberFromMeta(meta)
id := compat.ensureID()
response := map[string]any{
"id": id,
"object": "response",
"created_at": compat.createdAt,
"completed_at": compat.createdAt,
"status": "incomplete",
"output": []any{},
"error": nil,
"incomplete_details": map[string]any{"reason": code},
}
if model := strings.TrimSpace(meta.Model); model != "" {
response["model"] = model
}
event := map[string]any{
"type": "response.incomplete",
"id": id,
"sequence_number": meta.SequenceNumber + 1,
"response": response,
}
sanitizeResponsesEvent(event, compat)
payload, err := json.Marshal(event)
if err != nil {
return nil
}
return []byte("event: response.incomplete\ndata: " + string(payload) + "\n\n")
case streamProtocolAnthropic:
payload, err := json.Marshal(map[string]any{
"type": "error",
"error": map[string]any{"type": "api_error", "message": message},
})
if err != nil {
return nil
}
return []byte("event: error\ndata: " + string(payload) + "\n\n")
default:
return nil
}
}
type internalSSEMarkerFilter struct {
enabled bool
pending []byte
@@ -1434,6 +1553,13 @@ func (i *responseInspector) Inspect(chunk []byte) {
index := bytes.IndexByte(i.pending, '\n')
if index < 0 {
if len(i.pending) > maxStreamEventInspectionBytes {
// The line has already been forwarded by copyStream. Treat an
// oversized SSE data line as observed output conservatively so a
// later idle timeout cannot misclassify a non-empty response and
// apply the long empty-stream cooldown.
if bytes.HasPrefix(bytes.TrimSpace(i.pending), []byte("data:")) {
i.metadata.Usage.OutputObserved = true
}
i.pending = nil
}
return
@@ -1446,6 +1572,9 @@ func (i *responseInspector) Inspect(chunk []byte) {
}
if bytes.HasPrefix(line, []byte("data:")) {
value := bytes.TrimSpace(bytes.TrimPrefix(line, []byte("data:")))
if containsGeneratedDelta(value, i.protocol) {
i.metadata.Usage.OutputObserved = true
}
i.observeFirstToken(value)
i.observeTerminal(value)
if !bytes.Equal(value, []byte("[DONE]")) {
@@ -1459,6 +1588,9 @@ func (i *responseInspector) Inspect(chunk []byte) {
if metadata.ResponseID != "" {
i.metadata.ResponseID = metadata.ResponseID
}
if metadata.SequenceNumber > i.metadata.SequenceNumber {
i.metadata.SequenceNumber = metadata.SequenceNumber
}
if metadata.Model != "" {
i.metadata.Model = metadata.Model
i.metadata.Usage.ResponseModel = metadata.Model
@@ -1784,7 +1916,7 @@ func extractMetadata(data []byte) responseMetadata {
if json.Unmarshal(data, &root) != nil {
return responseMetadata{}
}
metadata := responseMetadata{ResponseID: root.ID, Model: root.Model}
metadata := responseMetadata{ResponseID: root.ID, Model: root.Model, SequenceNumber: root.SequenceNumber}
usage := root.Usage
if root.Response != nil {
if metadata.ResponseID == "" {
@@ -1793,6 +1925,9 @@ func extractMetadata(data []byte) responseMetadata {
if metadata.Model == "" {
metadata.Model = root.Response.Model
}
if metadata.SequenceNumber == 0 {
metadata.SequenceNumber = root.Response.SequenceNumber
}
if usage == nil {
usage = root.Response.Usage
}
@@ -1806,10 +1941,11 @@ func extractMetadata(data []byte) responseMetadata {
}
type responsePayloadDTO struct {
ID string `json:"id"`
Model string `json:"model"`
Usage *responseUsageDTO `json:"usage"`
Response *responsePayloadDTO `json:"response"`
ID string `json:"id"`
Model string `json:"model"`
SequenceNumber int64 `json:"sequence_number"`
Usage *responseUsageDTO `json:"usage"`
Response *responsePayloadDTO `json:"response"`
}
type responseUsageDTO struct {
@@ -18,9 +18,16 @@ import (
"github.com/chenyme/grok2api/backend/internal/application/gateway"
clientkeydomain "github.com/chenyme/grok2api/backend/internal/domain/clientkey"
mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media"
"github.com/chenyme/grok2api/backend/internal/pkg/neterror"
"github.com/gin-gonic/gin"
)
type idleErrorReader struct{}
func (idleErrorReader) Read([]byte) (int, error) {
return 0, neterror.ErrUpstreamStreamIdleTimeout
}
type chunkErrorReader struct {
data []byte
done bool
@@ -967,8 +974,216 @@ func TestCopyStreamPreservesBufferedTailOnReadError(t *testing.T) {
if !errors.Is(err, errUpstreamStreamRead) {
t.Fatalf("copy error = %v", err)
}
if !bytes.Equal(recorder.Body.Bytes(), body) {
t.Fatalf("interrupted body = %q, want %q", recorder.Body.Bytes(), body)
got := recorder.Body.Bytes()
if !bytes.HasPrefix(got, body) {
t.Fatalf("interrupted body prefix = %q, want %q", got, body)
}
if !bytes.Contains(got, []byte(`"code":"upstream_stream_interrupted"`)) || !bytes.Contains(got, []byte("data: [DONE]")) {
t.Fatalf("interrupted body missing terminal SSE: %q", got)
}
}
func TestCopyStreamWritesTerminalOnIdleTimeout(t *testing.T) {
gin.SetMode(gin.TestMode)
tests := []struct {
name string
protocol streamProtocol
want []string
}{
{name: "chat", protocol: streamProtocolChat, want: []string{`"code":"upstream_stream_idle_timeout"`, "data: [DONE]"}},
{name: "responses", protocol: streamProtocolResponses, want: []string{`"type":"response.incomplete"`, `"id":"resp_abort"`, `"created_at":`, `"sequence_number":`, `"incomplete_details"`}},
{name: "anthropic", protocol: streamProtocolAnthropic, want: []string{`"type":"error"`, "上游流式响应长时间无数据"}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
recorder := httptest.NewRecorder()
context, _ := gin.CreateTestContext(recorder)
_, err := copyStream(context.Writer, &idleErrorReader{}, test.protocol, nil)
if !errors.Is(err, errUpstreamStreamRead) || !errors.Is(err, neterror.ErrUpstreamStreamIdleTimeout) {
t.Fatalf("copy error = %v", err)
}
got := recorder.Body.String()
for _, fragment := range test.want {
if !strings.Contains(got, fragment) {
t.Fatalf("body %q missing %q", got, fragment)
}
}
})
}
}
func TestCopyStreamFlushesUnterminatedResponsesTail(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
context, _ := gin.CreateTestContext(recorder)
body := "event: response.completed\n" + `data: {"type":"response.completed","response":{"id":"resp_tail","status":"completed","usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}`
metadata, err := copyStream(context.Writer, strings.NewReader(body), streamProtocolResponses, nil)
if err != nil {
t.Fatal(err)
}
got := recorder.Body.String()
if !strings.Contains(got, `"type":"response.completed"`) || !strings.HasSuffix(got, "\n\n") {
t.Fatalf("unterminated Responses tail was not flushed as an SSE event: %q", got)
}
if metadata.ResponseID != "resp_tail" || metadata.Usage.TotalTokens != 2 {
t.Fatalf("metadata = %#v", metadata)
}
}
func TestCopyStreamFlushesUnterminatedResponsesTailBeforeAbort(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
context, _ := gin.CreateTestContext(recorder)
body := []byte(`data: {"type":"response.output_text.delta","delta":"partial"}`)
marked := 0
metadata, err := copyStream(context.Writer, &chunkErrorReader{data: body}, streamProtocolResponses, func() {
marked++
if !strings.Contains(recorder.Body.String(), `"delta":"partial"`) {
t.Fatalf("first token marked before the unterminated tail was flushed: %q", recorder.Body.String())
}
})
if !errors.Is(err, errUpstreamStreamRead) {
t.Fatalf("copy error = %v", err)
}
got := recorder.Body.String()
if !strings.Contains(got, `"delta":"partial"`) || !strings.Contains(got, "\n\nevent: response.incomplete") {
t.Fatalf("unterminated tail and abort event were not separated: %q", got)
}
if marked != 1 {
t.Fatalf("first token marked %d times", marked)
}
if !metadata.Usage.OutputObserved {
t.Fatal("forwarded unterminated delta was not recorded as observed output")
}
}
func TestCopyStreamDropsMalformedResponsesTailBeforeAbort(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
context, _ := gin.CreateTestContext(recorder)
malformed := []byte(`data: {"type":"response.output_text.delta","delta":"partial`)
_, err := copyStream(context.Writer, &chunkErrorReader{data: malformed}, streamProtocolResponses, nil)
if !errors.Is(err, errUpstreamStreamRead) {
t.Fatalf("copy error = %v", err)
}
got := recorder.Body.String()
if strings.Contains(got, string(malformed)) {
t.Fatalf("malformed tail leaked before terminal event: %q", got)
}
if !strings.Contains(got, `"type":"response.incomplete"`) {
t.Fatalf("abort event missing after malformed tail: %q", got)
}
}
func TestCopyStreamDoesNotAppendAbortAfterUpstreamFailureTerminal(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
context, _ := gin.CreateTestContext(recorder)
body := []byte(`data: {"type":"response.failed","response":{"id":"resp_failed","status":"failed","error":{"message":"failed"}}}` + "\n\n")
_, err := copyStream(context.Writer, &chunkErrorReader{data: body}, streamProtocolResponses, nil)
if !errors.Is(err, errUpstreamStreamFailed) {
t.Fatalf("copy error = %v", err)
}
got := recorder.Body.String()
if strings.Count(got, `"type":"response.failed"`) != 1 || strings.Contains(got, `"type":"response.incomplete"`) {
t.Fatalf("upstream terminal was followed by a second terminal event: %q", got)
}
}
func TestCopyStreamWritesTerminalOnIncompleteEOF(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
context, _ := gin.CreateTestContext(recorder)
_, err := copyStream(context.Writer, strings.NewReader(""), streamProtocolResponses, nil)
if !errors.Is(err, errUpstreamStreamIncomplete) {
t.Fatalf("copy error = %v", err)
}
got := recorder.Body.String()
if !strings.Contains(got, `"type":"response.incomplete"`) || !strings.Contains(got, `"reason":"upstream_stream_incomplete"`) {
t.Fatalf("incomplete EOF missing terminal SSE event: %q", got)
}
}
func TestSanitizeResponsesFillsMissingIDs(t *testing.T) {
state := &responsesCompatState{}
got := rewriteResponsesDataLine([]byte(`data: {"type":"response.output_item.added","item":{"type":"reasoning"}}`+"\n"), state)
if !bytes.Contains(got, []byte(`"id":"item_1"`)) {
t.Fatalf("item id not filled: %s", got)
}
got = rewriteResponsesDataLine([]byte(`data: {"type":"response.created","response":{"status":"in_progress"}}`+"\n"), state)
if !bytes.Contains(got, []byte(`"id":"resp_abort"`)) || !bytes.Contains(got, []byte(`"created_at":`)) {
t.Fatalf("response id/created_at not filled: %s", got)
}
}
func TestSanitizeResponsesKeepsItemIDStableAcrossEvents(t *testing.T) {
state := &responsesCompatState{}
delta := rewriteResponsesDataLine([]byte(`data: {"type":"response.reasoning_text.delta","output_index":0,"delta":"plan"}`+"\n"), state)
added := rewriteResponsesDataLine([]byte(`data: {"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning"}}`+"\n"), state)
done := rewriteResponsesDataLine([]byte(`data: {"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning"}}`+"\n"), state)
for name, got := range map[string][]byte{"added": added, "done": done, "delta": delta} {
if !bytes.Contains(got, []byte(`"id":"item_1"`)) && !bytes.Contains(got, []byte(`"item_id":"item_1"`)) {
t.Fatalf("%s event did not reuse item_1: %s", name, got)
}
}
}
func TestSanitizeResponsesKeepsGeneratedResponseIDStable(t *testing.T) {
state := &responsesCompatState{}
created := rewriteResponsesDataLine([]byte(`data: {"type":"response.created","response":{"status":"in_progress"}}`+"\n"), state)
completed := rewriteResponsesDataLine([]byte(`data: {"type":"response.completed","id":"resp_late","response":{"id":"resp_late","status":"completed"}}`+"\n"), state)
for name, got := range map[string][]byte{"created": created, "completed": completed} {
if !bytes.Contains(got, []byte(`"id":"resp_abort"`)) || bytes.Contains(got, []byte("resp_late")) {
t.Fatalf("%s event changed response identity: %s", name, got)
}
}
}
func TestSanitizeResponsesUsesExistingEventIDForMissingResponseID(t *testing.T) {
state := &responsesCompatState{}
got := rewriteResponsesDataLine([]byte(`data: {"type":"response.created","id":"resp_real","response":{"status":"in_progress"}}`+"\n"), state)
if !bytes.Contains(got, []byte(`"id":"resp_real"`)) || bytes.Contains(got, []byte("resp_abort")) {
t.Fatalf("existing event id was not reused for response: %s", got)
}
}
func TestSanitizeResponsesKeepsResponseCreatedAtStable(t *testing.T) {
state := &responsesCompatState{}
created := rewriteResponsesDataLine([]byte(`data: {"type":"response.created","id":"resp_real","response":{"id":"resp_real","created_at":123,"status":"in_progress"}}`+"\n"), state)
completed := rewriteResponsesDataLine([]byte(`data: {"type":"response.completed","id":"resp_real","response":{"id":"resp_real","created_at":456,"status":"completed"}}`+"\n"), state)
for name, got := range map[string][]byte{"created": created, "completed": completed} {
if !bytes.Contains(got, []byte(`"created_at":123`)) || bytes.Contains(got, []byte(`"created_at":456`)) {
t.Fatalf("%s event changed response creation time: %s", name, got)
}
}
}
func TestSanitizeResponsesDoesNotAddResponseIDToErrorEvent(t *testing.T) {
state := &responsesCompatState{}
got := rewriteResponsesDataLine([]byte(`data: {"type":"error","code":"server_error","message":"failed"}`+"\n"), state)
if bytes.Contains(got, []byte(`"id":`)) {
t.Fatalf("Responses error event gained a non-protocol response id: %s", got)
}
}
func TestResponsesCompatBoundsUnterminatedLineBuffer(t *testing.T) {
state := &responsesCompatState{}
chunk := bytes.Repeat([]byte{'x'}, maxStreamEventInspectionBytes+1)
got := rewriteResponsesStreamChunk(chunk, state)
if len(got) != len(chunk) || len(state.pending) != 0 || !state.passingLongLine {
t.Fatalf("oversized line was retained: output=%d pending=%d passing=%t", len(got), len(state.pending), state.passingLongLine)
}
got = rewriteResponsesStreamChunk([]byte("tail\n"), state)
if string(got) != "tail\n" || state.passingLongLine {
t.Fatalf("oversized line passthrough did not finish: %q passing=%t", got, state.passingLongLine)
}
}
func TestResponseInspectorTreatsOversizedDataLineAsObservedOutput(t *testing.T) {
inspector := &responseInspector{protocol: streamProtocolResponses}
inspector.Inspect(append([]byte("data: "), bytes.Repeat([]byte{'x'}, maxStreamEventInspectionBytes)...))
if !inspector.Metadata().Usage.OutputObserved {
t.Fatal("forwarded oversized SSE data line was still classified as empty")
}
}
@@ -1151,9 +1366,12 @@ func TestCopyStreamRequiresProtocolTerminalEvent(t *testing.T) {
} else if metadata.StreamFailure != nil {
t.Fatalf("unexpected stream failure diagnostic = %#v", metadata.StreamFailure)
}
if recorder.Body.String() != test.body {
if test.protocol != streamProtocolResponses && recorder.Body.String() != test.body {
t.Fatalf("forwarded = %q", recorder.Body.String())
}
if test.protocol == streamProtocolResponses && !strings.Contains(recorder.Body.String(), `"type":`) {
t.Fatalf("responses stream missing type: %q", recorder.Body.String())
}
})
}
}
@@ -1182,7 +1400,7 @@ func TestWriteResultRecordsStreamFailureDiagnostic(t *testing.T) {
})
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil))
if recorder.Code != http.StatusOK || recorder.Body.String() != stream || finalCode != "upstream_stream_error" {
if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), `"type":"response.failed"`) || finalCode != "upstream_stream_error" {
t.Fatalf("status=%d body=%q final=%q", recorder.Code, recorder.Body.String(), finalCode)
}
if diagnostic == nil || !strings.Contains(string(diagnostic.Body), `"code":"server_error"`) {
@@ -0,0 +1,312 @@
package inference
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"time"
)
// responsesCompatState fills fields Grok CLI serde treats as required.
type responsesCompatState struct {
responseID string
createdAt int64
itemSeq int
itemIDs map[int64]string
usedItemIDs map[string]struct{}
pending []byte
passingLongLine bool
}
func rewriteResponsesStreamChunk(chunk []byte, state *responsesCompatState) []byte {
if state == nil {
return chunk
}
var out []byte
if state.passingLongLine {
index := bytes.IndexByte(chunk, '\n')
if index < 0 {
return append(out, chunk...)
}
out = append(out, chunk[:index+1]...)
chunk = chunk[index+1:]
state.passingLongLine = false
}
state.pending = append(state.pending, chunk...)
for {
index := bytes.IndexByte(state.pending, '\n')
if index < 0 {
// Compatibility rewriting only needs ordinary JSON-sized SSE lines.
// Stream an oversized line through instead of retaining unbounded
// memory; rewriting resumes at its terminating newline.
if len(state.pending) > maxStreamEventInspectionBytes {
out = append(out, state.pending...)
state.pending = nil
state.passingLongLine = true
}
break
}
line := state.pending[:index+1]
state.pending = state.pending[index+1:]
out = append(out, rewriteResponsesDataLine(line, state)...)
}
return out
}
// flushResponsesStreamTail forwards the final unterminated SSE line instead
// of silently dropping it. Two newlines complete the event so downstream SSE
// parsers can dispatch it before EOF or a locally generated abort event.
func flushResponsesStreamTail(state *responsesCompatState) []byte {
if state == nil || state.passingLongLine || len(state.pending) == 0 {
return nil
}
tail := state.pending
state.pending = nil
trimmed := bytes.TrimSpace(tail)
if !bytes.HasPrefix(trimmed, []byte("data:")) {
return nil
}
payload := bytes.TrimSpace(bytes.TrimPrefix(trimmed, []byte("data:")))
if len(payload) == 0 {
return nil
}
if bytes.Equal(payload, []byte("[DONE]")) {
return []byte("data: [DONE]\n\n")
}
var event map[string]any
if json.Unmarshal(payload, &event) != nil {
// Never turn a truncated JSON fragment into a dispatchable SSE event;
// the locally generated terminal event must remain parseable.
return nil
}
sanitizeResponsesEvent(event, state)
encoded, err := json.Marshal(event)
if err != nil {
return nil
}
return append([]byte("data: "+string(encoded)), '\n', '\n')
}
func (s *responsesCompatState) ensureID() string {
if s.responseID == "" {
s.responseID = "resp_abort"
}
if s.createdAt == 0 {
s.createdAt = time.Now().Unix()
}
return s.responseID
}
func (s *responsesCompatState) rememberFromMeta(meta responseMetadata) {
if id := strings.TrimSpace(meta.ResponseID); id != "" {
s.responseID = id
}
s.ensureID()
}
func rewriteResponsesDataLine(line []byte, state *responsesCompatState) []byte {
trimmed := bytes.TrimSpace(line)
if !bytes.HasPrefix(trimmed, []byte("data:")) {
return line
}
payload := bytes.TrimSpace(bytes.TrimPrefix(trimmed, []byte("data:")))
if len(payload) == 0 || bytes.Equal(payload, []byte("[DONE]")) {
return line
}
var event map[string]any
if json.Unmarshal(payload, &event) != nil {
return line
}
changed := sanitizeResponsesEvent(event, state)
if !changed {
return line
}
encoded, err := json.Marshal(event)
if err != nil {
return line
}
newline := ""
if bytes.HasSuffix(line, []byte("\n")) {
newline = "\n"
}
return []byte("data: " + string(encoded) + newline)
}
func sanitizeResponsesEvent(event map[string]any, state *responsesCompatState) bool {
changed := false
typ := stringAny(event["type"])
if responsesEventCarriesResponseID(typ) && state.responseID == "" {
if id := strings.TrimSpace(stringAny(event["id"])); id != "" {
state.responseID = id
}
}
if resp, ok := event["response"].(map[string]any); ok {
if id := strings.TrimSpace(stringAny(resp["id"])); id != "" {
if state.responseID == "" {
state.responseID = id
} else if id != state.responseID {
resp["id"] = state.responseID
changed = true
}
} else {
resp["id"] = state.ensureID()
changed = true
}
if resp["created_at"] == nil {
_ = state.ensureID()
resp["created_at"] = state.createdAt
changed = true
} else if ts, ok := asInt64(resp["created_at"]); ok && ts > 0 {
if state.createdAt == 0 {
state.createdAt = ts
} else if ts != state.createdAt {
resp["created_at"] = state.createdAt
changed = true
}
}
if resp["object"] == nil {
resp["object"] = "response"
changed = true
}
if resp["output"] == nil {
resp["output"] = []any{}
changed = true
}
if errObj, ok := resp["error"].(map[string]any); ok && strings.TrimSpace(stringAny(errObj["id"])) == "" {
errObj["id"] = "err_" + strings.TrimPrefix(state.ensureID(), "resp_")
changed = true
}
event["response"] = resp
}
if item, ok := event["item"].(map[string]any); ok {
itemID := strings.TrimSpace(stringAny(item["id"]))
outputIndex, hasOutputIndex := asInt64(event["output_index"])
if hasOutputIndex {
if remembered := state.itemID(outputIndex); remembered != "" {
itemID = remembered
}
}
if itemID == "" {
itemID = state.nextItemID()
}
if strings.TrimSpace(stringAny(item["id"])) != itemID {
item["id"] = itemID
event["item"] = item
changed = true
}
state.rememberItemID(outputIndex, hasOutputIndex, itemID)
}
if strings.TrimSpace(stringAny(event["item_id"])) == "" && responsesEventNeedsItemID(stringAny(event["type"])) {
if outputIndex, ok := asInt64(event["output_index"]); ok {
itemID := state.itemID(outputIndex)
if itemID == "" {
itemID = state.nextItemID()
state.rememberItemID(outputIndex, true, itemID)
}
event["item_id"] = itemID
changed = true
}
}
if responsesEventCarriesResponseID(typ) {
if id := strings.TrimSpace(stringAny(event["id"])); id == "" {
event["id"] = state.ensureID()
changed = true
} else {
if state.responseID == "" {
state.responseID = id
} else if id != state.responseID {
event["id"] = state.responseID
changed = true
}
}
}
return changed
}
func responsesEventCarriesResponseID(eventType string) bool {
switch eventType {
case "response.created", "response.in_progress", "response.completed", "response.incomplete", "response.failed":
return true
default:
return false
}
}
func (s *responsesCompatState) nextItemID() string {
if s.usedItemIDs == nil {
s.usedItemIDs = make(map[string]struct{})
}
for {
s.itemSeq++
candidate := fmt.Sprintf("item_%d", s.itemSeq)
if _, exists := s.usedItemIDs[candidate]; exists {
continue
}
s.usedItemIDs[candidate] = struct{}{}
return candidate
}
}
func (s *responsesCompatState) rememberItemID(outputIndex int64, hasOutputIndex bool, itemID string) {
if itemID == "" {
return
}
if s.usedItemIDs == nil {
s.usedItemIDs = make(map[string]struct{})
}
s.usedItemIDs[itemID] = struct{}{}
if !hasOutputIndex {
return
}
if s.itemIDs == nil {
s.itemIDs = make(map[int64]string)
}
if _, exists := s.itemIDs[outputIndex]; !exists {
s.itemIDs[outputIndex] = itemID
}
}
func (s *responsesCompatState) itemID(outputIndex int64) string {
if s == nil || s.itemIDs == nil {
return ""
}
return s.itemIDs[outputIndex]
}
func responsesEventNeedsItemID(eventType string) bool {
switch eventType {
case "response.output_text.delta", "response.output_text.done",
"response.reasoning_text.delta", "response.reasoning_text.done",
"response.reasoning_summary_text.delta", "response.reasoning_summary_text.done",
"response.refusal.delta", "response.refusal.done",
"response.function_call_arguments.delta", "response.function_call_arguments.done",
"response.custom_tool_call_input.delta", "response.custom_tool_call_input.done":
return true
default:
return false
}
}
func stringAny(value any) string {
switch typed := value.(type) {
case string:
return typed
default:
return ""
}
}
func asInt64(value any) (int64, bool) {
switch typed := value.(type) {
case float64:
return int64(typed), true
case int64:
return typed, true
case json.Number:
n, err := typed.Int64()
return n, err == nil
default:
return 0, false
}
}