From 4940556056b0c7f8422da4c9eb1e6e72c70f8a59 Mon Sep 17 00:00:00 2001 From: lij768423-svg Date: Wed, 19 Aug 2026 01:59:23 +0800 Subject: [PATCH 1/4] fix: do not fail-open empty held streams as HTTP 200 Empty hold timeouts and upstream idle were delivered as 200 without a terminal SSE event, so Sub2API wrapped them as 500. Keep waiting on a 0-token hold expire, treat idle as a retryable 504 instead of client 499, cool the hanging account, and write an SSE error + DONE when the flush path is already committed. --- .../application/gateway/quality_retry.go | 42 ++++++++++ .../application/gateway/quality_retry_scan.go | 8 +- .../application/gateway/quality_retry_test.go | 83 ++++++++++--------- .../internal/application/gateway/service.go | 27 +++++- .../application/gateway/service_test.go | 13 +++ .../transport/http/inference/handler.go | 54 ++++++++++++ .../transport/http/inference/handler_test.go | 44 +++++++++- 7 files changed, 224 insertions(+), 47 deletions(-) diff --git a/backend/internal/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go index df99047a..ade82ba6 100644 --- a/backend/internal/application/gateway/quality_retry.go +++ b/backend/internal/application/gateway/quality_retry.go @@ -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 ( @@ -99,6 +100,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 @@ -121,11 +124,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. diff --git a/backend/internal/application/gateway/quality_retry_scan.go b/backend/internal/application/gateway/quality_retry_scan.go index c70a4493..2cc56764 100644 --- a/backend/internal/application/gateway/quality_retry_scan.go +++ b/backend/internal/application/gateway/quality_retry_scan.go @@ -380,10 +380,12 @@ 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 @@ -403,7 +405,7 @@ func peekQualityStream(ctx context.Context, body io.ReadCloser, protocol string, } 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) } } } diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go index 409569d7..a523299d 100644 --- a/backend/internal/application/gateway/quality_retry_test.go +++ b/backend/internal/application/gateway/quality_retry_test.go @@ -20,6 +20,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) { @@ -37,6 +38,8 @@ func TestClassifyQualityHold(t *testing.T) { {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 +425,55 @@ 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, - }) - 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) } - 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 isClientRequestCancel(ctx, got) { + t.Fatal("idle timeout must not look like a client cancel") } - if verdict != QualityDeliver { - t.Fatalf("empty timed-out prefix verdict = %s", verdict) - } - body, err := io.ReadAll(replay) - if err != nil { - t.Fatal(err) - } - if err := <-writeErr; err != nil { - t.Fatal(err) - } - 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") } } diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index 666bb7bd..4883843b 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -454,7 +454,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 +1038,13 @@ 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 := 0, time.Duration(0) + if errorCode == "upstream_stream_idle_timeout" && usage.OutputTokens == 0 && usage.ReasoningTokens == 0 { + status = http.StatusGatewayTimeout + retryAfter = 24 * time.Hour + } 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 +1508,23 @@ 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)) { + writeCtx, writeCancel := context.WithTimeout(context.WithoutCancel(ctx), finalizationTimeout) + if markErr := s.selector.MarkFailureAfterSuccess(writeCtx, credential, http.StatusGatewayTimeout, 24*time.Hour); markErr != nil { + s.logger.Warn("quality_peek_idle_cooldown_failed", "request_id", input.RequestID, "account_id", credential.ID, "error", markErr) + } else { + s.logger.Warn("quality_peek_idle_retry", "request_id", input.RequestID, "account_id", credential.ID, "cooldown", "24h0m0s") + } + writeCancel() + } + if shouldStopForNonAccountFingerprint(failureFingerprints, lastFailure) { + break + } continue } response.Body = replay @@ -1634,7 +1653,7 @@ 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 diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index f161c727..06a54e06 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -4273,6 +4273,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 +4286,15 @@ 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") + } +} diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index 552b6943..fc3c7de3 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -1333,11 +1333,65 @@ func copyStream(writer gin.ResponseWriter, source io.Reader, protocol streamProt if inspector.terminalSuccess { return inspector.Metadata(), nil } + if trailer := streamAbortTrailer(protocol, readErr); len(trailer) > 0 { + if transferred+len(trailer) <= maxStreamResponseTransferBytes { + if err := setResponseWriteDeadline(writer); err == nil { + if _, err := writer.Write(trailer); err == nil { + writer.Flush() + } + } + } + } return inspector.Metadata(), fmt.Errorf("%w: %w", errUpstreamStreamRead, readErr) } } } +func streamAbortTrailer(protocol streamProtocol, cause error) []byte { + code, message := "upstream_stream_interrupted", "上游流式响应中断" + if errors.Is(cause, neterror.ErrUpstreamStreamIdleTimeout) { + code, message = "upstream_stream_idle_timeout", "上游流式响应长时间无数据" + } + 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: + payload, err := json.Marshal(map[string]any{ + "type": "response.incomplete", + "response": map[string]any{ + "status": "incomplete", + "error": map[string]any{"code": code, "message": message}, + }, + }) + if err != nil { + return nil + } + return []byte("data: " + 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 diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go index 3d63c2a5..39385604 100644 --- a/backend/internal/transport/http/inference/handler_test.go +++ b/backend/internal/transport/http/inference/handler_test.go @@ -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,41 @@ 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"`, `"code":"upstream_stream_idle_timeout"`}}, + {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) + } + } + }) } } From 48308eb4026836a2ddc6eb74f5ee751a322cade0 Mon Sep 17 00:00:00 2001 From: lij768423-svg Date: Wed, 19 Aug 2026 02:11:49 +0800 Subject: [PATCH 2/4] fix: give abort trailers the response id Grok CLI requires The empty-hold idle trailer emitted response.incomplete without id, created_at, or sequence_number. Grok CLI serde then failed with missing field id. Reuse the streamed response id when present and always write a complete response object. --- .../transport/http/inference/handler.go | 47 ++++++++++++++----- .../transport/http/inference/handler_test.go | 2 +- 2 files changed, 35 insertions(+), 14 deletions(-) diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index fc3c7de3..a5f1f721 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -1282,6 +1282,7 @@ type responseMetadata struct { cacheCreationInputTokens int64 ResponseID string Model string + SequenceNumber int64 StreamFailure *gateway.StreamFailureDiagnostic } @@ -1333,7 +1334,7 @@ func copyStream(writer gin.ResponseWriter, source io.Reader, protocol streamProt if inspector.terminalSuccess { return inspector.Metadata(), nil } - if trailer := streamAbortTrailer(protocol, readErr); len(trailer) > 0 { + if trailer := streamAbortTrailer(protocol, readErr, inspector.Metadata()); len(trailer) > 0 { if transferred+len(trailer) <= maxStreamResponseTransferBytes { if err := setResponseWriteDeadline(writer); err == nil { if _, err := writer.Write(trailer); err == nil { @@ -1347,7 +1348,7 @@ func copyStream(writer gin.ResponseWriter, source io.Reader, protocol streamProt } } -func streamAbortTrailer(protocol streamProtocol, cause error) []byte { +func streamAbortTrailer(protocol streamProtocol, cause error, meta responseMetadata) []byte { code, message := "upstream_stream_interrupted", "上游流式响应中断" if errors.Is(cause, neterror.ErrUpstreamStreamIdleTimeout) { code, message = "upstream_stream_idle_timeout", "上游流式响应长时间无数据" @@ -1367,17 +1368,30 @@ func streamAbortTrailer(protocol streamProtocol, cause error) []byte { } return []byte("data: " + string(payload) + "\n\ndata: [DONE]\n\n") case streamProtocolResponses: + id := strings.TrimSpace(meta.ResponseID) + if id == "" { + id = "resp_abort" + } + response := map[string]any{ + "id": id, + "object": "response", + "created_at": time.Now().Unix(), + "status": "incomplete", + "output": []any{}, + "error": map[string]any{"code": code, "message": message}, + } + if model := strings.TrimSpace(meta.Model); model != "" { + response["model"] = model + } payload, err := json.Marshal(map[string]any{ - "type": "response.incomplete", - "response": map[string]any{ - "status": "incomplete", - "error": map[string]any{"code": code, "message": message}, - }, + "type": "response.incomplete", + "sequence_number": meta.SequenceNumber + 1, + "response": response, }) if err != nil { return nil } - return []byte("data: " + string(payload) + "\n\n") + return []byte("event: response.incomplete\ndata: " + string(payload) + "\n\n") case streamProtocolAnthropic: payload, err := json.Marshal(map[string]any{ "type": "error", @@ -1513,6 +1527,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 @@ -1838,7 +1855,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 == "" { @@ -1847,6 +1864,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 } @@ -1860,10 +1880,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 { diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go index 39385604..966b057c 100644 --- a/backend/internal/transport/http/inference/handler_test.go +++ b/backend/internal/transport/http/inference/handler_test.go @@ -991,7 +991,7 @@ func TestCopyStreamWritesTerminalOnIdleTimeout(t *testing.T) { want []string }{ {name: "chat", protocol: streamProtocolChat, want: []string{`"code":"upstream_stream_idle_timeout"`, "data: [DONE]"}}, - {name: "responses", protocol: streamProtocolResponses, want: []string{`"type":"response.incomplete"`, `"code":"upstream_stream_idle_timeout"`}}, + {name: "responses", protocol: streamProtocolResponses, want: []string{`"type":"response.incomplete"`, `"code":"upstream_stream_idle_timeout"`, `"id":"resp_abort"`, `"created_at":`, `"sequence_number":`}}, {name: "anthropic", protocol: streamProtocolAnthropic, want: []string{`"type":"error"`, "上游流式响应长时间无数据"}}, } for _, test := range tests { From 633cf9b73e95c9cdacdbe9bc327e5f0f5cba7861 Mon Sep 17 00:00:00 2001 From: lij768423-svg Date: Wed, 19 Aug 2026 02:33:56 +0800 Subject: [PATCH 3/4] fix: fill required Responses ids for Grok CLI serde Idle abort still failed with missing field id because CLI requires id on the event and on item/error objects, not only response.id. Rewrite streamed Responses events to supply missing response/item ids and emit a complete incomplete trailer. --- .../transport/http/inference/handler.go | 37 +++-- .../transport/http/inference/handler_test.go | 21 ++- .../http/inference/responses_compat.go | 152 ++++++++++++++++++ 3 files changed, 194 insertions(+), 16 deletions(-) create mode 100644 backend/internal/transport/http/inference/responses_compat.go diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index a5f1f721..73f3a622 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -1289,6 +1289,7 @@ type responseMetadata struct { 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) transferred := 0 for { @@ -1297,6 +1298,9 @@ func copyStream(writer gin.ResponseWriter, source io.Reader, protocol streamProt chunk := buffer[:n] inspector.Inspect(chunk) chunk = markerFilter.Filter(chunk, false) + if protocol == streamProtocolResponses { + chunk = rewriteResponsesStreamChunk(chunk, &compat) + } if transferred+len(chunk) > maxStreamResponseTransferBytes { return inspector.Metadata(), fmt.Errorf("%w: 流式响应超过 %d MiB", errResponseTransferLimit, maxStreamResponseTransferBytes>>20) } @@ -1334,7 +1338,8 @@ func copyStream(writer gin.ResponseWriter, source io.Reader, protocol streamProt if inspector.terminalSuccess { return inspector.Metadata(), nil } - if trailer := streamAbortTrailer(protocol, readErr, inspector.Metadata()); len(trailer) > 0 { + compat.rememberFromMeta(inspector.Metadata()) + if trailer := streamAbortTrailer(protocol, readErr, inspector.Metadata(), &compat); len(trailer) > 0 { if transferred+len(trailer) <= maxStreamResponseTransferBytes { if err := setResponseWriteDeadline(writer); err == nil { if _, err := writer.Write(trailer); err == nil { @@ -1348,7 +1353,7 @@ func copyStream(writer gin.ResponseWriter, source io.Reader, protocol streamProt } } -func streamAbortTrailer(protocol streamProtocol, cause error, meta responseMetadata) []byte { +func streamAbortTrailer(protocol streamProtocol, cause error, meta responseMetadata, compat *responsesCompatState) []byte { code, message := "upstream_stream_interrupted", "上游流式响应中断" if errors.Is(cause, neterror.ErrUpstreamStreamIdleTimeout) { code, message = "upstream_stream_idle_timeout", "上游流式响应长时间无数据" @@ -1368,26 +1373,32 @@ func streamAbortTrailer(protocol streamProtocol, cause error, meta responseMetad } return []byte("data: " + string(payload) + "\n\ndata: [DONE]\n\n") case streamProtocolResponses: - id := strings.TrimSpace(meta.ResponseID) - if id == "" { - id = "resp_abort" + if compat == nil { + compat = &responsesCompatState{} } + compat.rememberFromMeta(meta) + id := compat.ensureID() response := map[string]any{ - "id": id, - "object": "response", - "created_at": time.Now().Unix(), - "status": "incomplete", - "output": []any{}, - "error": map[string]any{"code": code, "message": message}, + "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 } - payload, err := json.Marshal(map[string]any{ + 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 } diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go index 966b057c..70b6bdb0 100644 --- a/backend/internal/transport/http/inference/handler_test.go +++ b/backend/internal/transport/http/inference/handler_test.go @@ -991,7 +991,7 @@ func TestCopyStreamWritesTerminalOnIdleTimeout(t *testing.T) { want []string }{ {name: "chat", protocol: streamProtocolChat, want: []string{`"code":"upstream_stream_idle_timeout"`, "data: [DONE]"}}, - {name: "responses", protocol: streamProtocolResponses, want: []string{`"type":"response.incomplete"`, `"code":"upstream_stream_idle_timeout"`, `"id":"resp_abort"`, `"created_at":`, `"sequence_number":`}}, + {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 { @@ -1012,6 +1012,18 @@ func TestCopyStreamWritesTerminalOnIdleTimeout(t *testing.T) { } } +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 TestCopyStreamMarksFirstTokenAfterFlush(t *testing.T) { gin.SetMode(gin.TestMode) recorder := httptest.NewRecorder() @@ -1191,9 +1203,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()) + } }) } } @@ -1222,7 +1237,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"`) { diff --git a/backend/internal/transport/http/inference/responses_compat.go b/backend/internal/transport/http/inference/responses_compat.go new file mode 100644 index 00000000..0a4cc857 --- /dev/null +++ b/backend/internal/transport/http/inference/responses_compat.go @@ -0,0 +1,152 @@ +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 + pending []byte +} + +func rewriteResponsesStreamChunk(chunk []byte, state *responsesCompatState) []byte { + if state == nil { + return chunk + } + state.pending = append(state.pending, chunk...) + var out []byte + for { + index := bytes.IndexByte(state.pending, '\n') + if index < 0 { + break + } + line := state.pending[:index+1] + state.pending = state.pending[index+1:] + out = append(out, rewriteResponsesDataLine(line, state)...) + } + return out +} + +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 + if resp, ok := event["response"].(map[string]any); ok { + if id := strings.TrimSpace(stringAny(resp["id"])); id != "" { + state.responseID = id + } 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 { + state.createdAt = ts + } + 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 { + if strings.TrimSpace(stringAny(item["id"])) == "" { + state.itemSeq++ + item["id"] = fmt.Sprintf("item_%d", state.itemSeq) + event["item"] = item + changed = true + } + } + typ := stringAny(event["type"]) + if strings.HasPrefix(typ, "response.") && (event["id"] == nil || strings.TrimSpace(stringAny(event["id"])) == "") { + switch typ { + case "response.created", "response.in_progress", "response.completed", "response.incomplete", "response.failed", "error": + event["id"] = state.ensureID() + changed = true + } + } + return changed +} + +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 + } +} From 470b7c38add594d9a394dd0c7038311178a19988 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Wed, 19 Aug 2026 10:59:54 +0800 Subject: [PATCH 4/4] fix: retry empty streams and emit protocol-safe terminal events --- .../internal/application/gateway/failure.go | 2 + .../application/gateway/quality_retry.go | 11 +- .../application/gateway/quality_retry_scan.go | 25 ++- .../application/gateway/quality_retry_test.go | 64 +++++- .../internal/application/gateway/service.go | 32 ++- .../application/gateway/service_test.go | 26 ++- .../transport/http/inference/handler.go | 84 ++++++-- .../transport/http/inference/handler_test.go | 163 +++++++++++++++ .../http/inference/responses_compat.go | 190 ++++++++++++++++-- 9 files changed, 538 insertions(+), 59 deletions(-) diff --git a/backend/internal/application/gateway/failure.go b/backend/internal/application/gateway/failure.go index 766fdbf7..8cd3e183 100644 --- a/backend/internal/application/gateway/failure.go +++ b/backend/internal/application/gateway/failure.go @@ -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", "上游服务响应超时" } diff --git a/backend/internal/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go index ade82ba6..ff905890 100644 --- a/backend/internal/application/gateway/quality_retry.go +++ b/backend/internal/application/gateway/quality_retry.go @@ -23,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. @@ -115,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 } diff --git a/backend/internal/application/gateway/quality_retry_scan.go b/backend/internal/application/gateway/quality_retry_scan.go index 2cc56764..3a29d8b9 100644 --- a/backend/internal/application/gateway/quality_retry_scan.go +++ b/backend/internal/application/gateway/quality_retry_scan.go @@ -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} @@ -388,8 +388,7 @@ func peekQualityStream(ctx context.Context, body io.ReadCloser, protocol string, } 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 { @@ -400,8 +399,7 @@ 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() @@ -411,6 +409,23 @@ func peekQualityStream(ctx context.Context, body io.ReadCloser, protocol string, } } +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)) diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go index a523299d..b6aaf26b 100644 --- a/backend/internal/application/gateway/quality_retry_test.go +++ b/backend/internal/application/gateway/quality_retry_test.go @@ -2,6 +2,7 @@ package gateway import ( "context" + "errors" "fmt" "io" "net/http" @@ -35,6 +36,7 @@ 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}, @@ -459,6 +461,41 @@ func TestPeekQualityStreamHoldTimeoutEmptyDoesNotFailOpen(t *testing.T) { } } +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() + if verdict != QualityDeliver { + t.Fatalf("verdict = %s, want deliver for a real short response", verdict) + } +} + func TestQualityPeekAbortErrorPrefersIdleCause(t *testing.T) { t.Parallel() ctx, cancel := context.WithCancelCause(context.Background()) @@ -545,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), @@ -585,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, @@ -615,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 { @@ -624,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 { diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index 4883843b..0cec993a 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -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 @@ -1038,11 +1041,7 @@ 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 := 0, time.Duration(0) - if errorCode == "upstream_stream_idle_timeout" && usage.OutputTokens == 0 && usage.ReasoningTokens == 0 { - status = http.StatusGatewayTimeout - retryAfter = 24 * time.Hour - } + status, retryAfter := streamFailureHealthPenalty(errorCode, usage) if err := budget.run("account_health", finalizationHealthBudget, func(stageCtx context.Context) error { return s.selector.MarkFailureAfterSuccess(stageCtx, credential, status, retryAfter) }); err != nil { @@ -1513,12 +1512,16 @@ attemptLoop: break } lastFailure = newTransportUpstreamFailure(peekErr, credential.ID, credential.Name) - if neterrorpkg.IsUpstreamStreamIdleTimeout(peekErr) || neterrorpkg.IsUpstreamStreamIdleTimeout(context.Cause(ctx)) { + 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, 24*time.Hour); markErr != nil { - s.logger.Warn("quality_peek_idle_cooldown_failed", "request_id", input.RequestID, "account_id", credential.ID, "error", markErr) + 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("quality_peek_idle_retry", "request_id", input.RequestID, "account_id", credential.ID, "cooldown", "24h0m0s") + s.logger.Warn(logPrefix+"_retry", "request_id", input.RequestID, "account_id", credential.ID, "cooldown", qualityIdleAccountCooldown) } writeCancel() } @@ -1660,6 +1663,13 @@ func isUpstreamStreamFailure(errorCode string) bool { } } +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. @@ -1956,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 diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index 06a54e06..0d1069aa 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -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) { @@ -4298,3 +4302,21 @@ func TestIsUpstreamStreamFailureIncludesIdleTimeout(t *testing.T) { 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) + } + } +} diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index 73f3a622..af803a0f 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -1291,16 +1291,31 @@ func copyStream(writer gin.ResponseWriter, source io.Reader, protocol streamProt 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) } @@ -1330,33 +1345,58 @@ func copyStream(writer gin.ResponseWriter, source io.Reader, protocol streamProt writer.Flush() transferred += len(tail) } - inspector.markFirstTokenForwarded() - if errors.Is(readErr, io.EOF) { - inspector.Finish() - return inspector.Metadata(), inspector.TerminalError() - } - if inspector.terminalSuccess { - return inspector.Metadata(), nil - } - compat.rememberFromMeta(inspector.Metadata()) - if trailer := streamAbortTrailer(protocol, readErr, inspector.Metadata(), &compat); len(trailer) > 0 { - if transferred+len(trailer) <= maxStreamResponseTransferBytes { - if err := setResponseWriteDeadline(writer); err == nil { - if _, err := writer.Write(trailer); err == nil { - writer.Flush() - } + 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) { + 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", "上游流式响应中断" - if errors.Is(cause, neterror.ErrUpstreamStreamIdleTimeout) { + 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: @@ -1513,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 @@ -1525,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]")) { diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go index 70b6bdb0..9215bd34 100644 --- a/backend/internal/transport/http/inference/handler_test.go +++ b/backend/internal/transport/http/inference/handler_test.go @@ -1012,6 +1012,98 @@ func TestCopyStreamWritesTerminalOnIdleTimeout(t *testing.T) { } } +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) @@ -1024,6 +1116,77 @@ func TestSanitizeResponsesFillsMissingIDs(t *testing.T) { } } +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") + } +} + func TestCopyStreamMarksFirstTokenAfterFlush(t *testing.T) { gin.SetMode(gin.TestMode) recorder := httptest.NewRecorder() diff --git a/backend/internal/transport/http/inference/responses_compat.go b/backend/internal/transport/http/inference/responses_compat.go index 0a4cc857..4926d54b 100644 --- a/backend/internal/transport/http/inference/responses_compat.go +++ b/backend/internal/transport/http/inference/responses_compat.go @@ -10,21 +10,41 @@ import ( // responsesCompatState fills fields Grok CLI serde treats as required. type responsesCompatState struct { - responseID string - createdAt int64 - itemSeq int - pending []byte + 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 } - state.pending = append(state.pending, 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] @@ -34,6 +54,40 @@ func rewriteResponsesStreamChunk(chunk []byte, state *responsesCompatState) []by 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" @@ -81,9 +135,20 @@ func rewriteResponsesDataLine(line []byte, state *responsesCompatState) []byte { 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 != "" { - state.responseID = 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 @@ -93,7 +158,12 @@ func sanitizeResponsesEvent(event map[string]any, state *responsesCompatState) b resp["created_at"] = state.createdAt changed = true } else if ts, ok := asInt64(resp["created_at"]); ok && ts > 0 { - state.createdAt = ts + 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" @@ -110,24 +180,114 @@ func sanitizeResponsesEvent(event map[string]any, state *responsesCompatState) b event["response"] = resp } if item, ok := event["item"].(map[string]any); ok { - if strings.TrimSpace(stringAny(item["id"])) == "" { - state.itemSeq++ - item["id"] = fmt.Sprintf("item_%d", state.itemSeq) + 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) } - typ := stringAny(event["type"]) - if strings.HasPrefix(typ, "response.") && (event["id"] == nil || strings.TrimSpace(stringAny(event["id"])) == "") { - switch typ { - case "response.created", "response.in_progress", "response.completed", "response.incomplete", "response.failed", "error": - event["id"] = state.ensureID() + 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: