diff --git a/backend/internal/app/application.go b/backend/internal/app/application.go index e170426b..918736fd 100644 --- a/backend/internal/app/application.go +++ b/backend/internal/app/application.go @@ -496,6 +496,7 @@ func qualityRetryRuntime(value config.QualityGuardRequestRetryConfig) gateway.Qu HoldTimeout: value.HoldTimeout.Value(), MinOutputTokens: int64(value.MinOutputTokens), OnExhausted: value.OnExhausted, + AccountCooldown: value.AccountCooldown.Value(), } } diff --git a/backend/internal/application/audit/degrade.go b/backend/internal/application/audit/degrade.go index 06880b28..2b6e4950 100644 --- a/backend/internal/application/audit/degrade.go +++ b/backend/internal/application/audit/degrade.go @@ -59,6 +59,7 @@ type DegradeTotals struct { Hard int64 Soft int64 Burst int64 + Thinking int64 MaxTPS float64 } @@ -184,7 +185,7 @@ func normalizeDegradeAccountFilter(value DegradeAccountFilter) DegradeAccountFil if value.Status != "enabled" && value.Status != "disabled" && value.Status != "deleted" { value.Status = "" } - if value.Class != auditdomain.DegradeClassBurst && value.Class != auditdomain.DegradeClassSoft && value.Class != auditdomain.DegradeClassHard { + if value.Class != auditdomain.DegradeClassBurst && value.Class != auditdomain.DegradeClassSoft && value.Class != auditdomain.DegradeClassHard && value.Class != auditdomain.DegradeClassThinking { value.Class = "" } if value.MinHits < 1 { @@ -205,9 +206,10 @@ func buildDegradeSummary(window string, now time.Time, thresholds DegradeThresho accounts = append(accounts, DegradeAccount{ ID: value.ID, Name: value.Name, Email: value.Email, Hits: value.Hits, MaxTPS: round(value.MaxTPS, 1), Classes: map[string]int64{ - auditdomain.DegradeClassBurst: value.Burst, - auditdomain.DegradeClassSoft: value.Soft, - auditdomain.DegradeClassHard: value.Hard, + auditdomain.DegradeClassBurst: value.Burst, + auditdomain.DegradeClassSoft: value.Soft, + auditdomain.DegradeClassHard: value.Hard, + auditdomain.DegradeClassThinking: value.Thinking, }, Nodes: value.Nodes, Last: value.Last, Enabled: value.Enabled, Found: value.Found, BFS: value.BuildBotFlagSource, }) @@ -243,7 +245,7 @@ func buildDegradeSummary(window string, now time.Time, thresholds DegradeThresho Totals: DegradeTotals{ Hits: data.Totals.Hits, Accounts: data.Totals.Accounts, StillEnabled: data.Totals.StillEnabled, Disabled: data.Totals.Disabled, Deleted: data.Totals.Deleted, Hard: data.Totals.Hard, - Soft: data.Totals.Soft, Burst: data.Totals.Burst, MaxTPS: round(data.Totals.MaxTPS, 2), + Soft: data.Totals.Soft, Burst: data.Totals.Burst, Thinking: data.Totals.Thinking, MaxTPS: round(data.Totals.MaxTPS, 2), }, Series: series, Nodes: nodes, Accounts: accounts, AccountPage: DegradeAccountPage{ diff --git a/backend/internal/application/audit/degrade_test.go b/backend/internal/application/audit/degrade_test.go index 2c28488f..2d35feeb 100644 --- a/backend/internal/application/audit/degrade_test.go +++ b/backend/internal/application/audit/degrade_test.go @@ -233,6 +233,58 @@ func TestDegradeSummarySearchesEveryAccountIdentityField(t *testing.T) { } } +func TestDegradeSummaryIncludesQualityDegradedThinkingRetries(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-thinking.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + repo := relational.NewAuditRepository(database) + now := time.Now().UTC() + first := int64(100) + speedID := uint64(11) + thinkingID := uint64(22) + records := []auditdomain.Record{ + {RequestID: "speed-hard", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", AccountID: &speedID, AccountName: "fast", EgressNodeName: "edge-1", StatusCode: 200, Streaming: true, OutputTokens: 2000, FirstTokenMS: &first, DurationMS: 1100, CreatedAt: now.Add(-2 * time.Minute)}, + {RequestID: "think-retry-1", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", AccountID: &thinkingID, AccountName: "no-think", EgressNodeName: "edge-2", StatusCode: 200, Streaming: true, ErrorCode: auditdomain.ErrorQualityDegraded, OutputTokens: 48, CreatedAt: now.Add(-time.Minute)}, + {RequestID: "think-retry-2", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", AccountID: &thinkingID, AccountName: "no-think", EgressNodeName: "edge-2", StatusCode: 200, Streaming: true, ErrorCode: auditdomain.ErrorQualityDegraded, OutputTokens: 0, CreatedAt: now.Add(-30 * time.Second)}, + {RequestID: "think-final-503", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", AccountID: &thinkingID, AccountName: "no-think", StatusCode: 503, Streaming: true, ErrorCode: auditdomain.ErrorQualityDegraded, CreatedAt: now.Add(-20 * time.Second)}, + } + if err := repo.CreateBatch(ctx, records); err != nil { + t.Fatal(err) + } + service := NewService(repo, slog.Default(), 8, 4, time.Second) + service.now = func() time.Time { return now } + summary, err := service.DegradeSummary(ctx, "1h", DegradeThresholds{SoftTPS: 500, HardTPS: 1000}, DegradeAccountFilter{}) + if err != nil { + t.Fatal(err) + } + if summary.Totals.Hits != 3 || summary.Totals.Accounts != 2 || summary.Totals.Hard != 1 || summary.Totals.Thinking != 2 { + t.Fatalf("totals = %#v", summary.Totals) + } + if len(summary.Accounts) != 2 { + t.Fatalf("accounts = %#v", summary.Accounts) + } + byID := map[uint64]DegradeAccount{} + for _, account := range summary.Accounts { + byID[account.ID] = account + } + if byID[22].Hits != 2 || byID[22].Classes[auditdomain.DegradeClassThinking] != 2 { + t.Fatalf("thinking account = %#v", byID[22]) + } + thinkingOnly, err := service.DegradeSummary(ctx, "1h", DegradeThresholds{SoftTPS: 500, HardTPS: 1000}, DegradeAccountFilter{Class: auditdomain.DegradeClassThinking}) + if err != nil { + t.Fatal(err) + } + if thinkingOnly.AccountPage.Total != 1 || len(thinkingOnly.Accounts) != 1 || thinkingOnly.Accounts[0].ID != 22 { + t.Fatalf("thinking filter = %#v", thinkingOnly) + } +} + func TestDegradeSummaryRejectsUnknownWindow(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-window.db")) 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 b0f19014..78cd164e 100644 --- a/backend/internal/application/gateway/quality_retry.go +++ b/backend/internal/application/gateway/quality_retry.go @@ -13,18 +13,28 @@ 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 ( - ErrorQualityDegraded = "quality_degraded" - qualityRetryFailOpen = "fail_open" - qualityRetryFailClosed = "fail_closed" - defaultQualityMaxAttempts = 6 - defaultQualityHoldTimeout = 3 * time.Second - defaultQualityMinOutput = int64(32) + ErrorQualityDegraded = "quality_degraded" + qualityRetryFailOpen = "fail_open" + qualityRetryFailClosed = "fail_closed" + defaultQualityMaxAttempts = 6 + defaultQualityHoldTimeout = 3 * time.Second + defaultQualityMinOutput = int64(32) + defaultMissingThinkingCooldown = 24 * time.Hour + lastErrorMissingThinking = accountdomain.LastErrorMissingThinking + lastErrorMissingThinkingDisabled = accountdomain.LastErrorMissingThinkingDisabled + // 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. @@ -34,6 +44,7 @@ type QualityRetryRuntime struct { HoldTimeout time.Duration MinOutputTokens int64 OnExhausted string + AccountCooldown time.Duration } // QualityStreamSignals is the hold classifier input. Tests drive this @@ -76,6 +87,9 @@ func normalizeQualityRetry(cfg QualityRetryRuntime) QualityRetryRuntime { if cfg.MinOutputTokens <= 0 { cfg.MinOutputTokens = defaultQualityMinOutput } + if cfg.AccountCooldown <= 0 { + cfg.AccountCooldown = defaultMissingThinkingCooldown + } cfg.OnExhausted = normalizeQualityExhaustionPolicy(cfg.OnExhausted) return cfg } @@ -99,6 +113,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 +128,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 +140,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. @@ -275,6 +333,22 @@ func jsonStringEquals(raw json.RawMessage, want string) bool { return json.Unmarshal(raw, &value) == nil && strings.EqualFold(strings.TrimSpace(value), want) } +func (s *Service) applyMissingThinkingPenalty(ctx context.Context, requestID string, credential accountdomain.Credential, cooldown time.Duration) { + writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), finalizationTimeout) + defer cancel() + action, err := s.selector.markMissingThinking(writeCtx, credential, cooldown) + if err != nil { + s.logger.Error("quality_degraded_penalty_failed", "request_id", requestID, "account_id", credential.ID, "action", action, "error", err) + return + } + switch action { + case missingThinkingPenaltyDisabled: + s.logger.Info("quality_degraded_disabled", "request_id", requestID, "account_id", credential.ID) + case missingThinkingPenaltyCooled: + s.logger.Info("quality_degraded_cooldown", "request_id", requestID, "account_id", credential.ID, "cooldown", cooldown.String()) + } +} + func (s *Service) recordQualityDegraded(ctx context.Context, base audit.Record, credential accountdomain.Credential, usage Usage, startedAt time.Time, trace *infraegress.Trace, provider accountdomain.Provider) { record := base record.EventID = newAuditEventID() @@ -293,7 +367,9 @@ func (s *Service) recordQualityDegraded(ctx context.Context, base audit.Record, record.DurationMS = time.Since(startedAt).Milliseconds() record.CreatedAt = time.Now().UTC() applyAuditEgress(&record, trace, provider) - if err := s.audits.Create(ctx, record); err != nil { + writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), finalizationTimeout) + defer cancel() + if err := s.audits.Create(writeCtx, record); err != nil { s.logger.Error("quality_degraded_audit_failed", "event_id", record.EventID, "request_id", record.RequestID, "error", err) } } diff --git a/backend/internal/application/gateway/quality_retry_scan.go b/backend/internal/application/gateway/quality_retry_scan.go index c70a4493..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} @@ -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)) diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go index e51b5785..3c0035d8 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" @@ -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") } } @@ -551,8 +595,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), @@ -591,15 +635,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, @@ -621,8 +666,28 @@ 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) + } + noThinkingAccount, err := accountRepo.Get(ctx, credentials[1].ID) + if err != nil { + t.Fatal(err) + } + if !noThinkingAccount.Enabled || noThinkingAccount.LastError != lastErrorMissingThinking || noThinkingAccount.CooldownUntil == nil { + t.Fatalf("missing-thinking account was not cooled: %#v", noThinkingAccount) + } + if remaining := time.Until(*noThinkingAccount.CooldownUntil); remaining < 23*time.Hour || remaining > 24*time.Hour+time.Minute { + t.Fatalf("missing-thinking cooldown = %s, want about 24h", remaining) } logs, total, err := auditRepo.List(ctx, 0, 20) if err != nil { @@ -630,7 +695,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 { @@ -721,6 +786,13 @@ func TestAttemptLoopQualityHoldFailOpenKeepsSingleAccountBody(t *testing.T) { if attempts := adapter.Attempts(); len(attempts) != 1 || attempts[0] != credential.ID { t.Fatalf("single-account pool must not enter a fake retry, attempts=%#v", attempts) } + cooled, err := accountRepo.Get(ctx, credential.ID) + if err != nil { + t.Fatal(err) + } + if !cooled.Enabled || cooled.LastError != lastErrorMissingThinking || cooled.CooldownUntil == nil { + t.Fatalf("delivered fail-open response must still cool the no-thinking account: %#v", cooled) + } } func TestAttemptLoopQualityFailOpenFallbackAndTotalAttemptCap(t *testing.T) { @@ -822,7 +894,7 @@ func TestAttemptLoopQualityFailOpenFallbackAndTotalAttemptCap(t *testing.T) { func TestNormalizeQualityRetryDefaults(t *testing.T) { t.Parallel() got := normalizeQualityRetry(QualityRetryRuntime{Enabled: true}) - if !got.Enabled || got.MaxAttempts != 6 || got.MinOutputTokens != 32 || got.OnExhausted != qualityRetryFailClosed || got.HoldTimeout != 3*time.Second { + if !got.Enabled || got.MaxAttempts != 6 || got.MinOutputTokens != 32 || got.OnExhausted != qualityRetryFailClosed || got.HoldTimeout != 3*time.Second || got.AccountCooldown != 24*time.Hour { t.Fatalf("defaults = %#v", got) } } diff --git a/backend/internal/application/gateway/selector.go b/backend/internal/application/gateway/selector.go index 7604c2bc..32874d16 100644 --- a/backend/internal/application/gateway/selector.go +++ b/backend/internal/application/gateway/selector.go @@ -920,8 +920,21 @@ func (s *Selector) MarkSuccess(ctx context.Context, credential account.Credentia s.markSuccess(ctx, credential, true) } +func isMissingThinkingStrike(lastError string) bool { + return lastError == lastErrorMissingThinking || lastError == lastErrorMissingThinkingDisabled +} + +type missingThinkingPenaltyResult string + +const ( + missingThinkingPenaltyUnchanged missingThinkingPenaltyResult = "unchanged" + missingThinkingPenaltyCooled missingThinkingPenaltyResult = "cooled" + missingThinkingPenaltyDisabled missingThinkingPenaltyResult = "disabled" +) + func (s *Selector) markSuccess(ctx context.Context, credential account.Credential, quotaProbe bool) { now := time.Now().UTC() + keepThinkingStrike := isMissingThinkingStrike(credential.LastError) healthChanged := credential.FailureCount > 0 || credential.CooldownUntil != nil || credential.LastError != "" touchLastUsed := healthChanged s.selectionMu.Lock() @@ -933,9 +946,14 @@ func (s *Selector) markSuccess(ctx context.Context, credential account.Credentia } s.selectionMu.Unlock() if healthChanged { - if err := s.accounts.UpdateHealth(ctx, credential.ID, credential.Provider, 0, nil, "", true); err == nil { + lastError := "" + if keepThinkingStrike { + lastError = lastErrorMissingThinking + } + if err := s.accounts.UpdateHealth(ctx, credential.ID, credential.Provider, 0, nil, lastError, true); err == nil { s.ApplyInvalidation(repository.InvalidationEvent{ Kind: repository.InvalidationAccountHealthChanged, Provider: credential.Provider, AccountID: credential.ID, + HealthMarker: account.NormalizeHealthMarker(lastError), }) } } else if touchLastUsed { @@ -1107,6 +1125,44 @@ func (s *Selector) clearQuotaConsumptionAccount(provider account.Provider, accou s.quotaMu.Unlock() } +// markMissingThinking cools an account for the first no-thinking hit and +// disables it if missing thinking appears again after that cooldown. +func (s *Selector) markMissingThinking(ctx context.Context, credential account.Credential, cooldown time.Duration) (missingThinkingPenaltyResult, error) { + if cooldown <= 0 { + cooldown = defaultMissingThinkingCooldown + } + now := time.Now().UTC() + inCooldown := credential.CooldownUntil != nil && now.Before(*credential.CooldownUntil) + if isMissingThinkingStrike(credential.LastError) && !inCooldown { + disabled := false + if _, err := s.accounts.UpdateMany(ctx, credential.Provider, []uint64{credential.ID}, repository.AccountUpdates{Enabled: &disabled}); err != nil { + return missingThinkingPenaltyUnchanged, err + } + healthErr := s.accounts.UpdateHealth(ctx, credential.ID, credential.Provider, credential.FailureCount, nil, lastErrorMissingThinkingDisabled, false) + s.ApplyInvalidation(repository.InvalidationEvent{ + Kind: repository.InvalidationAccountStateChanged, Provider: credential.Provider, AccountID: credential.ID, + }) + s.evictCandidate(credential.Provider, credential.ID) + if s.sticky != nil { + _ = s.sticky.DeleteByAccount(ctx, credential.ID) + } + return missingThinkingPenaltyDisabled, healthErr + } + if inCooldown { + return missingThinkingPenaltyUnchanged, nil + } + until := now.Add(cooldown) + if err := s.accounts.UpdateHealth(ctx, credential.ID, credential.Provider, credential.FailureCount, &until, lastErrorMissingThinking, false); err != nil { + return missingThinkingPenaltyUnchanged, err + } + s.ApplyInvalidation(repository.InvalidationEvent{ + Kind: repository.InvalidationAccountHealthChanged, Provider: credential.Provider, AccountID: credential.ID, + FailureCount: credential.FailureCount, CooldownUntil: &until, HealthMarker: account.LastErrorMissingThinking, + }) + s.evictCandidate(credential.Provider, credential.ID) + return missingThinkingPenaltyCooled, nil +} + func (s *Selector) MarkFailure(ctx context.Context, credential account.Credential, status int, retryAfter time.Duration) { _ = s.markFailure(ctx, credential, credential.FailureCount, credential.FailureCount+1, status, retryAfter) } @@ -1454,8 +1510,8 @@ func (s *Selector) applyHealthInvalidation(event repository.InvalidationEvent) { value := event.CooldownUntil.UTC() cooldownUntil = &value } - overrideLastError := "" - if event.FailureCount > 0 || cooldownUntil != nil { + overrideLastError := account.NormalizeHealthMarker(event.HealthMarker) + if overrideLastError == "" && (event.FailureCount > 0 || cooldownUntil != nil) { overrideLastError = "upstream failure" } value := routingHealthOverride{ diff --git a/backend/internal/application/gateway/selector_layered_test.go b/backend/internal/application/gateway/selector_layered_test.go index 9958f8b0..2df16788 100644 --- a/backend/internal/application/gateway/selector_layered_test.go +++ b/backend/internal/application/gateway/selector_layered_test.go @@ -108,7 +108,7 @@ func (r *layeredAccountRepository) UpdateHealth(_ context.Context, id uint64, _ } r.healthUpdates = append(r.healthUpdates, repository.InvalidationEvent{ Kind: repository.InvalidationAccountHealthChanged, Provider: provider, AccountID: id, - FailureCount: failureCount, CooldownUntil: cooldownUntil, + FailureCount: failureCount, CooldownUntil: cooldownUntil, HealthMarker: account.NormalizeHealthMarker(lastError), }) return nil } @@ -192,8 +192,12 @@ func TestSelectorHealthInvalidationDoesNotRebuildProviderSnapshots(t *testing.T) cooldownUntil := now.Add(time.Minute) selector.ApplyInvalidation(repository.InvalidationEvent{ Kind: repository.InvalidationAccountHealthChanged, Provider: account.ProviderBuild, AccountID: 1, - FailureCount: 1, CooldownUntil: &cooldownUntil, PublishedAt: now, + FailureCount: 1, CooldownUntil: &cooldownUntil, HealthMarker: account.LastErrorMissingThinking, PublishedAt: now, }) + marked := selector.applyRoutingHealth(account.Credential{ID: 1, Provider: account.ProviderBuild}, now) + if marked.LastError != account.LastErrorMissingThinking { + t.Fatalf("durable health marker was lost in the runtime overlay: %#v", marked) + } _, err := selector.beginSelectionSession(context.Background(), account.ProviderBuild, 0, "model-a", "", "", nil, false) var unavailable *SelectionUnavailableError if !errors.As(err, &unavailable) || unavailable.Reason != SelectionCooling { diff --git a/backend/internal/application/gateway/selector_test.go b/backend/internal/application/gateway/selector_test.go index a239563f..fef73bd5 100644 --- a/backend/internal/application/gateway/selector_test.go +++ b/backend/internal/application/gateway/selector_test.go @@ -1472,6 +1472,89 @@ func (s *recordingStickyStore) Expiries() []time.Time { return append([]time.Time(nil), s.expiries...) } +func TestMarkMissingThinkingCoolsThenDisables(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "missing-thinking.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accounts := relational.NewAccountRepository(database) + credential, _, err := accounts.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, Name: "no-think", SourceKey: "no-think", EncryptedAccessToken: "encrypted", Enabled: true, + AuthStatus: account.AuthStatusActive, Priority: 10, MaxConcurrent: 1, + }) + if err != nil { + t.Fatal(err) + } + selector := NewSelector(accounts, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), nil, time.Hour, 30*time.Second, 30*time.Minute, 500*time.Millisecond) + before := time.Now().UTC() + if action, err := selector.markMissingThinking(ctx, credential, time.Hour); err != nil || action != missingThinkingPenaltyCooled { + t.Fatalf("first penalty = (%s, %v)", action, err) + } + first, err := accounts.Get(ctx, credential.ID) + if err != nil { + t.Fatal(err) + } + if !first.Enabled || first.LastError != lastErrorMissingThinking || first.CooldownUntil == nil { + t.Fatalf("first strike = %#v", first) + } + if wait := first.CooldownUntil.Sub(before); wait < 50*time.Minute || wait > 70*time.Minute { + t.Fatalf("first cooldown = %s", wait) + } + if action, err := selector.markMissingThinking(ctx, first, time.Hour); err != nil || action != missingThinkingPenaltyUnchanged { + t.Fatalf("in-cooldown penalty = (%s, %v)", action, err) + } + stillCooling, err := accounts.Get(ctx, credential.ID) + if err != nil { + t.Fatal(err) + } + if !stillCooling.Enabled { + t.Fatal("in-cooldown second call must not disable") + } + expired := time.Now().UTC().Add(-time.Second) + stillCooling.CooldownUntil = &expired + if action, err := selector.markMissingThinking(ctx, stillCooling, time.Hour); err != nil || action != missingThinkingPenaltyDisabled { + t.Fatalf("second penalty = (%s, %v)", action, err) + } + second, err := accounts.Get(ctx, credential.ID) + if err != nil { + t.Fatal(err) + } + if second.Enabled { + t.Fatalf("second strike after cooldown must disable, got %#v", second) + } + if second.LastError != lastErrorMissingThinkingDisabled { + t.Fatalf("disabled last error = %q", second.LastError) + } + + ok, _, err := accounts.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, Name: "recovered", SourceKey: "recovered", EncryptedAccessToken: "encrypted", Enabled: true, + AuthStatus: account.AuthStatusActive, Priority: 10, MaxConcurrent: 1, + }) + if err != nil { + t.Fatal(err) + } + if action, err := selector.markMissingThinking(ctx, ok, time.Hour); err != nil || action != missingThinkingPenaltyCooled { + t.Fatalf("recovery penalty = (%s, %v)", action, err) + } + cooled, err := accounts.Get(ctx, ok.ID) + if err != nil { + t.Fatal(err) + } + selector.MarkSuccess(ctx, cooled) + kept, err := accounts.Get(ctx, ok.ID) + if err != nil { + t.Fatal(err) + } + if kept.LastError != lastErrorMissingThinking || kept.CooldownUntil != nil || kept.FailureCount != 0 { + t.Fatalf("success must keep thinking strike and clear cooldown, got %#v", kept) + } +} + func TestMarkFailureSoftNetworkCooldown(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "soft-network.db")) diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index 5f1da2e7..0a6175b3 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -122,7 +122,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 @@ -459,7 +462,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 时按旧逻辑将账号标为失效并出池。 @@ -1052,8 +1057,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) } @@ -1517,17 +1523,36 @@ 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 hasNextAccount := attemptPolicy.hasNext(attempt) && selection.hasAvailableCandidate(excluded, !quotaProbeAttempted) hasNextAccount = hasNextAccount && qualityAccountAttempts < holdCfg.MaxAttempts commit := CommitQualityHold(verdict, qualityAccountAttempts-1, holdCfg.MaxAttempts, hasNextAccount, holdCfg.OnExhausted) + if verdict == QualityWithhold { + s.applyMissingThinkingPenalty(ctx, input.RequestID, credential, holdCfg.AccountCooldown) + } deferFailOpenAudit := commit.Action == QualityActionRetry && holdCfg.OnExhausted == qualityRetryFailOpen if commit.Audit && !deferFailOpenAudit { s.recordQualityDegraded(ctx, auditBase, credential, peekUsage, startedAt, egressTrace, route.Provider) @@ -1650,13 +1675,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. @@ -1953,7 +1985,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 31f17e63..a8bcb899 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -415,7 +415,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 { @@ -438,9 +438,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) { @@ -4312,6 +4316,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}, @@ -4324,3 +4329,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) + } + } +} diff --git a/backend/internal/domain/account/account.go b/backend/internal/domain/account/account.go index 9a7047ed..e4495b7e 100644 --- a/backend/internal/domain/account/account.go +++ b/backend/internal/domain/account/account.go @@ -110,6 +110,24 @@ const ( AuthStatusReauthRequired AuthStatus = "reauthRequired" ) +// LastErrorMissingThinking values are durable, non-sensitive quality strike +// markers. Unlike arbitrary upstream errors, they may be propagated through +// runtime invalidation events so every gateway instance preserves the strike. +const ( + LastErrorMissingThinking = "missing_thinking" + LastErrorMissingThinkingDisabled = "missing_thinking_disabled" +) + +// NormalizeHealthMarker admits only durable non-sensitive health markers. +func NormalizeHealthMarker(value string) string { + switch value { + case LastErrorMissingThinking, LastErrorMissingThinkingDisabled: + return value + default: + return "" + } +} + // EgressAssignmentMode 表示账号出口节点的维护方式。手工绑定绝不会被 // 自动均衡任务迁移,自动绑定才允许在健康或容量变化时重新分配。 type EgressAssignmentMode string diff --git a/backend/internal/domain/audit/degrade.go b/backend/internal/domain/audit/degrade.go index e3b7b2e4..6abc6798 100644 --- a/backend/internal/domain/audit/degrade.go +++ b/backend/internal/domain/audit/degrade.go @@ -1,9 +1,11 @@ package audit const ( - DegradeClassBurst = "buffered_burst" - DegradeClassSoft = "soft_tps" - DegradeClassHard = "hard_tps" + DegradeClassBurst = "buffered_burst" + DegradeClassSoft = "soft_tps" + DegradeClassHard = "hard_tps" + DegradeClassThinking = "missing_thinking" + ErrorQualityDegraded = "quality_degraded" ) const ( diff --git a/backend/internal/infra/config/config.go b/backend/internal/infra/config/config.go index 49f611c2..46d8f70b 100644 --- a/backend/internal/infra/config/config.go +++ b/backend/internal/infra/config/config.go @@ -291,6 +291,7 @@ type QualityGuardRequestRetryConfig struct { HoldTimeout Duration `yaml:"holdTimeout"` MinOutputTokens int `yaml:"minOutputTokens"` OnExhausted string `yaml:"onExhausted"` + AccountCooldown Duration `yaml:"accountCooldown"` } type ClientKeyDefaultsConfig struct { @@ -774,6 +775,9 @@ func validateQualityGuardRequestRetry(value QualityGuardRequestRetryConfig) erro default: return errors.New("qualityGuard.requestRetry.onExhausted 必须是 fail_open 或 fail_closed") } + if d := value.AccountCooldown.Value(); d != 0 && (d < time.Minute || d > 168*time.Hour) { + return errors.New("qualityGuard.requestRetry.accountCooldown 必须在 1m 到 168h 之间") + } return nil } @@ -907,6 +911,7 @@ func defaultConfig() Config { MinimumGenerationWindow: Duration(time.Second), RotationTimeout: Duration(45 * time.Second), RequestRetry: QualityGuardRequestRetryConfig{ MaxAttempts: 6, HoldTimeout: Duration(3 * time.Second), MinOutputTokens: 32, OnExhausted: "fail_closed", + AccountCooldown: Duration(24 * time.Hour), }, }, ClientKeyDefaults: ClientKeyDefaultsConfig{RPMLimit: clientkeydomain.DefaultRPMLimit, MaxConcurrent: clientkeydomain.DefaultMaxConcurrent}, diff --git a/backend/internal/infra/config/config_test.go b/backend/internal/infra/config/config_test.go index f06024ce..5204ac0f 100644 --- a/backend/internal/infra/config/config_test.go +++ b/backend/internal/infra/config/config_test.go @@ -215,7 +215,7 @@ qualityGuard: t.Fatalf("qualityGuard = %#v", value.QualityGuard) } retry := value.QualityGuard.RequestRetry - if retry.Enabled || retry.MaxAttempts != 6 || retry.HoldTimeout.Value() != 3*time.Second || retry.MinOutputTokens != 32 || retry.OnExhausted != "fail_closed" { + if retry.Enabled || retry.MaxAttempts != 6 || retry.HoldTimeout.Value() != 3*time.Second || retry.MinOutputTokens != 32 || retry.OnExhausted != "fail_closed" || retry.AccountCooldown.Value() != 24*time.Hour { t.Fatalf("loaded requestRetry defaults = %#v", retry) } } @@ -223,11 +223,35 @@ qualityGuard: func TestDefaultQualityGuardRequestRetryContract(t *testing.T) { t.Parallel() got := defaultConfig().QualityGuard.RequestRetry - if got.Enabled || got.MaxAttempts != 6 || got.HoldTimeout.Value() != 3*time.Second || got.MinOutputTokens != 32 || got.OnExhausted != "fail_closed" { + if got.Enabled || got.MaxAttempts != 6 || got.HoldTimeout.Value() != 3*time.Second || got.MinOutputTokens != 32 || got.OnExhausted != "fail_closed" || got.AccountCooldown.Value() != 24*time.Hour { t.Fatalf("requestRetry defaults = %#v", got) } } +func TestQualityGuardRequestRetryAccountCooldownBounds(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + value time.Duration + wantErr bool + }{ + {name: "default", value: 0}, + {name: "minimum", value: time.Minute}, + {name: "maximum", value: 168 * time.Hour}, + {name: "below minimum", value: time.Minute - time.Millisecond, wantErr: true}, + {name: "above maximum", value: 168*time.Hour + time.Millisecond, wantErr: true}, + } { + t.Run(test.name, func(t *testing.T) { + err := validateQualityGuardRequestRetry(QualityGuardRequestRetryConfig{ + Enabled: true, AccountCooldown: Duration(test.value), + }) + if (err != nil) != test.wantErr { + t.Fatalf("validate cooldown %s: err=%v, wantErr=%t", test.value, err, test.wantErr) + } + }) + } +} + func TestEnabledQualityGuardUsesManagedIdentity(t *testing.T) { value := defaultConfig() value.Secrets.JWTSecret = "12345678901234567890123456789012" diff --git a/backend/internal/infra/persistence/relational/account_repository.go b/backend/internal/infra/persistence/relational/account_repository.go index bd0c4b3a..d6f52087 100644 --- a/backend/internal/infra/persistence/relational/account_repository.go +++ b/backend/internal/infra/persistence/relational/account_repository.go @@ -2120,7 +2120,7 @@ func (r *AccountRepository) UpdateHealth(ctx context.Context, id uint64, provide } r.notifyInvalidation(ctx, repository.InvalidationEvent{ Kind: repository.InvalidationAccountHealthChanged, Provider: provider, AccountID: id, - FailureCount: failureCount, CooldownUntil: cooldownUntil, + FailureCount: failureCount, CooldownUntil: cooldownUntil, HealthMarker: account.NormalizeHealthMarker(lastError), }) return nil } diff --git a/backend/internal/infra/persistence/relational/audit_repository.go b/backend/internal/infra/persistence/relational/audit_repository.go index 8ec8eb54..840162fb 100644 --- a/backend/internal/infra/persistence/relational/audit_repository.go +++ b/backend/internal/infra/persistence/relational/audit_repository.go @@ -694,6 +694,7 @@ type degradeTotalsRow struct { Hard int64 `gorm:"column:hard"` Soft int64 `gorm:"column:soft"` Burst int64 `gorm:"column:burst"` + Thinking int64 `gorm:"column:thinking"` MaxTPS float64 `gorm:"column:max_tps"` } @@ -706,6 +707,7 @@ type degradeAccountRow struct { Burst int64 `gorm:"column:burst"` Soft int64 `gorm:"column:soft"` Hard int64 `gorm:"column:hard"` + Thinking int64 `gorm:"column:thinking"` Last degradeTimestamp `gorm:"column:last_seen"` Enabled bool `gorm:"column:enabled"` Found bool `gorm:"column:found"` @@ -809,6 +811,7 @@ func (r *AuditRepository) SummarizeDegrade(ctx context.Context, input repository COALESCE(SUM(CASE WHEN d.degrade_class = 'hard_tps' THEN 1 ELSE 0 END), 0) AS hard, COALESCE(SUM(CASE WHEN d.degrade_class = 'soft_tps' THEN 1 ELSE 0 END), 0) AS soft, COALESCE(SUM(CASE WHEN d.degrade_class = 'buffered_burst' THEN 1 ELSE 0 END), 0) AS burst, + COALESCE(SUM(CASE WHEN d.degrade_class = 'missing_thinking' THEN 1 ELSE 0 END), 0) AS thinking, COALESCE(MAX(d.tps), 0) AS max_tps`). Joins("LEFT JOIN provider_accounts p ON p.id = d.account_id"). Scan(&totals).Error; err != nil { @@ -817,7 +820,7 @@ func (r *AuditRepository) SummarizeDegrade(ctx context.Context, input repository result.Totals = repository.DegradeTotals{ Hits: totals.Hits, Accounts: totals.Accounts, StillEnabled: totals.StillEnabled, Disabled: totals.Disabled, Deleted: totals.Deleted, Hard: totals.Hard, Soft: totals.Soft, - Burst: totals.Burst, MaxTPS: totals.MaxTPS, + Burst: totals.Burst, Thinking: totals.Thinking, MaxTPS: totals.MaxTPS, } accountQuery := r.degradeAccountAggregate(tx, classified, input) @@ -840,7 +843,7 @@ func (r *AuditRepository) SummarizeDegrade(ctx context.Context, input repository for _, row := range accountRows { result.Accounts = append(result.Accounts, repository.DegradeAccount{ ID: row.ID, Name: row.Name, Email: row.Email, Hits: row.Hits, MaxTPS: row.MaxTPS, - Burst: row.Burst, Soft: row.Soft, Hard: row.Hard, Last: time.Time(row.Last), Enabled: row.Enabled, + Burst: row.Burst, Soft: row.Soft, Hard: row.Hard, Thinking: row.Thinking, Last: time.Time(row.Last), Enabled: row.Enabled, Found: row.Found, BuildBotFlagSource: row.BuildBotFlagSource, }) accountIDs = append(accountIDs, row.ID) @@ -878,7 +881,7 @@ func (r *AuditRepository) SummarizeDegrade(ctx context.Context, input repository bucketed := tx.Table("(?) AS d", classified).Select(caseSQL+" AS bucket_index, d.degrade_class", caseArgs...) var bucketRows []degradeBucketRow if err := tx.Table("(?) AS b", bucketed). - Select("b.bucket_index, COUNT(*) AS count, COALESCE(SUM(CASE WHEN b.degrade_class IN ('hard_tps', 'buffered_burst') THEN 1 ELSE 0 END), 0) AS severe"). + Select("b.bucket_index, COUNT(*) AS count, COALESCE(SUM(CASE WHEN b.degrade_class IN ('hard_tps', 'buffered_burst', 'missing_thinking') THEN 1 ELSE 0 END), 0) AS severe"). Where("b.bucket_index >= 0").Group("b.bucket_index").Order("b.bucket_index ASC").Scan(&bucketRows).Error; err != nil { return err } @@ -916,14 +919,22 @@ func (r *AuditRepository) degradeClassifiedQuery(tx *gorm.DB, input repository.D // NULLIF keeps PostgreSQL safe even if its planner evaluates the throughput // expression before the duration guard in the WHERE clause. tpsExpression := fmt.Sprintf("(CAST(a.output_tokens AS %s) * 1000.0 / NULLIF(%s, 0))", castType, generationExpression) - classExpression := fmt.Sprintf("CASE WHEN ? AND %s < ? THEN ? WHEN %s >= ? THEN ? ELSE ? END", generationExpression, tpsExpression) + selectTPS := fmt.Sprintf("CASE WHEN a.error_code = ? THEN 0 ELSE %s END", tpsExpression) + classExpression := fmt.Sprintf("CASE WHEN a.error_code = ? THEN ? WHEN ? AND %s < ? THEN ? WHEN %s >= ? THEN ? ELSE ? END", generationExpression, tpsExpression) + speedPredicate := fmt.Sprintf( + "a.streaming = ? AND %s AND a.output_tokens >= ? AND a.first_token_ms IS NOT NULL AND a.duration_ms > a.first_token_ms AND %s >= ?", + auditSuccessPredicate, tpsExpression, + ) + thinkingPredicate := "a.streaming = ? AND a.error_code = ? AND a.status_code >= 200 AND a.status_code < 300" query := tx.Table("request_audits AS a"). - Select("a.id, a.request_id, a.account_id, a.account_name, a.egress_node_id, a.egress_node_name, a.output_tokens, a.created_at, a.model_upstream_model, "+tpsExpression+" AS tps, "+classExpression+" AS degrade_class", - input.FailClosed, input.MinGenerationMS, audit.DegradeClassBurst, input.HardTPS, audit.DegradeClassHard, audit.DegradeClassSoft). - Where("a.provider = ?", "grok_build").Where("a.streaming = ?", true). - Where(auditSuccessPredicate).Where("a.output_tokens >= ?", input.MinOutputTokens). - Where("a.first_token_ms IS NOT NULL").Where("a.duration_ms > a.first_token_ms"). - Where("a.request_id NOT LIKE ?", "quality_%").Where(tpsExpression+" >= ?", input.SoftTPS) + Select("a.id, a.request_id, a.account_id, a.account_name, a.egress_node_id, a.egress_node_name, a.output_tokens, a.created_at, a.model_upstream_model, "+selectTPS+" AS tps, "+classExpression+" AS degrade_class", + audit.ErrorQualityDegraded, + audit.ErrorQualityDegraded, audit.DegradeClassThinking, input.FailClosed, input.MinGenerationMS, audit.DegradeClassBurst, input.HardTPS, audit.DegradeClassHard, audit.DegradeClassSoft). + Where("a.provider = ?", "grok_build"). + Where("a.request_id NOT LIKE ?", "quality_%"). + Where("(("+speedPredicate+") OR ("+thinkingPredicate+"))", + true, input.MinOutputTokens, input.SoftTPS, + true, audit.ErrorQualityDegraded) if !input.Start.IsZero() { query = query.Where("a.created_at >= ?", input.Start) } @@ -943,6 +954,7 @@ func (r *AuditRepository) degradeAccountAggregate(tx *gorm.DB, classified *gorm. COALESCE(SUM(CASE WHEN d.degrade_class = 'buffered_burst' THEN 1 ELSE 0 END), 0) AS burst, COALESCE(SUM(CASE WHEN d.degrade_class = 'soft_tps' THEN 1 ELSE 0 END), 0) AS soft, COALESCE(SUM(CASE WHEN d.degrade_class = 'hard_tps' THEN 1 ELSE 0 END), 0) AS hard, + COALESCE(SUM(CASE WHEN d.degrade_class = 'missing_thinking' THEN 1 ELSE 0 END), 0) AS thinking, MAX(d.created_at) AS last_seen, COALESCE(p.enabled, FALSE) AS enabled, CASE WHEN p.id IS NULL THEN FALSE ELSE TRUE END AS found, diff --git a/backend/internal/repository/audit.go b/backend/internal/repository/audit.go index d421a5d0..d8e7bced 100644 --- a/backend/internal/repository/audit.go +++ b/backend/internal/repository/audit.go @@ -61,6 +61,7 @@ type DegradeTotals struct { Hard int64 Soft int64 Burst int64 + Thinking int64 MaxTPS float64 } @@ -73,6 +74,7 @@ type DegradeAccount struct { Burst int64 Soft int64 Hard int64 + Thinking int64 Last time.Time Enabled bool Found bool diff --git a/backend/internal/repository/runtime.go b/backend/internal/repository/runtime.go index 429342f7..a5dd5d34 100644 --- a/backend/internal/repository/runtime.go +++ b/backend/internal/repository/runtime.go @@ -116,16 +116,19 @@ const ( ) type InvalidationEvent struct { - Kind InvalidationKind `json:"kind"` - Provider account.Provider `json:"provider,omitempty"` - AccountID uint64 `json:"accountId,omitempty"` - ClientKeyID uint64 `json:"clientKeyId,omitempty"` - UpstreamModel string `json:"upstreamModel,omitempty"` - FailureCount int `json:"failureCount,omitempty"` - CooldownUntil *time.Time `json:"cooldownUntil,omitempty"` - Revision uint64 `json:"revision,omitempty"` - SourceInstance string `json:"sourceInstance,omitempty"` - PublishedAt time.Time `json:"publishedAt,omitempty"` + Kind InvalidationKind `json:"kind"` + Provider account.Provider `json:"provider,omitempty"` + AccountID uint64 `json:"accountId,omitempty"` + ClientKeyID uint64 `json:"clientKeyId,omitempty"` + UpstreamModel string `json:"upstreamModel,omitempty"` + FailureCount int `json:"failureCount,omitempty"` + CooldownUntil *time.Time `json:"cooldownUntil,omitempty"` + // HealthMarker carries only domain-approved, non-sensitive durable markers. + // Arbitrary upstream error text must never be published on the runtime bus. + HealthMarker string `json:"healthMarker,omitempty"` + Revision uint64 `json:"revision,omitempty"` + SourceInstance string `json:"sourceInstance,omitempty"` + PublishedAt time.Time `json:"publishedAt,omitempty"` } func (e InvalidationEvent) Layer() InvalidationLayer { diff --git a/backend/internal/transport/http/audit/handler.go b/backend/internal/transport/http/audit/handler.go index 0c22e741..031d50f1 100644 --- a/backend/internal/transport/http/audit/handler.go +++ b/backend/internal/transport/http/audit/handler.go @@ -386,7 +386,7 @@ func (h *Handler) degradeAccounts(c *gin.Context) { Totals: degradeTotalsResponse{ Hits: result.Totals.Hits, Accounts: result.Totals.Accounts, StillEnabled: result.Totals.StillEnabled, Disabled: result.Totals.Disabled, Deleted: result.Totals.Deleted, Hard: result.Totals.Hard, - Soft: result.Totals.Soft, Burst: result.Totals.Burst, MaxTPS: result.Totals.MaxTPS, + Soft: result.Totals.Soft, Burst: result.Totals.Burst, Thinking: result.Totals.Thinking, MaxTPS: result.Totals.MaxTPS, }, Series: result.Series, Nodes: result.Nodes, Accounts: accounts, AccountPage: degradeAccountPageResponse{ @@ -432,6 +432,7 @@ type degradeTotalsResponse struct { Hard int64 `json:"hard"` Soft int64 `json:"soft"` Burst int64 `json:"burst"` + Thinking int64 `json:"thinking"` MaxTPS float64 `json:"maxTPS"` } diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index 552b6943..af803a0f 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -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 { diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go index 3d63c2a5..9215bd34 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,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"`) { 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..4926d54b --- /dev/null +++ b/backend/internal/transport/http/inference/responses_compat.go @@ -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 + } +} diff --git a/config.example.yaml b/config.example.yaml index 2fa23eb4..627df547 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -152,3 +152,6 @@ qualityGuard: holdTimeout: 3s minOutputTokens: 32 onExhausted: fail_closed # fail_open | fail_closed + # First missing-thinking hit cools the account; a later hit after the + # cooldown expires disables it. + accountCooldown: 24h diff --git a/frontend/src/features/quality-guard/degrade-accounts-panel.tsx b/frontend/src/features/quality-guard/degrade-accounts-panel.tsx index 8d269ff8..810d22dc 100644 --- a/frontend/src/features/quality-guard/degrade-accounts-panel.tsx +++ b/frontend/src/features/quality-guard/degrade-accounts-panel.tsx @@ -79,7 +79,7 @@ export function DegradeAccountsPanel({ softTPS, hardTPS, failClosed, minGenMs }: return (