diff --git a/backend/internal/application/audit/degrade_test.go b/backend/internal/application/audit/degrade_test.go index 4705aa37..2c28488f 100644 --- a/backend/internal/application/audit/degrade_test.go +++ b/backend/internal/application/audit/degrade_test.go @@ -129,6 +129,38 @@ func TestDegradeSummaryMatchesFailClosedShortWindowPolicy(t *testing.T) { } } +func TestDegradeSummaryUsesReasoningEvidenceForLateFlushFallback(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-reasoning.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(10000) + accountID := uint64(9) + records := []auditdomain.Record{ + {RequestID: "reasoning-late-flush", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", AccountID: &accountID, StatusCode: 200, Streaming: true, OutputTokens: 2000, ReasoningTokens: 1900, FirstTokenMS: &first, DurationMS: 10100, CreatedAt: now.Add(-2 * time.Minute)}, + {RequestID: "visible-output-burst", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", AccountID: &accountID, StatusCode: 200, Streaming: true, OutputTokens: 2000, FirstTokenMS: &first, DurationMS: 10100, CreatedAt: now.Add(-time.Minute)}, + } + 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, FailClosed: true}, DegradeAccountFilter{}) + if err != nil { + t.Fatal(err) + } + if summary.Totals.Hits != 1 || summary.Totals.Burst != 1 || len(summary.Events) != 1 || summary.Events[0].RequestID != "visible-output-burst" { + t.Fatalf("reasoning-aware summary = totals %#v events %#v", summary.Totals, summary.Events) + } +} + func TestDegradeSummaryPaginatesAccountsInRepository(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-page.db")) diff --git a/backend/internal/application/gateway/quality_probe.go b/backend/internal/application/gateway/quality_probe.go index 31fc3c7f..e66870af 100644 --- a/backend/internal/application/gateway/quality_probe.go +++ b/backend/internal/application/gateway/quality_probe.go @@ -2,6 +2,7 @@ package gateway import ( "bufio" + "bytes" "context" "crypto/sha256" "encoding/hex" @@ -32,6 +33,7 @@ type qualityProbeChatEvent struct { Content string `json:"content"` Reasoning string `json:"reasoning"` ReasoningContent string `json:"reasoning_content"` + ThinkingContent string `json:"thinking_content"` } `json:"delta"` } `json:"choices"` Usage *struct { @@ -108,6 +110,15 @@ func (s *Service) ProbeEgressQuality(ctx context.Context, nodeID uint64, input e return egressapp.QualityProbeResult{}, fmt.Errorf("质量探测响应超过 %d MiB", qualityProbeMaxStreamBytes>>20) } line = []byte(strings.TrimSpace(string(line))) + if bytes.Equal(line, []byte(": grok2api-reasoning-start")) { + if firstGeneratedAt.IsZero() { + firstGeneratedAt = time.Now() + if result.MarkFirstToken != nil { + result.MarkFirstToken() + } + } + continue + } if !strings.HasPrefix(string(line), "data:") { continue } @@ -133,7 +144,7 @@ func (s *Service) ProbeEgressQuality(ctx context.Context, nodeID uint64, input e } for _, choice := range event.Choices { delta := choice.Delta - generated := delta.Content != "" || delta.Reasoning != "" || delta.ReasoningContent != "" + generated := qualityProbeHasGeneratedDelta(delta.Content, delta.Reasoning, delta.ReasoningContent, delta.ThinkingContent) if generated && firstGeneratedAt.IsZero() { firstGeneratedAt = time.Now() if result.MarkFirstToken != nil { @@ -170,14 +181,14 @@ func (s *Service) ProbeEgressQuality(ctx context.Context, nodeID uint64, input e durationMS := completedAt.Sub(startedAt).Milliseconds() var generationMS int64 if !firstGeneratedAt.IsZero() { - generationMS = durationMS - firstTokenMS + generationMS = audit.GenerationWindowMS(firstTokenMS, durationMS, usage.ReasoningTokens) if generationMS < 1 { generationMS = 1 } } var outputTokensPerSecond float64 if !firstGeneratedAt.IsZero() { - outputTokensPerSecond = qualityProbeOutputTokensPerSecond(usage.OutputTokens, durationMS, firstTokenMS) + outputTokensPerSecond = qualityProbeOutputTokensPerSecond(usage.OutputTokens, usage.ReasoningTokens, durationMS, firstTokenMS) } digest := sha256.Sum256([]byte(text)) return egressapp.QualityProbeResult{ @@ -200,10 +211,10 @@ func normalizeQualityProbeRequestError(err error) error { return err } -func qualityProbeOutputTokensPerSecond(outputTokens, durationMS, firstTokenMS int64) float64 { - generationMS := durationMS - firstTokenMS - if outputTokens <= 0 || generationMS <= 0 { - return 0 - } - return float64(outputTokens) * 1000 / float64(generationMS) +func qualityProbeOutputTokensPerSecond(outputTokens, reasoningTokens, durationMS, firstTokenMS int64) float64 { + return audit.OutputTokensPerSecond(outputTokens, reasoningTokens, firstTokenMS, durationMS) +} + +func qualityProbeHasGeneratedDelta(content, reasoning, reasoningContent, thinkingContent string) bool { + return content != "" || reasoning != "" || reasoningContent != "" || thinkingContent != "" } diff --git a/backend/internal/application/gateway/quality_probe_test.go b/backend/internal/application/gateway/quality_probe_test.go index 390c6f30..80a17a67 100644 --- a/backend/internal/application/gateway/quality_probe_test.go +++ b/backend/internal/application/gateway/quality_probe_test.go @@ -25,8 +25,10 @@ func TestQualityProbeModelIsPinnedToBuildNamespace(t *testing.T) { } func TestQualityProbeOutputTokensPerSecondMatchesAuditPanel(t *testing.T) { - got := qualityProbeOutputTokensPerSecond(1335, 17320, 17100) - want := float64(1335) * 1000 / 220 + got := qualityProbeOutputTokensPerSecond(1335, 1200, 17320, 17100) + // 17100ms wait vs 220ms tail: use full duration so buffered thinking is + // not crushed into the flush window. + want := float64(1335) * 1000 / 17320 if got != want { t.Fatalf("output TPS = %v, want %v", got, want) } @@ -34,8 +36,36 @@ func TestQualityProbeOutputTokensPerSecondMatchesAuditPanel(t *testing.T) { func TestQualityProbeOutputTokensPerSecondIncludesReasoningTokens(t *testing.T) { // The panel reports completion/output tokens, including reasoning tokens. - got := qualityProbeOutputTokensPerSecond(1050, 1100, 1000) - if got != 10500 { - t.Fatalf("output TPS = %v, want 10500", got) + // 100ms tail after 1000ms wait is a short flush, so the window is duration. + got := qualityProbeOutputTokensPerSecond(1050, 1000, 1100, 1000) + want := float64(1050) * 1000 / 1100 + if got != want { + t.Fatalf("output TPS = %v, want %v", got, want) + } +} + +func TestQualityProbeOutputTokensPerSecondKeepsNormalTail(t *testing.T) { + got := qualityProbeOutputTokensPerSecond(200, 0, 2200, 200) + if got != 100 { + t.Fatalf("output TPS = %v, want 100", got) + } +} + +func TestQualityProbeOutputTokensPerSecondKeepsBurstWithoutReasoning(t *testing.T) { + got := qualityProbeOutputTokensPerSecond(2000, 0, 10100, 10000) + if got != 20000 { + t.Fatalf("output TPS = %v, want 20000", got) + } +} + +func TestQualityProbeCountsThinkingContentAsFirstToken(t *testing.T) { + if qualityProbeHasGeneratedDelta("", "", "", "") { + t.Fatal("empty deltas must not mark first token") + } + if !qualityProbeHasGeneratedDelta("", "", "", "hmm") { + t.Fatal("thinking_content must mark first token so thinking time stays in the generation window") + } + if !qualityProbeHasGeneratedDelta("", "", "hmm", "") { + t.Fatal("reasoning_content must still mark first token") } } diff --git a/backend/internal/application/gateway/selector.go b/backend/internal/application/gateway/selector.go index 60851724..7604c2bc 100644 --- a/backend/internal/application/gateway/selector.go +++ b/backend/internal/application/gateway/selector.go @@ -1108,25 +1108,25 @@ func (s *Selector) clearQuotaConsumptionAccount(provider account.Provider, accou } func (s *Selector) MarkFailure(ctx context.Context, credential account.Credential, status int, retryAfter time.Duration) { - _ = s.markFailure(ctx, credential, credential.FailureCount+1, status, retryAfter) + _ = s.markFailure(ctx, credential, credential.FailureCount, credential.FailureCount+1, status, retryAfter) } // MarkFailureAfterSuccess records a stream failure from a fresh health baseline. // The upstream already returned a successful response header, so failures that // preceded this request must not be carried into the new cooldown calculation. func (s *Selector) MarkFailureAfterSuccess(ctx context.Context, credential account.Credential, status int, retryAfter time.Duration) error { - return s.markFailure(ctx, credential, 1, status, retryAfter) + return s.markFailure(ctx, credential, 0, 1, status, retryAfter) } -func (s *Selector) markFailure(ctx context.Context, credential account.Credential, failureCount, status int, retryAfter time.Duration) error { +func (s *Selector) markFailure(ctx context.Context, credential account.Credential, baselineFailureCount, nextFailureCount, status int, retryAfter time.Duration) error { _, cooldownBase, cooldownMax, _ := s.routingConfig() // 网络/超时(status 0)只短隔离本号,不累加失败次数,避免瞬时抖动把号池指数冻空。 // 上游返回的 4xx/5xx 仍按原指数冷却:那是上游明确给出的状态,不是本地网络抖动。 softNetwork := status == 0 - effectiveFailureCount := failureCount + effectiveFailureCount := nextFailureCount cooldown := cooldownBase if softNetwork { - effectiveFailureCount = credential.FailureCount + effectiveFailureCount = baselineFailureCount cooldown = softNetworkCooldown if retryAfter > cooldown { cooldown = retryAfter diff --git a/backend/internal/application/gateway/selector_test.go b/backend/internal/application/gateway/selector_test.go index 499b6c1b..a239563f 100644 --- a/backend/internal/application/gateway/selector_test.go +++ b/backend/internal/application/gateway/selector_test.go @@ -1519,6 +1519,42 @@ func TestMarkFailureSoftNetworkCooldown(t *testing.T) { if hard.CooldownUntil == nil || hard.CooldownUntil.Sub(time.Now().UTC()) < 20*time.Second { t.Fatalf("hard cooldown too short: %v", hard.CooldownUntil) } + + before = time.Now().UTC() + selector.MarkFailure(ctx, hard, 0, 0) + preserved, err := accounts.Get(ctx, credential.ID) + if err != nil { + t.Fatal(err) + } + if preserved.FailureCount != hard.FailureCount { + t.Fatalf("ordinary soft failure count = %d, want preserved %d", preserved.FailureCount, hard.FailureCount) + } + if preserved.CooldownUntil == nil { + t.Fatal("ordinary soft failure did not set cooldown") + } + cooldown = preserved.CooldownUntil.Sub(before) + if cooldown < 4*time.Second || cooldown > 6*time.Second { + t.Fatalf("ordinary soft cooldown = %s, want ~5s", cooldown) + } + + before = time.Now().UTC() + if err := selector.MarkFailureAfterSuccess(ctx, preserved, 0, 0); err != nil { + t.Fatal(err) + } + reset, err := accounts.Get(ctx, credential.ID) + if err != nil { + t.Fatal(err) + } + if reset.FailureCount != 0 { + t.Fatalf("after-success soft failure count = %d, want 0", reset.FailureCount) + } + if reset.CooldownUntil == nil { + t.Fatal("after-success soft failure did not set cooldown") + } + cooldown = reset.CooldownUntil.Sub(before) + if cooldown < 4*time.Second || cooldown > 6*time.Second { + t.Fatalf("after-success soft cooldown = %s, want ~5s", cooldown) + } } type batchConcurrencyLimiter struct { diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index bf89113f..05e2261f 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -1358,7 +1358,7 @@ attemptLoop: budget := newFinalizationBudget(string(operation), string(route.Provider)) if isUpstreamStreamFailure(errorCode) { if err := budget.run("account_health", finalizationHealthBudget, func(stageCtx context.Context) error { - return s.selector.MarkFailureAfterSuccess(stageCtx, credential, http.StatusBadGateway, 0) + return s.selector.MarkFailureAfterSuccess(stageCtx, credential, 0, 0) }); err != nil { s.logger.Warn("stream_failure_health_write_failed", "account_id", credential.ID, "provider", credential.Provider, "error", err) } diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index 683ca03a..6be8cc6c 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -401,7 +401,7 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) { } _ = interrupted.Body.Close() interruptedAccount, err := accountRepo.Get(ctx, adapter.attempts[0]) - if err != nil || interruptedAccount.FailureCount != 1 || interruptedAccount.CooldownUntil == nil { + if err != nil || interruptedAccount.FailureCount != 0 || interruptedAccount.CooldownUntil == nil { t.Fatalf("interrupted account health = %#v, err=%v", interruptedAccount, err) } } diff --git a/backend/internal/domain/audit/degrade.go b/backend/internal/domain/audit/degrade.go index 66af0667..e3b7b2e4 100644 --- a/backend/internal/domain/audit/degrade.go +++ b/backend/internal/domain/audit/degrade.go @@ -14,15 +14,15 @@ const ( ) // ClassifyOutputSpeed matches the quality-guard panel formula: -// output tokens / (durationMs - firstTokenMs). In fail-closed mode, short -// generation windows with a soft-or-higher rate are buffered_burst; otherwise -// the hard and soft thresholds apply in that order. -func ClassifyOutputSpeed(outputTokens, firstTokenMS, durationMS int64, softTPS, hardTPS float64, minGenMS int64, failClosed bool) (class string, tps float64, genMS int64) { - genMS = durationMS - firstTokenMS +// output tokens / GenerationWindowMS. In fail-closed mode, short generation +// windows with a soft-or-higher rate are buffered_burst; otherwise the hard +// and soft thresholds apply in that order. +func ClassifyOutputSpeed(outputTokens, reasoningTokens, firstTokenMS, durationMS int64, softTPS, hardTPS float64, minGenMS int64, failClosed bool) (class string, tps float64, genMS int64) { + genMS = GenerationWindowMS(firstTokenMS, durationMS, reasoningTokens) if genMS <= 0 || outputTokens <= 0 { return "", 0, genMS } - tps = float64(outputTokens) * 1000 / float64(genMS) + tps = OutputTokensPerSecond(outputTokens, reasoningTokens, firstTokenMS, durationMS) if failClosed && minGenMS > 0 && genMS < minGenMS && tps >= softTPS { return DegradeClassBurst, tps, genMS } @@ -34,3 +34,36 @@ func ClassifyOutputSpeed(outputTokens, firstTokenMS, durationMS int64, softTPS, } return "", tps, genMS } + +// GenerationWindowMS is the Token/s denominator shared by the audit panel, +// dashboard, probes, and quality guard. +// +// Normally that is duration − first token. Older audit rows may have measured +// first token only when buffered reasoning was finally flushed. For rows that +// actually report reasoning tokens, use the full duration when the remaining +// tail is implausibly short. Rows without reasoning evidence retain the tail so +// real buffered output bursts remain visible to the fail-closed guard. +func GenerationWindowMS(firstTokenMS, durationMS, reasoningTokens int64) int64 { + if durationMS <= 0 { + return 0 + } + if firstTokenMS < 0 { + firstTokenMS = 0 + } + if firstTokenMS >= durationMS { + return 0 + } + generationMS := durationMS - firstTokenMS + if reasoningTokens > 0 && generationMS < firstTokenMS && generationMS < DefaultDegradeMinGenMS { + return durationMS + } + return generationMS +} + +func OutputTokensPerSecond(outputTokens, reasoningTokens, firstTokenMS, durationMS int64) float64 { + generationMS := GenerationWindowMS(firstTokenMS, durationMS, reasoningTokens) + if outputTokens <= 0 || generationMS <= 0 { + return 0 + } + return float64(outputTokens) * 1000 / float64(generationMS) +} diff --git a/backend/internal/domain/audit/degrade_test.go b/backend/internal/domain/audit/degrade_test.go index 476ce742..f6cb8936 100644 --- a/backend/internal/domain/audit/degrade_test.go +++ b/backend/internal/domain/audit/degrade_test.go @@ -4,12 +4,12 @@ import "testing" func TestClassifyOutputSpeed(t *testing.T) { tests := []struct { - name string - output, first, duration int64 - soft, hard float64 - minGen int64 - failClosed bool - wantClass string + name string + output, reasoning, first, duration int64 + soft, hard float64 + minGen int64 + failClosed bool + wantClass string }{ {name: "hard", output: 2000, first: 200, duration: 1200, soft: 500, hard: 1000, minGen: 1000, wantClass: DegradeClassHard}, {name: "soft", output: 600, first: 200, duration: 1400, soft: 500, hard: 1000, minGen: 1000, wantClass: DegradeClassSoft}, @@ -17,13 +17,48 @@ func TestClassifyOutputSpeed(t *testing.T) { {name: "burst short window when fail closed", output: 200, first: 50, duration: 250, soft: 500, hard: 1000, minGen: 1000, failClosed: true, wantClass: DegradeClassBurst}, {name: "healthy", output: 100, first: 200, duration: 2200, soft: 500, hard: 1000, minGen: 1000, wantClass: ""}, {name: "zero generation", output: 100, first: 500, duration: 500, soft: 500, hard: 1000, minGen: 1000, wantClass: ""}, + {name: "late first token with reasoning uses full duration", output: 1511, reasoning: 1400, first: 19763, duration: 19827, soft: 500, hard: 1000, minGen: 1000, wantClass: ""}, + {name: "late first token without reasoning remains burst", output: 2000, first: 10000, duration: 10100, soft: 500, hard: 1000, minGen: 1000, failClosed: true, wantClass: DegradeClassBurst}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - class, _, _ := ClassifyOutputSpeed(test.output, test.first, test.duration, test.soft, test.hard, test.minGen, test.failClosed) + class, tps, genMS := ClassifyOutputSpeed(test.output, test.reasoning, test.first, test.duration, test.soft, test.hard, test.minGen, test.failClosed) if class != test.wantClass { t.Fatalf("class = %q, want %q", class, test.wantClass) } + if test.name == "late first token with reasoning uses full duration" { + if genMS != test.duration { + t.Fatalf("genMS = %d, want duration %d", genMS, test.duration) + } + want := float64(test.output) * 1000 / float64(test.duration) + if tps != want { + t.Fatalf("tps = %v, want %v", tps, want) + } + } }) } } + +func TestGenerationWindowMSFallsBackOnlyWithReasoningEvidence(t *testing.T) { + if got := GenerationWindowMS(19763, 19827, 1400); got != 19827 { + t.Fatalf("late first token window = %d", got) + } + if got := GenerationWindowMS(19763, 19827, 0); got != 64 { + t.Fatalf("late first token without reasoning window = %d", got) + } + if got := GenerationWindowMS(200, 2200, 100); got != 2000 { + t.Fatalf("normal window = %d", got) + } + if got := GenerationWindowMS(50, 250, 100); got != 200 { + t.Fatalf("short-but-not-late window = %d", got) + } + if got := GenerationWindowMS(500, 500, 100); got != 0 { + t.Fatalf("zero window = %d", got) + } + if got := GenerationWindowMS(2000, 3500, 100); got != 1500 { + t.Fatalf("think-then-write window must keep the tail: %d", got) + } + if got := GenerationWindowMS(400, 1500, 100); got != 1100 { + t.Fatalf("tail at least 1s keeps after-first-token window: %d", got) + } +} diff --git a/backend/internal/infra/persistence/relational/audit_repository.go b/backend/internal/infra/persistence/relational/audit_repository.go index 61824b40..b908ce71 100644 --- a/backend/internal/infra/persistence/relational/audit_repository.go +++ b/backend/internal/infra/persistence/relational/audit_repository.go @@ -911,7 +911,7 @@ func (r *AuditRepository) degradeClassifiedQuery(tx *gorm.DB, input repository.D if r.db.dialect == "postgres" { castType = "DOUBLE PRECISION" } - generationExpression := "(a.duration_ms - a.first_token_ms)" + generationExpression := fmt.Sprintf("(CASE WHEN a.reasoning_tokens > 0 AND a.duration_ms - a.first_token_ms < a.first_token_ms AND a.duration_ms - a.first_token_ms < %d THEN a.duration_ms ELSE a.duration_ms - a.first_token_ms END)", audit.DefaultDegradeMinGenMS) // 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) diff --git a/backend/internal/infra/persistence/relational/dashboard_repository.go b/backend/internal/infra/persistence/relational/dashboard_repository.go index 673b047e..5d96e7f3 100644 --- a/backend/internal/infra/persistence/relational/dashboard_repository.go +++ b/backend/internal/infra/persistence/relational/dashboard_repository.go @@ -30,7 +30,7 @@ const dashboardUsageAggregateSelect = ` COALESCE(SUM(first_token_ms), 0) AS first_token_total_ms, COALESCE(SUM(CASE WHEN first_token_ms IS NOT NULL AND output_tokens > 0 AND duration_ms > first_token_ms THEN 1 ELSE 0 END), 0) AS throughput_samples, COALESCE(SUM(CASE WHEN first_token_ms IS NOT NULL AND output_tokens > 0 AND duration_ms > first_token_ms THEN output_tokens ELSE 0 END), 0) AS throughput_tokens, - COALESCE(SUM(CASE WHEN first_token_ms IS NOT NULL AND output_tokens > 0 AND duration_ms > first_token_ms THEN duration_ms - first_token_ms ELSE 0 END), 0) AS generation_total_ms` + COALESCE(SUM(CASE WHEN first_token_ms IS NOT NULL AND output_tokens > 0 AND duration_ms > first_token_ms THEN CASE WHEN reasoning_tokens > 0 AND duration_ms - first_token_ms < first_token_ms AND duration_ms - first_token_ms < 1000 THEN duration_ms ELSE duration_ms - first_token_ms END ELSE 0 END), 0) AS generation_total_ms` const dashboardTopModelsLimit = 10 diff --git a/backend/internal/infra/persistence/relational/dashboard_repository_test.go b/backend/internal/infra/persistence/relational/dashboard_repository_test.go index a3a64bb5..dd4aecd5 100644 --- a/backend/internal/infra/persistence/relational/dashboard_repository_test.go +++ b/backend/internal/infra/persistence/relational/dashboard_repository_test.go @@ -201,6 +201,38 @@ type dashboardBenchmarkUsage struct { GenerationTotalMS int64 } +func TestDashboardRepositoryUsesFullDurationOnlyWithReasoningEvidence(t *testing.T) { + ctx := context.Background() + database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "dashboard-short-tail.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + now := time.Date(2026, 8, 16, 12, 0, 0, 0, time.UTC) + lateFirst := int64(19763) + normalFirst := int64(200) + burstFirst := int64(10000) + rows := []requestAuditModel{ + {RequestID: "late-reasoning-flush", ClientKeyID: 1, ModelRouteID: 1, ModelPublicID: "grok-4.6", Provider: "grok_build", Operation: "chat", UsageSource: "upstream", StatusCode: 200, Streaming: true, OutputTokens: 1511, ReasoningTokens: 1400, FirstTokenMS: &lateFirst, DurationMS: 19827, CreatedAt: now.Add(-time.Hour)}, + {RequestID: "normal-tail", ClientKeyID: 1, ModelRouteID: 1, ModelPublicID: "grok-4.6", Provider: "grok_build", Operation: "chat", UsageSource: "upstream", StatusCode: 200, Streaming: true, OutputTokens: 80, FirstTokenMS: &normalFirst, DurationMS: 2200, CreatedAt: now.Add(-30 * time.Minute)}, + {RequestID: "no-reasoning-burst", ClientKeyID: 1, ModelRouteID: 1, ModelPublicID: "grok-4.6", Provider: "grok_build", Operation: "chat", UsageSource: "upstream", StatusCode: 200, Streaming: true, OutputTokens: 2000, FirstTokenMS: &burstFirst, DurationMS: 10100, CreatedAt: now.Add(-15 * time.Minute)}, + } + if err := database.db.WithContext(ctx).Create(&rows).Error; err != nil { + t.Fatal(err) + } + boundaries := testDashboardBoundaries(now.Add(-2*time.Hour), time.Hour, 2) + snapshot, err := NewDashboardRepository(database).Snapshot(ctx, testDashboardWindow(boundaries), now) + if err != nil { + t.Fatal(err) + } + if snapshot.Usage.ThroughputTokens != 3591 || snapshot.Usage.GenerationTotalMS != 19827+2000+100 { + t.Fatalf("short-tail generation window = %#v", snapshot.Usage) + } +} + func TestDashboardRepositoryRanksTopModels(t *testing.T) { ctx := context.Background() database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "dashboard-top-models.db")) diff --git a/backend/internal/infra/provider/conversation/chat_stream.go b/backend/internal/infra/provider/conversation/chat_stream.go index fe78807c..ea91432e 100644 --- a/backend/internal/infra/provider/conversation/chat_stream.go +++ b/backend/internal/infra/provider/conversation/chat_stream.go @@ -34,6 +34,23 @@ func (c *streamConverter) chatDelta(delta map[string]any) error { }) } +// markChatReasoningStart emits an SSE comment so the gateway can include +// encrypted or buffered thinking in its generation window. SSE clients ignore +// comments, so the public Chat Completions JSON contract remains unchanged. +func (c *streamConverter) markChatReasoningStart() error { + if c.chatReasoningMark { + return nil + } + if err := c.start(); err != nil { + return err + } + if _, err := io.WriteString(c.writer, ": grok2api-reasoning-start\n\n"); err != nil { + return err + } + c.chatReasoningMark = true + return nil +} + func (c *streamConverter) toolStartChat(item responseItem, _ int) error { if err := c.start(); err != nil { return err diff --git a/backend/internal/infra/provider/conversation/conversation_test.go b/backend/internal/infra/provider/conversation/conversation_test.go index 64906284..55ffded4 100644 --- a/backend/internal/infra/provider/conversation/conversation_test.go +++ b/backend/internal/infra/provider/conversation/conversation_test.go @@ -864,6 +864,35 @@ func TestConvertResponsesStreamChatErrorIsTerminal(t *testing.T) { } } +func TestConvertResponsesStreamMarksChatReasoningStart(t *testing.T) { + stream := strings.Join([]string{ + `event: response.created`, + `data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.6"}}`, "", + `event: response.output_item.added`, + `data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning","status":"in_progress"}}`, "", + `event: response.output_item.added`, + `data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`, "", + `event: response.output_text.delta`, + `data: {"type":"response.output_text.delta","delta":"hi"}`, "", + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed"}}`, "", "", + }, "\n") + converted, err := io.ReadAll(ConvertResponseStream(io.NopCloser(strings.NewReader(stream)), OperationChat)) + if err != nil { + t.Fatal(err) + } + text := string(converted) + if strings.Count(text, ": grok2api-reasoning-start\n\n") != 1 { + t.Fatalf("expected one reasoning start marker: %s", text) + } + if strings.Contains(text, "reasoning_started") { + t.Fatalf("internal timing marker leaked into Chat JSON: %s", text) + } + if !strings.Contains(text, `"content":"hi"`) { + t.Fatalf("missing visible content: %s", text) + } +} + func TestConvertResponsesStreamMessagesNormalizesTerminalError(t *testing.T) { stream := strings.Join([]string{ `event: response.failed`, diff --git a/backend/internal/infra/provider/conversation/stream.go b/backend/internal/infra/provider/conversation/stream.go index e8b8fde3..e7ecc55e 100644 --- a/backend/internal/infra/provider/conversation/stream.go +++ b/backend/internal/infra/provider/conversation/stream.go @@ -49,6 +49,7 @@ type streamConverter struct { thinkingClosed bool thinkingIndex int thinkingItemID string + chatReasoningMark bool nextIndex int tools map[string]streamTool webSearch []webSearchCall @@ -266,6 +267,9 @@ func (c *streamConverter) handle(event string, data []byte) error { if item.Type == "reasoning" && c.operation == OperationMessages && c.options.AnthropicThinking { return c.thinkingStart(item.ID) } + if item.Type == "reasoning" && item.ID != "" && c.operation == OperationChat { + return c.markChatReasoningStart() + } if item.Type == "web_search_call" && c.operation == OperationMessages && c.options.AnthropicWebSearch { if call, ok := parseWebSearchCallItem(item); ok { return c.noteWebSearch(call, false) diff --git a/backend/internal/infra/provider/web/attachments.go b/backend/internal/infra/provider/web/attachments.go index d5628538..020b2d9c 100644 --- a/backend/internal/infra/provider/web/attachments.go +++ b/backend/internal/infra/provider/web/attachments.go @@ -32,8 +32,14 @@ var ( ) type uploadedFile struct { - ID string - URI string + // ID is the best available generic attachment reference. Some upload + // responses only contain fileId or uploadId, which remain valid for chat + // attachment flows that already accept those references. + ID string + // MetadataID is populated only from fileMetadata.fileMetadataId. Current + // Imagine image-edit requests require this exact identifier in inputAssets. + MetadataID string + URI string } type remoteImageTarget struct { diff --git a/backend/internal/infra/provider/web/image.go b/backend/internal/infra/provider/web/image.go index 909f433b..81632953 100644 --- a/backend/internal/infra/provider/web/image.go +++ b/backend/internal/infra/provider/web/image.go @@ -846,27 +846,19 @@ func (a *Adapter) editImageAttempt(ctx context.Context, request provider.ImageEd } images = append(images, image) } - refs := make([]string, 0, len(images)) - parentID := "" + assets := make([]string, 0, len(images)) for _, image := range images { uploaded, uploadErr := a.uploadFileV2Direct(ctx, cfg, lease, token, image, cfg.BaseURL+"/imagine", imagineSelfUploadSource, "image_edit_upload") if uploadErr != nil { return nil, uploadErr } - if uploaded.URI == "" { - return nil, fmt.Errorf("上传图片成功但上游未返回 fileUri") - } - refs = append(refs, uploaded.URI) - postID, postErr := a.createMediaPost(ctx, cfg, lease, token, "MEDIA_POST_TYPE_IMAGE", uploaded.URI, "", "image_edit_media_post") - if postErr != nil { - return nil, postErr - } - if parentID == "" { - parentID = postID + if uploaded.MetadataID == "" { + return nil, fmt.Errorf("上传图片成功但上游未返回 fileMetadataId") } + assets = append(assets, uploaded.MetadataID) } - payload := buildImageEditPayload(request.Prompt, refs, parentID, ratio) - response, err := a.postJSONWithReferer(ctx, cfg, lease, token, cfg.BaseURL+"/rest/app-chat/conversations/new", payload, time.Duration(cfg.ImageTimeoutSeconds)*time.Second, cfg.BaseURL+"/imagine/post/"+parentID) + payload := buildImageEditPayload(request.Prompt, assets, ratio) + response, err := a.postJSONWithReferer(ctx, cfg, lease, token, cfg.BaseURL+"/rest/app-chat/conversations/new", payload, time.Duration(cfg.ImageTimeoutSeconds)*time.Second, cfg.BaseURL+"/imagine") if err != nil { return nil, err } @@ -908,20 +900,18 @@ func (a *Adapter) editImageAttempt(ctx context.Context, request provider.ImageEd return result, err } -func buildImageEditPayload(prompt string, refs []string, parentID, aspectRatio string) map[string]any { - config := map[string]any{"imageReferences": refs, "parentPostId": parentID} +func buildImageEditPayload(prompt string, assets []string, aspectRatio string) map[string]any { + imageToImage := map[string]any{ + "prompt": prompt, + "inputAssets": assets, + } if aspectRatio != "" { - config["aspectRatio"] = aspectRatio + imageToImage["aspectRatio"] = aspectRatio } return map[string]any{ - "temporary": true, "modelName": "imagine-image-edit", "message": prompt, - "enableImageGeneration": true, "returnImageBytes": false, "returnRawGrokInXaiRequest": false, - "enableImageStreaming": true, "imageGenerationCount": 2, "forceConcise": false, - "enableSideBySide": true, "sendFinalMetadata": true, "isReasoning": false, - "disableTextFollowUps": true, "disableMemory": false, "forceSideBySide": false, - "responseMetadata": map[string]any{"modelConfigOverride": map[string]any{"modelMap": map[string]any{ - "imageEditModel": "imagine", "imageEditModelConfig": config, - }}}, + "modelName": "imagine-image-edit", "message": prompt, + "enableImageStreaming": true, "enableSideBySide": true, "sendFinalMetadata": true, + "mediaGenInput": map[string]any{"imageToImage": imageToImage}, } } @@ -1356,23 +1346,25 @@ func decodeDirectFileUploadResponse(source io.Reader) (uploadedFile, error) { if directFileUploadTerminalError(value.TerminalError) { return uploadedFile{}, errors.New("V2 上传文件被上游拒绝") } - if value.FileMetadata.ID == "" { - value.FileMetadata.ID = value.FileMetadata.FileID + metadataID := strings.TrimSpace(value.FileMetadata.ID) + fileID := metadataID + if fileID == "" { + fileID = strings.TrimSpace(value.FileMetadata.FileID) } - if value.FileMetadata.ID == "" { + if fileID == "" { // Some successful uploads complete asynchronously and only expose the // upload task ID. Gateway accepts it as the file reference; prefer the // browser's fileMetadataId whenever it is already available. - value.FileMetadata.ID = strings.TrimSpace(value.UploadID) + fileID = strings.TrimSpace(value.UploadID) } fileURI := "" if value.FileMetadata.FileURI != "" { fileURI = absoluteAssetURL(value.FileMetadata.FileURI) } - if value.FileMetadata.ID == "" && fileURI == "" { + if fileID == "" && fileURI == "" { return uploadedFile{}, fmt.Errorf("V2 上传文件成功但上游未返回完整文件标识") } - return uploadedFile{ID: value.FileMetadata.ID, URI: fileURI}, nil + return uploadedFile{ID: fileID, MetadataID: metadataID, URI: fileURI}, nil } func directFileUploadTerminalError(raw json.RawMessage) bool { diff --git a/backend/internal/infra/provider/web/media_clearance_retry_test.go b/backend/internal/infra/provider/web/media_clearance_retry_test.go index 1a1486b4..6b374355 100644 --- a/backend/internal/infra/provider/web/media_clearance_retry_test.go +++ b/backend/internal/infra/provider/web/media_clearance_retry_test.go @@ -290,11 +290,10 @@ func TestLiteChallengeRetryExhaustionReturnsNormalizedJSON(t *testing.T) { } func TestImageEditReplaysWholeFlowWithRefreshedClearance(t *testing.T) { - for _, challengeStage := range []string{"upload", "media_post", "generation"} { + for _, challengeStage := range []string{"upload", "generation"} { t.Run(challengeStage, func(t *testing.T) { var solverCalls atomic.Int32 var uploadCalls atomic.Int32 - var mediaPostCalls atomic.Int32 var generationCalls atomic.Int32 server := fhttptest.NewServer(fhttp.HandlerFunc(func(writer fhttp.ResponseWriter, request *fhttp.Request) { switch request.URL.Path { @@ -311,16 +310,6 @@ func TestImageEditReplaysWholeFlowWithRefreshedClearance(t *testing.T) { writer.Header().Set("Content-Type", "application/json") _, _ = writer.Write([]byte(`{"uploadId":"upload-1","fileMetadata":{"fileMetadataId":"file-1","fileUri":"users/test/reference/content"}}`)) return - case "/rest/media/post/create": - call := mediaPostCalls.Add(1) - assertTestClearanceCookie(t, request, solverCalls.Load()) - if challengeStage == "media_post" && call == 1 { - writeTestChallenge(writer) - return - } - writer.Header().Set("Content-Type", "application/json") - _, _ = writer.Write([]byte(`{"post":{"id":"post-1"}}`)) - return case "/rest/app-chat/conversations/new": call := generationCalls.Add(1) assertTestClearanceCookie(t, request, solverCalls.Load()) @@ -340,12 +329,13 @@ func TestImageEditReplaysWholeFlowWithRefreshedClearance(t *testing.T) { adapter, credential := testMediaAdapter(t, server.URL) enableTestClearance(adapter, server.URL) response, err := adapter.EditImage(context.Background(), provider.ImageEditRequest{ - Credential: credential, - ImageURLs: []string{"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="}, - Prompt: "turn it blue", - Count: 1, - Resolution: "1k", - Streaming: true, + Credential: credential, + ImageURLs: []string{"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="}, + Prompt: "turn it blue", + Count: 1, + Resolution: "1k", + AspectRatio: "9:16", + Streaming: true, }) if err != nil { t.Fatal(err) @@ -355,17 +345,13 @@ func TestImageEditReplaysWholeFlowWithRefreshedClearance(t *testing.T) { } _ = response.Body.Close() - wantUpload, wantMediaPost, wantGeneration := int32(2), int32(1), int32(1) - switch challengeStage { - case "media_post": - wantMediaPost = 2 - case "generation": - wantMediaPost = 2 + wantGeneration := int32(1) + if challengeStage == "generation" { wantGeneration = 2 } - if solverCalls.Load() != 2 || uploadCalls.Load() != wantUpload || mediaPostCalls.Load() != wantMediaPost || generationCalls.Load() != wantGeneration { - t.Fatalf("solver/upload/post/generation=%d/%d/%d/%d, want 2/%d/%d/%d", - solverCalls.Load(), uploadCalls.Load(), mediaPostCalls.Load(), generationCalls.Load(), wantUpload, wantMediaPost, wantGeneration) + if solverCalls.Load() != 2 || uploadCalls.Load() != 2 || generationCalls.Load() != wantGeneration { + t.Fatalf("solver/upload/generation=%d/%d/%d, want 2/2/%d", + solverCalls.Load(), uploadCalls.Load(), generationCalls.Load(), wantGeneration) } }) } @@ -376,7 +362,6 @@ func TestImageEditStructuredForbiddenDoesNotRetryOrRefresh(t *testing.T) { t.Run(rejectedStage, func(t *testing.T) { var solverCalls atomic.Int32 var uploadCalls atomic.Int32 - var mediaPostCalls atomic.Int32 var generationCalls atomic.Int32 server := fhttptest.NewServer(fhttp.HandlerFunc(func(writer fhttp.ResponseWriter, request *fhttp.Request) { switch request.URL.Path { @@ -391,11 +376,6 @@ func TestImageEditStructuredForbiddenDoesNotRetryOrRefresh(t *testing.T) { } writer.Header().Set("Content-Type", "application/json") _, _ = writer.Write([]byte(`{"uploadId":"upload-1","fileMetadata":{"fileMetadataId":"file-1","fileUri":"users/test/reference/content"}}`)) - case "/rest/media/post/create": - mediaPostCalls.Add(1) - assertTestClearanceCookie(t, request, solverCalls.Load()) - writer.Header().Set("Content-Type", "application/json") - _, _ = writer.Write([]byte(`{"post":{"id":"post-1"}}`)) case "/rest/app-chat/conversations/new": generationCalls.Add(1) assertTestClearanceCookie(t, request, solverCalls.Load()) @@ -433,11 +413,11 @@ func TestImageEditStructuredForbiddenDoesNotRetryOrRefresh(t *testing.T) { t.Fatalf("upload calls=%d, want 2", uploadCalls.Load()) } if rejectedStage == "upload" { - if mediaPostCalls.Load() != 0 || generationCalls.Load() != 0 { - t.Fatalf("post/generation calls=%d/%d, want 0/0", mediaPostCalls.Load(), generationCalls.Load()) + if generationCalls.Load() != 0 { + t.Fatalf("generation calls=%d, want 0", generationCalls.Load()) } - } else if mediaPostCalls.Load() != 2 || generationCalls.Load() != 2 { - t.Fatalf("post/generation calls=%d/%d, want 2/2", mediaPostCalls.Load(), generationCalls.Load()) + } else if generationCalls.Load() != 2 { + t.Fatalf("generation calls=%d, want 2", generationCalls.Load()) } }) } diff --git a/backend/internal/infra/provider/web/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index 87b36468..8c403964 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -869,25 +869,34 @@ func TestImageEditRejectsUnsupportedCountAndStreamingOptions(t *testing.T) { } } -func TestBuildImageEditPayloadMatchesCapturedAspectRatioShape(t *testing.T) { - payload := buildImageEditPayload("改成兔子", []string{"https://assets.grok.com/users/test/reference/content"}, "post_1", "1:1") - metadata, _ := payload["responseMetadata"].(map[string]any) - override, _ := metadata["modelConfigOverride"].(map[string]any) - modelMap, _ := override["modelMap"].(map[string]any) - config, _ := modelMap["imageEditModelConfig"].(map[string]any) - if payload["modelName"] != "imagine-image-edit" || payload["imageGenerationCount"] != 2 || modelMap["imageEditModel"] != "imagine" { +func TestBuildImageEditPayloadMatchesCapturedMediaGenInputShape(t *testing.T) { + assets := []string{"metadata-1", "metadata-2"} + payload := buildImageEditPayload("改成兔子", assets, "1:1") + mediaGenInput, ok := payload["mediaGenInput"].(map[string]any) + if !ok { + t.Fatalf("mediaGenInput = %#v", payload["mediaGenInput"]) + } + imageToImage, ok := mediaGenInput["imageToImage"].(map[string]any) + if !ok { + t.Fatalf("imageToImage = %#v", mediaGenInput["imageToImage"]) + } + if len(payload) != 6 || payload["modelName"] != "imagine-image-edit" || payload["message"] != "改成兔子" || + payload["enableImageStreaming"] != true || payload["enableSideBySide"] != true || payload["sendFinalMetadata"] != true { t.Fatalf("payload = %#v", payload) } - if config["aspectRatio"] != "1:1" || config["parentPostId"] != "post_1" || !slices.Equal(config["imageReferences"].([]string), []string{"https://assets.grok.com/users/test/reference/content"}) { - t.Fatalf("image edit config = %#v", config) + if imageToImage["prompt"] != "改成兔子" || imageToImage["aspectRatio"] != "1:1" || !slices.Equal(imageToImage["inputAssets"].([]string), assets) { + t.Fatalf("imageToImage = %#v", imageToImage) } - withoutRatio := buildImageEditPayload("edit", []string{"reference"}, "post_2", "") - metadata = withoutRatio["responseMetadata"].(map[string]any) - override = metadata["modelConfigOverride"].(map[string]any) - modelMap = override["modelMap"].(map[string]any) - config = modelMap["imageEditModelConfig"].(map[string]any) - if _, exists := config["aspectRatio"]; exists { - t.Fatalf("empty aspect ratio leaked into payload: %#v", config) + for _, field := range []string{"temporary", "enableImageGeneration", "imageGenerationCount", "config", "responseMetadata", "kind", "parentPostId"} { + if _, exists := payload[field]; exists { + t.Fatalf("legacy field %q leaked into payload: %#v", field, payload) + } + } + withoutRatio := buildImageEditPayload("edit", []string{"metadata-1"}, "") + mediaGenInput = withoutRatio["mediaGenInput"].(map[string]any) + imageToImage = mediaGenInput["imageToImage"].(map[string]any) + if _, exists := imageToImage["aspectRatio"]; exists { + t.Fatalf("empty aspect ratio leaked into payload: %#v", imageToImage) } } @@ -1139,13 +1148,17 @@ func TestDecodeDirectFileUploadResponse(t *testing.T) { "uploadId":"upload-1", "fileMetadata":{"fileMetadataId":"metadata-1","fileUri":"users/test/reference/content"} }`)) - if err != nil || uploaded.ID != "metadata-1" || uploaded.URI != "https://assets.grok.com/users/test/reference/content" { + if err != nil || uploaded.ID != "metadata-1" || uploaded.MetadataID != "metadata-1" || uploaded.URI != "https://assets.grok.com/users/test/reference/content" { t.Fatalf("uploaded=%#v err=%v", uploaded, err) } uploaded, err = decodeDirectFileUploadResponse(strings.NewReader(`{"uploadId":"upload-1","terminalError":{}}`)) - if err != nil || uploaded.ID != "upload-1" || uploaded.URI != "" { + if err != nil || uploaded.ID != "upload-1" || uploaded.MetadataID != "" || uploaded.URI != "" { t.Fatalf("uploadId-only response: uploaded=%#v err=%v", uploaded, err) } + uploaded, err = decodeDirectFileUploadResponse(strings.NewReader(`{"fileMetadata":{"fileId":"file-1"}}`)) + if err != nil || uploaded.ID != "file-1" || uploaded.MetadataID != "" { + t.Fatalf("fileId-only response: uploaded=%#v err=%v", uploaded, err) + } if _, err := decodeDirectFileUploadResponse(strings.NewReader(`{"uploadId":"upload-1","terminalError":{"message":"rejected"}}`)); err == nil { t.Fatal("terminal upload error was accepted") } diff --git a/backend/internal/transport/http/audit/handler.go b/backend/internal/transport/http/audit/handler.go index bc3dbf6b..580c75b5 100644 --- a/backend/internal/transport/http/audit/handler.go +++ b/backend/internal/transport/http/audit/handler.go @@ -535,6 +535,9 @@ func auditOutputTokensPerSecond(value auditdomain.Record) *float64 { if !value.Streaming || value.StatusCode < 200 || value.StatusCode >= 300 || value.ErrorCode != "" || value.FirstTokenMS == nil || value.OutputTokens <= 0 || value.DurationMS <= *value.FirstTokenMS { return nil } - throughput := float64(value.OutputTokens) * 1000 / float64(value.DurationMS-*value.FirstTokenMS) + throughput := auditdomain.OutputTokensPerSecond(value.OutputTokens, value.ReasoningTokens, *value.FirstTokenMS, value.DurationMS) + if throughput <= 0 { + return nil + } return &throughput } diff --git a/backend/internal/transport/http/audit/handler_test.go b/backend/internal/transport/http/audit/handler_test.go index 857b8af7..d5a270dc 100644 --- a/backend/internal/transport/http/audit/handler_test.go +++ b/backend/internal/transport/http/audit/handler_test.go @@ -93,6 +93,17 @@ func TestAuditResponseDerivesOutputThroughput(t *testing.T) { if unmeasured.OutputTokensPerSecond != nil { t.Fatalf("unmeasured throughput = %v", *unmeasured.OutputTokensPerSecond) } + + lateFirst := int64(19763) + late := newAuditResponse(auditdomain.Record{StatusCode: http.StatusOK, Streaming: true, FirstTokenMS: &lateFirst, DurationMS: 19827, OutputTokens: 1511, ReasoningTokens: 1400}) + if late.OutputTokensPerSecond == nil || *late.OutputTokensPerSecond != float64(1511)*1000/19827 { + t.Fatalf("late first-token throughput = %#v", late) + } + burstFirst := int64(10000) + burst := newAuditResponse(auditdomain.Record{StatusCode: http.StatusOK, Streaming: true, FirstTokenMS: &burstFirst, DurationMS: 10100, OutputTokens: 2000}) + if burst.OutputTokensPerSecond == nil || *burst.OutputTokensPerSecond != 20000 { + t.Fatalf("no-reasoning burst throughput = %#v", burst) + } } func TestQualityGuardAuditListMarksOwnProbeWithoutExposingKeyIdentity(t *testing.T) { diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index 25a93754..552b6943 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -1287,27 +1287,45 @@ type responseMetadata struct { func copyStream(writer gin.ResponseWriter, source io.Reader, protocol streamProtocol, onFirstToken func()) (responseMetadata, error) { inspector := &responseInspector{protocol: protocol, onFirstToken: onFirstToken} + markerFilter := internalSSEMarkerFilter{enabled: protocol == streamProtocolChat} buffer := make([]byte, responseCopyBufferBytes) transferred := 0 for { n, readErr := source.Read(buffer) if n > 0 { - if transferred+n > maxStreamResponseTransferBytes { - return inspector.Metadata(), fmt.Errorf("%w: 流式响应超过 %d MiB", errResponseTransferLimit, maxStreamResponseTransferBytes>>20) - } chunk := buffer[:n] inspector.Inspect(chunk) - if err := setResponseWriteDeadline(writer); err != nil { - return inspector.Metadata(), err + chunk = markerFilter.Filter(chunk, false) + if transferred+len(chunk) > maxStreamResponseTransferBytes { + return inspector.Metadata(), fmt.Errorf("%w: 流式响应超过 %d MiB", errResponseTransferLimit, maxStreamResponseTransferBytes>>20) } - if _, err := writer.Write(chunk); err != nil { - return inspector.Metadata(), err + if len(chunk) > 0 { + if err := setResponseWriteDeadline(writer); err != nil { + return inspector.Metadata(), err + } + if _, err := writer.Write(chunk); err != nil { + return inspector.Metadata(), err + } + writer.Flush() + transferred += len(chunk) } - writer.Flush() inspector.markFirstTokenForwarded() - transferred += n } if readErr != nil { + if tail := markerFilter.Filter(nil, true); len(tail) > 0 { + 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.markFirstTokenForwarded() if errors.Is(readErr, io.EOF) { inspector.Finish() return inspector.Metadata(), inspector.TerminalError() @@ -1320,6 +1338,43 @@ func copyStream(writer gin.ResponseWriter, source io.Reader, protocol streamProt } } +type internalSSEMarkerFilter struct { + enabled bool + pending []byte +} + +func (f *internalSSEMarkerFilter) Filter(chunk []byte, final bool) []byte { + if !f.enabled { + return chunk + } + marker := []byte(reasoningStartSSEComment + "\n\n") + f.pending = append(f.pending, chunk...) + result := make([]byte, 0, len(f.pending)) + for { + if index := bytes.Index(f.pending, marker); index >= 0 { + result = append(result, f.pending[:index]...) + f.pending = f.pending[index+len(marker):] + continue + } + if final { + result = append(result, f.pending...) + f.pending = nil + return result + } + keep := 0 + limit := min(len(f.pending), len(marker)-1) + for size := limit; size > 0; size-- { + if bytes.Equal(f.pending[len(f.pending)-size:], marker[:size]) { + keep = size + break + } + } + result = append(result, f.pending[:len(f.pending)-keep]...) + f.pending = f.pending[len(f.pending)-keep:] + return result + } +} + func copyJSON(writer gin.ResponseWriter, source io.Reader, protocol streamProtocol) (responseMetadata, error) { buffer := make([]byte, responseCopyBufferBytes) metadataBody := make([]byte, 0, responseCopyBufferBytes) @@ -1371,6 +1426,8 @@ type responseInspector struct { terminalFailure bool } +const reasoningStartSSEComment = ": grok2api-reasoning-start" + func (i *responseInspector) Inspect(chunk []byte) { i.pending = append(i.pending, chunk...) for { @@ -1383,6 +1440,10 @@ func (i *responseInspector) Inspect(chunk []byte) { } line := bytes.TrimSpace(i.pending[:index]) i.pending = i.pending[index+1:] + if i.protocol == streamProtocolChat && bytes.Equal(line, []byte(reasoningStartSSEComment)) { + i.observeReasoningStart() + continue + } if bytes.HasPrefix(line, []byte("data:")) { value := bytes.TrimSpace(bytes.TrimPrefix(line, []byte("data:"))) i.observeFirstToken(value) @@ -1410,6 +1471,13 @@ func (i *responseInspector) Inspect(chunk []byte) { } } +func (i *responseInspector) observeReasoningStart() { + if i.firstTokenSeen || i.firstTokenReady || i.onFirstToken == nil { + return + } + i.firstTokenReady = true +} + func (i *responseInspector) observeFirstToken(data []byte) { if i.firstTokenSeen || i.firstTokenReady || i.onFirstToken == nil || len(data) == 0 || bytes.Equal(data, []byte("[DONE]")) { return @@ -1436,13 +1504,23 @@ func containsGeneratedDelta(data []byte, protocol streamProtocol) bool { var event struct { Type string `json:"type"` Delta string `json:"delta"` + Item struct { + ID string `json:"id"` + Type string `json:"type"` + } `json:"item"` } - if json.Unmarshal(data, &event) != nil || event.Delta == "" { + if json.Unmarshal(data, &event) != nil { return false } switch event.Type { case "response.output_text.delta", "response.reasoning_summary_text.delta", "response.reasoning_text.delta", "response.refusal.delta", "response.function_call_arguments.delta", "response.custom_tool_call_input.delta": - return true + return event.Delta != "" + case "response.output_item.added": + // Native Responses can stream an identified reasoning item with no + // text delta when only encrypted_content is requested. That item is + // still generation start; waiting for output_text kicks thinking + // time out of the TPS denominator. + return event.Item.Type == "reasoning" && event.Item.ID != "" } case streamProtocolChat: var event struct { @@ -1451,6 +1529,7 @@ func containsGeneratedDelta(data []byte, protocol streamProtocol) bool { Content string `json:"content"` Reasoning string `json:"reasoning"` ReasoningContent string `json:"reasoning_content"` + ThinkingContent string `json:"thinking_content"` Refusal string `json:"refusal"` ToolCalls []struct { Function struct { @@ -1465,7 +1544,7 @@ func containsGeneratedDelta(data []byte, protocol streamProtocol) bool { } for _, choice := range event.Choices { delta := choice.Delta - if delta.Content != "" || delta.Reasoning != "" || delta.ReasoningContent != "" || delta.Refusal != "" { + if delta.Content != "" || delta.Reasoning != "" || delta.ReasoningContent != "" || delta.ThinkingContent != "" || delta.Refusal != "" { return true } for _, call := range delta.ToolCalls { @@ -1476,7 +1555,10 @@ func containsGeneratedDelta(data []byte, protocol streamProtocol) bool { } case streamProtocolAnthropic: var event struct { - Type string `json:"type"` + Type string `json:"type"` + ContentBlock struct { + Type string `json:"type"` + } `json:"content_block"` Delta struct { Type string `json:"type"` Text string `json:"text"` @@ -1484,7 +1566,13 @@ func containsGeneratedDelta(data []byte, protocol streamProtocol) bool { PartialJSON string `json:"partial_json"` } `json:"delta"` } - if json.Unmarshal(data, &event) != nil || event.Type != "content_block_delta" { + if json.Unmarshal(data, &event) != nil { + return false + } + if event.Type == "content_block_start" { + return event.ContentBlock.Type == "thinking" + } + if event.Type != "content_block_delta" { return false } switch event.Delta.Type { diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go index d34f39b2..3d63c2a5 100644 --- a/backend/internal/transport/http/inference/handler_test.go +++ b/backend/internal/transport/http/inference/handler_test.go @@ -21,6 +21,19 @@ import ( "github.com/gin-gonic/gin" ) +type chunkErrorReader struct { + data []byte + done bool +} + +func (r *chunkErrorReader) Read(target []byte) (int, error) { + if r.done { + return 0, io.EOF + } + r.done = true + return copy(target, r.data), errors.New("upstream cut") +} + func TestVideoGenerationUsesOfficialXAIEndpointsAndFields(t *testing.T) { gin.SetMode(gin.TestMode) router := gin.New() @@ -835,16 +848,31 @@ func TestStreamInspectorMarksFirstGeneratedTokenOnce(t *testing.T) { prelude: `data: {"type":"response.custom_tool_call_input.delta","output_index":1,"item_id":"ctc_1","delta":""}` + "\n\n", delta: `data: {"type":"response.custom_tool_call_input.delta","output_index":1,"item_id":"ctc_1","delta":"{}"}` + "\n\n", }, + { + name: "responses encrypted reasoning item", protocol: streamProtocolResponses, + prelude: `data: {"type":"response.created","response":{"id":"resp_1"}}` + "\n\n", + delta: `data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning","status":"in_progress"}}` + "\n\n", + }, { name: "chat reasoning", protocol: streamProtocolChat, prelude: `data: {"choices":[{"delta":{"role":"assistant"}}]}` + "\n\n", delta: `data: {"choices":[{"delta":{"reasoning_content":"thinking"}}]}` + "\n\n", }, + { + name: "chat thinking_content", protocol: streamProtocolChat, + prelude: `data: {"choices":[{"delta":{"role":"assistant"}}]}` + "\n\n", + delta: `data: {"choices":[{"delta":{"thinking_content":"thinking"}}]}` + "\n\n", + }, { name: "anthropic tool input", protocol: streamProtocolAnthropic, prelude: `data: {"type":"message_start","message":{"id":"msg_1"}}` + "\n\n", delta: `data: {"type":"content_block_delta","delta":{"type":"input_json_delta","partial_json":"{\"q\":"}}` + "\n\n", }, + { + name: "anthropic thinking start", protocol: streamProtocolAnthropic, + prelude: `data: {"type":"message_start","message":{"id":"msg_1"}}` + "\n\n", + delta: `data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}` + "\n\n", + }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -878,6 +906,72 @@ func TestStreamInspectorDoesNotMarkImageEvents(t *testing.T) { } } +func TestStreamInspectorMarksChatReasoningComment(t *testing.T) { + marked := 0 + inspector := &responseInspector{protocol: streamProtocolChat, onFirstToken: func() { marked++ }} + inspector.Inspect([]byte(": grok2api-reasoning-start\n\n")) + if marked != 0 { + t.Fatalf("reasoning comment marked first token before forwarding %d times", marked) + } + inspector.markFirstTokenForwarded() + if marked != 1 { + t.Fatalf("reasoning comment marked first token %d times", marked) + } +} + +func TestInternalSSEMarkerFilterAcrossChunkBoundaries(t *testing.T) { + marker := reasoningStartSSEComment + "\n\n" + input := []byte("data: before\n\n" + marker + "data: after\n\n") + want := "data: before\n\ndata: after\n\n" + for split := 0; split <= len(input); split++ { + filter := internalSSEMarkerFilter{enabled: true} + var output []byte + output = append(output, filter.Filter(input[:split], false)...) + output = append(output, filter.Filter(input[split:], false)...) + output = append(output, filter.Filter(nil, true)...) + if string(output) != want { + t.Fatalf("split %d output = %q, want %q", split, output, want) + } + } +} + +func TestCopyStreamConsumesInternalReasoningMarker(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + context, _ := gin.CreateTestContext(recorder) + body := `data: {"choices":[{"delta":{"role":"assistant"}}]}` + "\n\n" + + ": grok2api-reasoning-start\n\n" + + `data: {"choices":[{"delta":{"content":"hello"}}]}` + "\n\n" + + "data: [DONE]\n\n" + marked := 0 + if _, err := copyStream(context.Writer, strings.NewReader(body), streamProtocolChat, func() { marked++ }); err != nil { + t.Fatal(err) + } + if marked != 1 { + t.Fatalf("first token marked %d times", marked) + } + if strings.Contains(recorder.Body.String(), "grok2api-reasoning-start") { + t.Fatalf("internal marker leaked to client: %q", recorder.Body.String()) + } + if !strings.Contains(recorder.Body.String(), `"content":"hello"`) { + t.Fatalf("visible Chat delta missing: %q", recorder.Body.String()) + } +} + +func TestCopyStreamPreservesBufferedTailOnReadError(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + context, _ := gin.CreateTestContext(recorder) + body := []byte(`data: {"choices":[{"delta":{"content":"partial"}}]}` + "\n\n:") + _, err := copyStream(context.Writer, &chunkErrorReader{data: body}, streamProtocolChat, nil) + 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) + } +} + func TestCopyStreamMarksFirstTokenAfterFlush(t *testing.T) { gin.SetMode(gin.TestMode) recorder := httptest.NewRecorder() diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index 75b08851..7a2f9c76 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -473,7 +473,7 @@ const resources = { title: "质量守护", description: "监测 Grok 出口质量并在异常时自动隔离节点。", overview: "质量守护概览", serviceStatus: "守护服务", running: "运行正常", stale: "状态滞后", mode: "检测模式", availableNodes: "已启用节点", quarantinedNodes: "已隔离节点", modes: { active: "主动检测", passive: "被动审计", hybrid: "混合模式" }, - nodes: "节点质量", nodesHelp: "速度与 grok2api 面板同口径:输出 Token 包含推理 Token。完整用户请求出现速度异常后会立即隔离,并在隔离期结束后使用受控探针复测。", updatedAt: "状态更新于 {{time}}", + nodes: "节点质量", nodesHelp: "速度与 grok2api 面板同口径:输出 Token 包含推理 Token。首字后窗口短于首字等待且不足 1 秒时改用全程,避免加密思考被挤进最后几十毫秒。完整用户请求出现速度异常后会立即隔离,并在隔离期结束后使用受控探针复测。", updatedAt: "状态更新于 {{time}}", node: "节点", state: "状态", outputTPS: "面板输出速度", firstToken: "首字延迟", source: "数据来源", strikes: "打击计数", lastObserved: "最近观测", test: "检测", sources: { active: "主动探针", passive: "请求审计" }, quarantined: "已隔离", fixedFallback: "固定回退(受保护)", suspect: "可疑", healthy: "正常", pending: "待观测", probeFailed: "检测失败", events: "最近事件", noEvents: "暂无异常或恢复事件", eventTypes: { node_quarantined: "节点已隔离", node_restored: "节点已恢复", node_rotated: "节点已更换 IP", passive_audit_anomaly: "检测到异常请求" }, @@ -1513,7 +1513,7 @@ const resources = { media: { images: { title: "Gallery", description: "Browse generated image assets", search: "Search ID, type, or hash", empty: "No images", noMatches: "No matching images", totalImages: "Total images", totalBytes: "Storage", pageSummary: "Showing {{count}} / {{total}}", openImage: "Open image {{id}}", deleteTitle: "Delete {{count}} selected images?", deleteDescription: "The image files and gallery records will be permanently removed, and existing image links will stop working. This cannot be undone.", deleted: "Deleted {{count}} images" }, videos: { title: "Video Gallery", description: "View video generation job records", search: "Search prompt or ID", empty: "No video jobs", statusFilter: "Status filter", totalJobs: "Total jobs", queued: "Queued", inProgress: "In progress", completed: "Completed", failed: "Failed", prompt: "Prompt", model: "Model", status: "Status", progress: "Progress", statusProgress: "Status / progress", spec: "Spec", owner: "Owner", createdAt: "Created", completedAt: "Completed", time: "Time", createdShort: "Created", completedShort: "Done", preview: "Preview video", previewTitle: "Video preview", previewUnavailable: "Local video unavailable", deleteTitle: "Delete {{count}} video records?", deleteDescription: "The task records and their local videos will be permanently removed, and existing video links will stop working. This cannot be undone.", deleted: "Deleted {{count}} video records", seconds: "{{count}} sec", pageSummary: "Showing {{count}} / {{total}}" }, videoStatus: { queued: "Queued", in_progress: "In progress", completed: "Completed", failed: "Failed" } }, auth: { title: "Admin sign in", productTitle: "Lightweight API gateway", subtitle: "Manage upstream accounts, model routes, and client access.", username: "Username", password: "Password", usernameRequired: "Enter your username", passwordRequired: "Enter your password", signIn: "Sign in", signingIn: "Signing in", signOut: "Sign out", changePassword: "Change password", currentPassword: "Current password", newPassword: "New password", passwordUpdated: "Password updated. Sign in again.", sessionUnavailable: "Unable to restore the session", sessionUnavailableDescription: "The service may be temporarily unavailable. Your session was not cleared; please retry shortly.", retrySession: "Retry" }, shell: { appearance: "Appearance", dark: "Dark", light: "Light", system: "System", language: "Language", navigation: "Navigation", openNavigation: "Open navigation" }, - qualityGuard: { title: "Quality guard", description: "Monitor Grok egress quality and quarantine anomalous nodes automatically.", overview: "Quality guard overview", serviceStatus: "Guard service", running: "Running", stale: "Status stale", mode: "Detection mode", availableNodes: "Enabled nodes", quarantinedNodes: "Quarantined", modes: { active: "Active probes", passive: "Passive audits", hybrid: "Hybrid" }, nodes: "Node quality", nodesHelp: "Speed matches the grok2api panel: output tokens include reasoning tokens. A completed user request with anomalous throughput is isolated immediately, then verified with a controlled probe after the hold.", updatedAt: "Updated {{time}}", node: "Node", state: "State", outputTPS: "Panel output speed", firstToken: "First token", source: "Source", strikes: "Strikes", lastObserved: "Last observed", test: "Test", sources: { active: "Active probe", passive: "Request audit" }, quarantined: "Quarantined", fixedFallback: "Fixed fallback (protected)", suspect: "Suspect", healthy: "Healthy", pending: "Pending", probeFailed: "Probe failed", events: "Recent events", noEvents: "No anomaly or recovery events", eventTypes: { node_quarantined: "Node quarantined", node_restored: "Node restored", node_rotated: "Node IP rotated", passive_audit_anomaly: "Anomalous request detected" }, statistics: "Automatic detection statistics", statisticsSince: "Accumulated since {{time}}. Manual tests are excluded.", statisticsChecks: "Valid checks", statisticsChecksHelp: "Active probes and valid passive audits", statisticsActive: "Active probes", statisticsActiveDetail: "Healthy {{healthy}}, errors {{errors}}", statisticsPassive: "Passive audits", statisticsPassiveDetail: "Healthy {{healthy}}, from real requests", statisticsTokens: "Active output tokens", statisticsTokensHelp: "Includes reasoning tokens; not proxy traffic", statisticsAnomalies: "Anomaly hits", statisticsAnomalyDetail: "Soft {{soft}}, hard {{hard}}", statisticsQuarantines: "Quarantines applied", statisticsActionDetail: "Restored {{restored}}, protected {{suppressed}}", reasons: { unknown: "No reason recorded", hard_tps: "Hard threshold exceeded", soft_tps: "Soft threshold exceeded", buffered_burst: "Short-window output burst; retesting the same IP", missing_thinking: "Missing thinking tokens", passive_hard_tps: "Request exceeded hard threshold", passive_soft_tps: "Request exceeded soft threshold", quality_probe_healthy: "Model quality probe recovered", expected_marker_missing: "Expected marker missing", insufficient_output_tokens: "Too few output tokens", insufficient_visible_tokens: "Too few visible tokens", insufficient_generation_window: "Generation window too short", probe_errors: "Repeated probe errors", probe_no_account: "No schedulable probe account; retry deferred", recovery_probe_error: "Recovery probe failed", rotation_error: "IP rotation failed" }, policy: "Current policy", editPolicy: "Edit policy", editPolicyTitle: "Edit quality guard policy", editPolicyDescription: "The guard hot-reloads saved changes without a service restart.", restoreDefaults: "Restore defaults", policySaved: "Policy saved and queued for hot reload", invalidPolicyValue: "Value is outside the allowed range", softThresholdMustBeLower: "The soft threshold must be lower than the hard threshold", activeIntervalSeconds: "Active interval (seconds)", passiveIntervalSeconds: "Passive interval (seconds)", consecutiveSoft: "Consecutive active soft strikes", consecutiveErrors: "Consecutive probe errors", quarantineSeconds: "Quarantine (seconds)", softThreshold: "Soft threshold", hardThreshold: "Hard threshold", activeInterval: "Active interval", passiveInterval: "Audit interval", quarantineDuration: "Quarantine", minimumNodes: "Minimum nodes", unavailable: "Quality guard is not connected", unavailableHelp: "Enable qualityGuard in config.yaml and start the quality-guard Compose profile to display live status here.", testing: "Testing node quality", testComplete: "Test complete: {{speed}}", testFailed: "Quality test is temporarily unavailable. Try again shortly.", refreshNodes: "Refresh nodes", nodeEnabled: "Node enabled", nodeDisabled: "Node disabled", nodesEnabled: "Selected nodes enabled", nodesDisabled: "Selected nodes disabled", enableNode: "Enable node {{name}}", disableNode: "Disable node {{name}}", nodeEditorDescription: "Manage Grok Build egress used by the quality guard. Proxy URLs are write-only; leave the field blank while editing to keep the current value.", nodeCapacityHelp: "Maximum number of bound accounts; 0 means unlimited.", deleteNodeTitle: "Delete proxy node?", deleteNodeDescription: "Node “{{name}}” will be permanently deleted. This action cannot be undone.", deleteNodesTitle: "Delete {{count}} selected nodes?", deleteNodesDescription: "The selected proxy nodes will be permanently deleted. This action cannot be undone.", + qualityGuard: { title: "Quality guard", description: "Monitor Grok egress quality and quarantine anomalous nodes automatically.", overview: "Quality guard overview", serviceStatus: "Guard service", running: "Running", stale: "Status stale", mode: "Detection mode", availableNodes: "Enabled nodes", quarantinedNodes: "Quarantined", modes: { active: "Active probes", passive: "Passive audits", hybrid: "Hybrid" }, nodes: "Node quality", nodesHelp: "Speed matches the grok2api panel: output tokens include reasoning tokens. A tail shorter than the first-token wait and under 1s uses the full request duration so encrypted thinking is not crushed into the flush. A completed user request with anomalous throughput is isolated immediately, then verified with a controlled probe after the hold.", updatedAt: "Updated {{time}}", node: "Node", state: "State", outputTPS: "Panel output speed", firstToken: "First token", source: "Source", strikes: "Strikes", lastObserved: "Last observed", test: "Test", sources: { active: "Active probe", passive: "Request audit" }, quarantined: "Quarantined", fixedFallback: "Fixed fallback (protected)", suspect: "Suspect", healthy: "Healthy", pending: "Pending", probeFailed: "Probe failed", events: "Recent events", noEvents: "No anomaly or recovery events", eventTypes: { node_quarantined: "Node quarantined", node_restored: "Node restored", node_rotated: "Node IP rotated", passive_audit_anomaly: "Anomalous request detected" }, statistics: "Automatic detection statistics", statisticsSince: "Accumulated since {{time}}. Manual tests are excluded.", statisticsChecks: "Valid checks", statisticsChecksHelp: "Active probes and valid passive audits", statisticsActive: "Active probes", statisticsActiveDetail: "Healthy {{healthy}}, errors {{errors}}", statisticsPassive: "Passive audits", statisticsPassiveDetail: "Healthy {{healthy}}, from real requests", statisticsTokens: "Active output tokens", statisticsTokensHelp: "Includes reasoning tokens; not proxy traffic", statisticsAnomalies: "Anomaly hits", statisticsAnomalyDetail: "Soft {{soft}}, hard {{hard}}", statisticsQuarantines: "Quarantines applied", statisticsActionDetail: "Restored {{restored}}, protected {{suppressed}}", reasons: { unknown: "No reason recorded", hard_tps: "Hard threshold exceeded", soft_tps: "Soft threshold exceeded", buffered_burst: "Short-window output burst; retesting the same IP", missing_thinking: "Missing thinking tokens", passive_hard_tps: "Request exceeded hard threshold", passive_soft_tps: "Request exceeded soft threshold", quality_probe_healthy: "Model quality probe recovered", expected_marker_missing: "Expected marker missing", insufficient_output_tokens: "Too few output tokens", insufficient_visible_tokens: "Too few visible tokens", insufficient_generation_window: "Generation window too short", probe_errors: "Repeated probe errors", probe_no_account: "No schedulable probe account; retry deferred", recovery_probe_error: "Recovery probe failed", rotation_error: "IP rotation failed" }, policy: "Current policy", editPolicy: "Edit policy", editPolicyTitle: "Edit quality guard policy", editPolicyDescription: "The guard hot-reloads saved changes without a service restart.", restoreDefaults: "Restore defaults", policySaved: "Policy saved and queued for hot reload", invalidPolicyValue: "Value is outside the allowed range", softThresholdMustBeLower: "The soft threshold must be lower than the hard threshold", activeIntervalSeconds: "Active interval (seconds)", passiveIntervalSeconds: "Passive interval (seconds)", consecutiveSoft: "Consecutive active soft strikes", consecutiveErrors: "Consecutive probe errors", quarantineSeconds: "Quarantine (seconds)", softThreshold: "Soft threshold", hardThreshold: "Hard threshold", activeInterval: "Active interval", passiveInterval: "Audit interval", quarantineDuration: "Quarantine", minimumNodes: "Minimum nodes", unavailable: "Quality guard is not connected", unavailableHelp: "Enable qualityGuard in config.yaml and start the quality-guard Compose profile to display live status here.", testing: "Testing node quality", testComplete: "Test complete: {{speed}}", testFailed: "Quality test is temporarily unavailable. Try again shortly.", refreshNodes: "Refresh nodes", nodeEnabled: "Node enabled", nodeDisabled: "Node disabled", nodesEnabled: "Selected nodes enabled", nodesDisabled: "Selected nodes disabled", enableNode: "Enable node {{name}}", disableNode: "Disable node {{name}}", nodeEditorDescription: "Manage Grok Build egress used by the quality guard. Proxy URLs are write-only; leave the field blank while editing to keep the current value.", nodeCapacityHelp: "Maximum number of bound accounts; 0 means unlimited.", deleteNodeTitle: "Delete proxy node?", deleteNodeDescription: "Node “{{name}}” will be permanently deleted. This action cannot be undone.", deleteNodesTitle: "Delete {{count}} selected nodes?", deleteNodesDescription: "The selected proxy nodes will be permanently deleted. This action cannot be undone.", nodesTab: "Node quality", profilesTab: "Probe profiles", profilesHelp: "Prompt and expected marker for active quality probes. A missing marker is a hard failure.", diff --git a/tools/egress-quality-guard/README.md b/tools/egress-quality-guard/README.md index f5a9619b..531d3387 100644 --- a/tools/egress-quality-guard/README.md +++ b/tools/egress-quality-guard/README.md @@ -21,8 +21,11 @@ your own traffic before allowing automatic quarantine. ## How it works 1. Passive mode polls recent successful streaming audits and computes the same - speed shown by the grok2api panel: `output / (duration - first token)`. - `output` intentionally includes reasoning tokens. + speed shown by the grok2api panel: `output / generation window`. + `output` includes reasoning tokens. The window is `duration - first token`, + except when that tail is both shorter than the first-token wait and under + 1s: then the full duration is used so buffered thinking is not assigned to + a few milliseconds. 2. Active mode calls a quality-guard-only internal probe endpoint. The scoped credential cannot access account exports, administrator management, or the rest of the administrator API. diff --git a/tools/egress-quality-guard/README.zh-CN.md b/tools/egress-quality-guard/README.zh-CN.md index 0a7d3f95..af6dab6e 100644 --- a/tools/egress-quality-guard/README.zh-CN.md +++ b/tools/egress-quality-guard/README.zh-CN.md @@ -15,7 +15,7 @@ Token/s,因此建议先观察 JSON 日志,再根据实际流量调整阈值 ## 工作流程 -1. 被动检测每 5 秒读取普通成功流式请求的新增审计,并按 grok2api 面板同口径的 `输出 Token / (总耗时 - 首字耗时)` 计算速度;输出 Token 故意包含 Reasoning Token。 +1. 被动检测每 5 秒读取普通成功流式请求的新增审计,并按 grok2api 面板同口径计算速度:输出 Token 包含 Reasoning Token,分母是生成窗口。默认是 `总耗时 - 首字耗时`;若这段尾巴既短于首字等待又不足 1 秒,则改用全程,避免加密思考被挤进最后几十毫秒。 2. 主动检测调用质量守护专用内部探测接口;该凭据不能导出账号、管理管理员或访问其他管理 API。 3. grok2api 优先使用明确绑定到该节点的账号;如果这些账号不可调度,则借用任意健康账号,但仍强制实际请求走被测节点,再发送固定流式 Prompt。即使其他 Provider 暴露同名模型,后端也会把探测路由固定为 Grok Build。 4. 普通真实请求达到硬阈值时立即隔离;达到软阈值时触发一次固定 Prompt 主动复测。 diff --git a/tools/egress-quality-guard/quality_guard.py b/tools/egress-quality-guard/quality_guard.py index 5ff53025..a0eac943 100755 --- a/tools/egress-quality-guard/quality_guard.py +++ b/tools/egress-quality-guard/quality_guard.py @@ -370,14 +370,18 @@ def classify_result(result: dict[str, Any], config: Config, profile: dict[str, A # Rolling upgrades may still expose panel-equivalent TPS under the legacy name. speed_value = result.get("visibleTokensPerSecond") speed = float(speed_value or 0.0) + reasoning_tokens = max(0, int(result.get("reasoningTokens") or result.get("reasoning_tokens") or 0)) generation_ms = int(result.get("generationMs") or 0) if generation_ms <= 0: - generation_ms = max(0, int(result.get("durationMs") or 0) - int(result.get("firstTokenMs") or 0)) + generation_ms = generation_window_ms( + int(result.get("firstTokenMs") or 0), + int(result.get("durationMs") or 0), + reasoning_tokens, + ) # QUALITY_OK is a content marker, not a quality proof. Apply the same # token / window / TPS rules used for user-traffic audits. if output_tokens < 32: return "soft", "insufficient_output_tokens" - reasoning_tokens = max(0, int(result.get("reasoningTokens") or result.get("reasoning_tokens") or 0)) if "thinkingRequired" in result: require_thinking = bool(result.get("thinkingRequired")) else: @@ -465,7 +469,12 @@ def classify_audit(value: dict[str, Any], config: Config) -> tuple[str, str, flo first_token_ms = value.get("firstTokenMs") if first_token_ms is None: return "ignored", "missing_first_token", 0.0, 0 - generation_ms = int(value.get("durationMs") or 0) - int(first_token_ms) + reasoning_tokens = max(0, int(value.get("reasoningTokens") or 0)) + generation_ms = generation_window_ms( + int(first_token_ms), + int(value.get("durationMs") or 0), + reasoning_tokens, + ) output_tokens = max(0, int(value.get("outputTokens") or 0)) if generation_ms <= 0 or output_tokens < 32: return "ignored", "insufficient_output_tokens", 0.0, output_tokens @@ -479,6 +488,19 @@ def classify_audit(value: dict[str, Any], config: Config) -> tuple[str, str, flo return "healthy", "within_threshold", speed, output_tokens +def generation_window_ms(first_token_ms: int, duration_ms: int, reasoning_tokens: int = 0) -> int: + if duration_ms <= 0: + return 0 + if first_token_ms < 0: + first_token_ms = 0 + if first_token_ms >= duration_ms: + return 0 + generation_ms = duration_ms - first_token_ms + if reasoning_tokens > 0 and generation_ms < first_token_ms and generation_ms < 1000: + return duration_ms + return generation_ms + + def default_node_state() -> dict[str, Any]: return { "active_soft_strikes": 0, diff --git a/tools/egress-quality-guard/quality_guard_test.py b/tools/egress-quality-guard/quality_guard_test.py index 272f5e00..0b5a45f0 100644 --- a/tools/egress-quality-guard/quality_guard_test.py +++ b/tools/egress-quality-guard/quality_guard_test.py @@ -58,11 +58,31 @@ class ClassificationTests(unittest.TestCase): cfg = config() classification, reason, speed, output = quality_guard.classify_audit({ "provider": "grok_build", "streaming": True, "statusCode": 200, - "firstTokenMs": 1000, "durationMs": 1100, + "firstTokenMs": 200, "durationMs": 1200, "outputTokens": 1050, "reasoningTokens": 950, }, cfg) self.assertEqual((classification, reason, output), ("hard", "hard_tps", 1050)) - self.assertEqual(speed, 10500) + self.assertEqual(speed, 1050) + + def test_passive_late_first_token_uses_full_duration(self): + cfg = config() + classification, reason, speed, output = quality_guard.classify_audit({ + "provider": "grok_build", "streaming": True, "statusCode": 200, + "firstTokenMs": 19763, "durationMs": 19827, + "outputTokens": 1511, "reasoningTokens": 1471, + }, cfg) + self.assertEqual((classification, reason, output), ("healthy", "within_threshold", 1511)) + self.assertAlmostEqual(speed, 1511 * 1000 / 19827) + + def test_passive_late_first_token_without_reasoning_remains_burst(self): + cfg = config(fail_closed=True, min_generation_ms=1000) + classification, reason, speed, output = quality_guard.classify_audit({ + "provider": "grok_build", "streaming": True, "statusCode": 200, + "firstTokenMs": 10000, "durationMs": 10100, + "outputTokens": 2000, "reasoningTokens": 0, + }, cfg) + self.assertEqual((classification, reason, output), ("hard", "buffered_burst", 2000)) + self.assertEqual(speed, 20000) def test_passive_audit_does_not_infer_thinking_requirement(self): cfg = config(fail_closed=True, min_generation_ms=1000) @@ -515,7 +535,6 @@ class GuardTests(unittest.TestCase): "generationMs": 1500, } audit = self.audit("user", "1", 600) - audit.update({"durationMs": 2500, "outputTokens": 900}) api = FakeApi(self.nodes(3), [good], [ {"items": [], "hasMore": False, "nextCursor": ""}, {"items": [audit], "hasMore": False, "nextCursor": ""}, @@ -920,12 +939,12 @@ class GuardTests(unittest.TestCase): @staticmethod def audit(audit_id, node_id, output_tps, quality_probe=False): - generation_ms = 100 + generation_ms = 2000 output_tokens = int(output_tps * generation_ms / 1000) return { "id": audit_id, "requestId": f"request-{audit_id}", "qualityProbe": quality_probe, "provider": "grok_build", "streaming": True, - "statusCode": 200, "firstTokenMs": 1000, "durationMs": 1000 + generation_ms, + "statusCode": 200, "firstTokenMs": 200, "durationMs": 200 + generation_ms, "outputTokens": output_tokens, "reasoningTokens": min(100, max(0, output_tokens - 1)), "egressNodeId": node_id, "errorCode": None, }