perf(metrics): record relay outcomes at the request boundary and classify stream results

Sample each relay once when the request finishes instead of inside the
billing paths, classify the protocol outcome (completed, failed,
incomplete, cancelled) on the stream status from events the adaptors
already parse, and show response status and success-rate windows in the
dashboard and model cards.
This commit is contained in:
CaIon committed 2026-09-18 11:24:30 +08:00
1 parent 8a11b4305e
commit a5b40663d3
40 files changed
+928 -311

No files matched your search

+3 -2
View File
@@ -66,8 +66,9 @@ const (
ContextKeyAdminRejectReason ContextKey = "admin_reject_reason"
// ContextKeyLanguage stores the user's language preference for i18n
ContextKeyLanguage ContextKey = "language"
ContextKeyIsStream ContextKey = "is_stream"
ContextKeyLanguage ContextKey = "language"
ContextKeyIsStream ContextKey = "is_stream"
ContextKeyResponseStreamStatus ContextKey = "response_stream_status"
// ContextKeyAuditLogged marks that the current request has already recorded
// a manage/operation audit log inside the handler. When set, the admin-audit
+4 -13
View File
@@ -53,9 +53,10 @@ func GetPerfMetrics(c *gin.Context) {
}
result, err := perfmetrics.Query(perfmetrics.QueryParams{
Model: modelName,
Group: c.Query("group"),
Hours: hours,
Model: modelName,
Group: c.Query("group"),
Hours: hours,
AllowedGroups: append(lo.Keys(ratio_setting.GetGroupRatioCopy()), "auto"),
})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
@@ -65,18 +66,8 @@ func GetPerfMetrics(c *gin.Context) {
return
}
result.Groups = filterActiveGroups(result.Groups)
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": result,
})
}
func filterActiveGroups(groups []perfmetrics.GroupResult) []perfmetrics.GroupResult {
activeRatios := ratio_setting.GetGroupRatioCopy()
return lo.Filter(groups, func(g perfmetrics.GroupResult, _ int) bool {
_, ok := activeRatios[g.Group]
return ok || g.Group == "auto"
})
}
+17 -7
View File
@@ -26,8 +26,6 @@ import (
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting/operation_setting"
"github.com/bytedance/gopkg/util/gopool"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
@@ -126,6 +124,20 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
return
}
defer func() {
recovered := recover()
resultErr := newAPIError
if recovered != nil {
resultErr = types.NewError(fmt.Errorf("relay panic: %v", recovered), types.ErrorCodeBadResponse)
}
if relayFormat != types.RelayFormatOpenAIRealtime {
perfmetrics.RecordRelayResult(c.Request.Context(), relayInfo, resultErr)
}
if recovered != nil {
panic(recovered)
}
}()
if newAPIError = relay.PrepareRequestBilling(c, relayInfo); newAPIError != nil {
return
}
@@ -144,6 +156,9 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
relayInfo.LastError = nil
for ; retryParam.GetRetry() <= common.RetryTimes; retryParam.IncreaseRetry() {
relayInfo.StreamStatus = nil
relayInfo.PerformanceBusinessRejection = false
relayInfo.PerformanceOutputTokens = 0
relayInfo.RetryIndex = retryParam.GetRetry()
channel, channelErr := getChannel(c, relayInfo, retryParam)
if channelErr != nil {
@@ -203,11 +218,6 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
logger.LogInfo(c, retryLogStr)
}
if newAPIError != nil {
gopool.Go(func() {
perfmetrics.RecordRelaySample(relayInfo, false, 0)
})
}
}
// CountClaudeTokens implements Anthropic's token-counting utility endpoint.
+80 -22
View File
@@ -11,7 +11,10 @@ import (
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/types"
"github.com/QuantumNous/new-api/setting/perf_metrics_setting"
"github.com/bytedance/gopkg/util/gopool"
)
var hotBuckets sync.Map
@@ -24,10 +27,16 @@ func Init() {
go flushLoop()
}
func RecordRelaySample(info *relaycommon.RelayInfo, success bool, outputTokens int64) {
// RecordRelayResult samples one finished relay exactly once, at the request
// boundary, regardless of how many channel attempts it took.
func RecordRelayResult(ctx context.Context, info *relaycommon.RelayInfo, apiErr *types.NewAPIError) {
if info == nil {
return
}
outcome := ClassifyRelayOutcome(ctx, info, apiErr)
if outcome == OutcomeIgnored {
return
}
now := time.Now()
hasTtft := info.IsStream && info.HasSendResponse()
ttftMs := int64(0)
@@ -48,8 +57,8 @@ func RecordRelaySample(info *relaycommon.RelayInfo, success bool, outputTokens i
LatencyMs: latencyMs,
TtftMs: ttftMs,
HasTtft: hasTtft,
Success: success,
OutputTokens: outputTokens,
Success: outcome == OutcomeSuccess,
OutputTokens: info.PerformanceOutputTokens,
GenerationMs: generationMs,
})
}
@@ -73,18 +82,25 @@ func Record(sample Sample) {
}
actual, _ := hotBuckets.LoadOrStore(key, &atomicBucket{})
actual.(*atomicBucket).add(sample)
recordRedis(key, sample)
gopool.Go(func() {
recordRedis(key, sample)
})
}
// queryWindow covers the current partial hour plus the preceding complete
// hours, so every reader shares the same hourly buckets.
func queryWindow(now time.Time, hours int) (int64, int64) {
if hours <= 0 {
hours = 24
}
hours = min(hours, 24*30)
endTs := now.Unix()
return endTs - endTs%3600 - int64(hours-1)*3600, endTs
}
func Query(params QueryParams) (QueryResult, error) {
if params.Hours <= 0 {
params.Hours = 24
}
if params.Hours > 24*30 {
params.Hours = 24 * 30
}
endTs := time.Now().Unix()
startTs := endTs - int64(params.Hours)*3600
startTs, endTs := queryWindow(time.Now(), params.Hours)
allowedGroups := allowedGroupSet(params.AllowedGroups)
merged := map[bucketKey]counters{}
rows, err := model.GetPerfMetrics(params.Model, params.Group, startTs, endTs)
@@ -92,6 +108,11 @@ func Query(params QueryParams) (QueryResult, error) {
return QueryResult{}, err
}
for _, row := range rows {
if allowedGroups != nil {
if _, ok := allowedGroups[row.Group]; !ok {
continue
}
}
mergeCounters(merged, bucketKey{
model: row.ModelName,
group: row.Group,
@@ -115,22 +136,22 @@ func Query(params QueryParams) (QueryResult, error) {
if params.Group != "" && k.group != params.Group {
return true
}
if allowedGroups != nil {
if _, ok := allowedGroups[k.group]; !ok {
return true
}
}
mergeCounters(merged, k, value.(*atomicBucket).snapshot())
return true
})
return buildQueryResult(params.Model, merged), nil
result := buildQueryResult(params.Model, merged)
result.WindowStart, result.WindowEnd = startTs, endTs
return result, nil
}
func QuerySummaryAll(hours int, groups []string) (SummaryAllResult, error) {
if hours <= 0 {
hours = 24
}
if hours > 24*30 {
hours = 24 * 30
}
endTs := time.Now().Unix()
startTs := endTs - int64(hours)*3600
startTs, endTs := queryWindow(time.Now(), hours)
allowedGroups := allowedGroupSet(groups)
rows, err := model.GetPerfMetricsSummaryBucketsAll(startTs, endTs, groups)
@@ -171,11 +192,17 @@ func QuerySummaryAll(hours int, groups []string) (SummaryAllResult, error) {
return true
})
all := counters{}
models := make([]ModelSummary, 0, len(totals))
for name, total := range totals {
if total.requestCount == 0 {
continue
}
all.requestCount += total.requestCount
all.successCount += total.successCount
all.totalLatencyMs += total.totalLatencyMs
all.outputTokens += total.outputTokens
all.generationMs += total.generationMs
avgLatency := total.totalLatencyMs / total.requestCount
successRate := float64(total.successCount) / float64(total.requestCount) * 100
avgTps := 0.0
@@ -195,7 +222,7 @@ func QuerySummaryAll(hours int, groups []string) (SummaryAllResult, error) {
return models[i].RequestCount > models[j].RequestCount
})
return SummaryAllResult{Models: models}, nil
return SummaryAllResult{Summary: summarize(all), WindowStart: startTs, WindowEnd: endTs, Models: models}, nil
}
func mergeModelTotals(totals map[string]counters, modelName string, value counters) {
@@ -302,6 +329,7 @@ func mergeCounters(merged map[bucketKey]counters, key bucketKey, value counters)
func buildQueryResult(modelName string, merged map[bucketKey]counters) QueryResult {
groupBuckets := map[string]map[int64]counters{}
modelBuckets := map[string]map[int64]counters{}
for key, value := range merged {
if value.requestCount == 0 {
continue
@@ -310,6 +338,7 @@ func buildQueryResult(modelName string, merged map[bucketKey]counters) QueryResu
groupBuckets[key.group] = map[int64]counters{}
}
groupBuckets[key.group][key.bucketTs] = value
mergeModelBucket(modelBuckets, modelName, key.bucketTs, value)
}
groups := make([]string, 0, len(groupBuckets))
@@ -318,6 +347,7 @@ func buildQueryResult(modelName string, merged map[bucketKey]counters) QueryResu
}
sort.Strings(groups)
all := counters{}
results := make([]GroupResult, 0, len(groups))
for _, group := range groups {
buckets := groupBuckets[group]
@@ -342,6 +372,11 @@ func buildQueryResult(modelName string, merged map[bucketKey]counters) QueryResu
total.generationMs += value.generationMs
series = append(series, bucketPoint(ts, value))
}
all.requestCount += total.requestCount
all.successCount += total.successCount
all.totalLatencyMs += total.totalLatencyMs
all.outputTokens += total.outputTokens
all.generationMs += total.generationMs
results = append(results, GroupResult{
Group: group,
@@ -353,13 +388,36 @@ func buildQueryResult(modelName string, merged map[bucketKey]counters) QueryResu
})
}
modelSeries := make([]BucketPoint, 0, len(modelBuckets[modelName]))
for ts, value := range modelBuckets[modelName] {
modelSeries = append(modelSeries, bucketPoint(ts, value))
}
sort.Slice(modelSeries, func(i, j int) bool {
return modelSeries[i].Ts < modelSeries[j].Ts
})
return QueryResult{
ModelName: modelName,
SeriesSchema: seriesSchema,
Summary: summarize(all),
Series: modelSeries,
Groups: results,
}
}
// summarize returns nil when nothing was sampled, so clients can show
// "no data" instead of a fabricated 0% success rate.
func summarize(total counters) *Summary {
if total.requestCount <= 0 {
return nil
}
return &Summary{
AvgLatencyMs: avg(total.totalLatencyMs, total.requestCount),
SuccessRate: math.Round(successRate(total)*100) / 100,
AvgTps: math.Round(avgTps(total)*100) / 100,
}
}
func bucketPoint(ts int64, value counters) BucketPoint {
return BucketPoint{
Ts: ts,
+213
View File
@@ -0,0 +1,213 @@
package perfmetrics
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestClassifyRelayOutcome(t *testing.T) {
canceled, cancel := context.WithCancel(context.Background())
cancel()
for _, tc := range []struct {
name string
ctx context.Context
err *types.NewAPIError
want Outcome
}{
{"success", context.Background(), nil, OutcomeSuccess},
{"upstream bad request", context.Background(), types.InitOpenAIError("unknown", 400), OutcomeIgnored},
{"upstream credentials returned as 400", context.Background(), types.InitOpenAIError("invalid_api_key", 400), OutcomeFailure},
{"wrapped credentials keep their cause", context.Background(), types.NewErrorWithStatusCode(types.InitOpenAIError("invalid_api_key", 400), types.ErrorCodeInvalidRequest, 400), OutcomeFailure},
{"upstream context limit returned as 500", context.Background(), types.InitOpenAIError("context_length_exceeded", 500), OutcomeIgnored},
{"local rate limit", context.Background(), types.NewErrorWithStatusCode(errors.New("limited"), types.ErrorCodeInvalidRequest, 429), OutcomeIgnored},
{"upstream rate limit", context.Background(), types.InitOpenAIError("rate_limit_exceeded", 429), OutcomeFailure},
{"local quota", context.Background(), types.NewError(errors.New("quota"), types.ErrorCodeInsufficientUserQuota), OutcomeIgnored},
{"local violation fee", context.Background(), types.NewError(errors.New("csam"), types.ErrorCodeViolationFeeGrokCSAM), OutcomeIgnored},
{"upstream quota", context.Background(), types.InitOpenAIError("insufficient_quota", 429), OutcomeFailure},
{"upstream gateway quota", context.Background(), types.InitOpenAIError(types.ErrorCodeInsufficientUserQuota, 403), OutcomeFailure},
{"unavailable channel", context.Background(), types.NewErrorWithStatusCode(errors.New("disabled"), types.ErrorCodeGetChannelFailed, 403), OutcomeFailure},
{"empty upstream response", context.Background(), types.NewError(errors.New("empty"), types.ErrorCodeEmptyResponse), OutcomeFailure},
{"network failure", context.Background(), types.NewOpenAIError(errors.New("connection refused"), types.ErrorCodeDoRequestFailed, 500), OutcomeFailure},
{"client cancellation", canceled, types.NewOpenAIError(errors.New("context canceled"), types.ErrorCodeDoRequestFailed, 500), OutcomeIgnored},
{"upstream deadline", context.Background(), types.NewOpenAIError(context.DeadlineExceeded, types.ErrorCodeDoRequestFailed, 504), OutcomeFailure},
} {
t.Run(tc.name, func(t *testing.T) {
assert.Equal(t, tc.want, ClassifyRelayOutcome(tc.ctx, &relaycommon.RelayInfo{}, tc.err))
})
}
assert.Equal(t, OutcomeIgnored, ClassifyRelayOutcome(context.Background(), &relaycommon.RelayInfo{PerformanceBusinessRejection: true}, nil))
}
func TestStreamOutcomeClassification(t *testing.T) {
for _, tc := range []struct {
name string
mark func(*relaycommon.StreamStatus)
end relaycommon.StreamEndReason
want Outcome
}{
{"completed", (*relaycommon.StreamStatus).MarkCompleted, relaycommon.StreamEndReasonEOF, OutcomeSuccess},
{"business rejection", func(s *relaycommon.StreamStatus) { s.MarkFailed("context_length_exceeded", "", 0) }, relaycommon.StreamEndReasonEOF, OutcomeIgnored},
{"service error", func(s *relaycommon.StreamStatus) { s.MarkFailed("server_error", "", 0) }, relaycommon.StreamEndReasonEOF, OutcomeFailure},
{"error after completion", func(s *relaycommon.StreamStatus) { s.MarkCompleted(); s.MarkFailed("", "server_error", 0) }, relaycommon.StreamEndReasonEOF, OutcomeFailure},
{"output limit", func(s *relaycommon.StreamStatus) { s.MarkIncomplete("max_output_tokens") }, relaycommon.StreamEndReasonEOF, OutcomeSuccess},
{"content filter", func(s *relaycommon.StreamStatus) { s.MarkIncomplete("content_filter") }, relaycommon.StreamEndReasonEOF, OutcomeIgnored},
{"client cancel", (*relaycommon.StreamStatus).MarkCancelled, relaycommon.StreamEndReasonEOF, OutcomeIgnored},
{"client gone", nil, relaycommon.StreamEndReasonClientGone, OutcomeIgnored},
{"timeout", nil, relaycommon.StreamEndReasonTimeout, OutcomeFailure},
{"missing terminal", nil, relaycommon.StreamEndReasonEOF, OutcomeFailure},
{"done marker without terminal", nil, relaycommon.StreamEndReasonDone, OutcomeSuccess},
} {
t.Run(tc.name, func(t *testing.T) {
stream := relaycommon.NewStreamStatus()
stream.RequireTerminal()
if tc.mark != nil {
tc.mark(stream)
}
stream.SetEndReason(tc.end, nil)
assert.Equal(t, tc.want, ClassifyRelayOutcome(context.Background(), &relaycommon.RelayInfo{StreamStatus: stream}, nil))
})
}
}
func TestClientCancellationDuringUpstreamRead(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
stream := relaycommon.NewStreamStatus()
stream.RequireTerminal()
stream.SetEndReason(relaycommon.StreamEndReasonScannerErr, errors.New("reader closed"))
assert.Equal(t, OutcomeIgnored, ClassifyRelayOutcome(ctx, &relaycommon.RelayInfo{StreamStatus: stream}, nil))
deadline := relaycommon.NewStreamStatus()
deadline.SetEndReason(relaycommon.StreamEndReasonClientGone, context.DeadlineExceeded)
assert.Equal(t, OutcomeFailure, ClassifyRelayOutcome(context.Background(), &relaycommon.RelayInfo{StreamStatus: deadline}, nil))
}
func TestPerformanceWindowIncludesCurrentHour(t *testing.T) {
now := time.Date(2026, 9, 14, 12, 37, 0, 0, time.UTC)
start, end := queryWindow(now, 24)
assert.Equal(t, time.Date(2026, 9, 13, 13, 0, 0, 0, time.UTC).Unix(), start)
assert.Equal(t, now.Unix(), end)
}
func TestHourlySuccessSeriesWeightsSmallerBuckets(t *testing.T) {
points := recentSuccessSeries(map[int64]counters{
3600: {requestCount: 100, successCount: 100},
3900: {requestCount: 1},
7200: {requestCount: 1, successCount: 1},
})
assert.Equal(t, []SuccessRatePoint{{Ts: 3600, SuccessRate: 99.01}, {Ts: 7200, SuccessRate: 100}}, points)
}
// TEST_PERF_MYSQL_DSN / TEST_PERF_POSTGRES_DSN optionally run the aggregation
// against isolated real MySQL/PostgreSQL databases.
func TestPerformanceAggregationAndFlush(t *testing.T) {
for _, dialect := range []struct{ name, env string }{
{"sqlite", ""}, {"mysql", "TEST_PERF_MYSQL_DSN"}, {"postgres", "TEST_PERF_POSTGRES_DSN"},
} {
t.Run(dialect.name, func(t *testing.T) {
dsn := ""
if dialect.env != "" {
dsn = os.Getenv(dialect.env)
if dsn == "" {
t.Skip("isolated test database DSN is not configured")
}
}
t.Setenv("SQL_DSN", dsn)
oldDB, oldPath, oldMaster, oldRedis := model.DB, common.SQLitePath, common.IsMasterNode, common.RedisEnabled
oldType, oldLogType := common.MainDatabaseType(), common.LogDatabaseType()
common.SQLitePath, common.IsMasterNode, common.RedisEnabled = filepath.Join(t.TempDir(), "perf.db"), false, false
hotBuckets.Clear()
t.Cleanup(func() {
model.DB, common.SQLitePath, common.IsMasterNode, common.RedisEnabled = oldDB, oldPath, oldMaster, oldRedis
common.SetDatabaseTypes(oldType, oldLogType)
hotBuckets.Clear()
})
require.NoError(t, model.InitDB())
db := model.DB
sqlDB, err := db.DB()
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, sqlDB.Close()) })
require.NoError(t, db.Migrator().DropTable(&model.PerfMetric{}))
require.NoError(t, db.AutoMigrate(&model.PerfMetric{}))
now := time.Now()
start, _ := queryWindow(now, 24)
hour := now.Unix() - now.Unix()%3600 - 3600
// Historical counters remain usable without reclassification or migration.
for _, row := range []model.PerfMetric{
{ModelName: "test-model", Group: "a", BucketTs: hour, RequestCount: 100, SuccessCount: 100, TotalLatencyMs: 100000, TtftCount: 100, TtftSumMs: 10000, OutputTokens: 200, GenerationMs: 40000},
{ModelName: "test-model", Group: "inactive", BucketTs: hour, RequestCount: 100},
{ModelName: "test-model", Group: "a", BucketTs: start - 3600, RequestCount: 100},
} {
require.NoError(t, model.UpsertPerfMetric(&row))
}
groups := []string{"a", "b"}
RecordRelayResult(context.Background(), &relaycommon.RelayInfo{OriginModelName: "test-model", UsingGroup: "b", StartTime: now}, types.InitOpenAIError("unknown", 400))
businessRejected, err := QuerySummaryAll(24, groups)
require.NoError(t, err)
require.NotNil(t, businessRejected.Summary)
assert.Equal(t, 100.0, businessRejected.Summary.SuccessRate)
failure := &atomicBucket{}
failure.add(Sample{LatencyMs: 2000})
hotBuckets.Store(bucketKey{model: "test-model", group: "b", bucketTs: hour}, failure)
before, err := Query(QueryParams{Model: "test-model", Hours: 24, AllowedGroups: groups})
require.NoError(t, err)
require.NotNil(t, before.Summary)
assert.Equal(t, Summary{SuccessRate: 99.01, AvgLatencyMs: 1009, AvgTps: 5}, *before.Summary)
assert.Equal(t, start, before.WindowStart)
require.Len(t, before.Series, 1)
assert.Equal(t, hour, before.Series[0].Ts)
assert.InDelta(t, 99.01, before.Series[0].SuccessRate, 0.01)
require.Len(t, before.Groups, 2)
summary, err := QuerySummaryAll(24, groups)
require.NoError(t, err)
assert.Equal(t, before.Summary, summary.Summary)
require.Len(t, summary.Models, 1)
assert.Equal(t, 99.01, summary.Models[0].SuccessRate)
assert.Equal(t, 99.01, summary.Models[0].RecentSuccessSeries[0].SuccessRate)
encoded, err := common.Marshal(summary)
require.NoError(t, err)
assert.NotContains(t, string(encoded), "request_count")
assert.NotContains(t, string(encoded), "success_count")
flushCompletedBuckets()
flushCompletedBuckets()
after, err := Query(QueryParams{Model: "test-model", Hours: 24, AllowedGroups: groups})
require.NoError(t, err)
assert.Equal(t, before.Summary, after.Summary)
assert.Equal(t, before.Series, after.Series)
RecordRelayResult(context.Background(), &relaycommon.RelayInfo{OriginModelName: "test-model", UsingGroup: "a", StartTime: now}, types.InitOpenAIError("context_length_exceeded", 400))
after, err = Query(QueryParams{Model: "test-model", Hours: 24, AllowedGroups: groups})
require.NoError(t, err)
assert.Equal(t, before.Summary, after.Summary)
onlyA, err := Query(QueryParams{Model: "test-model", Group: "a", Hours: 24, AllowedGroups: groups})
require.NoError(t, err)
assert.Equal(t, 100.0, onlyA.Summary.SuccessRate)
empty, err := Query(QueryParams{Model: "missing", Hours: 24, AllowedGroups: groups})
require.NoError(t, err)
assert.Nil(t, empty.Summary)
assert.Empty(t, empty.Series)
require.NoError(t, model.UpsertPerfMetric(&model.PerfMetric{ModelName: "second-model", Group: "a", BucketTs: hour, RequestCount: 1}))
combined, err := QuerySummaryAll(24, groups)
require.NoError(t, err)
assert.Equal(t, 98.04, combined.Summary.SuccessRate)
assert.Equal(t, 99.01, combined.Models[0].SuccessRate)
})
}
}
+122
View File
@@ -0,0 +1,122 @@
package perfmetrics
import (
"context"
"errors"
"strings"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/types"
)
type Outcome string
const (
OutcomeSuccess Outcome = "success"
OutcomeFailure Outcome = "failure"
OutcomeIgnored Outcome = "ignored"
)
// ClassifyRelayOutcome decides whether one finished relay counts as a health
// sample. Business rejections and client cancellations are not samples; the
// classification is independent of retries, channel disabling and billing.
func ClassifyRelayOutcome(ctx context.Context, info *relaycommon.RelayInfo, apiErr *types.NewAPIError) Outcome {
if info == nil || info.PerformanceBusinessRejection {
return OutcomeIgnored
}
if ctx != nil && ctx.Err() == context.Canceled {
return OutcomeIgnored
}
if apiErr != nil && errors.Is(apiErr, context.Canceled) {
return OutcomeIgnored
}
stream := info.StreamStatus.OutcomeSnapshot()
if stream.Response == relaycommon.ResponseOutcomeFailed {
return classifyFailure(false, stream.ErrorCode, stream.ErrorType, stream.ErrorStatus)
}
if apiErr != nil {
root := rootAPIError(apiErr)
local := root.GetErrorType() == types.ErrorTypeNewAPIError
return classifyFailure(local, string(root.GetErrorCode()), root.ToOpenAIError().Type, root.StatusCode)
}
deadlineExceeded := info.StreamStatus != nil && errors.Is(info.StreamStatus.EndError, context.DeadlineExceeded)
if stream.Response == relaycommon.ResponseOutcomeCancelled || stream.EndReason == relaycommon.StreamEndReasonPingFail {
return OutcomeIgnored
}
if stream.EndReason == relaycommon.StreamEndReasonClientGone && !deadlineExceeded {
return OutcomeIgnored
}
if stream.Response == relaycommon.ResponseOutcomeIncomplete {
switch stream.IncompleteReason {
case "max_output_tokens", "max_tokens":
return OutcomeSuccess
case "content_filter", "safety", "content_policy_violation":
return OutcomeIgnored
default:
return OutcomeFailure
}
}
if stream.HasErrors || deadlineExceeded {
return OutcomeFailure
}
switch stream.EndReason {
case relaycommon.StreamEndReasonTimeout, relaycommon.StreamEndReasonScannerErr, relaycommon.StreamEndReasonPanic:
return OutcomeFailure
}
if stream.ExpectsTerminal && stream.Response == relaycommon.ResponseOutcomeUnknown && stream.EndReason != relaycommon.StreamEndReasonDone {
return OutcomeFailure
}
return OutcomeSuccess
}
// rootAPIError follows host wrappers back to the error that describes what
// actually happened, e.g. an upstream credential error re-wrapped as a local
// invalid request.
func rootAPIError(apiErr *types.NewAPIError) *types.NewAPIError {
for {
var inner *types.NewAPIError
if !errors.As(apiErr.Unwrap(), &inner) || inner == apiErr {
return apiErr
}
apiErr = inner
}
}
func classifyFailure(local bool, code, errorType string, status int) Outcome {
code, errorType = strings.ToLower(code), strings.ToLower(errorType)
if local {
if strings.HasPrefix(code, "violation_fee.") {
return OutcomeIgnored
}
switch types.ErrorCode(code) {
case types.ErrorCodeInvalidRequest, types.ErrorCodeSensitiveWordsDetected, types.ErrorCodeReadRequestBodyFailed,
types.ErrorCodeConvertRequestFailed, types.ErrorCodeAccessDenied, types.ErrorCodeBadRequestBody,
types.ErrorCodeInsufficientUserQuota, types.ErrorCodePreConsumeTokenQuotaFailed, types.ErrorCodePromptBlocked:
return OutcomeIgnored
}
return OutcomeFailure
}
// Specific codes take precedence over broad protocol types, because
// providers also report invalid credentials as invalid_request_error.
for _, value := range []string{code, errorType} {
switch value {
case "invalid_api_key", "api_key_invalid", "api_key_expired", "api_key_service_blocked", "invalid_authentication",
"authentication_error", "unauthenticated", "permission_denied", "permission_error", "access_denied",
"insufficient_quota", "quota_exceeded", "resource_exhausted", "rate_limit_exceeded", "rate_limit_error",
"overloaded_error", "server_error", "internal_error", "service_unavailable", "model_not_found",
"insufficient_user_quota", "pre_consume_token_quota_failed":
return OutcomeFailure
case "context_length_exceeded", "invalid_request", "invalid_request_error", "invalid_argument",
"sensitive_words_detected", "prompt_blocked", "content_filter", "content_policy_violation", "safety":
return OutcomeIgnored
}
if strings.HasPrefix(value, "violation_fee.") {
return OutcomeIgnored
}
}
switch status {
case 400, 405, 409, 413, 415, 422:
return OutcomeIgnored
}
return OutcomeFailure
}
+18 -1
View File
@@ -22,6 +22,16 @@ type QueryParams struct {
Model string
Group string
Hours int
// AllowedGroups restricts both the per-group results and the model summary;
// nil allows every group.
AllowedGroups []string
}
// Summary is the request-weighted aggregate over every bucket in the window.
type Summary struct {
AvgLatencyMs int64 `json:"avg_latency_ms"`
SuccessRate float64 `json:"success_rate"`
AvgTps float64 `json:"avg_tps"`
}
type BucketPoint struct {
@@ -44,6 +54,10 @@ type GroupResult struct {
type QueryResult struct {
ModelName string `json:"model_name"`
SeriesSchema string `json:"series_schema"`
Summary *Summary `json:"summary"`
Series []BucketPoint `json:"series"`
WindowStart int64 `json:"window_start"`
WindowEnd int64 `json:"window_end"`
Groups []GroupResult `json:"groups"`
}
@@ -62,7 +76,10 @@ type ModelSummary struct {
}
type SummaryAllResult struct {
Models []ModelSummary `json:"models"`
Summary *Summary `json:"summary"`
WindowStart int64 `json:"window_start"`
WindowEnd int64 `json:"window_end"`
Models []ModelSummary `json:"models"`
}
type bucketKey struct {
+9 -4
View File
@@ -24,11 +24,12 @@ func stopReasonClaude2OpenAI(reason string) string {
return relayconvert.StopReasonClaudeToOpenAI(reason)
}
func maybeMarkClaudeRefusal(c *gin.Context, stopReason string) {
func maybeMarkClaudeRefusal(c *gin.Context, info *relaycommon.RelayInfo, stopReason string) {
if c == nil {
return
}
if strings.EqualFold(stopReason, "refusal") {
info.PerformanceBusinessRejection = true
common.SetContextKey(c, constant.ContextKeyAdminRejectReason, "claude_stop_reason=refusal")
}
}
@@ -95,10 +96,13 @@ func HandleStreamResponseData(c *gin.Context, info *relaycommon.RelayInfo, claud
return types.WithClaudeError(*claudeError, http.StatusInternalServerError)
}
if claudeResponse.StopReason != "" {
maybeMarkClaudeRefusal(c, claudeResponse.StopReason)
maybeMarkClaudeRefusal(c, info, claudeResponse.StopReason)
}
if claudeResponse.Delta != nil && claudeResponse.Delta.StopReason != nil {
maybeMarkClaudeRefusal(c, *claudeResponse.Delta.StopReason)
maybeMarkClaudeRefusal(c, info, *claudeResponse.Delta.StopReason)
}
if claudeResponse.Type == "message_stop" {
info.StreamStatus.MarkCompleted()
}
if info.RelayFormat == types.RelayFormatClaude {
FormatClaudeResponseInfo(&claudeResponse, nil, claudeInfo)
@@ -299,6 +303,7 @@ func ClaudeStreamHandler(c *gin.Context, resp *http.Response, info *relaycommon.
sr.Stop(err)
}
})
info.StreamStatus.RequireTerminal()
if err != nil {
return nil, err
}
@@ -316,7 +321,7 @@ func HandleClaudeResponseData(c *gin.Context, info *relaycommon.RelayInfo, claud
if claudeError := claudeResponse.GetClaudeError(); claudeError != nil && claudeError.Type != "" {
return types.WithClaudeError(*claudeError, http.StatusInternalServerError)
}
maybeMarkClaudeRefusal(c, claudeResponse.StopReason)
maybeMarkClaudeRefusal(c, info, claudeResponse.StopReason)
if claudeInfo.Usage == nil {
claudeInfo.Usage = &dto.Usage{}
}
+5 -2
View File
@@ -107,10 +107,13 @@ func ClaudeResponsesStreamHandler(c *gin.Context, resp *http.Response, info *rel
}
if claudeResponse.StopReason != "" {
maybeMarkClaudeRefusal(c, claudeResponse.StopReason)
maybeMarkClaudeRefusal(c, info, claudeResponse.StopReason)
}
if claudeResponse.Delta != nil && claudeResponse.Delta.StopReason != nil {
maybeMarkClaudeRefusal(c, *claudeResponse.Delta.StopReason)
maybeMarkClaudeRefusal(c, info, *claudeResponse.Delta.StopReason)
}
if claudeResponse.Type == "message_stop" {
info.StreamStatus.MarkCompleted()
}
if claudeResponse.Type == "message_start" && claudeResponse.Message != nil {
info.UpstreamModelName = claudeResponse.Message.Model
@@ -37,6 +37,7 @@ func GeminiTextGenerationHandler(c *gin.Context, info *relaycommon.RelayInfo, re
countGeminiBillableFunctionCalls(info, &geminiResponse)
if len(geminiResponse.Candidates) == 0 && geminiResponse.PromptFeedback != nil && geminiResponse.PromptFeedback.BlockReason != nil {
info.PerformanceBusinessRejection = true
common.SetContextKey(c, constant.ContextKeyAdminRejectReason, fmt.Sprintf("gemini_block_reason=%s", *geminiResponse.PromptFeedback.BlockReason))
}
+13
View File
@@ -181,8 +181,19 @@ func geminiStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http
}
if len(geminiResponse.Candidates) == 0 && geminiResponse.PromptFeedback != nil && geminiResponse.PromptFeedback.BlockReason != nil {
info.PerformanceBusinessRejection = true
common.SetContextKey(c, constant.ContextKeyAdminRejectReason, fmt.Sprintf("gemini_block_reason=%s", *geminiResponse.PromptFeedback.BlockReason))
}
for _, candidate := range geminiResponse.Candidates {
if candidate.FinishReason == nil || *candidate.FinishReason == "" || *candidate.FinishReason == "FINISH_REASON_UNSPECIFIED" {
continue
}
switch *candidate.FinishReason {
case "SAFETY", "RECITATION", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII", "IMAGE_SAFETY", "IMAGE_PROHIBITED_CONTENT", "IMAGE_RECITATION":
info.PerformanceBusinessRejection = true
}
info.StreamStatus.MarkCompleted()
}
markGeminiGoogleSearchCall(c, &geminiResponse)
countGeminiBillableFunctionCalls(info, &geminiResponse)
@@ -216,6 +227,7 @@ func geminiStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http
sr.Stop(streamErr)
}
})
info.StreamStatus.RequireTerminal()
if !hasBillableUsageMetadata {
if info.ReceivedResponseCount > 0 {
@@ -377,6 +389,7 @@ func GeminiChatHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.R
var newAPIError *types.NewAPIError
if geminiResponse.PromptFeedback != nil && geminiResponse.PromptFeedback.BlockReason != nil {
info.PerformanceBusinessRejection = true
common.SetContextKey(c, constant.ContextKeyAdminRejectReason, fmt.Sprintf("gemini_block_reason=%s", *geminiResponse.PromptFeedback.BlockReason))
newAPIError = types.NewOpenAIError(
errors.New("request blocked by Gemini API: "+*geminiResponse.PromptFeedback.BlockReason),
+1
View File
@@ -36,6 +36,7 @@ func GeminiResponsesHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *h
if len(geminiResponse.Candidates) == 0 {
usage := buildUsageFromGeminiResponse(c, info, &geminiResponse)
if geminiResponse.PromptFeedback != nil && geminiResponse.PromptFeedback.BlockReason != nil {
info.PerformanceBusinessRejection = true
common.SetContextKey(c, constant.ContextKeyAdminRejectReason, fmt.Sprintf("gemini_block_reason=%s", *geminiResponse.PromptFeedback.BlockReason))
return &usage, types.NewOpenAIError(
errors.New("request blocked by Gemini API: "+*geminiResponse.PromptFeedback.BlockReason),
@@ -60,6 +60,8 @@ func OaiResponsesToChatBufferedStreamHandler(c *gin.Context, info *relaycommon.R
}
defer service.CloseResponseBodyGracefully(resp)
info.StreamStatus = relaycommon.NewStreamStatus()
info.StreamStatus.RequireTerminal()
accumulator := relayconvert.NewResponsesBufferedAccumulator()
var finalResponse *dto.OpenAIResponsesResponse
var streamErr *types.NewAPIError
@@ -86,6 +88,7 @@ func OaiResponsesToChatBufferedStreamHandler(c *gin.Context, info *relaycommon.R
streamErr = types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
break
}
service.ObserveResponsesOutcome(info, &streamResp)
accumulator.ProcessEvent(&streamResp)
switch streamResp.Type {
case "response.completed", "response.done", "response.incomplete":
+13 -2
View File
@@ -134,7 +134,7 @@ func OaiStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Re
}
lastStreamData = data
collectStreamFunctionCallNames(data, seenStreamToolCalls, &streamFunctionCallNames)
observeStreamChoices(info, data, seenStreamToolCalls, &streamFunctionCallNames)
if err := processTokenData(info.RelayMode, data, &responseTextBuilder, &toolCount); err != nil {
logger.LogError(c, "error processing stream token data: "+err.Error())
sr.Error(err)
@@ -142,6 +142,8 @@ func OaiStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Re
}
})
info.StreamStatus.RequireTerminal()
// 处理最后的响应
shouldSendLastResp := true
if err := handleLastResponse(lastStreamData, &responseId, &createAt, &systemFingerprint, &model, &usage,
@@ -194,12 +196,20 @@ func OaiStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Re
return usage, nil
}
func collectStreamFunctionCallNames(data string, seen map[string]struct{}, names *[]string) {
// observeStreamChoices collects billable function call names and records the
// finish reason facts used by health sampling from one parsed chunk.
func observeStreamChoices(info *relaycommon.RelayInfo, data string, seen map[string]struct{}, names *[]string) {
var streamResponse dto.ChatCompletionsStreamResponse
if err := common.UnmarshalJsonStr(data, &streamResponse); err != nil {
return
}
for _, choice := range streamResponse.Choices {
if choice.FinishReason != nil && *choice.FinishReason != "" {
if *choice.FinishReason == constant.FinishReasonContentFilter {
info.PerformanceBusinessRejection = true
}
info.StreamStatus.MarkCompleted()
}
for i, tc := range choice.Delta.ToolCalls {
name := strings.TrimSpace(tc.Function.Name)
if name == "" {
@@ -274,6 +284,7 @@ func OpenaiHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Respo
for _, choice := range simpleResponse.Choices {
if choice.FinishReason == constant.FinishReasonContentFilter {
info.PerformanceBusinessRejection = true
common.SetContextKey(c, constant.ContextKeyAdminRejectReason, "openai_finish_reason=content_filter")
break
}
+2
View File
@@ -94,6 +94,8 @@ func OaiResponsesStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp
accumulator.Observe(&streamResponse)
})
common.SetContextKey(c, constant.ContextKeyResponseStreamStatus, info.StreamStatus)
info.StreamStatus.RequireTerminal()
return accumulator.Finish(), nil
}
@@ -3,11 +3,13 @@ package openai
import (
"testing"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCollectStreamFunctionCallNamesDedupesSameIndex(t *testing.T) {
func TestObserveStreamChoicesDedupesFunctionCallNames(t *testing.T) {
info := &relaycommon.RelayInfo{StreamStatus: relaycommon.NewStreamStatus()}
seen := make(map[string]struct{})
var names []string
@@ -19,9 +21,18 @@ func TestCollectStreamFunctionCallNamesDedupesSameIndex(t *testing.T) {
`{"choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"{}"}}]}}]}`,
}
for _, chunk := range chunks {
collectStreamFunctionCallNames(chunk, seen, &names)
observeStreamChoices(info, chunk, seen, &names)
}
require.Len(t, names, 2)
assert.Equal(t, []string{"get_weather", "get_time"}, names)
assert.Empty(t, info.StreamStatus.ResponseOutcome(), "tool call deltas carry no finish reason")
observeStreamChoices(info, `{"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}`, seen, &names)
assert.Equal(t, "completed", info.StreamStatus.ResponseOutcome())
assert.False(t, info.PerformanceBusinessRejection)
filtered := &relaycommon.RelayInfo{StreamStatus: relaycommon.NewStreamStatus()}
observeStreamChoices(filtered, `{"choices":[{"index":0,"delta":{},"finish_reason":"content_filter"}]}`, map[string]struct{}{}, &names)
assert.True(t, filtered.PerformanceBusinessRejection)
}
+4
View File
@@ -192,6 +192,10 @@ type RelayInfo struct {
FinalRequestRelayFormat types.RelayFormat
StreamStatus *StreamStatus
// PerformanceOutputTokens is captured by settlement and sampled once at
// the request boundary, independently of billing success or failure.
PerformanceOutputTokens int64
PerformanceBusinessRejection bool
// convOptions caches the converter settings snapshot (see ConvOptions).
convOptions *convmeta.Options
+8 -3
View File
@@ -1,7 +1,10 @@
package helper
import (
"errors"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/types"
)
// StreamResult is passed to each dataHandler invocation, providing methods
@@ -23,13 +26,15 @@ func (r *StreamResult) Error(err error) {
return
}
r.status.RecordError(err.Error())
var apiErr *types.NewAPIError
if errors.As(err, &apiErr) {
r.status.MarkFailed(string(apiErr.GetErrorCode()), apiErr.ToOpenAIError().Type, apiErr.StatusCode)
}
}
// Stop records a fatal error and marks the stream to stop after this chunk.
func (r *StreamResult) Stop(err error) {
if err != nil {
r.status.RecordError(err.Error())
}
r.Error(err)
r.status.SetEndReason(relaycommon.StreamEndReasonHandlerStop, err)
r.stopped = true
}
+4 -1
View File
@@ -145,13 +145,16 @@ func appendStreamStatus(relayInfo *relaycommon.RelayInfo, other *model.LogOther)
}
ss := relayInfo.StreamStatus
status := "ok"
if !ss.IsNormalEnd() || ss.HasErrors() {
if !ss.IsNormalEnd() || ss.HasErrors() || ss.ResponseFailed() {
status = "error"
}
streamInfo := map[string]any{
"status": status,
"end_reason": string(ss.EndReason),
}
if outcome := ss.ResponseOutcome(); outcome != "" {
streamInfo["response_status"] = outcome
}
if ss.EndError != nil {
streamInfo["end_error"] = ss.EndError.Error()
}
+1 -4
View File
@@ -11,7 +11,6 @@ import (
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/pkg/billingexpr"
perfmetrics "github.com/QuantumNous/new-api/pkg/perf_metrics"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/setting/ratio_setting"
@@ -388,9 +387,7 @@ func PostAudioConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, u
Group: relayInfo.UsingGroup,
Other: other,
})
gopool.Go(func() {
perfmetrics.RecordRelaySample(relayInfo, true, int64(usage.CompletionTokens))
})
relayInfo.PerformanceOutputTokens = int64(usage.CompletionTokens)
}
func PreConsumeTokenQuota(relayInfo *relaycommon.RelayInfo, quota int) error {
+39
View File
@@ -1,8 +1,10 @@
package service
import (
"fmt"
"strings"
"github.com/QuantumNous/new-api/common"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/relaykit/relayconvert"
@@ -29,6 +31,7 @@ func (a *ResponsesUsageAccumulator) Observe(event *dto.ResponsesStreamResponse)
if a == nil || event == nil || a.finished {
return
}
ObserveResponsesOutcome(a.info, event)
switch event.Type {
case "response.completed", "response.done", "response.failed", "response.incomplete", "response.cancelled", "response.canceled":
if event.Response != nil {
@@ -91,6 +94,42 @@ func (a *ResponsesUsageAccumulator) Finish() *dto.Usage {
return a.usage
}
// ObserveResponsesOutcome records the protocol outcome of one Responses event
// on the stream status for health classification. Only codes and types are
// kept; messages never leave the event.
func ObserveResponsesOutcome(info *relaycommon.RelayInfo, event *dto.ResponsesStreamResponse) {
if info == nil || info.StreamStatus == nil || event == nil {
return
}
var responseStatus string
if event.Response != nil {
_ = common.Unmarshal(event.Response.Status, &responseStatus)
}
switch {
case event.Type == "error" || event.Type == "response.failed" || event.Type == "response.error" || responseStatus == "failed":
code, errorType := event.Code, ""
if event.Response != nil {
if oaiErr := event.Response.GetOpenAIError(); oaiErr != nil {
if oaiErr.Code != nil {
code = fmt.Sprint(oaiErr.Code)
}
errorType = oaiErr.Type
}
}
info.StreamStatus.MarkFailed(code, errorType, 0)
case event.Type == "response.incomplete" || responseStatus == "incomplete":
reason := ""
if event.Response != nil && event.Response.IncompleteDetails != nil {
reason = event.Response.IncompleteDetails.Reason
}
info.StreamStatus.MarkIncomplete(reason)
case event.Type == "response.cancelled" || event.Type == "response.canceled" || responseStatus == "cancelled":
info.StreamStatus.MarkCancelled()
case event.Type == "response.completed" || event.Type == "response.done" || responseStatus == "completed":
info.StreamStatus.MarkCompleted()
}
}
func ApplyResponsesUsage(dst *dto.Usage, src *dto.Usage) {
if dst == nil || src == nil {
return
+33 -2
View File
@@ -3,6 +3,7 @@ package service
import (
"testing"
"github.com/QuantumNous/new-api/common"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/setting/operation_setting"
@@ -25,7 +26,7 @@ func TestResponsesUsageAccumulatorTerminalAccounting(t *testing.T) {
{eventType: "response.canceled"},
} {
t.Run(tc.eventType, func(t *testing.T) {
info := &relaycommon.RelayInfo{OriginModelName: "gpt-5.1"}
info := &relaycommon.RelayInfo{OriginModelName: "gpt-5.1", StreamStatus: relaycommon.NewStreamStatus()}
accumulator := NewResponsesUsageAccumulator(info)
for _, item := range []dto.ResponsesOutput{
{Type: dto.BuildInCallWebSearchCall},
@@ -48,6 +49,8 @@ func TestResponsesUsageAccumulatorTerminalAccounting(t *testing.T) {
accumulator.Observe(terminal)
accumulator.Observe(terminal)
usage := accumulator.Finish()
assert.Equal(t, tc.eventType == "response.failed", info.StreamStatus.ResponseFailed())
assert.NotEmpty(t, info.StreamStatus.ResponseOutcome())
assert.Equal(t, 20, usage.PromptTokens)
assert.Equal(t, 5, usage.CompletionTokens)
@@ -107,8 +110,36 @@ func TestResponsesUsageAccumulatorInterruptedTextFallback(t *testing.T) {
}
}
func TestObserveResponsesOutcomeRecordsProtocolFacts(t *testing.T) {
for _, tc := range []struct {
name string
event string
wantOutcome relaycommon.ResponseOutcome
wantCode string
wantType string
wantIncompl string
}{
{"flat sse error", `{"type":"error","code":"context_length_exceeded","message":"too long"}`, relaycommon.ResponseOutcomeFailed, "context_length_exceeded", "", ""},
{"done with failed status", `{"type":"response.done","response":{"status":"failed","error":{"code":"invalid_api_key","type":"invalid_request_error","message":"bad key"}}}`, relaycommon.ResponseOutcomeFailed, "invalid_api_key", "invalid_request_error", ""},
{"incomplete keeps reason", `{"type":"response.incomplete","response":{"status":"incomplete","incomplete_details":{"reason":"max_output_tokens"}}}`, relaycommon.ResponseOutcomeIncomplete, "", "", "max_output_tokens"},
{"in progress is not terminal", `{"type":"response.created","response":{"status":"in_progress"}}`, relaycommon.ResponseOutcomeUnknown, "", "", ""},
} {
t.Run(tc.name, func(t *testing.T) {
var event dto.ResponsesStreamResponse
require.NoError(t, common.UnmarshalJsonStr(tc.event, &event))
info := &relaycommon.RelayInfo{StreamStatus: relaycommon.NewStreamStatus()}
ObserveResponsesOutcome(info, &event)
outcome := info.StreamStatus.OutcomeSnapshot()
assert.Equal(t, tc.wantOutcome, outcome.Response)
assert.Equal(t, tc.wantCode, outcome.ErrorCode)
assert.Equal(t, tc.wantType, outcome.ErrorType)
assert.Equal(t, tc.wantIncompl, outcome.IncompleteReason)
})
}
}
func TestResponsesUsageAccumulatorDisconnectBillsCompletedImage(t *testing.T) {
info := &relaycommon.RelayInfo{OriginModelName: "gpt-5.1"}
info := &relaycommon.RelayInfo{OriginModelName: "gpt-5.1", StreamStatus: relaycommon.NewStreamStatus()}
accumulator := NewResponsesUsageAccumulator(info)
accumulator.Observe(&dto.ResponsesStreamResponse{
Type: dto.ResponsesOutputTypeItemDone,
+1 -5
View File
@@ -12,14 +12,12 @@ import (
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/pkg/billingexpr"
perfmetrics "github.com/QuantumNous/new-api/pkg/perf_metrics"
relaycommon "github.com/QuantumNous/new-api/relay/common"
relayconstant "github.com/QuantumNous/new-api/relay/constant"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/relaykit/types"
"github.com/QuantumNous/new-api/setting/operation_setting"
"github.com/bytedance/gopkg/util/gopool"
"github.com/gin-gonic/gin"
"github.com/shopspring/decimal"
)
@@ -549,7 +547,5 @@ func PostTextConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, us
Group: relayInfo.UsingGroup,
Other: other,
})
gopool.Go(func() {
perfmetrics.RecordRelaySample(relayInfo, true, int64(summary.CompletionTokens))
})
relayInfo.PerformanceOutputTokens = int64(summary.CompletionTokens)
}
@@ -38,52 +38,6 @@ import { cn } from '@/lib/utils'
const PERFORMANCE_WINDOW_HOURS = 24
const TOP_MODEL_LIMIT = 6
type WeightedMetric = 'avg_latency_ms' | 'avg_tps' | 'success_rate'
type PerformanceSummary = {
totalRequests: number
avgLatencyMs: number
avgTps: number
successRate: number
}
function simpleAverage(
rows: PerfModelSummary[],
metric: WeightedMetric,
isValid: (value: number) => boolean
): number {
let total = 0
let count = 0
for (const row of rows) {
const value = Number(row[metric])
if (!isValid(value)) continue
total += value
count++
}
return count > 0 ? total / count : Number.NaN
}
function buildPerformanceSummary(rows: PerfModelSummary[]): PerformanceSummary {
return {
totalRequests: rows.length,
avgLatencyMs: Math.round(
simpleAverage(
rows,
'avg_latency_ms',
(value) => Number.isFinite(value) && value > 0
)
),
avgTps: simpleAverage(
rows,
'avg_tps',
(value) => Number.isFinite(value) && value > 0
),
successRate: simpleAverage(rows, 'success_rate', Number.isFinite),
}
}
export function PerformanceOverview() {
const { t } = useTranslation()
const metricsQuery = useQuery({
@@ -100,7 +54,7 @@ export function PerformanceOverview() {
() => metricsQuery.data?.data.models ?? [],
[metricsQuery.data]
)
const summary = useMemo(() => buildPerformanceSummary(models), [models])
const summary = metricsQuery.data?.data.summary
const topModels = useMemo(() => models.slice(0, TOP_MODEL_LIMIT), [models])
const loading = metricsQuery.isLoading
const hasData = models.length > 0
@@ -144,20 +98,22 @@ export function PerformanceOverview() {
<InlineMetric
icon={HeartPulse}
label={t('Success rate')}
value={formatUptimePct(summary.successRate)}
valueClassName={getSuccessRateTextClass(summary.successRate)}
value={formatUptimePct(summary?.success_rate ?? Number.NaN)}
valueClassName={getSuccessRateTextClass(
summary?.success_rate ?? Number.NaN
)}
tone='success'
/>
<InlineMetric
icon={Timer}
label={t('Average latency')}
value={formatLatency(summary.avgLatencyMs)}
value={formatLatency(summary?.avg_latency_ms ?? 0)}
tone='warning'
/>
<InlineMetric
icon={Gauge}
label={t('Throughput')}
value={formatThroughput(summary.avgTps)}
value={formatThroughput(summary?.avg_tps ?? 0)}
tone='info'
/>
</div>
@@ -31,31 +31,12 @@ import {
getSuccessRateDotClass,
getSuccessRateTextClass,
} from '@/features/performance-metrics/lib/format'
import type { PerfModelSummary } from '@/features/performance-metrics/types'
import { requireServerSuccess } from '@/lib/server-error-message'
import { cn } from '@/lib/utils'
const PERFORMANCE_WINDOW_HOURS = 24
const TOP_MODEL_LIMIT = 6
type WeightedMetric = 'avg_latency_ms' | 'avg_tps' | 'success_rate'
function simpleAverage(
rows: PerfModelSummary[],
metric: WeightedMetric,
isValid: (value: number) => boolean
): number {
let total = 0
let count = 0
for (const row of rows) {
const value = Number(row[metric])
if (!isValid(value)) continue
total += value
count++
}
return count > 0 ? total / count : Number.NaN
}
export function PerformanceHealthPanel() {
const { t } = useTranslation()
const metricsQuery = useQuery({
@@ -73,23 +54,7 @@ export function PerformanceHealthPanel() {
[metricsQuery.data]
)
const summary = useMemo(() => {
return {
avgLatencyMs: Math.round(
simpleAverage(
models,
'avg_latency_ms',
(v) => Number.isFinite(v) && v > 0
)
),
avgTps: simpleAverage(
models,
'avg_tps',
(v) => Number.isFinite(v) && v > 0
),
successRate: simpleAverage(models, 'success_rate', Number.isFinite),
}
}, [models])
const summary = metricsQuery.data?.data.summary
const topModels = useMemo(() => models.slice(0, TOP_MODEL_LIMIT), [models])
const loading = metricsQuery.isLoading
@@ -112,22 +77,24 @@ export function PerformanceHealthPanel() {
<MetricCell
icon={HeartPulse}
label={t('Success rate')}
value={formatUptimePct(summary.successRate)}
value={formatUptimePct(summary?.success_rate ?? Number.NaN)}
loading={loading}
valueClassName={getSuccessRateTextClass(summary.successRate)}
valueClassName={getSuccessRateTextClass(
summary?.success_rate ?? Number.NaN
)}
tone='success'
/>
<MetricCell
icon={Timer}
label={t('Average latency')}
value={formatLatency(summary.avgLatencyMs)}
value={formatLatency(summary?.avg_latency_ms ?? 0)}
loading={loading}
tone='warning'
/>
<MetricCell
icon={Gauge}
label={t('Throughput')}
value={formatThroughput(summary.avgTps)}
value={formatThroughput(summary?.avg_tps ?? 0)}
loading={loading}
tone='info'
/>
@@ -0,0 +1,208 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { PerformanceOverview } from '@/features/dashboard/components/models/performance-overview'
import { PerformanceHealthPanel } from '@/features/dashboard/components/overview/performance-health-panel'
import { ModelDetailsPerformance } from '@/features/pricing/components/model-details-performance'
import { UptimeSparkline } from '@/features/pricing/components/model-details-uptime-sparkline'
const chart = vi.hoisted(() =>
vi.fn(
(_props: {
spec: { data: { id: string; values: Record<string, unknown>[] }[] }
}) => null
)
)
vi.mock('@visactor/react-vchart', () => ({ VChart: chart }))
vi.mock('@visactor/vchart', () => ({
ThemeManager: { setCurrentTheme: vi.fn() },
}))
let client: QueryClient
beforeEach(() => {
chart.mockClear()
client = new QueryClient({
defaultOptions: { queries: { retry: false, staleTime: Infinity } },
})
})
afterEach(() => client.clear())
const summary = { success_rate: 99.01, avg_latency_ms: 1009, avg_tps: 5 }
const windowStart = 1789387200
const windowEnd = windowStart + 23 * 3600 + 1800
const groups = [
{
group: 'a',
success_rate: 100,
avg_latency_ms: 1000,
avg_ttft_ms: 100,
avg_tps: 5,
series: [
{
ts: windowStart,
avg_ttft_ms: 100,
avg_latency_ms: 1000,
success_rate: 100,
avg_tps: 5,
},
],
},
{
group: 'b',
success_rate: 0,
avg_latency_ms: 2000,
avg_ttft_ms: 0,
avg_tps: 0,
series: [
{
ts: windowStart,
avg_ttft_ms: 0,
avg_latency_ms: 2000,
success_rate: 0,
avg_tps: 0,
},
],
},
]
function renderModelDetails() {
client.setQueryData(['perf-metrics', 'test-model'], {
success: true,
data: {
model_name: 'test-model',
summary,
series: [
{
ts: windowStart,
avg_ttft_ms: 100,
avg_latency_ms: 1009,
success_rate: 99.01,
avg_tps: 5,
},
],
window_start: windowStart,
window_end: windowEnd,
groups,
},
})
return render(
<QueryClientProvider client={client}>
<ModelDetailsPerformance
model={{
id: 1,
model_name: 'test-model',
quota_type: 0,
model_ratio: 1,
completion_ratio: 1,
enable_groups: ['a', 'b'],
}}
/>
</QueryClientProvider>
)
}
describe('server performance summaries', () => {
it.each([PerformanceHealthPanel, PerformanceOverview])(
'uses the weighted server result across models',
(Component) => {
client.setQueryData(['perf-metrics-summary', 24], {
success: true,
data: {
summary,
models: groups.map((group) => ({
...group,
model_name: group.group,
})),
},
})
render(
<QueryClientProvider client={client}>
<Component />
</QueryClientProvider>
)
expect(screen.getByText('99.01%')).toBeVisible()
expect(screen.queryByText('50.00%')).not.toBeInTheDocument()
expect(screen.getByText('1.01s')).toBeVisible()
}
)
it('shows the server summary and series incident count for model details instead of averaging groups', () => {
renderModelDetails()
expect(screen.getByText('99.01%')).toBeVisible()
expect(screen.queryByText('50.00%')).not.toBeInTheDocument()
expect(screen.getByText('1 incidents in the last 24 hours')).toBeVisible()
})
it('feeds the uptime chart from the backend series rather than group averages', async () => {
renderModelDetails()
await waitFor(() => expect(chart).toHaveBeenCalled())
const specs = chart.mock.calls.map(([props]) => props.spec)
const uptime = specs.find((value) => value.data[0].id === 'uptime')
const uptimeValues = uptime?.data[0].values.map((value) => value.uptime)
expect(uptimeValues).toContain(99.01)
expect(uptimeValues).not.toContain(50)
})
it('shows each group success rate in its own sparkline label', () => {
renderModelDetails()
expect(screen.getByText('100.00%')).toBeVisible()
expect(screen.getByText('0.00%')).toBeVisible()
})
it('displays the supplied group summary instead of averaging hourly percentages', () => {
render(
<UptimeSparkline
overallSuccessRate={99.01}
series={[
{
date: '2026-09-14T11:00:00Z',
uptime_pct: 100,
incidents: 0,
outage_minutes: 0,
},
{
date: '2026-09-14T12:00:00Z',
uptime_pct: 0,
incidents: 1,
outage_minutes: 0,
},
]}
/>
)
expect(screen.getByText('99.01%')).toBeVisible()
expect(screen.queryByText('50.00%')).not.toBeInTheDocument()
})
it('keeps an empty summary unknown instead of inventing a zero success rate', () => {
client.setQueryData(['perf-metrics-summary', 24], {
success: true,
data: { models: [], summary: null },
})
render(
<QueryClientProvider client={client}>
<PerformanceHealthPanel />
</QueryClientProvider>
)
expect(screen.getAllByText('—')).toHaveLength(3)
expect(screen.queryByText('0.00%')).not.toBeInTheDocument()
})
})
@@ -16,6 +16,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
export type PerformanceSummary = {
avg_latency_ms: number
success_rate: number
avg_tps: number
}
export type PerformanceSeriesPoint = {
ts: number
avg_ttft_ms: number
@@ -37,6 +43,10 @@ export type PerformanceMetricsData = {
success: boolean
message?: string
data: {
summary?: PerformanceSummary | null
series?: PerformanceSeriesPoint[]
window_start?: number
window_end?: number
model_name: string
series_schema?: string
groups: PerformanceGroup[]
@@ -58,6 +68,9 @@ export type PerfSummaryAllData = {
success: boolean
message?: string
data: {
summary?: PerformanceSummary | null
window_start?: number
window_end?: number
models: PerfModelSummary[]
}
}
@@ -160,7 +160,7 @@ describe('model cards', () => {
const metrics = screen.getByLabelText(
'Performance metrics for the last 24 hours'
)
expect(within(metrics).getByText('—%')).toBeVisible()
expect(within(metrics).getByText('—')).toBeVisible()
expect(within(metrics).getByText('—s')).toBeVisible()
expect(within(metrics).getByText('—t/s')).toBeVisible()
expect(within(metrics).queryByText(/100/)).not.toBeInTheDocument()
@@ -245,9 +245,9 @@ describe('model cards', () => {
})
it.each([
{ success_rate: 0, expected: '0.0%' },
{ success_rate: 99.8, expected: '99.8%' },
{ success_rate: Number.NaN, expected: '—%' },
{ success_rate: 0, expected: '0.00%' },
{ success_rate: 99.8, expected: '99.80%' },
{ success_rate: Number.NaN, expected: '—' },
])(
'shows $expected for the reported request success rate $success_rate',
({ success_rate, expected }) => {
@@ -501,6 +501,7 @@ describe('model cards', () => {
avg_latency_ms: 1200,
avg_tps: 42,
success_rate: 100,
window_start: currentHourStart - 23 * 3600,
recent_success_series: [
{ ts: currentHourStart, success_rate: 100 },
{ ts: currentHourStart - 5 * 3600, success_rate: 80 },
@@ -538,6 +539,7 @@ describe('model cards', () => {
avg_latency_ms: 1200,
avg_tps: 42,
success_rate: 100,
window_start: currentHourStart - 23 * 3600,
recent_success_series: [
{ ts: currentHourStart - 24 * 3600, success_rate: 100 },
],
@@ -577,7 +579,7 @@ describe('model cards', () => {
})
})
it('places a five-hour-old point in slot 18 when now is mid-hour', () => {
it('uses the server window even when the browser clock is a day ahead', () => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-09-07T12:37:00.000Z'))
const currentHourStart = Math.floor(Date.now() / 1000 / 3600) * 3600
@@ -590,8 +592,9 @@ describe('model cards', () => {
avg_latency_ms: 1200,
avg_tps: 42,
success_rate: 80,
window_start: currentHourStart - 47 * 3600,
recent_success_series: [
{ ts: currentHourStart - 5 * 3600, success_rate: 80 },
{ ts: currentHourStart - 29 * 3600, success_rate: 80 },
],
}}
/>
@@ -63,7 +63,11 @@ export function ModelCardGrid(props: ModelCardGridProps) {
const perfMap = useMemo(() => {
const map = new Map<string, ModelPerfBadgeData>()
for (const model of perfQuery.data?.data?.models ?? []) {
map.set(model.model_name, model)
map.set(model.model_name, {
...model,
window_start: perfQuery.data?.data.window_start,
window_end: perfQuery.data?.data.window_end,
})
}
return map
}, [perfQuery.data])
@@ -33,7 +33,10 @@ import {
formatUptimePct,
getSuccessRateTextClass,
} from '@/features/performance-metrics/lib/format'
import type { PerformanceGroup } from '@/features/performance-metrics/types'
import type {
PerformanceGroup,
PerformanceSeriesPoint,
} from '@/features/performance-metrics/types'
import { requireServerSuccess } from '@/lib/server-error-message'
import { cn } from '@/lib/utils'
@@ -87,56 +90,23 @@ function toUptimePct(value: number): number {
return Math.round(clamped * 100) / 100
}
function toLatencySeries(groups: PerformanceGroup[]) {
const byTs = new Map<number, number[]>()
for (const group of groups) {
for (const point of group.series) {
if (point.avg_ttft_ms <= 0) continue
const current = byTs.get(point.ts) ?? []
current.push(point.avg_ttft_ms)
byTs.set(point.ts, current)
}
}
return [...byTs.entries()]
.sort(([a], [b]) => a - b)
.map(([ts, values]) => ({
timestamp: new Date(ts * 1000).toISOString(),
function toLatencySeries(series: PerformanceSeriesPoint[]) {
return series
.filter((point) => point.avg_ttft_ms > 0)
.map((point) => ({
timestamp: new Date(point.ts * 1000).toISOString(),
group: 'latency',
ttft_ms: Math.round(
values.reduce((sum, value) => sum + value, 0) / values.length
),
ttft_ms: point.avg_ttft_ms,
}))
}
function toUptimeSeries(groups: PerformanceGroup[]): UptimeDayPoint[] {
const byTs = new Map<number, { rates: number[]; incidents: number }>()
for (const group of groups) {
for (const point of group.series) {
const current = byTs.get(point.ts) ?? { rates: [], incidents: 0 }
if (Number.isFinite(point.success_rate)) {
const successRate = toUptimePct(point.success_rate)
current.rates.push(successRate)
if (successRate < 100) current.incidents += 1
}
byTs.set(point.ts, current)
}
}
return [...byTs.entries()]
.sort(([a], [b]) => a - b)
.map(([ts, value]) => {
const uptime =
value.rates.length > 0
? value.rates.reduce((sum, rate) => sum + rate, 0) /
value.rates.length
: 0
return {
date: new Date(ts * 1000).toISOString(),
uptime_pct: toUptimePct(uptime),
incidents: value.incidents,
outage_minutes: 0,
}
})
function toUptimeSeries(series: PerformanceSeriesPoint[]): UptimeDayPoint[] {
return series.map((point) => ({
date: new Date(point.ts * 1000).toISOString(),
uptime_pct: toUptimePct(point.success_rate),
incidents: point.success_rate < 100 ? 1 : 0,
outage_minutes: 0,
}))
}
function toGroupUptimeSeries(group: PerformanceGroup): UptimeDayPoint[] {
@@ -151,17 +121,6 @@ function toGroupUptimeSeries(group: PerformanceGroup): UptimeDayPoint[] {
})
}
function average(
rows: PerformanceRow[],
field: 'avg_ttft_ms' | 'avg_latency_ms'
) {
const values = rows.map((row) => row[field]).filter((value) => value > 0)
if (values.length === 0) return 0
return Math.round(
values.reduce((sum, value) => sum + value, 0) / values.length
)
}
export function ModelDetailsPerformance(props: { model: PricingModel }) {
const { t } = useTranslation()
const metricsQuery = useQuery({
@@ -174,6 +133,11 @@ export function ModelDetailsPerformance(props: { model: PricingModel }) {
() => metricsQuery.data?.data.groups ?? [],
[metricsQuery.data]
)
const summary = metricsQuery.data?.data.summary
const series = useMemo(
() => metricsQuery.data?.data.series ?? [],
[metricsQuery.data]
)
const performances = useMemo<PerformanceRow[]>(
() =>
groups.map((group) => ({
@@ -185,8 +149,8 @@ export function ModelDetailsPerformance(props: { model: PricingModel }) {
})),
[groups]
)
const latencySeries = useMemo(() => toLatencySeries(groups), [groups])
const uptimeSeries = useMemo(() => toUptimeSeries(groups), [groups])
const latencySeries = useMemo(() => toLatencySeries(series), [series])
const uptimeSeries = useMemo(() => toUptimeSeries(series), [series])
const uptimeByGroup = useMemo<Record<string, UptimeDayPoint[]>>(() => {
const map: Record<string, UptimeDayPoint[]> = {}
for (const group of groups) {
@@ -203,22 +167,9 @@ export function ModelDetailsPerformance(props: { model: PricingModel }) {
)
}
const tpsValues = performances
.map((p) => p.avg_tps)
.filter((value) => value > 0)
const avgTps =
tpsValues.length > 0
? tpsValues.reduce((sum, value) => sum + value, 0) / tpsValues.length
: 0
const avgLatency = average(performances, 'avg_latency_ms')
const successRates = performances
.map((perf) => perf.success_rate)
.filter((value) => Number.isFinite(value))
const successRate =
successRates.length > 0
? successRates.reduce((sum, value) => sum + value, 0) /
successRates.length
: 0
const avgTps = summary?.avg_tps ?? 0
const avgLatency = summary?.avg_latency_ms ?? 0
const successRate = summary?.success_rate ?? Number.NaN
const incidentCount = uptimeSeries.reduce((s, p) => s + p.incidents, 0)
return (
@@ -300,6 +251,7 @@ export function ModelDetailsPerformance(props: { model: PricingModel }) {
<UptimeSparkline
size='sm'
series={uptimeByGroup[perf.group] ?? []}
overallSuccessRate={perf.success_rate}
/>
),
},
@@ -320,16 +272,9 @@ export function ModelDetailsPerformance(props: { model: PricingModel }) {
<SectionHeader
icon={HeartPulse}
title={t('Availability (last 24h)')}
description={
incidentCount > 0
? t(
'Request success rate; {{incidents}} incident buckets in the last 24 hours',
{
incidents: incidentCount,
}
)
: t('Request success rate sampled over the last 24 hours')
}
description={t(
'Success rate excludes business rejections and includes the current partial hour.'
)}
accent={
incidentCount > 0 ? (
<span className='inline-flex items-center gap-1 text-amber-600 dark:text-amber-400'>
@@ -50,6 +50,7 @@ type SparklineSize = 'sm' | 'md'
type UptimeSparklineProps = {
series: UptimeDayPoint[]
overallSuccessRate?: number
size?: SparklineSize
showOverall?: boolean
emptyLabel?: string
@@ -77,6 +78,7 @@ export function UptimeSparkline(props: UptimeSparklineProps) {
}
const overall =
props.overallSuccessRate ??
props.series.reduce((s, p) => s + p.uptime_pct, 0) / props.series.length
const containerHeight = size === 'sm' ? 'h-3.5' : 'h-5'
@@ -115,7 +117,7 @@ export function UptimeSparkline(props: UptimeSparklineProps) {
</TooltipTrigger>
<TooltipContent side='top' className='font-mono text-xs'>
<div className='font-medium'>{day.date}</div>
<div>{day.uptime_pct.toFixed(2)}%</div>
<div>{formatUptimePct(day.uptime_pct)}</div>
{day.outage_minutes > 0 && (
<div className='text-muted-foreground'>
{day.outage_minutes} min outage
@@ -132,7 +134,7 @@ export function UptimeSparkline(props: UptimeSparklineProps) {
getSuccessRateTextClass(overall)
)}
>
{overall.toFixed(1)}%
{formatUptimePct(overall)}
</span>
)}
</div>
@@ -156,30 +158,21 @@ export function UptimeStatusRow(props: {
return 'major'
}, [summary.uptime_pct])
const StatusIcon =
status === 'operational'
? CheckCircle2
: status === 'minor'
? Activity
: AlertCircle
const statusColour =
status === 'operational'
? 'text-emerald-600 dark:text-emerald-400'
: status === 'minor'
? 'text-emerald-600 dark:text-emerald-400'
: status === 'degraded'
? 'text-amber-600 dark:text-amber-400'
: 'text-rose-600 dark:text-rose-400'
const statusLabel =
status === 'operational'
? t('All systems operational')
: status === 'minor'
? t('Minor blips in the last 30 days')
: status === 'degraded'
? t('Degraded performance recently')
: t('Significant outages detected')
let StatusIcon = AlertCircle
let statusColour = 'text-rose-600 dark:text-rose-400'
let statusLabel = t('Significant outages detected')
if (status === 'operational') {
StatusIcon = CheckCircle2
statusColour = 'text-emerald-600 dark:text-emerald-400'
statusLabel = t('All systems operational')
} else if (status === 'minor') {
StatusIcon = Activity
statusColour = 'text-emerald-600 dark:text-emerald-400'
statusLabel = t('Minor blips in the last 30 days')
} else if (status === 'degraded') {
statusColour = 'text-amber-600 dark:text-amber-400'
statusLabel = t('Degraded performance recently')
}
return (
<div
@@ -273,31 +273,10 @@ function OverviewSummaryGrid(props: { model: PricingModel }) {
staleTime: 60 * 1000,
})
const groups = metricsQuery.data?.data.groups ?? []
const successRates = groups
.map((group) => group.success_rate)
.filter((rate) => Number.isFinite(rate))
const successRate =
successRates.length > 0
? successRates.reduce((sum, rate) => sum + rate, 0) / successRates.length
: Number.NaN
const tpsValues = groups
.map((group) => group.avg_tps)
.filter((value) => value > 0)
const avgTps =
tpsValues.length > 0
? tpsValues.reduce((sum, value) => sum + value, 0) / tpsValues.length
: 0
const latencyValues = groups
.map((group) => group.avg_latency_ms)
.filter((value) => value > 0)
const avgLatency =
latencyValues.length > 0
? Math.round(
latencyValues.reduce((sum, value) => sum + value, 0) /
latencyValues.length
)
: 0
const summary = metricsQuery.data?.data.summary
const successRate = summary?.success_rate ?? Number.NaN
const avgTps = summary?.avg_tps ?? 0
const avgLatency = summary?.avg_latency_ms ?? 0
return (
<div className='bg-muted/20 grid overflow-hidden rounded-lg border sm:grid-cols-3 sm:divide-x'>
@@ -28,6 +28,8 @@ import type { SuccessRatePoint } from '@/features/performance-metrics/types'
import { cn } from '@/lib/utils'
export type ModelPerfBadgeData = {
window_start?: number
window_end?: number
avg_latency_ms: number
success_rate: number
avg_tps: number
@@ -55,19 +57,20 @@ export const ModelPerfBadge = memo(function ModelPerfBadge(
Number.isFinite(successRate) &&
successRate >= 0 &&
successRate <= 100
// Hourly points with timestamps, anchored to the client's current hour.
// Hourly points use the server window, including the current partial hour.
// Hours without traffic stay gray. Slot 23 is the current, partial hour.
const statusRates = useMemo(() => {
const currentHourStart = Math.floor(Date.now() / 1000 / 3600) * 3600
const windowStart = props.perf?.window_start
if (windowStart == null) return STATUS_SLOTS.map(() => undefined)
const ratesByHour = new Map<number, number>()
for (const point of props.perf?.recent_success_series ?? []) {
ratesByHour.set(point.ts, point.success_rate)
}
return STATUS_SLOTS.map((slot) => {
const hourStart = currentHourStart - (23 - slot) * 3600
const hourStart = windowStart + slot * 3600
return ratesByHour.get(hourStart)
})
}, [props.perf?.recent_success_series])
}, [props.perf?.recent_success_series, props.perf?.window_start])
return (
<div
@@ -80,12 +83,14 @@ export const ModelPerfBadge = memo(function ModelPerfBadge(
<dl className='flex min-w-0 items-start gap-5 text-xs tabular-nums'>
<div className='w-24 shrink-0'>
<dt
title={t('Request success rate sampled over the last 24 hours')}
title={t(
'Success rate excludes business rejections and includes the current partial hour.'
)}
className='text-muted-foreground flex items-center justify-between gap-1 text-[11px] leading-4'
>
<span>{t('Status')}</span>
<span className='font-mono'>
{hasSuccessRate ? `${successRate.toFixed(1)}%` : '—%'}
{hasSuccessRate ? `${successRate.toFixed(2)}%` : '—'}
</span>
</dt>
<dd
+1
View File
@@ -5500,6 +5500,7 @@
"succeeded": "succeeded",
"Success": "Success",
"Success rate": "Success rate",
"Success rate excludes business rejections and includes the current partial hour.": "Success rate excludes business rejections and includes the current partial hour.",
"Successful scheduled or bulk checks can restore automatically disabled channels. Manually disabled channels stay disabled.": "Successful scheduled or bulk checks can restore automatically disabled channels. Manually disabled channels stay disabled.",
"Successfully created {{count}} API Key(s)": "Successfully created {{count}} API Key(s)",
"Successfully created {{count}} redemption codes": "Successfully created {{count}} redemption codes",
+1
View File
@@ -5500,6 +5500,7 @@
"succeeded": "réussi",
"Success": "Succès",
"Success rate": "Taux de réussite",
"Success rate excludes business rejections and includes the current partial hour.": "Le taux de réussite exclut les rejets métier et inclut l’heure en cours.",
"Successful scheduled or bulk checks can restore automatically disabled channels. Manually disabled channels stay disabled.": "Les contrôles périodiques ou groupés réussis peuvent rétablir les canaux désactivés automatiquement. Ceux désactivés manuellement le restent.",
"Successfully created {{count}} API Key(s)": "{{count}} clé(s) API créée(s) avec succès",
"Successfully created {{count}} redemption codes": "{{count}} codes de réduction créés avec succès",
+1
View File
@@ -5500,6 +5500,7 @@
"succeeded": "成功",
"Success": "成功",
"Success rate": "成功率",
"Success rate excludes business rejections and includes the current partial hour.": "成功率は業務上の拒否を除外し、現在進行中の時間帯を含みます。",
"Successful scheduled or bulk checks can restore automatically disabled channels. Manually disabled channels stay disabled.": "定期または一括テストの成功後、自動無効化されたチャネルを復旧できます。手動で無効にしたチャネルは復旧しません。",
"Successfully created {{count}} API Key(s)": "{{count}}個のAPIキーが正常に作成されました",
"Successfully created {{count}} redemption codes": "{{count}}件の引き換えコードが正常に作成されました",
+1
View File
@@ -5500,6 +5500,7 @@
"succeeded": "успешно",
"Success": "Успешно",
"Success rate": "Доля успешных запросов",
"Success rate excludes business rejections and includes the current partial hour.": "Доля успешных запросов не учитывает отказы по бизнес-правилам и включает текущий неполный час.",
"Successful scheduled or bulk checks can restore automatically disabled channels. Manually disabled channels stay disabled.": "Успешные периодические или массовые проверки могут восстановить автоматически отключённые каналы. Отключённые вручную остаются отключёнными.",
"Successfully created {{count}} API Key(s)": "Успешно создано {{count}} API-ключ(а/ей)",
"Successfully created {{count}} redemption codes": "Успешно создано {{count}} кодов активации",
+1
View File
@@ -5500,6 +5500,7 @@
"succeeded": "thành công",
"Success": "Thành công",
"Success rate": "Tỷ lệ thành công",
"Success rate excludes business rejections and includes the current partial hour.": "Tỷ lệ thành công loại trừ các yêu cầu bị từ chối do quy tắc nghiệp vụ và bao gồm giờ hiện tại chưa kết thúc.",
"Successful scheduled or bulk checks can restore automatically disabled channels. Manually disabled channels stay disabled.": "Kiểm tra định kỳ hoặc hàng loạt thành công có thể khôi phục kênh bị tự động vô hiệu hóa. Kênh tắt thủ công vẫn bị tắt.",
"Successfully created {{count}} API Key(s)": "Đã tạo thành công {{count}} khóa API",
"Successfully created {{count}} redemption codes": "Đã tạo thành công {{count}} mã đổi thưởng",
+1
View File
@@ -5500,6 +5500,7 @@
"succeeded": "已成功",
"Success": "成功",
"Success rate": "成功率",
"Success rate excludes business rejections and includes the current partial hour.": "成功率排除業務拒絕,統計包含目前尚未結束的小時。",
"Successful scheduled or bulk checks can restore automatically disabled channels. Manually disabled channels stay disabled.": "定時或批次檢查成功後,可恢復被自動停用的渠道;人工停用的渠道保持停用。",
"Successfully created {{count}} API Key(s)": "成功建立了 {{count}} 個 API 金鑰",
"Successfully created {{count}} redemption codes": "成功建立了 {{count}} 個兌換碼",
+1
View File
@@ -5500,6 +5500,7 @@
"succeeded": "已成功",
"Success": "成功",
"Success rate": "成功率",
"Success rate excludes business rejections and includes the current partial hour.": "成功率排除业务拒绝,统计包含当前尚未结束的小时。",
"Successful scheduled or bulk checks can restore automatically disabled channels. Manually disabled channels stay disabled.": "定时或批量检查成功后,可恢复被自动停用的渠道;人工停用的渠道保持停用。",
"Successfully created {{count}} API Key(s)": "成功创建了 {{count}} 个 API 密钥",
"Successfully created {{count}} redemption codes": "成功创建了 {{count}} 个兑换码",